From c401fefaf5343ce8496055b3139bd36cb0f58b63 Mon Sep 17 00:00:00 2001 From: Zachary Lowden Date: Thu, 3 Dec 2026 17:58:14 -0600 Subject: [PATCH 1/4] feat(client): versioned JSON output, validate --file, and an associate verb MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Go client gains the answers the Python client's last consumers read from its in-process objects, as a stable contract (`schema: 1`, documented in README.md → "Machine-readable output"), so packages.cairn can be retired (v1 plan Phase 5): - `recall --json`: the reader's report — status, exit, warning, scope, instance, cache_root, state, candidates, entries with sections keyed by heading. Same exit code and stderr warning as the text form; a refusal prints no document. - `validate --file PATH`: one draft, offline, judged by `write.CheckEntryBytes` — the predicate create/put run on the pod (loader parse + closed tag vocabulary) — then the write-protocol advisories. Exit 0 / 5 malformed / 2 unreadable. - `associate --scope S --paths-from FILE|- [--min-paths N] [--json]`: which entries a list of repo-relative paths names, through store.AssociatePaths (the matcher recall's focus window already uses). Go-only verb, ledger class `resolved`. - `routes --json`: every instance's cache root (via instanceCache, the read verbs' own resolver) and the scope->instance table (null when none). `--json --check` is refused. doctor --json is unchanged (the parity gate pins its bytes until Phase 5 removes it). Tests: internal/client/jsonout_test.go pins literal key sets and fixture values. Mutation sweep, 17 mutants over the four features, 17 killed, each by the test that names its feature (incl. M6: validate --file on the loader alone, no vocabulary — killed only by the off-vocabulary-tag case). Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 1 + README.md | 58 +++- flake.nix | 4 +- internal/client/associate.go | 149 +++++++++ internal/client/cli.go | 21 +- internal/client/jsonout.go | 253 ++++++++++++++ internal/client/jsonout_test.go | 492 ++++++++++++++++++++++++++++ internal/client/ledgerclass_test.go | 12 +- internal/client/options.go | 5 + internal/client/routes.go | 39 +++ internal/client/verbs.go | 111 ++++++- internal/write/tagvocab_test.go | 4 +- internal/write/write.go | 9 + tests/test_capability_ledger.py | 8 +- tests/testlib/capability_ledger.py | 16 + 15 files changed, 1152 insertions(+), 30 deletions(-) create mode 100644 internal/client/associate.go create mode 100644 internal/client/jsonout.go create mode 100644 internal/client/jsonout_test.go diff --git a/CHANGELOG.md b/CHANGELOG.md index 3054361f..66a95493 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ claim to cover them; `git log` and the PR history are the record for those. | change | anchor | what you may have to do | why it was taken | |---|---|---|---| +| **Versioned JSON output: `cairn recall --json`, `cairn routes --json`, and a new verb `cairn associate --scope S --paths-from F` (`--json`, `--min-paths N`); `cairn validate --file F` checks one draft offline with the predicate `create`/`put` apply.** Shapes carry `schema: 1` and are documented in `README.md` → *Machine-readable output*. | PR → `` | Nothing; every existing invocation prints what it did. A consumer parsing the new documents should refuse a `schema` it does not know. | The Python client's last consumers parsed its in-process report objects; these give the Go client the same answers as a stable contract, so the Python client can be retired (v1 plan Phase 5). | | **`cairn log list\|search` cover the CURRENT REPO's records by default, PER RECORD** — a search keeps the hits whose own record ran in a worktree of the repo `--repo` names (default: the working directory); a list, the sessions with any record there (showing that directory and its first prompt). New **`--all-repos`** widens to every record; `--cwd PREFIX` replaces the default and is now per record too; the two together, or neither outside a git repo, are exit 2. stderr names what was covered (`cairn: sessions=…`). The scoped request is a NEW `POST /client/v1/log/{list,search}` with a `cwd_under` form. **Index migration 5** adds `transcript_units.cwd` and `transcript_session_cwds` and zeroes every index cursor. `log query` is unchanged and unscoped | [#329](https://github.com/ZacxDev/cairn/pull/329) → `` | ⚠ **Deploy `cairn-ui` first**: migration 5 runs on start and the backfill re-reads every stream in place (rate-limited; scoped results grow as it goes, `--all-repos` is unaffected); then pin the client. An older listener answers the scoped POST 405, which exits 3 with nothing printed. ⚠ **A script that searched every repo** must add `--all-repos`; one run outside a git repo must add `--all-repos` or `--cwd`; one using `--cwd` now gets per-record hits. [`README.md`](README.md) § *`cairn log` covers the current repo* | `--repo` only picked the instance, and the index kept ONE cwd per session (its first), so a search printed other repos' (and clients') records into the caller's own captured transcript: [`internal/client/log.go`](internal/client/log.go)'s header | | **`cairn-capture` no longer HOLDS a session for a scope the routing table does not name** (on a host with more than one instance): it ships to the DEFAULT instance OWNER-ONLY (`*` declared), as a `*` session does. A session already bound to the DEFAULT instance is no longer withdrawn for it; one bound to ANOTHER instance is withdrawn from there and re-shipped whole to the default, owner-only — the `*` path (before, it was withdrawn and HELD). A scope the table EXPLICITLY routes to an instance this host does not configure is still held — the only routing hold left — and its `held_reason` now says so (`scope X is routed by the table to instance Y, which this host does not configure`). New mode **`--reevaluate-held [-apply]`** recovers the holds the old rule made | [#330](https://github.com/ZacxDev/cairn/pull/330) → `` | ⚠ **Sessions previously held stay held** until you run `--reevaluate-held` (read-only listing), then, with `-host`/`-worker`/`-capture-token-file`, `-apply`: it clears only holds whose destination answered the position probe; a 410 is listed `needs-server-restore` and left held — restore it by the server journal. The `routed back to …, which deleted this session's transcript` holds are never touched. ⚠ **If you match `held_reason` text**, the unconfigured-alias hold's wording changed. [`internal/capture/README.md`](internal/capture/README.md) step 3 and § *`--reevaluate-held`* | `scopeuse` reads header-shaped text anywhere in a transcript (test output, a source read, assistant prose) as a scope read, so a fixture name in a grep result held — and withdrew — whole sessions: measured on a two-instance host, 15 held this way, 14 on fixture names. An unnamed scope is a claim about no instance, so there is no leak to stop: [`internal/capture/route.go`](internal/capture/route.go)'s `Decide` | | **`cairn-capture --clear-held` no longer clears a hold whose session was ever bound or WITHDRAWN, nor any empty-`instance` hold in a state written by an earlier agent.** The state keeps a per-session shipping history (`bound_ever`, `withdrawn_from`, `history_kept`); `--list-held` prints a sixth field, why a `permanent` hold is kept, and `--clear-held` prints it per kept hold. EVERY first binding is now position-probed (one request per new session; a 410 there holds the session), a withdrawal is recorded before it is sent, and a 410 on an instance the session was withdrawn from HOLDS it instead of marking it `deleted`. The hold reason is neutral (`410: withdrawn or deleted there`): restore by the server journal's reason. | [#324](https://github.com/ZacxDev/cairn/pull/324) → `` | ⚠ **Existing empty-`instance` holds become `permanent`** (a legacy state cannot prove they never shipped). List them: `cairn-capture --list-held \| awk -F'\t' '$3 == "permanent"'`. ⚠ **If you parse `--list-held`**, one trailing field is added; the first five keep their positions. [`internal/capture/README.md`](internal/capture/README.md) § *`held=` is not the backlog* | DATA LOSS: an empty `instance` was read as "never shipped", but a withdrawal empties it too. `--clear-held` cleared withdrawn sessions, the next pass re-sent them unprobed, the instance answered 410 (a withdrawal is final for its uploader), and each was marked `deleted` for good — measured: 49 sessions on one host | diff --git a/README.md b/README.md index 093ff2f3..00f36dba 100644 --- a/README.md +++ b/README.md @@ -218,12 +218,12 @@ the Go client. | verb | what it does | | |---|---|---| | `sync` | refresh the local cache from the pod | | -| `recall --scope X` | the scope's digest (`--ref R`, `--list`, `--limit N`, `--page N`, `--tag`, `--ref-to`) | | +| `recall --scope X` | the scope's digest (`--ref R`, `--list`, `--limit N`, `--page N`, `--tag`, `--ref-to`; `--json` — [*Machine-readable output*](#machine-readable-output)) | | | `search 'query'` | find a hunk by text (`--all-scopes`, `--tag`, `--ref-to`) | | -| `validate` | the post-write check: parse, dropped lines, marker reachability | | +| `validate` | the post-write check: parse, dropped lines, marker reachability; `--file F` runs the same check on one draft, offline, with the predicate `create`/`put` apply | | | `ls-entries` | what the cache actually holds — the ENTRY files, never a scope's `README.md` | | | `doctor` | one call of diagnostics (`--json`, `--no-sync`) | | -| `routes` | the scope→instance table, graded (`--check`) | | +| `routes` | the scope→instance table, graded (`--check`); `--json` adds each instance's cache root | | | `append --scope S --ref R --text '…' --session ID` | append one dated, attributed bullet | writes | | `put --scope S --ref R --file F` | replace a whole entry behind `If-Match` | writes | | `create --scope S --ref R --file F` | create a new entry (refuses to overwrite) | writes | @@ -235,6 +235,7 @@ the Go client. | `audit-refs --scope X` | check entries' paths, symbols, commits and PRs against the declared sources | *Go* | | `memo-send`, `memo-check`, `memo-read`, `memo-retract` | scope memos — § [*Scope memos*](#scope-memos--messages-between-agent-sessions) | *Go* | | `transcript skeleton\|records\|tool` | read a stored session transcript; takes `--timeout` after the verb too, and a smaller positive value is raised to 90 s (a very large session's skeleton takes tens of seconds) | *Go* | +| `associate --scope X --paths-from F` | which entries of the scope a list of repo-relative paths names (`-` reads stdin; `--min-paths N`, `--json`) | *Go* | | `log list\|search QUERY\|read SESSION` | search stored transcripts: your sessions, full-text hits (one per block), or verbatim records around a hit (`--since`, `--until`, `--cwd`, `--all-repos`, `--session`, `--limit`; `read --from/--to` or `--around/--context`); `list`/`search` cover **the current repo's records by default** (per record) — § [*`cairn log` covers the current repo*](#cairn-log-covers-the-current-repo); single-user instances only | *Go* | | `log query SQL` | ONE read-only SELECT over `log_sessions` and `log_units` (your sessions only; `cairn log --help` lists the columns): a table, or the answer's JSON (`schema: 1`) with `--json`; `--limit` rows (default 100, max 1000), 1 MiB, 5 s. Single-user instances with a query role only — the guarantee and its escape battery: [`internal/transcript/README.md`](internal/transcript/README.md#the-l2-sql-route-v1-phase-2) | *Go* | @@ -347,6 +348,57 @@ clean bill of health. `arcs --check` and `audit-refs` reuse it. The `{0, 9}` ove stale write, so an unreachable store is a refused write at `7`, never a queued or local one. +### Machine-readable output + +`recall --json`, `associate --json` and `routes --json` print one JSON document on stdout. **The +shapes are a stable contract**, versioned by the integer field `schema` (today `1`): + +- **adding** a field is compatible and does not change `schema`; **removing, renaming or + re-typing** one does. Ignore fields you do not know; refuse a `schema` you do not know. +- every list is a JSON array, never `null` (`routes` is the one deliberate `null`, below); +- **the exit code is the verb's usual one** — `--json` changes stdout, nothing else. A run that + refuses before answering (usage, an unrouted scope, an unreadable cache) prints **no document**, + so an empty stdout means "no answer", never "an empty answer". Warnings still go to stderr. + +`recall --json` — the reader's answer for one scope: + +| field | | +|---|---| +| `schema`, `verb` | `1`, `"recall"` | +| `status` | the reader's verdict: `recalled`, `ref-absent`, `ref-ambiguous`, `scope-absent`, `scope-empty`, `scope-unreadable`, `tag-absent`, `ref-to-absent` | +| `exit`, `warning` | the code the command exits with, and the stderr warning (`""` when none) | +| `scope`, `instance`, `cache_root` | which scope, which configured instance, and the cache directory read | +| `state`, `state_detail` | the cache's state (`live`, `stale`, …) and the banner's detail sentence | +| `mode`, `ref` | the digest mode; the `--ref` asked for, or `null` | +| `candidates` | for `ref-ambiguous`, the refs the ask could mean | +| `known_scopes` | for `scope-absent`, the scopes the cache does hold | +| `total_in_scope` | entries in the scope | +| `entries` | the entries the digest shows in full (see below) | +| `listing`, `listing_total`, `listing_page`, `listing_pages` | the index page, for `--list` | +| `malformed`, `malformed_elsewhere` | rejected files, `{scope, filename, reason}` | + +Each entry: `ref`, `filename`, `sensitivity` (effective), `declared_sensitivity` (an unknown +marker the fail-safe overrode, else `""`), `sections` (an object keyed by the heading line as +written — `"## What it is"`, `"## Pointers"`, `"## Nuance / work-history"` — holding only the +headings the entry has), `missing_sections`, `bullet_count`, `open_count`, `near_miss_count`, +`unverifiable_count`, `tags`, `refs`, `mtime` (seconds since the epoch). + +`associate --json` — `schema`, `verb` (`"associate"`), `scope`, `instance`, `cache_root`, +`state`, `state_detail`, `min_paths`; `matched` and `below_threshold` (each +`{ref, filename, paths, evidence: [{path, component, ref, tier, matched_alias}]}`, where `tier` +is `filename` or `alias`); `ambiguous` (`{ref, tier, candidates, paths}`); `unmatched_paths`; +`considered_paths` (every non-blank input line, deduplicated, in input order); `malformed`. A +scope the cache does not hold is a usage error (2), so a typo cannot produce an empty answer; a +scope holding a malformed entry answers for the rest and exits 5. + +`routes --json` — `schema`, `verb` (`"routes"`), `multi_instance`, `instances` +(`[{alias, default, cache_root}]`, where `cache_root` is the directory every read verb uses for +that instance), `routes_source` (the table's path, or `""`) and `routes` (`{scope: alias}`, or +**`null` when no table is configured**, which is a different fact from an empty table). It reads +no cache and contacts no pod; `--json --check` is refused (2) — run `--check` on its own. + +`doctor --json` predates this contract and carries no `schema` field. + ### A sync that is already current does not re-download `GET /api/v1/snapshot` carries an **`ETag`** — `"sha256:<64 hex>"` over the diff --git a/flake.nix b/flake.nix index 175c5182..9b47bbbf 100644 --- a/flake.nix +++ b/flake.nix @@ -2000,9 +2000,11 @@ # first, `sessions`, is the arcs/sessions S2 slice; the arc registry is S3; the four # `memo-*` verbs are scope mail's S3 (decision 8 of the scope-mail plan); `sources` # is the scope-refs plan's S3 and `audit-refs` its S5; `transcript` is the transcripts - # plan's S8 (its decision 17); `log` is Phase 1 of the v1 event-log plan. + # plan's S8 (its decision 17); `log` is Phase 1 of the v1 event-log plan; `associate` is its + # Phase 5 (the Python client's last consumers move to the Go one). cat > want-go-only-verbs.txt <<'EOF' arc-register writes + associate reads arc-show reads arcs reads audit-refs reads diff --git a/internal/client/associate.go b/internal/client/associate.go new file mode 100644 index 00000000..43c726ee --- /dev/null +++ b/internal/client/associate.go @@ -0,0 +1,149 @@ +package client + +import ( + "bufio" + "fmt" + "io" + "os" + "strings" + + "github.com/ZacxDev/cairn/internal/store" +) + +// DefaultAssociateMinPaths is how many of the given paths must name an entry before `associate` +// counts it as MATCHED rather than BELOW THRESHOLD. One, the same bar `recall`'s focus window +// uses (`report.FocusMinPaths`): a caller asking "which entries do these paths touch" wants every +// entry any path names, and can raise the bar with `--min-paths`. +const DefaultAssociateMinPaths = 1 + +// Associate is `associate --scope S --paths-from FILE|-`: which entries of one scope a list of +// repo-relative paths names, read from the local cache through `store.AssociatePaths` — the same +// matcher `recall`'s focus window resolves a handoff doc's quoted paths with, so the two cannot +// disagree about what a path names. +// +// The path list is one path per line; blank lines are skipped. `-` reads stdin. Text output is +// one `\t path(s)` line per matched entry, then `unmatched\t` per path that named +// nothing; `--json` prints the `associate` document (`README.md`, "Machine-readable output"). +// +// Exit codes are the reader's: 0 answered (an empty match set included — the document says so in +// `considered_paths`/`unmatched_paths`), 2 usage, 3/4 a cache that could not be read, 5 a scope +// holding malformed entries (the answer is still printed; it covers the entries that parsed), and +// a scope the cache does not hold is a usage error (2), because a typo'd scope must not produce a +// well-formed empty answer. +func Associate(env Env, opts Options) (int, error) { + if opts.PathsFrom == "" { + fmt.Fprintln(env.Stderr, "cairn: associate requires --paths-from FILE (or - for stdin)") + return ExitUsage, nil + } + minPaths := DefaultAssociateMinPaths + if opts.MinPaths != nil { + minPaths = *opts.MinPaths + } + if minPaths < 1 { + fmt.Fprintf(env.Stderr, "cairn: --min-paths must be at least 1, got %d\n", minPaths) + return ExitUsage, nil + } + scope, scopeReason := ScopeOrReason(opts.Scope, opts.Repo) + if scopeReason != "" { + fmt.Fprintln(env.Stderr, scopeReason) + return ExitUsage, nil + } + paths, err := readPathList(env, opts.PathsFrom) + if err != nil { + fmt.Fprintf(env.Stderr, "cairn: associate: cannot read --paths-from %s: %v\n", opts.PathsFrom, err) + return ExitUsage, nil + } + + alias, label, cache, err := readInstance(opts, scope) + if err != nil { + return 0, err + } + state, err := ResolveState(cache, opts.NoSync, "", opts.Timeout, alias) + if err != nil { + return 0, err + } + if state.ExitHint != 0 { + fmt.Fprintln(env.Stderr, BannerNamed(state.Name, state.Detail, label)) + return state.ExitHint, nil + } + index, err := store.LoadStore(cache, "associated", store.VisibleScopeSet([]string{scope})) + if err != nil { + return 0, err + } + env.recordRead(alias, scope) + assoc, err := store.AssociatePaths(paths, index, scope, minPaths) + if err != nil { + fmt.Fprintf(env.Stderr, "cairn: associate: %v\n", err) + return ExitUsage, nil + } + malformed := index.MalformedIn(scope) + code := ExitOK + if len(malformed) > 0 { + code = ExitCorrupt + for _, bad := range malformed { + fmt.Fprintf(env.Stderr, "cairn: %s: malformed: %s\n", scope, bad.Line()) + } + } + + if opts.JSON { + doc := associateDoc{ + Schema: JSONSchema, + Verb: "associate", + Scope: scope, + Instance: alias, + CacheRoot: cache, + State: state.Name, + StateDetail: state.Detail, + MinPaths: minPaths, + Matched: matchesJSON(assoc.Matched), + BelowThreshold: matchesJSON(assoc.BelowThreshold), + Ambiguous: ambiguousJSON(assoc.Ambiguous), + UnmatchedPaths: nonNil(assoc.UnmatchedPaths), + ConsideredPaths: nonNil(assoc.ConsideredPaths), + Malformed: malformedJSON(malformed), + } + if err := writeJSON(env.Stdout, doc); err != nil { + return 0, err + } + return code, nil + } + fmt.Fprintln(env.Stderr, BannerNamed(state.Name, state.Detail, label)) + for _, m := range assoc.Matched { + fmt.Fprintf(env.Stdout, "%s\t%d path(s)\n", m.Entry.Ref(), m.PathCount()) + } + for _, a := range assoc.Ambiguous { + fmt.Fprintf(env.Stdout, "ambiguous\t%s\t%s\n", a.Ref, strings.Join(a.Candidates, ",")) + } + for _, p := range assoc.UnmatchedPaths { + fmt.Fprintf(env.Stdout, "unmatched\t%s\n", p) + } + return code, nil +} + +// readPathList reads one path per line from a file, or from stdin for `-`. Surrounding +// whitespace is trimmed and blank lines are skipped; nothing else is interpreted. +func readPathList(env Env, from string) ([]string, error) { + var r io.Reader + if from == "-" { + r = env.Stdin + if r == nil { + r = os.Stdin + } + } else { + f, err := os.Open(from) + if err != nil { + return nil, err + } + defer f.Close() + r = f + } + var out []string + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 0, 64*1024), 1024*1024) + for sc.Scan() { + if line := strings.TrimSpace(sc.Text()); line != "" { + out = append(out, line) + } + } + return out, sc.Err() +} diff --git a/internal/client/cli.go b/internal/client/cli.go index b8e8477a..714e5985 100644 --- a/internal/client/cli.go +++ b/internal/client/cli.go @@ -73,7 +73,7 @@ func Verbs() []Verb { // `--tag` is the scalar CATEGORY narrowing, and it composes with everything // here — it is a filter over the entry set, not a selector of one entry, so // `RejectRecallFlags` deliberately does not name it. - "--mode", "--ref", "--ref-to", "--tag", "--list", "--limit", "--page"), + "--mode", "--ref", "--ref-to", "--tag", "--list", "--limit", "--page", "--json"), Run: func(e Env, o Options) (int, error) { return Report(e, o, false) }}, {Name: "search", Ledger: LedgerResolved, Help: "search the scope for hunks", // The same `--ref-to` `recall` carries, for the same reason. Searching within @@ -124,8 +124,8 @@ func Verbs() []Verb { // only its own mirror cache, never the store and never the pod. {Name: "audit-refs", Ledger: LedgerResolved, Help: "check the scope's entries' paths, symbols, commits and PRs against its declared code sources (fetches them)", Flags: []string{"--scope", "--repo", "--json", "--no-sync"}, Run: AuditRefs}, - {Name: "validate", Ledger: LedgerResolved, Help: "the post-write check: parse, dropped lines, marker reachability", - Flags: commonReadFlags, Run: Validate}, + {Name: "validate", Ledger: LedgerResolved, Help: "the post-write check: parse, dropped lines, marker reachability; --file PATH: the same check on one draft, offline, as create/put would judge it", + Flags: append(append([]string{}, commonReadFlags...), "--file"), Run: Validate}, {Name: "ls-entries", Ledger: LedgerListed, Help: "one `/.md` per line", Flags: commonReadFlags, Run: LsEntries}, // 🔴 `doctor` TAKES NO `--scope`/`--repo`. It asks about THIS HOST and THIS @@ -152,7 +152,12 @@ func Verbs() []Verb { // instance in it, not about one scope, and a `--scope` here would invite the reading // that it grades a single row. {Name: "routes", Ledger: LedgerAll, Help: "print the scope->instance table, and grade it against reality", - Flags: []string{"--check", "--no-sync"}, Run: Routes}, + Flags: []string{"--check", "--no-sync", "--json"}, Run: Routes}, + // `associate` (Phase 5 of the v1 event-log plan): which entries of a scope a list of + // repo-relative paths names, through `store.AssociatePaths` — the matcher `recall`'s + // focus window already uses. Go-only, like every verb added after the default flip. + {Name: "associate", Ledger: LedgerResolved, Help: "which entries of the scope a list of repo-relative paths names (--paths-from FILE, or - for stdin)", + Flags: []string{"--scope", "--repo", "--no-sync", "--paths-from", "--min-paths", "--json"}, Run: Associate}, // 🔴 GO-ONLY, DECLARED: scope mail's four verbs (S3 of the scope-mail plan, decision 8) — // the `memo-*` rows of `capability_ledger.LEDGER` and `flake.nix`'s `want-go-only-verbs.txt` // make that legal. FLAT and hyphenated for the arc verbs' reason: ONE `Writes` bit each. They @@ -670,6 +675,14 @@ func Parse(argv []string) (Verb, Options, error) { opts.BodyFile = value case "--ttl": opts.TTL = value + case "--paths-from": + opts.PathsFrom = value + case "--min-paths": + n, err := strconv.Atoi(value) + if err != nil { + return verb, opts, usagef("cairn: --min-paths expects an integer, got %q", value) + } + opts.MinPaths = &n } i++ } diff --git a/internal/client/jsonout.go b/internal/client/jsonout.go new file mode 100644 index 00000000..9c79c11c --- /dev/null +++ b/internal/client/jsonout.go @@ -0,0 +1,253 @@ +package client + +import ( + "bytes" + "encoding/json" + "io" + + "github.com/ZacxDev/cairn/internal/report" + "github.com/ZacxDev/cairn/internal/store" +) + +// JSONSchema is the version every machine-readable document this client prints carries in its +// `schema` field: `recall --json`, `associate --json` and `routes --json`. The shapes are a +// CONTRACT, documented in `README.md` ("Machine-readable output"), because consumers parse them. +// +// 🔴 ADDING A FIELD IS COMPATIBLE AND DOES NOT MOVE THIS NUMBER; REMOVING, RENAMING OR RE-TYPING +// ONE DOES. A consumer is expected to ignore fields it does not know and to refuse a `schema` +// it does not know — so a breaking change that kept `1` would be read confidently and wrongly. +// +// ⚠ `doctor --json` IS NOT ON THIS LIST: it predates the versioned contract and carries no +// `schema` field. +const JSONSchema = 1 + +// writeJSON prints one document followed by a newline. `encoding/json`'s map-key sorting makes +// the bytes deterministic; HTML escaping is off because nothing here is ever embedded in HTML and +// `<`/`>`/`&` in entry text should reach a consumer as written. +func writeJSON(w io.Writer, doc any) error { + var buf bytes.Buffer + enc := json.NewEncoder(&buf) + enc.SetEscapeHTML(false) + enc.SetIndent("", " ") + if err := enc.Encode(doc); err != nil { + return err + } + _, err := w.Write(buf.Bytes()) + return err +} + +// nonNil turns a nil slice into an empty one, so an absent list prints `[]` and never `null`: +// a consumer iterating the field must not have to special-case a null. +func nonNil[T any](items []T) []T { + if items == nil { + return []T{} + } + return items +} + +// jsonMalformed is one rejected entry file. +type jsonMalformed struct { + Scope string `json:"scope"` + Filename string `json:"filename"` + Reason string `json:"reason"` +} + +func malformedJSON(items []store.MalformedEntry) []jsonMalformed { + out := make([]jsonMalformed, 0, len(items)) + for _, m := range items { + out = append(out, jsonMalformed{Scope: m.Scope, Filename: m.Filename, Reason: m.Reason}) + } + return out +} + +// jsonEntry is one recalled entry. `sections` holds every surfaced heading the entry HAS, keyed +// by the heading text; a heading the entry lacks is absent from the map and named in +// `missing_sections` instead, which is the distinction the text renderer draws too. +type jsonEntry struct { + Ref string `json:"ref"` + Filename string `json:"filename"` + Sensitivity string `json:"sensitivity"` + DeclaredSensitivity string `json:"declared_sensitivity"` + Sections map[string]string `json:"sections"` + MissingSections []string `json:"missing_sections"` + BulletCount int `json:"bullet_count"` + OpenCount int `json:"open_count"` + NearMissCount int `json:"near_miss_count"` + UnverifiableCount int `json:"unverifiable_count"` + Tags []string `json:"tags"` + Refs []string `json:"refs"` + MTime float64 `json:"mtime"` +} + +func entryJSON(e report.RecalledEntry) jsonEntry { + sections := map[string]string{} + for k, v := range e.Sections { + sections[k] = v + } + return jsonEntry{ + Ref: e.Ref, + Filename: e.Filename, + Sensitivity: e.Sensitivity, + DeclaredSensitivity: e.DeclaredSensitivity, + Sections: sections, + MissingSections: nonNil(e.MissingSections), + BulletCount: e.BulletCount, + OpenCount: e.OpenCount, + NearMissCount: e.NearMissCount, + UnverifiableCount: e.UnverifiableCount, + Tags: nonNil(e.Tags), + Refs: nonNil(e.Tasks), + MTime: e.MTime, + } +} + +func entriesJSON(items []report.RecalledEntry) []jsonEntry { + out := make([]jsonEntry, 0, len(items)) + for _, e := range items { + out = append(out, entryJSON(e)) + } + return out +} + +// recallDoc is `recall --json`. It carries the same facts the text digest prints, so a consumer +// never has to parse the banner: `status` is the reader's verdict, `state`/`state_detail` the +// cache's (live, stale, …), `cache_root` the directory the answer was read from, and `exit` the +// code the command is about to exit with. +type recallDoc struct { + Schema int `json:"schema"` + Verb string `json:"verb"` + Status string `json:"status"` + Exit int `json:"exit"` + Warning string `json:"warning"` + Scope string `json:"scope"` + Instance string `json:"instance"` + CacheRoot string `json:"cache_root"` + State string `json:"state"` + StateDetail string `json:"state_detail"` + Mode string `json:"mode"` + Ref *string `json:"ref"` + Candidates []string `json:"candidates"` + KnownScopes []string `json:"known_scopes"` + TotalInScope int `json:"total_in_scope"` + Entries []jsonEntry `json:"entries"` + Listing []jsonEntry `json:"listing"` + ListingTotal int `json:"listing_total"` + ListingPage int `json:"listing_page"` + ListingPages int `json:"listing_pages"` + Malformed []jsonMalformed `json:"malformed"` + MalformedElsewhere []jsonMalformed `json:"malformed_elsewhere"` +} + +func recallJSON(rep *report.RecallReport, state State, alias, cache string, code int, warning string) recallDoc { + var ref *string + if rep.HasRef { + r := rep.Ref + ref = &r + } + return recallDoc{ + Schema: JSONSchema, + Verb: "recall", + Status: rep.Status, + Exit: code, + Warning: warning, + Scope: rep.Scope, + Instance: alias, + CacheRoot: cache, + State: state.Name, + StateDetail: state.Detail, + Mode: rep.Mode, + Ref: ref, + Candidates: nonNil(rep.Candidates), + KnownScopes: nonNil(rep.KnownScopes), + TotalInScope: rep.TotalInScope, + Entries: entriesJSON(rep.Entries), + Listing: entriesJSON(rep.Listing), + ListingTotal: rep.ListingTotal, + ListingPage: rep.ListingPage, + ListingPages: rep.ListingPages, + Malformed: malformedJSON(rep.Malformed), + MalformedElsewhere: malformedJSON(rep.MalformedElsewhere), + } +} + +// associateDoc is `associate --json`: which entries of one scope a set of repo-relative paths +// names, through the same matcher `recall`'s focus window uses (`store.AssociatePaths`). +type associateDoc struct { + Schema int `json:"schema"` + Verb string `json:"verb"` + Scope string `json:"scope"` + Instance string `json:"instance"` + CacheRoot string `json:"cache_root"` + State string `json:"state"` + StateDetail string `json:"state_detail"` + MinPaths int `json:"min_paths"` + Matched []jsonMatch `json:"matched"` + BelowThreshold []jsonMatch `json:"below_threshold"` + Ambiguous []jsonAmbiguous `json:"ambiguous"` + UnmatchedPaths []string `json:"unmatched_paths"` + ConsideredPaths []string `json:"considered_paths"` + Malformed []jsonMalformed `json:"malformed"` +} + +type jsonEvidence struct { + Path string `json:"path"` + Component string `json:"component"` + Ref string `json:"ref"` + Tier string `json:"tier"` + MatchedAlias string `json:"matched_alias"` +} + +type jsonMatch struct { + Ref string `json:"ref"` + Filename string `json:"filename"` + Paths []string `json:"paths"` + Evidence []jsonEvidence `json:"evidence"` +} + +type jsonAmbiguous struct { + Ref string `json:"ref"` + Tier string `json:"tier"` + Candidates []string `json:"candidates"` + Paths []string `json:"paths"` +} + +func matchesJSON(items []store.SubsystemMatch) []jsonMatch { + out := make([]jsonMatch, 0, len(items)) + for _, m := range items { + ev := make([]jsonEvidence, 0, len(m.Evidence)) + for _, e := range m.Evidence { + ev = append(ev, jsonEvidence{Path: e.Path, Component: e.Component, Ref: e.Ref, + Tier: e.Tier, MatchedAlias: e.MatchedAlias}) + } + out = append(out, jsonMatch{Ref: m.Entry.Ref(), Filename: m.Entry.Filename, + Paths: nonNil(m.Paths), Evidence: ev}) + } + return out +} + +func ambiguousJSON(items []store.AmbiguousRef) []jsonAmbiguous { + out := make([]jsonAmbiguous, 0, len(items)) + for _, a := range items { + out = append(out, jsonAmbiguous{Ref: a.Ref, Tier: a.Tier, + Candidates: nonNil(a.Candidates), Paths: nonNil(a.Paths)}) + } + return out +} + +// routesDoc is `routes --json`: the instances this host is configured for, the cache root the +// reader resolves for each, and the scope -> instance table. It is the structured answer to +// "where does scope S's cache live", which otherwise has to be scraped from a recall banner. +type routesDoc struct { + Schema int `json:"schema"` + Verb string `json:"verb"` + MultiInstance bool `json:"multi_instance"` + Instances []jsonInstance `json:"instances"` + RoutesSource string `json:"routes_source"` + Routes map[string]string `json:"routes"` +} + +type jsonInstance struct { + Alias string `json:"alias"` + Default bool `json:"default"` + CacheRoot string `json:"cache_root"` +} diff --git a/internal/client/jsonout_test.go b/internal/client/jsonout_test.go new file mode 100644 index 00000000..c228fbe2 --- /dev/null +++ b/internal/client/jsonout_test.go @@ -0,0 +1,492 @@ +package client + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "slices" + "sort" + "strconv" + "strings" + "testing" +) + +// The machine-readable contracts: `recall --json`, `validate --file`, `associate` and +// `routes --json`. Consumers parse these (`README.md`, "Machine-readable output"), so every +// expectation below is a LITERAL — a key set, a value the fixture put there — and never a value +// read back out of the implementation under test. + +// decode parses one JSON document from stdout, refusing an empty stdout: a document that never +// printed would otherwise decode as "no fields" and every absence assertion would pass. +func decode(t *testing.T, stdout string) map[string]any { + t.Helper() + if strings.TrimSpace(stdout) == "" { + t.Fatal("stdout is EMPTY — no document was printed, so nothing below would be measured") + } + var doc map[string]any + dec := json.NewDecoder(strings.NewReader(stdout)) + dec.UseNumber() + if err := dec.Decode(&doc); err != nil { + t.Fatalf("stdout is not one JSON document: %v\n%s", err, stdout) + } + return doc +} + +func keysOf(m map[string]any) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// widgetEntry is an entry with every surfaced section, an alias, a tag and a ref, so each +// field of the document carries a value the fixture chose and a mutant that hard-codes an +// empty one is visible. +const widgetEntry = "---\nservice: widget-api\nscope: beta-notes\naliases: [gizmo]\n" + + "tags: [tooling]\nrefs: [gh:ZacxDev/cairn#7]\nsensitivity: personal\n---\n\n" + + "## What it is\n\nThe widget API.\n\n## Pointers\n\n- `internal/widget/main.go`\n\n" + + "## Nuance / work-history\n\n- 2000-01-01: OPEN: the retry loop.\n- 2000-01-02: settled.\n" + +func seedWidget(t *testing.T, home string) { + t.Helper() + p := filepath.Join(home, ".cache", "subsystem-store", "beta-notes", "widget-api.md") + if err := os.WriteFile(p, []byte(widgetEntry), 0o644); err != nil { + t.Fatal(err) + } +} + +// ---------------------------------------------------------------- B1: recall --json + +var recallKeys = []string{ + "cache_root", "candidates", "entries", "exit", "instance", "known_scopes", "listing", + "listing_page", "listing_pages", "listing_total", "malformed", "malformed_elsewhere", "mode", + "ref", "schema", "scope", "state", "state_detail", "status", "total_in_scope", "verb", "warning", +} + +var entryKeys = []string{ + "bullet_count", "declared_sensitivity", "filename", "missing_sections", "mtime", + "near_miss_count", "open_count", "refs", "sections", "sensitivity", "tags", + "unverifiable_count", + "ref", +} + +func TestRecallJSONCarriesTheEntryTheTextDigestShows(t *testing.T) { + home, _ := ledgerHost(t) + seedWidget(t, home) + + code, stdout, stderr := runCLI(t, "recall", "--no-sync", "--scope", "beta-notes", "--ref", "gizmo", "--json") + if code != ExitOK { + t.Fatalf("exit %d, want 0\n%s", code, stderr) + } + doc := decode(t, stdout) + if got := keysOf(doc); !slices.Equal(got, recallKeys) { + t.Fatalf("top-level keys are the contract:\n got %v\n want %v", got, recallKeys) + } + want := map[string]string{ + "schema": "1", "verb": "recall", "status": "recalled", "scope": "beta-notes", + "instance": DefaultAlias, "ref": "gizmo", "exit": "0", + "cache_root": filepath.Join(home, ".cache", "subsystem-store"), + } + for k, v := range want { + if got := jsonString(doc[k]); got != v { + t.Errorf("%s = %q, want %q", k, got, v) + } + } + entries, _ := doc["entries"].([]any) + if len(entries) != 1 { + t.Fatalf("one entry recalled by alias, got %d: %v", len(entries), doc["entries"]) + } + e := entries[0].(map[string]any) + keys := append([]string{}, entryKeys...) + sort.Strings(keys) + if got := keysOf(e); !slices.Equal(got, keys) { + t.Fatalf("entry keys are the contract:\n got %v\n want %v", got, keys) + } + for k, v := range map[string]string{ + "ref": "widget-api", "filename": "widget-api.md", "sensitivity": "personal", + "bullet_count": "2", "open_count": "1", + } { + if got := jsonString(e[k]); got != v { + t.Errorf("entry %s = %q, want %q", k, got, v) + } + } + sections := e["sections"].(map[string]any) + if got := jsonString(sections["## What it is"]); !strings.Contains(got, "The widget API.") { + t.Errorf("the `What it is` section is the body the file holds, got %q", got) + } + if got := jsonString(sections["## Pointers"]); !strings.Contains(got, "internal/widget/main.go") { + t.Errorf("the `Pointers` section is the body the file holds, got %q", got) + } + if got := e["tags"].([]any); len(got) != 1 || got[0] != "tooling" { + t.Errorf("tags = %v, want [tooling]", got) + } + if got := e["refs"].([]any); len(got) != 1 || got[0] != "gh:ZacxDev/cairn#7" { + t.Errorf("refs = %v, want [gh:ZacxDev/cairn#7]", got) + } +} + +// The verdict and the exit code are the reader's, unchanged by `--json`. The non-zero case is a +// scope whose only entry is malformed (the reader exits 3 and names it); the zero case is an +// absent ref, which the reader answers at 0 with `ref-absent`. +func TestRecallJSONKeepsTheReadersVerdictAndExitCode(t *testing.T) { + home, _ := ledgerHost(t) + seedWidget(t, home) + bad := filepath.Join(home, ".cache", "subsystem-store", "alpha-notes", "one.md") + if err := os.WriteFile(bad, []byte("---\nscope: alpha-notes\n---\nno service\n"), 0o644); err != nil { + t.Fatal(err) + } + + textCode, _, _ := runCLI(t, "recall", "--no-sync", "--scope", "alpha-notes") + code, stdout, stderr := runCLI(t, "recall", "--no-sync", "--scope", "alpha-notes", "--json") + if textCode == ExitOK { + t.Fatal("control: an all-malformed scope must exit non-zero in TEXT form, or this test measures nothing") + } + if code != textCode { + t.Fatalf("--json exited %d, the text form %d — the flag must not move the exit code", code, textCode) + } + doc := decode(t, stdout) + if got := jsonString(doc["exit"]); got != strconv.Itoa(code) { + t.Errorf("the document's exit = %q, the process exited %d", got, code) + } + if got := len(doc["malformed"].([]any)); got != 1 { + t.Errorf("malformed lists %d file(s), want 1", got) + } + if w := jsonString(doc["warning"]); w == "" || !strings.Contains(stderr, w) { + t.Errorf("the warning must be in the document AND on stderr: doc %q stderr %q", w, stderr) + } + + code, stdout, _ = runCLI(t, "recall", "--no-sync", "--scope", "beta-notes", "--ref", "no-such-thing", "--json") + doc = decode(t, stdout) + if got := jsonString(doc["status"]); got != "ref-absent" { + t.Errorf("status = %q, want ref-absent", got) + } + if entries := doc["entries"].([]any); len(entries) != 0 { + t.Errorf("an absent ref recalls nothing, got %v", entries) + } + if jsonString(doc["exit"]) != strconv.Itoa(code) { + t.Errorf("exit field %v, process %d", doc["exit"], code) + } +} + +// No answer, no document: a refusal before the reader ran prints nothing on stdout, so a +// consumer cannot mistake it for an empty answer. +func TestRecallJSONPrintsNoDocumentWhenItRefuses(t *testing.T) { + ledgerHost(t) + code, stdout, _ := runCLI(t, "recall", "--no-sync", "--scope", "ghost-scope", "--json") + if code == ExitOK { + t.Fatalf("an unroutable scope must refuse, got exit 0") + } + if strings.TrimSpace(stdout) != "" { + t.Fatalf("a refusal printed a document: %q", stdout) + } +} + +func TestSearchDoesNotAcceptJSON(t *testing.T) { + ledgerHost(t) + if code, _, _ := runCLI(t, "search", "synthetic", "--no-sync", "--scope", "beta-notes", "--json"); code != ExitUsage { + t.Fatalf("search --json is not part of the contract and must refuse at 2, got %d", code) + } +} + +// ---------------------------------------------------------------- B2: validate --file + +func draft(t *testing.T, scope, name, body string) string { + t.Helper() + dir := filepath.Join(t.TempDir(), scope) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + return p +} + +func TestValidateFileAcceptsADraftTheWritePathWouldAccept(t *testing.T) { + ledgerHost(t) + p := draft(t, "beta-notes", "widget-api.md", widgetEntry) + code, stdout, stderr := runCLI(t, "validate", "--file", p) + if code != ExitOK { + t.Fatalf("exit %d, want 0\n%s", code, stderr) + } + if want := "cairn: " + p + ": 1 of 1 entry file(s) parse, 0 malformed"; !strings.Contains(stdout, want) { + t.Fatalf("got %q, want a line containing %q", stdout, want) + } + // The advisories run too: the draft declares one OPEN bullet. + if !strings.Contains(stdout, "1 declared `OPEN:`") { + t.Errorf("the write-protocol advisories did not print:\n%s", stdout) + } +} + +func TestValidateFileRefusesADraftTheLoaderWouldReject(t *testing.T) { + ledgerHost(t) + p := draft(t, "beta-notes", "nameless.md", "---\nscope: beta-notes\n---\n\n## What it is\n\nx\n") + code, stdout, stderr := runCLI(t, "validate", "--file", p) + if code != ExitCorrupt { + t.Fatalf("exit %d, want %d (malformed)\n%s", code, ExitCorrupt, stderr) + } + if !strings.Contains(stderr, "service:") { + t.Errorf("the refusal must name the loader's reason (missing `service:`), got %q", stderr) + } + if !strings.Contains(stdout, "0 of 1 entry file(s) parse, 1 malformed") { + t.Errorf("got %q", stdout) + } +} + +// 🔴 THE CASE THAT PROVES IT IS THE WRITE PATH'S PREDICATE AND NOT THE LOADER'S. The loader +// ACCEPTS an off-vocabulary tag (an entry carrying one still reads); `create`/`put` refuse it. +// A `validate --file` built on the loader alone would pass this draft and the write would then +// be refused — the drift this verb exists to remove. +func TestValidateFileRefusesAnOffVocabularyTagLikeCreateWould(t *testing.T) { + ledgerHost(t) + body := strings.Replace(widgetEntry, "tags: [tooling]", "tags: [not-a-vocabulary-term]", 1) + p := draft(t, "beta-notes", "widget-api.md", body) + code, _, stderr := runCLI(t, "validate", "--file", p) + if code != ExitCorrupt { + t.Fatalf("exit %d, want %d — create would refuse this tag\n%s", code, ExitCorrupt, stderr) + } + if !strings.Contains(stderr, "not-a-vocabulary-term") { + t.Errorf("the refusal must name the tag, got %q", stderr) + } +} + +func TestValidateFileIsAUsageErrorForAMissingFile(t *testing.T) { + ledgerHost(t) + code, stdout, _ := runCLI(t, "validate", "--file", filepath.Join(t.TempDir(), "absent.md")) + if code != ExitUsage { + t.Fatalf("exit %d, want %d", code, ExitUsage) + } + if stdout != "" { + t.Errorf("a missing file printed a verdict: %q", stdout) + } +} + +// The scope comes from the directory holding the draft unless `--scope` names one, and the +// loader's scope rule is what decides it: front matter naming a DIFFERENT scope is overridden, +// not honoured. Measured through the one observable that depends on the scope — nothing — so +// this pins only that a draft whose front-matter scope disagrees with its directory still parses. +func TestValidateFileTakesTheScopeFromItsDirectory(t *testing.T) { + ledgerHost(t) + body := strings.Replace(widgetEntry, "scope: beta-notes", "scope: elsewhere", 1) + p := draft(t, "beta-notes", "widget-api.md", body) + if code, _, stderr := runCLI(t, "validate", "--file", p); code != ExitOK { + t.Fatalf("exit %d\n%s", code, stderr) + } +} + +// ---------------------------------------------------------------- B3: associate + +func pathList(t *testing.T, lines ...string) string { + t.Helper() + p := filepath.Join(t.TempDir(), "paths.txt") + if err := os.WriteFile(p, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil { + t.Fatal(err) + } + return p +} + +var associateKeys = []string{ + "ambiguous", "below_threshold", "cache_root", "considered_paths", "instance", "malformed", + "matched", "min_paths", "schema", "scope", "state", "state_detail", "unmatched_paths", "verb", +} + +func TestAssociateNamesTheEntriesThePathsTouch(t *testing.T) { + home, _ := ledgerHost(t) + seedWidget(t, home) + list := pathList(t, "internal/gizmo/handler.go", "docs/two.md", "", "README.md") + + code, stdout, stderr := runCLI(t, "associate", "--no-sync", "--scope", "beta-notes", "--paths-from", list, "--json") + if code != ExitOK { + t.Fatalf("exit %d\n%s", code, stderr) + } + doc := decode(t, stdout) + if got := keysOf(doc); !slices.Equal(got, associateKeys) { + t.Fatalf("keys are the contract:\n got %v\n want %v", got, associateKeys) + } + if jsonString(doc["schema"]) != "1" || jsonString(doc["verb"]) != "associate" || jsonString(doc["min_paths"]) != "1" { + t.Errorf("schema/verb/min_paths = %v/%v/%v", doc["schema"], doc["verb"], doc["min_paths"]) + } + matched := doc["matched"].([]any) + var refs []string + for _, m := range matched { + refs = append(refs, jsonString(m.(map[string]any)["ref"])) + } + sort.Strings(refs) + // `gizmo` is widget-api's ALIAS, `two` is the seeded entry's slug (a filename stem). + if want := []string{"two", "widget-api"}; !slices.Equal(refs, want) { + t.Fatalf("matched = %v, want %v", refs, want) + } + if got := toStrings(doc["unmatched_paths"]); !slices.Equal(got, []string{"README.md"}) { + t.Errorf("unmatched_paths = %v, want [README.md]", got) + } + // The blank line is skipped, not considered. + if got := toStrings(doc["considered_paths"]); len(got) != 3 { + t.Errorf("considered_paths = %v, want the three non-blank lines", got) + } +} + +func TestAssociateTextFormAndStdin(t *testing.T) { + home, _ := ledgerHost(t) + seedWidget(t, home) + var out bytes.Buffer + errFile, err := os.CreateTemp(t.TempDir(), "stderr") + if err != nil { + t.Fatal(err) + } + defer errFile.Close() + code := Run(Env{Stdout: &out, Stderr: errFile, Stdin: strings.NewReader("internal/gizmo/x.go\nnowhere/y.go\n"), + Host: func() string { return "fixture-host-000000000000" }}, + []string{"associate", "--no-sync", "--scope", "beta-notes", "--paths-from", "-"}) + if code != ExitOK { + t.Fatalf("exit %d", code) + } + if want := "widget-api\t1 path(s)\nunmatched\tnowhere/y.go\n"; out.String() != want { + t.Fatalf("got %q, want %q", out.String(), want) + } +} + +// `--min-paths` moves an entry named by fewer paths from `matched` to `below_threshold`. +func TestAssociateMinPathsIsTheBar(t *testing.T) { + home, _ := ledgerHost(t) + seedWidget(t, home) + list := pathList(t, "internal/gizmo/a.go", "internal/gizmo/b.go", "docs/two.md") + _, stdout, _ := runCLI(t, "associate", "--no-sync", "--scope", "beta-notes", "--paths-from", list, "--min-paths", "2", "--json") + doc := decode(t, stdout) + var matched, below []string + for _, m := range doc["matched"].([]any) { + matched = append(matched, jsonString(m.(map[string]any)["ref"])) + } + for _, m := range doc["below_threshold"].([]any) { + below = append(below, jsonString(m.(map[string]any)["ref"])) + } + if !slices.Equal(matched, []string{"widget-api"}) || !slices.Equal(below, []string{"two"}) { + t.Fatalf("matched %v below %v; want [widget-api] / [two]", matched, below) + } +} + +func TestAssociateRefusesAScopeTheCacheDoesNotHoldAndABadBar(t *testing.T) { + ledgerHost(t) + list := pathList(t, "a/b.go") + for name, argv := range map[string][]string{ + "unknown scope": {"associate", "--no-sync", "--scope", "alpha-notes-typo", "--paths-from", list}, + "min-paths 0": {"associate", "--no-sync", "--scope", "beta-notes", "--paths-from", list, "--min-paths", "0"}, + "no --paths-from": {"associate", "--no-sync", "--scope", "beta-notes"}, + } { + code, stdout, _ := runCLI(t, argv...) + if code == ExitOK { + t.Errorf("%s: exit 0, must refuse", name) + } + if strings.TrimSpace(stdout) != "" { + t.Errorf("%s: printed an answer: %q", name, stdout) + } + } +} + +// A scope holding a malformed entry still answers for the entries that parsed, and exits 5 so +// a caller branching on the code knows the answer is partial. +func TestAssociateOverAMalformedEntryAnswersAndExitsFive(t *testing.T) { + home, _ := ledgerHost(t) + seedWidget(t, home) + bad := filepath.Join(home, ".cache", "subsystem-store", "beta-notes", "broken.md") + if err := os.WriteFile(bad, []byte("---\nscope: beta-notes\n---\nno service\n"), 0o644); err != nil { + t.Fatal(err) + } + code, stdout, _ := runCLI(t, "associate", "--no-sync", "--scope", "beta-notes", "--paths-from", pathList(t, "internal/gizmo/a.go"), "--json") + if code != ExitCorrupt { + t.Fatalf("exit %d, want %d", code, ExitCorrupt) + } + doc := decode(t, stdout) + if got := len(doc["malformed"].([]any)); got != 1 { + t.Errorf("malformed lists %d, want 1", got) + } + if got := len(doc["matched"].([]any)); got != 1 { + t.Errorf("the parsed entry must still match, got %d", got) + } +} + +// ---------------------------------------------------------------- B4: routes --json + +func TestRoutesJSONNamesEveryInstancesCacheRootAndTheTable(t *testing.T) { + home := twoInstanceHost(t) + writeTable(t, filepath.Join(home, "config"), `{"alpha-notes": "`+DefaultAlias+`", "gamma-notes": "secondary"}`) + + code, stdout, stderr := runCLI(t, "routes", "--json") + if code != ExitOK { + t.Fatalf("exit %d\n%s", code, stderr) + } + doc := decode(t, stdout) + if got, want := keysOf(doc), []string{"instances", "multi_instance", "routes", "routes_source", "schema", "verb"}; !slices.Equal(got, want) { + t.Fatalf("keys:\n got %v\n want %v", got, want) + } + if doc["multi_instance"] != true { + t.Errorf("two instances are multi_instance, got %v", doc["multi_instance"]) + } + got := map[string]string{} + for _, raw := range doc["instances"].([]any) { + inst := raw.(map[string]any) + got[jsonString(inst["alias"])] = jsonString(inst["cache_root"]) + if (jsonString(inst["alias"]) == DefaultAlias) != (inst["default"] == true) { + t.Errorf("instance %v: default flag wrong", inst) + } + } + want := map[string]string{ + DefaultAlias: filepath.Join(home, ".cache", "subsystem-store"), + "secondary": filepath.Join(home, ".cache", "subsystem-store-secondary"), + } + if len(got) != len(want) || got[DefaultAlias] != want[DefaultAlias] || got["secondary"] != want["secondary"] { + t.Fatalf("instances = %v, want %v", got, want) + } + routes := doc["routes"].(map[string]any) + if routes["gamma-notes"] != "secondary" || routes["alpha-notes"] != DefaultAlias || len(routes) != 2 { + t.Errorf("routes = %v", routes) + } +} + +// No table is `null`, a different fact from an empty table. +func TestRoutesJSONSaysNullWhenNoTableIsConfigured(t *testing.T) { + twoInstanceHost(t) + _, stdout, _ := runCLI(t, "routes", "--json") + doc := decode(t, stdout) + if v, present := doc["routes"]; !present || v != nil { + t.Fatalf("routes = %v (present %v), want null", v, present) + } +} + +func TestRoutesJSONWithCheckIsRefused(t *testing.T) { + twoInstanceHost(t) + if code, stdout, _ := runCLI(t, "routes", "--json", "--check"); code != ExitUsage || stdout != "" { + t.Fatalf("exit %d stdout %q; want 2 and nothing", code, stdout) + } +} + +// ---------------------------------------------------------------- helpers + +func jsonString(v any) string { + switch x := v.(type) { + case nil: + return "" + case string: + return x + case json.Number: + return x.String() + case bool: + if x { + return "true" + } + return "false" + } + b, _ := json.Marshal(v) + return string(b) +} + +func toStrings(v any) []string { + var out []string + for _, x := range v.([]any) { + out = append(out, jsonString(x)) + } + return out +} diff --git a/internal/client/ledgerclass_test.go b/internal/client/ledgerclass_test.go index 81405343..d2f90a59 100644 --- a/internal/client/ledgerclass_test.go +++ b/internal/client/ledgerclass_test.go @@ -98,12 +98,22 @@ func TestEveryVerbRecordsWhatItsLedgerClassSays(t *testing.T) { "log": func(string) probe { return probe{"transcript", []string{"log", "search", "zircon", "--all-repos"}, "", nil} }, + "associate": func(home string) probe { + p := filepath.Join(home, "paths.txt") + if err := os.WriteFile(p, []byte("internal/widget/main.go\n"), 0o644); err != nil { + t.Fatal(err) + } + return probe{"offline", []string{"associate", "--no-sync", "--scope", "beta-notes", "--paths-from", p}, "beta-notes", nil} + }, } // `arcs --check` is a MODE of `arcs`, not a verb: probed beside it, under the same class. extra := []struct { verb string p probe - }{{"arcs", probe{"arc", []string{"arcs", "--check", "--scope", "alpha-notes"}, "", nil}}} + }{{"arcs", probe{"arc", []string{"arcs", "--check", "--scope", "alpha-notes"}, "", nil}}, + // The machine-readable forms read exactly what their text forms read. + {"recall", probe{"offline", []string{"recall", "--no-sync", "--scope", "beta-notes", "--json"}, "beta-notes", nil}}, + {"routes", probe{"offline", []string{"routes", "--json"}, "", nil}}} const session = "ses-ledger-class" run := func(t *testing.T, verb string, class LedgerClass, p probe, home string) { diff --git a/internal/client/options.go b/internal/client/options.go index ea3ce86b..134510f2 100644 --- a/internal/client/options.go +++ b/internal/client/options.go @@ -62,6 +62,11 @@ type Options struct { AllScopes bool JSON bool + + // PathsFrom and MinPaths are `associate`'s: where the path list is read from (`-` is stdin) + // and how many paths must name an entry for it to count as matched (nil = the default). + PathsFrom string + MinPaths *int // Check is `routes --check`: grade the table rather than only printing it. Check bool diff --git a/internal/client/routes.go b/internal/client/routes.go index 62ef1d6e..8c0db9b5 100644 --- a/internal/client/routes.go +++ b/internal/client/routes.go @@ -25,6 +25,17 @@ func Routes(env Env, opts Options) (int, error) { return 0, err } // `*`: the table names every routed scope (decision 3a). + // `routes --json` is the TABLE only, never the grade: `--check` reads every cache LIVE and + // refuses on a stale one, which is a different question with a different exit model, and + // folding it into one document would make an empty `findings` mean either "clean" or "not + // checked". So the pair is refused rather than half-answered. + if opts.JSON { + if opts.Check { + fmt.Fprintln(env.Stderr, "cairn: routes --json prints the table only; run --check separately") + return ExitUsage, nil + } + return routesJSON(env, opts, routing) + } env.recordRead("", LedgerAllScopes) fmt.Fprintf(env.Stdout, "instances: %s\n", joinComma(routing.Aliases())) if routing.Routes == nil { @@ -260,3 +271,31 @@ func refuseSharedCache(env Env, routing Routing, opts Options, verb string) int } return 0 } + +// routesJSON prints the `routes` document: every configured instance with the cache root the +// READER resolves for it (`instanceCache`, the function every read verb uses, so the answer is +// the reader's and not a re-derivation), and the scope -> instance table (`null` when none is +// configured). It reads no cache and contacts no pod. +func routesJSON(env Env, opts Options, routing Routing) (int, error) { + env.recordRead("", LedgerAllScopes) + doc := routesDoc{ + Schema: JSONSchema, + Verb: "routes", + MultiInstance: routing.MultiInstance(), + Instances: []jsonInstance{}, + RoutesSource: routing.RoutesSource, + Routes: routing.Routes, + } + for _, instance := range routing.Instances { + cache, err := instanceCache(opts, instance.Alias) + if err != nil { + return 0, err + } + doc.Instances = append(doc.Instances, jsonInstance{ + Alias: instance.Alias, Default: instance.IsDefault(), CacheRoot: cache}) + } + if err := writeJSON(env.Stdout, doc); err != nil { + return 0, err + } + return ExitOK, nil +} diff --git a/internal/client/verbs.go b/internal/client/verbs.go index 4b68f9d2..bb0232ea 100644 --- a/internal/client/verbs.go +++ b/internal/client/verbs.go @@ -24,6 +24,8 @@ import ( type Env struct { Stdout io.Writer Stderr *os.File + // Stdin is where a `-` operand reads from (`associate --paths-from -`). nil means os.Stdin. + Stdin io.Reader // Host is "whose disk is this", threaded to the renderer. nil means hostid.ThisHost. Host func() string // ledger is this call's client read ledger (`readledger.go`), set by [Run]; nil records @@ -338,6 +340,8 @@ func Report(env Env, opts Options, isSearch bool) (int, error) { var text, status, exitLabel string var malformed []store.MalformedEntry + // recalled is the recall report, kept for `--json`; nil on the search branch. + var recalled *report.RecallReport if isSearch { searchOpts := report.SearchOptions{ Scope: scope, @@ -448,6 +452,22 @@ func Report(env Env, opts Options, isSearch bool) (int, error) { if state.Name == StateLive && isEmptyStatus(rep.Status) { state = emptyState(state) } + recalled = &rep + } + + code, warning := report.ExitFor(status, exitLabel, malformed) + // `recall --json`: the SAME report, the SAME exit code and the SAME stderr warning, with the + // document replacing the banner and the digest on stdout. Everything that refused above (an + // unrouted scope, an unreadable cache, a usage error) refused before reaching here and printed + // no document — the contract in `README.md` says an empty stdout means "no answer". + if opts.JSON && recalled != nil { + if warning != "" { + fmt.Fprintln(env.Stderr, warning) + } + if err := writeJSON(env.Stdout, recallJSON(recalled, state, alias, cache, code, warning)); err != nil { + return 0, err + } + return code, nil } fmt.Fprint(env.Stdout, RecallPreamble(state.Name, state.Detail, label)) @@ -460,7 +480,6 @@ func Report(env Env, opts Options, isSearch bool) (int, error) { // 🔴 AND THE WARNING SENTENCE IS FORWARDED. `report.ExitFor` RETURNS it instead of // writing to stderr from inside the library (the one deliberate difference from the // oracle in that path), so the caller that drops it is the caller that loses the signal. - code, warning := report.ExitFor(status, exitLabel, malformed) if warning != "" { fmt.Fprintln(env.Stderr, warning) } @@ -572,6 +591,9 @@ func emptyState(state State) State { // verdict could not say where the malformed file is. With no scope at all the default instance // is the answer, which is what `RepoScope` swallowing its error is for. func Validate(env Env, opts Options) (int, error) { + if opts.File != "" { + return validateFile(env, opts) + } scope := opts.Scope if scope == "" { scope = RepoScope(opts.Repo) @@ -809,22 +831,7 @@ func Validate(env Env, opts Options) (int, error) { // them — `open actions: 0 declared` over a section no parser ever reached. The // shape block is the one that says why, and it has to be ABOVE them to be read // as the reason rather than as an afterthought. None of the four moves `worst`. - for _, line := range store.ValidationAdvisoryLines( - store.ScannedEntryCount(entryPaths), - store.ScanEntryShape(entryPaths), - store.ScanDroppedLines(entryPaths), - store.ScanOpenActions(entryPaths), - store.ScanUnreachableMarkers(entryPaths), - ) { - // A blank separator stays blank — prefixing it would print a trailing - // `cairn: : ` with nothing after it, and the parity gate would then - // pin that noise in both clients forever. - if line == "" { - fmt.Fprintln(env.Stdout) - continue - } - fmt.Fprintf(env.Stdout, "cairn: %s: %s\n", scope, line) - } + printAdvisories(env, scope, entryPaths) if len(index.Malformed) > 0 && ExitCorrupt > worst { worst = ExitCorrupt } @@ -1235,3 +1242,73 @@ func listedScopes(lines []string) []string { sort.Strings(out) return slices.Compact(out) } + +// validateFile is `validate --file PATH`: the PRE-write check over one file that is not in any +// cache yet — the draft an author is about to `create` or `put`. +// +// 🔴 IT ASKS THE WRITE PATH'S OWN QUESTION THROUGH THE WRITE PATH'S OWN FUNCTION. +// `write.CheckEntryBytes` is the predicate `create`/`put` run on the pod before bytes land (the +// loader's parse, then the closed `tags:` vocabulary), so a file this verb passes is a file the +// pod's validator passes, and the two cannot drift. Re-spelling the parse here would be a second +// implementation of "would this be accepted", which is the shape that lets a draft validate clean +// and then be refused at the write. +// +// OFFLINE BY CONSTRUCTION: no sync, no cache, no network. The scope is `--scope` when given, +// else the name of the directory holding the file — the loader's own rule, because the directory +// is where an entry's scope comes from. Exit 0 when accepted, 5 (`ExitCorrupt`, the same code a +// malformed CACHED entry gives) when refused, 2 when the file cannot be read. The write-protocol +// advisories print below the verdict exactly as they do for a cached scope, and move no exit +// code. +func validateFile(env Env, opts Options) (int, error) { + // Stat BEFORE reading: a FIFO handed here would block the read forever. + info, err := os.Stat(opts.File) + if err != nil { + fmt.Fprintf(env.Stderr, "cairn: validate --file: cannot read %s: %v\n", opts.File, err) + return ExitUsage, nil + } + if !info.Mode().IsRegular() { + fmt.Fprintf(env.Stderr, "cairn: validate --file: %s is not a regular file\n", opts.File) + return ExitUsage, nil + } + data, err := os.ReadFile(opts.File) + if err != nil { + fmt.Fprintf(env.Stderr, "cairn: validate --file: cannot read %s: %v\n", opts.File, err) + return ExitUsage, nil + } + scope := opts.Scope + if scope == "" { + scope = filepath.Base(filepath.Dir(opts.File)) + } + filename := filepath.Base(opts.File) + label := opts.File + if checkErr := write.CheckEntryBytes(data, scope, filename); checkErr != nil { + fmt.Fprintf(env.Stderr, "cairn: %s: malformed: %s\n", label, checkErr) + fmt.Fprintf(env.Stdout, "cairn: %s: 0 of 1 entry file(s) parse, 1 malformed\n", label) + printAdvisories(env, label, []string{opts.File}) + return ExitCorrupt, nil + } + fmt.Fprintf(env.Stdout, "cairn: %s: 1 of 1 entry file(s) parse, 0 malformed\n", label) + printAdvisories(env, label, []string{opts.File}) + return ExitOK, nil +} + +// printAdvisories prints the four write-protocol advisory blocks for a set of entry files, each +// line prefixed `cairn: