diff --git a/examples/tasks-axi-rust/.gitignore b/examples/tasks-axi-rust/.gitignore new file mode 100644 index 0000000000..e76446eb8f --- /dev/null +++ b/examples/tasks-axi-rust/.gitignore @@ -0,0 +1,2 @@ +# Cargo build output (the harness and CI put it under $CARGO_TARGET_DIR, a RAM disk). +/target/ diff --git a/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes.json b/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes.json new file mode 100644 index 0000000000..2a66c5c029 --- /dev/null +++ b/examples/tasks-axi-rust/.metaobjects/.gen-state/.hashes.json @@ -0,0 +1,10 @@ +{ + "crates/tasks-axi-gen/Cargo.toml": "8264f393b6d8dc42a9aa7343d4db4b0e40aaf7d295860620c4fa563dee1190e1", + "crates/tasks-axi-gen/src/cli.rs": "9eae5b155001caf4ca344658087a4e73e080a4fa031726ea8c7de73626267cf0", + "crates/tasks-axi-gen/src/dispatch.rs": "53c03673a89e480c6fe6324d4fc94f22b3f9117feb56613ac2fbd13dd9f60f3e", + "crates/tasks-axi-gen/src/enums.rs": "6cefaacbe7536d636455fa71684f53e5ae2ca110fc0cf809f0d57c92e04548af", + "crates/tasks-axi-gen/src/errors.rs": "b8c91ca62bca287aa0505ead5c9604bbbcec72a7aa90b4253febb1bd4a80a367", + "crates/tasks-axi-gen/src/lib.rs": "0cac8529449f191a039b53ef936f5fcffb65d417f514a27d5f2376637fc56015", + "crates/tasks-axi-gen/src/model.rs": "ea859d51e564baf231e02efa50aea537b9e2e86277770d15ef65774bd51c939f", + "crates/tasks-axi-gen/src/rows.rs": "7e07bd1e83a4015f67e21736fd497a5b21e590f3e8fa6af0d7521a932af98b77" +} diff --git a/examples/tasks-axi-rust/.metaobjects/.gitignore b/examples/tasks-axi-rust/.metaobjects/.gitignore new file mode 100644 index 0000000000..fe926fbc91 --- /dev/null +++ b/examples/tasks-axi-rust/.metaobjects/.gitignore @@ -0,0 +1,9 @@ +# Gen-state bodies are a second full copy of all generated output — not worth +# committing. The MANIFEST is: `.hashes.json` is the only thing that lets +# `meta gen` tell "this file is exactly what I wrote" from "somebody edited +# this" on a machine that did not generate it (CLAUDE.md, Storage format). +# +# The glob matters. Git will not descend into an excluded DIRECTORY, so a +# negation under `.gen-state/` can never apply — it has to be `.gen-state/*`. +.gen-state/* +!.gen-state/.hashes.json diff --git a/examples/tasks-axi-rust/.metaobjects/config.json b/examples/tasks-axi-rust/.metaobjects/config.json new file mode 100644 index 0000000000..03174a502a --- /dev/null +++ b/examples/tasks-axi-rust/.metaobjects/config.json @@ -0,0 +1,13 @@ +{ + "schema_version": 1, + "pending_in_git": true, + "confidence_thresholds": { + "pending_promote": 0.8, + "drift_warn": 0.7 + }, + "sources": [], + "extract": {}, + "verify": { + "handEdits": "fail" + } +} diff --git a/examples/tasks-axi-rust/Cargo.lock b/examples/tasks-axi-rust/Cargo.lock new file mode 100644 index 0000000000..23a83102c5 --- /dev/null +++ b/examples/tasks-axi-rust/Cargo.lock @@ -0,0 +1,24 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "jsre" +version = "0.1.0" + +[[package]] +name = "tasks-axi-gen" +version = "0.1.0" + +[[package]] +name = "tasks-axi-rs" +version = "0.1.0" +dependencies = [ + "jsre", + "tasks-axi-gen", + "toon-encode", +] + +[[package]] +name = "toon-encode" +version = "0.1.0" diff --git a/examples/tasks-axi-rust/Cargo.toml b/examples/tasks-axi-rust/Cargo.toml new file mode 100644 index 0000000000..b1207ec081 --- /dev/null +++ b/examples/tasks-axi-rust/Cargo.toml @@ -0,0 +1,10 @@ +[workspace] +resolver = "2" +members = ["crates/tasks-axi-gen", "crates/toon", "crates/jsre", "crates/tasks-axi-rs"] + +[profile.release] +opt-level = "s" +lto = true +codegen-units = 1 +panic = "abort" +strip = true diff --git a/examples/tasks-axi-rust/README.md b/examples/tasks-axi-rust/README.md new file mode 100644 index 0000000000..35b8905441 --- /dev/null +++ b/examples/tasks-axi-rust/README.md @@ -0,0 +1,205 @@ +# tasks-axi-rust: the read path of tasks-axi, in Rust, generated from a MetaObjects model + +`tasks-axi` is an agent-facing task tracker (a markdown backlog behind a TOON-printing CLI). This example +reimplements its **read path** (`show`, `list`, `ready`) as a small Rust binary, `tasks-axi-rs`, and +produces the Rust source for its **rows, enums, error codes, argument parser, help text and dispatcher** +from a MetaObjects model. The real tasks-axi 0.2.6 is the oracle: for every implemented read command and +flag the two tools print the same bytes and exit with the same code. + +It is a prototype and an experiment, not a product. It changes nothing in MetaObjects: no core change, no +new registered vocabulary, no version bump, and `server/rust` is untouched. Everything here lives under +`examples/tasks-axi-rust/`. + +Writes are not implemented. Every command that would write is **refused**, loudly (see +[What it refuses](#what-it-refuses)). + +## What comes from the model, and what is hand-written + +``` +metaobjects/meta.tasks.yaml rows, enums, error codes ─┐ +metaobjects/meta.cli.yaml the command surface (one bag) ─┤ meta gen +codegen/generators/rust-cli.ts the owned generator ─┘ │ + ▼ + crates/tasks-axi-gen/ (generated, committed) + ▲ +crates/tasks-axi-rs/ hand-written: the backlog grammar, the derived state, the output ─┘ implements `Handlers` +crates/toon/ hand-written: a std-only TOON encoder +crates/jsre/ hand-written: a std-only JavaScript regex engine +``` + +**Generator-owned** (`crates/tasks-axi-gen/`; never edit it, `meta verify --codegen` fails if you do): + +| File | What it holds | +|---|---| +| `enums.rs` | `TaskState`, `HoldKind`, `DepType`, `LinkKind`, `ListState`, with their wire strings | +| `model.rs` | `Hold`, `Dep`, `Link`, `Task` | +| `rows.rs` | `TaskRow` (18 columns), `Column`, the cell accessor, `TASK_LIST_ROW_EXTRA_COLUMNS` | +| `errors.rs` | `ErrorCode`, its exit codes, `AxiError` | +| `cli.rs` | the help and usage text, hint tables, the flag parser and its validation, in the real tool's order | +| `dispatch.rs` | `Handlers` (the trait a tool implements), `Outcome`, `run()`, the refusal of unimplemented commands | + +`cli.rs` also embeds a **fixed, model-independent chunk** of flag-handling code (`js_trim`, `take_flag`, +`parse_optional_uint`, ...). It is written into the generator's source as text, not derived from the model; +a Rust-native generator would ship it as a runtime crate instead. + +**Hand-written** (`crates/tasks-axi-rs/`): the markdown grammar and its regexes, link and dependency +derivation, what "blocked", "held" and "ready" mean, the config and backlog-file discovery, the hint-suffix +logic, truncation and the TOON views. The `Handlers` trait is the seam: the generator decides what the +command line means, the hand-written crate decides what the commands do. + +`crates/toon` is a standalone TOON v4.1 encoder (179 of 179 official encoder fixtures pass). It carries a +`Dialect::ToonJs2` option, because the `@toon-format/toon` library that tasks-axi prints with quotes +strings differently from the spec in three places (`#`, a leading `+`, and which padding counts). +`crates/jsre` is a std-only JavaScript regex engine, differentially tested against node's, because the +backlog grammar is defined by JS regexes and no regex crate matches them exactly (and `regex` would be a +dependency this tool does not otherwise need). + +The workspace has no crates.io dependencies at all (the binary depends on the three path crates above and +std). The release binary is about 0.5 MB. + +## The generator + +`codegen/` is an owned generator in the sense of ADR-0034: a plain TypeScript `Generator` you copy and +change. It is split in three layers so the middle one is the contract: + +1. **`read-model.ts`**: reads the loaded model (resolving accessors only, per ADR-0039) and the `cli` + bag, and validates them, so a typo in the model fails `meta gen` instead of shipping. +2. **`ir.ts`**: a plain-data intermediate representation: enums, structs, rows, error codes, commands, + flags, hints. No MetaObjects types, no Rust text. +3. **`emit/*.ts`**: turns the IR into Rust text, then `rustfmt` (read from stdin) formats it. One emitter + per generated file. + +The committed files under `crates/tasks-axi-gen/` are the **golden outputs**: the specification a +Rust-native generator would have to reproduce, byte for byte after `rustfmt`. The captain's goal is for +a Rust codegen to make the Rust project eventually; layers 1 and 2 are what it would port, and the goldens +are its test. + +Regenerate with: + +```sh +cd server/typescript && bun run packages/cli/bin/meta.ts gen --cwd ../../examples/tasks-axi-rust +``` + +`rustfmt` output can vary a little between releases and no toolchain is pinned, so a toolchain bump may +move the goldens. If it does, regenerate and commit; nothing semantic changes. + +## What the `cli` bag had to carry (evidence for a `binding.cli`) + +The command surface has no registered vocabulary, so it lives in one `attr.properties` bag +(`metaobjects/meta.cli.yaml`), which the strict-attr rule exempts. That is deliberate: this example is the +evidence for or against promoting it. What the bag needed, in order of how clearly it generalises: + +- **Per command**: name, aliases, help text, positionals (names, min, max, a type), ordered flags, + declared outputs (a label and a row shape), and hints with a condition and an optional "filters this + hint survives" list. +- **Per flag**: a name and one of six types: `bool`, `line` (a non-empty single-line string), `uint`, + `enum` (naming a model enum), `columns` (a comma list validated against a row's columns), and positional + `taskId`. **Order matters**: the real tool reports the first invalid flag in declared order, so the + order is part of the contract, not a detail. +- **Global**: flags that may appear anywhere and are consumed before the command's own, an optional + "noun" word (`tasks-axi task show x`), a top-level help text, a refused-command list and a refusal + message template. +- **Cross-references into the model**: an `enum` flag names a model enum; a `columns` flag names a row + type and a base row type; an output names a row type; `extra` lists must be real columns. Four checks of + this kind live in the generator, and they are exactly the checks a registered `binding.cli` would get + from the loader for free. + +What it did **not** need and a real `binding.cli` should still decide: sub-commands deeper than one level, +repeated flags, short flags (tasks-axi has none besides `-v`/`-V`), flag defaults (they are all absent), +environment variables and config files as inputs (those stayed hand-written in `config.rs`), and the +exit-code policy beyond "validation errors exit 2, everything else 1" (that is model data on +`ErrorCode`). + +## Differences from tasks-axi, on purpose + +- **Top-level `--help`** prints this tool's own text (it lists what is implemented), not tasks-axi's. + Per-command help (`list --help` and so on) is byte-identical. +- **No dashboard.** `tasks-axi-rs` with no command is refused; tasks-axi would print its dashboard. +- **Refused commands print a refusal even with `--help`**: `add --help` says it is not implemented here, + rather than showing help for a command that cannot run. +- **A backlog containing a `public-followup` task is refused** by `list`, `ready` and `show` (code + `UNSUPPORTED`). Reproducing that feature's payload rendering is out of scope, and printing a list that + silently omits or mangles those tasks would be worse than saying so. +- **Only the markdown backend.** `--backend` / `TASKS_AXI_BACKEND` / the `backend` config key accept + `markdown` and refuse any other value. +- **Node's I/O error text** is reproduced for the two cases a backlog hits in practice (a directory where + a file should be, a permission error); other I/O errors print Rust's message. +- Unset `HOME` is treated as "no home config". + +Everything else, including error text, exit codes (2 for a validation error, 1 for the rest), output on +stdout only, the hint suffix rules, UTF-16 truncation of titles and bodies, and local-date hold expiry, +matches. `harness/` is how that is checked. + +## What it refuses + +A refused command prints a TOON error on stdout and exits **1**: + +``` +error: "`add` is not implemented by tasks-axi-rs, which ships the read path only (show, list, ready)" +code: UNSUPPORTED +help[1]: Run the same command with the Node tasks-axi +``` + +The refused list is `add, create, start, done, close, reopen, update, edit, rm, delete, block, unblock, +hold, unhold, public-followup, mv, prune, render, setup`. An unknown command is not a refusal: it is the +same `VALIDATION_ERROR` (exit 2) that tasks-axi prints. `harness/differential.ts` asserts every refusal. + +## The gates + +```sh +scripts/gates.sh # all five +scripts/gates.sh --no-node # cargo only: compile, lint, tests (the golden outputs stand in for node) +``` + +| Gate | Command | Fails when | +|---|---|---| +| drift | `meta verify --codegen` | the committed generated crate differs from a fresh regen, or someone edited it (`handEdits: fail` is set in `.metaobjects/config.json`) | +| compile | `cargo check -p tasks-axi-gen --all-targets` and `rustfmt --check` on the generated files | the emitted Rust does not type-check or is not formatted | +| lint | `cargo clippy --workspace --all-targets -D warnings`, `cargo fmt --check` | any warning | +| tests | `cargo test --workspace` | a TOON conformance fixture, a regex differential, a unit test or a **golden output** differs | +| behaviour | `bun harness/differential.ts` | the real tasks-axi and `tasks-axi-rs` disagree on stdout, exit code or stderr for any case | + +**Golden outputs** (`crates/tasks-axi-rs/tests/golden/`) are recorded from the real tasks-axi 0.2.6 by +`bun harness/golden.ts` (148 cases) and replayed by `cargo test`, so the Rust side stays checkable without +node. They are inputs and outputs only; the tool that produced them is not needed to run them. + +**The differential harness** runs both binaries side by side over seeded synthetic backlogs +(`harness/synthetic-backlog.ts`: awkward Unicode, lone surrogates, CRLF, quoting edge cases, duplicate ids, +blocked-by chains, expiring holds) and a matrix of commands and flags, plus about 110 fixed cases for +argument errors, config precedence (`--file`, environment, `.tasks.toml`, the home config), unreadable +files and the refusals. Each run is in a throwaway directory under `$DEV_SCRATCH`, with `TZ=UTC` and a +synthetic `HOME`. Typical: `bun harness/differential.ts --seeds 40` (~1,500 comparisons, under 20 s). +Nothing in it reads a real backlog. + +## Benchmark + +`python3 bench/bench.py` interleaves node and rust runs (30 timed runs after one warm-up, median and p95 +wall time, median CPU time, median peak RSS) and refuses to time a scenario whose outputs differ. +Representative run, release build, 200-task backlog, on a heavily loaded workstation (load average ~26, so +read the **ratios and the CPU column**, not the absolute milliseconds): + +| command | tool | median ms | p95 ms | CPU ms | peak RSS MiB | +|---|---|---:|---:|---:|---:| +| list | node | 47.2 | 53.8 | 55.5 | 62.5 | +| list | rust | 3.9 | 4.7 | 3.7 | 8.8 | +| ready | node | 48.2 | 53.6 | 56.2 | 62.0 | +| ready | rust | 3.6 | 4.2 | 3.4 | 8.7 | +| show | node | 45.5 | 52.2 | 53.2 | 61.9 | +| show | rust | 3.2 | 4.1 | 3.0 | 9.0 | + +Most of node's time is start-up (a 5-task backlog still takes ~40 ms there, ~0.8 ms in Rust). + +## Layout + +``` +metaobjects/ the model: meta.tasks.yaml (data), meta.cli.yaml (command surface) +codegen/ the generator: generators/rust-cli.ts, rust/{read-model,ir,names,format}.ts, rust/emit/*.ts +metaobjects.config.ts wires rustCli() and the output directory +crates/tasks-axi-gen/ GENERATED, committed (the golden outputs) +crates/tasks-axi-rs/ the binary: main.rs, app.rs (Handlers), grammar, derive, suggest, config, view, tests/golden.rs +crates/toon/ TOON encoder + the official encoder fixtures (see its PROVENANCE.md) +crates/jsre/ JavaScript regex engine + a differential test (needs node) +harness/ differential harness, synthetic backlogs, golden recorder +bench/bench.py the benchmark +scripts/gates.sh every gate +``` diff --git a/examples/tasks-axi-rust/bench/bench.py b/examples/tasks-axi-rust/bench/bench.py new file mode 100755 index 0000000000..b5bbe5ed19 --- /dev/null +++ b/examples/tasks-axi-rust/bench/bench.py @@ -0,0 +1,121 @@ +#!/usr/bin/env python3 +"""Interleaved start-up and memory benchmark: the real tasks-axi (node) vs tasks-axi-rs. + + python3 bench/bench.py [--runs 30] [--tasks 200] [--rust PATH] [--node tasks-axi] + +For each scenario it builds a synthetic backlog, does one untimed warm-up run of each tool, then +alternates node / rust for --runs timed runs (interleaving, so a load spike hits both). It reports +median and p95 wall time, median CPU time (user+sys, which is steadier than wall time on a busy +machine) and median peak resident memory. It also checks every scenario's output is identical +between the two tools before timing it. + +Needs `tasks-axi` on PATH and a built tasks-axi-rs (cargo build --release -p tasks-axi-rs). +""" + +import argparse +import os +import resource +import shutil +import statistics +import subprocess +import sys +import tempfile +import time + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def backlog(n: int) -> str: + """A deterministic synthetic backlog of about n tasks across the three live states.""" + out = ["# Backlog", ""] + for state, share in (("In flight", 0.2), ("Queued", 0.5), ("Done", 0.3)): + out += [f"## {state}", ""] + for i in range(int(n * share)): + tid = f"{state[:2].lower()}-{i:04d}" + dep = f" blocked-by: qu-{i:04d}" if state == "In flight" and i % 3 == 0 else "" + kind = ("task", "scout", "bug")[i % 3] + out.append(f"- [{'x' if state == 'Done' else ' '}] {tid} - Synthetic {kind} number {i} (repo: repo-{i % 5}, kind: {kind}){dep}") + out.append(" A body line for this task that is long enough to be worth truncating " * 3) + out.append("") + return "\n".join(out) + "\n" + + +def timed(cmd, cwd, env): + """One run: (wall seconds, cpu seconds, peak RSS in KiB, stdout).""" + before = resource.getrusage(resource.RUSAGE_CHILDREN) + t0 = time.perf_counter() + p = subprocess.run(cmd, cwd=cwd, env=env, capture_output=True) + wall = time.perf_counter() - t0 + after = resource.getrusage(resource.RUSAGE_CHILDREN) + cpu = (after.ru_utime - before.ru_utime) + (after.ru_stime - before.ru_stime) + return wall, cpu, after.ru_maxrss, p.stdout + + +def peak_rss_kib(cmd, cwd, env): + """Peak RSS of one run, measured in a fresh child so ru_maxrss is not a running maximum.""" + code = ( + "import resource,subprocess,sys;" + "subprocess.run(sys.argv[1:],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL);" + "print(resource.getrusage(resource.RUSAGE_CHILDREN).ru_maxrss)" + ) + p = subprocess.run([sys.executable, "-c", code, *cmd], cwd=cwd, env=env, capture_output=True, text=True) + return int(p.stdout.strip()) + + +def p95(xs): + xs = sorted(xs) + return xs[min(len(xs) - 1, int(round(0.95 * (len(xs) - 1))))] + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--runs", type=int, default=30) + ap.add_argument("--tasks", type=int, default=200) + ap.add_argument("--node", default="tasks-axi") + default_target = os.environ.get("CARGO_TARGET_DIR") or os.path.join(HERE, "..", "target") + ap.add_argument("--rust", default=os.path.join(default_target, "release", "tasks-axi-rs")) + args = ap.parse_args() + if not os.path.exists(args.rust): + print(f"{args.rust} not found: cargo build --release -p tasks-axi-rs", file=sys.stderr) + return 2 + if shutil.which(args.node) is None: + print(f"{args.node} not on PATH", file=sys.stderr) + return 2 + + base = os.environ.get("DEV_SCRATCH") or tempfile.gettempdir() + work = tempfile.mkdtemp(prefix="tasks-axi-bench-", dir=base) + try: + home = os.path.join(work, "home") + os.makedirs(home) + for n, label in ((args.tasks, f"{args.tasks} tasks"), (5, "5 tasks")): + cwd = os.path.join(work, f"cwd-{n}") + os.makedirs(cwd) + with open(os.path.join(cwd, "backlog.md"), "w", encoding="utf-8") as f: + f.write(backlog(n)) + env = {"PATH": os.environ.get("PATH", ""), "HOME": home, "TZ": "UTC"} + scenarios = [("list", ["list"]), ("ready", ["ready"]), ("show", ["show", "qu-0001"])] + print(f"\n{label} (--runs {args.runs})") + print(f"{'command':8} {'tool':6} {'median ms':>10} {'p95 ms':>8} {'cpu ms':>8} {'peak RSS MiB':>13}") + for name, argv in scenarios: + tools = {"node": [args.node, *argv], "rust": [args.rust, *argv]} + outs = {k: timed(c, cwd, env)[3] for k, c in tools.items()} + if outs["node"] != outs["rust"]: + print(f"{name}: OUTPUT DIFFERS between node and rust; not timing it", file=sys.stderr) + return 1 + samples = {k: [] for k in tools} + for _ in range(args.runs): + for k, c in tools.items(): # interleaved + wall, cpu, _, _ = timed(c, cwd, env) + samples[k].append((wall, cpu)) + for k, c in tools.items(): + walls = [w * 1000 for w, _ in samples[k]] + cpus = [c_ * 1000 for _, c_ in samples[k]] + rss = statistics.median(peak_rss_kib(c, cwd, env) for _ in range(5)) / 1024 + print(f"{name:8} {k:6} {statistics.median(walls):10.1f} {p95(walls):8.1f} {statistics.median(cpus):8.1f} {rss:13.1f}") + finally: + shutil.rmtree(work, ignore_errors=True) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/examples/tasks-axi-rust/codegen/generators/rust-cli.ts b/examples/tasks-axi-rust/codegen/generators/rust-cli.ts new file mode 100644 index 0000000000..19869ba009 --- /dev/null +++ b/examples/tasks-axi-rust/codegen/generators/rust-cli.ts @@ -0,0 +1,40 @@ +// OWNED GENERATOR (ADR-0034 Amendment 4) — emits the Rust source of the tasks-axi read path. +// +// Three layers, each replaceable on its own (a Rust-native generator keeps the middle one's +// shape and the committed goldens as its specification): +// 1. codegen/rust/read-model.ts model -> IR (the only file that touches metadata classes) +// 2. codegen/rust/ir.ts the intermediate description, plain data +// 3. codegen/rust/emit/*.ts IR -> text (one file per emitted Rust module) +// +// RUNTIME: runs under whatever runs `meta gen` (node for the published CLI) — no `Bun.*`. + +import type { Generator } from "@metaobjectsdev/codegen-ts/engine"; +import { emitCargo, emitLib } from "../rust/emit/crate.js"; +import { emitCli } from "../rust/emit/cli.js"; +import { emitDispatch } from "../rust/emit/dispatch.js"; +import { emitEnums } from "../rust/emit/enums.js"; +import { emitErrors } from "../rust/emit/errors.js"; +import { emitModel } from "../rust/emit/model.js"; +import { emitRows } from "../rust/emit/rows.js"; +import { rustfmt } from "../rust/format.js"; +import { readModel } from "../rust/read-model.js"; + +export function rustCli(): Generator { + return { + name: "rust-cli", + generate(ctx) { + const ir = readModel(ctx.loadedRoot); + const rs = (path: string, text: string) => ({ path, content: rustfmt(text) }); + return [ + { path: "Cargo.toml", content: emitCargo() }, + rs("src/lib.rs", emitLib(ir)), + rs("src/enums.rs", emitEnums(ir)), + rs("src/model.rs", emitModel(ir)), + rs("src/rows.rs", emitRows(ir)), + rs("src/errors.rs", emitErrors(ir)), + rs("src/cli.rs", emitCli(ir)), + rs("src/dispatch.rs", emitDispatch(ir)), + ]; + }, + }; +} diff --git a/examples/tasks-axi-rust/codegen/rust/emit/cli.ts b/examples/tasks-axi-rust/codegen/rust/emit/cli.ts new file mode 100644 index 0000000000..1ee4724332 --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/emit/cli.ts @@ -0,0 +1,381 @@ +import type { CommandIr, FlagIr, Ir } from "../ir.js"; +import { extraConstName } from "./rows.js"; +import { GENERATED_BANNER, ident, lit, pascal, snake } from "../names.js"; + +const upper = (s: string): string => snake(s).toUpperCase(); + +/** The flag-reading runtime. Model-independent, so it is emitted verbatim: the generated crate + * carries it, the drift gate covers it, and a native generator copies it as a unit. */ +const RUNTIME = ` +/// JavaScript's \`\\s\` set, which \`String.prototype.trim\` also uses. +pub fn is_js_space(c: char) -> bool { + matches!( + c, + '\\t' | '\\n' + | '\\u{b}' + | '\\u{c}' + | '\\r' + | ' ' + | '\\u{a0}' + | '\\u{1680}' + | '\\u{2000}'..='\\u{200a}' + | '\\u{2028}' + | '\\u{2029}' + | '\\u{202f}' + | '\\u{205f}' + | '\\u{3000}' + | '\\u{feff}' + ) +} + +/// \`String.prototype.trim\`. +pub fn js_trim(s: &str) -> &str { + s.trim_matches(is_js_space) +} + +const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; + +fn require_flag_value(args: &[String], index: usize, flag: &str) -> Result { + match args.get(index + 1) { + Some(v) if !v.starts_with("--") => Ok(v.clone()), + _ => Err(AxiError::validation( + format!("{flag} requires a value"), + vec![format!("Pass {flag}=... if the value begins with --")], + )), + } +} + +/// \`--flag value\` or \`--flag=value\`: the first occurrence, removed from \`args\`. +fn take_flag(args: &mut Vec, flag: &str) -> Result, AxiError> { + let equals = format!("{flag}="); + for i in 0..args.len() { + if args[i] == flag { + let value = require_flag_value(args, i, flag)?; + args.drain(i..i + 2); + return Ok(Some(value)); + } + if let Some(value) = args[i].strip_prefix(equals.as_str()) { + let value = value.to_string(); + args.remove(i); + return Ok(Some(value)); + } + } + Ok(None) +} + +fn take_bool_flag(args: &mut Vec, flag: &str) -> bool { + match args.iter().position(|a| a == flag) { + Some(i) => { + args.remove(i); + true + } + None => false, + } +} + +fn require_non_empty_flag_value(flag: &str, value: Option) -> Result, AxiError> { + match value { + Some(v) if js_trim(&v).is_empty() => Err(AxiError::validation( + format!("{flag} requires a value"), + vec![format!("Pass {flag}=... with a non-empty value")], + )), + other => Ok(other), + } +} + +fn require_non_empty_single_line(flag: &str, value: Option) -> Result, AxiError> { + match require_non_empty_flag_value(flag, value)? { + Some(v) if v.contains(['\\r', '\\n']) => Err(AxiError::validation( + format!("{flag} must be a single line"), + vec![format!("Pass {flag}=... without line breaks")], + )), + other => Ok(other), + } +} + +fn parse_optional_uint(flag: &str, raw: Option) -> Result, AxiError> { + let Some(raw) = raw else { return Ok(None) }; + let bad = || AxiError::validation(format!("{flag} must be a non-negative integer"), vec![]); + if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) { + return Err(bad()); + } + match raw.parse::() { + Ok(n) if n <= MAX_SAFE_INTEGER => Ok(Some(n)), + _ => Err(bad()), + } +} + +fn parse_columns(flag: &str, raw: Option, available: &[Column]) -> Result, AxiError> { + let Some(raw) = raw else { return Ok(Vec::new()) }; + let mut requested: Vec = Vec::new(); + for part in raw.split(',') { + let name = js_trim(part); + if !name.is_empty() && !requested.iter().any(|r| r == name) { + requested.push(name.to_string()); + } + } + let unknown: Vec<&str> = requested + .iter() + .map(String::as_str) + .filter(|n| !available.iter().any(|c| c.name() == *n)) + .collect(); + if !unknown.is_empty() { + let mut names: Vec<&str> = available.iter().map(|c| c.name()).collect(); + names.sort_unstable(); + let _ = flag; + return Err(AxiError::validation( + format!("Unknown field(s): {}. Available: {}", unknown.join(", "), names.join(", ")), + vec![], + )); + } + Ok(requested.iter().filter_map(|n| Column::parse(n)).collect()) +} + +fn require_no_unknown_flags(args: &[String]) -> Result<(), AxiError> { + match args.iter().find(|a| a.starts_with('-')) { + Some(unknown) => Err(AxiError::validation( + format!("Unknown flag: {unknown}"), + vec!["Run the command with --help to see supported flags".to_string()], + )), + None => Ok(()), + } +} + +fn require_positionals(args: &[String], min: usize, max: usize, usage: &str) -> Result, AxiError> { + require_no_unknown_flags(args)?; + let positionals: Vec = args.iter().filter(|a| !a.starts_with('-')).cloned().collect(); + if positionals.len() >= min && positionals.len() <= max { + return Ok(positionals); + } + let expected = if min == max { + if min == 0 { + "no positional arguments".to_string() + } else { + format!("{min} positional argument{}", if min == 1 { "" } else { "s" }) + } + } else { + format!("{min}-{max} positional arguments") + }; + Err(AxiError::validation( + format!("Expected {expected}, got {}", positionals.len()), + vec![usage.to_string()], + )) +} + +/// A task id: slug-shaped, \`^[A-Za-z0-9][A-Za-z0-9._-]*$\`. +pub fn is_task_id(id: &str) -> bool { + let mut chars = id.chars(); + matches!(chars.next(), Some(c) if c.is_ascii_alphanumeric()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) +} + +fn require_id(raw: &str, label: &str) -> Result { + if js_trim(raw).is_empty() { + return Err(AxiError::validation( + format!("Missing {label}"), + vec![format!("Pass the task {label}, e.g. \`{BIN} show \`")], + )); + } + if !is_task_id(raw) { + return Err(AxiError::validation( + format!("Invalid id \\"{raw}\\" - ids must be slug-shaped (letters, digits, \\"._-\\") with no spaces"), + vec!["Use a slug like \`homemux-h7\`, or pass --mint to generate one".to_string()], + )); + } + Ok(raw.to_string()) +} +`; + +function argType(f: FlagIr): string { + switch (f.flag.kind) { + case "bool": + return "bool"; + case "line": + return "Option"; + case "uint": + return "Option"; + case "enum": + return `Option<${f.flag.enum}>`; + case "columns": + return "Vec"; + } +} + +function takeExpr(ir: Ir, f: FlagIr): string { + const flag = lit(`--${f.name}`); + switch (f.flag.kind) { + case "bool": + return `take_bool_flag(&mut args, ${flag})`; + case "line": + return `require_non_empty_single_line(${flag}, take_flag(&mut args, ${flag})?)?`; + case "uint": + return `parse_optional_uint(${flag}, take_flag(&mut args, ${flag})?)?`; + case "enum": { + const e = ir.enums.find((x) => x.name === (f.flag as { enum: string }).enum)!; + const msg = `--${f.name} must be one of ${e.members.map((m) => m.wire).join(", ")}`; + return `match take_flag(&mut args, ${flag})? { + None => None, + Some(raw) => Some(${e.name}::parse(&raw).ok_or_else(|| AxiError::validation(${lit(msg)}, Vec::new()))?), + }`; + } + case "columns": + return `parse_columns(${flag}, take_flag(&mut args, ${flag})?, &${extraConstName(f.flag.base)})?`; + } +} + +function commandBlock(ir: Ir, c: CommandIr): string { + const N = upper(c.name); + const P = pascal(c.name); + const idField = c.positionals.idType ? [`pub ${ident(c.positionals.names[0] as string)}: String,`] : []; + const fields = [...idField, ...c.flags.map((f) => `pub ${ident(f.name)}: ${argType(f)},`)]; + const idInit = c.positionals.idType + ? `\n let ${ident(c.positionals.names[0] as string)} = require_id(&positionals[0], ${lit(c.positionals.names[0] as string)})?;` + : ""; + const inits = [...(c.positionals.idType ? [ident(c.positionals.names[0] as string)] : []), ...c.flags.map((f) => ident(f.name))].join(", "); + const whenName = { always: "Always", empty: "Empty", nonEmpty: "NonEmpty", blocked: "Blocked" } as const; + return ` +pub const ${N}_HELP: &str = ${lit(c.help)}; +pub const ${N}_USAGE: &str = ${lit(c.usage)}; + +pub const ${N}_HINTS: &[Hint] = &[ +${c.hints + .map( + (h) => + `Hint { when: HintWhen::${whenName[h.when]}, line: ${lit(h.line)}, filters: &[${h.filters.map(lit).join(", ")}] },`, + ) + .join("\n")} +]; + +pub const ${N}_OUTPUTS: &[OutputSpec] = &[ +${c.outputs + .map( + (o) => + `OutputSpec { label: ${lit(o.label)}, columns: &[${o.columns.map((n) => `Column::${pascal(n)}`).join(", ")}] },`, + ) + .join("\n")} +]; + +#[derive(Debug, Clone, PartialEq)] +pub struct ${P}Args { +${fields.join("\n")} +} + +/// Read \`${c.name}\`'s arguments (global flags already removed), flag by flag in the order the +/// model lists them, then the positionals. +pub fn parse_${snake(c.name)}(raw: &[String]) -> Result<${P}Args, AxiError> { + let mut args: Vec = raw.to_vec(); +${c.flags.map((f) => ` let ${ident(f.name)} = ${takeExpr(ir, f)};`).join("\n")} + let positionals = require_positionals(&args, ${c.positionals.min}, ${c.positionals.max}, ${N}_USAGE)?;${idInit} + let _ = &positionals; + Ok(${P}Args { ${inits} }) +} +`; +} + +export function emitCli(ir: Ir): string { + const cli = ir.cli; + const enumsUsed = [...new Set(cli.commands.flatMap((c) => c.flags.flatMap((f) => (f.flag.kind === "enum" ? [f.flag.enum] : []))))]; + const extraConsts = [ + ...new Set(cli.commands.flatMap((c) => c.flags.flatMap((f) => (f.flag.kind === "columns" ? [extraConstName(f.flag.base)] : [])))), + ]; + const names = cli.commands.map((c) => pascal(c.name)); + const words = cli.commands.flatMap((c) => [c.name, ...c.aliases].map((w) => [w, pascal(c.name)] as const)); + + return `${GENERATED_BANNER} +//! The command surface: help text, argument parsing, hints and output column lists. + +use crate::enums::{${enumsUsed.join(", ")}}; +use crate::errors::AxiError; +use crate::rows::{${["Column", ...extraConsts].join(", ")}}; + +pub const BIN: &str = ${lit(cli.bin)}; +pub const VERSION: &str = ${lit(cli.version)}; +pub const NOUN: &str = ${lit(cli.noun)}; +pub const TOP_HELP: &str = ${lit(cli.topHelp)}; + +/// Commands the real tool has and this one refuses. +pub const REFUSED: [&str; ${cli.refused.length}] = [${cli.refused.map(lit).join(", ")}]; +pub const REFUSAL_MESSAGE: &str = ${lit(cli.refusal.message)}; +pub const REFUSAL_SUGGESTION: &str = ${lit(cli.refusal.suggestion)}; +pub const REFUSAL_HOME: &str = ${lit(cli.refusal.home)}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HintWhen { + Always, + Empty, + NonEmpty, + Blocked, +} + +/// A next-step suggestion: a template with \`{id}\` and a list of filter flags it may carry. +#[derive(Debug, Clone, Copy)] +pub struct Hint { + pub when: HintWhen, + pub line: &'static str, + pub filters: &'static [&'static str], +} + +/// One printed group: its label and the columns it prints. +#[derive(Debug, Clone, Copy)] +pub struct OutputSpec { + pub label: &'static str, + pub columns: &'static [Column], +} + +/// Flags every implemented command accepts, read before the command's own. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Globals { +${cli.globalFlags.map((f) => `pub ${ident(f.name)}: Option,`).join("\n")} +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CommandName { +${names.map((n) => `${n},`).join("\n")} +} + +impl CommandName { + /// The implemented command a word names (its name or an alias). + pub fn from_word(word: &str) -> Option { + match word { +${words.map(([w, v]) => `${lit(w)} => Some(CommandName::${v}),`).join("\n")} + _ => None, + } + } + + pub const fn help(self) -> &'static str { + match self { +${cli.commands.map((c) => `CommandName::${pascal(c.name)} => ${upper(c.name)}_HELP,`).join("\n")} + } + } +} + +/// Remove the global flags from \`args\`; the rest is the command's own. +pub fn parse_globals(args: &[String]) -> Result<(Globals, Vec), AxiError> { + let mut globals = Globals::default(); + let mut stripped: Vec = Vec::new(); + let mut i = 0; + while i < args.len() { + let arg = args[i].as_str(); +${cli.globalFlags + .map((f) => { + const flag = lit(`--${f.name}`); + return ` if arg == ${flag} { + let value = require_flag_value(args, i, ${flag})?; + globals.${ident(f.name)} = require_non_empty_single_line(${flag}, Some(value))?; + i += 2; + continue; + } + if let Some(value) = arg.strip_prefix(${lit(`--${f.name}=`)}) { + globals.${ident(f.name)} = require_non_empty_single_line(${flag}, Some(value.to_string()))?; + i += 1; + continue; + }`; + }) + .join("\n")} + stripped.push(args[i].clone()); + i += 1; + } + Ok((globals, stripped)) +} +${cli.commands.map((c) => commandBlock(ir, c)).join("")}${RUNTIME}`; +} diff --git a/examples/tasks-axi-rust/codegen/rust/emit/crate.ts b/examples/tasks-axi-rust/codegen/rust/emit/crate.ts new file mode 100644 index 0000000000..bcf4a722be --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/emit/crate.ts @@ -0,0 +1,30 @@ +import type { Ir } from "../ir.js"; +import { GENERATED_BANNER } from "../names.js"; + +export function emitCargo(): string { + return `# @generated by the rust-cli generator. Do not edit. +[package] +name = "tasks-axi-gen" +version = "0.1.0" +edition = "2021" +publish = false +license = "Apache-2.0" +description = "Generated from the tasksaxi MetaObjects model: rows, enums, error codes, argument parser, help and dispatcher for the tasks-axi read path." + +[dependencies] +`; +} + +export function emitLib(_ir: Ir): string { + return `${GENERATED_BANNER} +//! Generated half of the tasks-axi read path. The hand-written half implements +//! \`dispatch::Handlers\`; see the example's README for the split. + +pub mod cli; +pub mod dispatch; +pub mod enums; +pub mod errors; +pub mod model; +pub mod rows; +`; +} diff --git a/examples/tasks-axi-rust/codegen/rust/emit/dispatch.ts b/examples/tasks-axi-rust/codegen/rust/emit/dispatch.ts new file mode 100644 index 0000000000..15ea61ba4c --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/emit/dispatch.ts @@ -0,0 +1,102 @@ +import type { Ir } from "../ir.js"; +import { GENERATED_BANNER, pascal, snake } from "../names.js"; + +export function emitDispatch(ir: Ir): string { + const cmds = ir.cli.commands; + const argTypes = cmds.map((c) => `${pascal(c.name)}Args`); + return `${GENERATED_BANNER} +//! The handlers trait the hand-written side implements, and the dispatcher that drives it. + +use crate::cli::{ + self, parse_globals, CommandName, Globals, ${argTypes.join(", ")}, BIN, NOUN, REFUSAL_HOME, REFUSAL_MESSAGE, + REFUSAL_SUGGESTION, REFUSED, TOP_HELP, VERSION, +}; +use crate::errors::{AxiError, ErrorCode}; + +/// What a run produced. \`Output\` and \`Failure\` are rendered by the caller (an output gets a +/// trailing newline); \`Verbatim\` is printed exactly as given. +#[derive(Debug, Clone, PartialEq)] +pub enum Outcome { + Output(String), + Verbatim(String), + Failure(AxiError), +} + +/// One method per implemented command. The dispatcher cannot call a command this trait lacks, +/// and the hand-written side cannot lose one without failing to compile. +pub trait Handlers { + /// Resolve the backlog context (config, backend, file) once the global flags are read. + fn resolve_context(&mut self, globals: &Globals) -> Result<(), AxiError>; +${cmds.map((c) => ` fn ${snake(c.name)}(&mut self, args: ${pascal(c.name)}Args) -> Result;`).join("\n")} +} + +fn refusal(command: &str) -> AxiError { + AxiError::new( + REFUSAL_MESSAGE.replace("{command}", command), + ErrorCode::Unsupported, + vec![REFUSAL_SUGGESTION.to_string()], + ) +} + +/// Run one invocation: \`argv\` excludes the program name. +pub fn run(argv: &[String], handlers: &mut H) -> Outcome { + match run_inner(argv, handlers) { + Ok(outcome) => outcome, + Err(e) => Outcome::Failure(e), + } +} + +fn run_inner(argv: &[String], handlers: &mut H) -> Result { + // The noun is optional: \`tasks-axi task show x\` is \`tasks-axi show x\`. + let argv: &[String] = if argv.first().map(String::as_str) == Some(NOUN) { &argv[1..] } else { argv }; + + if argv.len() == 1 && argv[0] == "--help" { + return Ok(Outcome::Verbatim(format!("{TOP_HELP}\\n"))); + } + if argv.len() == 1 && matches!(argv[0].as_str(), "-v" | "-V" | "--version") { + return Ok(Outcome::Verbatim(format!("{VERSION}\\n"))); + } + let Some(command) = argv.first() else { + return Err(refusal(REFUSAL_HOME)); + }; + if command.starts_with('-') { + return Err(AxiError::validation( + "Flags must come after the command", + vec![ + format!("Run \`{BIN} [args] [flags]\`"), + format!("Move \`{command}\` after the command instead of before it"), + ], + )); + } + let args = &argv[1..]; + let implemented = CommandName::from_word(command); + let refused = REFUSED.contains(&command.as_str()); + if args.iter().any(|a| a == "--help") { + if let Some(name) = implemented { + return Ok(Outcome::Verbatim(name.help().to_string())); + } + } + if refused { + return Err(refusal(command)); + } + let Some(name) = implemented else { + return Err(AxiError::validation( + format!("Unknown command: {command}"), + vec!["Run \`--help\` to see available commands".to_string()], + )); + }; + + let (globals, rest) = parse_globals(args)?; + handlers.resolve_context(&globals)?; + let output = match name { +${cmds + .map( + (c) => + ` CommandName::${pascal(c.name)} => handlers.${snake(c.name)}(cli::parse_${snake(c.name)}(&rest)?)?,`, + ) + .join("\n")} + }; + Ok(Outcome::Output(output)) +} +`; +} diff --git a/examples/tasks-axi-rust/codegen/rust/emit/enums.ts b/examples/tasks-axi-rust/codegen/rust/emit/enums.ts new file mode 100644 index 0000000000..1e97ddd9b3 --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/emit/enums.ts @@ -0,0 +1,35 @@ +import type { Ir } from "../ir.js"; +import { GENERATED_BANNER, lit } from "../names.js"; + +export function emitEnums(ir: Ir): string { + const out: string[] = [GENERATED_BANNER, "//! Closed sets of the tasks-axi model: the three task states, the five hold kinds, and so on.\n"]; + for (const e of ir.enums) { + const n = e.members.length; + out.push(`#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ${e.name} { +${e.members.map((m) => `${m.variant},`).join("\n")} +} + +impl ${e.name} { + /// Every member, in declaration order. + pub const ALL: [${e.name}; ${n}] = [${e.members.map((m) => `${e.name}::${m.variant}`).join(", ")}]; + + /// The printed and parsed spelling. + pub const fn as_str(self) -> &'static str { + match self { +${e.members.map((m) => `${e.name}::${m.variant} => ${lit(m.wire)},`).join("\n")} + } + } + + /// The member spelled \`s\`, if any. + pub fn parse(s: &str) -> Option<${e.name}> { + match s { +${e.members.map((m) => `${lit(m.wire)} => Some(${e.name}::${m.variant}),`).join("\n")} + _ => None, + } + } +} +`); + } + return out.join("\n"); +} diff --git a/examples/tasks-axi-rust/codegen/rust/emit/errors.ts b/examples/tasks-axi-rust/codegen/rust/emit/errors.ts new file mode 100644 index 0000000000..58a1135d58 --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/emit/errors.ts @@ -0,0 +1,58 @@ +import type { Ir } from "../ir.js"; +import { GENERATED_BANNER, lit } from "../names.js"; + +export function emitErrors(ir: Ir): string { + const e = ir.errors; + return `${GENERATED_BANNER} +//! Error codes with their exit codes, and the structured error every command fails with. + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ErrorCode { +${e.map((c) => `${c.variant},`).join("\n")} +} + +impl ErrorCode { + pub const ALL: [ErrorCode; ${e.length}] = [${e.map((c) => `ErrorCode::${c.variant}`).join(", ")}]; + + /// The code as printed after \`code:\`. + pub const fn as_str(self) -> &'static str { + match self { +${e.map((c) => `ErrorCode::${c.variant} => ${lit(c.name)},`).join("\n")} + } + } + + /// The process exit status the code maps to. + pub const fn exit_code(self) -> i32 { + match self { +${e.map((c) => `ErrorCode::${c.variant} => ${c.exit},`).join("\n")} + } + } +} + +/// A command failure: a message, a code, and next-step suggestions. +#[derive(Debug, Clone, PartialEq)] +pub struct AxiError { + pub message: String, + pub code: ErrorCode, + pub suggestions: Vec, +} + +impl AxiError { + pub fn new(message: impl Into, code: ErrorCode, suggestions: Vec) -> AxiError { + AxiError { + message: message.into(), + code, + suggestions, + } + } + + pub fn validation(message: impl Into, suggestions: Vec) -> AxiError { + AxiError::new(message, ErrorCode::ValidationError, suggestions) + } + + pub fn exit_code(&self) -> i32 { + self.code.exit_code() + } +} +`; +} diff --git a/examples/tasks-axi-rust/codegen/rust/emit/model.ts b/examples/tasks-axi-rust/codegen/rust/emit/model.ts new file mode 100644 index 0000000000..7e5e651d07 --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/emit/model.ts @@ -0,0 +1,41 @@ +import type { FieldIr, Ir, ScalarIr } from "../ir.js"; +import { GENERATED_BANNER, ident } from "../names.js"; + +export function scalarType(s: ScalarIr): string { + switch (s.kind) { + case "string": + return "String"; + case "int": + return "i64"; + case "boolean": + return "bool"; + case "enum": + return s.enum; + case "object": + return s.object; + } +} + +function fieldType(f: FieldIr): string { + const t = scalarType(f.scalar); + if (f.array) return `Vec<${t}>`; + return f.required ? t : `Option<${t}>`; +} + +export function emitModel(ir: Ir): string { + const structs = [...ir.values, ir.task]; + const enumNames = [...new Set(structs.flatMap((s) => s.fields.flatMap((f) => (f.scalar.kind === "enum" ? [f.scalar.enum] : []))))]; + const out: string[] = [ + GENERATED_BANNER, + "//! The task record and its value objects, as the markdown backlog parser builds them.\n", + `use crate::enums::{${enumNames.join(", ")}};\n`, + ]; + for (const s of structs) { + out.push(`#[derive(Debug, Clone, PartialEq)] +pub struct ${s.name} { +${s.fields.map((f) => `pub ${ident(f.name)}: ${fieldType(f)},`).join("\n")} +} +`); + } + return out.join("\n"); +} diff --git a/examples/tasks-axi-rust/codegen/rust/emit/rows.ts b/examples/tasks-axi-rust/codegen/rust/emit/rows.ts new file mode 100644 index 0000000000..779c8cf39d --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/emit/rows.ts @@ -0,0 +1,133 @@ +import type { ColumnIr, Ir } from "../ir.js"; +import { GENERATED_BANNER, ident, lit } from "../names.js"; +import { scalarType } from "./model.js"; + +function rowType(c: ColumnIr): string { + const t = scalarType(c.scalar); + if (c.array) return `Vec<${t}>`; + if (c.scalar.kind === "boolean") return "bool"; + return c.rules.absent !== undefined || !c.required ? `Option<${t}>` : t; +} + +/** The expression that turns column `c` of `self` into a Cell. */ +function cellExpr(c: ColumnIr): string { + const f = `self.${ident(c.name)}`; + const absent = lit(c.rules.absent ?? ""); + if (c.scalar.kind === "boolean") { + return `Cell::Str((if ${f} { ${lit(c.rules.trueText as string)} } else { ${lit(c.rules.falseText as string)} }).to_string())`; + } + if (c.array) { + return c.rules.absent !== undefined + ? `Cell::Str(if ${f}.is_empty() { ${absent}.to_string() } else { ${f}.join(${lit(c.rules.join)}) })` + : `Cell::Str(${f}.join(${lit(c.rules.join)}))`; + } + const optional = rowType(c).startsWith("Option<"); + switch (c.scalar.kind) { + case "int": + return optional + ? `match ${f} { Some(v) => Cell::Int(v), None => Cell::Str(${absent}.to_string()) }` + : `Cell::Int(${f})`; + case "enum": + return optional + ? `Cell::Str(${f}.map(|v| v.as_str().to_string()).unwrap_or_else(|| ${absent}.to_string()))` + : `Cell::Str(${f}.as_str().to_string())`; + default: + return optional + ? c.rules.absent === "" || c.rules.absent === undefined + ? `Cell::Str(${f}.clone().unwrap_or_default())` + : `Cell::Str(${f}.clone().unwrap_or_else(|| ${absent}.to_string()))` + : `Cell::Str(${f}.clone())`; + } +} + +const constName = (n: string): string => n.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toUpperCase(); +export const extraConstName = (base: string): string => `${constName(base)}_EXTRA_COLUMNS`; + +export function emitRows(ir: Ir): string { + const cols = ir.row.columns; + const enumsUsed = [...new Set(cols.flatMap((c) => (c.scalar.kind === "enum" ? [c.scalar.enum] : [])))]; + const set = (name: string): string[] => ir.row.sets.find((s) => s.name === name)!.columns; + const variant = (n: string): string => `Column::${cols.find((c) => c.name === n)!.variant}`; + const flagBases = [ + ...new Set(ir.cli.commands.flatMap((c) => c.flags.flatMap((f) => (f.flag.kind === "columns" ? [f.flag.base] : [])))), + ]; + const extraConsts = flagBases + .map((b) => { + const base = set(b); + const extra = cols.map((c) => c.name).filter((n) => !base.includes(n)); + return `/// Columns a caller may add with \`--fields\` to a view printing \`${b}\`: every column that set lacks.\npub const ${extraConstName(b)}: [Column; ${extra.length}] = [${extra.map(variant).join(", ")}];`; + }) + .join("\n\n"); + + const setConsts = ir.row.sets + .map( + (s) => + `/// Columns of \`${s.name}\`, in print order.\npub const ${constName(s.name)}_COLUMNS: [Column; ${s.columns.length}] = [${s.columns.map(variant).join(", ")}];`, + ) + .join("\n\n"); + + return `${GENERATED_BANNER} +//! The printed row, its columns and the column sets each view prints. + +use crate::enums::{${enumsUsed.join(", ")}}; + +/// One printed value: text, or an integer (printed as a TOON number). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Cell { + Str(String), + Int(i64), +} + +/// ${ir.row.name}: one flat record carrying every derivable column. +#[derive(Debug, Clone, PartialEq)] +pub struct ${ir.row.name} { +${cols.map((c) => `pub ${ident(c.name)}: ${rowType(c)},`).join("\n")} +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Column { +${cols.map((c) => `${c.variant},`).join("\n")} +} + +impl Column { + /// Every column, in row order. + pub const ALL: [Column; ${cols.length}] = [${cols.map((c) => `Column::${c.variant}`).join(", ")}]; + + /// The header name. + pub const fn name(self) -> &'static str { + match self { +${cols.map((c) => `Column::${c.variant} => ${lit(c.name)},`).join("\n")} + } + } + + /// The column called \`s\`, if any. + pub fn parse(s: &str) -> Option { + match s { +${cols.map((c) => `${lit(c.name)} => Some(Column::${c.variant}),`).join("\n")} + _ => None, + } + } + + /// Display limit in UTF-16 units for columns whose text is truncated, else None. + pub const fn truncate_limit(self) -> Option { + match self { +${cols.filter((c) => c.rules.truncate !== undefined).map((c) => `Column::${c.variant} => Some(${c.rules.truncate}),`).join("\n")} + _ => None, + } + } +} + +impl ${ir.row.name} { + /// The printed value of column \`c\`. + pub fn cell(&self, c: Column) -> Cell { + match c { +${cols.map((c) => `Column::${c.variant} => ${cellExpr(c)},`).join("\n")} + } + } +} + +${setConsts} + +${extraConsts} +`; +} diff --git a/examples/tasks-axi-rust/codegen/rust/format.ts b/examples/tasks-axi-rust/codegen/rust/format.ts new file mode 100644 index 0000000000..b390a66e7c --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/format.ts @@ -0,0 +1,11 @@ +import { spawnSync } from "node:child_process"; + +/** Run `rustfmt` over Rust text (stdin to stdout). The committed goldens are rustfmt output, so + * the generator's own emit may be sloppy about layout; only this step decides it. */ +export function rustfmt(source: string): string { + const r = spawnSync("rustfmt", ["--edition", "2021", "--emit", "stdout"], { input: source, encoding: "utf8" }); + if (r.error) throw new Error(`rust-cli: cannot run rustfmt: ${r.error.message}`); + if (r.status !== 0) throw new Error(`rust-cli: rustfmt rejected the emitted Rust:\n${r.stderr}\n--- source ---\n${source}`); + // `--emit stdout` prefixes a ":" line only when given files; stdin gets bare output. + return r.stdout; +} diff --git a/examples/tasks-axi-rust/codegen/rust/ir.ts b/examples/tasks-axi-rust/codegen/rust/ir.ts new file mode 100644 index 0000000000..0d5696c7db --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/ir.ts @@ -0,0 +1,110 @@ +// LAYER 2 — the intermediate description. Everything an emitter needs, as plain data, with no +// reference to the metadata classes. A Rust-native generator that reproduces the committed +// golden crate builds this same shape from the same model; only layers 1 and 3 change. + +export interface EnumMemberIr { + symbol: string; // the declared member symbol, e.g. in_flight + variant: string; // Rust variant, e.g. InFlight + wire: string; // printed / parsed spelling (stringValueMap, else the symbol) +} +export interface EnumIr { + name: string; + members: EnumMemberIr[]; +} + +export type ScalarIr = + | { kind: "string" } + | { kind: "int" } + | { kind: "boolean" } + | { kind: "enum"; enum: string } + | { kind: "object"; object: string }; + +export interface FieldIr { + name: string; + scalar: ScalarIr; + array: boolean; + required: boolean; +} +export interface StructIr { + name: string; + fields: FieldIr[]; +} + +/** How a printed column turns its typed value into a cell (the `row` bag). */ +export interface RowRulesIr { + absent?: string; + join: string; + trueText?: string; + falseText?: string; + truncate?: number; +} +export interface ColumnIr { + name: string; // wire/header name, e.g. blocked_by + variant: string; // Rust variant, e.g. BlockedBy + scalar: ScalarIr; + array: boolean; + required: boolean; + rules: RowRulesIr; +} +export interface ColumnSetIr { + name: string; // e.g. TaskListRow + columns: string[]; // TaskRow column names, in print order +} + +export interface ErrorCodeIr { + name: string; // VALIDATION_ERROR + variant: string; // ValidationError + exit: number; +} + +export type FlagKindIr = + | { kind: "bool" } + | { kind: "line" } + | { kind: "uint" } + | { kind: "enum"; enum: string } + | { kind: "columns"; row: string; base: string }; +export interface FlagIr { + name: string; // as typed after `--` + flag: FlagKindIr; +} + +export type HintWhen = "always" | "empty" | "nonEmpty" | "blocked"; +export interface HintIr { + when: HintWhen; + line: string; + filters: string[]; +} +export interface OutputIr { + label: string; + columns: string[]; // fully expanded: base set then extras +} +export interface CommandIr { + name: string; + aliases: string[]; + help: string; // final text, placeholders resolved + usage: string; // first line of help + flags: FlagIr[]; + positionals: { names: string[]; min: number; max: number; idType: boolean }; + outputs: OutputIr[]; + hints: HintIr[]; +} + +export interface CliIr { + bin: string; + version: string; + noun: string; + globalFlags: FlagIr[]; + topHelp: string; + refused: string[]; + refusal: { message: string; suggestion: string; home: string }; + commands: CommandIr[]; +} + +export interface Ir { + enums: EnumIr[]; + values: StructIr[]; // Hold, Dep, Link — emitted before Task + task: StructIr; + row: { name: string; columns: ColumnIr[]; sets: ColumnSetIr[] }; + errors: ErrorCodeIr[]; + cli: CliIr; +} diff --git a/examples/tasks-axi-rust/codegen/rust/names.ts b/examples/tasks-axi-rust/codegen/rust/names.ts new file mode 100644 index 0000000000..6c8160680c --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/names.ts @@ -0,0 +1,54 @@ +// Naming and literal helpers shared by every emitter. Pure functions, no model access. + +const RUST_KEYWORDS = new Set([ + "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", "if", + "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", + "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", "async", + "await", "dyn", +]); + +/** `in_flight` / `VALIDATION_ERROR` / `Draft` -> `InFlight` / `ValidationError` / `Draft`. */ +export function pascal(symbol: string): string { + const parts = symbol.split(/[_\-\s]+/).filter(Boolean); + const allUpper = symbol === symbol.toUpperCase(); + return parts + .map((p) => { + const w = allUpper ? p.toLowerCase() : p; + return w.charAt(0).toUpperCase() + w.slice(1); + }) + .join(""); +} + +/** `include-held` / `blockedBy` -> `include_held` / `blocked_by`. */ +export function snake(name: string): string { + return name + .replace(/([a-z0-9])([A-Z])/g, "$1_$2") + .replace(/[-\s]+/g, "_") + .toLowerCase(); +} + +/** A Rust field or variable identifier: snake case, raw-escaped when it is a keyword. */ +export function ident(name: string): string { + const s = snake(name); + return RUST_KEYWORDS.has(s) ? `r#${s}` : s; +} + +/** A Rust string literal for arbitrary text (escapes every control and non-ASCII-safe char). */ +export function lit(text: string): string { + let out = '"'; + for (const ch of text) { + const c = ch.codePointAt(0) as number; + if (ch === "\\") out += "\\\\"; + else if (ch === '"') out += '\\"'; + else if (ch === "\n") out += "\\n"; + else if (ch === "\r") out += "\\r"; + else if (ch === "\t") out += "\\t"; + else if (c < 0x20 || c === 0x7f) out += `\\u{${c.toString(16)}}`; + else out += ch; + } + return out + '"'; +} + +export const GENERATED_BANNER = + "// @generated by the rust-cli generator from the tasksaxi model. Do not edit:\n" + + "// change the model or the generator and run `meta gen`.\n"; diff --git a/examples/tasks-axi-rust/codegen/rust/read-model.ts b/examples/tasks-axi-rust/codegen/rust/read-model.ts new file mode 100644 index 0000000000..b11be71392 --- /dev/null +++ b/examples/tasks-axi-rust/codegen/rust/read-model.ts @@ -0,0 +1,226 @@ +// LAYER 1 — read the loaded metadata model into the intermediate description (ir.ts). +// This is the only file that touches the metadata classes. Every read RESOLVES (`attr`, +// `fields`, `children`) rather than reading own-only, so an `extends` is followed +// (ADR-0039). A malformed model throws with the offending name; nothing is guessed. + +import type { MetaData, MetaRoot } from "@metaobjectsdev/metadata"; +import type { + ColumnIr, CliIr, CommandIr, EnumIr, FieldIr, FlagIr, HintIr, Ir, OutputIr, RowRulesIr, ScalarIr, StructIr, +} from "./ir.js"; +import { pascal } from "./names.js"; + +const PKG_MODEL = "tasksaxi::model"; +const PKG_CLI = "tasksaxi::cli"; + +function fail(msg: string): never { + throw new Error(`rust-cli: ${msg}`); +} +function last(fqn: string): string { + return fqn.split("::").pop() as string; +} +function top(root: MetaRoot, type: string, subType: string, name: string): MetaData { + const found = root.children().find((c) => c.type === type && c.subType === subType && c.name === name); + return found ?? fail(`model has no ${type}.${subType} ${name}`); +} +function strArr(v: unknown, what: string): string[] { + if (!Array.isArray(v) || v.some((x) => typeof x !== "string")) fail(`${what} must be a list of strings`); + return v as string[]; +} +function bag(node: MetaData, name: string): Record | undefined { + const v = node.attr(name); + if (v === undefined) return undefined; + if (typeof v !== "object" || v === null || Array.isArray(v)) fail(`${node.name}: @${name} must be a map`); + return v as Record; +} + +function readEnum(node: MetaData): EnumIr { + const values = strArr(node.attr("values"), `enum ${node.name} @values`); + const map = (node.attr("stringValueMap") ?? {}) as Record; + return { + name: node.name, + members: values.map((symbol) => ({ symbol, variant: pascal(symbol), wire: map[symbol] ?? symbol })), + }; +} + +/** The shared enum an enum-typed field points at (`extends`). */ +function enumNameOf(field: MetaData): string { + const sup = field.superResolved; + if (!sup || sup.subType !== "enum") fail(`${field.parent?.name}.${field.name}: an enum field must extend a shared enum`); + return sup.name; +} + +function scalarOf(field: MetaData): ScalarIr { + switch (field.subType) { + case "string": + return { kind: "string" }; + case "int": + return { kind: "int" }; + case "boolean": + return { kind: "boolean" }; + case "enum": + return { kind: "enum", enum: enumNameOf(field) }; + case "object": { + const ref = field.attr("objectRef"); + if (typeof ref !== "string") fail(`${field.name}: field.object needs @objectRef`); + return { kind: "object", object: last(ref) }; + } + default: + return fail(`${field.parent?.name}.${field.name}: unsupported field subtype ${field.subType}`); + } +} + +function fieldsOf(obj: MetaData): MetaData[] { + return obj.children().filter((c) => c.type === "field"); +} + +function readStruct(obj: MetaData): StructIr { + const fields: FieldIr[] = fieldsOf(obj).map((f) => ({ + name: f.name, + scalar: scalarOf(f), + array: f.resolvedIsArray(), + required: f.attr("required") === true, + })); + return { name: obj.name, fields }; +} + +function readColumn(f: MetaData): ColumnIr { + const b = bag(f, "row") ?? {}; + const rules: RowRulesIr = { join: typeof b.join === "string" ? b.join : "," }; + if (typeof b.absent === "string") rules.absent = b.absent; + if (typeof b.trueText === "string") rules.trueText = b.trueText; + if (typeof b.falseText === "string") rules.falseText = b.falseText; + if (typeof b.truncate === "number") rules.truncate = b.truncate; + const scalar = scalarOf(f); + if (scalar.kind === "boolean" && (rules.trueText === undefined || rules.falseText === undefined)) { + fail(`TaskRow.${f.name}: a boolean column needs trueText and falseText in its row bag`); + } + return { + name: f.name, + variant: pascal(f.name), + scalar, + array: f.resolvedIsArray(), + required: f.attr("required") === true, + rules, + }; +} + +/** A column set's members, proven to be TaskRow columns by their `extends`. */ +function readColumnSet(obj: MetaData, rowName: string, rowColumns: Set): string[] { + return fieldsOf(obj).map((f) => { + const sup = f.superResolved; + if (!sup || sup.parent?.name !== rowName) fail(`${obj.name}.${f.name} must extend ${rowName}.${f.name}`); + if (!rowColumns.has(f.name)) fail(`${obj.name}.${f.name} is not a ${rowName} column`); + return f.name; + }); +} + +function flagOf(raw: Record): FlagIr { + const name = String(raw.name); + switch (raw.type) { + case "bool": + case "line": + case "uint": + return { name, flag: { kind: raw.type } }; + case "enum": + return { name, flag: { kind: "enum", enum: String(raw.enum) } }; + case "columns": + return { name, flag: { kind: "columns", row: String(raw.row), base: String(raw.base) } }; + default: + return fail(`flag --${name}: unknown type ${String(raw.type)}`); + } +} + +export function readModel(root: MetaRoot): Ir { + const enums = root + .children() + .filter((c) => c.type === "field" && c.subType === "enum") + .map(readEnum); + const enumNames = new Set(enums.map((e) => e.name)); + + const values = ["Hold", "Dep", "Link"].map((n) => readStruct(top(root, "object", "value", n))); + const task = readStruct(top(root, "object", "entity", "Task")); + + const rowObj = top(root, "object", "value", "TaskRow"); + const columns = fieldsOf(rowObj).map(readColumn); + const colNames = new Set(columns.map((c) => c.name)); + const sets = ["TaskListRow", "TaskDetailRow"].map((n) => ({ + name: n, + columns: readColumnSet(top(root, "object", "value", n), "TaskRow", colNames), + })); + const setByName = new Map(sets.map((s) => [s.name, s.columns])); + + const errors = fieldsOf(top(root, "object", "value", "ErrorCode")).map((f) => { + const exit = f.attr("default"); + if (typeof exit !== "number") fail(`ErrorCode.${f.name}: the @default must be the exit code`); + return { name: f.name, variant: pascal(f.name), exit }; + }); + + const cliObj = root.children().find((c) => c.type === "object" && c.resolutionKey() === `${PKG_CLI}::Cli`); + const raw = (cliObj ?? fail("model has no tasksaxi::cli::Cli")).attr("cli") as Record | undefined; + if (!raw) fail("Cli has no `cli` bag"); + + const extraColumns = columns + .map((c) => c.name) + .filter((n) => !(setByName.get("TaskListRow") as string[]).includes(n)); + + const expand = (cols: string, extra: unknown): string[] => { + const base = setByName.get(cols) ?? fail(`unknown column set ${cols}`); + const more = extra === undefined ? [] : strArr(extra, "extra"); + for (const n of more) if (!colNames.has(n)) fail(`extra column ${n} is not a TaskRow column`); + return [...base, ...more]; + }; + + const checkFlag = (f: FlagIr): void => { + if (f.flag.kind === "enum" && !enumNames.has(f.flag.enum)) fail(`--${f.name}: unknown enum ${f.flag.enum}`); + if (f.flag.kind === "columns") { + if (f.flag.row !== rowObj.name) fail(`--${f.name}: row ${f.flag.row} is not ${rowObj.name}`); + if (!setByName.has(f.flag.base)) fail(`--${f.name}: unknown column set ${f.flag.base}`); + } + }; + + const commands: CommandIr[] = Object.entries(raw.commands as Record).map(([name, c]) => { + const flags: FlagIr[] = (c.flags as Record[]).map(flagOf); + flags.forEach(checkFlag); + const help = String(c.help).replace("{extraColumns}", [...extraColumns].sort().join(", ")); + const outputs: OutputIr[] = (c.outputs as any[]).map((o) => ({ + label: String(o.label), + columns: expand(String(o.columns), o.extra), + })); + const hints: HintIr[] = ((c.hints ?? []) as any[]).map((h) => ({ + when: h.when, + line: String(h.line), + filters: h.filters === undefined ? [] : strArr(h.filters, "hint filters"), + })); + return { + name, + aliases: c.aliases === undefined ? [] : strArr(c.aliases, `${name} aliases`), + help, + usage: help.split("\n")[0] as string, + flags, + positionals: { + names: strArr(c.positionals.names, `${name} positionals`), + min: c.positionals.min, + max: c.positionals.max, + idType: c.positionals.type === "taskId", + }, + outputs, + hints, + }; + }); + + const globalFlags = (raw.globalFlags as Record[]).map(flagOf); + globalFlags.forEach(checkFlag); + + const cli: CliIr = { + bin: String(raw.bin), + version: String(raw.version), + noun: String(raw.noun), + globalFlags, + topHelp: String(raw.topHelp), + refused: strArr(raw.refused, "refused"), + refusal: { message: raw.refusal.message, suggestion: raw.refusal.suggestion, home: raw.refusal.home }, + commands, + }; + void PKG_MODEL; + return { enums, values, task, row: { name: "TaskRow", columns, sets }, errors, cli }; +} diff --git a/examples/tasks-axi-rust/crates/jsre/Cargo.toml b/examples/tasks-axi-rust/crates/jsre/Cargo.toml new file mode 100644 index 0000000000..078a3e35ff --- /dev/null +++ b/examples/tasks-axi-rust/crates/jsre/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "jsre" +version = "0.1.0" +edition = "2021" +publish = false +license = "Apache-2.0" +description = "A tiny std-only backtracking regex engine reproducing JavaScript (non-unicode, no flags) semantics for a fixed pattern subset" + +[dependencies] diff --git a/examples/tasks-axi-rust/crates/jsre/README.md b/examples/tasks-axi-rust/crates/jsre/README.md new file mode 100644 index 0000000000..0acf29c8b4 --- /dev/null +++ b/examples/tasks-axi-rust/crates/jsre/README.md @@ -0,0 +1,46 @@ +# jsre + +A tiny, std-only (zero crates.io dependencies) backtracking regex engine that +reproduces JavaScript (ECMAScript, non-unicode mode, no `i`/`m`/`s` flags) +matching semantics for a fixed list of real patterns. + +## What it is not + +It is not a general regex engine. It supports only the subset below; any other +syntax makes `Regex::new` return `Err` instead of risking a silent mis-match. +There is no step budget: it is plain backtracking, intended for anchored +patterns over short single-line inputs. + +## Supported subset + +- Literals; escapes `\s \S \d \D \w \W \b \B \t \n \r \v \f` and escaped + punctuation (`\. \/ \- \( \) \[ \] \+ \\ \$` ...). +- `.` (anything except `\n`, `\r`, U+2028, U+2029). +- Classes `[...]` / `[^...]` with ranges and `\s \d \w` style escapes. +- Groups: capturing `(...)`, non-capturing `(?:...)`, negative lookahead `(?!...)`. +- Alternation `|`; quantifiers `* + ? {n} {n,} {n,m}`, each greedy or lazy. +- Anchors `^` and `$` (start / end of input only). +- JS details: leftmost match, JS backtracking priority, empty-iteration + rejection, captures inside a repeated group reset per iteration, `\s` is the + exact JS whitespace set (including NBSP, U+FEFF, U+2028/9, U+3000), `\w`/`\b` + are ASCII-only. Not-participating groups are `None`. + +Not supported (errors): backreferences, lookbehind, positive lookahead, named +groups, `\u`/`\x`/`\0`/`\c` escapes, literal `{`, flags, Unicode mode. + +## API + +`Regex::new`, `Regex::find_at(&[char], start) -> Option`, +`Regex::find_all` (`matchAll` / `g`-flag semantics, empty match advances by one), +`Regex::captures_str`. Offsets are `char` indices. + +## How it is verified + +`tests/differential.rs` runs every real pattern (the `tasks-axi` markdown +grammar and PR URL regexes, copied verbatim) over thousands of deterministic +pseudo-random inputs per pattern, evaluates the same cases with node's real +`RegExp` through `tests/oracle.mjs`, and compares match start/end and every +capture group (UTF-16 indices are converted to code-point indices). It prints +the number of cases compared and fails with the first 10 mismatches. If `node` +is not on PATH the test prints `SKIPPED` and passes. Engine unit tests live in +`src/lib.rs`. diff --git a/examples/tasks-axi-rust/crates/jsre/src/lib.rs b/examples/tasks-axi-rust/crates/jsre/src/lib.rs new file mode 100644 index 0000000000..9b8bf3d8aa --- /dev/null +++ b/examples/tasks-axi-rust/crates/jsre/src/lib.rs @@ -0,0 +1,712 @@ +//! `jsre`: a tiny backtracking regex engine that reproduces JavaScript +//! (ECMAScript, non-unicode mode, no `i`/`m`/`s` flags) matching semantics for a +//! small, fixed subset of pattern syntax. Anything outside the subset is +//! rejected by [`Regex::new`] rather than silently mis-matched. +//! +//! Positions are indices into a `&[char]` (code points), not bytes or UTF-16 +//! units. + +/// Predefined character-class escapes. +#[derive(Debug, Clone, Copy, PartialEq)] +enum Esc { + Space, + NotSpace, + Digit, + NotDigit, + Word, + NotWord, +} + +fn is_js_space(c: char) -> bool { + matches!( + c, + '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}' + ..='\u{200a}' + | '\u{2028}' + | '\u{2029}' + | '\u{202f}' + | '\u{205f}' + | '\u{3000}' + | '\u{feff}' + ) +} + +fn is_word(c: char) -> bool { + c.is_ascii_alphanumeric() || c == '_' +} + +impl Esc { + fn matches(self, c: char) -> bool { + match self { + Esc::Space => is_js_space(c), + Esc::NotSpace => !is_js_space(c), + Esc::Digit => c.is_ascii_digit(), + Esc::NotDigit => !c.is_ascii_digit(), + Esc::Word => is_word(c), + Esc::NotWord => !is_word(c), + } + } +} + +#[derive(Debug, Clone)] +enum ClassItem { + Range(char, char), + Esc(Esc), +} + +#[derive(Debug, Clone)] +struct Rep { + node: Node, + min: usize, + max: usize, + greedy: bool, + /// Capture indices `lo..hi` live inside the body and reset per iteration. + lo: usize, + hi: usize, +} + +#[derive(Debug, Clone)] +enum Node { + Empty, + Char(char), + Any, + Class { items: Vec, neg: bool }, + Esc(Esc), + Seq(Vec), + Alt(Vec), + Group(usize, Box), + NegLook(Box), + Repeat(Box), + Bol, + Eol, + WordB(bool), +} + +impl Node { + /// For single-character nodes, whether `c` matches; `None` otherwise. + fn single(&self, c: char) -> Option { + match self { + Node::Char(x) => Some(*x == c), + Node::Any => Some(!matches!(c, '\n' | '\r' | '\u{2028}' | '\u{2029}')), + Node::Esc(e) => Some(e.matches(c)), + Node::Class { items, neg } => { + let hit = items.iter().any(|it| match it { + ClassItem::Range(lo, hi) => *lo <= c && c <= *hi, + ClassItem::Esc(e) => e.matches(c), + }); + Some(hit != *neg) + } + _ => None, + } + } + + fn is_single(&self) -> bool { + matches!( + self, + Node::Char(_) | Node::Any | Node::Esc(_) | Node::Class { .. } + ) + } +} + +// --------------------------------------------------------------------------- +// Parser +// --------------------------------------------------------------------------- + +struct Parser { + s: Vec, + pos: usize, + ngroups: usize, +} + +impl Parser { + fn peek(&self) -> Option { + self.s.get(self.pos).copied() + } + + fn next(&mut self) -> Option { + let c = self.peek(); + if c.is_some() { + self.pos += 1; + } + c + } + + fn err(&self, msg: &str) -> Result { + Err(format!("{} at offset {}", msg, self.pos)) + } + + fn parse_alt(&mut self) -> Result { + let mut alts = vec![self.parse_seq()?]; + while self.peek() == Some('|') { + self.pos += 1; + alts.push(self.parse_seq()?); + } + Ok(if alts.len() == 1 { + alts.pop().unwrap() + } else { + Node::Alt(alts) + }) + } + + fn parse_seq(&mut self) -> Result { + let mut items = Vec::new(); + while let Some(c) = self.peek() { + if c == '|' || c == ')' { + break; + } + items.push(self.parse_term()?); + } + Ok(match items.len() { + 0 => Node::Empty, + 1 => items.pop().unwrap(), + _ => Node::Seq(items), + }) + } + + fn parse_term(&mut self) -> Result { + let before = self.ngroups; + let c = self.next().unwrap(); + let (atom, quantifiable) = match c { + '^' => (Node::Bol, false), + '$' => (Node::Eol, false), + '.' => (Node::Any, true), + '(' => { + if self.peek() == Some('?') { + self.pos += 1; + match self.next() { + Some(':') => { + let n = self.parse_alt()?; + self.expect_close()?; + (n, true) + } + Some('!') => { + let n = self.parse_alt()?; + self.expect_close()?; + (Node::NegLook(Box::new(n)), false) + } + _ => return self.err("unsupported group syntax"), + } + } else { + self.ngroups += 1; + let idx = self.ngroups; + let n = self.parse_alt()?; + self.expect_close()?; + (Node::Group(idx, Box::new(n)), true) + } + } + '[' => (self.parse_class()?, true), + '\\' => self.parse_escape()?, + '*' | '+' | '?' => return self.err("nothing to repeat"), + '{' | '}' | ']' => return self.err("unsupported brace or bracket"), + c => (Node::Char(c), true), + }; + let after = self.ngroups; + match self.peek() { + Some('*') | Some('+') | Some('?') | Some('{') => { + if !quantifiable { + return self.err("quantifier on a non-quantifiable atom"); + } + let (min, max) = self.parse_quant()?; + let greedy = if self.peek() == Some('?') { + self.pos += 1; + false + } else { + true + }; + if matches!(self.peek(), Some('*') | Some('+') | Some('?') | Some('{')) { + return self.err("nothing to repeat"); + } + Ok(Node::Repeat(Box::new(Rep { + node: atom, + min, + max, + greedy, + lo: before + 1, + hi: after + 1, + }))) + } + _ => Ok(atom), + } + } + + fn expect_close(&mut self) -> Result<(), String> { + if self.next() == Some(')') { + Ok(()) + } else { + self.err("unterminated group") + } + } + + fn parse_quant(&mut self) -> Result<(usize, usize), String> { + match self.next().unwrap() { + '*' => Ok((0, usize::MAX)), + '+' => Ok((1, usize::MAX)), + '?' => Ok((0, 1)), + _ => { + let min = self.parse_int()?; + let max = if self.peek() == Some(',') { + self.pos += 1; + if self.peek() == Some('}') { + usize::MAX + } else { + self.parse_int()? + } + } else { + min + }; + if self.next() != Some('}') { + return self.err("malformed {} quantifier"); + } + if max < min { + return self.err("quantifier range out of order"); + } + Ok((min, max)) + } + } + } + + fn parse_int(&mut self) -> Result { + let start = self.pos; + while matches!(self.peek(), Some(c) if c.is_ascii_digit()) { + self.pos += 1; + } + if start == self.pos { + return self.err("expected digits"); + } + let t: String = self.s[start..self.pos].iter().collect(); + t.parse().map_err(|_| "quantifier too large".to_string()) + } + + fn simple_escape(c: char) -> Option { + match c { + 't' => Some('\t'), + 'n' => Some('\n'), + 'r' => Some('\r'), + 'v' => Some('\u{b}'), + 'f' => Some('\u{c}'), + _ => None, + } + } + + fn class_esc(c: char) -> Option { + match c { + 's' => Some(Esc::Space), + 'S' => Some(Esc::NotSpace), + 'd' => Some(Esc::Digit), + 'D' => Some(Esc::NotDigit), + 'w' => Some(Esc::Word), + 'W' => Some(Esc::NotWord), + _ => None, + } + } + + fn parse_escape(&mut self) -> Result<(Node, bool), String> { + let c = match self.next() { + Some(c) => c, + None => return self.err("trailing backslash"), + }; + if let Some(e) = Self::class_esc(c) { + return Ok((Node::Esc(e), true)); + } + if let Some(l) = Self::simple_escape(c) { + return Ok((Node::Char(l), true)); + } + match c { + 'b' => Ok((Node::WordB(true), false)), + 'B' => Ok((Node::WordB(false), false)), + c if c.is_ascii_alphanumeric() => self.err("unsupported escape"), + c => Ok((Node::Char(c), true)), + } + } + + /// One class atom: `Ok(Err(esc))` for a class escape, `Ok(Ok(char))` for a char. + fn class_atom(&mut self) -> Result, String> { + let c = match self.next() { + Some(c) => c, + None => return self.err("unterminated class"), + }; + if c != '\\' { + return Ok(Ok(c)); + } + let e = match self.next() { + Some(e) => e, + None => return self.err("trailing backslash"), + }; + if let Some(esc) = Self::class_esc(e) { + return Ok(Err(esc)); + } + if let Some(l) = Self::simple_escape(e) { + return Ok(Ok(l)); + } + if e.is_ascii_alphanumeric() { + return self.err("unsupported escape in class"); + } + Ok(Ok(e)) + } + + fn parse_class(&mut self) -> Result { + let neg = if self.peek() == Some('^') { + self.pos += 1; + true + } else { + false + }; + let mut items = Vec::new(); + loop { + if self.peek().is_none() { + return self.err("unterminated class"); + } + if self.peek() == Some(']') { + self.pos += 1; + break; + } + let lo = self.class_atom()?; + let is_range = + self.peek() == Some('-') && self.s.get(self.pos + 1).is_some_and(|c| *c != ']'); + match (lo, is_range) { + (Ok(lo), true) => { + self.pos += 1; + match self.class_atom()? { + Ok(hi) if lo <= hi => items.push(ClassItem::Range(lo, hi)), + Ok(_) => return self.err("class range out of order"), + Err(_) => return self.err("class escape as range endpoint"), + } + } + (Err(_), true) => return self.err("class escape as range endpoint"), + (Ok(c), false) => items.push(ClassItem::Range(c, c)), + (Err(e), false) => items.push(ClassItem::Esc(e)), + } + } + Ok(Node::Class { items, neg }) + } +} + +// --------------------------------------------------------------------------- +// Matcher +// --------------------------------------------------------------------------- + +struct St { + caps: Vec>, +} + +type K<'a> = &'a mut dyn FnMut(usize, &mut St) -> bool; + +struct Ctx<'h> { + h: &'h [char], +} + +impl Ctx<'_> { + fn m(&self, node: &Node, i: usize, st: &mut St, k: K) -> bool { + match node { + Node::Empty => k(i, st), + Node::Char(_) | Node::Any | Node::Esc(_) | Node::Class { .. } => { + if i < self.h.len() && node.single(self.h[i]) == Some(true) { + k(i + 1, st) + } else { + false + } + } + Node::Seq(v) => self.seq(v, i, st, k), + Node::Alt(v) => { + for n in v { + if self.m(n, i, st, &mut *k) { + return true; + } + } + false + } + Node::Group(idx, n) => self.m(n, i, st, &mut |j, st| { + let old = st.caps[*idx]; + st.caps[*idx] = Some((i, j)); + if k(j, st) { + true + } else { + st.caps[*idx] = old; + false + } + }), + Node::NegLook(n) => { + let saved = st.caps.clone(); + let matched = self.m(n, i, st, &mut |_, _| true); + st.caps = saved; + !matched && k(i, st) + } + Node::Bol => i == 0 && k(i, st), + Node::Eol => i == self.h.len() && k(i, st), + Node::WordB(want) => { + let a = i > 0 && is_word(self.h[i - 1]); + let b = i < self.h.len() && is_word(self.h[i]); + ((a != b) == *want) && k(i, st) + } + Node::Repeat(r) => { + if r.node.is_single() { + self.rep_single(r, i, st, k) + } else { + self.rep(r, 0, i, st, k) + } + } + } + } + + fn seq(&self, v: &[Node], i: usize, st: &mut St, k: K) -> bool { + match v.split_first() { + None => k(i, st), + Some((first, rest)) => { + self.m(first, i, st, &mut |j, st| self.seq(rest, j, st, &mut *k)) + } + } + } + + fn rep_single(&self, r: &Rep, i: usize, st: &mut St, k: K) -> bool { + let mut avail = 0; + while avail < r.max + && i + avail < self.h.len() + && r.node.single(self.h[i + avail]) == Some(true) + { + avail += 1; + } + if avail < r.min { + return false; + } + if r.greedy { + for n in (r.min..=avail).rev() { + if k(i + n, st) { + return true; + } + } + } else { + for n in r.min..=avail { + if k(i + n, st) { + return true; + } + } + } + false + } + + fn iterate(&self, r: &Rep, count: usize, i: usize, st: &mut St, k: K) -> bool { + let saved: Vec<_> = st.caps[r.lo..r.hi].to_vec(); + for c in &mut st.caps[r.lo..r.hi] { + *c = None; + } + let ok = self.m(&r.node, i, st, &mut |j, st| { + if j == i && count >= r.min { + return false; + } + self.rep(r, count + 1, j, st, &mut *k) + }); + if !ok { + st.caps[r.lo..r.hi].copy_from_slice(&saved); + } + ok + } + + fn rep(&self, r: &Rep, count: usize, i: usize, st: &mut St, k: K) -> bool { + if r.greedy { + if count < r.max && self.iterate(r, count, i, st, &mut *k) { + return true; + } + count >= r.min && k(i, st) + } else { + if count >= r.min && k(i, st) { + return true; + } + count < r.max && self.iterate(r, count, i, st, k) + } + } +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/// A successful match. `groups[0]` is the whole match; non-participating +/// groups are `None`. Offsets are char indices. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Match { + pub start: usize, + pub end: usize, + pub groups: Vec>, +} + +/// A compiled pattern. +#[derive(Debug, Clone)] +pub struct Regex { + node: Node, + ngroups: usize, +} + +impl Regex { + /// Compile `pattern`, or return an error naming the unsupported feature. + pub fn new(pattern: &str) -> Result { + let mut p = Parser { + s: pattern.chars().collect(), + pos: 0, + ngroups: 0, + }; + let node = p.parse_alt()?; + if p.pos != p.s.len() { + return p.err("unmatched )"); + } + Ok(Regex { + node, + ngroups: p.ngroups, + }) + } + + /// Leftmost match starting at an index `>= start`. + pub fn find_at(&self, hay: &[char], start: usize) -> Option { + let ctx = Ctx { h: hay }; + for s in start..=hay.len() { + let mut st = St { + caps: vec![None; self.ngroups + 1], + }; + let mut end = None; + if ctx.m(&self.node, s, &mut st, &mut |j, _| { + end = Some(j); + true + }) { + let end = end.unwrap(); + st.caps[0] = Some((s, end)); + return Some(Match { + start: s, + end, + groups: st.caps, + }); + } + } + None + } + + /// All matches with `matchAll` / global-flag semantics. + pub fn find_all(&self, hay: &[char]) -> Vec { + let mut out = Vec::new(); + let mut last = 0; + while last <= hay.len() { + let Some(m) = self.find_at(hay, last) else { + break; + }; + last = if m.end == m.start { m.end + 1 } else { m.end }; + out.push(m); + } + out + } + + /// First match at or after `start`, with every group as a `String`. + pub fn captures_str(&self, hay: &[char], start: usize) -> Option>> { + let m = self.find_at(hay, start)?; + Some( + m.groups + .iter() + .map(|g| g.map(|(s, e)| hay[s..e].iter().collect())) + .collect(), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn cs(s: &str) -> Vec { + s.chars().collect() + } + + fn caps(p: &str, s: &str) -> Option>> { + Regex::new(p).unwrap().captures_str(&cs(s), 0) + } + + fn some(s: &str) -> Option { + Some(s.to_string()) + } + + #[test] + fn literals_and_leftmost() { + let r = Regex::new("ab").unwrap(); + let m = r.find_at(&cs("xxabab"), 0).unwrap(); + assert_eq!((m.start, m.end), (2, 4)); + let m = r.find_at(&cs("xxabab"), 3).unwrap(); + assert_eq!((m.start, m.end), (4, 6)); + assert!(r.find_at(&cs("ba"), 0).is_none()); + } + + #[test] + fn greedy_vs_lazy() { + assert_eq!(caps("a(.*)b", "axbxb").unwrap()[1], some("xbx")); + assert_eq!(caps("a(.*?)b", "axbxb").unwrap()[1], some("x")); + assert_eq!(caps("a(x{1,2}?)", "axxx").unwrap()[1], some("x")); + assert_eq!(caps("a(x{2,})", "axxxb").unwrap()[1], some("xxx")); + assert_eq!(caps("(a??)a", "a").unwrap()[1], some("")); + assert_eq!(caps("(a??)b", "ab").unwrap()[1], some("a")); + } + + #[test] + fn alternation_and_captures() { + let c = caps("(a)|(b)", "b").unwrap(); + assert_eq!(c, vec![some("b"), None, some("b")]); + let c = caps("(?:ab|a)(c)?", "abd").unwrap(); + assert_eq!(c, vec![some("ab"), None]); + // JS resets captures inside a repeated group on each iteration. + let c = caps("(?:(a)|b)+", "ab").unwrap(); + assert_eq!(c, vec![some("ab"), None]); + } + + #[test] + fn negative_lookahead() { + let c = caps("(?:(?!ab).)+", "xxabyy").unwrap(); + assert_eq!(c[0], some("xx")); + assert!(caps("^(?!a)", "abc").is_none()); + assert!(caps("^(?!a)", "bbc").is_some()); + } + + #[test] + fn classes() { + assert_eq!(caps("[^a-c]+", "abxyc").unwrap()[0], some("xy")); + assert_eq!(caps("[\\d.-]+", "a1.-2b").unwrap()[0], some("1.-2")); + assert_eq!( + caps("[A-Za-z0-9._-]*", "a_b-c d").unwrap()[0], + some("a_b-c") + ); + assert_eq!(caps("[^)]+", "ab)c").unwrap()[0], some("ab")); + } + + #[test] + fn anchors_and_boundaries() { + assert!(caps("^a$", "a").is_some()); + assert!(caps("^a$", "a\n").is_none()); + assert!(caps("^$", "").is_some()); + assert_eq!(caps("\\bfoo\\b", "a foo.").unwrap()[0], some("foo")); + assert!(caps("\\bfoo\\b", "afoo").is_none()); + assert!(caps("\\Boo", "foo").is_some()); + } + + #[test] + fn js_whitespace_and_dot() { + for c in [ + '\u{a0}', '\u{3000}', '\u{feff}', '\u{2028}', '\u{b}', '\u{c}', + ] { + assert!(caps("^\\s$", &c.to_string()).is_some(), "{:?}", c); + } + assert!(caps("^\\s$", "\u{200b}").is_none()); + assert!(caps("^.$", "\u{2028}").is_none()); + assert!(caps("^.$", "\u{1F600}").is_some()); + } + + #[test] + fn find_all_empty_matches_advance() { + let r = Regex::new("a*").unwrap(); + let ms = r.find_all(&cs("baab")); + let spans: Vec<_> = ms.iter().map(|m| (m.start, m.end)).collect(); + assert_eq!(spans, vec![(0, 0), (1, 3), (3, 3), (4, 4)]); + } + + #[test] + fn unsupported_features_are_errors() { + for p in [ + "(a)\\1", "(?=a)", "(?<=a)", "(?a)", "a{", "a**", "\\u0041", "\\x41", "(a", "a)", + "[a-\\d]", "^*", "[b-a]", "\\0", "}", + ] { + assert!(Regex::new(p).is_err(), "{}", p); + } + } +} diff --git a/examples/tasks-axi-rust/crates/jsre/tests/differential.rs b/examples/tasks-axi-rust/crates/jsre/tests/differential.rs new file mode 100644 index 0000000000..cf73d1fa31 --- /dev/null +++ b/examples/tasks-axi-rust/crates/jsre/tests/differential.rs @@ -0,0 +1,841 @@ +//! Differential test: every real pattern is run over deterministic pseudo-random +//! inputs through both `jsre` and node's `RegExp` (via `tests/oracle.mjs`). + +use jsre::Regex; +use std::path::PathBuf; +use std::process::Command; + +const CASES_PER_PATTERN: usize = 4000; + +// ---- tiny JSON writer / reader ------------------------------------------------ + +fn json_str(s: &str) -> String { + let mut o = String::from("\""); + for c in s.chars() { + match c { + '"' => o.push_str("\\\""), + '\\' => o.push_str("\\\\"), + c if (' '..='~').contains(&c) => o.push(c), + c => { + let mut b = [0u16; 2]; + for u in c.encode_utf16(&mut b) { + o.push_str(&format!("\\u{:04x}", u)); + } + } + } + } + o.push('"'); + o +} + +#[derive(Debug, Clone, PartialEq)] +enum J { + Null, + Num(usize), + Arr(Vec), +} + +fn parse_json(s: &[u8], p: &mut usize) -> J { + match s[*p] { + b'n' => { + *p += 4; + J::Null + } + b'[' => { + *p += 1; + let mut v = Vec::new(); + while s[*p] != b']' { + v.push(parse_json(s, p)); + if s[*p] == b',' { + *p += 1; + } + } + *p += 1; + J::Arr(v) + } + _ => { + let st = *p; + while s[*p].is_ascii_digit() { + *p += 1; + } + J::Num(std::str::from_utf8(&s[st..*p]).unwrap().parse().unwrap()) + } + } +} + +type Groups = Vec>; + +fn to_matches(j: &J) -> Vec { + let J::Arr(ms) = j else { + panic!("bad oracle output") + }; + ms.iter() + .map(|m| { + let J::Arr(gs) = m else { panic!("bad match") }; + gs.iter() + .map(|g| match g { + J::Null => None, + J::Arr(p) => match (&p[0], &p[1]) { + (J::Num(a), J::Num(b)) => Some((*a, *b)), + _ => panic!("bad pair"), + }, + _ => panic!("bad group"), + }) + .collect() + }) + .collect() +} + +// ---- deterministic RNG ---------------------------------------------------------- + +struct Rng(u64); +impl Rng { + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x << 13; + x ^= x >> 7; + x ^= x << 17; + self.0 = x; + x + } + fn below(&mut self, n: usize) -> usize { + (self.next() % n as u64) as usize + } + fn pick<'a>(&mut self, v: &[&'a str]) -> &'a str { + v[self.below(v.len())] + } +} + +const VOCAB: &[&str] = &[ + "fix-login-k3", + "a", + "Z9", + "x.y_z-1", + "-bad", + ".dot", + "foo bar", + "SHIP", + "SCOUT", + "DOCS-ONLY", + "PERSISTENT SECONDMATE", + "SHIPPING", + "SCOUTx", + "SHIP-it", + " ", + " ", + "\t", + "\u{a0}", + "\u{3000}", + "\u{2003}", + "\u{feff}", + "\u{b}", + "\u{c}", + "\u{2028}", + "\u{200b}", + "\u{85}", + "\r", + "\n", + " - ", + "-", + "blocked-by:", + "parent:", + "discovered-from:", + " blocked-by: ", + "blocked-by:x", + "parent: ", + "(repo: x)", + "(repo: a/b)", + "(a + repo: c)", + "(repo:)", + "(kind: y)", + "(kind: ship)", + "(priority: 3)", + "(priority: 9)", + "(priority:0)", + "(since 2026-01-02)", + "(since 2026-1-02)", + "(merged 2026-01-02)", + "(reported 2026-06-22)", + "(done 2026-01-02)", + "(closed 2026-01-02)", + "(hold: a b)", + "(hold: x (y))", + "(hold-kind: external)", + "(hold-kind: captain)", + "(hold-kind: parked)", + "(hold-kind: future)", + "(hold-kind: load)", + "(hold-kind: bogus)", + "(hold-until: 2026-12-31)", + "(hold-until: 2026-12-3)", + " - reason text", + " - ", + "reason", + "https://github.com/o/r/pull/12", + "http://example.com/x", + "https://example.com/a/b/pulls/7", + "data/x/report.md", + "data/a/b/report.md", + "data/report.md", + "report.md", + "data/x/report.mdx", + "xdata/x/report.md", + "(", + ")", + "((", + "))", + "()", + "[", + "]", + "*", + "**", + "- [ ] ", + "- [x] ", + "- **", + "- [X] ", + "## ", + "##", + "### ", + "Heading", + "", + "é", + "ß", + "日本", + "😀", + "a😀b", + ".", + ",", + ";", + "text", + "2026-01-02", + "0", + "1", + "42", + "/", + ":", + "?", + "#", + "@", + "_", + "\\", +]; + +const NOISE: &[char] = &[ + ' ', '(', ')', '-', ':', '*', '[', ']', 'a', 'b', 'x', 'Z', '0', '9', '.', '/', ',', ';', '!', + '#', '_', '\t', '\u{a0}', 'é', '😀', '日', 'h', 't', 'p', 's', '=', '"', '\'', '\u{3000}', +]; + +type Skel = &'static [&'static [&'static str]]; + +const IDS: &[&str] = &["fix-login-k3", "a.b", "-x", "", "x y", "Z9_", "é"]; +const REST: &[&str] = &[ + "rest text", + "", + "x\u{a0}y", + "(repo: x)", + "😀", + "a\r", + " ", + "(kind: y) ", +]; + +/// Slot-wise skeletons (first alternative is canonical) for the anchored +/// patterns, whose random-fragment hit rate would otherwise be tiny. +fn skeleton(name: &str) -> Skel { + match name { + "IN_FLIGHT_RE" => &[ + &["- **", "- [ ] ", "- *"], + IDS, + &["** - ", "** - ", "** -", "*** - "], + REST, + ], + "QUEUED_RE" => &[ + &["- [ ] ", "- [x] ", "- [ ]"], + IDS, + &[" - ", " - ", " -"], + REST, + ], + "DONE_RE" => &[ + &["- [x] ", "- [X] ", "- [ ] "], + IDS, + &[" - ", " - ", " -"], + REST, + ], + "TAIL_HOLD_UNTIL" => &[ + &["text ", ""], + &["(hold-until: ", "(hold-until:", "(hold-until: "], + &["2026-12-31", "2026-1-31"], + &[")", ") ", ")\u{a0}", "))"], + ], + "TAIL_CLOSED" => &[ + &["text ", ""], + &["(merged ", "(done ", "(reported ", "(since "], + &["2026-01-02", "2026-1-02"], + &[")", ") ", ")\u{3000}", "))"], + ], + "PUBLIC_FOLLOWUP_METADATA_RE" => &[ + &["", " --> ", ">"], + ], + "PR_URL_RE" => &[ + &["https://", "http://"], + &["github.com", "example.org", "GitHub.com", "a-b.c", "-a.com"], + &["/"], + &["o", "o.p", "..", "a b"], + &["/"], + &["r", "r_s", "."], + &["/"], + &["pull", "pulls", "pull/"], + &["/"], + &["12", "0", "07", "1a"], + &["", "/", "?x"], + ], + _ => &[], + } +} + +fn gen_skel(rng: &mut Rng, skel: Skel) -> String { + let mut s = String::new(); + for slot in skel { + if rng.below(100) < 75 { + s.push_str(slot[0]); + } else { + s.push_str(rng.pick(slot)); + } + } + s +} + +fn gen(rng: &mut Rng, focus: &[&str], skel: Skel) -> String { + if !skel.is_empty() && rng.below(100) < 70 { + return gen_skel(rng, skel); + } + if rng.below(10) == 0 { + let n = rng.below(30); + return (0..n).map(|_| NOISE[rng.below(NOISE.len())]).collect(); + } + let mut s = String::new(); + for _ in 0..1 + rng.below(9) { + if !focus.is_empty() && rng.below(100) < 55 { + s.push_str(rng.pick(focus)); + } else { + s.push_str(rng.pick(VOCAB)); + } + } + if rng.below(10) < 3 { + let mut cs: Vec = s.chars().collect(); + if !cs.is_empty() { + let i = rng.below(cs.len()); + match rng.below(3) { + 0 => { + cs.remove(i); + } + 1 => cs.insert(i, NOISE[rng.below(NOISE.len())]), + _ => { + let c = cs[i]; + cs.insert(i, c); + } + } + } + s = cs.into_iter().collect(); + } + s +} + +// ---- the real patterns (verbatim regex sources from the tasks-axi package) ------ + +const ID: &str = r"[A-Za-z0-9][A-Za-z0-9._-]*"; +const DATE: &str = r"\d{4}-\d{2}-\d{2}"; +const DEP: &str = r"(?:blocked-by|parent|discovered-from)"; + +struct Pat { + name: &'static str, + src: String, + global: bool, + focus: &'static [&'static str], +} + +const BULLET: &[&str] = &[ + "- [ ] ", + "- [x] ", + "- **", + "- [X] ", + "- [ ]", + "- [ ] ", + "**", + "** - ", + "fix-login-k3", + "a.b-c_d", + " - ", + " - text", + "- ", + "\r", +]; + +fn patterns() -> Vec { + let p = |name, src: String, global, focus| Pat { + name, + src, + global, + focus, + }; + vec![ + p( + "IN_FLIGHT_RE", + format!(r"^- \*\*({ID})\*\* - (.*)$"), + false, + BULLET, + ), + p( + "QUEUED_RE", + format!(r"^- \[ \] ({ID}) - (.*)$"), + false, + BULLET, + ), + p( + "DONE_RE", + format!(r"^- \[x\] ({ID}) - (.*)$"), + false, + BULLET, + ), + p( + "ID_RE", + format!("^{ID}$"), + false, + &[ + "a", + "Z9", + "x.y_z-1", + "-", + ".", + "_", + "é", + " ", + "\n", + "fix-login-k3", + ], + ), + p( + "TAIL_DEP", + format!(r"\s*({DEP}):\s*({ID})(?:\s+-\s+((?:(?!\s+{DEP}:\s).)+?))?\s*$"), + false, + &[ + "blocked-by:", + "parent:", + "discovered-from:", + " ", + "fix-login-k3", + " - ", + "because", + " blocked-by: ", + " parent: z", + "\t", + "\u{a0}", + "text", + ":", + "x - y", + ], + ), + p( + "TAIL_REPO", + r"\s*\((?:[^()]*\+\s*)?repo:\s*([^)]+)\)\s*$".to_string(), + false, + &[ + "(repo: x)", + "(a + repo: b)", + "(", + ")", + " ", + "repo:", + "+", + "x", + "(repo:", + "\t", + ], + ), + p( + "TAIL_KIND", + r"\s*\(kind:\s*([^)]+)\)\s*$".to_string(), + false, + &[ + "(kind: y)", + "(kind:", + ")", + " ", + "x", + "\u{3000}", + "(kind: z )", + ], + ), + p( + "TAIL_PRIORITY", + r"\s*\(priority:\s*([0-4])\)\s*$".to_string(), + false, + &[ + "(priority:", + " ", + "0", + "3", + "4", + "5", + "9", + ")", + "\u{a0}", + "(priority: 2)", + ], + ), + p( + "TAIL_SINCE", + format!(r"\s*\(since\s+({DATE})\)\s*$"), + false, + &[ + "(since", + " ", + "2026-01-02", + "2026-1-02", + ")", + "\t", + "x", + "(since 2026-01-02)", + ], + ), + p( + "TAIL_CLOSED", + format!(r"\s*\((?:merged|reported|done|closed)\s+({DATE})\)\s*$"), + false, + &[ + "(merged", + "(reported", + "(done", + "(closed", + "(since", + " ", + "2026-01-02", + ")", + "x", + "\u{2003}", + ], + ), + p( + "TAIL_HOLD", + r"\s*\(hold:\s*([^()]+)\)\s*$".to_string(), + false, + &["(hold:", " ", "why", "(", ")", "(hold: a b)", "x", "\u{a0}"], + ), + p( + "TAIL_HOLD_KIND", + format!( + r"\s*\(hold-kind:\s*({})\)\s*$", + "captain|external|load|parked|future" + ), + false, + &[ + "(hold-kind:", + " ", + "captain", + "external", + "load", + "parked", + "future", + "x", + ")", + "(hold-kind: load)", + ], + ), + p( + "TAIL_HOLD_UNTIL", + format!(r"\s*\(hold-until:\s*({DATE})\)\s*$"), + false, + &[ + "(hold-until:", + " ", + "2026-12-31", + "2026-12-3", + ")", + "x", + "\t", + ], + ), + p( + "REPORT_LINK", + r"\bdata\/\S+?\/report\.md\b".to_string(), + true, + &[ + "data/", + "/report.md", + "data/x/report.md", + " ", + "x", + "report.mdx", + "\u{a0}", + "data/a b/report.md", + "_", + "-", + ], + ), + p( + "GENERIC_URL", + r"https?:\/\/\S+".to_string(), + true, + &[ + "http://", + "https://", + "x.com/y", + " ", + "\u{a0}", + "(", + ")", + ".", + "http:/", + "😀", + "https://github.com/o/r/pull/1", + ], + ), + p( + "LEADING_KIND_PERSISTENT_SECONDMATE", + r"^PERSISTENT SECONDMATE\b".to_string(), + false, + &[ + "PERSISTENT SECONDMATE", + "PERSISTENT SECONDMATE ", + "PERSISTENT SECONDMATES", + "PERSISTENT SECONDMATE_", + "-", + " ", + "x", + ], + ), + p( + "LEADING_KIND_SHIP", + r"^SHIP\b".to_string(), + false, + &["SHIP", " ", "-", "S", "SHIPS", "_", "é", ":"], + ), + p( + "LEADING_KIND_SCOUT", + r"^SCOUT\b".to_string(), + false, + &["SCOUT", " ", "-", "SCOUTS", "_", "é", ":"], + ), + p( + "LEADING_KIND_DOCS_ONLY", + r"^DOCS-ONLY\b".to_string(), + false, + &["DOCS-ONLY", " ", "-", "DOCS-ONLYX", "_", "é", ":"], + ), + p( + "TRIM_URL", + r"[).,;]+$".to_string(), + false, + &[")", ".", ",", ";", "x", "https://a.b/c", " ", "\n"], + ), + p( + "SECTION_HEADER", + r"^##\s+(.*?)\s*$".to_string(), + false, + &[ + "## ", "##", "Heading", " ", "\t", "\u{a0}", "###", " ", "a b", "\r", "\u{2028}", + "😀", + ], + ), + p( + "BACKLOG_HEADER", + r"^##\s+".to_string(), + false, + &["## ", "##", "###", " ", "\t", "\u{3000}", "x", "#"], + ), + p( + "PUBLIC_FOLLOWUP_METADATA_RE", + r"^$".to_string(), + false, + &[ + "", + " ", + "-->", + "x", + "", + "é", + "\n", + ], + ), + p( + "PR_URL_RE", + format!( + r"^https://({h}(?:\.{h})*)/({s})/({s})/(pull|pulls)/([1-9][0-9]*)$", + h = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?", + s = "[A-Za-z0-9._-]+" + ), + false, + &[ + "https://", + "github.com", + "example.org", + "a-b.c", + "-", + "/", + "o", + "r.s", + "..", + ".", + "pull", + "pulls", + "/pull/", + "/pulls/", + "12", + "0", + "07", + "9", + "x", + "?q", + "#f", + ":80", + "user@", + "EXAMPLE.com", + "https://github.com/o/r/pull/12", + "a", + "aa", + "A", + "https://example.org/o/r/pulls/3", + "é", + " ", + ], + ), + ] +} + +// ---- the test --------------------------------------------------------------------- + +fn run() { + if Command::new("node").arg("--version").output().is_err() { + println!("SKIPPED: `node` not found on PATH; differential test not run"); + return; + } + let pats = patterns(); + let mut rng = Rng(0x9E37_79B9_7F4A_7C15); + let mut cases: Vec<(usize, Vec)> = Vec::new(); + let mut file = String::new(); + for (pi, pat) in pats.iter().enumerate() { + for _ in 0..CASES_PER_PATTERN { + let input = gen(&mut rng, pat.focus, skeleton(pat.name)); + file.push_str(&format!( + "{{\"id\":{},\"src\":{},\"global\":{},\"input\":{}}}\n", + cases.len(), + json_str(&pat.src), + pat.global, + json_str(&input) + )); + cases.push((pi, input.chars().collect())); + } + } + let scratch = + std::env::var("DEV_SCRATCH").unwrap_or_else(|_| std::env::temp_dir().display().to_string()); + let dir = PathBuf::from(scratch).join(format!("jsre-diff-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let input_path = dir.join("cases.jsonl"); + std::fs::write(&input_path, file).unwrap(); + let oracle = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/oracle.mjs"); + let out = Command::new("node") + .arg(&oracle) + .arg(&input_path) + .output() + .unwrap(); + let _ = std::fs::remove_dir_all(&dir); + assert!( + out.status.success(), + "oracle failed: {}", + String::from_utf8_lossy(&out.stderr) + ); + let stdout = out.stdout; + + let regexes: Vec = pats + .iter() + .map(|p| Regex::new(&p.src).unwrap_or_else(|e| panic!("{} did not compile: {}", p.name, e))) + .collect(); + let mut compared = vec![0usize; pats.len()]; + let mut hit = vec![0usize; pats.len()]; + let mut mismatches: Vec = Vec::new(); + let mut nmismatch = 0; + let mut seen = 0; + for line in stdout.split(|b| *b == b'\n').filter(|l| !l.is_empty()) { + let mut p = 0; + let J::Arr(top) = parse_json(line, &mut p) else { + panic!("bad line") + }; + let J::Num(id) = top[0] else { panic!("bad id") }; + let expected = to_matches(&top[1]); + let (pi, hay) = &cases[id]; + let re = ®exes[*pi]; + let got: Vec = if pats[*pi].global { + re.find_all(hay).into_iter().map(|m| m.groups).collect() + } else { + re.find_at(hay, 0).into_iter().map(|m| m.groups).collect() + }; + seen += 1; + compared[*pi] += 1; + if !expected.is_empty() { + hit[*pi] += 1; + } + if expected != got { + nmismatch += 1; + if mismatches.len() < 10 { + mismatches.push(format!( + "pattern {} ({})\n input: {:?}\n expected: {:?}\n got: {:?}", + pats[*pi].name, + pats[*pi].src, + hay.iter().collect::(), + expected, + got + )); + } + } + } + assert_eq!( + seen, + cases.len(), + "oracle returned the wrong number of results" + ); + println!("differential: compared {} cases against node", seen); + for (i, p) in pats.iter().enumerate() { + println!( + " {:<38} compared {:>5} with-match {:>5}", + p.name, compared[i], hit[i] + ); + } + if nmismatch > 0 { + panic!( + "{} mismatches; first {}:\n{}", + nmismatch, + mismatches.len(), + mismatches.join("\n") + ); + } + for (i, p) in pats.iter().enumerate() { + assert!( + hit[i] >= 20, + "{}: only {} inputs matched; generator too weak", + p.name, + hit[i] + ); + } +} + +#[test] +fn differential_against_node() { + // Deep backtracking recursion: run on a thread with a generous stack. + std::thread::Builder::new() + .stack_size(256 << 20) + .spawn(run) + .unwrap() + .join() + .unwrap(); +} diff --git a/examples/tasks-axi-rust/crates/jsre/tests/oracle.mjs b/examples/tasks-axi-rust/crates/jsre/tests/oracle.mjs new file mode 100644 index 0000000000..276a7becfb --- /dev/null +++ b/examples/tasks-axi-rust/crates/jsre/tests/oracle.mjs @@ -0,0 +1,37 @@ +// Oracle for the differential test: evaluates each case with the real JS RegExp. +// Input: path to a JSON-lines file of {"id","src","global","input"}. +// Output (stdout): one JSON line per case: [id, [match, ...]] where a match is +// an array of [start,end] code-point offsets (or null for a missing group), +// group 0 first. + +import fs from "node:fs"; +const cases = fs.readFileSync(process.argv[2], "utf8").split("\n").filter(Boolean); +const cache = new Map(); +const out = []; +for (const line of cases) { + const c = JSON.parse(line); + const key = (c.global ? "g:" : "n:") + c.src; + let re = cache.get(key); + if (!re) { + // The `d` flag only adds group indices; it does not change matching. + re = new RegExp(c.src, c.global ? "gd" : "d"); + cache.set(key, re); + } + const s = c.input; + const map = new Array(s.length + 1); + let cp = 0; + for (let i = 0; i < s.length; ) { + const w = s.codePointAt(i) > 0xffff ? 2 : 1; + for (let k = 0; k < w; k++) map[i + k] = cp; + i += w; + cp++; + } + map[s.length] = cp; + re.lastIndex = 0; + const found = c.global ? Array.from(s.matchAll(re)) : [re.exec(s)].filter((m) => m !== null); + const matches = found.map((m) => + Array.from(m.indices, (ix) => (ix === undefined ? null : [map[ix[0]], map[ix[1]]])), + ); + out.push(JSON.stringify([c.id, matches])); +} +process.stdout.write(out.join("\n") + "\n"); diff --git a/examples/tasks-axi-rust/crates/tasks-axi-gen/Cargo.toml b/examples/tasks-axi-rust/crates/tasks-axi-gen/Cargo.toml new file mode 100644 index 0000000000..9addf2c937 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-gen/Cargo.toml @@ -0,0 +1,10 @@ +# @generated by the rust-cli generator. Do not edit. +[package] +name = "tasks-axi-gen" +version = "0.1.0" +edition = "2021" +publish = false +license = "Apache-2.0" +description = "Generated from the tasksaxi MetaObjects model: rows, enums, error codes, argument parser, help and dispatcher for the tasks-axi read path." + +[dependencies] diff --git a/examples/tasks-axi-rust/crates/tasks-axi-gen/src/cli.rs b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/cli.rs new file mode 100644 index 0000000000..566b42683e --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/cli.rs @@ -0,0 +1,539 @@ +// @generated by the rust-cli generator from the tasksaxi model. Do not edit: +// change the model or the generator and run `meta gen`. + +//! The command surface: help text, argument parsing, hints and output column lists. + +use crate::enums::ListState; +use crate::errors::AxiError; +use crate::rows::{Column, TASK_LIST_ROW_EXTRA_COLUMNS}; + +pub const BIN: &str = "tasks-axi"; +pub const VERSION: &str = "0.2.6"; +pub const NOUN: &str = "task"; +pub const TOP_HELP: &str = "usage: tasks-axi-rs [args] [flags]\nRead path of tasks-axi 0.2.6: show, list and ready.\ncommands[3]:\n show (alias view), list, ready\nflags[4]:\n --backend (after command), --file (after command), --help, -v/-V/--version\nEvery other tasks-axi command is refused with exit code 1; use tasks-axi for those."; + +/// Commands the real tool has and this one refuses. +pub const REFUSED: [&str; 19] = [ + "add", + "create", + "start", + "done", + "close", + "reopen", + "update", + "edit", + "rm", + "delete", + "block", + "unblock", + "hold", + "unhold", + "public-followup", + "mv", + "prune", + "render", + "setup", +]; +pub const REFUSAL_MESSAGE: &str = "`{command}` is not implemented by tasks-axi-rs, which ships the read path only (show, list, ready)"; +pub const REFUSAL_SUGGESTION: &str = "Run the same command with the Node tasks-axi"; +pub const REFUSAL_HOME: &str = "the dashboard (tasks-axi with no command)"; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HintWhen { + Always, + Empty, + NonEmpty, + Blocked, +} + +/// A next-step suggestion: a template with `{id}` and a list of filter flags it may carry. +#[derive(Debug, Clone, Copy)] +pub struct Hint { + pub when: HintWhen, + pub line: &'static str, + pub filters: &'static [&'static str], +} + +/// One printed group: its label and the columns it prints. +#[derive(Debug, Clone, Copy)] +pub struct OutputSpec { + pub label: &'static str, + pub columns: &'static [Column], +} + +/// Flags every implemented command accepts, read before the command's own. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Globals { + pub backend: Option, + pub file: Option, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CommandName { + Show, + List, + Ready, +} + +impl CommandName { + /// The implemented command a word names (its name or an alias). + pub fn from_word(word: &str) -> Option { + match word { + "show" => Some(CommandName::Show), + "view" => Some(CommandName::Show), + "list" => Some(CommandName::List), + "ready" => Some(CommandName::Ready), + _ => None, + } + } + + pub const fn help(self) -> &'static str { + match self { + CommandName::Show => SHOW_HELP, + CommandName::List => LIST_HELP, + CommandName::Ready => READY_HELP, + } + } +} + +/// Remove the global flags from `args`; the rest is the command's own. +pub fn parse_globals(args: &[String]) -> Result<(Globals, Vec), AxiError> { + let mut globals = Globals::default(); + let mut stripped: Vec = Vec::new(); + let mut i = 0; + while i < args.len() { + let arg = args[i].as_str(); + if arg == "--backend" { + let value = require_flag_value(args, i, "--backend")?; + globals.backend = require_non_empty_single_line("--backend", Some(value))?; + i += 2; + continue; + } + if let Some(value) = arg.strip_prefix("--backend=") { + globals.backend = require_non_empty_single_line("--backend", Some(value.to_string()))?; + i += 1; + continue; + } + if arg == "--file" { + let value = require_flag_value(args, i, "--file")?; + globals.file = require_non_empty_single_line("--file", Some(value))?; + i += 2; + continue; + } + if let Some(value) = arg.strip_prefix("--file=") { + globals.file = require_non_empty_single_line("--file", Some(value.to_string()))?; + i += 1; + continue; + } + stripped.push(args[i].clone()); + i += 1; + } + Ok((globals, stripped)) +} + +pub const SHOW_HELP: &str = "usage: tasks-axi show [--full]\naliases: view\nexamples:\n tasks-axi show homemux-h7\n tasks-axi show homemux-h7 --full"; +pub const SHOW_USAGE: &str = "usage: tasks-axi show [--full]"; + +pub const SHOW_HINTS: &[Hint] = &[ + Hint { + when: HintWhen::Blocked, + line: "Run `tasks-axi unblock {id} --by ` to clear a blocker", + filters: &[], + }, + Hint { + when: HintWhen::Blocked, + line: "Run `tasks-axi start {id}` to move it to in flight", + filters: &[], + }, +]; + +pub const SHOW_OUTPUTS: &[OutputSpec] = &[OutputSpec { + label: "task", + columns: &[ + Column::Id, + Column::Title, + Column::State, + Column::Blocked, + Column::BlockedBy, + Column::Held, + Column::HoldReason, + Column::HoldKind, + Column::HoldUntil, + Column::Kind, + Column::Repo, + Column::Priority, + Column::Created, + Column::Closed, + Column::Deps, + Column::Links, + Column::Body, + ], +}]; + +#[derive(Debug, Clone, PartialEq)] +pub struct ShowArgs { + pub id: String, + pub full: bool, +} + +/// Read `show`'s arguments (global flags already removed), flag by flag in the order the +/// model lists them, then the positionals. +pub fn parse_show(raw: &[String]) -> Result { + let mut args: Vec = raw.to_vec(); + let full = take_bool_flag(&mut args, "--full"); + let positionals = require_positionals(&args, 1, 1, SHOW_USAGE)?; + let id = require_id(&positionals[0], "id")?; + let _ = &positionals; + Ok(ShowArgs { id, full }) +} + +pub const LIST_HELP: &str = "usage: tasks-axi list [flags]\nflags:\n --state , --repo , --kind , --blocked\n --limit , --fields (extra: blocked, blocked_by, body, closed, created, delivery_state, deps, held, hold_kind, hold_reason, hold_until, links, priority)\nexamples:\n tasks-axi list --state queued\n tasks-axi list --repo no-mistakes --fields blocked_by,created\n tasks-axi list --blocked"; +pub const LIST_USAGE: &str = "usage: tasks-axi list [flags]"; + +pub const LIST_HINTS: &[Hint] = &[ + Hint { + when: HintWhen::NonEmpty, + line: "Run `tasks-axi show ` for full notes on a task", + filters: &[], + }, + Hint { + when: HintWhen::NonEmpty, + line: "Run `tasks-axi ready` to see unblocked queued work", + filters: &["repo"], + }, + Hint { + when: HintWhen::Empty, + line: "Run `tasks-axi add \"\"` to add a task", + filters: &["repo", "kind"], + }, + Hint { + when: HintWhen::Empty, + line: "Run `tasks-axi list --state done` to see completed work", + filters: &["repo", "kind"], + }, +]; + +pub const LIST_OUTPUTS: &[OutputSpec] = &[OutputSpec { + label: "tasks", + columns: &[ + Column::Id, + Column::State, + Column::Kind, + Column::Repo, + Column::Title, + ], +}]; + +#[derive(Debug, Clone, PartialEq)] +pub struct ListArgs { + pub fields: Vec<Column>, + pub state: Option<ListState>, + pub repo: Option<String>, + pub kind: Option<String>, + pub blocked: bool, + pub limit: Option<u64>, +} + +/// Read `list`'s arguments (global flags already removed), flag by flag in the order the +/// model lists them, then the positionals. +pub fn parse_list(raw: &[String]) -> Result<ListArgs, AxiError> { + let mut args: Vec<String> = raw.to_vec(); + let fields = parse_columns( + "--fields", + take_flag(&mut args, "--fields")?, + &TASK_LIST_ROW_EXTRA_COLUMNS, + )?; + let state = match take_flag(&mut args, "--state")? { + None => None, + Some(raw) => Some(ListState::parse(&raw).ok_or_else(|| { + AxiError::validation( + "--state must be one of queued, in_flight, done, held", + Vec::new(), + ) + })?), + }; + let repo = require_non_empty_single_line("--repo", take_flag(&mut args, "--repo")?)?; + let kind = require_non_empty_single_line("--kind", take_flag(&mut args, "--kind")?)?; + let blocked = take_bool_flag(&mut args, "--blocked"); + let limit = parse_optional_uint("--limit", take_flag(&mut args, "--limit")?)?; + let positionals = require_positionals(&args, 0, 0, LIST_USAGE)?; + let _ = &positionals; + Ok(ListArgs { + fields, + state, + repo, + kind, + blocked, + limit, + }) +} + +pub const READY_HELP: &str = "usage: tasks-axi ready [--repo <name>] [--include-held]\nList unblocked, unheld queued work dispatchable right now.\nPublic-followup obligations are never dispatchable and appear only in the separate\nready_public_followups group; use tasks-axi public-followup ready for their full payloads.\nHeld work is excluded by default; --include-held shows it in a separate held group."; +pub const READY_USAGE: &str = "usage: tasks-axi ready [--repo <name>] [--include-held]"; + +pub const READY_HINTS: &[Hint] = &[ + Hint { + when: HintWhen::NonEmpty, + line: "Run `tasks-axi start <id>` to dispatch one of these", + filters: &[], + }, + Hint { + when: HintWhen::Empty, + line: "Run `tasks-axi list --state queued` to see all queued work (incl. blocked)", + filters: &["repo"], + }, +]; + +pub const READY_OUTPUTS: &[OutputSpec] = &[ + OutputSpec { + label: "ready", + columns: &[ + Column::Id, + Column::State, + Column::Kind, + Column::Repo, + Column::Title, + ], + }, + OutputSpec { + label: "ready_public_followups", + columns: &[ + Column::Id, + Column::State, + Column::Kind, + Column::Repo, + Column::Title, + Column::DeliveryState, + ], + }, + OutputSpec { + label: "held", + columns: &[ + Column::Id, + Column::State, + Column::Kind, + Column::Repo, + Column::Title, + Column::HoldReason, + Column::HoldKind, + Column::HoldUntil, + ], + }, +]; + +#[derive(Debug, Clone, PartialEq)] +pub struct ReadyArgs { + pub repo: Option<String>, + pub include_held: bool, +} + +/// Read `ready`'s arguments (global flags already removed), flag by flag in the order the +/// model lists them, then the positionals. +pub fn parse_ready(raw: &[String]) -> Result<ReadyArgs, AxiError> { + let mut args: Vec<String> = raw.to_vec(); + let repo = require_non_empty_single_line("--repo", take_flag(&mut args, "--repo")?)?; + let include_held = take_bool_flag(&mut args, "--include-held"); + let positionals = require_positionals(&args, 0, 0, READY_USAGE)?; + let _ = &positionals; + Ok(ReadyArgs { repo, include_held }) +} + +/// JavaScript's `\s` set, which `String.prototype.trim` also uses. +pub fn is_js_space(c: char) -> bool { + matches!( + c, + '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}' + ..='\u{200a}' + | '\u{2028}' + | '\u{2029}' + | '\u{202f}' + | '\u{205f}' + | '\u{3000}' + | '\u{feff}' + ) +} + +/// `String.prototype.trim`. +pub fn js_trim(s: &str) -> &str { + s.trim_matches(is_js_space) +} + +const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991; + +fn require_flag_value(args: &[String], index: usize, flag: &str) -> Result<String, AxiError> { + match args.get(index + 1) { + Some(v) if !v.starts_with("--") => Ok(v.clone()), + _ => Err(AxiError::validation( + format!("{flag} requires a value"), + vec![format!("Pass {flag}=... if the value begins with --")], + )), + } +} + +/// `--flag value` or `--flag=value`: the first occurrence, removed from `args`. +fn take_flag(args: &mut Vec<String>, flag: &str) -> Result<Option<String>, AxiError> { + let equals = format!("{flag}="); + for i in 0..args.len() { + if args[i] == flag { + let value = require_flag_value(args, i, flag)?; + args.drain(i..i + 2); + return Ok(Some(value)); + } + if let Some(value) = args[i].strip_prefix(equals.as_str()) { + let value = value.to_string(); + args.remove(i); + return Ok(Some(value)); + } + } + Ok(None) +} + +fn take_bool_flag(args: &mut Vec<String>, flag: &str) -> bool { + match args.iter().position(|a| a == flag) { + Some(i) => { + args.remove(i); + true + } + None => false, + } +} + +fn require_non_empty_flag_value( + flag: &str, + value: Option<String>, +) -> Result<Option<String>, AxiError> { + match value { + Some(v) if js_trim(&v).is_empty() => Err(AxiError::validation( + format!("{flag} requires a value"), + vec![format!("Pass {flag}=... with a non-empty value")], + )), + other => Ok(other), + } +} + +fn require_non_empty_single_line( + flag: &str, + value: Option<String>, +) -> Result<Option<String>, AxiError> { + match require_non_empty_flag_value(flag, value)? { + Some(v) if v.contains(['\r', '\n']) => Err(AxiError::validation( + format!("{flag} must be a single line"), + vec![format!("Pass {flag}=... without line breaks")], + )), + other => Ok(other), + } +} + +fn parse_optional_uint(flag: &str, raw: Option<String>) -> Result<Option<u64>, AxiError> { + let Some(raw) = raw else { return Ok(None) }; + let bad = || AxiError::validation(format!("{flag} must be a non-negative integer"), vec![]); + if raw.is_empty() || !raw.bytes().all(|b| b.is_ascii_digit()) { + return Err(bad()); + } + match raw.parse::<u64>() { + Ok(n) if n <= MAX_SAFE_INTEGER => Ok(Some(n)), + _ => Err(bad()), + } +} + +fn parse_columns( + flag: &str, + raw: Option<String>, + available: &[Column], +) -> Result<Vec<Column>, AxiError> { + let Some(raw) = raw else { + return Ok(Vec::new()); + }; + let mut requested: Vec<String> = Vec::new(); + for part in raw.split(',') { + let name = js_trim(part); + if !name.is_empty() && !requested.iter().any(|r| r == name) { + requested.push(name.to_string()); + } + } + let unknown: Vec<&str> = requested + .iter() + .map(String::as_str) + .filter(|n| !available.iter().any(|c| c.name() == *n)) + .collect(); + if !unknown.is_empty() { + let mut names: Vec<&str> = available.iter().map(|c| c.name()).collect(); + names.sort_unstable(); + let _ = flag; + return Err(AxiError::validation( + format!( + "Unknown field(s): {}. Available: {}", + unknown.join(", "), + names.join(", ") + ), + vec![], + )); + } + Ok(requested.iter().filter_map(|n| Column::parse(n)).collect()) +} + +fn require_no_unknown_flags(args: &[String]) -> Result<(), AxiError> { + match args.iter().find(|a| a.starts_with('-')) { + Some(unknown) => Err(AxiError::validation( + format!("Unknown flag: {unknown}"), + vec!["Run the command with --help to see supported flags".to_string()], + )), + None => Ok(()), + } +} + +fn require_positionals( + args: &[String], + min: usize, + max: usize, + usage: &str, +) -> Result<Vec<String>, AxiError> { + require_no_unknown_flags(args)?; + let positionals: Vec<String> = args + .iter() + .filter(|a| !a.starts_with('-')) + .cloned() + .collect(); + if positionals.len() >= min && positionals.len() <= max { + return Ok(positionals); + } + let expected = if min == max { + if min == 0 { + "no positional arguments".to_string() + } else { + format!( + "{min} positional argument{}", + if min == 1 { "" } else { "s" } + ) + } + } else { + format!("{min}-{max} positional arguments") + }; + Err(AxiError::validation( + format!("Expected {expected}, got {}", positionals.len()), + vec![usage.to_string()], + )) +} + +/// A task id: slug-shaped, `^[A-Za-z0-9][A-Za-z0-9._-]*$`. +pub fn is_task_id(id: &str) -> bool { + let mut chars = id.chars(); + matches!(chars.next(), Some(c) if c.is_ascii_alphanumeric()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) +} + +fn require_id(raw: &str, label: &str) -> Result<String, AxiError> { + if js_trim(raw).is_empty() { + return Err(AxiError::validation( + format!("Missing {label}"), + vec![format!("Pass the task {label}, e.g. `{BIN} show <id>`")], + )); + } + if !is_task_id(raw) { + return Err(AxiError::validation( + format!("Invalid id \"{raw}\" - ids must be slug-shaped (letters, digits, \"._-\") with no spaces"), + vec!["Use a slug like `homemux-h7`, or pass --mint to generate one".to_string()], + )); + } + Ok(raw.to_string()) +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-gen/src/dispatch.rs b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/dispatch.rs new file mode 100644 index 0000000000..671d88351f --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/dispatch.rs @@ -0,0 +1,99 @@ +// @generated by the rust-cli generator from the tasksaxi model. Do not edit: +// change the model or the generator and run `meta gen`. + +//! The handlers trait the hand-written side implements, and the dispatcher that drives it. + +use crate::cli::{ + self, parse_globals, CommandName, Globals, ListArgs, ReadyArgs, ShowArgs, BIN, NOUN, + REFUSAL_HOME, REFUSAL_MESSAGE, REFUSAL_SUGGESTION, REFUSED, TOP_HELP, VERSION, +}; +use crate::errors::{AxiError, ErrorCode}; + +/// What a run produced. `Output` and `Failure` are rendered by the caller (an output gets a +/// trailing newline); `Verbatim` is printed exactly as given. +#[derive(Debug, Clone, PartialEq)] +pub enum Outcome { + Output(String), + Verbatim(String), + Failure(AxiError), +} + +/// One method per implemented command. The dispatcher cannot call a command this trait lacks, +/// and the hand-written side cannot lose one without failing to compile. +pub trait Handlers { + /// Resolve the backlog context (config, backend, file) once the global flags are read. + fn resolve_context(&mut self, globals: &Globals) -> Result<(), AxiError>; + fn show(&mut self, args: ShowArgs) -> Result<String, AxiError>; + fn list(&mut self, args: ListArgs) -> Result<String, AxiError>; + fn ready(&mut self, args: ReadyArgs) -> Result<String, AxiError>; +} + +fn refusal(command: &str) -> AxiError { + AxiError::new( + REFUSAL_MESSAGE.replace("{command}", command), + ErrorCode::Unsupported, + vec![REFUSAL_SUGGESTION.to_string()], + ) +} + +/// Run one invocation: `argv` excludes the program name. +pub fn run<H: Handlers>(argv: &[String], handlers: &mut H) -> Outcome { + match run_inner(argv, handlers) { + Ok(outcome) => outcome, + Err(e) => Outcome::Failure(e), + } +} + +fn run_inner<H: Handlers>(argv: &[String], handlers: &mut H) -> Result<Outcome, AxiError> { + // The noun is optional: `tasks-axi task show x` is `tasks-axi show x`. + let argv: &[String] = if argv.first().map(String::as_str) == Some(NOUN) { + &argv[1..] + } else { + argv + }; + + if argv.len() == 1 && argv[0] == "--help" { + return Ok(Outcome::Verbatim(format!("{TOP_HELP}\n"))); + } + if argv.len() == 1 && matches!(argv[0].as_str(), "-v" | "-V" | "--version") { + return Ok(Outcome::Verbatim(format!("{VERSION}\n"))); + } + let Some(command) = argv.first() else { + return Err(refusal(REFUSAL_HOME)); + }; + if command.starts_with('-') { + return Err(AxiError::validation( + "Flags must come after the command", + vec![ + format!("Run `{BIN} <command> [args] [flags]`"), + format!("Move `{command}` after the command instead of before it"), + ], + )); + } + let args = &argv[1..]; + let implemented = CommandName::from_word(command); + let refused = REFUSED.contains(&command.as_str()); + if args.iter().any(|a| a == "--help") { + if let Some(name) = implemented { + return Ok(Outcome::Verbatim(name.help().to_string())); + } + } + if refused { + return Err(refusal(command)); + } + let Some(name) = implemented else { + return Err(AxiError::validation( + format!("Unknown command: {command}"), + vec!["Run `--help` to see available commands".to_string()], + )); + }; + + let (globals, rest) = parse_globals(args)?; + handlers.resolve_context(&globals)?; + let output = match name { + CommandName::Show => handlers.show(cli::parse_show(&rest)?)?, + CommandName::List => handlers.list(cli::parse_list(&rest)?)?, + CommandName::Ready => handlers.ready(cli::parse_ready(&rest)?)?, + }; + Ok(Outcome::Output(output)) +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-gen/src/enums.rs b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/enums.rs new file mode 100644 index 0000000000..ea5c6ffd4a --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/enums.rs @@ -0,0 +1,179 @@ +// @generated by the rust-cli generator from the tasksaxi model. Do not edit: +// change the model or the generator and run `meta gen`. + +//! Closed sets of the tasks-axi model: the three task states, the five hold kinds, and so on. + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum TaskState { + Queued, + InFlight, + Done, +} + +impl TaskState { + /// Every member, in declaration order. + pub const ALL: [TaskState; 3] = [TaskState::Queued, TaskState::InFlight, TaskState::Done]; + + /// The printed and parsed spelling. + pub const fn as_str(self) -> &'static str { + match self { + TaskState::Queued => "queued", + TaskState::InFlight => "in_flight", + TaskState::Done => "done", + } + } + + /// The member spelled `s`, if any. + pub fn parse(s: &str) -> Option<TaskState> { + match s { + "queued" => Some(TaskState::Queued), + "in_flight" => Some(TaskState::InFlight), + "done" => Some(TaskState::Done), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum HoldKind { + Captain, + External, + Load, + Parked, + Future, +} + +impl HoldKind { + /// Every member, in declaration order. + pub const ALL: [HoldKind; 5] = [ + HoldKind::Captain, + HoldKind::External, + HoldKind::Load, + HoldKind::Parked, + HoldKind::Future, + ]; + + /// The printed and parsed spelling. + pub const fn as_str(self) -> &'static str { + match self { + HoldKind::Captain => "captain", + HoldKind::External => "external", + HoldKind::Load => "load", + HoldKind::Parked => "parked", + HoldKind::Future => "future", + } + } + + /// The member spelled `s`, if any. + pub fn parse(s: &str) -> Option<HoldKind> { + match s { + "captain" => Some(HoldKind::Captain), + "external" => Some(HoldKind::External), + "load" => Some(HoldKind::Load), + "parked" => Some(HoldKind::Parked), + "future" => Some(HoldKind::Future), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum DepType { + BlockedBy, + Parent, + DiscoveredFrom, +} + +impl DepType { + /// Every member, in declaration order. + pub const ALL: [DepType; 3] = [DepType::BlockedBy, DepType::Parent, DepType::DiscoveredFrom]; + + /// The printed and parsed spelling. + pub const fn as_str(self) -> &'static str { + match self { + DepType::BlockedBy => "blocked-by", + DepType::Parent => "parent", + DepType::DiscoveredFrom => "discovered-from", + } + } + + /// The member spelled `s`, if any. + pub fn parse(s: &str) -> Option<DepType> { + match s { + "blocked-by" => Some(DepType::BlockedBy), + "parent" => Some(DepType::Parent), + "discovered-from" => Some(DepType::DiscoveredFrom), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum LinkKind { + Pr, + Report, + Doc, +} + +impl LinkKind { + /// Every member, in declaration order. + pub const ALL: [LinkKind; 3] = [LinkKind::Pr, LinkKind::Report, LinkKind::Doc]; + + /// The printed and parsed spelling. + pub const fn as_str(self) -> &'static str { + match self { + LinkKind::Pr => "pr", + LinkKind::Report => "report", + LinkKind::Doc => "doc", + } + } + + /// The member spelled `s`, if any. + pub fn parse(s: &str) -> Option<LinkKind> { + match s { + "pr" => Some(LinkKind::Pr), + "report" => Some(LinkKind::Report), + "doc" => Some(LinkKind::Doc), + _ => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ListState { + Queued, + InFlight, + Done, + Held, +} + +impl ListState { + /// Every member, in declaration order. + pub const ALL: [ListState; 4] = [ + ListState::Queued, + ListState::InFlight, + ListState::Done, + ListState::Held, + ]; + + /// The printed and parsed spelling. + pub const fn as_str(self) -> &'static str { + match self { + ListState::Queued => "queued", + ListState::InFlight => "in_flight", + ListState::Done => "done", + ListState::Held => "held", + } + } + + /// The member spelled `s`, if any. + pub fn parse(s: &str) -> Option<ListState> { + match s { + "queued" => Some(ListState::Queued), + "in_flight" => Some(ListState::InFlight), + "done" => Some(ListState::Done), + "held" => Some(ListState::Held), + _ => None, + } + } +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-gen/src/errors.rs b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/errors.rs new file mode 100644 index 0000000000..03022dd382 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/errors.rs @@ -0,0 +1,75 @@ +// @generated by the rust-cli generator from the tasksaxi model. Do not edit: +// change the model or the generator and run `meta gen`. + +//! Error codes with their exit codes, and the structured error every command fails with. + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ErrorCode { + ValidationError, + NotFound, + Conflict, + Unsupported, + Locked, + Unknown, +} + +impl ErrorCode { + pub const ALL: [ErrorCode; 6] = [ + ErrorCode::ValidationError, + ErrorCode::NotFound, + ErrorCode::Conflict, + ErrorCode::Unsupported, + ErrorCode::Locked, + ErrorCode::Unknown, + ]; + + /// The code as printed after `code:`. + pub const fn as_str(self) -> &'static str { + match self { + ErrorCode::ValidationError => "VALIDATION_ERROR", + ErrorCode::NotFound => "NOT_FOUND", + ErrorCode::Conflict => "CONFLICT", + ErrorCode::Unsupported => "UNSUPPORTED", + ErrorCode::Locked => "LOCKED", + ErrorCode::Unknown => "UNKNOWN", + } + } + + /// The process exit status the code maps to. + pub const fn exit_code(self) -> i32 { + match self { + ErrorCode::ValidationError => 2, + ErrorCode::NotFound => 1, + ErrorCode::Conflict => 1, + ErrorCode::Unsupported => 1, + ErrorCode::Locked => 1, + ErrorCode::Unknown => 1, + } + } +} + +/// A command failure: a message, a code, and next-step suggestions. +#[derive(Debug, Clone, PartialEq)] +pub struct AxiError { + pub message: String, + pub code: ErrorCode, + pub suggestions: Vec<String>, +} + +impl AxiError { + pub fn new(message: impl Into<String>, code: ErrorCode, suggestions: Vec<String>) -> AxiError { + AxiError { + message: message.into(), + code, + suggestions, + } + } + + pub fn validation(message: impl Into<String>, suggestions: Vec<String>) -> AxiError { + AxiError::new(message, ErrorCode::ValidationError, suggestions) + } + + pub fn exit_code(&self) -> i32 { + self.code.exit_code() + } +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-gen/src/lib.rs b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/lib.rs new file mode 100644 index 0000000000..7f7fabfa2f --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/lib.rs @@ -0,0 +1,12 @@ +// @generated by the rust-cli generator from the tasksaxi model. Do not edit: +// change the model or the generator and run `meta gen`. + +//! Generated half of the tasks-axi read path. The hand-written half implements +//! `dispatch::Handlers`; see the example's README for the split. + +pub mod cli; +pub mod dispatch; +pub mod enums; +pub mod errors; +pub mod model; +pub mod rows; diff --git a/examples/tasks-axi-rust/crates/tasks-axi-gen/src/model.rs b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/model.rs new file mode 100644 index 0000000000..21e0949454 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/model.rs @@ -0,0 +1,42 @@ +// @generated by the rust-cli generator from the tasksaxi model. Do not edit: +// change the model or the generator and run `meta gen`. + +//! The task record and its value objects, as the markdown backlog parser builds them. + +use crate::enums::{DepType, HoldKind, LinkKind, TaskState}; + +#[derive(Debug, Clone, PartialEq)] +pub struct Hold { + pub reason: String, + pub kind: Option<HoldKind>, + pub until: Option<String>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Dep { + pub r#type: DepType, + pub id: String, + pub reason: Option<String>, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Link { + pub kind: LinkKind, + pub url: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Task { + pub id: String, + pub title: String, + pub state: TaskState, + pub kind: Option<String>, + pub repo: Option<String>, + pub priority: Option<i64>, + pub created: Option<String>, + pub closed: Option<String>, + pub body: Option<String>, + pub hold: Option<Hold>, + pub deps: Vec<Dep>, + pub links: Vec<Link>, +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-gen/src/rows.rs b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/rows.rs new file mode 100644 index 0000000000..a205916e6c --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-gen/src/rows.rs @@ -0,0 +1,240 @@ +// @generated by the rust-cli generator from the tasksaxi model. Do not edit: +// change the model or the generator and run `meta gen`. + +//! The printed row, its columns and the column sets each view prints. + +use crate::enums::{HoldKind, TaskState}; + +/// One printed value: text, or an integer (printed as a TOON number). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Cell { + Str(String), + Int(i64), +} + +/// TaskRow: one flat record carrying every derivable column. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskRow { + pub id: String, + pub title: String, + pub state: TaskState, + pub blocked: bool, + pub blocked_by: Vec<String>, + pub held: bool, + pub hold_reason: Option<String>, + pub hold_kind: Option<HoldKind>, + pub hold_until: Option<String>, + pub kind: Option<String>, + pub repo: Option<String>, + pub priority: Option<i64>, + pub created: Option<String>, + pub closed: Option<String>, + pub delivery_state: Option<String>, + pub deps: Vec<String>, + pub links: Vec<String>, + pub body: Option<String>, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Column { + Id, + Title, + State, + Blocked, + BlockedBy, + Held, + HoldReason, + HoldKind, + HoldUntil, + Kind, + Repo, + Priority, + Created, + Closed, + DeliveryState, + Deps, + Links, + Body, +} + +impl Column { + /// Every column, in row order. + pub const ALL: [Column; 18] = [ + Column::Id, + Column::Title, + Column::State, + Column::Blocked, + Column::BlockedBy, + Column::Held, + Column::HoldReason, + Column::HoldKind, + Column::HoldUntil, + Column::Kind, + Column::Repo, + Column::Priority, + Column::Created, + Column::Closed, + Column::DeliveryState, + Column::Deps, + Column::Links, + Column::Body, + ]; + + /// The header name. + pub const fn name(self) -> &'static str { + match self { + Column::Id => "id", + Column::Title => "title", + Column::State => "state", + Column::Blocked => "blocked", + Column::BlockedBy => "blocked_by", + Column::Held => "held", + Column::HoldReason => "hold_reason", + Column::HoldKind => "hold_kind", + Column::HoldUntil => "hold_until", + Column::Kind => "kind", + Column::Repo => "repo", + Column::Priority => "priority", + Column::Created => "created", + Column::Closed => "closed", + Column::DeliveryState => "delivery_state", + Column::Deps => "deps", + Column::Links => "links", + Column::Body => "body", + } + } + + /// The column called `s`, if any. + pub fn parse(s: &str) -> Option<Column> { + match s { + "id" => Some(Column::Id), + "title" => Some(Column::Title), + "state" => Some(Column::State), + "blocked" => Some(Column::Blocked), + "blocked_by" => Some(Column::BlockedBy), + "held" => Some(Column::Held), + "hold_reason" => Some(Column::HoldReason), + "hold_kind" => Some(Column::HoldKind), + "hold_until" => Some(Column::HoldUntil), + "kind" => Some(Column::Kind), + "repo" => Some(Column::Repo), + "priority" => Some(Column::Priority), + "created" => Some(Column::Created), + "closed" => Some(Column::Closed), + "delivery_state" => Some(Column::DeliveryState), + "deps" => Some(Column::Deps), + "links" => Some(Column::Links), + "body" => Some(Column::Body), + _ => None, + } + } + + /// Display limit in UTF-16 units for columns whose text is truncated, else None. + pub const fn truncate_limit(self) -> Option<usize> { + match self { + Column::Title => Some(80), + Column::Body => Some(500), + _ => None, + } + } +} + +impl TaskRow { + /// The printed value of column `c`. + pub fn cell(&self, c: Column) -> Cell { + match c { + Column::Id => Cell::Str(self.id.clone()), + Column::Title => Cell::Str(self.title.clone()), + Column::State => Cell::Str(self.state.as_str().to_string()), + Column::Blocked => Cell::Str((if self.blocked { "yes" } else { "no" }).to_string()), + Column::BlockedBy => Cell::Str(if self.blocked_by.is_empty() { + "none".to_string() + } else { + self.blocked_by.join(",") + }), + Column::Held => Cell::Str((if self.held { "yes" } else { "no" }).to_string()), + Column::HoldReason => { + Cell::Str(self.hold_reason.clone().unwrap_or_else(|| "-".to_string())) + } + Column::HoldKind => Cell::Str( + self.hold_kind + .map(|v| v.as_str().to_string()) + .unwrap_or_else(|| "-".to_string()), + ), + Column::HoldUntil => { + Cell::Str(self.hold_until.clone().unwrap_or_else(|| "-".to_string())) + } + Column::Kind => Cell::Str(self.kind.clone().unwrap_or_else(|| "task".to_string())), + Column::Repo => Cell::Str(self.repo.clone().unwrap_or_else(|| "-".to_string())), + Column::Priority => match self.priority { + Some(v) => Cell::Int(v), + None => Cell::Str("-".to_string()), + }, + Column::Created => Cell::Str(self.created.clone().unwrap_or_else(|| "-".to_string())), + Column::Closed => Cell::Str(self.closed.clone().unwrap_or_else(|| "-".to_string())), + Column::DeliveryState => Cell::Str( + self.delivery_state + .clone() + .unwrap_or_else(|| "-".to_string()), + ), + Column::Deps => Cell::Str(if self.deps.is_empty() { + "none".to_string() + } else { + self.deps.join(",") + }), + Column::Links => Cell::Str(if self.links.is_empty() { + "none".to_string() + } else { + self.links.join(",") + }), + Column::Body => Cell::Str(self.body.clone().unwrap_or_default()), + } + } +} + +/// Columns of `TaskListRow`, in print order. +pub const TASK_LIST_ROW_COLUMNS: [Column; 5] = [ + Column::Id, + Column::State, + Column::Kind, + Column::Repo, + Column::Title, +]; + +/// Columns of `TaskDetailRow`, in print order. +pub const TASK_DETAIL_ROW_COLUMNS: [Column; 17] = [ + Column::Id, + Column::Title, + Column::State, + Column::Blocked, + Column::BlockedBy, + Column::Held, + Column::HoldReason, + Column::HoldKind, + Column::HoldUntil, + Column::Kind, + Column::Repo, + Column::Priority, + Column::Created, + Column::Closed, + Column::Deps, + Column::Links, + Column::Body, +]; + +/// Columns a caller may add with `--fields` to a view printing `TaskListRow`: every column that set lacks. +pub const TASK_LIST_ROW_EXTRA_COLUMNS: [Column; 13] = [ + Column::Blocked, + Column::BlockedBy, + Column::Held, + Column::HoldReason, + Column::HoldKind, + Column::HoldUntil, + Column::Priority, + Column::Created, + Column::Closed, + Column::DeliveryState, + Column::Deps, + Column::Links, + Column::Body, +]; diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/Cargo.toml b/examples/tasks-axi-rust/crates/tasks-axi-rs/Cargo.toml new file mode 100644 index 0000000000..33d17f1618 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "tasks-axi-rs" +version = "0.1.0" +edition = "2021" +publish = false +license = "Apache-2.0" +description = "The read path of tasks-axi (show, list, ready) in Rust: the hand-written half, over the generated tasks-axi-gen crate." + +[[bin]] +name = "tasks-axi-rs" +path = "src/main.rs" + +[dependencies] +tasks-axi-gen = { path = "../tasks-axi-gen" } +toon-encode = { path = "../toon" } +jsre = { path = "../jsre" } diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/src/app.rs b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/app.rs new file mode 100644 index 0000000000..2ccf3ebdf3 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/app.rs @@ -0,0 +1,263 @@ +//! The read commands over the markdown backlog: the hand-written half of the generated +//! `Handlers` trait. + +use crate::config::{check_archives, read_file_safe, resolve_config, Config, Env}; +use crate::derive::{blocked_ids, held_tasks, local_date, ready_tasks}; +use crate::grammar::{parse_backlog, Grammar}; +use crate::suggest::{suggestions, HintContext}; +use crate::view::{ + render_detail, render_help, render_list, render_output, render_scalar, show_full_text_hint, + to_row, DEFAULT_TRUNCATION_HINT, +}; +use tasks_axi_gen::cli::{ + Globals, HintWhen, ListArgs, ReadyArgs, ShowArgs, LIST_HINTS, LIST_OUTPUTS, READY_HINTS, + READY_OUTPUTS, SHOW_HINTS, SHOW_OUTPUTS, +}; +use tasks_axi_gen::dispatch::Handlers; +use tasks_axi_gen::enums::{ListState, TaskState}; +use tasks_axi_gen::errors::{AxiError, ErrorCode}; +use tasks_axi_gen::model::Task; +use tasks_axi_gen::rows::TaskRow; + +/// The backend the Node tool ships; the only one this port reads. +const SUPPORTED_BACKEND: &str = "markdown"; + +pub struct App { + env: Env, + globals: Globals, + config: Option<Config>, +} + +impl App { + pub fn new(env: Env) -> App { + App { + env, + globals: Globals::default(), + config: None, + } + } + + /// The backlog's tasks, refusing one that holds an unimplemented task kind. + fn load(&self) -> Result<Vec<Task>, AxiError> { + let config = self.config.as_ref().ok_or_else(|| { + AxiError::new( + "backlog context was not resolved", + ErrorCode::Unknown, + vec![], + ) + })?; + let src = read_file_safe(&config.path)?.unwrap_or_default(); + let backlog = parse_backlog(&Grammar::new(), &src); + if backlog.has_public_followup { + return Err(AxiError::new( + "This backlog holds public-followup tasks, which tasks-axi-rs does not read", + ErrorCode::Unsupported, + vec!["Run the same command with the Node tasks-axi".to_string()], + )); + } + Ok(backlog.tasks) + } + + /// Suggestions only carry the globals when one was passed. + fn suggestion_globals(&self) -> Option<&Globals> { + (self.globals.backend.is_some() || self.globals.file.is_some()).then_some(&self.globals) + } +} + +impl Handlers for App { + fn resolve_context(&mut self, globals: &Globals) -> Result<(), AxiError> { + self.globals = globals.clone(); + let config = resolve_config(globals, &self.env)?; + if config.backend != SUPPORTED_BACKEND { + return Err(AxiError::new( + format!( + "Unsupported backend \"{}\" \u{2014} P1 ships the markdown backend only", + config.backend + ), + ErrorCode::Unsupported, + vec!["Set `backend = \"markdown\"` in .tasks.toml, or omit --backend".to_string()], + )); + } + check_archives(&config)?; + self.config = Some(config); + Ok(()) + } + + fn show(&mut self, args: ShowArgs) -> Result<String, AxiError> { + let all = self.load()?; + let Some(task) = all.iter().find(|t| t.id == args.id) else { + let lines = vec!["Run `tasks-axi list` to see existing tasks".to_string()]; + return Err(AxiError::new( + format!("Task \"{}\" not found in this backlog", args.id), + ErrorCode::NotFound, + crate::suggest::with_globals(lines, self.suggestion_globals()), + )); + }; + let is_blocked = blocked_ids(&all).contains(&args.id); + let row = to_row(task, &all, args.full, DEFAULT_TRUNCATION_HINT, &local_date); + let mut blocks = vec![render_detail(&SHOW_OUTPUTS[0], &row)]; + let active: &[HintWhen] = if is_blocked { + &[HintWhen::Blocked] + } else { + &[] + }; + let help = suggestions( + SHOW_HINTS, + &HintContext { + active, + id: Some(&args.id), + filters: &[], + globals: self.suggestion_globals(), + }, + ); + if !help.is_empty() { + blocks.push(render_help(&help)); + } + Ok(render_output(blocks)) + } + + fn list(&mut self, args: ListArgs) -> Result<String, AxiError> { + let all = self.load()?; + let blocked = blocked_ids(&all); + let held: Vec<&str> = held_tasks(&all, &local_date) + .iter() + .map(|t| t.id.as_str()) + .collect(); + let mut matched: Vec<&Task> = all.iter().collect(); + match args.state { + Some(ListState::Held) => matched.retain(|t| held.contains(&t.id.as_str())), + Some(state) => matched.retain(|t| t.state.as_str() == state.as_str()), + None => {} + } + if let Some(repo) = &args.repo { + matched.retain(|t| t.repo.as_deref() == Some(repo.as_str())); + } + if let Some(kind) = &args.kind { + matched.retain(|t| t.kind.as_deref().unwrap_or("task") == kind); + } + if args.blocked { + matched.retain(|t| blocked.contains(&t.id)); + } + let total = matched.len(); + let items: Vec<&Task> = match args.limit { + Some(limit) => matched.iter().take(limit as usize).copied().collect(), + None => matched, + }; + let is_empty = total == 0; + let count_line = if total != items.len() { + format!("count: {} of {total} total", items.len()) + } else { + format!("count: {}", items.len()) + }; + + let mut blocks = vec![count_line]; + if is_empty { + blocks.push(render_scalar("tasks", &empty_state(&args))); + } else { + let rows: Vec<TaskRow> = items + .iter() + .map(|t| to_row(t, &all, false, &show_full_text_hint(t), &local_date)) + .collect(); + blocks.push(render_list(&LIST_OUTPUTS[0], &rows, &args.fields)); + } + let mut filters: Vec<(&'static str, &str)> = Vec::new(); + if let Some(s) = args.state { + filters.push(("state", s.as_str())); + } + if let Some(r) = &args.repo { + filters.push(("repo", r)); + } + if let Some(k) = &args.kind { + filters.push(("kind", k)); + } + blocks.push(render_help(&suggestions( + LIST_HINTS, + &HintContext { + active: if is_empty { + &[HintWhen::Empty] + } else { + &[HintWhen::NonEmpty] + }, + id: None, + filters: &filters, + globals: self.suggestion_globals(), + }, + ))); + Ok(render_output(blocks)) + } + + fn ready(&mut self, args: ReadyArgs) -> Result<String, AxiError> { + let all = self.load()?; + let blocked = blocked_ids(&all); + let mut items = ready_tasks(&all, false, &local_date); + let mut held: Vec<&Task> = held_tasks(&all, &local_date) + .into_iter() + .filter(|t| { + t.state == TaskState::Queued + && t.kind.as_deref() != Some("public-followup") + && !blocked.contains(&t.id) + }) + .collect(); + if let Some(repo) = &args.repo { + items.retain(|t| t.repo.as_deref() == Some(repo.as_str())); + held.retain(|t| t.repo.as_deref() == Some(repo.as_str())); + } + let is_empty = items.is_empty(); + let rows_of = |tasks: &[&Task]| -> Vec<TaskRow> { + tasks + .iter() + .map(|t| to_row(t, &all, false, &show_full_text_hint(t), &local_date)) + .collect() + }; + + let mut blocks = vec![format!("count: {}", items.len())]; + if is_empty { + blocks.push("ready: 0 unblocked queued tasks".to_string()); + } else { + blocks.push(render_list(&READY_OUTPUTS[0], &rows_of(&items), &[])); + } + // Public-followup tasks make the backlog unreadable here (see `load`), so this group is + // always the empty one. + blocks.push("ready_public_followups: 0 delivery-ready obligations".to_string()); + if args.include_held && !held.is_empty() { + blocks.push(render_list(&READY_OUTPUTS[2], &rows_of(&held), &[])); + } + let mut filters: Vec<(&'static str, &str)> = Vec::new(); + if let Some(r) = &args.repo { + filters.push(("repo", r)); + } + blocks.push(render_help(&suggestions( + READY_HINTS, + &HintContext { + active: if is_empty { + &[HintWhen::Empty] + } else { + &[HintWhen::NonEmpty] + }, + id: None, + filters: &filters, + globals: self.suggestion_globals(), + }, + ))); + Ok(render_output(blocks)) + } +} + +/// `0 <qualifiers> tasks in this backlog`. +fn empty_state(args: &ListArgs) -> String { + let qualifiers: Vec<String> = [ + args.blocked.then(|| "blocked".to_string()), + args.state.map(|s| s.as_str().to_string()), + args.kind.as_ref().map(|k| format!("kind={k}")), + args.repo.as_ref().map(|r| format!("repo={r}")), + ] + .into_iter() + .flatten() + .collect(); + let scope = if qualifiers.is_empty() { + String::new() + } else { + format!("{} ", qualifiers.join(" ")) + }; + format!("0 {scope}tasks in this backlog") +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/src/config.rs b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/config.rs new file mode 100644 index 0000000000..0ea55b18f7 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/config.rs @@ -0,0 +1,380 @@ +//! Backend and path resolution: `--file` / `--backend`, the environment, `.tasks.toml` in the +//! working directory and `~/.tasks-axi/config.toml`, in the Node tool's precedence order. + +use crate::jsutil::js_trim; +use jsre::Regex; +use std::io::ErrorKind; +use std::path::Path; +use tasks_axi_gen::cli::Globals; +use tasks_axi_gen::errors::{AxiError, ErrorCode}; + +const DEFAULT_KEEP: f64 = 10.0; +const PATH_CANDIDATES: [&str; 2] = ["backlog.md", "data/backlog.md"]; + +/// What the process environment contributes. +pub struct Env { + pub cwd: String, + pub home: Option<String>, + pub file: Option<String>, + pub backend: Option<String>, +} + +impl Env { + pub fn from_process() -> Env { + let cwd = std::env::current_dir() + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|_| "/".to_string()); + Env { + cwd, + home: std::env::var_os("HOME").map(|h| h.to_string_lossy().into_owned()), + file: std::env::var_os("TASKS_AXI_FILE").map(|v| v.to_string_lossy().into_owned()), + backend: std::env::var_os("TASKS_AXI_BACKEND") + .map(|v| v.to_string_lossy().into_owned()), + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Config { + pub backend: String, + pub path: String, + pub archive_path: Option<String>, +} + +#[derive(Default)] +struct Toml { + backend: Option<String>, + path: Option<String>, + archive: Option<String>, + done_keep: Option<f64>, +} + +fn validation(message: &str, suggestions: &[&str]) -> AxiError { + AxiError::validation(message, suggestions.iter().map(|s| s.to_string()).collect()) +} + +fn chars(s: &str) -> Vec<char> { + s.chars().collect() +} + +fn strip_toml_comment(raw: &str) -> &str { + let mut quote: Option<char> = None; + for (i, ch) in raw.char_indices() { + if let Some(q) = quote { + if ch == q { + quote = None; + } + continue; + } + if ch == '"' || ch == '\'' { + quote = Some(ch); + continue; + } + if ch == '#' { + return &raw[..i]; + } + } + raw +} + +#[derive(Clone, Copy, PartialEq)] +enum Table { + Root, + Markdown, + Unsupported, +} + +enum Value { + Text(String), + Number(f64), +} + +fn parse_value(raw: &str, source: &str, int_re: &Regex) -> Result<Value, AxiError> { + let trimmed = js_trim(raw); + if trimmed.starts_with('"') || trimmed.starts_with('\'') { + let quote = trimmed.chars().next().unwrap_or('"'); + // `trimmed.length === 1` counts UTF-16 units; a lone quote is one. + if !trimmed.ends_with(quote) || trimmed.chars().count() == 1 { + return Err(AxiError::validation( + format!("{source} has an unterminated quoted value"), + vec![], + )); + } + let inner = &trimmed[quote.len_utf8()..trimmed.len() - quote.len_utf8()]; + return Ok(Value::Text(inner.to_string())); + } + if int_re.find_at(&chars(trimmed), 0).is_some() { + return Ok(Value::Number( + trimmed.parse::<f64>().unwrap_or(f64::INFINITY), + )); + } + Err(AxiError::validation( + format!("{source} has an invalid value"), + vec![], + )) +} + +fn require_string(value: Value, source: &str) -> Result<String, AxiError> { + match value { + Value::Text(s) => Ok(s), + Value::Number(_) => Err(AxiError::validation( + format!("{source} must be a quoted string"), + vec![], + )), + } +} + +/// The tiny TOML subset the config needs: a root `backend` and a `[markdown]` table. +fn parse_config_toml(src: &str) -> Result<Toml, AxiError> { + let section_re = Regex::new(r"^\[([^\]]+)\]$").map_err(internal)?; + let kv_re = Regex::new(r"^([A-Za-z0-9_]+)\s*=\s*(.*)$").map_err(internal)?; + let int_re = Regex::new(r"^-?\d+$").map_err(internal)?; + let mut config = Toml::default(); + let mut table = Table::Root; + for raw_line in src.split('\n') { + let line = js_trim(strip_toml_comment(raw_line)); + if line.is_empty() { + continue; + } + let line_chars = chars(line); + if let Some(g) = section_re.captures_str(&line_chars, 0) { + let name = g[1].as_deref().unwrap_or(""); + table = if js_trim(name) == "markdown" { + Table::Markdown + } else { + Table::Unsupported + }; + continue; + } + if table == Table::Unsupported { + continue; + } + let Some(kv) = kv_re.captures_str(&line_chars, 0) else { + return Err(validation( + "Invalid config line: expected `key = value`", + &["Use `key = value` assignments in .tasks.toml"], + )); + }; + let key = kv[1].as_deref().unwrap_or(""); + let value_raw = kv[2].as_deref().unwrap_or(""); + let source = match (table, key) { + (Table::Root, "backend") => "backend".to_string(), + (Table::Markdown, "path" | "archive" | "done_keep") => format!("markdown.{key}"), + _ => continue, + }; + let value = parse_value(value_raw, &source, &int_re)?; + if table == Table::Root { + config.backend = Some(require_string(value, &source)?); + continue; + } + match key { + "path" => config.path = Some(require_string(value, &source)?), + "archive" => config.archive = Some(require_string(value, &source)?), + _ => match value { + Value::Number(n) => config.done_keep = Some(n), + Value::Text(_) => { + return Err(validation( + "markdown.done_keep must be an integer", + &["Set `[markdown] done_keep = 10` in .tasks.toml"], + )) + } + }, + } + } + Ok(config) +} + +fn internal(e: String) -> AxiError { + AxiError::new(e, ErrorCode::Unknown, vec![]) +} + +/// A file's text, `None` when it does not exist; other failures surface as `UNKNOWN`, the way an +/// unhandled Node error would. +pub fn read_file_safe(path: &str) -> Result<Option<String>, AxiError> { + match std::fs::read(path) { + Ok(bytes) => Ok(Some(String::from_utf8_lossy(&bytes).into_owned())), + Err(e) if e.kind() == ErrorKind::NotFound => Ok(None), + Err(e) => Err(AxiError::new( + io_message(&e, path), + ErrorCode::Unknown, + vec![], + )), + } +} + +/// Node's `errno` message shapes for the failures a backlog read can hit. +fn io_message(e: &std::io::Error, path: &str) -> String { + match e.raw_os_error() { + Some(21) => "EISDIR: illegal operation on a directory, read".to_string(), + Some(13) => format!("EACCES: permission denied, open '{path}'"), + _ => e.to_string(), + } +} + +fn load_toml(path: &str) -> Result<Toml, AxiError> { + match read_file_safe(path)? { + Some(src) if !src.is_empty() => parse_config_toml(&src), + _ => Ok(Toml::default()), + } +} + +/// `path.resolve(cwd, p)` for a POSIX path. +pub fn resolve(cwd: &str, p: &str) -> String { + let joined = if p.starts_with('/') { + p.to_string() + } else { + format!("{cwd}/{p}") + }; + let mut parts: Vec<&str> = Vec::new(); + for seg in joined.split('/') { + match seg { + "" | "." => {} + ".." => { + parts.pop(); + } + s => parts.push(s), + } + } + format!("/{}", parts.join("/")) +} + +fn dirname(abs: &str) -> &str { + match abs.rfind('/') { + Some(0) | None => "/", + Some(i) => &abs[..i], + } +} + +fn validate_path_value(value: Option<String>, source: &str) -> Result<Option<String>, AxiError> { + match value { + Some(v) if js_trim(&v).is_empty() => Err(validation( + &format!("{source} must not be empty"), + &["Set it to a backlog path or remove the empty override"], + )), + other => Ok(other), + } +} + +fn is_safe_non_negative(n: f64) -> bool { + (0.0..=9_007_199_254_740_991.0).contains(&n) +} + +/// Resolve the backlog context. `globals` are the `--backend` / `--file` flags. +pub fn resolve_config(globals: &Globals, env: &Env) -> Result<Config, AxiError> { + let home_toml = match &env.home { + Some(home) => { + let p = if home.is_empty() { + ".tasks-axi/config.toml".to_string() + } else { + format!("{home}/.tasks-axi/config.toml") + }; + load_toml(&p)? + } + None => Toml::default(), + }; + let project_toml = load_toml(&resolve(&env.cwd, ".tasks.toml"))?; + + let explicit_path = match (&globals.file, &env.file) { + (Some(f), _) => validate_path_value(Some(f.clone()), "--file")?, + (None, Some(f)) => validate_path_value(Some(f.clone()), "TASKS_AXI_FILE")?, + (None, None) => None, + }; + let toml_path = if explicit_path.is_some() { + None + } else if project_toml.path.is_some() { + validate_path_value(project_toml.path.clone(), "markdown.path")? + } else { + validate_path_value(home_toml.path.clone(), "markdown.path")? + }; + + let backend = globals + .backend + .clone() + .or_else(|| env.backend.clone()) + .or_else(|| project_toml.backend.clone()) + .or_else(|| home_toml.backend.clone()) + .unwrap_or_else(|| "markdown".to_string()); + + let chosen = explicit_path.or(toml_path); + let path = match chosen { + Some(c) => resolve(&env.cwd, &c), + None => PATH_CANDIDATES + .iter() + .map(|c| resolve(&env.cwd, c)) + .find(|full| Path::new(full).exists()) + .unwrap_or_else(|| resolve(&env.cwd, PATH_CANDIDATES[0])), + }; + + let archive = if project_toml.archive.is_some() { + validate_path_value(project_toml.archive.clone(), "markdown.archive")? + } else { + validate_path_value(home_toml.archive.clone(), "markdown.archive")? + }; + + let keep = project_toml + .done_keep + .or(home_toml.done_keep) + .unwrap_or(DEFAULT_KEEP); + if !is_safe_non_negative(keep) { + return Err(validation( + "markdown.done_keep must be a non-negative integer", + &["Set `[markdown] done_keep = 10` in .tasks.toml"], + )); + } + + Ok(Config { + backend, + path, + archive_path: archive + .filter(|a| !a.is_empty()) + .map(|a| resolve(&env.cwd, &a)), + }) +} + +/// The store's constructor checks: neither archive may be the active backlog. +pub fn check_archives(config: &Config) -> Result<(), AxiError> { + let dir = dirname(&config.path); + let archive = config + .archive_path + .clone() + .unwrap_or_else(|| format!("{dir}/done-archive.md")); + if resolve("/", &archive) == resolve("/", &config.path) { + return Err(AxiError::validation( + "Archive path must not be the active backlog path", + vec![], + )); + } + if resolve("/", &format!("{dir}/note-archive.md")) == resolve("/", &config.path) { + return Err(AxiError::validation( + "Note archive path must not be the active backlog path", + vec![], + )); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn resolve_normalises_like_posix_path_resolve() { + assert_eq!(resolve("/a/b", "c"), "/a/b/c"); + assert_eq!(resolve("/a/b", "../c/./d/"), "/a/c/d"); + assert_eq!(resolve("/a/b", "/x//y"), "/x/y"); + assert_eq!(resolve("/a", "../../.."), "/"); + } + + #[test] + fn toml_reads_root_and_markdown_tables() { + let t = parse_config_toml("backend = \"markdown\" # c\n[markdown]\npath = 'x.md'\ndone_keep = 3\n[other]\nz = 1\n").unwrap(); + assert_eq!(t.backend.as_deref(), Some("markdown")); + assert_eq!(t.path.as_deref(), Some("x.md")); + assert_eq!(t.done_keep, Some(3.0)); + } + + #[test] + fn toml_rejects_a_line_that_is_not_an_assignment() { + assert!(parse_config_toml("nonsense").is_err()); + } +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/src/derive.rs b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/derive.rs new file mode 100644 index 0000000000..34962694d6 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/derive.rs @@ -0,0 +1,159 @@ +//! Derived projections: blocked, held and ready, computed from the whole task list. + +use std::collections::{HashMap, HashSet}; +use tasks_axi_gen::enums::{DepType, TaskState}; +use tasks_axi_gen::model::Task; + +/// The task a dependency id points at. As in the Node tool's `new Map(...)`, a later task with a +/// duplicated id wins. +fn by_id(tasks: &[Task]) -> HashMap<&str, &Task> { + tasks.iter().map(|t| (t.id.as_str(), t)).collect() +} + +/// Tasks that are not done and wait on a blocker that exists and is not done. A dangling +/// `blocked-by` edge counts as resolved. +pub fn blocked_ids(tasks: &[Task]) -> HashSet<String> { + let index = by_id(tasks); + let mut blocked = HashSet::new(); + for task in tasks { + if task.state == TaskState::Done { + continue; + } + let waits = task + .deps + .iter() + .filter(|d| d.r#type == DepType::BlockedBy) + .any(|d| { + index + .get(d.id.as_str()) + .is_some_and(|b| b.state != TaskState::Done) + }); + if waits { + blocked.insert(task.id.clone()); + } + } + blocked +} + +/// The unresolved `blocked-by` edges of `task`, in declaration order. +pub fn active_blockers(task: &Task, tasks: &[Task]) -> Vec<String> { + let index = by_id(tasks); + task.deps + .iter() + .filter(|d| d.r#type == DepType::BlockedBy) + .filter(|d| { + index + .get(d.id.as_str()) + .is_some_and(|b| b.state != TaskState::Done) + }) + .map(|d| d.id.clone()) + .collect() +} + +/// True when a structured hold is in force today (a `hold-until` date is a strict upper bound). +pub fn is_hold_active(task: &Task, today: &dyn Fn() -> String) -> bool { + let Some(hold) = &task.hold else { return false }; + match &hold.until { + None => task.state != TaskState::Done, + // ISO dates are ASCII, so byte order is the UTF-16 order JavaScript compares in. + Some(until) => task.state != TaskState::Done && until.as_str() > today().as_str(), + } +} + +pub fn held_tasks<'a>(tasks: &'a [Task], today: &dyn Fn() -> String) -> Vec<&'a Task> { + tasks.iter().filter(|t| is_hold_active(t, today)).collect() +} + +/// Unblocked, unheld queued work (held work too when `include_held`). +pub fn ready_tasks<'a>( + tasks: &'a [Task], + include_held: bool, + today: &dyn Fn() -> String, +) -> Vec<&'a Task> { + let blocked = blocked_ids(tasks); + tasks + .iter() + .filter(|t| { + t.state == TaskState::Queued + && t.kind.as_deref() != Some("public-followup") + && !blocked.contains(&t.id) + && (include_held || !is_hold_active(t, today)) + }) + .collect() +} + +/// The local calendar date as `YYYY-MM-DD`: what `new Date()`'s local getters give the Node tool. +#[cfg(unix)] +pub fn local_date() -> String { + #[repr(C)] + struct Tm { + tm_sec: i32, + tm_min: i32, + tm_hour: i32, + tm_mday: i32, + tm_mon: i32, + tm_year: i32, + tm_wday: i32, + tm_yday: i32, + tm_isdst: i32, + tm_gmtoff: i64, + tm_zone: *const u8, + } + extern "C" { + fn time(t: *mut i64) -> i64; + fn tzset(); + fn localtime_r(t: *const i64, out: *mut Tm) -> *mut Tm; + } + // SAFETY: `Tm` matches the C `struct tm` on 64-bit glibc, musl and the BSD/macOS libc (nine + // ints, then a long and a pointer); every pointer passed is to a live local. + unsafe { + let mut now: i64 = 0; + time(&mut now); + tzset(); + let mut tm: Tm = std::mem::zeroed(); + if !localtime_r(&now, &mut tm).is_null() { + return format!( + "{}-{:02}-{:02}", + tm.tm_year + 1900, + tm.tm_mon + 1, + tm.tm_mday + ); + } + civil_from_unix(now) + } +} + +#[cfg(not(unix))] +pub fn local_date() -> String { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_secs() as i64) + .unwrap_or(0); + civil_from_unix(now) +} + +/// The UTC date of a unix timestamp (days-from-civil inverse), the fallback with no local zone. +fn civil_from_unix(secs: i64) -> String { + let z = secs.div_euclid(86_400) + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!("{year}-{month:02}-{day:02}") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn civil_date_from_unix_seconds() { + assert_eq!(civil_from_unix(0), "1970-01-01"); + assert_eq!(civil_from_unix(951_782_400), "2000-02-29"); + assert_eq!(civil_from_unix(1_700_000_000), "2023-11-14"); + } +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/src/grammar.rs b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/grammar.rs new file mode 100644 index 0000000000..1b543c5ade --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/grammar.rs @@ -0,0 +1,431 @@ +//! The markdown backlog grammar: sections, task bullets, indented bodies and the trailing inline +//! tags. A port of the Node tool's `markdown-grammar`, with JavaScript regex behaviour supplied +//! by `jsre` (differentially tested against node) so the tag grammar is not re-derived. + +use crate::jsutil::{js_trim, semantic_line}; +use jsre::Regex; +use tasks_axi_gen::enums::{DepType, HoldKind, LinkKind, TaskState}; +use tasks_axi_gen::model::{Dep, Hold, Link, Task}; + +const ID: &str = r"[A-Za-z0-9][A-Za-z0-9._-]*"; +const DATE: &str = r"\d{4}-\d{2}-\d{2}"; +const DEP: &str = r"(?:blocked-by|parent|discovered-from)"; +const PUBLIC_FOLLOWUP_KIND: &str = "public-followup"; +const PUBLIC_FOLLOWUP_MARKER: &str = "tasks-axi:public-followup"; + +fn re(pattern: &str) -> Regex { + Regex::new(pattern).unwrap_or_else(|e| panic!("grammar pattern {pattern:?}: {e}")) +} + +/// Every pattern the grammar uses, compiled once per run. +pub struct Grammar { + in_flight: Regex, + queued: Regex, + done: Regex, + tail_dep: Regex, + tail_repo: Regex, + tail_kind: Regex, + tail_priority: Regex, + tail_since: Regex, + tail_closed: Regex, + tail_hold: Regex, + tail_hold_kind: Regex, + tail_hold_until: Regex, + report_link: Regex, + generic_url: Regex, + leading_kind: Vec<(Regex, &'static str)>, + trim_url: Regex, + section_header: Regex, + pr_url: Regex, +} + +impl Grammar { + pub fn new() -> Grammar { + let hold_kinds: Vec<&str> = HoldKind::ALL.iter().map(|k| k.as_str()).collect(); + let host = "[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?"; + let segment = "[A-Za-z0-9._-]+"; + Grammar { + in_flight: re(&format!(r"^- \*\*({ID})\*\* - (.*)$")), + queued: re(&format!(r"^- \[ \] ({ID}) - (.*)$")), + done: re(&format!(r"^- \[x\] ({ID}) - (.*)$")), + tail_dep: re(&format!( + r"\s*({DEP}):\s*({ID})(?:\s+-\s+((?:(?!\s+{DEP}:\s).)+?))?\s*$" + )), + tail_repo: re(r"\s*\((?:[^()]*\+\s*)?repo:\s*([^)]+)\)\s*$"), + tail_kind: re(r"\s*\(kind:\s*([^)]+)\)\s*$"), + tail_priority: re(r"\s*\(priority:\s*([0-4])\)\s*$"), + tail_since: re(&format!(r"\s*\(since\s+({DATE})\)\s*$")), + tail_closed: re(&format!( + r"\s*\((?:merged|reported|done|closed)\s+({DATE})\)\s*$" + )), + tail_hold: re(r"\s*\(hold:\s*([^()]+)\)\s*$"), + tail_hold_kind: re(&format!( + r"\s*\(hold-kind:\s*({})\)\s*$", + hold_kinds.join("|") + )), + tail_hold_until: re(&format!(r"\s*\(hold-until:\s*({DATE})\)\s*$")), + report_link: re(r"\bdata\/\S+?\/report\.md\b"), + generic_url: re(r"https?:\/\/\S+"), + leading_kind: vec![ + (re(r"^PERSISTENT SECONDMATE\b"), "secondmate"), + (re(r"^SHIP\b"), "ship"), + (re(r"^SCOUT\b"), "scout"), + (re(r"^DOCS-ONLY\b"), "docs"), + ], + trim_url: re(r"[).,;]+$"), + section_header: re(r"^##\s+(.*?)\s*$"), + pr_url: re(&format!( + r"^https://({host}(?:\.{host})*)/({segment})/({segment})/(pull|pulls)/([1-9][0-9]*)$" + )), + } + } + + fn leading_kind(&self, title: &[char]) -> Option<&'static str> { + self.leading_kind + .iter() + .find(|(r, _)| r.find_at(title, 0).is_some()) + .map(|(_, kind)| *kind) + } + + fn trim_url(&self, url: &str) -> String { + let chars: Vec<char> = url.chars().collect(); + match self.trim_url.find_at(&chars, 0) { + Some(m) => chars[..m.start].iter().collect(), + None => url.to_string(), + } + } + + /// True when `url` is byte-for-byte a canonical GitHub or Forgejo pull request URL. + fn is_pr_url(&self, url: &str) -> bool { + let chars: Vec<char> = url.chars().collect(); + let Some(g) = self.pr_url.captures_str(&chars, 0) else { + return false; + }; + let get = |i: usize| g[i].as_deref().unwrap_or(""); + let (host, owner, repo, route) = (get(1), get(2), get(3), get(4)); + if owner == "." || owner == ".." || repo == "." || repo == ".." { + return false; + } + if route == "pull" { + host == "github.com" + } else { + host != "github.com" + } + } + + /// Typed links derived from prose: pull requests, then reports, then other URLs. + fn derive_links(&self, text: &[char]) -> Vec<Link> { + let mut links: Vec<Link> = Vec::new(); + let mut seen: Vec<String> = Vec::new(); + let mut add = |this: &Grammar, kind: LinkKind, raw: &str| { + let url = this.trim_url(raw); + if seen.contains(&url) { + return; + } + seen.push(url.clone()); + links.push(Link { kind, url }); + }; + let slice = |s: usize, e: usize| -> String { text[s..e].iter().collect() }; + for m in self.generic_url.find_all(text) { + let raw = slice(m.start, m.end); + if self.is_pr_url(&self.trim_url(&raw)) { + add(self, LinkKind::Pr, &raw); + } + } + for m in self.report_link.find_all(text) { + add(self, LinkKind::Report, &slice(m.start, m.end)); + } + for m in self.generic_url.find_all(text) { + let raw = slice(m.start, m.end); + if !self.is_pr_url(&self.trim_url(&raw)) { + add(self, LinkKind::Doc, &raw); + } + } + links + } +} + +impl Default for Grammar { + fn default() -> Self { + Grammar::new() + } +} + +/// What `extractTags` found on a bullet's content. +struct Tags { + title: String, + kind: Option<String>, + repo: Option<String>, + deps: Vec<Dep>, + created: Option<String>, + closed: Option<String>, + priority: Option<i64>, + hold: Option<Hold>, + links: Vec<Link>, +} + +fn cap(groups: &[Option<String>], i: usize) -> Option<String> { + groups.get(i).cloned().flatten() +} + +/// Strip the trailing tag region off `rest`, one tag at a time, in the Node tool's order. +fn extract_tags(g: &Grammar, rest: &str) -> Tags { + let mut deps: Vec<Dep> = Vec::new(); + let (mut repo, mut kind_tag, mut created, mut closed, mut priority) = + (None, None, None, None, None); + let (mut hold_reason, mut hold_kind, mut hold_until): ( + Option<String>, + Option<String>, + Option<String>, + ) = (None, None, None); + let mut title: Vec<char> = rest.chars().collect(); + + loop { + // (regex, handler) in the order the Node tool tries them; the first that matches strips + // its tail and the scan restarts. + if let Some(m) = g.tail_dep.find_at(&title, 0) { + let caps = captures(&title, &m); + let dep_type = DepType::parse(caps[1].as_deref().unwrap_or("")); + if let Some(t) = dep_type { + deps.insert( + 0, + Dep { + r#type: t, + id: cap(&caps, 2).unwrap_or_default(), + reason: cap(&caps, 3), + }, + ); + } + title.truncate(m.start); + continue; + } + if let Some(m) = g.tail_repo.find_at(&title, 0) { + if repo.is_none() { + repo = cap(&captures(&title, &m), 1).map(|s| js_trim(&s).to_string()); + } + title.truncate(m.start); + continue; + } + if let Some(m) = g.tail_kind.find_at(&title, 0) { + if kind_tag.is_none() { + kind_tag = cap(&captures(&title, &m), 1).map(|s| js_trim(&s).to_string()); + } + title.truncate(m.start); + continue; + } + if let Some(m) = g.tail_priority.find_at(&title, 0) { + if priority.is_none() { + priority = cap(&captures(&title, &m), 1).and_then(|s| s.parse::<i64>().ok()); + } + title.truncate(m.start); + continue; + } + if let Some(m) = g.tail_since.find_at(&title, 0) { + if created.is_none() { + created = cap(&captures(&title, &m), 1); + } + title.truncate(m.start); + continue; + } + if let Some(m) = g.tail_closed.find_at(&title, 0) { + if closed.is_none() { + closed = cap(&captures(&title, &m), 1); + } + title.truncate(m.start); + continue; + } + if let Some(m) = g.tail_hold_until.find_at(&title, 0) { + if hold_until.is_none() { + hold_until = cap(&captures(&title, &m), 1); + } + title.truncate(m.start); + continue; + } + if let Some(m) = g.tail_hold_kind.find_at(&title, 0) { + if hold_kind.is_none() { + hold_kind = cap(&captures(&title, &m), 1); + } + title.truncate(m.start); + continue; + } + if let Some(m) = g.tail_hold.find_at(&title, 0) { + if hold_reason.is_none() { + hold_reason = cap(&captures(&title, &m), 1).map(|s| js_trim(&s).to_string()); + } + title.truncate(m.start); + continue; + } + break; + } + + let title_text: String = title.iter().collect(); + let title_trimmed = js_trim(&title_text).to_string(); + let trimmed_chars: Vec<char> = title_trimmed.chars().collect(); + // `kindTag ?? leadingKind(title)`: a present-but-empty tag wins and is then falsy. + let kind = kind_tag.or_else(|| g.leading_kind(&trimmed_chars).map(str::to_string)); + let links = g.derive_links(&trimmed_chars); + let hold = hold_reason.map(|reason| Hold { + reason, + kind: hold_kind.as_deref().and_then(HoldKind::parse), + until: hold_until, + }); + Tags { + title: title_trimmed, + kind, + repo, + deps, + created, + closed, + priority, + hold, + links, + } +} + +fn captures(hay: &[char], m: &jsre::Match) -> Vec<Option<String>> { + m.groups + .iter() + .map(|g| g.map(|(s, e)| hay[s..e].iter().collect())) + .collect() +} + +/// A parsed backlog: its tasks in document order, and whether it holds anything this port refuses. +pub struct Backlog { + pub tasks: Vec<Task>, + /// A `public-followup` task or its metadata marker is present (not implemented here). + pub has_public_followup: bool, +} + +fn section_state(g: &Grammar, header: &str) -> Option<TaskState> { + let chars: Vec<char> = semantic_line(header).chars().collect(); + let groups = g.section_header.captures_str(&chars, 0)?; + let text = groups.get(1).cloned().flatten()?.to_lowercase(); + if text == "in flight" { + Some(TaskState::InFlight) + } else if text == "queued" { + Some(TaskState::Queued) + } else if text.starts_with("done") { + Some(TaskState::Done) + } else { + None + } +} + +fn is_section_header(line: &str) -> bool { + match semantic_line(line).strip_prefix("##") { + Some(rest) => rest.chars().next().is_some_and(crate::jsutil::is_js_space), + None => false, + } +} + +fn match_bullet(g: &Grammar, line: &str, state: TaskState) -> Option<(String, String)> { + let chars: Vec<char> = semantic_line(line).chars().collect(); + let pick = |re: &Regex| -> Option<(String, String)> { + let c = re.captures_str(&chars, 0)?; + Some((cap(&c, 1)?, cap(&c, 2)?)) + }; + match state { + TaskState::Done => pick(&g.done), + TaskState::Queued => pick(&g.queued), + TaskState::InFlight => pick(&g.in_flight).or_else(|| pick(&g.queued)), + } +} + +/// `parseBacklog` followed by `allTasks`: every task bullet under a recognised section. +pub fn parse_backlog(g: &Grammar, src: &str) -> Backlog { + let mut backlog = Backlog { + tasks: Vec::new(), + has_public_followup: false, + }; + if src.is_empty() { + return backlog; + } + let body = src.strip_suffix('\n').unwrap_or(src); + let lines: Vec<&str> = body.split('\n').collect(); + + let mut state: Option<TaskState> = None; + let mut in_section = false; + let mut buffer: Vec<&str> = Vec::new(); + let close = |state: Option<TaskState>, buffer: &mut Vec<&str>, backlog: &mut Backlog| { + parse_entries(g, buffer, state, backlog); + buffer.clear(); + }; + for line in lines { + if is_section_header(line) { + if in_section { + close(state, &mut buffer, &mut backlog); + } + in_section = true; + state = section_state(g, line); + continue; + } + if in_section { + buffer.push(line); + } + } + if in_section { + close(state, &mut buffer, &mut backlog); + } + backlog +} + +fn parse_entries(g: &Grammar, lines: &[&str], state: Option<TaskState>, backlog: &mut Backlog) { + let Some(state) = state else { return }; + let mut i = 0; + while i < lines.len() { + let Some((id, rest)) = match_bullet(g, lines[i], state) else { + i += 1; + continue; + }; + let mut body_lines: Vec<String> = Vec::new(); + while i + 1 < lines.len() { + let next = semantic_line(lines[i + 1]); + if js_trim(next).is_empty() { + i += 1; + body_lines.push(String::new()); + continue; + } + if let Some(stripped) = next.strip_prefix(" ") { + i += 1; + body_lines.push(stripped.to_string()); + continue; + } + break; + } + i += 1; + let tags = extract_tags(g, &rest); + if body_lines + .iter() + .any(|l| l.contains(PUBLIC_FOLLOWUP_MARKER)) + || tags.kind.as_deref() == Some(PUBLIC_FOLLOWUP_KIND) + { + backlog.has_public_followup = true; + } + backlog.tasks.push(build_task(id, tags, state, body_lines)); + } +} + +fn build_task(id: String, tags: Tags, state: TaskState, mut body_lines: Vec<String>) -> Task { + while body_lines.last().is_some_and(String::is_empty) { + body_lines.pop(); + } + let body = if body_lines.is_empty() { + None + } else { + Some(body_lines.join("\n")) + }; + Task { + id, + title: tags.title, + state, + kind: tags.kind.filter(|k| !k.is_empty()), + repo: tags.repo.filter(|r| !r.is_empty()), + priority: tags.priority, + created: tags.created, + closed: tags.closed, + body, + hold: tags.hold, + deps: tags.deps, + links: tags.links, + } +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/src/jsutil.rs b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/jsutil.rs new file mode 100644 index 0000000000..2ba73b6b9f --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/jsutil.rs @@ -0,0 +1,51 @@ +//! JavaScript string semantics the markdown backlog grammar leans on. + +/// JavaScript's `\s` set (also what `String.prototype.trim` strips). +pub use tasks_axi_gen::cli::{is_js_space, js_trim}; + +/// `String.prototype.length`: the number of UTF-16 code units. +pub fn utf16_len(s: &str) -> usize { + s.chars().map(char::len_utf16).sum() +} + +/// `String.prototype.slice(0, n)` for text a JavaScript program then writes to stdout as UTF-8. +/// A cut that falls between the halves of a surrogate pair leaves a lone high surrogate, which +/// the UTF-8 encoder writes as U+FFFD. +pub fn slice_utf16(s: &str, n: usize) -> String { + let mut out = String::new(); + let mut units = 0; + for c in s.chars() { + let w = c.len_utf16(); + if units + w > n { + if units < n { + out.push('\u{FFFD}'); + } + break; + } + out.push(c); + units += w; + } + out +} + +/// `semanticLine`: a line without its one trailing carriage return. +pub fn semantic_line(line: &str) -> &str { + line.strip_suffix('\r').unwrap_or(line) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lengths_count_utf16_units() { + assert_eq!(utf16_len("a\u{1F600}b"), 4); + } + + #[test] + fn a_cut_inside_a_surrogate_pair_leaves_the_replacement_character() { + assert_eq!(slice_utf16("ab\u{1F600}c", 3), "ab\u{FFFD}"); + assert_eq!(slice_utf16("ab\u{1F600}c", 4), "ab\u{1F600}"); + assert_eq!(slice_utf16("abc", 10), "abc"); + } +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/src/main.rs b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/main.rs new file mode 100644 index 0000000000..1442d651eb --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/main.rs @@ -0,0 +1,29 @@ +//! tasks-axi-rs: the read path of tasks-axi (show, list, ready), parsed, dispatched and printed +//! by code generated from the MetaObjects model, over a hand-written markdown backlog reader. + +mod app; +mod config; +mod derive; +mod grammar; +mod jsutil; +mod suggest; +mod view; + +use std::io::Write; +use tasks_axi_gen::dispatch::{run, Outcome}; + +fn main() { + let argv: Vec<String> = std::env::args_os() + .skip(1) + .map(|a| a.to_string_lossy().into_owned()) + .collect(); + let mut app = app::App::new(config::Env::from_process()); + let (text, code) = match run(&argv, &mut app) { + Outcome::Output(s) => (format!("{s}\n"), 0), + Outcome::Verbatim(s) => (s, 0), + Outcome::Failure(e) => (format!("{}\n", view::render_error(&e)), e.exit_code()), + }; + // A closed pipe is not an error here, as in the Node tool. + let _ = std::io::stdout().write_all(text.as_bytes()); + std::process::exit(code); +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/src/suggest.rs b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/suggest.rs new file mode 100644 index 0000000000..a78d42cfb6 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/suggest.rs @@ -0,0 +1,128 @@ +//! Next-step suggestions: the model's hint templates, filtered and suffixed the way the Node tool +//! does it (a hint that cannot carry the active filters is dropped, never mis-stated). + +use tasks_axi_gen::cli::{Globals, Hint, HintWhen}; + +/// What a command knows when it asks for hints. +pub struct HintContext<'a> { + pub active: &'a [HintWhen], + pub id: Option<&'a str>, + /// The filter flags the invocation carried, in the order the Node tool lists them. + pub filters: &'a [(&'static str, &'a str)], + pub globals: Option<&'a Globals>, +} + +/// `shellQuoteOneLine`: a value safe to paste after `--flag=`, or None when it cannot be quoted. +fn shell_quote(value: &str) -> Option<String> { + if value.chars().any(|c| matches!(c, '\0' | '\r' | '\n' | '`')) { + return None; + } + let plain = !value.is_empty() + && value + .chars() + .all(|c| c.is_ascii_alphanumeric() || "_./:@%+=,-".contains(c)); + if plain { + Some(value.to_string()) + } else { + Some(format!("'{}'", value.replace('\'', "'\\''"))) + } +} + +/// Insert `suffix` just before the closing backtick of the line's `tasks-axi` command. +fn append_suffix(line: &str, suffix: &str) -> Option<String> { + let first = line.find('`')?; + let second = first + 1 + line[first + 1..].find('`')?; + let command = &line[first + 1..second]; + if command != "tasks-axi" && !command.starts_with("tasks-axi ") { + return None; + } + Some(format!("{}{}{}", &line[..second], suffix, &line[second..])) +} + +fn filter_suffix(filters: &[(&'static str, &str)], supported: &[&str]) -> Option<String> { + if filters.iter().any(|(flag, _)| !supported.contains(flag)) { + return None; + } + let mut parts: Vec<String> = Vec::new(); + for flag in supported { + if let Some((_, value)) = filters.iter().find(|(f, _)| f == flag) { + parts.push(format!("--{flag}={}", shell_quote(value)?)); + } + } + Some(if parts.is_empty() { + String::new() + } else { + format!(" {}", parts.join(" ")) + }) +} + +fn global_suffix(globals: Option<&Globals>) -> Option<String> { + let Some(g) = globals else { + return Some(String::new()); + }; + let mut parts: Vec<String> = Vec::new(); + if let Some(b) = &g.backend { + parts.push(format!("--backend={}", shell_quote(b)?)); + } + if let Some(f) = &g.file { + parts.push(format!("--file={}", shell_quote(f)?)); + } + Some(if parts.is_empty() { + String::new() + } else { + format!(" {}", parts.join(" ")) + }) +} + +/// `withSuggestionGlobals`: carry `--backend` / `--file` into every suggested command. +pub fn with_globals(lines: Vec<String>, globals: Option<&Globals>) -> Vec<String> { + match global_suffix(globals) { + None => Vec::new(), + Some(s) if s.is_empty() => lines, + Some(s) => lines.iter().filter_map(|l| append_suffix(l, &s)).collect(), + } +} + +/// The suggestion lines for a command's hints. +pub fn suggestions(hints: &[Hint], ctx: &HintContext) -> Vec<String> { + let lines: Vec<String> = hints + .iter() + .filter(|h| ctx.active.contains(&h.when)) + .filter_map(|h| { + let mut line = h.line.to_string(); + if let Some(id) = ctx.id { + line = line.replace("{id}", id); + } + if h.filters.is_empty() { + return Some(line); + } + match filter_suffix(ctx.filters, h.filters)? { + s if s.is_empty() => Some(line), + s => append_suffix(&line, &s), + } + }) + .collect(); + with_globals(lines, ctx.globals) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn quoting_matches_the_node_tool() { + assert_eq!(shell_quote("plain-1.2/x").as_deref(), Some("plain-1.2/x")); + assert_eq!(shell_quote("a b").as_deref(), Some("'a b'")); + assert_eq!(shell_quote("it's").as_deref(), Some("'it'\\''s'")); + assert_eq!(shell_quote("a`b"), None); + } + + #[test] + fn suffix_goes_inside_the_backticks() { + assert_eq!( + append_suffix("Run `tasks-axi ready` now", " --repo=x").as_deref(), + Some("Run `tasks-axi ready --repo=x` now") + ); + assert_eq!(append_suffix("Run `other` now", " --repo=x"), None); + } +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/src/view.rs b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/view.rs new file mode 100644 index 0000000000..8de93ccfe7 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/src/view.rs @@ -0,0 +1,201 @@ +//! Task to printed row, and rows to TOON. + +use crate::derive::{active_blockers, is_hold_active}; +use crate::jsutil::{slice_utf16, utf16_len}; +use tasks_axi_gen::cli::OutputSpec; +use tasks_axi_gen::errors::AxiError; +use tasks_axi_gen::model::Task; +use tasks_axi_gen::rows::{Cell, Column, TaskRow}; +use toon_encode::{Dialect, Options, Value}; + +/// The shipped `@toon-format/toon` 2.3.x quoting rules, which differ from the spec's. +fn toon_options() -> Options { + Options { + dialect: Dialect::ToonJs2, + ..Options::default() + } +} + +fn encode(value: &Value) -> String { + toon_encode::encode_with(value, &toon_options()) +} + +/// Shorten `text` to `limit` UTF-16 units and say how much was lost and how to get it back. +pub fn truncate(text: &str, limit: usize, hint: &str) -> String { + if text.is_empty() { + return String::new(); + } + let len = utf16_len(text); + if len <= limit { + return text.to_string(); + } + format!( + "{}\n... (truncated, {len} chars total - {hint})", + slice_utf16(text, limit) + ) +} + +/// The hint a list row's truncation carries. +pub fn show_full_text_hint(task: &Task) -> String { + format!("use show {} --full to see complete text", task.id) +} + +/// The hint `show` carries when it truncates a field. +pub const DEFAULT_TRUNCATION_HINT: &str = "use --full to see complete text"; + +/// `toRow`: the flat record carrying every derivable column. +pub fn to_row( + task: &Task, + all: &[Task], + full: bool, + hint: &str, + today: &dyn Fn() -> String, +) -> TaskRow { + let blockers = active_blockers(task, all); + let title_limit = Column::Title.truncate_limit().unwrap_or(usize::MAX); + let body_limit = Column::Body.truncate_limit().unwrap_or(usize::MAX); + let body = task.body.as_deref().unwrap_or(""); + TaskRow { + id: task.id.clone(), + title: if full { + task.title.clone() + } else { + truncate(&task.title, title_limit, hint) + }, + state: task.state, + blocked: !blockers.is_empty(), + blocked_by: blockers, + held: is_hold_active(task, today), + hold_reason: task.hold.as_ref().map(|h| h.reason.clone()), + hold_kind: task.hold.as_ref().and_then(|h| h.kind), + hold_until: task.hold.as_ref().and_then(|h| h.until.clone()), + kind: Some(task.kind.clone().unwrap_or_else(|| "task".to_string())), + repo: task.repo.clone(), + priority: task.priority, + created: task.created.clone(), + closed: task.closed.clone(), + delivery_state: None, + deps: task + .deps + .iter() + .map(|d| format!("{}:{}", d.r#type.as_str(), d.id)) + .collect(), + links: task + .links + .iter() + .map(|l| format!("{}:{}", l.kind.as_str(), l.url)) + .collect(), + body: Some(if full { + body.to_string() + } else { + truncate(body, body_limit, hint) + }), + } +} + +fn cell_value(cell: Cell) -> Value { + match cell { + Cell::Str(s) => Value::Str(s), + Cell::Int(n) => Value::Int(n), + } +} + +fn row_value(row: &TaskRow, columns: &[Column]) -> Value { + Value::Object( + columns + .iter() + .map(|c| (c.name().to_string(), cell_value(row.cell(*c)))) + .collect(), + ) +} + +/// `renderList`: a labeled array of rows. The columns are the spec's, then any `extra`. +pub fn render_list(spec: &OutputSpec, rows: &[TaskRow], extra: &[Column]) -> String { + let mut columns: Vec<Column> = spec.columns.to_vec(); + columns.extend_from_slice(extra); + encode(&Value::Object(vec![( + spec.label.to_string(), + Value::Array(rows.iter().map(|r| row_value(r, &columns)).collect()), + )])) +} + +/// `renderDetail`: one labeled record. +pub fn render_detail(spec: &OutputSpec, row: &TaskRow) -> String { + encode(&Value::Object(vec![( + spec.label.to_string(), + row_value(row, spec.columns), + )])) +} + +/// `renderScalar`: `label: text`. +pub fn render_scalar(label: &str, text: &str) -> String { + encode(&Value::Object(vec![( + label.to_string(), + Value::Str(text.to_string()), + )])) +} + +/// `renderHelp`: suggestions as a one-item-per-line array, or nothing. +pub fn render_help(lines: &[String]) -> String { + if lines.is_empty() { + return String::new(); + } + let items: Vec<String> = lines + .iter() + .map(|l| { + format!( + " - {}", + toon_encode::encode_scalar_with(&Value::Str(l.clone()), &toon_options()) + ) + }) + .collect(); + format!("help[{}]:\n{}", lines.len(), items.join("\n")) +} + +/// `renderOutput`: the non-empty blocks, one per line group. +pub fn render_output(blocks: Vec<String>) -> String { + blocks + .into_iter() + .filter(|b| !b.is_empty()) + .collect::<Vec<_>>() + .join("\n") +} + +/// The error block: `error`, `code` and, when there are suggestions, `help`. +pub fn render_error(e: &AxiError) -> String { + let mut fields = vec![ + ("error".to_string(), Value::Str(e.message.clone())), + ("code".to_string(), Value::Str(e.code.as_str().to_string())), + ]; + if !e.suggestions.is_empty() { + fields.push(( + "help".to_string(), + Value::Array( + e.suggestions + .iter() + .map(|s| Value::Str(s.clone())) + .collect(), + ), + )); + } + encode(&Value::Object(fields)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn truncation_names_the_size_and_the_escape_hatch() { + let text = "x".repeat(90); + assert_eq!( + truncate(&text, 80, "use --full"), + format!( + "{}\n... (truncated, 90 chars total - use --full)", + "x".repeat(80) + ) + ); + assert_eq!(truncate("short", 80, "h"), "short"); + assert_eq!(truncate("", 80, "h"), ""); + } +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden.rs b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden.rs new file mode 100644 index 0000000000..efc173c284 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden.rs @@ -0,0 +1,139 @@ +//! Golden outputs recorded from the real tasks-axi 0.2.6 (see `harness/golden.ts`): run +//! `tasks-axi-rs` over each recorded invocation and require the same stdout bytes, the same exit +//! code and an empty stderr. Needs no node. + +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::Command; + +#[derive(Default)] +struct Case { + name: String, + args: Vec<String>, + env: Vec<(String, String)>, + files: Vec<(String, String)>, + home: Vec<(String, String)>, + code: i32, + stdout: String, +} + +fn unescape(s: &str) -> String { + let mut out = String::new(); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('n') => out.push('\n'), + Some('r') => out.push('\r'), + Some('t') => out.push('\t'), + Some(other) => out.push(other), + None => out.push('\\'), + } + } + out +} + +fn parse(text: &str) -> Vec<Case> { + let mut cases = Vec::new(); + let mut cur: Option<Case> = None; + for line in text.split('\n') { + if line.is_empty() { + if let Some(c) = cur.take() { + cases.push(c); + } + continue; + } + let mut parts = line.splitn(3, '\t'); + let key = parts.next().unwrap_or(""); + let a = parts.next().unwrap_or(""); + let b = parts.next().unwrap_or(""); + if key == "case" { + cur = Some(Case { + name: a.to_string(), + ..Case::default() + }); + continue; + } + let c = cur.as_mut().expect("a record starts with `case`"); + match key { + "arg" => c.args.push(unescape(a)), + "env" => c.env.push((a.to_string(), unescape(b))), + "file" => c.files.push((unescape(a), b.to_string())), + "home" => c.home.push((unescape(a), b.to_string())), + "code" => c.code = a.parse().expect("exit code"), + "stdout" => c.stdout = unescape(a), + other => panic!("unknown golden key {other}"), + } + } + cases +} + +fn write_tree(root: &Path, files: &[(String, String)], fixtures: &Path) { + for (rel, fixture) in files { + let dest = root.join(rel); + fs::create_dir_all(dest.parent().expect("parent")).expect("mkdir"); + fs::copy(fixtures.join(fixture), dest).expect("copy fixture"); + } +} + +fn scratch() -> PathBuf { + let base = std::env::var_os("DEV_SCRATCH") + .filter(|v| !v.is_empty()) + .map(PathBuf::from) + .unwrap_or_else(std::env::temp_dir); + let dir = base.join(format!("tasks-axi-rs-golden-{}", std::process::id())); + fs::create_dir_all(&dir).expect("scratch"); + dir +} + +#[test] +fn matches_the_recorded_outputs() { + let golden = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/golden"); + let fixtures = golden.join("fixtures"); + let cases = parse(&fs::read_to_string(golden.join("golden.txt")).expect("golden.txt")); + assert!(cases.len() > 100, "only {} golden cases", cases.len()); + + let root = scratch(); + let mut failures: Vec<String> = Vec::new(); + for (i, case) in cases.iter().enumerate() { + let dir = root.join(format!("c{i}")); + let (cwd, home) = (dir.join("cwd"), dir.join("home")); + fs::create_dir_all(&cwd).expect("cwd"); + fs::create_dir_all(&home).expect("home"); + write_tree(&cwd, &case.files, &fixtures); + write_tree(&home, &case.home, &fixtures); + let out = Command::new(env!("CARGO_BIN_EXE_tasks-axi-rs")) + .args(&case.args) + .current_dir(&cwd) + .env_clear() + .env("HOME", &home) + .env("TZ", "UTC") + .envs(case.env.iter().map(|(k, v)| (k, v))) + .output() + .expect("run tasks-axi-rs"); + let stdout = String::from_utf8_lossy(&out.stdout).into_owned(); + if stdout != case.stdout || out.status.code() != Some(case.code) || !out.stderr.is_empty() { + failures.push(format!( + "{}: args {:?}\n code want {} got {:?}\n want {:?}\n got {:?}\n stderr {:?}", + case.name, + case.args, + case.code, + out.status.code(), + case.stdout, + stdout, + String::from_utf8_lossy(&out.stderr) + )); + } + } + let _ = fs::remove_dir_all(&root); + assert!( + failures.is_empty(), + "{} of {} cases differ:\n{}", + failures.len(), + cases.len(), + failures.join("\n") + ); +} diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/01a7cf944466c2ac.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/01a7cf944466c2ac.bin new file mode 100644 index 0000000000..223af01aa6 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/01a7cf944466c2ac.bin @@ -0,0 +1,2 @@ +[markdown] +path = "" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/01ba4719c80b6fe9.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/01ba4719c80b6fe9.bin new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/01ba4719c80b6fe9.bin @@ -0,0 +1 @@ + diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/167396b16774aa5b.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/167396b16774aa5b.bin new file mode 100644 index 0000000000..fec3b30a93 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/167396b16774aa5b.bin @@ -0,0 +1,2 @@ +[markdown] +done_keep = -2 diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/1dcb09d9adbd2ecc.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/1dcb09d9adbd2ecc.bin new file mode 100644 index 0000000000..a9a88f8bd4 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/1dcb09d9adbd2ecc.bin @@ -0,0 +1,2 @@ +[markdown] +path = "docs/t.md" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/2f9d23efc1830169.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/2f9d23efc1830169.bin new file mode 100644 index 0000000000..a14d5231fb --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/2f9d23efc1830169.bin @@ -0,0 +1 @@ +nonsense diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/315863d2ed6d735e.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/315863d2ed6d735e.bin new file mode 100644 index 0000000000..587a74047e --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/315863d2ed6d735e.bin @@ -0,0 +1,2 @@ +[markdown] +path = "docs/t.md" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/3cae5bba6005a270.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/3cae5bba6005a270.bin new file mode 100644 index 0000000000..f2bd579b8c --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/3cae5bba6005a270.bin @@ -0,0 +1,5 @@ +# Backlog + +## Queued + +- [ ] one-a1 - The one task (repo: r1) diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/4d0a2052951fe95d.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/4d0a2052951fe95d.bin new file mode 100644 index 0000000000..d9094b50d2 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/4d0a2052951fe95d.bin @@ -0,0 +1,79 @@ +# Backlog + +## In flight + +- [ ] beta-9h - comma,s café a#b -dash backoff comma,s retry quote"s 日本語 [bracket] 日本語 adopt -dash backoff 42 100% flaky colon: here index router colon: here adopt adopt café -da (hold: {brace} flaky) (hold-kind: load) (hold-until: 2500-01-01) +- [ ] x_y-od - SHIP -dash schema 日本語 retry cleanup (since 2026-10-02) (kind: chore) (hold: résumé spaced spaced ) (hold-until: 3000-06-15) + +- [ ] a.b-98 - flaky true lease quote"s service retry spaced naïve parser adopt index tab here (hold: ß colon: here backoff) (hold-until: 3000-06-15) (since 2026-09-30) + + a,b + spaced rewrite service parser cache -dash 100% {brace} metrics widget schema migrate cache cache flaky queue adopt 日本語 cleanup metrics 3.14 true true retry backoff audit gateway 100% adopt gateway router spaced backoff Ünïcode index ß [bracket] lease spaced backoff rewrite adopt café quote"s -dash 日本語 Ünïcode -dash résumé -dash -dash Ω audit ß 3.14 naïve gateway index Ünïcode gateway Ω -dash parser a#b tab here backoff queue null colon: here test true flaky [bracket] test schema 10😀 + 100% test quote"s 42 -dash {brace} metrics gateway widget gateway quote"s résumé 3.14 migrate colon: here migrate -dash queue cleanup résumé {brace} 100% rewrite {brace} queue true {brace} comma,s colon: here flaky widget queue ß 日本語 日本語 Ω widget true comma,s Ω {brace} 42 spaced spaced {brace} lease test 日本語 service ß ß {brace}  migrate Ünïcode 日本語 index rewrite router  backoff metrics ß naïve index rewrite metrics lease backoff service backoff router 100% flaky colon: here cleanupx + tab here a#b a#b a#b 100% test 3.14 audit router router audit 100% +- **sm-idle-es.3** - null naïve rewrite 100% gateway café cleanup (repo: infra) (since 2024-02-29) blocked-by: a.b-98 - tab here 100% + +## Notes + +- [ ] gamma-nm - index lease rewrite adopt flaky a#b rewrite résumé parser 100% parser rewrite {brace} router backoff -dash {brace} a#b backoff quote"s 100% parser migrate 3.14 résumé {brace} comma,s metrics quote"s test retry migrate true ß widge (repo: x:y) (hold-kind: parked) (since 2025-01-01) +## Queued + +- [ ] gamma-1f - résumé test tab here café flaky 日本語 comma,s null lease parser  test flaky 日本語 +## Done (retained) + +- [x] beta-kr - colon: here (since 2024-02-29) + audit a#b naïve + null cache {brace} service naïve gateway widget parser backoff cache retry comma,s backoff schema flaky [bracket] parser 3.14 backoff  naïve colon: here null quote"s [bracket] audit 42 colon: here résumé Ω a#b widget colon: here résumé colon: here adopt flaky router comma,s tab here cache quote"s café flaky metrics lease spaced audit schema 100% parser flaky index Ünïcode audit test 100% cache comma,s spaced backoff {brace} 42 index metrics 100% 100% 42 metrics 3.14 audit parser Ün😀ode nu + quote"s schema naïve comma,s quote"s widget ß quote"s + 05 + + +- [x] Z-0j - true ß gateway ß migrate ß Ünïcode a#b (priority: 9) (reported 2026-09-30) + extra-indented tab here + 100% index colon: here test backoff adopt  + + index test widget true audit spaced + retry naïve index cache 42 metrics backoff gateway naïve parser true colon: here audit  Ω retry a#b tab here 日本語 adopt 100% café test backoff ß Ω tab here cleanup gateway widget -dash 3.14  spaced rewrite {brace}  router 日本語 日本語 Ω résumé metrics flaky migrate adopt cleanup [bracket] spaced tab here rewrite colon: here  true retry queue lease metrics  cache 3.14 migrate gateway test retry metrics queue null  metrics retry Ω tab here [bracket] spaced router g + + +- [x] Homemux-ea - SCOUTS cleanup metrics {brace} widget (merged 2026-10-02) + Ω quote"s null queue Ω audit tab here ß spaced comma,s 3.14 100% + ## Intent + extra-indented a#b + + + +## Queued + +- [ ] fm-x-gl - audit spaced spaced migrate null flaky quote"s naïve (since 2026-10-01) +  ß Ω audit tab here tab here queue + ## Intent + + + +- [ ] gamma-5g - lease ß [bracket] parser naïve résumé retry service widget index Ünïcode retry test parser parser retry cache audit résumé  a#b [bracket] cleanup schema cac (repo: a/b) (priority: 3) + +- [ ] alpha-b4 - café backoff https://github.com/o/r/pull/42 (priority: 2) (hold: queue cache) +- [ ] Z-ju - retry blocked-by: x_y-od blocked-by: Z-0j (since 2026-09-30) + {x} +  gateway index Ünïcode true tab here audit index spaced 日本語 résumé 42 metrics comma,s [bracket] colon: here metrics cleanup metrics parser Ünïcode retry 日本語  Ünïcode cache colon: here test tab here null comma,s résumé colon: here null retry 42 Ünïcode retry Ünïcode {brace} true cleanup test cache index 42 backoff résumé 42 index café -dash [bracket] 日本語 metrics 3.14 42 cache lease 42 quote"s comma,s migrate 100% spaced [bracket] 42 日本語 a#b colon: here ß widget queue 42 adopt 42😀a + ## Intent + + extra-indented index + +- [ ] sm-idle-b3 - [bracket] gateway service café widget backoff  cache queue null cleanup test Ω service résumé retry colon: here tab here Ω index cleanup flaky audit naïve router queue flaky a#b 日本語 gateway schema quote"s {brace} café true migrate parser 100% 日本語 nullx (since 2026-10-01) (repo: 7) (hold: index queue colon: here) + gateway a#b 42 日本語 a#b widget widget + + +- [ ] beta-9h - DOCS-ONLY résumé retry audit + 1. + extra-indented résumé + a#b 3.14 100% quote"s null index ß audit + metrics comma,s true rewrite  {brace} colon: here + 1e5 +- [ ] a.b-fx - index cache (hold-kind: captain) (repo: é-repo) (hold-until: 2001-06-15) (hold: null) (since 2025-01-01) + retry a#b naïve quote"s router audit 42 café + + + + diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/50b7dde7c190b2c1.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/50b7dde7c190b2c1.bin new file mode 100644 index 0000000000..1b388a609a --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/50b7dde7c190b2c1.bin @@ -0,0 +1,2 @@ +[markdown] +path = "h.md" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/52afa28aa0823dd2.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/52afa28aa0823dd2.bin new file mode 100644 index 0000000000..dc7f10fad1 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/52afa28aa0823dd2.bin @@ -0,0 +1,5 @@ +# Backlog + +## Queued + +- [ ] one-a1 - The one task (repo: r1) diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/54a20e07cafd1319.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/54a20e07cafd1319.bin new file mode 100644 index 0000000000..1e20940508 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/54a20e07cafd1319.bin @@ -0,0 +1,5 @@ +# Backlog + +## Queued + +- [ ] one-a1 - The one task (repo: r1) diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/650ffdda645b4e53.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/650ffdda645b4e53.bin new file mode 100644 index 0000000000..dbaf93e7a9 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/650ffdda645b4e53.bin @@ -0,0 +1,2 @@ +[markdown] +archive = "backlog.md" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/676c90b2f2c57ad5.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/676c90b2f2c57ad5.bin new file mode 100644 index 0000000000..81ef02b93d --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/676c90b2f2c57ad5.bin @@ -0,0 +1,2 @@ +[markdown] +path = "p.md" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/6fa5623959fcfe4d.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/6fa5623959fcfe4d.bin new file mode 100644 index 0000000000..59469225c3 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/6fa5623959fcfe4d.bin @@ -0,0 +1,2 @@ +[markdown] +done_keep = 3 diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/725fe99b9b31b6b0.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/725fe99b9b31b6b0.bin new file mode 100644 index 0000000000..24a8e0f897 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/725fe99b9b31b6b0.bin @@ -0,0 +1,2 @@ +[markdown] +path = 'docs/t.md' # comment diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/761a9f94996191ee.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/761a9f94996191ee.bin new file mode 100644 index 0000000000..e8b919796b --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/761a9f94996191ee.bin @@ -0,0 +1,2 @@ +[markdown] +archive = "old.md" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/8aa488e0524ac436.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/8aa488e0524ac436.bin new file mode 100644 index 0000000000..310f52388d --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/8aa488e0524ac436.bin @@ -0,0 +1,34 @@ +# Backlog + +## In flight + +- [ ] x_y-fb - metrics migrate (priority: 9) (priority: 0) + a,b +  index backoff flaky + extra-indented index + cache audit widget résumé -dash migrate spaced colon: here + .5 +- **x_y-x2** - SHIP retry true naïve 42 comma,s index quote"s 42 (reported 2024-02-29): index (hold: audit index retry) (hold-until: 2000-01-01) + service naïve naïve gateway a#b migrate spaced 3.14 -dash adopt parser lease spaced backoff colon: here -dash rewrite migrate -dash a#b a#b queue service index flaky 日本語 retry true backoff null -dash résumé quote"s queue metrics retry gateway audit 42 3.14 index backoff rewrite lease 100% metrics migrate index [bracket] retry true 日本語 flaky quote"s schema migrate 日本語 100% a#b widget gateway résumé tab here lease backoff test -dash tab here router schema Ω adopt null 日本語 Ünïcode résumé c😀he + + +- [ ] x_y-9y - rewrite service parser quote"s lease 日本語 router 100% audit (reported 2024-02-29): spaced data/some-task/report.md blocked-by: x_y-x2 (hold: Ω 日本語 lease) (hold-until: 2000-01-01) (hold-kind: parked) +- **x_y-9y** - SCOUTS Ünïcode router service rewrite quote"s https://github.com/o/r/pull/042 (since 2026-10-01) + +- [ ] t-c4 - Ω test gateway index 42 https://github.com/o/r/pull/042 (hold-until: 2500-01-01) (priority: 2) (repo: true) +## Queued + +- [ ] a.b-s8 - migrate index true metrics 3.14 naïve résumé http://plain.example.net/a/b. parent: x_y-9y parent: x_y-fb (hold-kind: external) (since 2026-10-01) (kind: ) +- [ ] a.b-74 - router null widget test migrate adopt naïve cleanup a#b (kind: secondmate) + +- [ ] fm-x-k7 - retry retry résumé ß rewrite metrics parser 100% 日本語 gateway café adopt index schema ß spaced router Ω naïve metrics metrics widget Ω tab here naïve lease backoff rewrite résumé spacedx (since 2026-10-01) + parser widget parser résumé café naïve cleanup backoff + [bracket] rewrite -dash Ünïcode schema -dash naïve schema router [bracket] + queue true flaky  cache retry backoff comma,s router naïve cleanup + spaced rewrite 3.14 retry service metrics tab here metrics 日本語 router comma,s null  service backoff retry parser 日本語 widget rewrite backoff flaky audit quote"s queue lease tab here Ünïcode spaced a#b metrics café ß tab here widget résumé router audit  true schema  true spaced {brace} [bracket] test flaky queue true colon: here widget migrate {brace} résumé 100% adopt résumé ß widget queue lease colon: here rewrite true gateway metrics lease résumé quote"s -dash null rewr😀ex + Ω backoff widget [bracket] parser quote"s true retry metrics +## Notes + +## Done (retained) + +- [x] fm-x-5x.2 - 42 backoff (reported 2026-10-02): gateway 😀🙂 (hold-until: 2001-06-15) (merged 2024-02-29) (hold: metrics) diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/994af6b8cada21a6.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/994af6b8cada21a6.bin new file mode 100644 index 0000000000..dd66a01ff8 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/994af6b8cada21a6.bin @@ -0,0 +1 @@ +backend = "markdown diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/a1fce4363854ff88.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/a1fce4363854ff88.bin new file mode 100644 index 0000000000..e25f1814e5 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/a1fce4363854ff88.bin @@ -0,0 +1 @@ +y \ No newline at end of file diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/a4c2923d5552bc15.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/a4c2923d5552bc15.bin new file mode 100644 index 0000000000..645e20752d --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/a4c2923d5552bc15.bin @@ -0,0 +1,3 @@ +## Queued + +- [ ] bad-a1 - cafÃ(ÿâ‚ tail diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/a67b92c3ce5a07e0.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/a67b92c3ce5a07e0.bin new file mode 100644 index 0000000000..9404ad91ca --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/a67b92c3ce5a07e0.bin @@ -0,0 +1 @@ +backend = "jira" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/ab3d40b876f36b3d.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/ab3d40b876f36b3d.bin new file mode 100644 index 0000000000..68542c37ca --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/ab3d40b876f36b3d.bin @@ -0,0 +1,3 @@ +# Backlog + +Nothing here. diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/af33b80dd831b45f.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/af33b80dd831b45f.bin new file mode 100644 index 0000000000..828aee35de --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/af33b80dd831b45f.bin @@ -0,0 +1,8 @@ +## In flight + +- [ ] dep-b2 - Blocker + +## Queued + +- [ ] user-c3 - Waits blocked-by: dep-b2 + Body text diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b3075c6d975d14e5.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b3075c6d975d14e5.bin new file mode 100644 index 0000000000..ea8ffaea26 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b3075c6d975d14e5.bin @@ -0,0 +1 @@ +backend = 3 diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b41fb0d2cea4e05b.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b41fb0d2cea4e05b.bin new file mode 100644 index 0000000000..d4497bf2b6 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b41fb0d2cea4e05b.bin @@ -0,0 +1,2 @@ +[markdown] +done_keep = 99999999999999999999 diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b6f052c5ed4c2e15.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b6f052c5ed4c2e15.bin new file mode 100644 index 0000000000..795c40a95a --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b6f052c5ed4c2e15.bin @@ -0,0 +1,45 @@ +# Backlog + +## In flight + +- [ ] Homemux-cu - gateway flaky {brace} ß cache quote"s router 3.14 lease null widget cache gateway adopt 42 test résumé spaced queue cleanup schema widget naïve service widget 3.14 a#b adopt spaced rewrite 3.14 日本語 gateway quote"s widget 100% null [bracket] test 42 widget comm (since 2024-02-29) + test a#b -dash null test + + +- **x_y-xr** - lease retry [bracket] parser 100% (hold-kind: captain) (since 2025-01-01) (hold: tab here retry backoff) (hold-until: 2500-01-01) +- [ ] Z-fb - queue ß cleanup Ünïcode naïve retry queue null Ω naïve gateway index migrate [😀ack (repo: docs-site) +- [ ] Homemux-u1 - backoff true (repo: widgets) + ## Intent + ß  adopt quote"s rewrite true adopt migrate service null service tab here 日本語 naïve lease router naïve null index tab here Ω parser lease café [bracket] 日本語 résumé tab here cleanup quote"s cache cleanup index tab here adopt comma,s {brace} queue index router 42 router test naïve quote"s flaky widget Ünïcode quote"s schema café Ω 100% widget 3.14 -dash index router metrics adopt café 3.14 queue gateway lease adopt Ünïcode cleanup café 100% queue 日本語 a#b 100% service Ω tab here rewrite café b + index true colon: here flaky colon: here + extra-indented rewrite +- [ ] Z-3g - migrate Ünïcode quote"s backoff https://github.com/o/r/pulls/3 (hold-until: 2000-01-01) (kind: ship) (hold: {brace}) (hold-kind: external) +## Queued + +- [ ] x_y-b6 - [bracket] (priority: 2) + ## Intent + tab here metrics colon: here -dash metrics tab here schema audit widget quote"s -dash + ## Intent + + extra-indented colon: here + widget cleanup schema gateway café tab here migrate spaced +## Done (retained) + +- [x] gamma-5u - spaced -dash quote"s naïve spaced router gateway blocked-by: Homemux-cu blocked-by: Homemux-cu (repo: 7) (priority: 4) (closed 2026-09-30) (kind: docs) parent: Z-3g - audit + tab here ß lease Ω + {brace} 日本語 日本語 日本語 rewrite a#b {brace} {brace} rewrite index + 42 [bracket] test naïve {brace} cache 3.14 100% gateway service + ## Intent + + +- [x] sm-idle-qv - quote"s résumé widget true quote"s parser tab here  Ω comma,s index cache adopt ß cleanup audit naïve ß audit rewrite 42 café -dash comma,s colon: here test spaced quote"s résumé null cache Ω metr (priority: 4) (kind: ship) parent: x_y-b6 - gateway flaky null + ## Intent + ## Intent + a#b 日本語 [bracket] [bracket] index + a#b 42 spaced retry widget tab here index + Ünïcode quote"s [bracket] router adopt comma,s 日本語 100% Ω café index +- [x] x_y-7u - SHIPPING lease gateway flaky  discovered-from: Homemux-cu (merged 2026-10-01) (since 2025-01-01) (priority: 4) blocked-by: sm-idle-qv - spaced café +- [x] Homemux-3h - 42 null (priority: 2) (since 2026-09-30) +- [x] x_y-f6 -  queue 100% widget -dash widget tab here audit queue queue cache quote"s rewrite  ß retry service tab here 100% 42 42 日本語 router colon: here {brace} router lease migrate queue 42 ß spaced quote"s audit Ünïcode true comma,s lease backoff widget Ünïcode a#b -dash null résumé ß (kind: secondmate) (since 2024-02-29) (priority: 2) (closed 2026-09-30) + +- [x] Z-ft - lease 42 metrics backoff 42 spaced retry 3.14 null (since 2024-02-29) (kind: secondmate) (merged 2026-09-30) (repo: widgets) diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b9190515a56d4df5.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b9190515a56d4df5.bin new file mode 100644 index 0000000000..af5dbac4d9 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/b9190515a56d4df5.bin @@ -0,0 +1,3 @@ +[server] +port = 1 +nonsense diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/cb5ec2b32468d2a6.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/cb5ec2b32468d2a6.bin new file mode 100644 index 0000000000..5e26a14bdb --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/cb5ec2b32468d2a6.bin @@ -0,0 +1 @@ +backend = markdown diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/cbdd63418276ff9d.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/cbdd63418276ff9d.bin new file mode 100644 index 0000000000..02b3e85c84 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/cbdd63418276ff9d.bin @@ -0,0 +1,2 @@ +[markdown] +path = "done-archive.md" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e3a6450154542881.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e3a6450154542881.bin new file mode 100644 index 0000000000..ba201bd366 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e3a6450154542881.bin @@ -0,0 +1,2 @@ +[markdown] +done_keep = "3" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e3b0c44298fc1c14.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e3b0c44298fc1c14.bin new file mode 100644 index 0000000000..e69de29bb2 diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e49c8792ad67e117.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e49c8792ad67e117.bin new file mode 100644 index 0000000000..11d599eb11 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e49c8792ad67e117.bin @@ -0,0 +1,2 @@ +[markdown] +path = "note-archive.md" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e51ac269aa782daa.bin b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e51ac269aa782daa.bin new file mode 100644 index 0000000000..6559e9e39f --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/fixtures/e51ac269aa782daa.bin @@ -0,0 +1 @@ +backend = "markdown" diff --git a/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/golden.txt b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/golden.txt new file mode 100644 index 0000000000..ac594d9b80 --- /dev/null +++ b/examples/tasks-axi-rust/crates/tasks-axi-rs/tests/golden/golden.txt @@ -0,0 +1,1097 @@ +case fixed/version +arg --version +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout 0.2.6\n + +case fixed/version-v +arg -v +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout 0.2.6\n + +case fixed/version-V +arg -V +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout 0.2.6\n + +case fixed/noun-version +arg task +arg --version +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout 0.2.6\n + +case fixed/help-list +arg list +arg --help +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout usage: tasks-axi list [flags]\nflags:\n --state <queued|in_flight|done|held>, --repo <name>, --kind <name>, --blocked\n --limit <n>, --fields <a,b,c> (extra: blocked, blocked_by, body, closed, created, delivery_state, deps, held, hold_kind, hold_reason, hold_until, links, priority)\nexamples:\n tasks-axi list --state queued\n tasks-axi list --repo no-mistakes --fields blocked_by,created\n tasks-axi list --blocked + +case fixed/help-show +arg show +arg --help +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout usage: tasks-axi show <id> [--full]\naliases: view\nexamples:\n tasks-axi show homemux-h7\n tasks-axi show homemux-h7 --full + +case fixed/help-view +arg view +arg --help +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout usage: tasks-axi show <id> [--full]\naliases: view\nexamples:\n tasks-axi show homemux-h7\n tasks-axi show homemux-h7 --full + +case fixed/help-ready +arg ready +arg --help +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout usage: tasks-axi ready [--repo <name>] [--include-held]\nList unblocked, unheld queued work dispatchable right now.\nPublic-followup obligations are never dispatchable and appear only in the separate\nready_public_followups group; use tasks-axi public-followup ready for their full payloads.\nHeld work is excluded by default; --include-held shows it in a separate held group. + +case fixed/help-noun-list +arg task +arg list +arg --help +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout usage: tasks-axi list [flags]\nflags:\n --state <queued|in_flight|done|held>, --repo <name>, --kind <name>, --blocked\n --limit <n>, --fields <a,b,c> (extra: blocked, blocked_by, body, closed, created, delivery_state, deps, held, hold_kind, hold_reason, hold_until, links, priority)\nexamples:\n tasks-axi list --state queued\n tasks-axi list --repo no-mistakes --fields blocked_by,created\n tasks-axi list --blocked + +case fixed/help-wins +arg list +arg --bogus +arg --help +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout usage: tasks-axi list [flags]\nflags:\n --state <queued|in_flight|done|held>, --repo <name>, --kind <name>, --blocked\n --limit <n>, --fields <a,b,c> (extra: blocked, blocked_by, body, closed, created, delivery_state, deps, held, hold_kind, hold_reason, hold_until, links, priority)\nexamples:\n tasks-axi list --state queued\n tasks-axi list --repo no-mistakes --fields blocked_by,created\n tasks-axi list --blocked + +case fixed/help-unknown +arg frobnicate +arg --help +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown command: frobnicate"\ncode: VALIDATION_ERROR\nhelp[1]: Run `--help` to see available commands\n + +case fixed/unknown-command +arg frobnicate +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown command: frobnicate"\ncode: VALIDATION_ERROR\nhelp[1]: Run `--help` to see available commands\n + +case fixed/unknown-command-noun +arg task +arg frobnicate +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown command: frobnicate"\ncode: VALIDATION_ERROR\nhelp[1]: Run `--help` to see available commands\n + +case fixed/leading-flag +arg --foo +arg list +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: Flags must come after the command\ncode: VALIDATION_ERROR\nhelp[2]: "Run `tasks-axi <command> [args] [flags]`",Move `--foo` after the command instead of before it\n + +case fixed/leading-short-flag +arg -x +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: Flags must come after the command\ncode: VALIDATION_ERROR\nhelp[2]: "Run `tasks-axi <command> [args] [flags]`",Move `-x` after the command instead of before it\n + +case fixed/leading-flag-noun +arg task +arg --foo +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: Flags must come after the command\ncode: VALIDATION_ERROR\nhelp[2]: "Run `tasks-axi <command> [args] [flags]`",Move `--foo` after the command instead of before it\n + +case fixed/show-no-id +arg show +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Expected 1 positional argument, got 0"\ncode: VALIDATION_ERROR\nhelp[1]: "usage: tasks-axi show <id> [--full]"\n + +case fixed/show-two-ids +arg show +arg one-a1 +arg two +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Expected 1 positional argument, got 2"\ncode: VALIDATION_ERROR\nhelp[1]: "usage: tasks-axi show <id> [--full]"\n + +case fixed/show-unknown-flag +arg show +arg --bogus +arg one-a1 +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown flag: --bogus"\ncode: VALIDATION_ERROR\nhelp[1]: Run the command with --help to see supported flags\n + +case fixed/show-short-flag +arg show +arg -x +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown flag: -x"\ncode: VALIDATION_ERROR\nhelp[1]: Run the command with --help to see supported flags\n + +case fixed/show-bad-id +arg show +arg bad id! +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Invalid id \\"bad id!\\" - ids must be slug-shaped (letters, digits, \\"._-\\") with no spaces"\ncode: VALIDATION_ERROR\nhelp[1]: "Use a slug like `homemux-h7`, or pass --mint to generate one"\n + +case fixed/show-empty-id +arg show +arg +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: Missing id\ncode: VALIDATION_ERROR\nhelp[1]: "Pass the task id, e.g. `tasks-axi show <id>`"\n + +case fixed/show-blank-id +arg show +arg +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: Missing id\ncode: VALIDATION_ERROR\nhelp[1]: "Pass the task id, e.g. `tasks-axi show <id>`"\n + +case fixed/show-dot-id +arg show +arg .hidden +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Invalid id \\".hidden\\" - ids must be slug-shaped (letters, digits, \\"._-\\") with no spaces"\ncode: VALIDATION_ERROR\nhelp[1]: "Use a slug like `homemux-h7`, or pass --mint to generate one"\n + +case fixed/show-full-twice +arg show +arg one-a1 +arg --full +arg --full +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown flag: --full"\ncode: VALIDATION_ERROR\nhelp[1]: Run the command with --help to see supported flags\n + +case fixed/list-bad-state +arg list +arg --state +arg bogus +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--state must be one of queued, in_flight, done, held"\ncode: VALIDATION_ERROR\n + +case fixed/list-state-novalue +arg list +arg --state +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--state requires a value"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --state=... if the value begins with --\n + +case fixed/list-state-flaglike +arg list +arg --state +arg --blocked +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--state requires a value"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --state=... if the value begins with --\n + +case fixed/list-limit-negative +arg list +arg --limit +arg -1 +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--limit must be a non-negative integer"\ncode: VALIDATION_ERROR\n + +case fixed/list-limit-text +arg list +arg --limit +arg abc +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--limit must be a non-negative integer"\ncode: VALIDATION_ERROR\n + +case fixed/list-limit-float +arg list +arg --limit +arg 1.5 +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--limit must be a non-negative integer"\ncode: VALIDATION_ERROR\n + +case fixed/list-limit-huge +arg list +arg --limit +arg 99999999999999999999 +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--limit must be a non-negative integer"\ncode: VALIDATION_ERROR\n + +case fixed/list-limit-maxsafe +arg list +arg --limit +arg 9007199254740991 +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/list-limit-unsafe +arg list +arg --limit +arg 9007199254740992 +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--limit must be a non-negative integer"\ncode: VALIDATION_ERROR\n + +case fixed/list-limit-leading-zero +arg list +arg --limit +arg 007 +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/list-bad-field +arg list +arg --fields +arg nope,body +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown field(s): nope. Available: blocked, blocked_by, body, closed, created, delivery_state, deps, held, hold_kind, hold_reason, hold_until, links, priority"\ncode: VALIDATION_ERROR\n + +case fixed/list-field-already-default +arg list +arg --fields +arg id +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown field(s): id. Available: blocked, blocked_by, body, closed, created, delivery_state, deps, held, hold_kind, hold_reason, hold_until, links, priority"\ncode: VALIDATION_ERROR\n + +case fixed/list-fields-empty +arg list +arg --fields= +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/list-fields-blank +arg list +arg --fields +arg , , +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/list-repo-empty +arg list +arg --repo= +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--repo requires a value"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --repo=... with a non-empty value\n + +case fixed/list-repo-multiline +arg list +arg --repo +arg a\nb +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--repo must be a single line"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --repo=... without line breaks\n + +case fixed/list-repo-novalue +arg list +arg --repo +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--repo requires a value"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --repo=... if the value begins with --\n + +case fixed/list-kind-blank +arg list +arg --kind +arg +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--kind requires a value"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --kind=... with a non-empty value\n + +case fixed/list-positional +arg list +arg extra +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Expected no positional arguments, got 1"\ncode: VALIDATION_ERROR\nhelp[1]: "usage: tasks-axi list [flags]"\n + +case fixed/list-unknown-flag +arg list +arg --bogus +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown flag: --bogus"\ncode: VALIDATION_ERROR\nhelp[1]: Run the command with --help to see supported flags\n + +case fixed/list-blocked-twice +arg list +arg --blocked +arg --blocked +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown flag: --blocked"\ncode: VALIDATION_ERROR\nhelp[1]: Run the command with --help to see supported flags\n + +case fixed/ready-positional +arg ready +arg extra +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Expected no positional arguments, got 1"\ncode: VALIDATION_ERROR\nhelp[1]: "usage: tasks-axi ready [--repo <name>] [--include-held]"\n + +case fixed/ready-unknown-flag +arg ready +arg --bogus +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown flag: --bogus"\ncode: VALIDATION_ERROR\nhelp[1]: Run the command with --help to see supported flags\n + +case fixed/ready-repo-twice +arg ready +arg --repo +arg r1 +arg --repo +arg r2 +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "Unknown flag: --repo"\ncode: VALIDATION_ERROR\nhelp[1]: Run the command with --help to see supported flags\n + +case fixed/backend-markdown +arg list +arg --backend +arg markdown +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id> --backend=markdown` for full notes on a task\n - Run `tasks-axi ready --backend=markdown` to see unblocked queued work\n + +case fixed/backend-markdown-eq +arg list +arg --backend=markdown +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id> --backend=markdown` for full notes on a task\n - Run `tasks-axi ready --backend=markdown` to see unblocked queued work\n + +case fixed/backend-unsupported +arg list +arg --backend +arg sqlite +file backlog.md 52afa28aa0823dd2.bin +code 1 +stdout error: "Unsupported backend \\"sqlite\\" — P1 ships the markdown backend only"\ncode: UNSUPPORTED\nhelp[1]: "Set `backend = \\"markdown\\"` in .tasks.toml, or omit --backend"\n + +case fixed/backend-novalue +arg list +arg --backend +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--backend requires a value"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --backend=... if the value begins with --\n + +case fixed/backend-empty +arg list +arg --backend= +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--backend requires a value"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --backend=... with a non-empty value\n + +case fixed/file-novalue +arg list +arg --file +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--file requires a value"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --file=... if the value begins with --\n + +case fixed/file-empty +arg list +arg --file= +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--file requires a value"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --file=... with a non-empty value\n + +case fixed/file-multiline +arg list +arg --file +arg a\nb +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: "--file must be a single line"\ncode: VALIDATION_ERROR\nhelp[1]: Pass --file=... without line breaks\n + +case fixed/file-missing +arg list +arg --file +arg missing.md +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 0\ntasks: 0 tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\" --file=missing.md` to add a task"\n - Run `tasks-axi list --state done --file=missing.md` to see completed work\n + +case fixed/file-space +arg list +arg --file +arg x y.md +file x y.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id> --file='x y.md'` for full notes on a task\n - Run `tasks-axi ready --file='x y.md'` to see unblocked queued work\n + +case fixed/file-quote +arg ready +arg --file +arg it's.md +file it's.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\nready[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - "Run `tasks-axi start <id> --file='it'\\\\''s.md'` to dispatch one of these"\n + +case fixed/file-backtick +arg list +arg --file +arg back`tick.md +file back`tick.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\n + +case fixed/file-twice +arg list +arg --file +arg a.md +arg --file +arg b.md +file a.md 52afa28aa0823dd2.bin +file b.md af33b80dd831b45f.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n dep-b2,in_flight,task,"-",Blocker\n user-c3,queued,task,"-",Waits\nhelp[2]:\n - Run `tasks-axi show <id> --file=b.md` for full notes on a task\n - Run `tasks-axi ready --file=b.md` to see unblocked queued work\n + +case fixed/notfound-globals +arg show +arg none +arg --file +arg a.md +arg --backend +arg markdown +file a.md 52afa28aa0823dd2.bin +code 1 +stdout error: "Task \\"none\\" not found in this backlog"\ncode: NOT_FOUND\nhelp[1]: Run `tasks-axi list --backend=markdown --file=a.md` to see existing tasks\n + +case fixed/list-filter-and-globals +arg list +arg --repo +arg r1 +arg --file +arg a.md +file a.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id> --file=a.md` for full notes on a task\n - Run `tasks-axi ready --repo=r1 --file=a.md` to see unblocked queued work\n + +case fixed/ready-filter-quoted +arg ready +arg --repo +arg x y +arg --file +arg a.md +file a.md 52afa28aa0823dd2.bin +code 0 +stdout count: 0\nready: 0 unblocked queued tasks\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi list --state queued --repo='x y' --file=a.md` to see all queued work (incl. blocked)\n + +case fixed/globals-before-command +arg --file +arg a.md +arg list +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: Flags must come after the command\ncode: VALIDATION_ERROR\nhelp[2]: "Run `tasks-axi <command> [args] [flags]`",Move `--file` after the command instead of before it\n + +case fixed/discover-backlog +arg list +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/discover-data-backlog +arg list +file data/backlog.md af33b80dd831b45f.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n dep-b2,in_flight,task,"-",Blocker\n user-c3,queued,task,"-",Waits\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/discover-prefers-root +arg list +file backlog.md 52afa28aa0823dd2.bin +file data/backlog.md af33b80dd831b45f.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/no-backlog +arg list +code 0 +stdout count: 0\ntasks: 0 tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\"` to add a task"\n - Run `tasks-axi list --state done` to see completed work\n + +case fixed/no-backlog-ready +arg ready +code 0 +stdout count: 0\nready: 0 unblocked queued tasks\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi list --state queued` to see all queued work (incl. blocked)\n + +case fixed/empty-file +arg list +file backlog.md e3b0c44298fc1c14.bin +code 0 +stdout count: 0\ntasks: 0 tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\"` to add a task"\n - Run `tasks-axi list --state done` to see completed work\n + +case fixed/only-newline +arg list +file backlog.md 01ba4719c80b6fe9.bin +code 0 +stdout count: 0\ntasks: 0 tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\"` to add a task"\n - Run `tasks-axi list --state done` to see completed work\n + +case fixed/preamble-only +arg list +file backlog.md ab3d40b876f36b3d.bin +code 0 +stdout count: 0\ntasks: 0 tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\"` to add a task"\n - Run `tasks-axi list --state done` to see completed work\n + +case fixed/bom +arg list +file backlog.md 54a20e07cafd1319.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/invalid-utf8 +arg list +file backlog.md a4c2923d5552bc15.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n bad-a1,queued,task,"-",caf�(�� tail\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/crlf +arg list +file backlog.md 3cae5bba6005a270.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/backlog-is-directory +arg list +file backlog.md/x a1fce4363854ff88.bin +code 1 +stdout error: "EISDIR: illegal operation on a directory, read"\ncode: UNKNOWN\n + +case fixed/show-blocked-hints +arg show +arg user-c3 +file backlog.md af33b80dd831b45f.bin +code 0 +stdout task:\n id: user-c3\n title: Waits\n state: queued\n blocked: yes\n blocked_by: dep-b2\n held: no\n hold_reason: "-"\n hold_kind: "-"\n hold_until: "-"\n kind: task\n repo: "-"\n priority: "-"\n created: "-"\n closed: "-"\n deps: "blocked-by:dep-b2"\n links: none\n body: Body text\nhelp[2]:\n - Run `tasks-axi unblock user-c3 --by <other>` to clear a blocker\n - Run `tasks-axi start user-c3` to move it to in flight\n + +case fixed/show-blocked-hints-globals +arg show +arg user-c3 +arg --file +arg backlog.md +file backlog.md af33b80dd831b45f.bin +code 0 +stdout task:\n id: user-c3\n title: Waits\n state: queued\n blocked: yes\n blocked_by: dep-b2\n held: no\n hold_reason: "-"\n hold_kind: "-"\n hold_until: "-"\n kind: task\n repo: "-"\n priority: "-"\n created: "-"\n closed: "-"\n deps: "blocked-by:dep-b2"\n links: none\n body: Body text\nhelp[2]:\n - Run `tasks-axi unblock user-c3 --by <other> --file=backlog.md` to clear a blocker\n - Run `tasks-axi start user-c3 --file=backlog.md` to move it to in flight\n + +case fixed/list-blocked-fixed +arg list +arg --blocked +file backlog.md af33b80dd831b45f.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n user-c3,queued,task,"-",Waits\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/env-file +arg list +env TASKS_AXI_FILE other.md +file other.md af33b80dd831b45f.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n dep-b2,in_flight,task,"-",Blocker\n user-c3,queued,task,"-",Waits\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/env-file-empty +arg list +env TASKS_AXI_FILE +file backlog.md 52afa28aa0823dd2.bin +code 2 +stdout error: TASKS_AXI_FILE must not be empty\ncode: VALIDATION_ERROR\nhelp[1]: Set it to a backlog path or remove the empty override\n + +case fixed/flag-beats-env +arg list +arg --file +arg backlog.md +env TASKS_AXI_FILE other.md +file other.md af33b80dd831b45f.bin +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id> --file=backlog.md` for full notes on a task\n - Run `tasks-axi ready --file=backlog.md` to see unblocked queued work\n + +case fixed/env-backend +arg list +env TASKS_AXI_BACKEND linear +file backlog.md 52afa28aa0823dd2.bin +code 1 +stdout error: "Unsupported backend \\"linear\\" — P1 ships the markdown backend only"\ncode: UNSUPPORTED\nhelp[1]: "Set `backend = \\"markdown\\"` in .tasks.toml, or omit --backend"\n + +case fixed/env-backend-empty +arg list +env TASKS_AXI_BACKEND +file backlog.md 52afa28aa0823dd2.bin +code 1 +stdout error: "Unsupported backend \\"\\" — P1 ships the markdown backend only"\ncode: UNSUPPORTED\nhelp[1]: "Set `backend = \\"markdown\\"` in .tasks.toml, or omit --backend"\n + +case fixed/toml-path +arg list +file .tasks.toml 315863d2ed6d735e.bin +file docs/t.md af33b80dd831b45f.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n dep-b2,in_flight,task,"-",Blocker\n user-c3,queued,task,"-",Waits\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/toml-path-single-quotes +arg list +file .tasks.toml 725fe99b9b31b6b0.bin +file docs/t.md af33b80dd831b45f.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n dep-b2,in_flight,task,"-",Blocker\n user-c3,queued,task,"-",Waits\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/toml-backend +arg list +file .tasks.toml a67b92c3ce5a07e0.bin +code 1 +stdout error: "Unsupported backend \\"jira\\" — P1 ships the markdown backend only"\ncode: UNSUPPORTED\nhelp[1]: "Set `backend = \\"markdown\\"` in .tasks.toml, or omit --backend"\n + +case fixed/toml-backend-ok +arg list +file .tasks.toml e51ac269aa782daa.bin +code 0 +stdout count: 0\ntasks: 0 tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\"` to add a task"\n - Run `tasks-axi list --state done` to see completed work\n + +case fixed/toml-bad-line +arg list +file .tasks.toml 2f9d23efc1830169.bin +code 2 +stdout error: "Invalid config line: expected `key = value`"\ncode: VALIDATION_ERROR\nhelp[1]: Use `key = value` assignments in .tasks.toml\n + +case fixed/toml-bad-value +arg list +file .tasks.toml cb5ec2b32468d2a6.bin +code 2 +stdout error: backend has an invalid value\ncode: VALIDATION_ERROR\n + +case fixed/toml-unterminated +arg list +file .tasks.toml 994af6b8cada21a6.bin +code 2 +stdout error: backend has an unterminated quoted value\ncode: VALIDATION_ERROR\n + +case fixed/toml-backend-number +arg list +file .tasks.toml b3075c6d975d14e5.bin +code 2 +stdout error: backend must be a quoted string\ncode: VALIDATION_ERROR\n + +case fixed/toml-done-keep-ok +arg list +file .tasks.toml 6fa5623959fcfe4d.bin +code 0 +stdout count: 0\ntasks: 0 tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\"` to add a task"\n - Run `tasks-axi list --state done` to see completed work\n + +case fixed/toml-done-keep-negative +arg list +file .tasks.toml 167396b16774aa5b.bin +code 2 +stdout error: markdown.done_keep must be a non-negative integer\ncode: VALIDATION_ERROR\nhelp[1]: "Set `[markdown] done_keep = 10` in .tasks.toml"\n + +case fixed/toml-done-keep-text +arg list +file .tasks.toml e3a6450154542881.bin +code 2 +stdout error: markdown.done_keep must be an integer\ncode: VALIDATION_ERROR\nhelp[1]: "Set `[markdown] done_keep = 10` in .tasks.toml"\n + +case fixed/toml-done-keep-huge +arg list +file .tasks.toml b41fb0d2cea4e05b.bin +code 2 +stdout error: markdown.done_keep must be a non-negative integer\ncode: VALIDATION_ERROR\nhelp[1]: "Set `[markdown] done_keep = 10` in .tasks.toml"\n + +case fixed/toml-path-empty +arg list +file .tasks.toml 01a7cf944466c2ac.bin +code 2 +stdout error: markdown.path must not be empty\ncode: VALIDATION_ERROR\nhelp[1]: Set it to a backlog path or remove the empty override\n + +case fixed/toml-other-table +arg list +file .tasks.toml b9190515a56d4df5.bin +code 0 +stdout count: 0\ntasks: 0 tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\"` to add a task"\n - Run `tasks-axi list --state done` to see completed work\n + +case fixed/toml-crlf +arg list +file .tasks.toml 1dcb09d9adbd2ecc.bin +file docs/t.md af33b80dd831b45f.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n dep-b2,in_flight,task,"-",Blocker\n user-c3,queued,task,"-",Waits\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/toml-archive-is-backlog +arg list +file .tasks.toml 650ffdda645b4e53.bin +code 2 +stdout error: Archive path must not be the active backlog path\ncode: VALIDATION_ERROR\n + +case fixed/toml-archive-other +arg list +file .tasks.toml 761a9f94996191ee.bin +code 0 +stdout count: 0\ntasks: 0 tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\"` to add a task"\n - Run `tasks-axi list --state done` to see completed work\n + +case fixed/backlog-named-done-archive +arg list +file .tasks.toml cbdd63418276ff9d.bin +file done-archive.md 52afa28aa0823dd2.bin +code 2 +stdout error: Archive path must not be the active backlog path\ncode: VALIDATION_ERROR\n + +case fixed/backlog-named-note-archive +arg list +file .tasks.toml e49c8792ad67e117.bin +file note-archive.md 52afa28aa0823dd2.bin +code 2 +stdout error: Note archive path must not be the active backlog path\ncode: VALIDATION_ERROR\n + +case fixed/home-config-path +arg list +file h.md af33b80dd831b45f.bin +home .tasks-axi/config.toml 50b7dde7c190b2c1.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n dep-b2,in_flight,task,"-",Blocker\n user-c3,queued,task,"-",Waits\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/home-config-bad +arg list +file backlog.md 52afa28aa0823dd2.bin +home .tasks-axi/config.toml 2f9d23efc1830169.bin +code 2 +stdout error: "Invalid config line: expected `key = value`"\ncode: VALIDATION_ERROR\nhelp[1]: Use `key = value` assignments in .tasks.toml\n + +case fixed/project-beats-home +arg list +file .tasks.toml 676c90b2f2c57ad5.bin +file h.md 52afa28aa0823dd2.bin +file p.md af33b80dd831b45f.bin +home .tasks-axi/config.toml 50b7dde7c190b2c1.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n dep-b2,in_flight,task,"-",Blocker\n user-c3,queued,task,"-",Waits\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case fixed/flag-beats-toml +arg list +arg --file +arg backlog.md +file .tasks.toml 676c90b2f2c57ad5.bin +file p.md af33b80dd831b45f.bin +file backlog.md 52afa28aa0823dd2.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n one-a1,queued,task,r1,The one task\nhelp[2]:\n - Run `tasks-axi show <id> --file=backlog.md` for full notes on a task\n - Run `tasks-axi ready --file=backlog.md` to see unblocked queued work\n + +case seed1/list +arg list +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout count: 9\ntasks[9]{id,state,kind,repo,title}:\n x_y-fb,in_flight,task,"-","metrics migrate (priority: 9)"\n x_y-x2,in_flight,ship,"-","SHIP retry true naïve 42 comma,s index quote\\"s 42 (reported 2024-02-29): index"\n x_y-9y,in_flight,task,"-","rewrite service parser quote\\"s lease 日本語 router 100% audit (reported 2024-02-29)\\n... (truncated, 117 chars total - use show x_y-9y --full to see complete text)"\n x_y-9y,in_flight,task,"-","SCOUTS Ünïcode router service rewrite quote\\"s https://github.com/o/r/pull/042"\n t-c4,in_flight,task,"true","Ω test gateway index 42 https://github.com/o/r/pull/042"\n a.b-s8,queued,task,"-","migrate index true metrics 3.14 naïve résumé http://plain.example.net/a/b."\n a.b-74,queued,secondmate,"-",router null widget test migrate adopt naïve cleanup a#b\n fm-x-k7,queued,task,"-","retry retry résumé ß rewrite metrics parser 100% 日本語 gateway café adopt index sc\\n... (truncated, 191 chars total - use show fm-x-k7 --full to see complete text)"\n fm-x-5x.2,done,task,"-","42 backoff (reported 2026-10-02): gateway 😀🙂"\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case seed1/list-queued +arg list +arg --state +arg queued +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout count: 3\ntasks[3]{id,state,kind,repo,title}:\n a.b-s8,queued,task,"-","migrate index true metrics 3.14 naïve résumé http://plain.example.net/a/b."\n a.b-74,queued,secondmate,"-",router null widget test migrate adopt naïve cleanup a#b\n fm-x-k7,queued,task,"-","retry retry résumé ß rewrite metrics parser 100% 日本語 gateway café adopt index sc\\n... (truncated, 191 chars total - use show fm-x-k7 --full to see complete text)"\nhelp[1]:\n - Run `tasks-axi show <id>` for full notes on a task\n + +case seed1/list-held +arg list +arg --state +arg held +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout count: 0\ntasks: 0 held tasks in this backlog\n + +case seed1/list-blocked +arg list +arg --blocked +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n x_y-9y,in_flight,task,"-","rewrite service parser quote\\"s lease 日本語 router 100% audit (reported 2024-02-29)\\n... (truncated, 117 chars total - use show x_y-9y --full to see complete text)"\n x_y-9y,in_flight,task,"-","SCOUTS Ünïcode router service rewrite quote\\"s https://github.com/o/r/pull/042"\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case seed1/list-limit1 +arg list +arg --limit +arg 1 +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout count: 1 of 9 total\ntasks[1]{id,state,kind,repo,title}:\n x_y-fb,in_flight,task,"-","metrics migrate (priority: 9)"\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case seed1/list-allfields +arg list +arg --fields +arg blocked,blocked_by,body,closed,created,delivery_state,deps,held,hold_kind,hold_reason,hold_until,links,priority +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout count: 9\ntasks[9]{id,state,kind,repo,title,blocked,blocked_by,body,closed,created,delivery_state,deps,held,hold_kind,hold_reason,hold_until,links,priority}:\n x_y-fb,in_flight,task,"-","metrics migrate (priority: 9)",no,none,"a,b\\n\\u001b[0m index backoff flaky\\n extra-indented index\\ncache audit widget résumé -dash migrate spaced colon: here\\n.5","-","-","-",none,no,"-","-","-",none,0\n x_y-x2,in_flight,ship,"-","SHIP retry true naïve 42 comma,s index quote\\"s 42 (reported 2024-02-29): index",no,none,"service naïve naïve gateway a#b migrate spaced 3.14 -dash adopt parser lease spaced backoff colon: here -dash rewrite migrate -dash a#b a#b queue service index flaky 日本語 retry true backoff null -dash résumé quote\\"s queue metrics retry gateway audit 42 3.14 index backoff rewrite lease 100% metrics migrate index [bracket] retry true 日本語 flaky quote\\"s schema migrate 日本語 100% a#b widget gateway résumé tab\\there lease backoff test -dash tab\\there router schema Ω adopt null 日本語 Ünïcode résumé c�\\n... (truncated, 503 chars total - use show x_y-x2 --full to see complete text)","-","-","-",none,no,"-",audit index retry,2000-01-01,none,"-"\n x_y-9y,in_flight,task,"-","rewrite service parser quote\\"s lease 日本語 router 100% audit (reported 2024-02-29)\\n... (truncated, 117 chars total - use show x_y-9y --full to see complete text)",yes,x_y-x2,"","-","-","-","blocked-by:x_y-x2",no,parked,Ω 日本語 lease,2000-01-01,"report:data/some-task/report.md","-"\n x_y-9y,in_flight,task,"-","SCOUTS Ünïcode router service rewrite quote\\"s https://github.com/o/r/pull/042",no,none,"","-",2026-10-01,"-",none,no,"-","-","-","doc:https://github.com/o/r/pull/042","-"\n t-c4,in_flight,task,"true","Ω test gateway index 42 https://github.com/o/r/pull/042",no,none,"","-","-","-",none,no,"-","-","-","doc:https://github.com/o/r/pull/042",2\n a.b-s8,queued,task,"-","migrate index true metrics 3.14 naïve résumé http://plain.example.net/a/b.",no,none,"","-",2026-10-01,"-","parent:x_y-9y,parent:x_y-fb",no,"-","-","-","doc:http://plain.example.net/a/b","-"\n a.b-74,queued,secondmate,"-",router null widget test migrate adopt naïve cleanup a#b,no,none,"","-","-","-",none,no,"-","-","-",none,"-"\n fm-x-k7,queued,task,"-","retry retry résumé ß rewrite metrics parser 100% 日本語 gateway café adopt index sc\\n... (truncated, 191 chars total - use show fm-x-k7 --full to see complete text)",no,none,"parser widget parser résumé café naïve cleanup backoff\\n[bracket] rewrite -dash Ünïcode schema -dash naïve schema router [bracket]\\nqueue true flaky \\u001b[0m cache retry backoff comma,s router naïve cleanup\\n spaced rewrite 3.14 retry service metrics tab\\there metrics 日本語 router comma,s null \\u001b[0m service backoff retry parser 日本語 widget rewrite backoff flaky audit quote\\"s queue lease tab\\there Ünïcode spaced a#b metrics café ß tab\\there widget résumé router audit \\u001b[0m true schema \\u001b[0m true spaced \\n... (truncated, 765 chars total - use show fm-x-k7 --full to see complete text)","-",2026-10-01,"-",none,no,"-","-","-",none,"-"\n fm-x-5x.2,done,task,"-","42 backoff (reported 2026-10-02): gateway 😀🙂",no,none,"",2024-02-29,"-","-",none,no,"-",metrics,2001-06-15,none,"-"\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case seed1/ready +arg ready +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout count: 3\nready[3]{id,state,kind,repo,title}:\n a.b-s8,queued,task,"-","migrate index true metrics 3.14 naïve résumé http://plain.example.net/a/b."\n a.b-74,queued,secondmate,"-",router null widget test migrate adopt naïve cleanup a#b\n fm-x-k7,queued,task,"-","retry retry résumé ß rewrite metrics parser 100% 日本語 gateway café adopt index sc\\n... (truncated, 191 chars total - use show fm-x-k7 --full to see complete text)"\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi start <id>` to dispatch one of these\n + +case seed1/ready-held +arg ready +arg --include-held +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout count: 3\nready[3]{id,state,kind,repo,title}:\n a.b-s8,queued,task,"-","migrate index true metrics 3.14 naïve résumé http://plain.example.net/a/b."\n a.b-74,queued,secondmate,"-",router null widget test migrate adopt naïve cleanup a#b\n fm-x-k7,queued,task,"-","retry retry résumé ß rewrite metrics parser 100% 日本語 gateway café adopt index sc\\n... (truncated, 191 chars total - use show fm-x-k7 --full to see complete text)"\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi start <id>` to dispatch one of these\n + +case seed1/ready-repo +arg ready +arg --repo +arg true +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout count: 0\nready: 0 unblocked queued tasks\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi list --state queued --repo=true` to see all queued work (incl. blocked)\n + +case seed1/show-missing +arg show +arg no-such-task +file backlog.md 8aa488e0524ac436.bin +code 1 +stdout error: "Task \\"no-such-task\\" not found in this backlog"\ncode: NOT_FOUND\nhelp[1]: Run `tasks-axi list` to see existing tasks\n + +case seed1/show-x_y-fb +arg show +arg x_y-fb +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout task:\n id: x_y-fb\n title: "metrics migrate (priority: 9)"\n state: in_flight\n blocked: no\n blocked_by: none\n held: no\n hold_reason: "-"\n hold_kind: "-"\n hold_until: "-"\n kind: task\n repo: "-"\n priority: 0\n created: "-"\n closed: "-"\n deps: none\n links: none\n body: "a,b\\n\\u001b[0m index backoff flaky\\n extra-indented index\\ncache audit widget résumé -dash migrate spaced colon: here\\n.5"\n + +case seed1/show-full-x_y-fb +arg view +arg x_y-fb +arg --full +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout task:\n id: x_y-fb\n title: "metrics migrate (priority: 9)"\n state: in_flight\n blocked: no\n blocked_by: none\n held: no\n hold_reason: "-"\n hold_kind: "-"\n hold_until: "-"\n kind: task\n repo: "-"\n priority: 0\n created: "-"\n closed: "-"\n deps: none\n links: none\n body: "a,b\\n\\u001b[0m index backoff flaky\\n extra-indented index\\ncache audit widget résumé -dash migrate spaced colon: here\\n.5"\n + +case seed1/show-x_y-x2 +arg show +arg x_y-x2 +file backlog.md 8aa488e0524ac436.bin +code 0 +stdout task:\n id: x_y-x2\n title: "SHIP retry true naïve 42 comma,s index quote\\"s 42 (reported 2024-02-29): index"\n state: in_flight\n blocked: no\n blocked_by: none\n held: no\n hold_reason: audit index retry\n hold_kind: "-"\n hold_until: 2000-01-01\n kind: ship\n repo: "-"\n priority: "-"\n created: "-"\n closed: "-"\n deps: none\n links: none\n body: "service naïve naïve gateway a#b migrate spaced 3.14 -dash adopt parser lease spaced backoff colon: here -dash rewrite migrate -dash a#b a#b queue service index flaky 日本語 retry true backoff null -dash résumé quote\\"s queue metrics retry gateway audit 42 3.14 index backoff rewrite lease 100% metrics migrate index [bracket] retry true 日本語 flaky quote\\"s schema migrate 日本語 100% a#b widget gateway résumé tab\\there lease backoff test -dash tab\\there router schema Ω adopt null 日本語 Ünïcode résumé c�\\n... (truncated, 503 chars total - use --full to see complete text)"\n + +case seed2/list +arg list +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout count: 12\ntasks[12]{id,state,kind,repo,title}:\n Homemux-cu,in_flight,task,"-","gateway flaky {brace} ß cache quote\\"s router 3.14 lease null widget cache gatewa\\n... (truncated, 268 chars total - use show Homemux-cu --full to see complete text)"\n x_y-xr,in_flight,task,"-","lease retry [bracket] parser 100%"\n Z-fb,in_flight,task,docs-site,"queue ß cleanup Ünïcode naïve retry queue null Ω naïve gateway index migrate [😀\\n... (truncated, 83 chars total - use show Z-fb --full to see complete text)"\n Homemux-u1,in_flight,task,widgets,backoff true\n Z-3g,in_flight,ship,"-","migrate Ünïcode quote\\"s backoff https://github.com/o/r/pulls/3"\n x_y-b6,queued,task,"-","[bracket]"\n gamma-5u,done,docs,"7","spaced -dash quote\\"s naïve spaced router gateway"\n sm-idle-qv,done,ship,"-","quote\\"s résumé widget true quote\\"s parser tab\\there \\u001b[0m Ω comma,s index cache ad\\n... (truncated, 204 chars total - use show sm-idle-qv --full to see complete text)"\n x_y-7u,done,task,"-","SHIPPING lease gateway flaky \\u001b[0m"\n Homemux-3h,done,task,"-",42 null\n x_y-f6,done,secondmate,"-","\\u001b[0m queue 100% widget -dash widget tab\\there audit queue queue cache quote\\"s rew\\n... (truncated, 287 chars total - use show x_y-f6 --full to see complete text)"\n Z-ft,done,secondmate,widgets,lease 42 metrics backoff 42 spaced retry 3.14 null\nhelp[2]:\n - Run `tasks-axi show <id> --file=docs/tasks.md` for full notes on a task\n - Run `tasks-axi ready --file=docs/tasks.md` to see unblocked queued work\n + +case seed2/list-queued +arg list +arg --state +arg queued +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n x_y-b6,queued,task,"-","[bracket]"\nhelp[1]:\n - Run `tasks-axi show <id> --file=docs/tasks.md` for full notes on a task\n + +case seed2/list-held +arg list +arg --state +arg held +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout count: 1\ntasks[1]{id,state,kind,repo,title}:\n x_y-xr,in_flight,task,"-","lease retry [bracket] parser 100%"\nhelp[1]:\n - Run `tasks-axi show <id> --file=docs/tasks.md` for full notes on a task\n + +case seed2/list-blocked +arg list +arg --blocked +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout count: 0\ntasks: 0 blocked tasks in this backlog\nhelp[2]:\n - "Run `tasks-axi add <id> \\"<title>\\" --file=docs/tasks.md` to add a task"\n - Run `tasks-axi list --state done --file=docs/tasks.md` to see completed work\n + +case seed2/list-limit1 +arg list +arg --limit +arg 1 +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout count: 1 of 12 total\ntasks[1]{id,state,kind,repo,title}:\n Homemux-cu,in_flight,task,"-","gateway flaky {brace} ß cache quote\\"s router 3.14 lease null widget cache gatewa\\n... (truncated, 268 chars total - use show Homemux-cu --full to see complete text)"\nhelp[2]:\n - Run `tasks-axi show <id> --file=docs/tasks.md` for full notes on a task\n - Run `tasks-axi ready --file=docs/tasks.md` to see unblocked queued work\n + +case seed2/list-allfields +arg list +arg --fields +arg blocked,blocked_by,body,closed,created,delivery_state,deps,held,hold_kind,hold_reason,hold_until,links,priority +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout count: 12\ntasks[12]{id,state,kind,repo,title,blocked,blocked_by,body,closed,created,delivery_state,deps,held,hold_kind,hold_reason,hold_until,links,priority}:\n Homemux-cu,in_flight,task,"-","gateway flaky {brace} ß cache quote\\"s router 3.14 lease null widget cache gatewa\\n... (truncated, 268 chars total - use show Homemux-cu --full to see complete text)",no,none,test a#b -dash null test,"-",2024-02-29,"-",none,no,"-","-","-",none,"-"\n x_y-xr,in_flight,task,"-","lease retry [bracket] parser 100%",no,none,"","-",2025-01-01,"-",none,yes,captain,"tab\\there retry backoff",2500-01-01,none,"-"\n Z-fb,in_flight,task,docs-site,"queue ß cleanup Ünïcode naïve retry queue null Ω naïve gateway index migrate [😀\\n... (truncated, 83 chars total - use show Z-fb --full to see complete text)",no,none,"","-","-","-",none,no,"-","-","-",none,"-"\n Homemux-u1,in_flight,task,widgets,backoff true,no,none,"## Intent\\nß \\u001b[0m adopt quote\\"s rewrite true adopt migrate service null service tab\\there 日本語 naïve lease router naïve null index tab\\there Ω parser lease café [bracket] 日本語 résumé tab\\there cleanup quote\\"s cache cleanup index tab\\there adopt comma,s {brace} queue index router 42 router test naïve quote\\"s flaky widget Ünïcode quote\\"s schema café Ω 100% widget 3.14 -dash index router metrics adopt café 3.14 queue gateway lease adopt Ünïcode cleanup café 100% queue 日本語 a#b 100% service Ω tab\\there rewri\\n... (truncated, 574 chars total - use show Homemux-u1 --full to see complete text)","-","-","-",none,no,"-","-","-",none,"-"\n Z-3g,in_flight,ship,"-","migrate Ünïcode quote\\"s backoff https://github.com/o/r/pulls/3",no,none,"","-","-","-",none,no,external,"{brace}",2000-01-01,"doc:https://github.com/o/r/pulls/3","-"\n x_y-b6,queued,task,"-","[bracket]",no,none,"## Intent\\ntab\\there metrics colon: here -dash metrics tab\\there schema audit widget quote\\"s -dash\\n## Intent\\n\\n extra-indented colon: here\\nwidget cleanup schema gateway café tab\\there migrate spaced ","-","-","-",none,no,"-","-","-",none,2\n gamma-5u,done,docs,"7","spaced -dash quote\\"s naïve spaced router gateway",yes,"Homemux-cu,Homemux-cu","tab\\there ß lease Ω\\n{brace} 日本語 日本語 日本語 rewrite a#b {brace} {brace} rewrite index\\n42 [bracket] test naïve {brace} cache 3.14 100% gateway service\\n## Intent",2026-09-30,"-","-","blocked-by:Homemux-cu,blocked-by:Homemux-cu,parent:Z-3g",no,"-","-","-",none,4\n sm-idle-qv,done,ship,"-","quote\\"s résumé widget true quote\\"s parser tab\\there \\u001b[0m Ω comma,s index cache ad\\n... (truncated, 204 chars total - use show sm-idle-qv --full to see complete text)",no,none,"## Intent\\n## Intent\\na#b 日本語 [bracket] [bracket] index\\na#b 42 spaced retry widget tab\\there index\\nÜnïcode quote\\"s [bracket] router adopt comma,s 日本語 100% Ω café index","-","-","-","parent:x_y-b6",no,"-","-","-",none,4\n x_y-7u,done,task,"-","SHIPPING lease gateway flaky \\u001b[0m",no,none,"",2026-10-01,2025-01-01,"-","discovered-from:Homemux-cu,blocked-by:sm-idle-qv",no,"-","-","-",none,4\n Homemux-3h,done,task,"-",42 null,no,none,"","-",2026-09-30,"-",none,no,"-","-","-",none,2\n x_y-f6,done,secondmate,"-","\\u001b[0m queue 100% widget -dash widget tab\\there audit queue queue cache quote\\"s rew\\n... (truncated, 287 chars total - use show x_y-f6 --full to see complete text)",no,none,"",2026-09-30,2024-02-29,"-",none,no,"-","-","-",none,2\n Z-ft,done,secondmate,widgets,lease 42 metrics backoff 42 spaced retry 3.14 null,no,none,"",2026-09-30,2024-02-29,"-",none,no,"-","-","-",none,"-"\nhelp[2]:\n - Run `tasks-axi show <id> --file=docs/tasks.md` for full notes on a task\n - Run `tasks-axi ready --file=docs/tasks.md` to see unblocked queued work\n + +case seed2/ready +arg ready +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout count: 1\nready[1]{id,state,kind,repo,title}:\n x_y-b6,queued,task,"-","[bracket]"\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi start <id> --file=docs/tasks.md` to dispatch one of these\n + +case seed2/ready-held +arg ready +arg --include-held +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout count: 1\nready[1]{id,state,kind,repo,title}:\n x_y-b6,queued,task,"-","[bracket]"\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi start <id> --file=docs/tasks.md` to dispatch one of these\n + +case seed2/ready-repo +arg ready +arg --repo +arg docs-site +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout count: 0\nready: 0 unblocked queued tasks\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi list --state queued --repo=docs-site --file=docs/tasks.md` to see all queued work (incl. blocked)\n + +case seed2/show-missing +arg show +arg no-such-task +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 1 +stdout error: "Task \\"no-such-task\\" not found in this backlog"\ncode: NOT_FOUND\nhelp[1]: Run `tasks-axi list --file=docs/tasks.md` to see existing tasks\n + +case seed2/show-Z-3g +arg show +arg Z-3g +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout task:\n id: Z-3g\n title: "migrate Ünïcode quote\\"s backoff https://github.com/o/r/pulls/3"\n state: in_flight\n blocked: no\n blocked_by: none\n held: no\n hold_reason: "{brace}"\n hold_kind: external\n hold_until: 2000-01-01\n kind: ship\n repo: "-"\n priority: "-"\n created: "-"\n closed: "-"\n deps: none\n links: "doc:https://github.com/o/r/pulls/3"\n body: ""\n + +case seed2/show-full-Z-3g +arg view +arg Z-3g +arg --full +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout task:\n id: Z-3g\n title: "migrate Ünïcode quote\\"s backoff https://github.com/o/r/pulls/3"\n state: in_flight\n blocked: no\n blocked_by: none\n held: no\n hold_reason: "{brace}"\n hold_kind: external\n hold_until: 2000-01-01\n kind: ship\n repo: "-"\n priority: "-"\n created: "-"\n closed: "-"\n deps: none\n links: "doc:https://github.com/o/r/pulls/3"\n body: ""\n + +case seed2/show-x_y-f6 +arg show +arg x_y-f6 +arg --file +arg docs/tasks.md +file docs/tasks.md b6f052c5ed4c2e15.bin +code 0 +stdout task:\n id: x_y-f6\n title: "\\u001b[0m queue 100% widget -dash widget tab\\there audit queue queue cache quote\\"s rew\\n... (truncated, 287 chars total - use --full to see complete text)"\n state: done\n blocked: no\n blocked_by: none\n held: no\n hold_reason: "-"\n hold_kind: "-"\n hold_until: "-"\n kind: secondmate\n repo: "-"\n priority: 2\n created: 2024-02-29\n closed: 2026-09-30\n deps: none\n links: none\n body: ""\n + +case seed3/list +arg list +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout count: 15\ntasks[15]{id,state,kind,repo,title}:\n beta-9h,in_flight,task,"-","comma,s café a#b -dash backoff comma,s retry quote\\"s 日本語 [bracket] 日本語 adopt -da\\n... (truncated, 162 chars total - use show beta-9h --full to see complete text)"\n x_y-od,in_flight,chore,"-",SHIP -dash schema 日本語 retry cleanup\n a.b-98,in_flight,task,"-","flaky true lease quote\\"s service retry spaced naïve parser adopt index tab\\th\\n... (truncated, 83 chars total - use show a.b-98 --full to see complete text)"\n sm-idle-es.3,in_flight,task,infra,null naïve rewrite 100% gateway café cleanup\n gamma-1f,queued,task,"-","résumé test tab\\there café flaky 日本語 comma,s null lease parser \\u001b[0m test flaky 日本\\n... (truncated, 81 chars total - use show gamma-1f --full to see complete text)"\n beta-kr,done,task,"-","colon: here"\n Z-0j,done,task,"-","true ß gateway ß migrate ß Ünïcode a#b (priority: 9)"\n Homemux-ea,done,task,"-","SCOUTS cleanup metrics {brace} widget"\n fm-x-gl,queued,task,"-","audit spaced spaced migrate null flaky quote\\"s naïve"\n gamma-5g,queued,task,a/b,"lease ß [bracket] parser naïve résumé retry service widget index Ünïcode retry t\\n... (truncated, 160 chars total - use show gamma-5g --full to see complete text)"\n alpha-b4,queued,task,"-","café backoff https://github.com/o/r/pull/42"\n Z-ju,queued,task,"-",retry\n sm-idle-b3,queued,task,"7","[bracket] gateway service café widget backoff \\u001b[0m cache queue null cleanup test\\n... (truncated, 256 chars total - use show sm-idle-b3 --full to see complete text)"\n beta-9h,queued,docs,"-",DOCS-ONLY résumé retry audit\n a.b-fx,queued,task,é-repo,index cache\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case seed3/list-queued +arg list +arg --state +arg queued +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout count: 8\ntasks[8]{id,state,kind,repo,title}:\n gamma-1f,queued,task,"-","résumé test tab\\there café flaky 日本語 comma,s null lease parser \\u001b[0m test flaky 日本\\n... (truncated, 81 chars total - use show gamma-1f --full to see complete text)"\n fm-x-gl,queued,task,"-","audit spaced spaced migrate null flaky quote\\"s naïve"\n gamma-5g,queued,task,a/b,"lease ß [bracket] parser naïve résumé retry service widget index Ünïcode retry t\\n... (truncated, 160 chars total - use show gamma-5g --full to see complete text)"\n alpha-b4,queued,task,"-","café backoff https://github.com/o/r/pull/42"\n Z-ju,queued,task,"-",retry\n sm-idle-b3,queued,task,"7","[bracket] gateway service café widget backoff \\u001b[0m cache queue null cleanup test\\n... (truncated, 256 chars total - use show sm-idle-b3 --full to see complete text)"\n beta-9h,queued,docs,"-",DOCS-ONLY résumé retry audit\n a.b-fx,queued,task,é-repo,index cache\nhelp[1]:\n - Run `tasks-axi show <id>` for full notes on a task\n + +case seed3/list-held +arg list +arg --state +arg held +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout count: 6\ntasks[6]{id,state,kind,repo,title}:\n beta-9h,in_flight,task,"-","comma,s café a#b -dash backoff comma,s retry quote\\"s 日本語 [bracket] 日本語 adopt -da\\n... (truncated, 162 chars total - use show beta-9h --full to see complete text)"\n x_y-od,in_flight,chore,"-",SHIP -dash schema 日本語 retry cleanup\n a.b-98,in_flight,task,"-","flaky true lease quote\\"s service retry spaced naïve parser adopt index tab\\th\\n... (truncated, 83 chars total - use show a.b-98 --full to see complete text)"\n alpha-b4,queued,task,"-","café backoff https://github.com/o/r/pull/42"\n sm-idle-b3,queued,task,"7","[bracket] gateway service café widget backoff \\u001b[0m cache queue null cleanup test\\n... (truncated, 256 chars total - use show sm-idle-b3 --full to see complete text)"\n beta-9h,queued,docs,"-",DOCS-ONLY résumé retry audit\nhelp[1]:\n - Run `tasks-axi show <id>` for full notes on a task\n + +case seed3/list-blocked +arg list +arg --blocked +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout count: 2\ntasks[2]{id,state,kind,repo,title}:\n sm-idle-es.3,in_flight,task,infra,null naïve rewrite 100% gateway café cleanup\n Z-ju,queued,task,"-",retry\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case seed3/list-limit1 +arg list +arg --limit +arg 1 +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout count: 1 of 15 total\ntasks[1]{id,state,kind,repo,title}:\n beta-9h,in_flight,task,"-","comma,s café a#b -dash backoff comma,s retry quote\\"s 日本語 [bracket] 日本語 adopt -da\\n... (truncated, 162 chars total - use show beta-9h --full to see complete text)"\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case seed3/list-allfields +arg list +arg --fields +arg blocked,blocked_by,body,closed,created,delivery_state,deps,held,hold_kind,hold_reason,hold_until,links,priority +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout count: 15\ntasks[15]{id,state,kind,repo,title,blocked,blocked_by,body,closed,created,delivery_state,deps,held,hold_kind,hold_reason,hold_until,links,priority}:\n beta-9h,in_flight,task,"-","comma,s café a#b -dash backoff comma,s retry quote\\"s 日本語 [bracket] 日本語 adopt -da\\n... (truncated, 162 chars total - use show beta-9h --full to see complete text)",no,none,"","-","-","-",none,yes,load,"{brace} flaky",2500-01-01,none,"-"\n x_y-od,in_flight,chore,"-",SHIP -dash schema 日本語 retry cleanup,no,none,"","-",2026-10-02,"-",none,yes,"-",résumé spaced spaced,3000-06-15,none,"-"\n a.b-98,in_flight,task,"-","flaky true lease quote\\"s service retry spaced naïve parser adopt index tab\\th\\n... (truncated, 83 chars total - use show a.b-98 --full to see complete text)",no,none,"\\na,b\\n spaced rewrite service parser cache -dash 100% {brace} metrics widget schema migrate cache cache flaky queue adopt 日本語 cleanup metrics 3.14 true true retry backoff audit gateway 100% adopt gateway router spaced backoff Ünïcode index ß [bracket] lease spaced backoff rewrite adopt café quote\\"s -dash 日本語 Ünïcode -dash résumé -dash -dash Ω audit ß 3.14 naïve gateway index Ünïcode gateway Ω -dash parser a#b tab\\there backoff queue null colon: here test true flaky [bracket] test schema\\n... (truncated, 1076 chars total - use show a.b-98 --full to see complete text)","-",2026-09-30,"-",none,yes,"-","ß colon: here backoff",3000-06-15,none,"-"\n sm-idle-es.3,in_flight,task,infra,null naïve rewrite 100% gateway café cleanup,yes,a.b-98,"","-",2024-02-29,"-","blocked-by:a.b-98",no,"-","-","-",none,"-"\n gamma-1f,queued,task,"-","résumé test tab\\there café flaky 日本語 comma,s null lease parser \\u001b[0m test flaky 日本\\n... (truncated, 81 chars total - use show gamma-1f --full to see complete text)",no,none,"","-","-","-",none,no,"-","-","-",none,"-"\n beta-kr,done,task,"-","colon: here",no,none,"audit a#b naïve\\nnull cache {brace} service naïve gateway widget parser backoff cache retry comma,s backoff schema flaky [bracket] parser 3.14 backoff \\u001b[0m naïve colon: here null quote\\"s [bracket] audit 42 colon: here résumé Ω a#b widget colon: here résumé colon: here adopt flaky router comma,s tab\\there cache quote\\"s café flaky metrics lease spaced audit schema 100% parser flaky index Ünïcode audit test 100% cache comma,s spaced backoff {brace} 42 index metrics 100% 100% 42 metrics 3.14 a\\n... (truncated, 579 chars total - use show beta-kr --full to see complete text)","-",2024-02-29,"-",none,no,"-","-","-",none,"-"\n Z-0j,done,task,"-","true ß gateway ß migrate ß Ünïcode a#b (priority: 9)",no,none," extra-indented tab\\there\\n100% index colon: here test backoff adopt \\u001b[0m\\n\\nindex test widget true audit spaced \\nretry naïve index cache 42 metrics backoff gateway naïve parser true colon: here audit \\u001b[0m Ω retry a#b tab\\there 日本語 adopt 100% café test backoff ß Ω tab\\there cleanup gateway widget -dash 3.14 \\u001b[0m spaced rewrite {brace} \\u001b[0m router 日本語 日本語 Ω résumé metrics flaky migrate adopt cleanup [bracket] spaced tab\\there rewrite colon: here \\u001b[0m true retry queue lease metrics \\u001b[0m cache \\n... (truncated, 610 chars total - use show Z-0j --full to see complete text)",2026-09-30,"-","-",none,no,"-","-","-",none,"-"\n Homemux-ea,done,task,"-","SCOUTS cleanup metrics {brace} widget",no,none,"Ω quote\\"s null queue Ω audit tab\\there ß spaced comma,s 3.14 100%\\n## Intent\\n extra-indented a#b",2026-10-02,"-","-",none,no,"-","-","-",none,"-"\n fm-x-gl,queued,task,"-","audit spaced spaced migrate null flaky quote\\"s naïve",no,none,"\\u001b[0m ß Ω audit tab\\there tab\\there queue\\n## Intent","-",2026-10-01,"-",none,no,"-","-","-",none,"-"\n gamma-5g,queued,task,a/b,"lease ß [bracket] parser naïve résumé retry service widget index Ünïcode retry t\\n... (truncated, 160 chars total - use show gamma-5g --full to see complete text)",no,none,"","-","-","-",none,no,"-","-","-",none,3\n alpha-b4,queued,task,"-","café backoff https://github.com/o/r/pull/42",no,none,"","-","-","-",none,yes,"-",queue cache,"-","pr:https://github.com/o/r/pull/42",2\n Z-ju,queued,task,"-",retry,yes,x_y-od,"{x}\\n\\u001b[0m gateway index Ünïcode true tab\\there audit index spaced 日本語 résumé 42 metrics comma,s [bracket] colon: here metrics cleanup metrics parser Ünïcode retry 日本語 \\u001b[0m Ünïcode cache colon: here test tab\\there null comma,s résumé colon: here null retry 42 Ünïcode retry Ünïcode {brace} true cleanup test cache index 42 backoff résumé 42 index café -dash [bracket] 日本語 metrics 3.14 42 cache lease 42 quote\\"s comma,s migrate 100% spaced [bracket] 42 日本語 a#b colon: here ß widget queue 42 adopt \\n... (truncated, 538 chars total - use show Z-ju --full to see complete text)","-",2026-09-30,"-","blocked-by:x_y-od,blocked-by:Z-0j",no,"-","-","-",none,"-"\n sm-idle-b3,queued,task,"7","[bracket] gateway service café widget backoff \\u001b[0m cache queue null cleanup test\\n... (truncated, 256 chars total - use show sm-idle-b3 --full to see complete text)",no,none,gateway a#b 42 日本語 a#b widget widget,"-",2026-10-01,"-",none,yes,"-","index queue colon: here","-",none,"-"\n beta-9h,queued,docs,"-",DOCS-ONLY résumé retry audit,no,none,"1.\\n extra-indented résumé\\na#b 3.14 100% quote\\"s null index ß audit\\nmetrics comma,s true rewrite \\u001b[0m {brace} colon: here\\n1e5","-","-","-",none,no,"-","-","-",none,"-"\n a.b-fx,queued,task,é-repo,index cache,no,none,"retry a#b naïve quote\\"s router audit 42 café","-",2025-01-01,"-",none,no,captain,"null",2001-06-15,none,"-"\nhelp[2]:\n - Run `tasks-axi show <id>` for full notes on a task\n - Run `tasks-axi ready` to see unblocked queued work\n + +case seed3/ready +arg ready +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout count: 5\nready[5]{id,state,kind,repo,title}:\n gamma-1f,queued,task,"-","résumé test tab\\there café flaky 日本語 comma,s null lease parser \\u001b[0m test flaky 日本\\n... (truncated, 81 chars total - use show gamma-1f --full to see complete text)"\n fm-x-gl,queued,task,"-","audit spaced spaced migrate null flaky quote\\"s naïve"\n gamma-5g,queued,task,a/b,"lease ß [bracket] parser naïve résumé retry service widget index Ünïcode retry t\\n... (truncated, 160 chars total - use show gamma-5g --full to see complete text)"\n beta-9h,queued,docs,"-",DOCS-ONLY résumé retry audit\n a.b-fx,queued,task,é-repo,index cache\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi start <id>` to dispatch one of these\n + +case seed3/ready-held +arg ready +arg --include-held +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout count: 5\nready[5]{id,state,kind,repo,title}:\n gamma-1f,queued,task,"-","résumé test tab\\there café flaky 日本語 comma,s null lease parser \\u001b[0m test flaky 日本\\n... (truncated, 81 chars total - use show gamma-1f --full to see complete text)"\n fm-x-gl,queued,task,"-","audit spaced spaced migrate null flaky quote\\"s naïve"\n gamma-5g,queued,task,a/b,"lease ß [bracket] parser naïve résumé retry service widget index Ünïcode retry t\\n... (truncated, 160 chars total - use show gamma-5g --full to see complete text)"\n beta-9h,queued,docs,"-",DOCS-ONLY résumé retry audit\n a.b-fx,queued,task,é-repo,index cache\nready_public_followups: 0 delivery-ready obligations\nheld[2]{id,state,kind,repo,title,hold_reason,hold_kind,hold_until}:\n alpha-b4,queued,task,"-","café backoff https://github.com/o/r/pull/42",queue cache,"-","-"\n sm-idle-b3,queued,task,"7","[bracket] gateway service café widget backoff \\u001b[0m cache queue null cleanup test\\n... (truncated, 256 chars total - use show sm-idle-b3 --full to see complete text)","index queue colon: here","-","-"\nhelp[1]:\n - Run `tasks-axi start <id>` to dispatch one of these\n + +case seed3/ready-repo +arg ready +arg --repo +arg infra +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout count: 0\nready: 0 unblocked queued tasks\nready_public_followups: 0 delivery-ready obligations\nhelp[1]:\n - Run `tasks-axi list --state queued --repo=infra` to see all queued work (incl. blocked)\n + +case seed3/show-missing +arg show +arg no-such-task +file backlog.md 4d0a2052951fe95d.bin +code 1 +stdout error: "Task \\"no-such-task\\" not found in this backlog"\ncode: NOT_FOUND\nhelp[1]: Run `tasks-axi list` to see existing tasks\n + +case seed3/show-Z-ju +arg show +arg Z-ju +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout task:\n id: Z-ju\n title: retry\n state: queued\n blocked: yes\n blocked_by: x_y-od\n held: no\n hold_reason: "-"\n hold_kind: "-"\n hold_until: "-"\n kind: task\n repo: "-"\n priority: "-"\n created: 2026-09-30\n closed: "-"\n deps: "blocked-by:x_y-od,blocked-by:Z-0j"\n links: none\n body: "{x}\\n\\u001b[0m gateway index Ünïcode true tab\\there audit index spaced 日本語 résumé 42 metrics comma,s [bracket] colon: here metrics cleanup metrics parser Ünïcode retry 日本語 \\u001b[0m Ünïcode cache colon: here test tab\\there null comma,s résumé colon: here null retry 42 Ünïcode retry Ünïcode {brace} true cleanup test cache index 42 backoff résumé 42 index café -dash [bracket] 日本語 metrics 3.14 42 cache lease 42 quote\\"s comma,s migrate 100% spaced [bracket] 42 日本語 a#b colon: here ß widget queue 42 adopt \\n... (truncated, 538 chars total - use --full to see complete text)"\nhelp[2]:\n - Run `tasks-axi unblock Z-ju --by <other>` to clear a blocker\n - Run `tasks-axi start Z-ju` to move it to in flight\n + +case seed3/show-full-Z-ju +arg view +arg Z-ju +arg --full +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout task:\n id: Z-ju\n title: retry\n state: queued\n blocked: yes\n blocked_by: x_y-od\n held: no\n hold_reason: "-"\n hold_kind: "-"\n hold_until: "-"\n kind: task\n repo: "-"\n priority: "-"\n created: 2026-09-30\n closed: "-"\n deps: "blocked-by:x_y-od,blocked-by:Z-0j"\n links: none\n body: "{x}\\n\\u001b[0m gateway index Ünïcode true tab\\there audit index spaced 日本語 résumé 42 metrics comma,s [bracket] colon: here metrics cleanup metrics parser Ünïcode retry 日本語 \\u001b[0m Ünïcode cache colon: here test tab\\there null comma,s résumé colon: here null retry 42 Ünïcode retry Ünïcode {brace} true cleanup test cache index 42 backoff résumé 42 index café -dash [bracket] 日本語 metrics 3.14 42 cache lease 42 quote\\"s comma,s migrate 100% spaced [bracket] 42 日本語 a#b colon: here ß widget queue 42 adopt 42😀a\\n## Intent\\n\\n extra-indented index"\nhelp[2]:\n - Run `tasks-axi unblock Z-ju --by <other>` to clear a blocker\n - Run `tasks-axi start Z-ju` to move it to in flight\n + +case seed3/show-beta-kr +arg show +arg beta-kr +file backlog.md 4d0a2052951fe95d.bin +code 0 +stdout task:\n id: beta-kr\n title: "colon: here"\n state: done\n blocked: no\n blocked_by: none\n held: no\n hold_reason: "-"\n hold_kind: "-"\n hold_until: "-"\n kind: task\n repo: "-"\n priority: "-"\n created: 2024-02-29\n closed: "-"\n deps: none\n links: none\n body: "audit a#b naïve\\nnull cache {brace} service naïve gateway widget parser backoff cache retry comma,s backoff schema flaky [bracket] parser 3.14 backoff \\u001b[0m naïve colon: here null quote\\"s [bracket] audit 42 colon: here résumé Ω a#b widget colon: here résumé colon: here adopt flaky router comma,s tab\\there cache quote\\"s café flaky metrics lease spaced audit schema 100% parser flaky index Ünïcode audit test 100% cache comma,s spaced backoff {brace} 42 index metrics 100% 100% 42 metrics 3.14 a\\n... (truncated, 579 chars total - use --full to see complete text)"\n + diff --git a/examples/tasks-axi-rust/crates/toon/Cargo.toml b/examples/tasks-axi-rust/crates/toon/Cargo.toml new file mode 100644 index 0000000000..4a2dc84389 --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "toon-encode" +version = "0.1.0" +edition = "2021" +description = "A std-only TOON v4.1 encoder" +license = "Apache-2.0" +publish = false + +[lib] +name = "toon_encode" +path = "src/lib.rs" + +[dependencies] diff --git a/examples/tasks-axi-rust/crates/toon/README.md b/examples/tasks-axi-rust/crates/toon/README.md new file mode 100644 index 0000000000..87c4646e4d --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/README.md @@ -0,0 +1,28 @@ +# toon-encode + +A TOON (Token-Oriented Object Notation) v4.1 encoder in Rust. It is std-only: +the crate has zero dependencies. + +It encodes a JSON-shaped `Value` (null, bool, integer, float, string, array, +insertion-ordered object) as inline primitive arrays, tabular arrays, keyed +tabular objects or list form, with comma, tab or pipe delimiters and a +configurable indent. Output has no trailing newline. + +```rust +use toon_encode::{encode, Value}; +let v = Value::Object(vec![("n".into(), Value::Int(1))]); +assert_eq!(encode(&v), "n: 1"); +``` + +## Verification + +`tests/conformance.rs` runs all 179 cases of the 9 official encode fixtures +(vendored byte-for-byte under `tests/fixtures/`, see `PROVENANCE.md`) and +requires every one to pass. It also asserts the case count, so a fixture that +stops being collected fails the suite instead of shrinking the score. Unit tests +in `src/lib.rs` cover the quoting and number rules. + +## Hand-written by design + +This is a hand-written runtime. The encoder is deliberately not generated from a +model. diff --git a/examples/tasks-axi-rust/crates/toon/src/lib.rs b/examples/tasks-axi-rust/crates/toon/src/lib.rs new file mode 100644 index 0000000000..8a53399d84 --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/src/lib.rs @@ -0,0 +1,620 @@ +//! A strict, std-only encoder for TOON (Token-Oriented Object Notation) v4.1. +//! +//! Covers objects, inline primitive arrays, tabular arrays, keyed tabular +//! objects and list form, for the JSON data model. + +/// A JSON-shaped value. Object keys keep insertion order. +#[derive(Debug, Clone, PartialEq)] +pub enum Value { + Null, + Bool(bool), + Int(i64), + Num(f64), + Str(String), + Array(Vec<Value>), + Object(Vec<(String, Value)>), +} + +/// Delimiter used between array values and tabular cells. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Delimiter { + Comma, + Tab, + Pipe, +} + +impl Delimiter { + fn ch(self) -> char { + match self { + Delimiter::Comma => ',', + Delimiter::Tab => '\t', + Delimiter::Pipe => '|', + } + } + + /// The symbol shown inside a bracket segment; comma is spelled by omission. + fn symbol(self) -> &'static str { + match self { + Delimiter::Comma => "", + Delimiter::Tab => "\t", + Delimiter::Pipe => "|", + } + } +} + +/// Which encoder's string-quoting rules to follow. +/// +/// The spec's own rules and the ones the `@toon-format/toon` 2.3.x library ships differ in three +/// places, and a tool that must print what that library prints needs the second set. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Dialect { + /// Spec v4.1.1 (the conformance fixtures): a string starting with `#` is quoted, a leading `+` + /// makes a string numeric-like, and padding means a space or tab. + Spec, + /// `@toon-format/toon` 2.3.x: `#` is not special, `+1` is not numeric-like, and padding is + /// anything JavaScript's `String.prototype.trim` strips. + ToonJs2, +} + +/// Encoder options. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Options { + pub indent: usize, + pub delimiter: Delimiter, + pub dialect: Dialect, +} + +impl Default for Options { + fn default() -> Self { + Options { + indent: 2, + delimiter: Delimiter::Comma, + dialect: Dialect::Spec, + } + } +} + +/// JavaScript's `\s` set, which `String.prototype.trim` strips. +fn is_js_space(c: char) -> bool { + matches!( + c, + '\t' | '\n' | '\u{b}' | '\u{c}' | '\r' | ' ' | '\u{a0}' | '\u{1680}' | '\u{2000}' + ..='\u{200a}' + | '\u{2028}' + | '\u{2029}' + | '\u{202f}' + | '\u{205f}' + | '\u{3000}' + | '\u{feff}' + ) +} + +/// Encode with default options. No trailing newline. +pub fn encode(value: &Value) -> String { + encode_with(value, &Options::default()) +} + +/// Encode with explicit options. No trailing newline. +pub fn encode_with(value: &Value, opts: &Options) -> String { + Encoder { opts: *opts }.root(value).join("\n") +} + +/// Encode one primitive as it would appear as a field value (comma delimiter). +/// Non-primitives encode as `null`. +pub fn encode_scalar(value: &Value) -> String { + encode_scalar_with(value, &Options::default()) +} + +/// [`encode_scalar`] with explicit options. +pub fn encode_scalar_with(value: &Value, opts: &Options) -> String { + Encoder { opts: *opts }.primitive(value) +} + +/// Header columns: a name plus, for a nested-uniform column, its own columns. +type Fields = Vec<Field>; + +struct Field { + name: String, + nested: Option<Fields>, +} + +fn is_primitive(v: &Value) -> bool { + !matches!(v, Value::Array(_) | Value::Object(_)) +} + +fn lookup<'a>(obj: &'a [(String, Value)], name: &str) -> &'a Value { + obj.iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v) + .unwrap_or(&Value::Null) +} + +fn is_bare_key(s: &str) -> bool { + let mut chars = s.chars(); + match chars.next() { + Some(c) if c.is_ascii_alphabetic() || c == '_' => {} + _ => return false, + } + chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.') +} + +/// Section 7.2: would this string be read back as a number? +fn is_numeric_like(s: &str, dialect: Dialect) -> bool { + let b = s.as_bytes(); + let mut i = 0; + let signs: &[u8] = match dialect { + Dialect::Spec => b"+-", + Dialect::ToonJs2 => b"-", + }; + if i < b.len() && signs.contains(&b[i]) { + i += 1; + } + let digits = |i: &mut usize| { + let start = *i; + while *i < b.len() && b[*i].is_ascii_digit() { + *i += 1; + } + *i > start + }; + if !digits(&mut i) { + return false; + } + if i < b.len() && b[i] == b'.' { + i += 1; + if !digits(&mut i) { + return false; + } + } + if i < b.len() && (b[i] == b'e' || b[i] == b'E') { + i += 1; + if i < b.len() && (b[i] == b'+' || b[i] == b'-') { + i += 1; + } + if !digits(&mut i) { + return false; + } + } + i == b.len() +} + +fn quote(s: &str) -> String { + let mut out = String::with_capacity(s.len() + 2); + out.push('"'); + for ch in s.chars() { + match ch { + '\\' => out.push_str("\\\\"), + '"' => out.push_str("\\\""), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)), + c => out.push(c), + } + } + out.push('"'); + out +} + +/// Section 2: canonical decimal form for 0 and 1e-6 <= |x| < 1e21. +fn format_number(v: f64) -> String { + if !v.is_finite() { + return "null".to_string(); + } + if v == 0.0 { + return "0".to_string(); + } + let a = v.abs(); + if (1e-6..1e21).contains(&a) { + // Display prints the shortest round-tripping digits and never uses an + // exponent; an integral value prints without a fractional part. + return format!("{v}"); + } + // Exponent notation is permitted outside the canonical range. + let s = format!("{v:e}"); + match s.split_once('e') { + Some((m, e)) if !e.starts_with('-') => format!("{m}e+{e}"), + _ => s, + } +} + +struct Encoder { + opts: Options, +} + +impl Encoder { + fn delim(&self) -> char { + self.opts.delimiter.ch() + } + + fn pad(&self, depth: usize) -> String { + " ".repeat(self.opts.indent * depth) + } + + fn primitive(&self, v: &Value) -> String { + match v { + Value::Null => "null".into(), + Value::Bool(true) => "true".into(), + Value::Bool(false) => "false".into(), + Value::Int(i) => i.to_string(), + Value::Num(n) => format_number(*n), + Value::Str(s) => self.string(s), + _ => "null".into(), + } + } + + fn string(&self, s: &str) -> String { + if self.needs_quote(s) { + quote(s) + } else { + s.to_string() + } + } + + fn needs_quote(&self, s: &str) -> bool { + let padded = match self.opts.dialect { + Dialect::Spec => s.starts_with([' ', '\t']) || s.ends_with([' ', '\t']), + Dialect::ToonJs2 => s.starts_with(is_js_space) || s.ends_with(is_js_space), + }; + let hash = self.opts.dialect == Dialect::Spec && s.starts_with('#'); + s.is_empty() + || padded + || matches!(s, "true" | "false" | "null") + || is_numeric_like(s, self.opts.dialect) + || s.chars().any(|c| { + matches!(c, ':' | '"' | '\\' | '[' | ']' | '{' | '}') + || (c as u32) < 0x20 + || c == self.delim() + }) + || hash + || s.starts_with('-') + } + + fn key(&self, name: &str) -> String { + if is_bare_key(name) { + name.to_string() + } else { + quote(name) + } + } + + fn bracket(&self, len: usize, keyed: bool) -> String { + let marker = if keyed { + format!("{len}:") + } else { + len.to_string() + }; + format!("[{marker}{}]", self.opts.delimiter.symbol()) + } + + fn field_list(&self, fields: &Fields) -> String { + let d = self.delim().to_string(); + fields + .iter() + .map(|f| match &f.nested { + None => self.key(&f.name), + Some(n) => format!("{}{{{}}}", self.key(&f.name), self.field_list(n)), + }) + .collect::<Vec<_>>() + .join(&d) + } + + fn tabular_fields(&self, items: &[&Value]) -> Option<Fields> { + if items.is_empty() { + return None; + } + let mut objs = Vec::with_capacity(items.len()); + for item in items { + match item { + Value::Object(o) if !o.is_empty() => objs.push(o), + _ => return None, + } + } + let first = objs[0]; + let same_keys = |o: &[(String, Value)]| { + o.len() == first.len() + && o.iter().all(|(k, _)| first.iter().any(|(k2, _)| k2 == k)) + && first.iter().all(|(k, _)| o.iter().any(|(k2, _)| k2 == k)) + }; + if !objs.iter().all(|o| same_keys(o)) { + return None; + } + let mut fields = Fields::new(); + for (name, _) in first { + let column: Vec<&Value> = objs.iter().map(|o| lookup(o, name)).collect(); + if column.iter().all(|v| is_primitive(v)) { + fields.push(Field { + name: name.clone(), + nested: None, + }); + } else { + fields.push(Field { + name: name.clone(), + nested: Some(self.tabular_fields(&column)?), + }); + } + } + Some(fields) + } + + fn keyed_fields(&self, obj: &[(String, Value)]) -> Option<Fields> { + if obj.len() < 2 { + return None; + } + let vals: Vec<&Value> = obj.iter().map(|(_, v)| v).collect(); + self.tabular_fields(&vals) + } + + fn cells(&self, obj: &[(String, Value)], fields: &Fields, out: &mut Vec<String>) { + for f in fields { + let v = lookup(obj, &f.name); + match (&f.nested, v) { + (None, v) => out.push(self.primitive(v)), + (Some(n), Value::Object(o)) => self.cells(o, n, out), + _ => {} + } + } + } + + fn row(&self, v: &Value, fields: &Fields) -> String { + let mut cells = Vec::new(); + if let Value::Object(o) = v { + self.cells(o, fields, &mut cells); + } + cells.join(&self.delim().to_string()) + } + + fn keyed_block( + &self, + head_prefix: &str, + obj: &[(String, Value)], + fields: &Fields, + depth: usize, + ) -> Vec<String> { + let mut lines = vec![format!( + "{head_prefix}{}{{{}}}:", + self.bracket(obj.len(), true), + self.field_list(fields) + )]; + for (k, v) in obj { + lines.push(format!( + "{}{}: {}", + self.pad(depth + 1), + self.key(k), + self.row(v, fields) + )); + } + lines + } + + fn root(&self, v: &Value) -> Vec<String> { + match v { + Value::Object(o) => { + if o.is_empty() { + return Vec::new(); + } + if let Some(f) = self.keyed_fields(o) { + return self.keyed_block("", o, &f, 0); + } + self.object_body(o, 0) + } + Value::Array(a) => self.array(None, a, 0, true), + _ => vec![self.primitive(v)], + } + } + + fn object_body(&self, obj: &[(String, Value)], depth: usize) -> Vec<String> { + obj.iter() + .flat_map(|(k, v)| self.field(k, v, depth)) + .collect() + } + + fn field(&self, name: &str, v: &Value, depth: usize) -> Vec<String> { + let pad = self.pad(depth); + let key = self.key(name); + match v { + Value::Array(a) => self.array(Some(&key), a, depth, true), + Value::Object(o) => { + if o.is_empty() { + return vec![format!("{pad}{key}:")]; + } + if let Some(f) = self.keyed_fields(o) { + return self.keyed_block(&format!("{pad}{key}"), o, &f, depth); + } + let mut lines = vec![format!("{pad}{key}:")]; + lines.extend(self.object_body(o, depth + 1)); + lines + } + _ => vec![format!("{pad}{key}: {}", self.primitive(v))], + } + } + + fn array( + &self, + key: Option<&str>, + items: &[Value], + depth: usize, + allow_tabular: bool, + ) -> Vec<String> { + let pad = self.pad(depth); + let prefix = key.unwrap_or(""); + if items.is_empty() { + return vec![match key { + Some(k) => format!("{pad}{k}: []"), + None => format!("{pad}[]"), + }]; + } + let bracket = self.bracket(items.len(), false); + if items.iter().all(is_primitive) { + let vals: Vec<String> = items.iter().map(|i| self.primitive(i)).collect(); + return vec![format!( + "{pad}{prefix}{bracket}: {}", + vals.join(&self.delim().to_string()) + )]; + } + if allow_tabular { + let refs: Vec<&Value> = items.iter().collect(); + if let Some(fields) = self.tabular_fields(&refs) { + let mut lines = vec![format!( + "{pad}{prefix}{bracket}{{{}}}:", + self.field_list(&fields) + )]; + for item in items { + lines.push(format!( + "{}{}", + self.pad(depth + 1), + self.row(item, &fields) + )); + } + return lines; + } + } + let mut lines = vec![format!("{pad}{prefix}{bracket}:")]; + for item in items { + lines.extend(self.list_item(item, depth + 1)); + } + lines + } + + fn list_item(&self, v: &Value, depth: usize) -> Vec<String> { + let pad = self.pad(depth); + match v { + Value::Array(a) => { + if a.is_empty() { + return vec![format!("{pad}- {}:", self.bracket(0, false))]; + } + self.hyphenate(self.array(None, a, depth, false), depth, depth) + } + Value::Object(o) => { + let Some((first, first_v)) = o.first() else { + return vec![format!("{pad}-")]; + }; + let mut lines = + self.hyphenate(self.field(first, first_v, depth + 1), depth, depth + 1); + for (k, val) in &o[1..] { + lines.extend(self.field(k, val, depth + 1)); + } + lines + } + _ => vec![format!("{pad}- {}", self.primitive(v))], + } + } + + /// Move the first line onto a `- ` marker at `marker_depth`. + fn hyphenate(&self, lines: Vec<String>, marker_depth: usize, head_depth: usize) -> Vec<String> { + let mut it = lines.into_iter(); + let head = it.next().unwrap_or_default(); + let rest = &head[self.pad(head_depth).len()..]; + let mut out = vec![format!("{}- {rest}", self.pad(marker_depth))]; + out.extend(it); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn s(x: &str) -> String { + encode_scalar(&Value::Str(x.into())) + } + + #[test] + fn plain_strings_stay_bare() { + assert_eq!(s("hello world"), "hello world"); + assert_eq!(s("a-b"), "a-b"); + assert_eq!(s("é"), "é"); + } + + #[test] + fn reserved_and_numeric_like_are_quoted() { + for v in [ + "", "true", "false", "null", "42", "-3.5", "1e5", "+7", "1E-2", + ] { + assert_eq!(s(v), format!("\"{v}\""), "{v}"); + } + assert_eq!(s("1.2.3"), "1.2.3"); + assert_eq!(s("1."), "1."); + } + + #[test] + fn structural_and_edge_chars_are_quoted() { + assert_eq!(s("a:b"), "\"a:b\""); + assert_eq!(s(" x"), "\" x\""); + assert_eq!(s("x "), "\"x \""); + assert_eq!(s("-x"), "\"-x\""); + assert_eq!(s("#x"), "\"#x\""); + assert_eq!(s("a,b"), "\"a,b\""); + assert_eq!(s("[x]"), "\"[x]\""); + assert_eq!(s("a\nb"), "\"a\\nb\""); + assert_eq!(s("a\u{1}b"), "\"a\\u0001b\""); + assert_eq!(s("q\"b\\"), "\"q\\\"b\\\\\""); + } + + #[test] + fn delimiter_quoting_is_delimiter_aware() { + let v = Value::Array(vec![Value::Str("a|b".into()), Value::Str("c,d".into())]); + let o = Options { + delimiter: Delimiter::Pipe, + ..Options::default() + }; + assert_eq!(encode_with(&v, &o), "[2|]: \"a|b\"|c,d"); + } + + #[test] + fn keys_quote_unless_bare() { + let v = Value::Object(vec![ + ("ok_key.1".into(), Value::Int(1)), + ("a b".into(), Value::Int(2)), + ("1x".into(), Value::Int(3)), + ]); + assert_eq!(encode(&v), "ok_key.1: 1\n\"a b\": 2\n\"1x\": 3"); + } + + #[test] + fn numbers() { + let n = |x: f64| encode_scalar(&Value::Num(x)); + assert_eq!(n(1.0), "1"); + assert_eq!(n(-0.0), "0"); + assert_eq!(n(1.5), "1.5"); + assert_eq!(n(1e-6), "0.000001"); + assert_eq!(n(1e20), "100000000000000000000"); + assert_eq!(n(1e21), "1e+21"); + assert_eq!(n(1e-7), "1e-7"); + assert_eq!(n(f64::NAN), "null"); + assert_eq!(n(f64::INFINITY), "null"); + assert_eq!(encode_scalar(&Value::Int(-5)), "-5"); + } + + #[test] + fn empty_object_root_is_empty() { + assert_eq!(encode(&Value::Object(vec![])), ""); + } +} + +#[cfg(test)] +mod dialect_tests { + use super::*; + + fn js(s: &str) -> String { + let opts = Options { + dialect: Dialect::ToonJs2, + ..Options::default() + }; + encode_scalar_with(&Value::Str(s.to_string()), &opts) + } + + #[test] + fn the_js_library_does_not_quote_a_leading_hash_or_plus_number() { + assert_eq!(js("## Intent"), "## Intent"); + assert_eq!(js("+1"), "+1"); + assert_eq!(encode_scalar(&Value::Str("#x".into())), "\"#x\""); + assert_eq!(encode_scalar(&Value::Str("+1".into())), "\"+1\""); + } + + #[test] + fn the_js_library_pads_with_every_trimmed_character() { + assert_eq!(js("\u{a0}x"), "\"\u{a0}x\""); + assert_eq!(js("x\u{feff}"), "\"x\u{feff}\""); + assert_eq!(js("\u{85}x"), "\u{85}x"); + } +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/conformance.rs b/examples/tasks-axi-rust/crates/toon/tests/conformance.rs new file mode 100644 index 0000000000..49f3258545 --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/conformance.rs @@ -0,0 +1,92 @@ +//! Runs every case of every official encode fixture through the encoder. + +mod support { + pub mod json; +} + +use std::fs; +use std::path::PathBuf; +use toon_encode::{encode_with, Delimiter, Options, Value}; + +const EXPECTED_CASES: usize = 179; + +fn get<'a>(obj: &'a [(String, Value)], key: &str) -> Option<&'a Value> { + obj.iter().find(|(k, _)| k == key).map(|(_, v)| v) +} + +fn options(case: &[(String, Value)]) -> Options { + let mut o = Options::default(); + if let Some(Value::Object(opts)) = get(case, "options") { + for (k, v) in opts { + match (k.as_str(), v) { + ("delimiter", Value::Str(d)) => { + o.delimiter = match d.as_str() { + "," => Delimiter::Comma, + "\t" => Delimiter::Tab, + "|" => Delimiter::Pipe, + other => panic!("unknown delimiter {other:?}"), + } + } + ("indentSize", Value::Int(n)) => o.indent = *n as usize, + _ => panic!("fixture option {k:?} is not applied by this suite"), + } + } + } + o +} + +#[test] +fn official_encode_fixtures() { + let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/encode"); + let mut files: Vec<_> = fs::read_dir(&dir) + .expect("fixture dir") + .map(|e| e.expect("entry").path()) + .filter(|p| p.extension().is_some_and(|e| e == "json")) + .collect(); + files.sort(); + assert_eq!(files.len(), 9, "expected 9 fixture files"); + + let (mut total, mut failures) = (0usize, Vec::new()); + for path in &files { + let fname = path.file_name().unwrap().to_string_lossy().into_owned(); + let doc = support::json::parse(&fs::read_to_string(path).unwrap()) + .unwrap_or_else(|e| panic!("{fname}: {e}")); + let Value::Object(doc) = doc else { + panic!("{fname}: not an object") + }; + let Some(Value::Array(tests)) = get(&doc, "tests") else { + panic!("{fname}: no tests array") + }; + for case in tests { + let Value::Object(case) = case else { + panic!("{fname}: bad case") + }; + let name = match get(case, "name") { + Some(Value::Str(n)) => n.clone(), + _ => panic!("{fname}: case without name"), + }; + assert!( + !matches!(get(case, "shouldError"), Some(Value::Bool(true))), + "{fname}/{name}: error cases are not supported" + ); + let input = get(case, "input").expect("input"); + let Some(Value::Str(expected)) = get(case, "expected") else { + panic!("{fname}/{name}: no expected string") + }; + total += 1; + let got = encode_with(input, &options(case)); + if &got != expected { + failures.push(format!( + "{fname}/{name}: expected {expected:?}, got {got:?}" + )); + } + } + } + assert!( + failures.is_empty(), + "{} failing:\n{}", + failures.len(), + failures.join("\n") + ); + assert_eq!(total, EXPECTED_CASES, "case count changed"); +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/LICENSE b/examples/tasks-axi-rust/crates/toon/tests/fixtures/LICENSE new file mode 100644 index 0000000000..986bae4e3c --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025-PRESENT Johann Schopplich + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/PROVENANCE.md b/examples/tasks-axi-rust/crates/toon/tests/fixtures/PROVENANCE.md new file mode 100644 index 0000000000..be7ec309d6 --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/PROVENANCE.md @@ -0,0 +1,17 @@ +# Fixture provenance + +The files under `encode/` are the official TOON encoder conformance fixtures. + +- Upstream: https://github.com/toon-format/spec +- Path upstream: `tests/fixtures/encode/` +- Spec version: v4.1.1 +- Commit: 62f16b369408180f1faf1cba7da1b46d1f336f12 +- License: MIT (see `LICENSE` in this directory) +- Copy: byte-for-byte; no file has been edited. + +## Refreshing + +1. Check out the upstream repository at the desired commit. +2. Copy `tests/fixtures/encode/*.json` over the files in `encode/` here, and the upstream `LICENSE` over `LICENSE`. +3. Update the spec version and commit above. +4. Run `cargo test`; the conformance test counts the cases it finds and requires every one to pass. diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-nested.json b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-nested.json new file mode 100644 index 0000000000..69c570ec4a --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-nested.json @@ -0,0 +1,132 @@ +{ + "version": "4.0", + "category": "encode", + "description": "Nested and mixed array encoding – arrays of arrays, mixed type arrays, root arrays", + "tests": [ + { + "name": "encodes nested arrays of primitives", + "input": { + "pairs": [["a", "b"], ["c", "d"]] + }, + "expected": "pairs[2]:\n - [2]: a,b\n - [2]: c,d", + "specSection": "9.2" + }, + { + "name": "quotes strings containing delimiters in nested arrays", + "input": { + "pairs": [["a", "b"], ["c,d", "e:f", "true"]] + }, + "expected": "pairs[2]:\n - [2]: a,b\n - [3]: \"c,d\",\"e:f\",\"true\"", + "specSection": "9.2" + }, + { + "name": "encodes empty inner arrays", + "input": { + "pairs": [[], []] + }, + "expected": "pairs[2]:\n - [0]:\n - [0]:", + "specSection": "9.2" + }, + { + "name": "encodes mixed-length inner arrays", + "input": { + "pairs": [[1], [2, 3]] + }, + "expected": "pairs[2]:\n - [1]: 1\n - [2]: 2,3", + "specSection": "9.2" + }, + { + "name": "encodes root-level primitive array", + "input": ["x", "y", "true", true, 10], + "expected": "[5]: x,y,\"true\",true,10", + "specSection": "9.1" + }, + { + "name": "encodes root-level array of uniform objects in tabular form", + "input": [{ "id": 1 }, { "id": 2 }], + "expected": "[2]{id}:\n 1\n 2", + "specSection": "9.3" + }, + { + "name": "encodes root-level array of non-uniform objects in list form", + "input": [{ "id": 1 }, { "id": 2, "name": "Ada" }], + "expected": "[2]:\n - id: 1\n - id: 2\n name: Ada", + "specSection": "9.4" + }, + { + "name": "encodes root-level array mixing primitive, object, and array of objects in list form", + "input": ["summary", { "id": 1, "name": "Ada" }, [{ "id": 2 }, { "status": "draft" }]], + "expected": "[3]:\n - summary\n - id: 1\n name: Ada\n - [2]:\n - id: 2\n - status: draft", + "specSection": "9.4" + }, + { + "name": "encodes root-level arrays of arrays", + "input": [[1, 2], []], + "expected": "[2]:\n - [2]: 1,2\n - [0]:", + "specSection": "9.2" + }, + { + "name": "encodes empty root-level array", + "input": [], + "expected": "[]", + "specSection": "9.1" + }, + { + "name": "encodes complex nested structure", + "input": { + "user": { + "id": 123, + "name": "Ada", + "tags": ["reading", "gaming"], + "active": true, + "prefs": [] + } + }, + "expected": "user:\n id: 123\n name: Ada\n tags[2]: reading,gaming\n active: true\n prefs: []", + "specSection": "8" + }, + { + "name": "uses list form for arrays mixing primitives and objects", + "input": { + "items": [1, { "a": 1 }, "text"] + }, + "expected": "items[3]:\n - 1\n - a: 1\n - text", + "specSection": "9.4" + }, + { + "name": "uses list form for arrays mixing objects and arrays", + "input": { + "items": [{ "a": 1 }, [1, 2]] + }, + "expected": "items[2]:\n - a: 1\n - [2]: 1,2", + "specSection": "9.4" + }, + { + "name": "quotes hash-leading string as list item", + "input": { + "items": ["#x", { "a": 1 }] + }, + "expected": "items[2]:\n - \"#x\"\n - a: 1", + "specSection": "7.2" + }, + { + "name": "uses list form for a tabular-eligible array in list-item position", + "input": { + "a": [ + [ + { + "x": 1 + }, + { + "x": 2 + } + ] + ] + }, + "expected": "a[1]:\n - [2]:\n - x: 1\n - x: 2", + "specSection": "9.3", + "note": "A keyless fields-bearing header is valid only at the document root", + "minSpecVersion": "4.1" + } + ] +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-objects.json b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-objects.json new file mode 100644 index 0000000000..ad8342b37b --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-objects.json @@ -0,0 +1,191 @@ +{ + "version": "4.0", + "category": "encode", + "description": "Arrays of objects encoding – list form for non-uniform objects and complex structures", + "tests": [ + { + "name": "uses list form for objects with different fields", + "input": { + "items": [ + { "id": 1, "name": "First" }, + { "id": 2, "name": "Second", "extra": true } + ] + }, + "expected": "items[2]:\n - id: 1\n name: First\n - id: 2\n name: Second\n extra: true", + "specSection": "9.4" + }, + { + "name": "uses list form for objects with nested values", + "input": { + "items": [ + { "id": 1, "nested": { "x": 1 } }, + { "id": 2, "nested": { "y": 2 } } + ] + }, + "expected": "items[2]:\n - id: 1\n nested:\n x: 1\n - id: 2\n nested:\n y: 2", + "specSection": "9.4", + "note": "The nested column mixes key sets {x} and {y}, so it is not nested-uniform (§9.3), so the array uses list form" + }, + { + "name": "preserves field order in list items - array first", + "input": { + "items": [{ "nums": [1, 2, 3], "name": "Ada" }] + }, + "expected": "items[1]:\n - nums[3]: 1,2,3\n name: Ada", + "specSection": "10" + }, + { + "name": "preserves field order in list items - primitive first", + "input": { + "items": [{ "name": "Ada", "nums": [1, 2, 3] }] + }, + "expected": "items[1]:\n - name: Ada\n nums[3]: 1,2,3", + "specSection": "10" + }, + { + "name": "uses list form for objects containing arrays of arrays", + "input": { + "items": [ + { "matrix": [[1, 2], [3, 4]], "name": "grid" } + ] + }, + "expected": "items[1]:\n - matrix[2]:\n - [2]: 1,2\n - [2]: 3,4\n name: grid", + "specSection": "10" + }, + { + "name": "uses tabular form for nested uniform object arrays", + "input": { + "items": [ + { "users": [{ "id": 1, "name": "Ada" }, { "id": 2, "name": "Bob" }], "status": "active" } + ] + }, + "expected": "items[1]:\n - users[2]{id,name}:\n 1,Ada\n 2,Bob\n status: active", + "specSection": "10", + "note": "Tabular header on hyphen line with rows at depth +2 and sibling fields at depth +1" + }, + { + "name": "uses list form for nested object arrays with mismatched keys", + "input": { + "items": [ + { "users": [{ "id": 1, "name": "Ada" }, { "id": 2 }], "status": "active" } + ] + }, + "expected": "items[1]:\n - users[2]:\n - id: 1\n name: Ada\n - id: 2\n status: active", + "specSection": "10" + }, + { + "name": "uses list form for objects with multiple array fields", + "input": { + "items": [{ "nums": [1, 2], "tags": ["a", "b"], "name": "test" }] + }, + "expected": "items[1]:\n - nums[2]: 1,2\n tags[2]: a,b\n name: test", + "specSection": "10" + }, + { + "name": "uses list form for objects with only array fields", + "input": { + "items": [{ "nums": [1, 2, 3], "tags": ["a", "b"] }] + }, + "expected": "items[1]:\n - nums[3]: 1,2,3\n tags[2]: a,b", + "specSection": "10" + }, + { + "name": "encodes objects with empty arrays in list form", + "input": { + "items": [ + { "name": "Ada", "data": [] } + ] + }, + "expected": "items[1]:\n - name: Ada\n data: []", + "specSection": "10" + }, + { + "name": "uses canonical encoding for multi-field list-item objects with tabular arrays", + "input": { + "items": [{ "users": [{ "id": 1 }, { "id": 2 }], "note": "x" }] + }, + "expected": "items[1]:\n - users[2]{id}:\n 1\n 2\n note: x", + "specSection": "10", + "note": "Tabular header on hyphen line with rows at depth +2 and sibling fields at depth +1" + }, + { + "name": "uses canonical encoding for single-field list-item tabular arrays", + "input": { + "items": [{ "users": [{ "id": 1, "name": "Ada" }, { "id": 2, "name": "Bob" }] }] + }, + "expected": "items[1]:\n - users[2]{id,name}:\n 1,Ada\n 2,Bob", + "specSection": "10", + "note": "Tabular header on hyphen line with rows at depth +2" + }, + { + "name": "places empty arrays on hyphen line when first", + "input": { + "items": [{ "data": [], "name": "x" }] + }, + "expected": "items[1]:\n - data: []\n name: x", + "specSection": "10" + }, + { + "name": "encodes empty object list items as bare hyphen", + "input": { + "items": ["first", "second", {}] + }, + "expected": "items[3]:\n - first\n - second\n -", + "specSection": "10", + "note": "Empty object list items encode as a single \"-\" line at the list-item depth" + }, + { + "name": "uses field order from first object for tabular headers", + "input": { + "items": [ + { "a": 1, "b": 2, "c": 3 }, + { "c": 30, "b": 20, "a": 10 } + ] + }, + "expected": "items[2]{a,b,c}:\n 1,2,3\n 10,20,30", + "specSection": "9.3" + }, + { + "name": "uses list form when one object has nested field", + "input": { + "items": [ + { "id": 1, "data": "string" }, + { "id": 2, "data": { "nested": true } } + ] + }, + "expected": "items[2]:\n - id: 1\n data: string\n - id: 2\n data:\n nested: true", + "specSection": "9.4" + }, + { + "name": "uses list form for arrays containing empty objects", + "input": { + "items": [{}, {}] + }, + "expected": "items[2]:\n -\n -", + "specSection": "9.4", + "note": "Empty objects are excluded from tabular detection (§9.3), so the array uses list form with bare hyphen markers (§10)" + }, + { + "name": "encodes a keyed-eligible object in a tabular column as a nested field group", + "input": { + "a": [ + { + "t": { + "p": { + "x": 1 + }, + "q": { + "x": 2 + } + }, + "other": 9 + } + ] + }, + "expected": "a[1]{t{p{x},q{x}},other}:\n 1,2,9", + "specSection": "9.5", + "note": "Keyed tabular form is mandated in object-field and root positions, not in a column", + "minSpecVersion": "4.1" + } + ] +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-primitive.json b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-primitive.json new file mode 100644 index 0000000000..5644091372 --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-primitive.json @@ -0,0 +1,111 @@ +{ + "version": "4.0", + "category": "encode", + "description": "Primitive array encoding – inline arrays of strings, numbers, booleans", + "tests": [ + { + "name": "encodes string arrays inline", + "input": { + "tags": ["reading", "gaming"] + }, + "expected": "tags[2]: reading,gaming", + "specSection": "9.1" + }, + { + "name": "encodes number arrays inline", + "input": { + "nums": [1, 2, 3] + }, + "expected": "nums[3]: 1,2,3", + "specSection": "9.1" + }, + { + "name": "encodes mixed primitive arrays inline", + "input": { + "data": ["x", "y", true, 10] + }, + "expected": "data[4]: x,y,true,10", + "specSection": "9.1" + }, + { + "name": "encodes empty arrays", + "input": { + "items": [] + }, + "expected": "items: []", + "specSection": "9.1" + }, + { + "name": "encodes empty string keys for inline arrays", + "input": { + "": [1, 2, 3] + }, + "expected": "\"\"[3]: 1,2,3", + "specSection": "9.1" + }, + { + "name": "encodes empty string keys for empty arrays", + "input": { + "": [] + }, + "expected": "\"\": []", + "specSection": "9.1" + }, + { + "name": "encodes empty string in single-item array", + "input": { + "items": [""] + }, + "expected": "items[1]: \"\"", + "specSection": "9.1" + }, + { + "name": "encodes empty string in multi-item array", + "input": { + "items": ["a", "", "b"] + }, + "expected": "items[3]: a,\"\",b", + "specSection": "9.1" + }, + { + "name": "encodes whitespace-only strings in arrays", + "input": { + "items": [" ", " "] + }, + "expected": "items[2]: \" \",\" \"", + "specSection": "9.1" + }, + { + "name": "quotes array strings with comma", + "input": { + "items": ["a", "b,c", "d:e"] + }, + "expected": "items[3]: a,\"b,c\",\"d:e\"", + "specSection": "9.1" + }, + { + "name": "quotes strings that look like booleans in arrays", + "input": { + "items": ["x", "true", "42", "-3.14"] + }, + "expected": "items[4]: x,\"true\",\"42\",\"-3.14\"", + "specSection": "9.1" + }, + { + "name": "quotes strings with structural meanings in arrays", + "input": { + "items": ["[5]", "- item", "{key}"] + }, + "expected": "items[3]: \"[5]\",\"- item\",\"{key}\"", + "specSection": "9.1" + }, + { + "name": "quotes hash-leading string in inline array", + "input": { + "tags": ["#a", "b"] + }, + "expected": "tags[2]: \"#a\",b", + "specSection": "7.2" + } + ] +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-tabular.json b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-tabular.json new file mode 100644 index 0000000000..236504248e --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/arrays-tabular.json @@ -0,0 +1,182 @@ +{ + "version": "4.0", + "category": "encode", + "description": "Tabular array encoding – arrays of uniform objects with primitive values", + "tests": [ + { + "name": "encodes arrays of uniform objects in tabular form", + "input": { + "items": [ + { "sku": "A1", "qty": 2, "price": 9.99 }, + { "sku": "B2", "qty": 1, "price": 14.5 } + ] + }, + "expected": "items[2]{sku,qty,price}:\n A1,2,9.99\n B2,1,14.5", + "specSection": "9.3" + }, + { + "name": "encodes null values in tabular form", + "input": { + "items": [ + { "id": 1, "value": null }, + { "id": 2, "value": "test" } + ] + }, + "expected": "items[2]{id,value}:\n 1,null\n 2,test", + "specSection": "9.3" + }, + { + "name": "quotes strings containing delimiters in tabular rows", + "input": { + "items": [ + { "sku": "A,1", "desc": "cool", "qty": 2 }, + { "sku": "B2", "desc": "wip: test", "qty": 1 } + ] + }, + "expected": "items[2]{sku,desc,qty}:\n \"A,1\",cool,2\n B2,\"wip: test\",1", + "specSection": "9.3" + }, + { + "name": "quotes ambiguous strings in tabular rows", + "input": { + "items": [ + { "id": 1, "status": "true" }, + { "id": 2, "status": "false" } + ] + }, + "expected": "items[2]{id,status}:\n 1,\"true\"\n 2,\"false\"", + "specSection": "9.3" + }, + { + "name": "encodes tabular arrays with keys needing quotes", + "input": { + "items": [ + { "order:id": 1, "full name": "Ada" }, + { "order:id": 2, "full name": "Bob" } + ] + }, + "expected": "items[2]{\"order:id\",\"full name\"}:\n 1,Ada\n 2,Bob", + "specSection": "9.3" + }, + { + "name": "encodes tabular arrays with empty string keys", + "input": { + "": [ + { "id": 1, "name": "Ada" }, + { "id": 2, "name": "Bob" } + ] + }, + "expected": "\"\"[2]{id,name}:\n 1,Ada\n 2,Bob", + "specSection": "9.3" + }, + { + "name": "quotes hash-leading string in tabular cell", + "input": { + "items": [{ "tag": "#a" }, { "tag": "b" }] + }, + "expected": "items[2]{tag}:\n \"#a\"\n b", + "specSection": "7.2", + "note": "Unquoted, the first row would read as a comment line on decode" + }, + { + "name": "collapses a uniform nested object column into a nested field group", + "input": { + "orders": [ + { "id": 1, "customer": { "name": "Ada", "country": "DK" }, "total": 99 }, + { "id": 2, "customer": { "name": "Bob", "country": "UK" }, "total": 149 } + ] + }, + "expected": "orders[2]{id,customer{name,country},total}:\n 1,Ada,DK,99\n 2,Bob,UK,149", + "specSection": "9.3" + }, + { + "name": "collapses sibling nested field groups with depth-first row layout", + "input": { + "shipments": [ + { "id": "s1", "sender": { "name": "ACME", "city": "Berlin" }, "receiver": { "name": "Globex", "city": "Oslo" } } + ] + }, + "expected": "shipments[1]{id,sender{name,city},receiver{name,city}}:\n s1,ACME,Berlin,Globex,Oslo", + "specSection": "9.3" + }, + { + "name": "collapses nested field groups recursively without a depth cap", + "input": { + "items": [ + { "id": 1, "geo": { "point": { "lat": 1.5, "lon": 2.5 } } }, + { "id": 2, "geo": { "point": { "lat": 3, "lon": 4 } } } + ] + }, + "expected": "items[2]{id,geo{point{lat,lon}}}:\n 1,1.5,2.5\n 2,3,4", + "specSection": "9.3" + }, + { + "name": "uses the active delimiter inside nested field groups", + "input": { + "orders": [ + { "id": 1, "customer": { "name": "Ada", "country": "DK" }, "total": 99 }, + { "id": 2, "customer": { "name": "Bob", "country": "UK" }, "total": 149 } + ] + }, + "options": { "delimiter": "|" }, + "expected": "orders[2|]{id|customer{name|country}|total}:\n 1|Ada|DK|99\n 2|Bob|UK|149", + "specSection": "9.3" + }, + { + "name": "quotes subfield names inside nested field groups per key encoding", + "input": { + "items": [ + { "id": 1, "customer": { "full name": "Ada", "country": "UK" } } + ] + }, + "expected": "items[1]{id,customer{\"full name\",country}}:\n 1,Ada,UK", + "specSection": "9.3" + }, + { + "name": "falls back to list form when nested object keys differ per row", + "input": { + "entries": [ + { "id": 1, "meta": { "a": 1 } }, + { "id": 2, "meta": { "b": 2 } } + ] + }, + "expected": "entries[2]:\n - id: 1\n meta:\n a: 1\n - id: 2\n meta:\n b: 2", + "specSection": "9.3", + "note": "The meta column is not nested-uniform (differing key sets), so the whole array uses §9.4" + }, + { + "name": "falls back to list form when a column mixes null and objects", + "input": { + "orders": [ + { "id": 1, "customer": { "name": "Ada" } }, + { "id": 2, "customer": null } + ] + }, + "expected": "orders[2]:\n - id: 1\n customer:\n name: Ada\n - id: 2\n customer: null", + "specSection": "9.3", + "note": "A null cell is a primitive, so the customer column is neither uniform-primitive nor nested-uniform" + }, + { + "name": "falls back to list form when a nested object contains an array", + "input": { + "orders": [ + { "id": 1, "customer": { "name": "Ada", "tags": ["x"] } } + ] + }, + "expected": "orders[1]:\n - id: 1\n customer:\n name: Ada\n tags[1]: x", + "specSection": "9.3", + "note": "Array values disqualify a column; rows must contain only primitive cells" + }, + { + "name": "falls back to list form when a nested column contains an empty object", + "input": { + "items": [ + { "id": 1, "meta": {} } + ] + }, + "expected": "items[1]:\n - id: 1\n meta:", + "specSection": "9.3", + "note": "Nested-uniform requires non-empty objects, mirroring the empty-object exclusion for elements" + } + ] +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/delimiters.json b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/delimiters.json new file mode 100644 index 0000000000..03c9271dce --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/delimiters.json @@ -0,0 +1,253 @@ +{ + "version": "4.0", + "category": "encode", + "description": "Delimiter options – tab and pipe delimiters, delimiter-aware quoting", + "tests": [ + { + "name": "encodes primitive arrays with tab delimiter", + "input": { + "tags": ["reading", "gaming", "coding"] + }, + "expected": "tags[3\t]: reading\tgaming\tcoding", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "encodes primitive arrays with pipe delimiter", + "input": { + "tags": ["reading", "gaming", "coding"] + }, + "expected": "tags[3|]: reading|gaming|coding", + "options": { + "delimiter": "|" + }, + "specSection": "11" + }, + { + "name": "encodes primitive arrays with comma delimiter", + "input": { + "tags": ["reading", "gaming", "coding"] + }, + "expected": "tags[3]: reading,gaming,coding", + "options": { + "delimiter": "," + }, + "specSection": "11" + }, + { + "name": "encodes tabular arrays with tab delimiter", + "input": { + "items": [ + { "sku": "A1", "qty": 2, "price": 9.99 }, + { "sku": "B2", "qty": 1, "price": 14.5 } + ] + }, + "expected": "items[2\t]{sku\tqty\tprice}:\n A1\t2\t9.99\n B2\t1\t14.5", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "encodes tabular arrays with pipe delimiter", + "input": { + "items": [ + { "sku": "A1", "qty": 2, "price": 9.99 }, + { "sku": "B2", "qty": 1, "price": 14.5 } + ] + }, + "expected": "items[2|]{sku|qty|price}:\n A1|2|9.99\n B2|1|14.5", + "options": { + "delimiter": "|" + }, + "specSection": "11" + }, + { + "name": "encodes nested arrays with tab delimiter", + "input": { + "pairs": [["a", "b"], ["c", "d"]] + }, + "expected": "pairs[2\t]:\n - [2\t]: a\tb\n - [2\t]: c\td", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "encodes nested arrays with pipe delimiter", + "input": { + "pairs": [["a", "b"], ["c", "d"]] + }, + "expected": "pairs[2|]:\n - [2|]: a|b\n - [2|]: c|d", + "options": { + "delimiter": "|" + }, + "specSection": "11" + }, + { + "name": "encodes root-level array with tab delimiter", + "input": ["x", "y", "z"], + "expected": "[3\t]: x\ty\tz", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "encodes root-level array with pipe delimiter", + "input": ["x", "y", "z"], + "expected": "[3|]: x|y|z", + "options": { + "delimiter": "|" + }, + "specSection": "11" + }, + { + "name": "encodes root-level array of objects with tab delimiter", + "input": [{ "id": 1 }, { "id": 2 }], + "expected": "[2\t]{id}:\n 1\n 2", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "encodes root-level array of objects with pipe delimiter", + "input": [{ "id": 1 }, { "id": 2 }], + "expected": "[2|]{id}:\n 1\n 2", + "options": { + "delimiter": "|" + }, + "specSection": "11" + }, + { + "name": "quotes strings containing tab delimiter", + "input": { + "items": ["a", "b\tc", "d"] + }, + "expected": "items[3\t]: a\t\"b\\tc\"\td", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "quotes strings containing pipe delimiter", + "input": { + "items": ["a", "b|c", "d"] + }, + "expected": "items[3|]: a|\"b|c\"|d", + "options": { + "delimiter": "|" + }, + "specSection": "11" + }, + { + "name": "does not quote commas with tab delimiter", + "input": { + "items": ["a,b", "c,d"] + }, + "expected": "items[2\t]: a,b\tc,d", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "does not quote commas with pipe delimiter", + "input": { + "items": ["a,b", "c,d"] + }, + "expected": "items[2|]: a,b|c,d", + "options": { + "delimiter": "|" + }, + "specSection": "11" + }, + { + "name": "quotes tabular values containing comma delimiter", + "input": { + "items": [ + { "id": 1, "note": "a,b" }, + { "id": 2, "note": "c,d" } + ] + }, + "expected": "items[2]{id,note}:\n 1,\"a,b\"\n 2,\"c,d\"", + "options": { + "delimiter": "," + }, + "specSection": "11" + }, + { + "name": "does not quote commas in tabular values with tab delimiter", + "input": { + "items": [ + { "id": 1, "note": "a,b" }, + { "id": 2, "note": "c,d" } + ] + }, + "expected": "items[2\t]{id\tnote}:\n 1\ta,b\n 2\tc,d", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "does not quote commas in object values with pipe delimiter", + "input": { + "note": "a,b" + }, + "expected": "note: a,b", + "options": { + "delimiter": "|" + }, + "specSection": "11" + }, + { + "name": "does not quote commas in object values with tab delimiter", + "input": { + "note": "a,b" + }, + "expected": "note: a,b", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "quotes nested array values containing pipe delimiter", + "input": { + "pairs": [["a", "b|c"]] + }, + "expected": "pairs[1|]:\n - [2|]: a|\"b|c\"", + "options": { + "delimiter": "|" + }, + "specSection": "11" + }, + { + "name": "quotes nested array values containing tab delimiter", + "input": { + "pairs": [["a", "b\tc"]] + }, + "expected": "pairs[1\t]:\n - [2\t]: a\t\"b\\tc\"", + "options": { + "delimiter": "\t" + }, + "specSection": "11" + }, + { + "name": "preserves ambiguity quoting regardless of delimiter", + "input": { + "items": ["true", "42", "-3.14"] + }, + "expected": "items[3|]: \"true\"|\"42\"|\"-3.14\"", + "options": { + "delimiter": "|" + }, + "specSection": "11" + } + ] +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/objects-keyed.json b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/objects-keyed.json new file mode 100644 index 0000000000..7fd4e879db --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/objects-keyed.json @@ -0,0 +1,155 @@ +{ + "version": "4.0", + "category": "encode", + "description": "Keyed tabular encoding – objects whose values are uniform objects collapse into keyed headers with entry rows", + "tests": [ + { + "name": "encodes objects of uniform objects in keyed tabular form", + "input": { + "servers": { + "alpha": { "host": "a.example.com", "port": 8080 }, + "beta": { "host": "b.example.com", "port": 9090 } + } + }, + "expected": "servers[2:]{host,port}:\n alpha: a.example.com,8080\n beta: b.example.com,9090", + "specSection": "9.5" + }, + { + "name": "encodes an eligible root object with a keyless keyed header", + "input": { + "alice": { "age": 30, "city": "Berlin" }, + "bob": { "age": 25, "city": "Oslo" } + }, + "expected": "[2:]{age,city}:\n alice: 30,Berlin\n bob: 25,Oslo", + "specSection": "9.5", + "note": "The keyless keyed header is valid only at the root (§5)" + }, + { + "name": "collapses uniform nested object columns inside keyed headers", + "input": { + "regions": { + "eu": { "name": "Europe", "geo": { "lat": 50, "lon": 10 } }, + "us": { "name": "America", "geo": { "lat": 40, "lon": -100 } } + } + }, + "expected": "regions[2:]{name,geo{lat,lon}}:\n eu: Europe,50,10\n us: America,40,-100", + "specSection": "9.5" + }, + { + "name": "orders fields by the first entry value's encounter order", + "input": { + "m": { + "a": { "x": 1, "y": 2 }, + "b": { "y": 4, "x": 3 } + } + }, + "expected": "m[2:]{x,y}:\n a: 1,2\n b: 3,4", + "specSection": "9.5" + }, + { + "name": "uses the active delimiter in keyed headers and entry-row cells", + "input": { + "servers": { + "alpha": { "host": "a.example.com", "port": 8080 }, + "beta": { "host": "b.example.com", "port": 9090 } + } + }, + "options": { "delimiter": "|" }, + "expected": "servers[2:|]{host|port}:\n alpha: a.example.com|8080\n beta: b.example.com|9090", + "specSection": "9.5", + "note": "The keyed marker precedes the delimiter symbol: [2:|]" + }, + { + "name": "quotes entry keys per key encoding", + "input": { + "ids": { + "42": { "v": 1 }, + "my key": { "v": 2 } + } + }, + "expected": "ids[2:]{v}:\n \"42\": 1\n \"my key\": 2", + "specSection": "9.5", + "note": "Entry keys follow §7.3, the same rule as object keys" + }, + { + "name": "quotes entry-row cells containing the active delimiter", + "input": { + "notes": { + "n1": { "text": "a,b" }, + "n2": { "text": "c" } + } + }, + "expected": "notes[2:]{text}:\n n1: \"a,b\"\n n2: c", + "specSection": "9.5" + }, + { + "name": "keeps single-entry objects in nested form", + "input": { + "config": { + "only": { "a": 1, "b": 2 } + } + }, + "expected": "config:\n only:\n a: 1\n b: 2", + "specSection": "9.5", + "note": "Keyed tabular detection requires at least two entries" + }, + { + "name": "keeps objects in nested form when entry values have differing key sets", + "input": { + "envs": { + "dev": { "host": "x" }, + "prod": { "host": "y", "port": 1 } + } + }, + "expected": "envs:\n dev:\n host: x\n prod:\n host: y\n port: 1", + "specSection": "9.5" + }, + { + "name": "keeps objects in nested form when a value is primitive", + "input": { + "m": { + "a": { "x": 1 }, + "b": 2 + } + }, + "expected": "m:\n a:\n x: 1\n b: 2", + "specSection": "9.5" + }, + { + "name": "keeps objects in nested form when an entry value contains an array", + "input": { + "m": { + "a": { "tags": ["x"] }, + "b": { "tags": ["y"] } + } + }, + "expected": "m:\n a:\n tags[1]: x\n b:\n tags[1]: y", + "specSection": "9.5", + "note": "Entry-row cells must be primitive leaves; an array value disqualifies the column" + }, + { + "name": "emits a keyed header on the hyphen line when it is the first field of a list item", + "input": { + "items": [ + { "config": { "a": { "x": 1 }, "b": { "x": 2 } }, "status": "ok" }, + { "status": "down" } + ] + }, + "expected": "items[2]:\n - config[2:]{x}:\n a: 1\n b: 2\n status: ok\n - status: down", + "specSection": "10", + "note": "Entry rows at depth +2, sibling fields at depth +1, mirroring tabular arrays on hyphen lines" + }, + { + "name": "never encodes an anonymous array element in keyed tabular form", + "input": { + "items": [ + { "a": { "x": 1 }, "b": { "x": 2 } }, + 5 + ] + }, + "expected": "items[2]:\n - a:\n x: 1\n b:\n x: 2\n - 5", + "specSection": "9.5", + "note": "The element object is keyed-eligible but has no key; the keyless form is root-only, so it encodes per §10" + } + ] +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/objects.json b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/objects.json new file mode 100644 index 0000000000..a63f92c679 --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/objects.json @@ -0,0 +1,297 @@ +{ + "version": "4.0", + "category": "encode", + "description": "Object encoding – simple objects, nested objects, key encoding", + "tests": [ + { + "name": "preserves key order in objects", + "input": { + "id": 123, + "name": "Ada", + "active": true + }, + "expected": "id: 123\nname: Ada\nactive: true", + "specSection": "8" + }, + { + "name": "encodes null values in objects", + "input": { + "id": 123, + "value": null + }, + "expected": "id: 123\nvalue: null", + "specSection": "8" + }, + { + "name": "encodes empty objects as empty string", + "input": {}, + "expected": "", + "specSection": "8" + }, + { + "name": "quotes string value with colon", + "input": { + "note": "a:b" + }, + "expected": "note: \"a:b\"", + "specSection": "7.2" + }, + { + "name": "quotes string value with comma", + "input": { + "note": "a,b" + }, + "expected": "note: \"a,b\"", + "specSection": "7.2" + }, + { + "name": "quotes string value with newline", + "input": { + "text": "line1\nline2" + }, + "expected": "text: \"line1\\nline2\"", + "specSection": "7.2" + }, + { + "name": "quotes string value with embedded quotes", + "input": { + "text": "say \"hello\"" + }, + "expected": "text: \"say \\\"hello\\\"\"", + "specSection": "7.2" + }, + { + "name": "quotes string value with leading space", + "input": { + "text": " padded " + }, + "expected": "text: \" padded \"", + "specSection": "7.2" + }, + { + "name": "quotes string value with only spaces", + "input": { + "text": " " + }, + "expected": "text: \" \"", + "specSection": "7.2" + }, + { + "name": "quotes string value that looks like true", + "input": { + "v": "true" + }, + "expected": "v: \"true\"", + "specSection": "7.2" + }, + { + "name": "quotes string value that looks like number", + "input": { + "v": "42" + }, + "expected": "v: \"42\"", + "specSection": "7.2" + }, + { + "name": "quotes string value that looks like negative decimal", + "input": { + "v": "-7.5" + }, + "expected": "v: \"-7.5\"", + "specSection": "7.2" + }, + { + "name": "quotes key with colon", + "input": { + "order:id": 7 + }, + "expected": "\"order:id\": 7", + "specSection": "7.3" + }, + { + "name": "quotes key with brackets", + "input": { + "[index]": 5 + }, + "expected": "\"[index]\": 5", + "specSection": "7.3" + }, + { + "name": "quotes key with braces", + "input": { + "{key}": 5 + }, + "expected": "\"{key}\": 5", + "specSection": "7.3" + }, + { + "name": "quotes key with comma", + "input": { + "a,b": 1 + }, + "expected": "\"a,b\": 1", + "specSection": "7.3" + }, + { + "name": "quotes key with spaces", + "input": { + "full name": "Ada" + }, + "expected": "\"full name\": Ada", + "specSection": "7.3" + }, + { + "name": "quotes key with leading hyphen", + "input": { + "-lead": 1 + }, + "expected": "\"-lead\": 1", + "specSection": "7.3" + }, + { + "name": "quotes key with leading and trailing spaces", + "input": { + " a ": 1 + }, + "expected": "\" a \": 1", + "specSection": "7.3" + }, + { + "name": "quotes numeric key", + "input": { + "123": "x" + }, + "expected": "\"123\": x", + "specSection": "7.3" + }, + { + "name": "quotes empty string key", + "input": { + "": 1 + }, + "expected": "\"\": 1", + "specSection": "7.3" + }, + { + "name": "quotes non-ASCII key", + "input": { + "café": 1 + }, + "expected": "\"café\": 1", + "specSection": "7.3", + "note": "The unquoted-key pattern is ASCII-only, so every non-ASCII key is quoted" + }, + { + "name": "quotes CJK key", + "input": { + "名前": "x" + }, + "expected": "\"名前\": x", + "specSection": "7.3" + }, + { + "name": "escapes newline in key", + "input": { + "line\nbreak": 1 + }, + "expected": "\"line\\nbreak\": 1", + "specSection": "7.1" + }, + { + "name": "escapes tab in key", + "input": { + "tab\there": 2 + }, + "expected": "\"tab\\there\": 2", + "specSection": "7.1" + }, + { + "name": "escapes quotes in key", + "input": { + "he said \"hi\"": 1 + }, + "expected": "\"he said \\\"hi\\\"\": 1", + "specSection": "7.1" + }, + { + "name": "escapes U+0004 control character in key via \\uXXXX", + "input": { + "a\u0004b": 1 + }, + "expected": "\"a\\u0004b\": 1", + "specSection": "7.1" + }, + { + "name": "escapes U+001F control character in key via \\uXXXX", + "input": { + "x\u001fy": 2 + }, + "expected": "\"x\\u001fy\": 2", + "specSection": "7.1" + }, + { + "name": "encodes deeply nested objects", + "input": { + "a": { + "b": { + "c": "deep" + } + } + }, + "expected": "a:\n b:\n c: deep", + "specSection": "8" + }, + { + "name": "encodes empty nested object", + "input": { + "user": {} + }, + "expected": "user:", + "specSection": "8" + }, + { + "name": "encodes __proto__ own property as an ordinary key", + "input": { + "__proto__": "polluted", + "safe": true + }, + "expected": "__proto__: polluted\nsafe: true", + "specSection": "15", + "note": "No key has special meaning, so the encoder emits prototype-named own entries like any other (§8)" + }, + { + "name": "encodes constructor and prototype own properties as ordinary keys", + "input": { + "constructor": 1, + "prototype": 2 + }, + "expected": "constructor: 1\nprototype: 2", + "specSection": "15" + }, + { + "name": "encodes __proto__ as a tabular field name", + "input": { + "rows": [ + { + "__proto__": "a", + "x": 1 + }, + { + "__proto__": "b", + "x": 2 + } + ] + }, + "expected": "rows[2]{__proto__,x}:\n a,1\n b,2", + "specSection": "15" + }, + { + "name": "quotes hash-leading string in object field value", + "input": { + "note": "#x" + }, + "expected": "note: \"#x\"", + "specSection": "7.2" + } + ] +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/primitives.json b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/primitives.json new file mode 100644 index 0000000000..9d6041a0b0 --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/primitives.json @@ -0,0 +1,278 @@ +{ + "version": "4.0", + "category": "encode", + "description": "Primitive value encoding – strings, numbers, booleans, null", + "tests": [ + { + "name": "encodes safe strings without quotes", + "input": "hello", + "expected": "hello", + "specSection": "7.2" + }, + { + "name": "encodes safe string with underscore and numbers", + "input": "Ada_99", + "expected": "Ada_99", + "specSection": "7.2" + }, + { + "name": "quotes empty string", + "input": "", + "expected": "\"\"", + "specSection": "7.2" + }, + { + "name": "quotes string that looks like true", + "input": "true", + "expected": "\"true\"", + "specSection": "7.2" + }, + { + "name": "quotes string that looks like false", + "input": "false", + "expected": "\"false\"", + "specSection": "7.2" + }, + { + "name": "quotes string that looks like null", + "input": "null", + "expected": "\"null\"", + "specSection": "7.2" + }, + { + "name": "quotes string that looks like integer", + "input": "42", + "expected": "\"42\"", + "specSection": "7.2" + }, + { + "name": "quotes string that looks like negative decimal", + "input": "-3.14", + "expected": "\"-3.14\"", + "specSection": "7.2" + }, + { + "name": "quotes string that looks like scientific notation", + "input": "1e-6", + "expected": "\"1e-6\"", + "specSection": "7.2" + }, + { + "name": "quotes string with leading zero", + "input": "05", + "expected": "\"05\"", + "specSection": "7.2", + "note": "Matches the numeric-like pattern, so it MUST be quoted" + }, + { + "name": "escapes newline in string", + "input": "line1\nline2", + "expected": "\"line1\\nline2\"", + "specSection": "7.1" + }, + { + "name": "escapes tab in string", + "input": "tab\there", + "expected": "\"tab\\there\"", + "specSection": "7.1" + }, + { + "name": "escapes carriage return in string", + "input": "return\rcarriage", + "expected": "\"return\\rcarriage\"", + "specSection": "7.1" + }, + { + "name": "encodes string with U+0004 control character via \\uXXXX", + "input": { "val": "a\u0004b" }, + "expected": "val: \"a\\u0004b\"", + "specSection": "7.1" + }, + { + "name": "escapes backslash in string", + "input": "C:\\Users\\path", + "expected": "\"C:\\\\Users\\\\path\"", + "specSection": "7.1" + }, + { + "name": "quotes string with array-like syntax", + "input": "[3]: x,y", + "expected": "\"[3]: x,y\"", + "specSection": "7.2" + }, + { + "name": "quotes string starting with hyphen-space", + "input": "- item", + "expected": "\"- item\"", + "specSection": "7.2" + }, + { + "name": "quotes single hyphen as object value", + "input": { "marker": "-" }, + "expected": "marker: \"-\"", + "specSection": "7.2", + "note": "Single hyphen must be quoted to avoid list item ambiguity" + }, + { + "name": "quotes string starting with hyphen as object value", + "input": { "note": "- item" }, + "expected": "note: \"- item\"", + "specSection": "7.2" + }, + { + "name": "quotes single hyphen in array", + "input": { "items": ["-"] }, + "expected": "items[1]: \"-\"", + "specSection": "7.2" + }, + { + "name": "quotes leading-hyphen string in array", + "input": { "tags": ["a", "- item", "b"] }, + "expected": "tags[3]: a,\"- item\",b", + "specSection": "7.2" + }, + { + "name": "quotes string with bracket notation", + "input": "[test]", + "expected": "\"[test]\"", + "specSection": "7.2" + }, + { + "name": "quotes string with brace notation", + "input": "{key}", + "expected": "\"{key}\"", + "specSection": "7.2" + }, + { + "name": "encodes Unicode string without quotes", + "input": "café", + "expected": "café", + "specSection": "7.2" + }, + { + "name": "encodes Chinese characters without quotes", + "input": "你好", + "expected": "你好", + "specSection": "7.2" + }, + { + "name": "encodes emoji without quotes", + "input": "🚀", + "expected": "🚀", + "specSection": "7.2" + }, + { + "name": "encodes string with emoji and spaces", + "input": "hello 👋 world", + "expected": "hello 👋 world", + "specSection": "7.2" + }, + { + "name": "encodes emoji inside a quoted string", + "input": "a,🚀", + "expected": "\"a,🚀\"", + "specSection": "7.1", + "note": "Quoting is triggered by the delimiter; the supplementary scalar stays literal UTF-8, never a surrogate escape" + }, + { + "name": "encodes positive integer", + "input": 42, + "expected": "42", + "specSection": "2" + }, + { + "name": "encodes decimal number", + "input": 3.14, + "expected": "3.14", + "specSection": "2" + }, + { + "name": "encodes negative integer", + "input": -7, + "expected": "-7", + "specSection": "2" + }, + { + "name": "encodes zero", + "input": 0, + "expected": "0", + "specSection": "2" + }, + { + "name": "encodes negative zero as zero", + "input": -0, + "expected": "0", + "specSection": "2" + }, + { + "name": "encodes large integer without exponent notation", + "input": 1000000, + "expected": "1000000", + "specSection": "2", + "note": "Within the canonical decimal range" + }, + { + "name": "encodes small decimal without exponent notation", + "input": 0.000001, + "expected": "0.000001", + "specSection": "2", + "note": "Lower bound of the canonical decimal range" + }, + { + "name": "encodes large number", + "input": 100000000000000000000, + "expected": "100000000000000000000", + "specSection": "2" + }, + { + "name": "encodes MAX_SAFE_INTEGER", + "input": 9007199254740991, + "expected": "9007199254740991", + "specSection": "2" + }, + { + "name": "encodes repeating decimal with full precision", + "input": 0.3333333333333333, + "expected": "0.3333333333333333", + "specSection": "2" + }, + { + "name": "encodes true", + "input": true, + "expected": "true", + "specSection": "2" + }, + { + "name": "encodes false", + "input": false, + "expected": "false", + "specSection": "2" + }, + { + "name": "encodes null", + "input": null, + "expected": "null", + "specSection": "2" + }, + { + "name": "quotes leading-plus numeric-like string", + "input": "+1", + "expected": "\"+1\"", + "specSection": "7.2", + "note": "Unquoted, a v3 host-parser decoder would read the number 1" + }, + { + "name": "quotes string equal to hash", + "input": "#", + "expected": "\"#\"", + "specSection": "7.2", + "note": "Comment marker at position 0 must be quoted" + }, + { + "name": "quotes string starting with hash", + "input": "#hello", + "expected": "\"#hello\"", + "specSection": "7.2" + } + ] +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/whitespace.json b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/whitespace.json new file mode 100644 index 0000000000..1c6eae3369 --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/fixtures/encode/whitespace.json @@ -0,0 +1,51 @@ +{ + "version": "4.0", + "category": "encode", + "description": "Whitespace and formatting invariants – no trailing spaces, no trailing newlines", + "tests": [ + { + "name": "produces no trailing newline at end of output", + "input": { + "id": 123 + }, + "expected": "id: 123", + "specSection": "12" + }, + { + "name": "maintains proper indentation for nested structures", + "input": { + "user": { + "id": 123, + "name": "Ada" + }, + "items": ["a", "b"] + }, + "expected": "user:\n id: 123\n name: Ada\nitems[2]: a,b", + "specSection": "12" + }, + { + "name": "respects custom indentSize option", + "input": { + "user": { + "name": "Ada", + "role": "admin" + } + }, + "expected": "user:\n name: Ada\n role: admin", + "specSection": "12", + "options": { + "indentSize": 4 + } + }, + { + "name": "leaves non-ASCII whitespace unquoted", + "input": { + "k": "\u00a0x\u00a0" + }, + "expected": "k: \u00a0x\u00a0", + "specSection": "7.2", + "note": "The whitespace trigger is U+0020 and U+0009 only", + "minSpecVersion": "4.1" + } + ] +} diff --git a/examples/tasks-axi-rust/crates/toon/tests/support/json.rs b/examples/tasks-axi-rust/crates/toon/tests/support/json.rs new file mode 100644 index 0000000000..14825e4168 --- /dev/null +++ b/examples/tasks-axi-rust/crates/toon/tests/support/json.rs @@ -0,0 +1,189 @@ +//! A small strict JSON parser that keeps object key order and tells integers +//! from floats (a number token with no '.', 'e' or 'E' is an integer). + +use toon_encode::Value; + +pub fn parse(src: &str) -> Result<Value, String> { + let mut p = P { + b: src.as_bytes(), + i: 0, + }; + p.ws(); + let v = p.value()?; + p.ws(); + if p.i != p.b.len() { + return Err(format!("trailing data at {}", p.i)); + } + Ok(v) +} + +struct P<'a> { + b: &'a [u8], + i: usize, +} + +impl P<'_> { + fn ws(&mut self) { + while matches!(self.b.get(self.i), Some(b' ' | b'\t' | b'\n' | b'\r')) { + self.i += 1; + } + } + + fn eat(&mut self, lit: &str) -> bool { + if self.b[self.i..].starts_with(lit.as_bytes()) { + self.i += lit.len(); + true + } else { + false + } + } + + fn value(&mut self) -> Result<Value, String> { + match self.b.get(self.i) { + None => Err("unexpected end".into()), + Some(b'{') => self.object(), + Some(b'[') => self.array(), + Some(b'"') => Ok(Value::Str(self.string()?)), + Some(b't') if self.eat("true") => Ok(Value::Bool(true)), + Some(b'f') if self.eat("false") => Ok(Value::Bool(false)), + Some(b'n') if self.eat("null") => Ok(Value::Null), + Some(b'-' | b'0'..=b'9') => self.number(), + Some(c) => Err(format!("unexpected {:?} at {}", *c as char, self.i)), + } + } + + fn number(&mut self) -> Result<Value, String> { + let start = self.i; + let mut is_float = false; + if self.b[self.i] == b'-' { + self.i += 1; + } + while let Some(c) = self.b.get(self.i) { + match c { + b'0'..=b'9' => {} + b'.' | b'e' | b'E' | b'+' | b'-' => is_float = true, + _ => break, + } + self.i += 1; + } + let tok = std::str::from_utf8(&self.b[start..self.i]).map_err(|e| e.to_string())?; + if !is_float { + if let Ok(i) = tok.parse::<i64>() { + return Ok(Value::Int(i)); + } + } + tok.parse::<f64>() + .map(Value::Num) + .map_err(|e| format!("bad number {tok:?}: {e}")) + } + + fn hex4(&mut self) -> Result<u32, String> { + let h = self.b.get(self.i..self.i + 4).ok_or("short \\u escape")?; + let h = std::str::from_utf8(h).map_err(|e| e.to_string())?; + self.i += 4; + u32::from_str_radix(h, 16).map_err(|e| e.to_string()) + } + + fn string(&mut self) -> Result<String, String> { + self.i += 1; + let mut out = String::new(); + loop { + let c = *self.b.get(self.i).ok_or("unterminated string")?; + match c { + b'"' => { + self.i += 1; + return Ok(out); + } + b'\\' => { + let e = *self.b.get(self.i + 1).ok_or("bad escape")?; + self.i += 2; + match e { + b'"' => out.push('"'), + b'\\' => out.push('\\'), + b'/' => out.push('/'), + b'b' => out.push('\u{8}'), + b'f' => out.push('\u{c}'), + b'n' => out.push('\n'), + b'r' => out.push('\r'), + b't' => out.push('\t'), + b'u' => { + let mut cp = self.hex4()?; + if (0xD800..0xDC00).contains(&cp) { + if !self.eat("\\u") { + return Err("lone high surrogate".into()); + } + let lo = self.hex4()?; + if !(0xDC00..0xE000).contains(&lo) { + return Err("bad low surrogate".into()); + } + cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00); + } + out.push(char::from_u32(cp).ok_or("bad code point")?); + } + _ => return Err(format!("bad escape \\{}", e as char)), + } + } + c if c < 0x20 => return Err("control char in string".into()), + _ => { + // Copy one full UTF-8 sequence. + let rest = std::str::from_utf8(&self.b[self.i..]).map_err(|e| e.to_string())?; + let ch = rest.chars().next().ok_or("eof")?; + out.push(ch); + self.i += ch.len_utf8(); + } + } + } + } + + fn array(&mut self) -> Result<Value, String> { + self.i += 1; + let mut items = Vec::new(); + self.ws(); + if self.eat("]") { + return Ok(Value::Array(items)); + } + loop { + self.ws(); + items.push(self.value()?); + self.ws(); + if self.eat(",") { + continue; + } + if self.eat("]") { + return Ok(Value::Array(items)); + } + return Err(format!("expected , or ] at {}", self.i)); + } + } + + fn object(&mut self) -> Result<Value, String> { + self.i += 1; + let mut items = Vec::new(); + self.ws(); + if self.eat("}") { + return Ok(Value::Object(items)); + } + loop { + self.ws(); + if self.b.get(self.i) != Some(&b'"') { + return Err(format!("expected key at {}", self.i)); + } + let k = self.string()?; + self.ws(); + if !self.eat(":") { + return Err(format!("expected : at {}", self.i)); + } + self.ws(); + let v = self.value()?; + items.push((k, v)); + self.ws(); + if self.eat(",") { + continue; + } + if self.eat("}") { + return Ok(Value::Object(items)); + } + return Err(format!("expected , or }} at {}", self.i)); + } + } +} diff --git a/examples/tasks-axi-rust/harness/cases.ts b/examples/tasks-axi-rust/harness/cases.ts new file mode 100644 index 0000000000..9c62059266 --- /dev/null +++ b/examples/tasks-axi-rust/harness/cases.ts @@ -0,0 +1,215 @@ +// The invocations the differential harness compares, in three groups: +// differential — run through the real tasks-axi and tasks-axi-rs, outputs must be byte-identical +// refusals — run through tasks-axi-rs only; each must fail loudly and say why +// Every backlog is synthetic (see synthetic-backlog.ts). + +import type { Invocation } from "./sandbox.js"; +import { idsIn, mulberry32, syntheticBacklog } from "./synthetic-backlog.js"; + +export interface Case extends Invocation { + name: string; +} + +const BACKLOG = "backlog.md"; + +/** Read-path commands over one synthetic backlog. */ +export function backlogCases(seed: number): Case[] { + const text = syntheticBacklog({ seed }); + const ids = idsIn(text); + const r = mulberry32(seed * 7919 + 13); + const useFile = seed % 2 === 0; + const base = (args: string[], name: string): Case => ({ + name: `seed${seed}/${name}`, + args: useFile ? [...args, "--file", "docs/tasks.md"] : args, + files: useFile ? { "docs/tasks.md": text } : { [BACKLOG]: text }, + }); + const repos = [...text.matchAll(/\(repo:\s*([^)]+)\)/g)].map((m) => (m[1] as string).trim()).filter(Boolean); + const kinds = [...text.matchAll(/\(kind:\s*([^)]+)\)/g)].map((m) => (m[1] as string).trim()).filter(Boolean); + const repo = repos[0] ?? "widgets"; + const kind = kinds[0] ?? "scout"; + const extras = "blocked,blocked_by,body,closed,created,delivery_state,deps,held,hold_kind,hold_reason,hold_until,links,priority"; + const cases: Case[] = [ + base(["list"], "list"), + base(["list", "--state", "queued"], "list-queued"), + base(["list", "--state=in_flight"], "list-in_flight"), + base(["list", "--state", "done"], "list-done"), + base(["list", "--state", "held"], "list-held"), + base(["list", "--blocked"], "list-blocked"), + base(["list", "--repo", repo], "list-repo"), + base(["list", "--repo", "no-such-repo"], "list-repo-none"), + base(["list", "--kind", kind], "list-kind"), + base(["list", "--kind", "task"], "list-kind-task"), + base(["list", "--limit", "0"], "list-limit0"), + base(["list", "--limit", "1"], "list-limit1"), + base(["list", "--limit=3"], "list-limit3"), + base(["list", "--limit", "100"], "list-limit100"), + base(["list", "--fields", extras], "list-allfields"), + base(["list", "--fields", "body,body,priority, created"], "list-fields-dup"), + base(["list", "--blocked", "--state", "held", "--fields", "hold_reason"], "list-combo-empty"), + base(["list", "--state", "queued", "--repo", repo, "--kind", kind], "list-state-repo-kind"), + base(["ready"], "ready"), + base(["ready", "--include-held"], "ready-held"), + base(["ready", "--repo", repo], "ready-repo"), + base(["ready", "--repo", repo, "--include-held"], "ready-repo-held"), + base(["ready", "--repo", "no-such-repo"], "ready-repo-none"), + base(["show", "no-such-task"], "show-missing"), + ]; + const picks = ids.length <= 10 ? ids : Array.from({ length: 10 }, () => ids[Math.floor(r() * ids.length)] as string); + for (const id of new Set(picks)) { + cases.push(base(["show", id], `show-${id}`)); + cases.push(base(["view", id, "--full"], `show-full-${id}`)); + } + return cases; +} + +const ONE_TASK = "# Backlog\n\n## Queued\n\n- [ ] one-a1 - The one task (repo: r1)\n"; +const TWO_TASKS = + "## In flight\n\n- [ ] dep-b2 - Blocker\n\n## Queued\n\n- [ ] user-c3 - Waits blocked-by: dep-b2\n Body text\n"; + +/** Behaviour that does not depend on a backlog's content: parsing, errors, help, configuration. */ +export function fixedCases(): Case[] { + const f = (args: string[], name: string, extra: Partial<Case> = {}): Case => ({ + name: `fixed/${name}`, + args, + files: { [BACKLOG]: ONE_TASK }, + ...extra, + }); + return [ + // version and help + f(["--version"], "version"), + f(["-v"], "version-v"), + f(["-V"], "version-V"), + f(["task", "--version"], "noun-version"), + f(["list", "--help"], "help-list"), + f(["show", "--help"], "help-show"), + f(["view", "--help"], "help-view"), + f(["ready", "--help"], "help-ready"), + f(["task", "list", "--help"], "help-noun-list"), + f(["list", "--bogus", "--help"], "help-wins"), + f(["frobnicate", "--help"], "help-unknown"), + // command-line errors + f(["frobnicate"], "unknown-command"), + f(["task", "frobnicate"], "unknown-command-noun"), + f(["--foo", "list"], "leading-flag"), + f(["-x"], "leading-short-flag"), + f(["task", "--foo"], "leading-flag-noun"), + f(["show"], "show-no-id"), + f(["show", "one-a1", "two"], "show-two-ids"), + f(["show", "--bogus", "one-a1"], "show-unknown-flag"), + f(["show", "-x"], "show-short-flag"), + f(["show", "bad id!"], "show-bad-id"), + f(["show", ""], "show-empty-id"), + f(["show", " "], "show-blank-id"), + f(["show", ".hidden"], "show-dot-id"), + f(["show", "one-a1", "--full", "--full"], "show-full-twice"), + f(["list", "--state", "bogus"], "list-bad-state"), + f(["list", "--state"], "list-state-novalue"), + f(["list", "--state", "--blocked"], "list-state-flaglike"), + f(["list", "--limit", "-1"], "list-limit-negative"), + f(["list", "--limit", "abc"], "list-limit-text"), + f(["list", "--limit", "1.5"], "list-limit-float"), + f(["list", "--limit", "99999999999999999999"], "list-limit-huge"), + f(["list", "--limit", "9007199254740991"], "list-limit-maxsafe"), + f(["list", "--limit", "9007199254740992"], "list-limit-unsafe"), + f(["list", "--limit", "007"], "list-limit-leading-zero"), + f(["list", "--fields", "nope,body"], "list-bad-field"), + f(["list", "--fields", "id"], "list-field-already-default"), + f(["list", "--fields="], "list-fields-empty"), + f(["list", "--fields", " , ,"], "list-fields-blank"), + f(["list", "--repo="], "list-repo-empty"), + f(["list", "--repo", "a\nb"], "list-repo-multiline"), + f(["list", "--repo"], "list-repo-novalue"), + f(["list", "--kind", " "], "list-kind-blank"), + f(["list", "extra"], "list-positional"), + f(["list", "--bogus"], "list-unknown-flag"), + f(["list", "--blocked", "--blocked"], "list-blocked-twice"), + f(["ready", "extra"], "ready-positional"), + f(["ready", "--bogus"], "ready-unknown-flag"), + f(["ready", "--repo", "r1", "--repo", "r2"], "ready-repo-twice"), + // global flags and suggestion suffixes + f(["list", "--backend", "markdown"], "backend-markdown"), + f(["list", "--backend=markdown"], "backend-markdown-eq"), + f(["list", "--backend", "sqlite"], "backend-unsupported"), + f(["list", "--backend"], "backend-novalue"), + f(["list", "--backend="], "backend-empty"), + f(["list", "--file"], "file-novalue"), + f(["list", "--file="], "file-empty"), + f(["list", "--file", "a\nb"], "file-multiline"), + f(["list", "--file", "missing.md"], "file-missing"), + f(["list", "--file", "x y.md"], "file-space", { files: { "x y.md": ONE_TASK } }), + f(["ready", "--file", "it's.md"], "file-quote", { files: { "it's.md": ONE_TASK } }), + f(["list", "--file", "back`tick.md"], "file-backtick", { files: { "back`tick.md": ONE_TASK } }), + f(["list", "--file", "a.md", "--file", "b.md"], "file-twice", { files: { "a.md": ONE_TASK, "b.md": TWO_TASKS } }), + f(["show", "none", "--file", "a.md", "--backend", "markdown"], "notfound-globals", { files: { "a.md": ONE_TASK } }), + f(["list", "--repo", "r1", "--file", "a.md"], "list-filter-and-globals", { files: { "a.md": ONE_TASK } }), + f(["ready", "--repo", "x y", "--file", "a.md"], "ready-filter-quoted", { files: { "a.md": ONE_TASK } }), + f(["--file", "a.md", "list"], "globals-before-command"), + // file discovery and file content + f(["list"], "discover-backlog", { files: { "backlog.md": ONE_TASK } }), + f(["list"], "discover-data-backlog", { files: { "data/backlog.md": TWO_TASKS } }), + f(["list"], "discover-prefers-root", { files: { "backlog.md": ONE_TASK, "data/backlog.md": TWO_TASKS } }), + f(["list"], "no-backlog", { files: {} }), + f(["ready"], "no-backlog-ready", { files: {} }), + f(["list"], "empty-file", { files: { "backlog.md": "" } }), + f(["list"], "only-newline", { files: { "backlog.md": "\n" } }), + f(["list"], "preamble-only", { files: { "backlog.md": "# Backlog\n\nNothing here.\n" } }), + f(["list"], "bom", { files: { "backlog.md": "" + ONE_TASK } }), + f(["list"], "invalid-utf8", { + files: { "backlog.md": Buffer.concat([Buffer.from("## Queued\n\n- [ ] bad-a1 - caf"), Buffer.from([0xc3, 0x28, 0xff, 0xe2, 0x82]), Buffer.from(" tail\n")]) }, + }), + f(["list"], "crlf", { files: { "backlog.md": ONE_TASK.replace(/\n/g, "\r\n") } }), + f(["list"], "backlog-is-directory", { files: { "backlog.md/x": "y" } }), + f(["show", "user-c3"], "show-blocked-hints", { files: { "backlog.md": TWO_TASKS } }), + f(["show", "user-c3", "--file", "backlog.md"], "show-blocked-hints-globals", { files: { "backlog.md": TWO_TASKS } }), + f(["list", "--blocked"], "list-blocked-fixed", { files: { "backlog.md": TWO_TASKS } }), + // environment and config files + f(["list"], "env-file", { env: { TASKS_AXI_FILE: "other.md" }, files: { "other.md": TWO_TASKS } }), + f(["list"], "env-file-empty", { env: { TASKS_AXI_FILE: "" } }), + f(["list", "--file", "backlog.md"], "flag-beats-env", { env: { TASKS_AXI_FILE: "other.md" }, files: { "other.md": TWO_TASKS, "backlog.md": ONE_TASK } }), + f(["list"], "env-backend", { env: { TASKS_AXI_BACKEND: "linear" } }), + f(["list"], "env-backend-empty", { env: { TASKS_AXI_BACKEND: "" } }), + f(["list"], "toml-path", { files: { ".tasks.toml": '[markdown]\npath = "docs/t.md"\n', "docs/t.md": TWO_TASKS } }), + f(["list"], "toml-path-single-quotes", { files: { ".tasks.toml": "[markdown]\npath = 'docs/t.md' # comment\n", "docs/t.md": TWO_TASKS } }), + f(["list"], "toml-backend", { files: { ".tasks.toml": 'backend = "jira"\n' } }), + f(["list"], "toml-backend-ok", { files: { ".tasks.toml": 'backend = "markdown"\n' } }), + f(["list"], "toml-bad-line", { files: { ".tasks.toml": "nonsense\n" } }), + f(["list"], "toml-bad-value", { files: { ".tasks.toml": "backend = markdown\n" } }), + f(["list"], "toml-unterminated", { files: { ".tasks.toml": 'backend = "markdown\n' } }), + f(["list"], "toml-backend-number", { files: { ".tasks.toml": "backend = 3\n" } }), + f(["list"], "toml-done-keep-ok", { files: { ".tasks.toml": "[markdown]\ndone_keep = 3\n" } }), + f(["list"], "toml-done-keep-negative", { files: { ".tasks.toml": "[markdown]\ndone_keep = -2\n" } }), + f(["list"], "toml-done-keep-text", { files: { ".tasks.toml": '[markdown]\ndone_keep = "3"\n' } }), + f(["list"], "toml-done-keep-huge", { files: { ".tasks.toml": "[markdown]\ndone_keep = 99999999999999999999\n" } }), + f(["list"], "toml-path-empty", { files: { ".tasks.toml": '[markdown]\npath = ""\n' } }), + f(["list"], "toml-other-table", { files: { ".tasks.toml": "[server]\nport = 1\nnonsense\n" } }), + f(["list"], "toml-crlf", { files: { ".tasks.toml": '[markdown]\r\npath = "docs/t.md"\r\n', "docs/t.md": TWO_TASKS } }), + f(["list"], "toml-archive-is-backlog", { files: { ".tasks.toml": '[markdown]\narchive = "backlog.md"\n' } }), + f(["list"], "toml-archive-other", { files: { ".tasks.toml": '[markdown]\narchive = "old.md"\n' } }), + f(["list"], "backlog-named-done-archive", { files: { ".tasks.toml": '[markdown]\npath = "done-archive.md"\n', "done-archive.md": ONE_TASK } }), + f(["list"], "backlog-named-note-archive", { files: { ".tasks.toml": '[markdown]\npath = "note-archive.md"\n', "note-archive.md": ONE_TASK } }), + f(["list"], "home-config-path", { home: { ".tasks-axi/config.toml": '[markdown]\npath = "h.md"\n' }, files: { "h.md": TWO_TASKS } }), + f(["list"], "home-config-bad", { home: { ".tasks-axi/config.toml": "nonsense\n" } }), + f(["list"], "project-beats-home", { + home: { ".tasks-axi/config.toml": '[markdown]\npath = "h.md"\n' }, + files: { ".tasks.toml": '[markdown]\npath = "p.md"\n', "h.md": ONE_TASK, "p.md": TWO_TASKS }, + }), + f(["list", "--file", "backlog.md"], "flag-beats-toml", { files: { ".tasks.toml": '[markdown]\npath = "p.md"\n', "p.md": TWO_TASKS, "backlog.md": ONE_TASK } }), + ]; +} + +const REFUSED = ["add", "create", "start", "done", "close", "reopen", "update", "edit", "rm", "delete", "block", "unblock", "hold", "unhold", "public-followup", "mv", "prune", "render", "setup"]; + +/** Cases only tasks-axi-rs runs: it must refuse, loudly. */ +export function refusalCases(): Case[] { + const files = { [BACKLOG]: ONE_TASK }; + const cases: Case[] = REFUSED.map((c) => ({ name: `refuse/${c}`, args: [c, "x-1"], files })); + cases.push({ name: "refuse/noun-add", args: ["task", "add", "x-1", "t"], files }); + cases.push({ name: "refuse/dashboard", args: [], files }); + cases.push({ name: "refuse/dashboard-noun", args: ["task"], files }); + const followup = + "## Queued\n\n- [ ] pf-a1 - Needs a reply (kind: public-followup)\n <!-- tasks-axi:public-followup/v1:eyJ4IjoxfQ -->\n- [ ] plain-b2 - Plain\n"; + for (const args of [["list"], ["ready"], ["show", "plain-b2"]]) { + cases.push({ name: `refuse/public-followup-${args[0]}`, args, files: { [BACKLOG]: followup } }); + } + return cases; +} diff --git a/examples/tasks-axi-rust/harness/differential.ts b/examples/tasks-axi-rust/harness/differential.ts new file mode 100644 index 0000000000..f31c446d5a --- /dev/null +++ b/examples/tasks-axi-rust/harness/differential.ts @@ -0,0 +1,99 @@ +// Differential harness: run the real tasks-axi and tasks-axi-rs over the same synthetic +// backlogs and invocations and require byte-identical stdout, the same exit code and empty +// stderr from both. Then check that everything tasks-axi-rs does not implement is refused. +// +// bun harness/differential.ts [--seeds N] [--start S] [--jobs J] [--only SUBSTRING] [--keep] +// +// Environment: TASKS_AXI_BIN (default `tasks-axi`), TASKS_AXI_RS_BIN (default: the debug binary +// under $CARGO_TARGET_DIR or ./target). + +import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { backlogCases, fixedCases, refusalCases, type Case } from "./cases.js"; +import { makeSandbox, pool, run, scratchRoot } from "./sandbox.js"; + +const args = process.argv.slice(2); +const opt = (name: string, fallback: string): string => { + const i = args.indexOf(`--${name}`); + return i >= 0 ? (args[i + 1] ?? fallback) : fallback; +}; +const SEEDS = Number(opt("seeds", "40")); +const START = Number(opt("start", "1")); +const JOBS = Number(opt("jobs", "4")); +const ONLY = opt("only", ""); +const KEEP_FAILURES = opt("report-dir", ""); + +const REAL = process.env.TASKS_AXI_BIN ?? "tasks-axi"; +const target = process.env.CARGO_TARGET_DIR ?? resolve(import.meta.dirname, "..", "target"); +const RUST = process.env.TASKS_AXI_RS_BIN ?? join(target, "debug", "tasks-axi-rs"); +if (!existsSync(RUST)) { + console.error(`tasks-axi-rs binary not found at ${RUST}; build it (cargo build -p tasks-axi-rs) or set TASKS_AXI_RS_BIN`); + process.exit(2); +} + +const show = (b: Buffer): string => JSON.stringify(b.toString("utf8")); + +interface Failure { + name: string; + why: string; +} +const failures: Failure[] = []; +let compared = 0; +let refused = 0; + +async function differential(c: Case, root: string): Promise<void> { + const sb = makeSandbox(root, c.name, c); + try { + const [real, rs] = await Promise.all([run(REAL, c, sb), run(RUST, c, sb)]); + compared++; + const why: string[] = []; + if (!real.stdout.equals(rs.stdout)) why.push(`stdout differs\n real: ${show(real.stdout)}\n rust: ${show(rs.stdout)}`); + if (real.code !== rs.code) why.push(`exit code real=${real.code} rust=${rs.code}`); + if (real.stderr.length > 0 || rs.stderr.length > 0) why.push(`stderr real=${show(real.stderr)} rust=${show(rs.stderr)}`); + if (why.length > 0) { + failures.push({ name: `${c.name} [${c.args.join(" ")}]`, why: why.join("\n ") }); + if (KEEP_FAILURES) { + mkdirSync(KEEP_FAILURES, { recursive: true }); + writeFileSync(join(KEEP_FAILURES, `${c.name.replace(/[^A-Za-z0-9._-]/g, "_")}.json`), JSON.stringify({ args: c.args, files: Object.keys(c.files ?? {}) })); + } + } + } finally { + sb.dispose(); + } +} + +async function refusal(c: Case, root: string): Promise<void> { + const sb = makeSandbox(root, c.name, c); + try { + const rs = await run(RUST, c, sb); + refused++; + const out = rs.stdout.toString("utf8"); + const problems: string[] = []; + if (rs.code === 0) problems.push("exited 0"); + if (rs.stderr.length > 0) problems.push(`wrote to stderr: ${show(rs.stderr)}`); + if (!/^error: .*\ncode: UNSUPPORTED\nhelp/.test(out)) problems.push(`not a clear UNSUPPORTED refusal: ${show(rs.stdout)}`); + if (problems.length > 0) failures.push({ name: `${c.name} [${c.args.join(" ")}]`, why: problems.join("; ") }); + } finally { + sb.dispose(); + } +} + +const root = scratchRoot(); +const started = Date.now(); +try { + const all: Case[] = [...fixedCases()]; + for (let s = START; s < START + SEEDS; s++) all.push(...backlogCases(s)); + const diffCases = all.filter((c) => c.name.includes(ONLY)); + const refCases = refusalCases().filter((c) => c.name.includes(ONLY)); + await pool(diffCases, JOBS, (c) => differential(c, root)); + await pool(refCases, JOBS, (c) => refusal(c, root)); +} finally { + const { rmSync } = await import("node:fs"); + rmSync(root, { recursive: true, force: true }); +} + +const secs = ((Date.now() - started) / 1000).toFixed(1); +for (const f of failures.slice(0, 25)) console.error(`FAIL ${f.name}\n ${f.why}`); +if (failures.length > 25) console.error(`... and ${failures.length - 25} more`); +console.log(`differential: ${compared} compared, ${refused} refusals checked, ${failures.length} failed (${secs}s)`); +process.exit(failures.length === 0 ? 0 : 1); diff --git a/examples/tasks-axi-rust/harness/golden.ts b/examples/tasks-axi-rust/harness/golden.ts new file mode 100644 index 0000000000..0883a41dd6 --- /dev/null +++ b/examples/tasks-axi-rust/harness/golden.ts @@ -0,0 +1,76 @@ +// Record golden outputs from the REAL tasks-axi, so `cargo test` can check tasks-axi-rs against +// them with no node in sight. +// +// bun harness/golden.ts # rewrite crates/tasks-axi-rs/tests/golden/ +// +// Format (crates/tasks-axi-rs/tests/golden/golden.txt): one record per case, tab-separated lines +// case<TAB>name arg<TAB>text env<TAB>KEY<TAB>text +// file<TAB>path<TAB>fixture home<TAB>path<TAB>fixture +// code<TAB>n stdout<TAB>text (end of record: a blank line) +// Text is escaped (\\ \n \r \t); a fixture is a file under fixtures/ holding the bytes to write. + +import { createHash } from "node:crypto"; +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { join, resolve } from "node:path"; +import { backlogCases, fixedCases, type Case } from "./cases.js"; +import { makeSandbox, run, scratchRoot, type FileMap } from "./sandbox.js"; + +const REAL = process.env.TASKS_AXI_BIN ?? "tasks-axi"; +const OUT = resolve(import.meta.dirname, "..", "crates", "tasks-axi-rs", "tests", "golden"); +const SEEDS = [1, 2, 3]; +// Per backlog: the commands that between them reach every column set, hint and group. +const KEEP = /\/(list|list-queued|list-held|list-blocked|list-allfields|list-limit1|ready|ready-held|ready-repo|show-missing)$|\/show(-full)?-/; + +const esc = (s: string): string => s.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t"); + +function selected(): Case[] { + const cases: Case[] = [...fixedCases()]; + for (const s of SEEDS) { + const all = backlogCases(s).filter((c) => KEEP.test(c.name)); + const shows = all.filter((c) => c.args[0] === "show" || c.args[0] === "view").slice(0, 4); + cases.push(...all.filter((c) => c.args[0] !== "show" && c.args[0] !== "view"), ...shows); + } + return cases; +} + +rmSync(OUT, { recursive: true, force: true }); +mkdirSync(join(OUT, "fixtures"), { recursive: true }); +const written = new Set<string>(); +const fixture = (content: string | Buffer): string => { + const buf = typeof content === "string" ? Buffer.from(content, "utf8") : content; + const name = createHash("sha256").update(buf).digest("hex").slice(0, 16) + ".bin"; + if (!written.has(name)) { + writeFileSync(join(OUT, "fixtures", name), buf); + written.add(name); + } + return name; +}; +const tree = (kind: string, files: FileMap | undefined): string[] => + Object.entries(files ?? {}).map(([path, content]) => `${kind}\t${esc(path)}\t${fixture(content)}`); + +const root = scratchRoot(); +const records: string[] = []; +try { + for (const c of selected()) { + const sb = makeSandbox(root, c.name, c); + const r = await run(REAL, c, sb); + sb.dispose(); + if (r.stderr.length > 0) throw new Error(`${c.name}: the real tool wrote to stderr`); + records.push( + [ + `case\t${c.name}`, + ...c.args.map((a) => `arg\t${esc(a)}`), + ...Object.entries(c.env ?? {}).map(([k, v]) => `env\t${k}\t${esc(v)}`), + ...tree("file", c.files), + ...tree("home", c.home), + `code\t${r.code}`, + `stdout\t${esc(r.stdout.toString("utf8"))}`, + "", + ].join("\n"), + ); + } +} finally { + rmSync(root, { recursive: true, force: true }); +} +writeFileSync(join(OUT, "golden.txt"), records.join("\n") + "\n"); +console.log(`golden: ${records.length} cases, ${written.size} fixtures`); diff --git a/examples/tasks-axi-rust/harness/sandbox.ts b/examples/tasks-axi-rust/harness/sandbox.ts new file mode 100644 index 0000000000..f29b14adbd --- /dev/null +++ b/examples/tasks-axi-rust/harness/sandbox.ts @@ -0,0 +1,95 @@ +// Run one invocation of a binary in a throwaway sandbox (a cwd and a HOME under $DEV_SCRATCH, +// RAM-backed), capturing stdout, stderr and the exit code byte-for-byte. + +import { spawn } from "node:child_process"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +export type FileMap = Record<string, string | Buffer>; + +export interface Invocation { + args: string[]; + /** Files written under the working directory. */ + files?: FileMap; + /** Files written under HOME. */ + home?: FileMap; + /** Extra environment (TASKS_AXI_FILE, ...). HOME, TZ and PATH are always set. */ + env?: Record<string, string>; +} + +export interface Result { + stdout: Buffer; + stderr: Buffer; + code: number | null; +} + +export function scratchRoot(): string { + const base = process.env.DEV_SCRATCH && process.env.DEV_SCRATCH !== "" ? process.env.DEV_SCRATCH : tmpdir(); + mkdirSync(base, { recursive: true }); + return mkdtempSync(join(base, "tasks-axi-harness-")); +} + +function writeTree(root: string, files: FileMap | undefined): void { + for (const [rel, content] of Object.entries(files ?? {})) { + const full = join(root, rel); + mkdirSync(dirname(full), { recursive: true }); + writeFileSync(full, content); + } +} + +export interface Sandbox { + cwd: string; + home: string; + dispose(): void; +} + +export function makeSandbox(root: string, name: string, inv: Invocation): Sandbox { + const dir = mkdtempSync(join(root, `${name.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 40)}-`)); + const cwd = join(dir, "cwd"); + const home = join(dir, "home"); + mkdirSync(cwd, { recursive: true }); + mkdirSync(home, { recursive: true }); + writeTree(cwd, inv.files); + writeTree(home, inv.home); + return { cwd, home, dispose: () => rmSync(dir, { recursive: true, force: true }) }; +} + +export function run(bin: string, inv: Invocation, sb: Sandbox, timeoutMs = 30_000): Promise<Result> { + return new Promise((resolve, reject) => { + const env: Record<string, string> = { + PATH: process.env.PATH ?? "/usr/bin:/bin", + HOME: sb.home, + TZ: "UTC", + LANG: "C.UTF-8", + ...(inv.env ?? {}), + }; + const child = spawn(bin, inv.args, { cwd: sb.cwd, env, stdio: ["ignore", "pipe", "pipe"] }); + const out: Buffer[] = []; + const err: Buffer[] = []; + const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs); + child.stdout.on("data", (d: Buffer) => out.push(d)); + child.stderr.on("data", (d: Buffer) => err.push(d)); + child.on("error", (e) => { + clearTimeout(timer); + reject(e); + }); + child.on("close", (code) => { + clearTimeout(timer); + resolve({ stdout: Buffer.concat(out), stderr: Buffer.concat(err), code }); + }); + }); +} + +/** Run `work` over `items` with at most `n` in flight. */ +export async function pool<T>(items: T[], n: number, work: (item: T) => Promise<void>): Promise<void> { + let next = 0; + const lane = async (): Promise<void> => { + for (;;) { + const i = next++; + if (i >= items.length) return; + await work(items[i] as T); + } + }; + await Promise.all(Array.from({ length: n }, lane)); +} diff --git a/examples/tasks-axi-rust/harness/synthetic-backlog.ts b/examples/tasks-axi-rust/harness/synthetic-backlog.ts new file mode 100644 index 0000000000..5f4dda74e7 --- /dev/null +++ b/examples/tasks-axi-rust/harness/synthetic-backlog.ts @@ -0,0 +1,188 @@ +// Seeded generator of SYNTHETIC markdown backlogs. Nothing here is copied from a real backlog: +// every id, title and tag is built from the small vocabularies below. The same seed always +// gives the same file, so a failing seed is a reproducer. + +export function mulberry32(seed: number): () => number { + let a = seed >>> 0; + return () => { + a = (a + 0x6d2b79f5) >>> 0; + let t = a; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +type Rng = () => number; +const pick = <T>(r: Rng, xs: readonly T[]): T => xs[Math.floor(r() * xs.length)] as T; +const chance = (r: Rng, p: number): boolean => r() < p; +const int = (r: Rng, lo: number, hi: number): number => lo + Math.floor(r() * (hi - lo + 1)); + +const WORDS = [ + "adopt", "lease", "widget", "rewrite", "service", "cache", "index", "parser", "gateway", "queue", + "migrate", "audit", "retry", "backoff", "schema", "router", "metrics", "flaky", "test", "cleanup", + "café", "naïve", "日本語", "Ünïcode", "ß", "Ω", "résumé", "tab\there", "quote\"s", "comma,s", "colon: here", + "\u001b[0m", "100%", "a#b", "[bracket]", "{brace}", "-dash", "true", "null", "42", "3.14", " spaced ", +]; +const REPOS = ["widgets", "svc", "docs-site", "infra", "a/b", "repo with space", "x:y", "é-repo", "7", "true"]; +const KINDS = ["task", "scout", "ship", "docs", "secondmate", "chore", "kind with space", "a,b"]; +const HOLD_KINDS = ["captain", "external", "load", "parked", "future"]; +const LEADING = ["SHIP", "SCOUT", "DOCS-ONLY", "PERSISTENT SECONDMATE", "SHIPPING", "SCOUTS", "ship"]; +const PAST = ["2000-01-01", "2001-06-15", "2010-12-31"]; +const FUTURE = ["2999-12-31", "2500-01-01", "3000-06-15"]; +const ANY_DATE = ["2026-09-30", "2026-10-01", "2026-10-02", "2025-01-01", "2024-02-29"]; +const URLS = [ + "https://github.com/o/r/pull/42", + "https://github.com/o/r/pull/7).", + "https://github.com/o/r/issues/9", + "https://git.example.org/o/r/pulls/12", + "https://github.com/o/r/pulls/3", + "https://github.com/o/r/pull/042", + "https://example.com/docs/page?x=1,2;", + "http://plain.example.net/a/b.", + "data/some-task/report.md", + "see data/other-x1/report.md.", +]; + +function word(r: Rng): string { + return pick(r, WORDS); +} +function sentence(r: Rng, n: number): string { + return Array.from({ length: n }, () => word(r)).join(" "); +} + +function slug(r: Rng, used: string[]): string { + if (used.length > 0 && chance(r, 0.04)) return pick(r, used); // duplicate id + const heads = ["alpha", "beta", "gamma", "fm-x", "sm-idle", "Homemux", "a.b", "x_y", "k9", "Z", "t"]; + return `${pick(r, heads)}-${Math.floor(r() * 1296).toString(36).padStart(2, "0")}${chance(r, 0.1) ? "." + int(r, 1, 9) : ""}`; +} + +/** A title of exactly `len` UTF-16 units, with an astral character straddling the cut when asked. */ +function boundaryText(r: Rng, len: number, astralAt: number | null): string { + let s = ""; + while (s.length < len) s += word(r).replace(/[()]/g, "") + " "; + s = s.slice(0, len); + if (astralAt !== null && astralAt + 2 <= s.length) s = s.slice(0, astralAt) + "😀" + s.slice(astralAt + 2); + return s.replace(/\s+$/, "x"); +} + +function title(r: Rng): string { + const mode = int(r, 0, 9); + if (mode === 0) return boundaryText(r, int(r, 76, 84), pick(r, [null, 78, 79, 80])); + if (mode === 1) return boundaryText(r, int(r, 150, 300), null); + const lead = chance(r, 0.2) ? pick(r, LEADING) + " " : ""; + let t = lead + sentence(r, int(r, 1, 9)); + if (chance(r, 0.15)) t += ` (reported ${pick(r, ANY_DATE)}): ${word(r)}`; // mid-sentence parenthetical + if (chance(r, 0.15)) t += " " + pick(r, URLS); + if (chance(r, 0.05)) t += " 😀🙂"; + return t; +} + +function tags(r: Rng, state: string, ids: string[]): string { + const parts: string[] = []; + if (chance(r, 0.35)) parts.push(`(repo: ${chance(r, 0.04) ? " " : pick(r, REPOS)})`); + if (chance(r, 0.2)) parts.push(`(kind: ${chance(r, 0.04) ? " " : pick(r, KINDS)})`); + if (chance(r, 0.3)) parts.push(`(priority: ${int(r, 0, 4)})`); + if (chance(r, 0.05)) parts.push(`(priority: 9)`); + if (chance(r, 0.35)) parts.push(`(since ${pick(r, ANY_DATE)})`); + if (state === "done" && chance(r, 0.7)) parts.push(`(${pick(r, ["merged", "reported", "done", "closed"])} ${pick(r, ANY_DATE)})`); + if (chance(r, 0.2)) { + parts.push(`(hold: ${chance(r, 0.04) ? " " : sentence(r, int(r, 1, 3))})`); + if (chance(r, 0.7)) parts.push(`(hold-kind: ${pick(r, HOLD_KINDS)})`); + if (chance(r, 0.8)) parts.push(`(hold-until: ${pick(r, [...PAST, ...FUTURE])})`); + } else { + if (chance(r, 0.04)) parts.push(`(hold-kind: ${pick(r, HOLD_KINDS)})`); + if (chance(r, 0.04)) parts.push(`(hold-until: ${pick(r, FUTURE)})`); + } + // shuffle the order, since tail parsing is order-sensitive + for (let i = parts.length - 1; i > 0; i--) { + const j = Math.floor(r() * (i + 1)); + [parts[i], parts[j]] = [parts[j] as string, parts[i] as string]; + } + const deps: string[] = []; + const nDeps = chance(r, 0.35) ? int(r, 1, 3) : 0; + for (let i = 0; i < nDeps; i++) { + const type = pick(r, ["blocked-by", "blocked-by", "parent", "discovered-from"]); + const target = ids.length > 0 && chance(r, 0.8) ? pick(r, ids) : `ghost-${int(r, 1, 9)}x`; + const reason = chance(r, 0.3) ? ` - ${sentence(r, int(r, 1, 4))}` : ""; + deps.push(`${type}: ${target}${reason}`); + } + const bare = deps.filter((d) => !d.includes(" - ")); + const reasoned = deps.filter((d) => d.includes(" - ")); + const space = chance(r, 0.05) ? " " : " "; + return [...bare, ...parts, ...reasoned.slice(-1)].map((p) => space + p).join(""); +} + +// Body lines whose first or last character exercises string quoting in the printed output. +const STRANGE_BODY = [ + "## Heading", "#hash", "+1", "05", "1e5", "-3", "1.5E+3", "0", "1.", ".5", "0x10", "true", "null", "NaN", + "\u00a0nbsp-lead", "nbsp-trail\u00a0", "\ufeffbom-lead", "\u2003em-space", "\u0085next-line", "- dash", "key: value", + "\u001b[0m", "\u0001ctl", "ctl\u001f", "a,b", "x\ty", "\"quoted\"", "back\\slash", "[1]", "{x}", "trail ", " lead", +]; + +function body(r: Rng): string[] { + if (!chance(r, 0.4)) return []; + const lines: string[] = []; + const n = int(r, 1, 6); + for (let i = 0; i < n; i++) { + const k = int(r, 0, 9); + if (k === 0) lines.push(""); + else if (k === 1) lines.push(" ## Intent"); + else if (k === 2) lines.push(" extra-indented " + word(r)); + else if (k === 3) lines.push(" " + boundaryText(r, int(r, 495, 506), pick(r, [null, 498, 499, 500]))); + else if (k === 4) lines.push(" " + pick(r, STRANGE_BODY)); + else lines.push(" " + sentence(r, int(r, 2, 12))); + } + if (chance(r, 0.3)) lines.push("", ""); + return lines; +} + +export interface BacklogOptions { + seed: number; + crlf?: boolean; +} + +export function syntheticBacklog(opts: BacklogOptions): string { + const r = mulberry32(opts.seed); + const out: string[] = ["# Backlog", ""]; + if (chance(r, 0.5)) out.push("Free-form preamble. - [ ] not-a-task - preamble bullet", ""); + const ids: string[] = []; + const sections: [string, string][] = [ + ["## In flight", "in_flight"], + ["## Queued", "queued"], + ["## Done (retained)", "done"], + ]; + if (chance(r, 0.3)) sections.splice(int(r, 0, 3), 0, ["## Notes", "none"]); + if (chance(r, 0.15)) sections.push(["## Queued ", "queued"]); + if (chance(r, 0.1)) sections.push(["## DONE", "done"]); + for (const [header, state] of sections) { + out.push(header, ""); + const n = chance(r, 0.15) ? 0 : int(r, 1, 7); + for (let i = 0; i < n; i++) { + const id = slug(r, ids); + ids.push(id); + const prose = title(r) + tags(r, state, ids.slice(0, -1)); + let bullet: string; + if (state === "done") bullet = `- [x] ${id} - ${prose}`; + else if (state === "in_flight" && chance(r, 0.3)) bullet = `- **${id}** - ${prose}`; + else bullet = `- [ ] ${id} - ${prose}`; + out.push(bullet, ...body(r)); + if (chance(r, 0.3)) out.push(""); + } + } + if (chance(r, 0.1)) out.push("- [ ] stray-after-sections - stray bullet"); + let text = out.join("\n"); + if (!chance(r, 0.1)) text += "\n"; + if (opts.crlf ?? chance(r, 0.15)) text = text.replace(/\n/g, "\r\n"); + return text; +} + +/** The task ids written in a backlog's text (any section), for choosing `show` targets. */ +export function idsIn(text: string): string[] { + const found: string[] = []; + for (const line of text.split(/\r?\n/)) { + const m = /^- (?:\[[ x]\] |\*\*)([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(line); + if (m) found.push(m[1] as string); + } + return found; +} diff --git a/examples/tasks-axi-rust/metaobjects.config.ts b/examples/tasks-axi-rust/metaobjects.config.ts new file mode 100644 index 0000000000..51c627e38f --- /dev/null +++ b/examples/tasks-axi-rust/metaobjects.config.ts @@ -0,0 +1,4 @@ +import { defineConfig } from "@metaobjectsdev/cli"; +import { rustCli } from "./codegen/generators/rust-cli.js"; + +export default defineConfig({ outDir: "crates/tasks-axi-gen", generators: [rustCli()] }); diff --git a/examples/tasks-axi-rust/metaobjects/meta.cli.yaml b/examples/tasks-axi-rust/metaobjects/meta.cli.yaml new file mode 100644 index 0000000000..b478f34113 --- /dev/null +++ b/examples/tasks-axi-rust/metaobjects/meta.cli.yaml @@ -0,0 +1,108 @@ +# tasks-axi (read path) — the command surface. +# +# There is no registered vocabulary for a command line, so the surface lives in ONE +# `attr.properties` bag (the registered escape hatch, exempt from the strict-attr check) +# that the owned `rust-cli` generator reads. The README records what the bag had to carry, +# as evidence for or against a future `api.operational` + `binding.cli` proposal (ADR-0030). +# +# Conventions the generator enforces, so a typo here fails `meta gen` instead of shipping: +# - every `columns` / `extra` name must be a TaskRow column; +# - flags are parsed in the order listed (the real tool validates in that order, so the +# first error a caller sees depends on it); +# - every command text is printed byte-for-byte, with no trailing newline. +metadata: + package: tasksaxi::cli + children: + - object.value: + name: Cli + children: + - attr.properties: + name: cli + value: + bin: tasks-axi + # The tasks-axi release whose behaviour this tool reproduces. + version: "0.2.6" + # `tasks-axi task show x` is `tasks-axi show x`. + noun: task + # Flags that may appear anywhere after the command, are removed before the + # command's own flags are read, and are resolved into the backlog context. + globalFlags: + - { name: backend, type: line } + - { name: file, type: line } + # The Rust tool's own top-level help: it lists what it implements. + topHelp: |- + usage: tasks-axi-rs <command> [args] [flags] + Read path of tasks-axi 0.2.6: show, list and ready. + commands[3]: + show (alias view), list, ready + flags[4]: + --backend <name> (after command), --file <path> (after command), --help, -v/-V/--version + Every other tasks-axi command is refused with exit code 1; use tasks-axi for those. + refused: + [add, create, start, done, close, reopen, update, edit, rm, delete, block, unblock, + hold, unhold, public-followup, mv, prune, render, setup] + # What the tool answers for a command it does not implement (exit code 1). + refusal: + message: "`{command}` is not implemented by tasks-axi-rs, which ships the read path only (show, list, ready)" + suggestion: "Run the same command with the Node tasks-axi" + home: "the dashboard (tasks-axi with no command)" + commands: + show: + aliases: [view] + help: |- + usage: tasks-axi show <id> [--full] + aliases: view + examples: + tasks-axi show homemux-h7 + tasks-axi show homemux-h7 --full + flags: + - { name: full, type: bool } + positionals: { names: [id], min: 1, max: 1, type: taskId } + outputs: + - { label: task, columns: TaskDetailRow } + hints: + - { when: blocked, line: "Run `tasks-axi unblock {id} --by <other>` to clear a blocker" } + - { when: blocked, line: "Run `tasks-axi start {id}` to move it to in flight" } + list: + help: |- + usage: tasks-axi list [flags] + flags: + --state <queued|in_flight|done|held>, --repo <name>, --kind <name>, --blocked + --limit <n>, --fields <a,b,c> (extra: {extraColumns}) + examples: + tasks-axi list --state queued + tasks-axi list --repo no-mistakes --fields blocked_by,created + tasks-axi list --blocked + flags: + - { name: fields, type: columns, row: TaskRow, base: TaskListRow } + - { name: state, type: enum, enum: ListState } + - { name: repo, type: line } + - { name: kind, type: line } + - { name: blocked, type: bool } + - { name: limit, type: uint } + positionals: { names: [], min: 0, max: 0 } + outputs: + - { label: tasks, columns: TaskListRow } + hints: + - { when: nonEmpty, line: "Run `tasks-axi show <id>` for full notes on a task" } + - { when: nonEmpty, line: "Run `tasks-axi ready` to see unblocked queued work", filters: [repo] } + - { when: empty, line: "Run `tasks-axi add <id> \"<title>\"` to add a task", filters: [repo, kind] } + - { when: empty, line: "Run `tasks-axi list --state done` to see completed work", filters: [repo, kind] } + ready: + help: |- + usage: tasks-axi ready [--repo <name>] [--include-held] + List unblocked, unheld queued work dispatchable right now. + Public-followup obligations are never dispatchable and appear only in the separate + ready_public_followups group; use tasks-axi public-followup ready for their full payloads. + Held work is excluded by default; --include-held shows it in a separate held group. + flags: + - { name: repo, type: line } + - { name: include-held, type: bool } + positionals: { names: [], min: 0, max: 0 } + outputs: + - { label: ready, columns: TaskListRow } + - { label: ready_public_followups, columns: TaskListRow, extra: [delivery_state] } + - { label: held, columns: TaskListRow, extra: [hold_reason, hold_kind, hold_until] } + hints: + - { when: nonEmpty, line: "Run `tasks-axi start <id>` to dispatch one of these" } + - { when: empty, line: "Run `tasks-axi list --state queued` to see all queued work (incl. blocked)", filters: [repo] } diff --git a/examples/tasks-axi-rust/metaobjects/meta.tasks.yaml b/examples/tasks-axi-rust/metaobjects/meta.tasks.yaml new file mode 100644 index 0000000000..71619d9610 --- /dev/null +++ b/examples/tasks-axi-rust/metaobjects/meta.tasks.yaml @@ -0,0 +1,181 @@ +# tasks-axi (read path) — the data shapes the Rust tool prints and parses. +# Sigil-free YAML (ADR-0006). The command surface is NOT here: see meta.cli.yaml. +metadata: + package: tasksaxi::model + children: + # ---- shared enums (package-level abstract field.enum, referenced by `extends`) ---- + - field.enum: { name: TaskState, abstract: true, values: [queued, in_flight, done] } + - field.enum: { name: HoldKind, abstract: true, values: [captain, external, load, parked, future] } + - field.enum: + name: DepType + abstract: true + values: [blocked_by, parent, discovered_from] + stringValueMap: { blocked_by: blocked-by, parent: parent, discovered_from: discovered-from } + - field.enum: { name: LinkKind, abstract: true, values: [pr, report, doc] } + # `list --state` accepts the three states plus the derived `held`. + - field.enum: { name: ListState, abstract: true, values: [queued, in_flight, done, held] } + + # ---- value objects ---- + - object.value: + name: Hold + children: + - field.string: { name: reason, required: true } + - field.enum: { name: kind, extends: "tasksaxi::model::HoldKind" } + - field.string: { name: until } + - object.value: + name: Dep + children: + - field.enum: { name: type, required: true, extends: "tasksaxi::model::DepType" } + - field.string: { name: id, required: true } + - field.string: { name: reason } + - object.value: + name: Link + children: + - field.enum: { name: kind, required: true, extends: "tasksaxi::model::LinkKind" } + - field.string: { name: url, required: true } + + # ---- the record ---- + - object.entity: + name: Task + children: + - field.string: { name: id, required: true } + - field.string: { name: title, required: true } + - field.enum: { name: state, required: true, extends: "tasksaxi::model::TaskState" } + - field.string: { name: kind } + - field.string: { name: repo } + - field.int: { name: priority } + - field.string: { name: created } + - field.string: { name: closed } + - field.string: { name: body } + - field.object: { name: hold, objectRef: Hold } + - field.object: { name: deps, objectRef: Dep, isArray: true } + - field.object: { name: links, objectRef: Link, isArray: true } + - identity.primary: { name: id, fields: id } + + # ---- the printed row: one flat record carrying every derivable column ---- + # Each column's `row` bag says how its typed value becomes the printed cell: + # absent text printed when the value is None / empty (default: none) + # join separator for an array column (default: ",") + # trueText / falseText printed for a boolean column + # truncate display limit in UTF-16 units; the hand-written read path applies it + # (`@maxLength` is validation, not display, so truncation has no registered home.) + - object.value: + name: TaskRow + children: + - field.string: { name: id, required: true } + - field.string: + name: title + required: true + children: + - attr.properties: { name: row, value: { truncate: 80 } } + - field.enum: { name: state, required: true, extends: "tasksaxi::model::TaskState" } + - field.boolean: + name: blocked + children: + - attr.properties: { name: row, value: { trueText: "yes", falseText: "no" } } + - field.string: + name: blocked_by + isArray: true + children: + - attr.properties: { name: row, value: { join: ",", absent: "none" } } + - field.boolean: + name: held + children: + - attr.properties: { name: row, value: { trueText: "yes", falseText: "no" } } + - field.string: + name: hold_reason + children: + - attr.properties: { name: row, value: { absent: "-" } } + - field.enum: + name: hold_kind + extends: "tasksaxi::model::HoldKind" + children: + - attr.properties: { name: row, value: { absent: "-" } } + - field.string: + name: hold_until + children: + - attr.properties: { name: row, value: { absent: "-" } } + - field.string: + name: kind + children: + - attr.properties: { name: row, value: { absent: "task" } } + - field.string: + name: repo + children: + - attr.properties: { name: row, value: { absent: "-" } } + - field.int: + name: priority + children: + - attr.properties: { name: row, value: { absent: "-" } } + - field.string: + name: created + children: + - attr.properties: { name: row, value: { absent: "-" } } + - field.string: + name: closed + children: + - attr.properties: { name: row, value: { absent: "-" } } + - field.string: + name: delivery_state + children: + - attr.properties: { name: row, value: { absent: "-" } } + - field.string: + name: deps + isArray: true + children: + - attr.properties: { name: row, value: { join: ",", absent: "none" } } + - field.string: + name: links + isArray: true + children: + - attr.properties: { name: row, value: { join: ",", absent: "none" } } + - field.string: + name: body + children: + - attr.properties: { name: row, value: { absent: "", truncate: 500 } } + + # ---- column sets: which TaskRow columns a view prints, in order ---- + # Each field names its TaskRow column through `extends`, so a rename or removal in + # TaskRow fails the load instead of silently changing a printed header. + - object.value: + name: TaskListRow + children: + - field.string: { name: id, extends: "tasksaxi::model::TaskRow.id" } + - field.enum: { name: state, extends: "tasksaxi::model::TaskRow.state" } + - field.string: { name: kind, extends: "tasksaxi::model::TaskRow.kind" } + - field.string: { name: repo, extends: "tasksaxi::model::TaskRow.repo" } + - field.string: { name: title, extends: "tasksaxi::model::TaskRow.title" } + - object.value: + name: TaskDetailRow + children: + - field.string: { name: id, extends: "tasksaxi::model::TaskRow.id" } + - field.string: { name: title, extends: "tasksaxi::model::TaskRow.title" } + - field.enum: { name: state, extends: "tasksaxi::model::TaskRow.state" } + - field.boolean: { name: blocked, extends: "tasksaxi::model::TaskRow.blocked" } + - field.string: { name: blocked_by, extends: "tasksaxi::model::TaskRow.blocked_by" } + - field.boolean: { name: held, extends: "tasksaxi::model::TaskRow.held" } + - field.string: { name: hold_reason, extends: "tasksaxi::model::TaskRow.hold_reason" } + - field.enum: { name: hold_kind, extends: "tasksaxi::model::TaskRow.hold_kind" } + - field.string: { name: hold_until, extends: "tasksaxi::model::TaskRow.hold_until" } + - field.string: { name: kind, extends: "tasksaxi::model::TaskRow.kind" } + - field.string: { name: repo, extends: "tasksaxi::model::TaskRow.repo" } + - field.int: { name: priority, extends: "tasksaxi::model::TaskRow.priority" } + - field.string: { name: created, extends: "tasksaxi::model::TaskRow.created" } + - field.string: { name: closed, extends: "tasksaxi::model::TaskRow.closed" } + - field.string: { name: deps, extends: "tasksaxi::model::TaskRow.deps" } + - field.string: { name: links, extends: "tasksaxi::model::TaskRow.links" } + - field.string: { name: body, extends: "tasksaxi::model::TaskRow.body" } + + # ---- error codes: one int field per code, its exit code as the @default ---- + # An enum with @intValueMap was the first try, and the loader refuses it: the map's + # integers must be unique and the exit codes are not (every code but VALIDATION_ERROR + # exits 1). + - object.value: + name: ErrorCode + children: + - field.int: { name: VALIDATION_ERROR, default: 2 } + - field.int: { name: NOT_FOUND, default: 1 } + - field.int: { name: CONFLICT, default: 1 } + - field.int: { name: UNSUPPORTED, default: 1 } + - field.int: { name: LOCKED, default: 1 } + - field.int: { name: UNKNOWN, default: 1 } diff --git a/examples/tasks-axi-rust/scripts/gates.sh b/examples/tasks-axi-rust/scripts/gates.sh new file mode 100755 index 0000000000..f24bb856eb --- /dev/null +++ b/examples/tasks-axi-rust/scripts/gates.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Every gate for this example, in the order they are cheapest to fail. +# +# scripts/gates.sh # all of them +# scripts/gates.sh --no-node # skip the ones that need node, bun and the real tasks-axi +# +# Gates: +# 1 drift the committed generated crate is exactly what the generator emits now +# (`meta verify --codegen`, with hand edits set to fail in .metaobjects/config.json) +# 2 compile the emitted crate type-checks (`cargo check`) and is rustfmt-clean +# 3 lint clippy over the workspace, warnings denied +# 4 tests cargo test over the workspace (TOON conformance, JS-regex differential, +# recorded golden outputs of the real tasks-axi) +# 5 behaviour the differential harness: real tasks-axi vs tasks-axi-rs, byte for byte +# +# Build output goes under $CARGO_TARGET_DIR, else $DEV_SCRATCH/tasks-axi-rust-target (a RAM disk) +# else ./target; it is never left running. + +set -euo pipefail +here="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +root="$(cd "$here/../.." && pwd)" +cd "$here" + +node_gates=1 +[ "${1:-}" = "--no-node" ] && node_gates=0 + +if [ -z "${CARGO_TARGET_DIR:-}" ] && [ -n "${DEV_SCRATCH:-}" ]; then + export CARGO_TARGET_DIR="$DEV_SCRATCH/tasks-axi-rust-target" +fi + +step() { printf '\n== %s\n' "$*"; } + +if [ "$node_gates" = 1 ]; then + step "1 drift: the generated crate matches the model and the generator" + (cd "$root/server/typescript" && bun run packages/cli/bin/meta.ts verify --codegen --cwd "$here" >/dev/null) +fi + +step "2 compile: the emitted crate type-checks and is rustfmt-clean" +cargo check -p tasks-axi-gen --all-targets +rustfmt --edition 2021 --check crates/tasks-axi-gen/src/*.rs + +step "3 lint: clippy, warnings denied" +cargo clippy --workspace --all-targets -- -D warnings +cargo fmt --all -- --check + +step "4 tests: workspace" +cargo test --workspace + +if [ "$node_gates" = 1 ]; then + step "5 behaviour: differential against the real tasks-axi" + command -v tasks-axi >/dev/null || { echo "tasks-axi 0.2.6 is not on PATH (npm install -g tasks-axi@0.2.6)"; exit 2; } + cargo build -p tasks-axi-rs + bun harness/differential.ts --seeds "${DIFF_SEEDS:-40}" +fi + +printf '\nall gates passed\n' diff --git a/scripts/sync-owned-template-copies.ts b/scripts/sync-owned-template-copies.ts index ffc4a572b7..ec188350ad 100644 --- a/scripts/sync-owned-template-copies.ts +++ b/scripts/sync-owned-template-copies.ts @@ -2,8 +2,9 @@ // Re-sync this repo's OWNED copies of the reference generator templates. // // `owned-copies-current.test.ts` requires every owned copy in this repo — the -// `test-generators` package, and one set per `examples/*/codegen/` — to be exactly what -// `meta eject` writes today: the generator, and the template modules it calls +// `test-generators` package, and one set per `examples/*/codegen/` that owns a reference +// copy (an example of bespoke generators owns none; `ownedTiers()` decides) — to be exactly +// what `meta eject` writes today: the generator, and the template modules it calls // (ADR-0034 Amendment 8), which sit in a `templates/` directory beside the generators'. That // gate exists because a drifted copy lets the suites and examples keep passing while proving // nothing about what an adopter actually runs. diff --git a/server/typescript/packages/cli/test/owned-copies-current.test.ts b/server/typescript/packages/cli/test/owned-copies-current.test.ts index a0c8d85ef8..84eb3fd19d 100644 --- a/server/typescript/packages/cli/test/owned-copies-current.test.ts +++ b/server/typescript/packages/cli/test/owned-copies-current.test.ts @@ -3,7 +3,8 @@ // `meta init` / `meta eject` hand an adopter a generator and the template modules it calls // (ADR-0034 Amendment 8): `codegen/generators/<name>.ts` and `codegen/templates/`. This repo // carries owned copies of its own — the `test-generators` package, and one set per example -// under `examples/*/codegen/` — because 1.0 removed the four ownable generators from +// under `examples/*/codegen/` that owns a reference copy (an example of bespoke generators +// owns none; `ownedTiers()` decides) — because 1.0 removed the four ownable generators from // `@metaobjectsdev/codegen-ts/generators`. If a copy drifts, the suites and examples keep // passing while proving nothing about what an adopter runs. That is ADR-0034's byte-identity // blindness one level out, so it gets the same treatment. diff --git a/server/typescript/packages/cli/test/support/owned-tiers.ts b/server/typescript/packages/cli/test/support/owned-tiers.ts index 9b1de28a08..d83a199a34 100644 --- a/server/typescript/packages/cli/test/support/owned-tiers.ts +++ b/server/typescript/packages/cli/test/support/owned-tiers.ts @@ -21,6 +21,8 @@ interface OwnedTier { templates: string; } +const names = new Set<string>([...CORE_NAMES, ...REACT_NAMES, ...TANSTACK_NAMES]); + /** Same discovery the gate uses — a new owned copy is covered the moment it lands. */ export function ownedTiers(repo: string = REPO_ROOT): OwnedTier[] { const packageSrc = join(repo, "server/typescript/packages/test-generators/src"); @@ -32,14 +34,21 @@ export function ownedTiers(repo: string = REPO_ROOT): OwnedTier[] { for (const e of readdirSync(examples, { withFileTypes: true })) { if (!e.isDirectory()) continue; const generators = join(examples, e.name, "codegen", "generators"); - if (existsSync(generators)) tiers.push({ generators, templates: join(examples, e.name, "codegen", "templates") }); + if (!existsSync(generators)) continue; + // A directory of BESPOKE generators — an example's own, written from scratch rather + // than ejected (e.g. tasks-axi-rust's rust-cli.ts) — owns no reference copy, so it is + // not a tier: the gate demands each tier hold at least one eject, and the sync script + // never introduces one ("which copies an example owns is that example's decision"). + // It is a tier exactly when it already holds a file a reference generator is named for. + const holdsOwnedCopy = readdirSync(generators).some( + (f) => f.endsWith(".ts") && names.has(f.slice(0, -3)), + ); + if (holdsOwnedCopy) tiers.push({ generators, templates: join(examples, e.name, "codegen", "templates") }); } } return tiers; } -const names = new Set<string>([...CORE_NAMES, ...REACT_NAMES, ...TANSTACK_NAMES]); - export function tsFilesUnder(dir: string): string[] { if (!existsSync(dir)) return []; return readdirSync(dir, { recursive: true, withFileTypes: true })