diff --git a/CHANGELOG.md b/CHANGELOG.md index 3054361f..0ee341cb 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 new verbs `cairn associate --scope S --paths-from F` (`--json`, `--min-paths N`), `cairn refs` (ref collisions, by the reader's resolver; `--all-scopes` exits 11 on a cached scope with no route and prints a PARTIAL answer at 3 when an instance's cache is unreadable), `cairn parse --file F --json` (the reader's parse of an entry or a bullet body) and `cairn fold --file F --json` (the reader's ref fold of a JSON array of strings); `cairn validate --file F [--ref R]` checks one draft offline with the body predicate `create`/`put` apply and the store's 1 MiB body cap (with `--ref`, under the filename `create --ref R` would use).** 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..657456b6 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 [--ref R]` checks one draft offline with the body predicate `create`/`put` apply and the store's 1 MiB body cap — with `--ref`, under the filename `create --ref R` would use (without it, under the draft's own name, which can differ) | | | `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,10 @@ 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* | +| `refs --scope X` / `refs --all-scopes` | every ref the cached entries make addressable, and every one the resolver finds AMBIGUOUS (`--json`); `--all-scopes` counts each scope once, in its routed instance | *Go* | +| `parse --file F --json` | the reader's parse of one entry (front matter, headings, sections, journal bullets) or, with `--bullets`, of any text using the bullet grammar; offline | *Go* | +| `fold --file F --json` | the reader's ref fold (`NormalizeRef`, `PathRefs`) of each string in a JSON array (`-` reads stdin) — for a string that is not an entry's; offline | *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 +351,112 @@ 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`, `routes --json`, `refs --json`, `parse --json` and `fold --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. The + one exception is `refs --all-scopes`, which walks several instances: it prints what it could + walk and names what it could not, at a non-zero exit (below). + +`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"`), `status` (`associated`, or `scope-absent` — `recall`'s spelling, exit 0, the same answer for a scope that never existed and one this credential cannot see), `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 answers `status: scope-absent` (never an empty `matched` that reads +as "these paths touch nothing"); 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. + +`refs --json` — `schema`, `verb` (`"refs"`), `status` (`answered`, or `scope-absent` for a +`--scope` the cache does not hold — `recall`'s spelling, exit 0, with an instance whose `scopes` +is empty), `instances` (`[{instance, cache_root, state, state_detail, scopes, not_routed_here, +unrouted}]`) and `unread_instances`. Each scope: `scope`, `refs_tried` (the denominator — every +slug, kind-qualified ref and normalized alias fed to the resolver), `entries` +(`[{ref, filename, slug, kind, aliases}]`), `collisions` (`[{ref, tier, candidates}]`, exactly the +refs `recall --ref` would refuse as ambiguous; `tier` is `filename` or `alias`, `candidates` are +filenames) and `malformed`. With `--all-scopes` a scope is counted only under the instance the +routing table sends it to: + +| a cached scope that… | is listed in | exit | +|---|---|---| +| the table routes to THIS instance | `scopes` | 0 (5 if it holds a malformed entry) | +| the table routes to ANOTHER configured instance | `not_routed_here` (not counted: its copy is not the one any read uses) | 0 | +| has no route (`recall --scope` refuses it) | `unrouted`, and named on stderr — **not counted** | **11** | + +and an instance whose cache cannot be read is `search --all-scopes`'s PARTIAL: it is listed in +`unread_instances`, a `🔴 cairn: PARTIAL` line names it on stderr, the instances that answered are +still in the document, and the exit is the unread state's (**3**, or 4). The exit is the HIGHEST +that applies (11 > 5 > 4 > 3); `unrouted`, `malformed` and `unread_instances` say which. **A +consumer that reads only `scopes` must treat any non-zero exit as an incomplete census.** +With `--scope`: an unrouted scope is refused at 11 and an unreadable cache at 3, printing no +document, as `recall` does. + +`parse --json` — `schema`, `verb` (`"parse"`), `mode` (`entry` or `bullets`), `source`, +`front_matter` (strings and lists of strings, as the reader parses them), `headings` (every `#` +heading line in order), `sections` (heading line → body, a repeated heading's bodies joined) and +`bullets`: the `## Nuance / work-history` journal (or, with `--bullets`, the whole input) as +`[{start_line, lines, date, openness, resolved_by, population, citation_id}]`, where `population` +is exactly one of `open`, `resolved`, `unverifiable` (RESOLVED with no sha), `near-miss`, +`unmarked`, `none`. It is NOT a well-formedness verdict — that is `validate --file`. Input over the +store's body cap (`write.MaxEntryBytes`, 1 MiB) is refused (2). + +`fold --json` — the reader's ref fold, for a string that is not an entry's (a service name typed on +a command line, a repo basename, a path no entry matched). Input: `--file PATH` or `--file -` +(stdin), ONE JSON array of strings, so any string — empty, `--`, surrounding whitespace — is +carried exactly. Output: `schema`, `verb` (`"fold"`), `results`, one per input in input order: +`{input, ref, path_refs}`, where `ref` is `NormalizeRef(input)` — the fold `recall --ref` and +`create --ref` apply; `""` means "not a ref", never a wildcard — and `path_refs` is +`[{component, ref}]`, `PathRefs(input)`: every `/`-separated component's fold plus the final +component's stem with ONE extension stripped (`foo.tar.gz` offers `foo.tar`), duplicates collapsed, +order kept, empty folds dropped. Exit 0 on any array (`[]` included); 2 when the input is +unreadable or not an array of strings (a `null` element included). + +```console +$ printf '%s' '["Widget_API", "apps/values.yaml"]' | cairn fold --json --file - +{"schema": 1, "verb": "fold", "results": [ + {"input": "Widget_API", "ref": "widget-api", "path_refs": [{"component": "Widget_API", "ref": "widget-api"}]}, + {"input": "apps/values.yaml", "ref": "apps-values.yaml", "path_refs": [{"component": "apps", "ref": "apps"}, + {"component": "values.yaml", "ref": "values.yaml"}, {"component": "values", "ref": "values"}]}]} +``` +(reflowed; the real output is indented JSON) + +`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..fa9a4bcb 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`, `refs`, `parse` + # and `fold` are 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 @@ -2011,6 +2013,9 @@ memo-read reads memo-retract writes memo-send writes + fold reads + parse reads + refs reads sessions reads sources reads transcript reads diff --git a/internal/api/server.go b/internal/api/server.go index be442c82..376a8619 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -79,8 +79,9 @@ const ( // How much of a request body this server will read. The oracle's cap, kept: it // bounds what an authenticated caller can make the process hold in memory per - // in-flight request. - maxBodyBytes = 1 << 20 + // in-flight request. Defined from `write.MaxEntryBytes` so the client's offline + // `validate --file` refuses an oversize draft at the same bound. + maxBodyBytes = write.MaxEntryBytes // auditTimeLayout is the audit record's `ts=` spelling, and it is NOT `time.RFC3339`. // diff --git a/internal/client/associate.go b/internal/client/associate.go new file mode 100644 index 00000000..2e97345e --- /dev/null +++ b/internal/client/associate.go @@ -0,0 +1,166 @@ +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 `below-threshold\t\t path(s)`, +// `ambiguous\t\t` and `unmatched\t` lines — or the single line +// `scope-absent\t`; `--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). A +// scope the cache does not hold is `recall`'s answer: exit 0 with status `scope-absent`, so a +// typo'd scope reads as absent and never as an empty match. +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) + malformed := index.MalformedIn(scope) + // 🔴 A SCOPE THE CACHE DOES NOT HOLD IS AN ANSWER, NOT A USAGE ERROR — and it is + // `recall`'s answer: status `scope-absent`, exit 0, so a caller branches on the + // STATUS. It is deliberately the same answer for "never existed" and "not visible + // to this credential" (the cache only ever holds what the token could read), and it + // is never an empty `matched` list wearing a success: the status says no scope was + // matched against. + if !index.HasScope(scope) { + if opts.JSON { + doc := newAssociateDoc(scope, alias, cache, state, minPaths, StatusScopeAbsent) + doc.ConsideredPaths = nonNil(paths) + doc.UnmatchedPaths = nonNil(paths) + doc.Malformed = malformedJSON(malformed) + if err := writeJSON(env.Stdout, doc); err != nil { + return 0, err + } + return ExitOK, nil + } + fmt.Fprintln(env.Stderr, BannerNamed(state.Name, state.Detail, label)) + fmt.Fprintf(env.Stdout, "%s\t%s\n", StatusScopeAbsent, scope) + return ExitOK, nil + } + assoc, err := store.AssociatePaths(paths, index, scope, minPaths) + if err != nil { + fmt.Fprintf(env.Stderr, "cairn: associate: %v\n", err) + return ExitUsage, nil + } + 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 := newAssociateDoc(scope, alias, cache, state, minPaths, StatusAssociated) + doc.Matched = matchesJSON(assoc.Matched) + doc.BelowThreshold = matchesJSON(assoc.BelowThreshold) + doc.Ambiguous = ambiguousJSON(assoc.Ambiguous) + doc.UnmatchedPaths = nonNil(assoc.UnmatchedPaths) + doc.ConsideredPaths = nonNil(assoc.ConsideredPaths) + doc.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 _, m := range assoc.BelowThreshold { + fmt.Fprintf(env.Stdout, "below-threshold\t%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..b73c2451 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 [--ref REF]: the same check on one draft, offline; with --ref, judged under the filename create would use", + Flags: append(append([]string{}, commonReadFlags...), "--file", "--ref"), 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,22 @@ 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. + // `refs` and `parse` (Phase 5): the reader's own answers to "which refs collide" and + // "what does the reader see in this entry", so no consumer re-implements either. + {Name: "refs", Ledger: LedgerResolved, Help: "every ref the scope's cached entries make addressable, and every AMBIGUOUS one (--all-scopes: each scope once, in its routed instance)", + Flags: []string{"--scope", "--repo", "--all-scopes", "--no-sync", "--json"}, Run: Refs}, + {Name: "parse", Ledger: LedgerNone, Help: "the reader's parse of one entry file (front matter, headings, sections, journal bullets) or, with --bullets, of a bare journal body; offline, --json only", + Flags: []string{"--file", "--bullets", "--json"}, Run: ParseEntry}, + // `fold` (Phase 5): the reader's ref fold (`NormalizeRef`, `PathRefs`) for strings that are + // not an entry's, so no consumer keeps a copy of the fold. + {Name: "fold", Ledger: LedgerNone, Help: "the reader's ref fold of each string in a JSON array (--file FILE, or - for stdin): its ref and its path components' refs; offline, --json only", + Flags: []string{"--file", "--json"}, Run: Fold}, + {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 @@ -542,7 +557,8 @@ func Parse(argv []string) (Verb, Options, error) { // token as its value; missing from the switch, it parses and sets nothing. Both leave // a well-formed command line doing the wrong thing at exit 0. needsValue := name != "--no-sync" && name != "--list" && name != "--all-scopes" && - name != "--json" && name != "--check" && name != "--statuses" && name != "--outline" && name != "--all-repos" + name != "--json" && name != "--check" && name != "--statuses" && name != "--outline" && + name != "--all-repos" && name != "--bullets" if !needsValue { if hasValue { return verb, opts, usagef("cairn: %s takes no value", name) @@ -567,6 +583,8 @@ func Parse(argv []string) (Verb, Options, error) { opts.Statuses = true case "--outline": opts.Outline = true + case "--bullets": + opts.Bullets = true } i++ continue @@ -670,6 +688,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/fold.go b/internal/client/fold.go new file mode 100644 index 00000000..1902a106 --- /dev/null +++ b/internal/client/fold.go @@ -0,0 +1,106 @@ +package client + +import ( + "encoding/json" + "fmt" + "io" + "os" + + "github.com/ZacxDev/cairn/internal/store" +) + +// Fold is `fold --file PATH|- --json`: the reader's OWN ref fold, for strings that are not (yet) +// an entry's — a service name typed on a command line, a repo basename, the components of a path +// no entry matched. `refs`, `parse` and `associate` answer questions about ENTRIES; this is the +// one question with no entry to ask about, so without it a consumer re-implements the fold. +// +// The input is ONE JSON array of strings, so any string — empty, all dashes, leading `--`, +// surrounding whitespace — is carried exactly; a line or argv form would have to escape or +// refuse those. Each result is, in input order: +// +// - `ref`: `store.NormalizeRef(input)` — the fold `recall --ref`, `create --ref` and the +// resolver apply. `""` means "not a ref", never a wildcard. +// - `path_refs`: `store.PathRefs(input)` — the `(component, ref)` candidates `associate` +// matches a repo-relative path by: every component's fold, plus the FINAL component's stem +// with ONE extension stripped; duplicates collapsed, order kept, empty folds dropped. +// +// Offline: no cache, no pod, no network. Exit 0 on any array of strings (an empty array included), +// 2 when the input cannot be read or is not an array of strings. +func Fold(env Env, opts Options) (int, error) { + if opts.File == "" { + fmt.Fprintln(env.Stderr, "cairn: fold requires --file PATH (or - for stdin): a JSON array of strings") + return ExitUsage, nil + } + if !opts.JSON { + fmt.Fprintln(env.Stderr, "cairn: fold prints a document only; pass --json") + return ExitUsage, nil + } + var data []byte + var err error + if opts.File == "-" { + var r io.Reader = env.Stdin + if r == nil { + r = os.Stdin + } + data, err = io.ReadAll(r) + } else { + data, err = os.ReadFile(opts.File) + } + if err != nil { + fmt.Fprintf(env.Stderr, "cairn: fold: cannot read %s: %v\n", opts.File, err) + return ExitUsage, nil + } + inputs, ok := decodeStringArray(data) + if !ok { + fmt.Fprintf(env.Stderr, "cairn: fold: %s is not a JSON array of strings\n", opts.File) + return ExitUsage, nil + } + doc := foldDoc{Schema: JSONSchema, Verb: "fold", Results: make([]foldResult, 0, len(inputs))} + for _, in := range inputs { + res := foldResult{Input: in, Ref: store.NormalizeRef(in), PathRefs: []foldPathRef{}} + for _, pair := range store.PathRefs(in) { + res.PathRefs = append(res.PathRefs, foldPathRef{Component: pair[0], Ref: pair[1]}) + } + doc.Results = append(doc.Results, res) + } + if err := writeJSON(env.Stdout, doc); err != nil { + return 0, err + } + return ExitOK, nil +} + +// decodeStringArray is `data` as a JSON array of strings. 🔴 ELEMENT BY ELEMENT, because +// `json.Unmarshal` into `[]string` turns a `null` element into "" — a fold of "" ("not a ref") +// reported for an input nobody sent. +func decodeStringArray(data []byte) ([]string, bool) { + var raw []json.RawMessage + if err := json.Unmarshal(data, &raw); err != nil || raw == nil { + return nil, false + } + out := make([]string, 0, len(raw)) + for _, r := range raw { + var s *string + if err := json.Unmarshal(r, &s); err != nil || s == nil { + return nil, false + } + out = append(out, *s) + } + return out, true +} + +type foldDoc struct { + Schema int `json:"schema"` + Verb string `json:"verb"` + Results []foldResult `json:"results"` +} + +type foldResult struct { + Input string `json:"input"` + Ref string `json:"ref"` + PathRefs []foldPathRef `json:"path_refs"` +} + +type foldPathRef struct { + Component string `json:"component"` + Ref string `json:"ref"` +} diff --git a/internal/client/jsonout.go b/internal/client/jsonout.go new file mode 100644 index 00000000..b1eebadc --- /dev/null +++ b/internal/client/jsonout.go @@ -0,0 +1,269 @@ +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"` + Status string `json:"status"` + 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"` +} + +// The `associate` document's statuses. `scope-absent` is `recall`'s own spelling. +const ( + StatusAssociated = "associated" + StatusScopeAbsent = report.StatusScopeAbsent +) + +func newAssociateDoc(scope, alias, cache string, state State, minPaths int, status string) associateDoc { + return associateDoc{ + Schema: JSONSchema, Verb: "associate", Status: status, Scope: scope, Instance: alias, + CacheRoot: cache, State: state.Name, StateDetail: state.Detail, MinPaths: minPaths, + Matched: []jsonMatch{}, BelowThreshold: []jsonMatch{}, Ambiguous: []jsonAmbiguous{}, + UnmatchedPaths: []string{}, ConsideredPaths: []string{}, Malformed: []jsonMalformed{}, + } +} + +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..f0af5c64 --- /dev/null +++ b/internal/client/jsonout_test.go @@ -0,0 +1,611 @@ +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) + } +} + +// F1: `validate --file` vs the write path. Every expectation below was MEASURED against the +// real pod (`cairn-server` + `cairn create`, this branch, 2026-12-03) before it was written: +// +// file --ref validate(no ref) validate(--ref) create --ref +// draft.md widget-api 5 0 0 (201) +// widget-api.md other 0 5 6 [entry-shape] +// x.runbook.md x 5 0 0 (201) +// x.process.md x.process 0 2 6 [bad-request] invalid path component +// big.md (>1MiB) widget-big 5 5 6 [bad-request] unreadable request body +func TestValidateFileWithRefJudgesUnderTheFilenameCreateUses(t *testing.T) { + ledgerHost(t) + body := strings.Replace(widgetEntry, "scope: beta-notes\n", "", 1) + rows := []struct { + file, ref string + noRef, withRef int + }{ + {"draft.md", "widget-api", ExitCorrupt, ExitOK}, + {"widget-api.md", "other", ExitOK, ExitCorrupt}, + } + for _, r := range rows { + p := draft(t, "beta-notes", r.file, body) + if code, _, stderr := runCLI(t, "validate", "--file", p); code != r.noRef { + t.Errorf("%s without --ref: exit %d, want %d\n%s", r.file, code, r.noRef, stderr) + } + if code, _, stderr := runCLI(t, "validate", "--file", p, "--ref", r.ref); code != r.withRef { + t.Errorf("%s --ref %s: exit %d, want %d\n%s", r.file, r.ref, code, r.withRef, stderr) + } + } +} + +func TestValidateFileWithRefOnAKindQualifiedDraftName(t *testing.T) { + ledgerHost(t) + body := strings.Replace(strings.Replace(widgetEntry, "service: widget-api", "service: x", 1), "aliases: [gizmo]\n", "", 1) + p := draft(t, "beta-notes", "x.runbook.md", body) + if code, _, _ := runCLI(t, "validate", "--file", p); code != ExitCorrupt { + t.Errorf("x.runbook.md without --ref: exit %d, want %d (`runbook` is not a kind)", code, ExitCorrupt) + } + if code, _, stderr := runCLI(t, "validate", "--file", p, "--ref", "x"); code != ExitOK { + t.Errorf("x.runbook.md --ref x: exit %d, want 0 (create --ref x accepts it)\n%s", code, stderr) + } + // A dotted ref is not a path component the pod accepts: it refuses before the body. + code, stdout, stderr := runCLI(t, "validate", "--file", p, "--ref", "x.runbook") + if code != ExitUsage || stdout != "" || !strings.Contains(stderr, "not a path component") { + t.Errorf("--ref x.runbook: exit %d stdout %q stderr %q; want 2 naming the path component", code, stdout, stderr) + } +} + +func TestValidateFileRefusesABodyOverTheStoresCapInBothModes(t *testing.T) { + ledgerHost(t) + big := widgetEntry + "- 2000-01-03: " + strings.Repeat("z", 1<<20) + "\n" + p := draft(t, "beta-notes", "widget-api.md", big) + for _, argv := range [][]string{{"validate", "--file", p}, {"validate", "--file", p, "--ref", "widget-api"}} { + code, _, stderr := runCLI(t, argv...) + if code != ExitCorrupt || !strings.Contains(stderr, "1048576-byte body") { + t.Errorf("%v: exit %d stderr %q; want 5 naming the cap", argv, code, stderr) + } + } + // The boundary itself: a body of exactly the cap is not refused for its size. + exact := widgetEntry + strings.Repeat("\n", (1<<20)-len(widgetEntry)) + q := draft(t, "beta-notes", "widget-api.md", exact) + if _, _, stderr := runCLI(t, "validate", "--file", q); strings.Contains(stderr, "byte body") { + t.Errorf("a body of exactly the cap was refused for its size: %s", stderr) + } +} + +func TestValidateRefWithoutFileIsAUsageError(t *testing.T) { + ledgerHost(t) + if code, _, _ := runCLI(t, "validate", "--no-sync", "--scope", "beta-notes", "--ref", "x"); code != ExitUsage { + t.Fatalf("exit %d, want 2", code) + } +} + +// ---------------------------------------------------------------- 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", "status", "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["status"]) != "associated" { + t.Errorf("status = %v, want associated", doc["status"]) + } + 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 TestAssociateRefusesABadBarAndAMissingPathList(t *testing.T) { + ledgerHost(t) + list := pathList(t, "a/b.go") + for name, argv := range map[string][]string{ + "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) + } + } +} + +// F2: a scope the cache does not hold is `recall`'s answer — status `scope-absent`, exit 0 +// — in a DOCUMENT, never a usage error with nothing on stdout and never an empty `matched` +// list that reads as "these paths touch nothing". +func TestAssociateOnAnUnknownScopeAnswersScopeAbsent(t *testing.T) { + ledgerHost(t) + list := pathList(t, "internal/gizmo/a.go") + code, stdout, stderr := runCLI(t, "associate", "--no-sync", "--scope", "alpha-notes-typo", "--paths-from", list, "--json") + if code != ExitOK { + t.Fatalf("exit %d, want 0 (recall's convention for scope-absent)\n%s", code, stderr) + } + doc := decode(t, stdout) + if got := keysOf(doc); !slices.Equal(got, associateKeys) { + t.Fatalf("a scope-absent answer carries the same keys:\n got %v\n want %v", got, associateKeys) + } + if jsonString(doc["status"]) != "scope-absent" || jsonString(doc["scope"]) != "alpha-notes-typo" { + t.Fatalf("status/scope = %v/%v", doc["status"], doc["scope"]) + } + if n := len(doc["matched"].([]any)); n != 0 { + t.Errorf("matched = %d, want 0", n) + } + if got := toStrings(doc["unmatched_paths"]); !slices.Equal(got, []string{"internal/gizmo/a.go"}) { + t.Errorf("unmatched_paths = %v", got) + } + // And the text form says it in one line, not as an empty listing. + code, stdout, _ = runCLI(t, "associate", "--no-sync", "--scope", "alpha-notes-typo", "--paths-from", list) + if code != ExitOK || stdout != "scope-absent\talpha-notes-typo\n" { + t.Fatalf("text form: exit %d stdout %q", code, stdout) + } +} + +// F3: the text form prints the below-threshold entries too. +func TestAssociateTextFormPrintsBelowThreshold(t *testing.T) { + home, _ := ledgerHost(t) + seedWidget(t, home) + list := pathList(t, "internal/gizmo/a.go", "internal/gizmo/b.go", "docs/two.md") + code, stdout, _ := runCLI(t, "associate", "--no-sync", "--scope", "beta-notes", "--paths-from", list, "--min-paths", "2") + if code != ExitOK { + t.Fatalf("exit %d", code) + } + if want := "widget-api\t2 path(s)\nbelow-threshold\ttwo\t1 path(s)\n"; stdout != want { + t.Fatalf("got %q, want %q", stdout, want) + } +} + +// 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..7f6bee1a 100644 --- a/internal/client/ledgerclass_test.go +++ b/internal/client/ledgerclass_test.go @@ -98,12 +98,35 @@ func TestEveryVerbRecordsWhatItsLedgerClassSays(t *testing.T) { "log": func(string) probe { return probe{"transcript", []string{"log", "search", "zircon", "--all-repos"}, "", nil} }, + "refs": func(string) probe { + return probe{"offline", []string{"refs", "--no-sync", "--scope", "beta-notes"}, "beta-notes", nil} + }, + "parse": func(home string) probe { + return probe{"offline", []string{"parse", "--json", "--file", entry(home, "alpha-notes", "parsed")}, "", nil} + }, + "fold": func(home string) probe { + p := filepath.Join(home, "fold.json") + if err := os.WriteFile(p, []byte(`["Widget_API"]`), 0o644); err != nil { + t.Fatal(err) + } + return probe{"offline", []string{"fold", "--json", "--file", p}, "", 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..068a08f5 100644 --- a/internal/client/options.go +++ b/internal/client/options.go @@ -50,7 +50,7 @@ type Options struct { // this client and the pod cannot disagree about what a query named. Tag string HasTag bool - List bool + List bool // Limit / Page are pointers because `nil` is a DIFFERENT REQUEST from any integer: it is // `--limit` that selects full-body mode, and defaulting it at the call site would make // "the caller asked for a cap" indistinguishable from "the caller asked for nothing", @@ -62,6 +62,13 @@ 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 + // Bullets is `parse --bullets`: the input is one journal body, not an entry. + Bullets bool + MinPaths *int // Check is `routes --check`: grade the table rather than only printing it. Check bool @@ -169,7 +176,7 @@ var selectors = [][2]string{ // // 🔴 THE ORDER IS THE CONTRACT. A call carrying two incoherent pairs gets ONE message, and which // one it gets is what a test over a single pair cannot see. -// ⚠ `hasRef` IS A FLAG, NOT `ref != ""`. The oracle tests `ref is not None`, so `--ref ''` +// ⚠ `hasRef` IS A FLAG, NOT `ref != ""`. The oracle tests `ref is not None`, so `--ref ”` // COUNTS as a selector and refuses alongside `--list` — an empty ref still narrows and finds // nothing, which is a different request from not passing one. func RejectRecallFlags(hasRef bool, list bool, limit, page *int) string { diff --git a/internal/client/parse.go b/internal/client/parse.go new file mode 100644 index 00000000..7d90e8cc --- /dev/null +++ b/internal/client/parse.go @@ -0,0 +1,137 @@ +package client + +import ( + "fmt" + "io" + "os" + "sort" + + "github.com/ZacxDev/cairn/internal/store" + "github.com/ZacxDev/cairn/internal/write" +) + +// ParseEntry is `parse --file PATH|- [--bullets] --json`: the reader's OWN parse of one entry file (or +// of a bare journal body), as a document, so a consumer that needs an entry's structure never +// re-implements the grammar. Offline: no cache, no pod, no network. +// +// - entry mode (default): `front_matter` (the reader's `ParseFrontMatter`: strings and lists of +// strings), `headings` (every `#` heading line in order, fences respected), `sections` (each +// heading's body, a repeated heading's bodies joined — `ExtractSections`), and `bullets`, the +// `## Nuance / work-history` section's journal bullets. +// - `--bullets`: the WHOLE input is one journal body (no front matter, no sections) — for text +// that is not an entry but uses the bullet grammar, e.g. one line of a handoff doc. +// +// Each bullet is the reader's `JournalBullet`: `start_line` (index into the body's lines), +// `lines`, `date`, `openness` (`open`/`resolved`/""), `resolved_by`, `population` (exactly one of +// open, resolved, unverifiable, near-miss, unmarked, none) and `citation_id`. +// +// 🔴 IT IS NOT A WELL-FORMEDNESS VERDICT. `validate --file` answers "would the store accept this"; +// `parse` reports what the reader sees in it, malformed or not. Exit 0 on any readable input, 2 +// when the input cannot be read or is over the size cap. +func ParseEntry(env Env, opts Options) (int, error) { + if opts.File == "" { + fmt.Fprintln(env.Stderr, "cairn: parse requires --file PATH (or - for stdin)") + return ExitUsage, nil + } + if !opts.JSON { + fmt.Fprintln(env.Stderr, "cairn: parse prints a document only; pass --json") + return ExitUsage, nil + } + var r io.Reader + if opts.File == "-" { + r = env.Stdin + if r == nil { + r = os.Stdin + } + } else { + info, err := os.Stat(opts.File) + if err != nil || !info.Mode().IsRegular() { + fmt.Fprintf(env.Stderr, "cairn: parse: cannot read %s as a regular file\n", opts.File) + return ExitUsage, nil + } + f, err := os.Open(opts.File) + if err != nil { + fmt.Fprintf(env.Stderr, "cairn: parse: cannot read %s: %v\n", opts.File, err) + return ExitUsage, nil + } + defer f.Close() + r = f + } + // Bounded by the store's own body cap (`write.MaxEntryBytes`, the constant `validate --file` + // and the pod's request cap are defined from), so nothing larger than an entry the store + // could hold is ever parsed here. + data, err := io.ReadAll(io.LimitReader(r, write.MaxEntryBytes+1)) + if err != nil { + fmt.Fprintf(env.Stderr, "cairn: parse: cannot read %s: %v\n", opts.File, err) + return ExitUsage, nil + } + if len(data) > write.MaxEntryBytes { + fmt.Fprintf(env.Stderr, "cairn: parse: %s is over the %d-byte cap\n", opts.File, write.MaxEntryBytes) + return ExitUsage, nil + } + text := store.DecodeReplace(data) + doc := parseDoc{Schema: JSONSchema, Verb: "parse", Source: opts.File, + FrontMatter: map[string]any{}, Headings: []string{}, Sections: map[string]string{}} + if opts.Bullets { + doc.Mode = "bullets" + doc.Bullets = bulletsJSON(store.ParseJournalBullets(text)) + } else { + doc.Mode = "entry" + for k, v := range store.ParseFrontMatter(text) { + doc.FrontMatter[k] = v + } + doc.Headings = nonNil(store.HeadingInventory(text)) + unique := uniqueStrings(doc.Headings) + doc.Sections = store.ExtractSections(text, unique) + doc.Bullets = bulletsJSON(store.ParseJournalBullets(doc.Sections[store.NuanceHeading])) + } + if err := writeJSON(env.Stdout, doc); err != nil { + return 0, err + } + return ExitOK, nil +} + +func uniqueStrings(items []string) []string { + seen := map[string]bool{} + var out []string + for _, s := range items { + if !seen[s] { + seen[s] = true + out = append(out, s) + } + } + sort.Strings(out) + return out +} + +type parseDoc struct { + Schema int `json:"schema"` + Verb string `json:"verb"` + Mode string `json:"mode"` + Source string `json:"source"` + FrontMatter map[string]any `json:"front_matter"` + Headings []string `json:"headings"` + Sections map[string]string `json:"sections"` + Bullets []jsonBullet `json:"bullets"` +} + +type jsonBullet struct { + StartLine int `json:"start_line"` + Lines []string `json:"lines"` + Date string `json:"date"` + Openness string `json:"openness"` + ResolvedBy string `json:"resolved_by"` + Population string `json:"population"` + CitationID string `json:"citation_id"` +} + +func bulletsJSON(bullets []store.JournalBullet) []jsonBullet { + out := make([]jsonBullet, 0, len(bullets)) + for _, b := range bullets { + out = append(out, jsonBullet{ + StartLine: b.StartLine, Lines: nonNil(b.Lines), Date: b.Date, Openness: b.Openness, + ResolvedBy: b.ResolvedBy, Population: b.OpennessPopulation(), CitationID: b.CitationID(), + }) + } + return out +} diff --git a/internal/client/parserefs_test.go b/internal/client/parserefs_test.go new file mode 100644 index 00000000..afd4486b --- /dev/null +++ b/internal/client/parserefs_test.go @@ -0,0 +1,494 @@ +package client + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/ZacxDev/cairn/internal/write" +) + +// `parse` and `refs`: the reader's own parse and resolver, exposed as versioned documents so a +// consumer never re-implements the grammar or the collision walk. Every expectation is a literal +// chosen by the fixture. + +func TestParseAnEntryReturnsTheReadersStructure(t *testing.T) { + ledgerHost(t) + p := draft(t, "beta-notes", "widget-api.md", widgetEntry) + code, stdout, stderr := runCLI(t, "parse", "--json", "--file", p) + if code != ExitOK { + t.Fatalf("exit %d\n%s", code, stderr) + } + doc := decode(t, stdout) + want := []string{"bullets", "front_matter", "headings", "mode", "schema", "sections", "source", "verb"} + if got := keysOf(doc); !slices.Equal(got, want) { + t.Fatalf("keys:\n got %v\n want %v", got, want) + } + if jsonString(doc["verb"]) != "parse" || jsonString(doc["mode"]) != "entry" || jsonString(doc["schema"]) != "1" { + t.Fatalf("verb/mode/schema = %v/%v/%v", doc["verb"], doc["mode"], doc["schema"]) + } + fm := doc["front_matter"].(map[string]any) + if fm["service"] != "widget-api" || !slices.Equal(toStrings(fm["aliases"]), []string{"gizmo"}) || + !slices.Equal(toStrings(fm["tags"]), []string{"tooling"}) { + t.Errorf("front_matter = %v", fm) + } + if got := toStrings(doc["headings"]); !slices.Equal(got, []string{"## What it is", "## Pointers", "## Nuance / work-history"}) { + t.Errorf("headings = %v", got) + } + sections := doc["sections"].(map[string]any) + if s := jsonString(sections["## Pointers"]); s != "- `internal/widget/main.go`" { + t.Errorf("Pointers section = %q", s) + } + bullets := doc["bullets"].([]any) + if len(bullets) != 2 { + t.Fatalf("bullets = %d, want the nuance section's 2", len(bullets)) + } + b0, b1 := bullets[0].(map[string]any), bullets[1].(map[string]any) + for k, v := range map[string]string{"start_line": "0", "date": "2000-01-01", "openness": "open", "population": "open"} { + if jsonString(b0[k]) != v { + t.Errorf("bullet 0 %s = %v, want %s", k, b0[k], v) + } + } + for k, v := range map[string]string{"start_line": "1", "date": "2000-01-02", "openness": "", "population": "none"} { + if jsonString(b1[k]) != v { + t.Errorf("bullet 1 %s = %v, want %s", k, b1[k], v) + } + } + if jsonString(b0["citation_id"]) == "" || len(jsonString(b0["citation_id"])) != 8 { + t.Errorf("citation_id = %v, want the 8-hex id", b0["citation_id"]) + } +} + +// --bullets reads ANY text with the journal grammar — every population, from stdin. +func TestParseBulletsCoversEveryPopulation(t *testing.T) { + ledgerHost(t) + body := "- 2026-01-02: RESOLVED abc1234: fixed\n- RESOLVED: no sha\n- **OPEN**: bold\n" + + "- FIX (now): the bug\n- 2026-01-03: OPEN: real\n- a note\n" + var out bytes.Buffer + errFile, _ := os.CreateTemp(t.TempDir(), "stderr") + defer errFile.Close() + code := Run(Env{Stdout: &out, Stderr: errFile, Stdin: strings.NewReader(body), + Host: func() string { return "fixture-host-000000000000" }}, + []string{"parse", "--json", "--bullets", "--file", "-"}) + if code != ExitOK { + t.Fatalf("exit %d", code) + } + doc := decode(t, out.String()) + if jsonString(doc["mode"]) != "bullets" || len(doc["headings"].([]any)) != 0 { + t.Fatalf("mode/headings = %v/%v", doc["mode"], doc["headings"]) + } + var pops []string + for _, b := range doc["bullets"].([]any) { + pops = append(pops, jsonString(b.(map[string]any)["population"])) + } + if want := []string{"resolved", "unverifiable", "near-miss", "unmarked", "open", "none"}; !slices.Equal(pops, want) { + t.Fatalf("populations = %v, want %v", pops, want) + } + if rb := jsonString(doc["bullets"].([]any)[0].(map[string]any)["resolved_by"]); rb != "abc1234" { + t.Errorf("resolved_by = %q", rb) + } +} + +func TestParseRefusesWithoutJSONOrAFile(t *testing.T) { + ledgerHost(t) + p := draft(t, "beta-notes", "widget-api.md", widgetEntry) + for name, argv := range map[string][]string{ + "no --json": {"parse", "--file", p}, + "no --file": {"parse", "--json"}, + "no such": {"parse", "--json", "--file", filepath.Join(t.TempDir(), "absent.md")}, + } { + if code, stdout, _ := runCLI(t, argv...); code != ExitUsage || stdout != "" { + t.Errorf("%s: exit %d stdout %q; want 2 and nothing", name, code, stdout) + } + } +} + +func entryFile(t *testing.T, cache, scope, name, service, aliases string) { + t.Helper() + dir := filepath.Join(cache, scope) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + fm := "---\nservice: " + service + "\nscope: " + scope + "\n" + if aliases != "" { + fm += "aliases: [" + aliases + "]\n" + } + body := fm + "---\n\n## What it is\n\nx\n\n## Pointers\n\n- none\n\n## Nuance / work-history\n\n- 2000-01-01: y\n" + if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { + t.Fatal(err) + } +} + +// The resolver decides: two entries sharing an alias collide in the ALIAS tier; a slug with two +// kinds collides in the FILENAME tier for the bare ref; an alias equal to ANOTHER entry's slug is +// not a collision (the filename tier wins). +func TestRefsReportsExactlyTheResolversAmbiguities(t *testing.T) { + home, _ := ledgerHost(t) + cache := filepath.Join(home, ".cache", "subsystem-store") + entryFile(t, cache, "beta-notes", "alpha-svc.md", "alpha-svc", "shared, two") + entryFile(t, cache, "beta-notes", "bravo-svc.md", "bravo-svc", "shared") + entryFile(t, cache, "beta-notes", "widget.md", "widget", "") + entryFile(t, cache, "beta-notes", "widget.process.md", "widget", "") + + code, stdout, stderr := runCLI(t, "refs", "--no-sync", "--scope", "beta-notes", "--json") + if code != ExitOK { + t.Fatalf("exit %d\n%s", code, stderr) + } + doc := decode(t, stdout) + insts := doc["instances"].([]any) + if len(insts) != 1 { + t.Fatalf("instances = %d", len(insts)) + } + scopes := insts[0].(map[string]any)["scopes"].([]any) + if len(scopes) != 1 { + t.Fatalf("scopes = %v", scopes) + } + sc := scopes[0].(map[string]any) + var got []string + for _, c := range sc["collisions"].([]any) { + m := c.(map[string]any) + got = append(got, jsonString(m["ref"])+"|"+jsonString(m["tier"])+"|"+strings.Join(toStrings(m["candidates"]), ",")) + } + want := []string{ + "shared|alias|alpha-svc.md,bravo-svc.md", + "widget|filename|widget.md,widget.process.md", + } + if !slices.Equal(got, want) { + t.Fatalf("collisions:\n got %v\n want %v", got, want) + } + // The denominator, counted by hand over the fixture: `two` (ledgerHost's two.md, and also an + // alias of alpha-svc — tried once), `alpha-svc`, `bravo-svc`, `shared`, `widget`, + // `widget.process`. `two` as an alias equal to another entry's slug is NOT a collision. + if tried := jsonString(sc["refs_tried"]); tried != "6" { + t.Errorf("refs_tried = %s, want 6", tried) + } +} + +// F4: a `--scope` the routing table sends to this host but the cache does not hold is an ANSWER — +// `recall`'s and `associate`'s `scope-absent`, exit 0 — not a usage error. +func TestRefsOnAScopeTheCacheDoesNotHoldAnswersScopeAbsent(t *testing.T) { + ledgerHost(t) + code, stdout, stderr := runCLI(t, "refs", "--no-sync", "--scope", "nope-notes", "--json") + if code != ExitOK { + t.Fatalf("exit %d, want 0\n%s", code, stderr) + } + doc := decode(t, stdout) + if jsonString(doc["status"]) != "scope-absent" { + t.Fatalf("status = %v, want scope-absent", doc["status"]) + } + insts := doc["instances"].([]any) + if len(insts) != 1 || len(insts[0].(map[string]any)["scopes"].([]any)) != 0 { + t.Fatalf("instances = %v, want one instance with no scopes", insts) + } + code, stdout, _ = runCLI(t, "refs", "--no-sync", "--scope", "nope-notes") + if code != ExitOK || stdout != "scope-absent\tnope-notes\n" { + t.Fatalf("text form: exit %d stdout %q, want 0 and one scope-absent line", code, stdout) + } + // And a scope it DOES hold answers `answered` — the status is not a constant — under the + // scope's FOLDED name too, as `recall --scope` resolves it. + for _, spelled := range []string{"beta-notes", "Beta_Notes"} { + code, stdout, stderr := runCLI(t, "refs", "--no-sync", "--scope", spelled, "--json") + if code != ExitOK { + t.Fatalf("held scope %q: exit %d\n%s", spelled, code, stderr) + } + doc := decode(t, stdout) + scopes := doc["instances"].([]any)[0].(map[string]any)["scopes"].([]any) + if jsonString(doc["status"]) != "answered" || len(scopes) != 1 || + jsonString(scopes[0].(map[string]any)["scope"]) != "beta-notes" { + t.Fatalf("held scope %q: status %v scopes %v, want answered and beta-notes", spelled, doc["status"], scopes) + } + } +} + +// --all-scopes counts each scope ONCE, in the instance the routing table sends it to; a copy +// cached on another instance is listed under that instance's not_routed_here. +func TestRefsAllScopesCountsEachScopeOnceInItsRoutedInstance(t *testing.T) { + home := twoInstanceHost(t) + writeTable(t, filepath.Join(home, "config"), `{"alpha-notes": "`+DefaultAlias+`", "gamma-notes": "secondary"}`) + // A stale copy of alpha-notes on the SECONDARY instance — not where alpha-notes is routed. + seedCache(t, filepath.Join(home, ".cache", "subsystem-store-secondary"), "alpha-notes", "stale") + + code, stdout, stderr := runCLI(t, "refs", "--no-sync", "--all-scopes", "--json") + if code != ExitOK { + t.Fatalf("exit %d\n%s", code, stderr) + } + doc := decode(t, stdout) + counted := map[string][]string{} + notHere := map[string][]string{} + for _, raw := range doc["instances"].([]any) { + inst := raw.(map[string]any) + alias := jsonString(inst["instance"]) + for _, s := range inst["scopes"].([]any) { + counted[alias] = append(counted[alias], jsonString(s.(map[string]any)["scope"])) + } + notHere[alias] = toStrings(inst["not_routed_here"]) + } + if !slices.Equal(counted[DefaultAlias], []string{"alpha-notes"}) || !slices.Equal(counted["secondary"], []string{"gamma-notes"}) { + t.Fatalf("counted = %v", counted) + } + if !slices.Equal(notHere["secondary"], []string{"alpha-notes"}) { + t.Fatalf("not_routed_here = %v, want the stale alpha-notes copy on secondary", notHere) + } +} + +// F2: on a TWO-instance host whose table names `alpha-notes` only, `gamma-notes` (cached on the +// secondary) has no route — `recall --scope gamma-notes` refuses it at 11. `refs --all-scopes` +// must not file it quietly beside the routed-elsewhere copies at exit 0: it is listed under +// `unrouted`, named on stderr, and the run exits 11 with the document still printed. +func TestRefsAllScopesIsLoudAboutAnUnroutedScope(t *testing.T) { + home := twoInstanceHost(t) + writeTable(t, filepath.Join(home, "config"), `{"alpha-notes": "`+DefaultAlias+`"}`) + + if code, _, _ := runCLI(t, "recall", "--no-sync", "--scope", "gamma-notes"); code != ExitUnrouted { + t.Fatalf("recall --scope gamma-notes exit %d, want %d — the fixture must exhibit the refusal", code, ExitUnrouted) + } + code, stdout, stderr := runCLI(t, "refs", "--no-sync", "--all-scopes", "--json") + if code != ExitUnrouted { + t.Fatalf("exit %d, want %d (recall's refusal for the same scope)\n%s", code, ExitUnrouted, stderr) + } + if !strings.Contains(stderr, "'gamma-notes'") || !strings.Contains(stderr, "secondary") { + t.Errorf("stderr does not name the unrouted scope and its instance:\n%s", stderr) + } + doc := decode(t, stdout) + for _, raw := range doc["instances"].([]any) { + inst := raw.(map[string]any) + alias := jsonString(inst["instance"]) + var counted []string + for _, s := range inst["scopes"].([]any) { + counted = append(counted, jsonString(s.(map[string]any)["scope"])) + } + switch alias { + case DefaultAlias: + if !slices.Equal(counted, []string{"alpha-notes"}) || len(toStrings(inst["unrouted"])) != 0 { + t.Errorf("default: counted %v unrouted %v", counted, inst["unrouted"]) + } + case "secondary": + if len(counted) != 0 || !slices.Equal(toStrings(inst["unrouted"]), []string{"gamma-notes"}) || + len(toStrings(inst["not_routed_here"])) != 0 { + t.Errorf("secondary: counted %v unrouted %v not_routed_here %v; want gamma-notes under unrouted only", + counted, inst["unrouted"], inst["not_routed_here"]) + } + default: + t.Errorf("unexpected instance %q", alias) + } + } +} + +// F3: one instance with no cache is `search --all-scopes`'s PARTIAL — what the others hold is +// still printed, the unread one is named (document and stderr), and the exit is the unread +// state's 3 — not an empty stdout. +func TestRefsAllScopesPrintsAPartialAnswerWhenAnInstanceIsUnread(t *testing.T) { + home := twoInstanceHost(t) + writeTable(t, filepath.Join(home, "config"), `{"alpha-notes": "`+DefaultAlias+`", "gamma-notes": "secondary"}`) + if err := os.RemoveAll(filepath.Join(home, ".cache", "subsystem-store-secondary")); err != nil { + t.Fatal(err) + } + code, stdout, stderr := runCLI(t, "refs", "--no-sync", "--all-scopes", "--json") + if code != ExitUnreachableNoCache { + t.Fatalf("exit %d, want %d\n%s", code, ExitUnreachableNoCache, stderr) + } + if !strings.Contains(stderr, "PARTIAL — 1 of 2 instance(s) could not be read (secondary)") { + t.Errorf("stderr lacks the PARTIAL line:\n%s", stderr) + } + doc := decode(t, stdout) + if got := toStrings(doc["unread_instances"]); !slices.Equal(got, []string{"secondary"}) { + t.Fatalf("unread_instances = %v, want [secondary]", got) + } + insts := doc["instances"].([]any) + if len(insts) != 1 || jsonString(insts[0].(map[string]any)["instance"]) != DefaultAlias { + t.Fatalf("instances = %v, want the default instance only", insts) + } + scopes := insts[0].(map[string]any)["scopes"].([]any) + if len(scopes) != 1 || jsonString(scopes[0].(map[string]any)["scope"]) != "alpha-notes" { + t.Fatalf("scopes = %v, want alpha-notes", scopes) + } + // Text form: the same exit, the same PARTIAL line. + code, _, stderr = runCLI(t, "refs", "--no-sync", "--all-scopes") + if code != ExitUnreachableNoCache || !strings.Contains(stderr, "PARTIAL") { + t.Fatalf("text form: exit %d stderr %q", code, stderr) + } +} + +// F5: the `refs` document's field names are the contract a consumer reads (one reads +// `entries`, `cache_root`, `malformed`, `collisions`). Every level's key set is pinned +// literally, so a rename without a `schema` bump is a red test. +func TestRefsDocumentFieldNamesArePinned(t *testing.T) { + home, _ := ledgerHost(t) + cache := filepath.Join(home, ".cache", "subsystem-store") + entryFile(t, cache, "beta-notes", "alpha-svc.md", "alpha-svc", "shared") + entryFile(t, cache, "beta-notes", "bravo-svc.md", "bravo-svc", "shared") + code, stdout, stderr := runCLI(t, "refs", "--no-sync", "--scope", "beta-notes", "--json") + if code != ExitOK { + t.Fatalf("exit %d\n%s", code, stderr) + } + doc := decode(t, stdout) + check := func(level string, m map[string]any, want ...string) { + t.Helper() + if got := keysOf(m); !slices.Equal(got, want) { + t.Errorf("%s keys:\n got %v\n want %v", level, got, want) + } + } + check("document", doc, "instances", "schema", "status", "unread_instances", "verb") + inst := doc["instances"].([]any)[0].(map[string]any) + check("instance", inst, "cache_root", "instance", "not_routed_here", "scopes", "state", "state_detail", "unrouted") + if jsonString(inst["cache_root"]) != cache { + t.Errorf("cache_root = %v, want %s", inst["cache_root"], cache) + } + sc := inst["scopes"].([]any)[0].(map[string]any) + check("scope", sc, "collisions", "entries", "malformed", "refs_tried", "scope") + entries := sc["entries"].([]any) + if len(entries) != 3 { + t.Fatalf("entries = %d, want alpha-svc, bravo-svc and ledgerHost's two", len(entries)) + } + check("entry", entries[0].(map[string]any), "aliases", "filename", "kind", "ref", "slug") + collisions := sc["collisions"].([]any) + if len(collisions) != 1 { + t.Fatalf("collisions = %v, want the shared alias", collisions) + } + check("collision", collisions[0].(map[string]any), "candidates", "ref", "tier") + if m, ok := sc["malformed"].([]any); !ok || len(m) != 0 { + t.Errorf("malformed = %v, want an empty list", sc["malformed"]) + } +} + +// F1: `fold` is the reader's `NormalizeRef`/`PathRefs`, so a consumer keeps no copy. The `ref` +// rows are the seven folding rows of a downstream consumer's reference fixture, produced by the +// retired Python oracle; the `path_refs` rows were produced by that consumer's own Python copy of +// `path_refs` — the copy this verb retires. Literal, both: an independent implementation, never +// this one. +func TestFoldIsTheReadersRefFold(t *testing.T) { + ledgerHost(t) + refRows := [][2]string{ + {"Widget_API", "widget-api"}, + {" --a..b-- ", "a..b"}, + {"ünïcode", "n-code"}, + {"x.process", "x.process"}, + {"", ""}, + {"A B C", "a-b-c"}, + {"--", ""}, + } + pathRows := []struct { + in, ref string + pairs []string + }{ + {"apps/Widget_API/values.yaml", "apps-widget-api-values.yaml", + []string{"apps|apps", "Widget_API|widget-api", "values.yaml|values.yaml", "values|values"}}, + {"pkg/foo.tar.gz", "pkg-foo.tar.gz", []string{"pkg|pkg", "foo.tar.gz|foo.tar.gz", "foo.tar|foo.tar"}}, + {".gitignore", ".gitignore", []string{".gitignore|.gitignore"}}, + {"a/a/values.yaml", "a-a-values.yaml", []string{"a|a", "values.yaml|values.yaml", "values|values"}}, + {"./src//My File.GO", ".-src-my-file.go", []string{"src|src", "My File.GO|my-file.go", "My File|my-file"}}, + {"...", "...", []string{"...|..."}}, + {"x/--", "x", []string{"x|x"}}, + } + var inputs []string + for _, r := range refRows { + inputs = append(inputs, r[0]) + } + for _, r := range pathRows { + inputs = append(inputs, r.in) + } + raw, _ := json.Marshal(inputs) + var out bytes.Buffer + errFile, _ := os.CreateTemp(t.TempDir(), "stderr") + defer errFile.Close() + code := Run(Env{Stdout: &out, Stderr: errFile, Stdin: bytes.NewReader(raw), + Host: func() string { return "fixture-host-000000000000" }}, + []string{"fold", "--json", "--file", "-"}) + if code != ExitOK { + t.Fatalf("exit %d", code) + } + doc := decode(t, out.String()) + if got := keysOf(doc); !slices.Equal(got, []string{"results", "schema", "verb"}) { + t.Fatalf("document keys = %v", got) + } + if jsonString(doc["schema"]) != "1" || jsonString(doc["verb"]) != "fold" { + t.Fatalf("schema/verb = %v/%v", doc["schema"], doc["verb"]) + } + results := doc["results"].([]any) + if len(results) != len(inputs) { + t.Fatalf("results = %d, want %d (one per input, in order)", len(results), len(inputs)) + } + for i, r := range refRows { + res := results[i].(map[string]any) + if got := keysOf(res); !slices.Equal(got, []string{"input", "path_refs", "ref"}) { + t.Fatalf("result keys = %v", got) + } + if jsonString(res["input"]) != r[0] || jsonString(res["ref"]) != r[1] { + t.Errorf("fold(%q) = %q (input echoed %q), want %q", r[0], res["ref"], res["input"], r[1]) + } + } + for j, r := range pathRows { + res := results[len(refRows)+j].(map[string]any) + if jsonString(res["input"]) != r.in || jsonString(res["ref"]) != r.ref { + t.Errorf("fold(%q).ref = %q, want %q", r.in, res["ref"], r.ref) + } + var pairs []string + for _, p := range res["path_refs"].([]any) { + m := p.(map[string]any) + if got := keysOf(m); !slices.Equal(got, []string{"component", "ref"}) { + t.Fatalf("path_refs keys = %v", got) + } + pairs = append(pairs, jsonString(m["component"])+"|"+jsonString(m["ref"])) + } + if !slices.Equal(pairs, r.pairs) { + t.Errorf("fold(%q).path_refs:\n got %v\n want %v", r.in, pairs, r.pairs) + } + } +} + +func TestFoldRefusesAnythingButAJSONArrayOfStrings(t *testing.T) { + ledgerHost(t) + dir := t.TempDir() + for name, body := range map[string]string{ + "object": `{"a": "b"}`, + "null": `null`, + "null element": `["a", null]`, + "number": `["a", 1]`, + "not json": `Widget_API`, + } { + p := filepath.Join(dir, strings.ReplaceAll(name, " ", "-")+".json") + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + if code, stdout, _ := runCLI(t, "fold", "--json", "--file", p); code != ExitUsage || stdout != "" { + t.Errorf("%s: exit %d stdout %q; want 2 and nothing", name, code, stdout) + } + } + empty := filepath.Join(dir, "empty.json") + if err := os.WriteFile(empty, []byte(`[]`), 0o644); err != nil { + t.Fatal(err) + } + if code, stdout, _ := runCLI(t, "fold", "--json", "--file", empty); code != ExitOK || + len(decode(t, stdout)["results"].([]any)) != 0 { + t.Errorf("[]: exit %d stdout %q; want 0 and no results", code, stdout) + } + if code, stdout, _ := runCLI(t, "fold", "--file", empty); code != ExitUsage || stdout != "" { + t.Errorf("no --json: exit %d stdout %q", code, stdout) + } +} + +// F6: `parse`'s read cap IS the store's body cap — `write.MaxEntryBytes`, not a private copy. +// ⚠ An INVARIANT guard: the private constant had the same value, so this was green before the +// change too; it fails if the two caps ever diverge. +func TestParseCapIsTheStoresBodyCap(t *testing.T) { + ledgerHost(t) + dir := t.TempDir() + at := filepath.Join(dir, "at.md") + over := filepath.Join(dir, "over.md") + if err := os.WriteFile(at, bytes.Repeat([]byte("x"), write.MaxEntryBytes), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(over, bytes.Repeat([]byte("x"), write.MaxEntryBytes+1), 0o644); err != nil { + t.Fatal(err) + } + if code, _, stderr := runCLI(t, "parse", "--json", "--file", at); code != ExitOK { + t.Errorf("exactly MaxEntryBytes: exit %d\n%s", code, stderr) + } + if code, stdout, _ := runCLI(t, "parse", "--json", "--file", over); code != ExitUsage || stdout != "" { + t.Errorf("MaxEntryBytes+1: exit %d stdout %q; want 2 and nothing", code, stdout) + } +} diff --git a/internal/client/refs.go b/internal/client/refs.go new file mode 100644 index 00000000..2bf2a514 --- /dev/null +++ b/internal/client/refs.go @@ -0,0 +1,284 @@ +package client + +import ( + "errors" + "fmt" + "sort" + + "github.com/ZacxDev/cairn/internal/report" + "github.com/ZacxDev/cairn/internal/store" +) + +// Refs is `refs (--scope S | --all-scopes) [--no-sync] [--json]`: every ref the cached entries +// make addressable, and every one of them that is AMBIGUOUS — a ref that resolves to more than one +// entry surfaces nothing on `recall --ref`, so a collision is content nobody can reach. +// +// 🔴 THE RESOLVER IS THE ONLY JUDGE. Each candidate an entry makes addressable — its bare slug, +// its kind-qualified ref and each normalized alias — is fed back through `store.ResolveRefTiered`, +// the function `recall --ref` and the pod resolve with, and a collision is exactly an +// `AmbiguousRefError` coming out (with its tier and candidates). An alias that merely equals +// ANOTHER entry's slug is not reported: the filename tier wins there, so the resolver has no +// ambiguity to report. +// +// `--all-scopes` walks every configured instance and counts each scope ONCE, in the instance the +// routing table sends it to (`routes`). A scope cached on an instance the table routes it AWAY +// from is listed under that instance's `not_routed_here`, never counted, because its copy is not +// the one any read or write uses. `refs_tried` is the denominator, so "0 collisions" can be told +// apart from "nothing was walked". +// +// 🔴 AN UNROUTED SCOPE IS LOUD, NOT A QUIET LIST ENTRY. A cached scope `routing.AliasFor` REFUSES +// (the table names it nowhere on a multi-instance host, or names an instance this host lacks) is +// what `recall --scope` refuses at 11. Listing it beside the routed-elsewhere copies at exit 0 +// let a consumer that reads only `scopes` drop its entries without a sign. It goes in the +// instance's `unrouted`, is named on stderr, and the run exits 11 — the document is still printed. +// +// 🔴 AN UNREAD INSTANCE IS `search --all-scopes`'s PARTIAL: what the instances that answered hold +// is still printed (with `--json`, the document), the unread ones are named in `unread_instances` +// and in a `PARTIAL` line on stderr, and the run exits non-zero with the unread state's code (3). +// +// Exit codes are the reader's: 0 answered (a `--scope` the cache does not hold included — status +// `scope-absent`, `recall`'s and `associate`'s answer), 2 usage, 3/4 a cache that could not be +// read or dated (with `--all-scopes`, a PARTIAL answer), 5 a walked scope holds a malformed entry +// (it is listed and the rest still answered), 11 an unrouted scope (`--scope`: nothing printed; +// `--all-scopes`: the document is printed and names it). With `--all-scopes` the exit is the +// HIGHEST that applies; the document's `unread_instances`, `unrouted` and `malformed` say which. +func Refs(env Env, opts Options) (int, error) { + if opts.AllScopes && opts.Scope != "" { + fmt.Fprintln(env.Stderr, "cairn: refs takes --scope/--repo OR --all-scopes, not both") + return ExitUsage, nil + } + routing, err := Discover(nil) + if err != nil { + return 0, err + } + doc := refsDoc{Schema: JSONSchema, Verb: "refs", Status: RefsStatusAnswered, + Instances: []refsInstance{}, UnreadInstances: []string{}} + worst := ExitOK + absentScope := "" + if !opts.AllScopes { + scope, reason := ScopeOrReason(opts.Scope, opts.Repo) + if reason != "" { + fmt.Fprintln(env.Stderr, reason) + return ExitUsage, nil + } + alias, label, cache, err := readInstance(opts, scope) + if err != nil { + return 0, err + } + folded := store.NormalizeRef(scope) + inst, code, err := refsOverInstance(env, opts, alias, label, cache, func(index *store.Index) refsPick { + if !index.HasScope(scope) { + env.recordRead(alias, folded) + return refsPick{} + } + return refsPick{here: []string{folded}} + }) + if err != nil { + return 0, err + } + if inst == nil { + return code, nil + } + // 🔴 A SCOPE THE CACHE DOES NOT HOLD IS AN ANSWER, NOT A USAGE ERROR — `recall`'s and + // `associate`'s: status `scope-absent`, exit 0, the same for "never existed" and "not + // visible to this credential". + if len(inst.Scopes) == 0 { + doc.Status = RefsStatusScopeAbsent + absentScope = scope + } + doc.Instances = append(doc.Instances, *inst) + worst = max(worst, code) + } else { + if refusal := refuseSharedCache(env, routing, opts, "refs --all-scopes"); refusal != 0 { + return refusal, nil + } + for _, instance := range routing.Instances { + cache, err := instanceCache(opts, instance.Alias) + if err != nil { + return 0, err + } + label := instanceLabel(routing, instance.Alias) + inst, code, err := refsOverInstance(env, opts, instance.Alias, label, cache, func(index *store.Index) refsPick { + var pick refsPick + for _, scope := range index.Scopes() { + routed, rerr := routing.AliasFor(scope) + switch { + case rerr != nil: + pick.unrouted = append(pick.unrouted, scope) + fmt.Fprintf(env.Stderr, "🔴 cairn: refs --all-scopes: scope %s is cached on instance `%s` "+ + "but has no route, so its entries are NOT counted (recall --scope refuses it at %d): %v\n", + store.PyRepr(scope), instance.Alias, ExitUnrouted, rerr) + case routed == instance.Alias: + pick.here = append(pick.here, scope) + default: + pick.elsewhere = append(pick.elsewhere, scope) + } + } + return pick + }) + if err != nil { + return 0, err + } + if inst == nil { + doc.UnreadInstances = append(doc.UnreadInstances, instance.Alias) + worst = max(worst, code) + continue + } + doc.Instances = append(doc.Instances, *inst) + worst = max(worst, code) + if len(inst.Unrouted) > 0 { + worst = max(worst, ExitUnrouted) + } + } + if len(doc.UnreadInstances) > 0 { + fmt.Fprintf(env.Stderr, "🔴 cairn: PARTIAL — %d of %d instance(s) could not be read "+ + "(%s). What is printed is what the instances that ANSWERED hold; it is NOT an answer "+ + "about the ones that did not, and '0 collisions' does not cover them.\n", + len(doc.UnreadInstances), len(routing.Instances), joinComma(doc.UnreadInstances)) + } + } + if opts.JSON { + if err := writeJSON(env.Stdout, doc); err != nil { + return 0, err + } + return worst, nil + } + if absentScope != "" { + fmt.Fprintf(env.Stdout, "%s\t%s\n", RefsStatusScopeAbsent, absentScope) + return worst, nil + } + for _, inst := range doc.Instances { + for _, sc := range inst.Scopes { + for _, c := range sc.Collisions { + fmt.Fprintf(env.Stdout, "collision\t%s\t%s\t%s\t%s\n", sc.Scope, c.Ref, c.Tier, joinComma(c.Candidates)) + } + fmt.Fprintf(env.Stderr, "cairn: %s: %d ref(s) tried, %d collision(s)\n", sc.Scope, sc.RefsTried, len(sc.Collisions)) + } + } + return worst, nil +} + +// The `refs` document's statuses. `scope-absent` is `recall`'s own spelling. +const ( + RefsStatusAnswered = "answered" + RefsStatusScopeAbsent = report.StatusScopeAbsent +) + +// refsPick is which cached scopes one instance's walk counts (`here`), lists as routed to +// another instance (`elsewhere`), and lists as having no route at all (`unrouted`). +type refsPick struct { + here, elsewhere, unrouted []string +} + +// refsOverInstance loads one instance's cache and walks the scopes `pick` chooses. A nil +// instance with a code means the cache could not be read (banner already printed). +func refsOverInstance(env Env, opts Options, alias, label, cache string, + pick func(*store.Index) refsPick) (*refsInstance, int, error) { + state, err := ResolveState(cache, opts.NoSync, "", opts.Timeout, alias) + if err != nil { + return nil, 0, err + } + if state.ExitHint != 0 { + fmt.Fprintln(env.Stderr, BannerNamed(state.Name, state.Detail, label)) + return nil, state.ExitHint, nil + } + index, err := store.LoadStore(cache, "walked", store.Unrestricted()) + if err != nil { + return nil, 0, err + } + chosen := pick(index) + inst := &refsInstance{Instance: alias, CacheRoot: cache, State: state.Name, + StateDetail: state.Detail, Scopes: []refsScope{}, NotRoutedHere: nonNil(chosen.elsewhere), + Unrouted: nonNil(chosen.unrouted)} + code := ExitOK + for _, scope := range chosen.here { + env.recordRead(alias, scope) + sc, err := refsForScope(index, scope) + if err != nil { + return nil, 0, err + } + if len(sc.Malformed) > 0 { + code = ExitCorrupt + } + inst.Scopes = append(inst.Scopes, sc) + } + return inst, code, nil +} + +func refsForScope(index *store.Index, scope string) (refsScope, error) { + entries, err := index.Entries(scope) + if err != nil { + return refsScope{}, err + } + sc := refsScope{Scope: scope, Entries: []refsEntry{}, Collisions: []refsCollision{}, + Malformed: malformedJSON(index.MalformedIn(scope))} + candidates := map[string]bool{} + for _, e := range entries { + sc.Entries = append(sc.Entries, refsEntry{Ref: e.Ref(), Filename: e.Filename, Slug: e.Slug, + Kind: e.Kind, Aliases: nonNil(e.Aliases)}) + candidates[e.Slug] = true + candidates[e.Ref()] = true + for _, a := range e.Aliases { + candidates[a] = true + } + } + refs := make([]string, 0, len(candidates)) + for r := range candidates { + refs = append(refs, r) + } + sort.Strings(refs) + for _, ref := range refs { + _, _, rerr := store.ResolveRefTiered(ref, index, scope) + var amb *store.AmbiguousRefError + switch { + case rerr == nil: + case errors.As(rerr, &amb): + sc.Collisions = append(sc.Collisions, refsCollision{Ref: ref, Tier: amb.Tier, + Candidates: nonNil(amb.Candidates)}) + default: + return refsScope{}, rerr + } + } + sc.RefsTried = len(refs) + return sc, nil +} + +type refsDoc struct { + Schema int `json:"schema"` + Verb string `json:"verb"` + Status string `json:"status"` + Instances []refsInstance `json:"instances"` + UnreadInstances []string `json:"unread_instances"` +} + +type refsInstance struct { + Instance string `json:"instance"` + CacheRoot string `json:"cache_root"` + State string `json:"state"` + StateDetail string `json:"state_detail"` + Scopes []refsScope `json:"scopes"` + NotRoutedHere []string `json:"not_routed_here"` + Unrouted []string `json:"unrouted"` +} + +type refsScope struct { + Scope string `json:"scope"` + RefsTried int `json:"refs_tried"` + Entries []refsEntry `json:"entries"` + Collisions []refsCollision `json:"collisions"` + Malformed []jsonMalformed `json:"malformed"` +} + +type refsEntry struct { + Ref string `json:"ref"` + Filename string `json:"filename"` + Slug string `json:"slug"` + Kind string `json:"kind"` + Aliases []string `json:"aliases"` +} + +type refsCollision struct { + Ref string `json:"ref"` + Tier string `json:"tier"` + Candidates []string `json:"candidates"` +} 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..8861d5e9 100644 --- a/internal/client/verbs.go +++ b/internal/client/verbs.go @@ -13,6 +13,7 @@ import ( "sort" "strings" + "github.com/ZacxDev/cairn/internal/authz" "github.com/ZacxDev/cairn/internal/hostid" "github.com/ZacxDev/cairn/internal/report" "github.com/ZacxDev/cairn/internal/store" @@ -24,6 +25,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 +341,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 +453,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 +481,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 +592,13 @@ 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) + } + if opts.HasRef { + fmt.Fprintln(env.Stderr, "cairn: validate --ref applies only with --file (it names the ref the draft will be written under)") + return ExitUsage, nil + } scope := opts.Scope if scope == "" { scope = RepoScope(opts.Repo) @@ -809,22 +836,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 +1247,112 @@ func listedScopes(lines []string) []string { sort.Strings(out) return slices.Compact(out) } + +// validateFile is `validate --file PATH [--ref REF] [--scope S]`: 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, AND THE +// AGREEMENT IS ONLY AS WIDE AS THE INPUTS IT IS HANDED. `write.CheckEntryBytes` is the +// predicate `create`/`put` run on the pod (the loader's parse, then the closed `tags:` +// vocabulary), but the pod judges the bytes against a (scope, filename) it derives itself. +// So: +// +// - WITH `--ref`: the pair is derived EXACTLY as `create` derives it — the folded scope +// and `NormalizeRef(ref)+".md"` — so a draft this accepts is one `create --ref` +// accepts, and vice versa, for the body bytes. (`put` judges against the RESOLVED +// entry's own filename, which is the same file unless the ref reached it by alias.) +// - WITHOUT `--ref`: the filename is the draft's own basename and the scope its +// directory (or `--scope`) — the loader's rule for a file sitting in a cache. A draft +// named differently from the ref it will be written under can be judged differently +// here than at the write; pass `--ref` when you know it. +// +// IN BOTH MODES the pod's request-size cap (`write.MaxEntryBytes`) is checked first, since +// an oversize body is refused before any parse. +// +// OFFLINE BY CONSTRUCTION: no sync, no cache, no network. Exit 0 when accepted, 5 +// (`ExitCorrupt`, the same code a malformed CACHED entry gives) when refused, 2 when the +// file cannot be read, or the scope/ref is not a path component the store accepts. 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 + } + scope := opts.Scope + if scope == "" { + scope = filepath.Base(filepath.Dir(opts.File)) + } + filename := filepath.Base(opts.File) + if opts.HasRef { + // The pod refuses a scope or ref that is not ONE safe path component before it + // reads the body (`authz.SafePathComponent`: `[A-Za-z0-9_-]+`, so a dotted + // `x.process` is a 400 there), so it is refused here for the same reason. + for _, part := range []string{scope, opts.Ref} { + if !authz.SafePathComponent.MatchString(part) { + fmt.Fprintf(env.Stderr, "cairn: validate --file: %s is not a path component "+ + "the store accepts (letters, digits, `_` and `-` only) — a write under it "+ + "would be refused before the body is read\n", store.PyRepr(part)) + return ExitUsage, nil + } + } + folded := store.NormalizeRef(opts.Ref) + foldedScope := store.NormalizeRef(scope) + if folded == "" || foldedScope == "" { + fmt.Fprintf(env.Stderr, "cairn: validate --file: the scope and the ref must each "+ + "normalize to a non-empty slug (got scope %s, ref %s)\n", + store.PyRepr(scope), store.PyRepr(opts.Ref)) + return ExitUsage, nil + } + scope, filename = foldedScope, folded+".md" + } + label := opts.File + if info.Size() > write.MaxEntryBytes { + fmt.Fprintf(env.Stderr, "cairn: %s: malformed: %d bytes is over the %d-byte body "+ + "the store accepts — the write would be refused before it was read\n", + label, info.Size(), write.MaxEntryBytes) + fmt.Fprintf(env.Stdout, "cairn: %s: 0 of 1 entry file(s) parse, 1 malformed\n", label) + return ExitCorrupt, 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 + } + 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: