diff --git a/CHANGELOG.md b/CHANGELOG.md index e2f0a5f..eb9b1db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,14 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] ### Added +- Agent CLI: native discovery, source/full reads, structural queries, keyword + search, guarded writes, typed JSONL batches, staging/promotion and complete + session/audit history. +- Merge: complete directory and local Git captures, namespace-aware identity + relocation, exact heading selectors, portable replay/conflict records, + audited resolution/repair and nonblocking duplicate advice. +- Core: bounded 10,000-deep trees, complete optional agent layers, native node + annotations and exact UTF-8 source spans for lossless edits and grounding. - Core and viewer: preserve claim falsification criteria and show claim IDs, experiment proof references, and claim dependencies (#61). - Core and viewer: explicit per-node `artifacts` lists carry names, display-only @@ -41,8 +49,179 @@ All notable changes to this project are documented here. The format follows Original source and visible errors remain on malformed equations or local renderer, stylesheet, or font failures. Protected code and non-math text stay unchanged; untrusted commands and macros are isolated and bounded (#31). +- Agent reads: canonical addresses (`path#h//…[;occurrence=N]`, plus + cited `logic/claims.md#C04`, `C04`, `trace:N09`) are accepted by `show` and + printed by every brief read. Misses report `unknown_id` and ambiguities + `ambiguous_heading`, each with up to 40 ranked candidates. +- Agent reads: `show --lines A:B` and `--max-bytes N` page native source on whole + lines; each page carries the full selection's digest and the next `--lines` + window. `find --context N` and `ls ` are new. +- Core: claim headings accept a spaced hyphen, en dash or em dash separator; a + stray leading `---` before `# Claims` in `logic/claims.md` is recovered with + `ARA228`, and other unclosed front matter stays hidden with `ARA229`. +- Agent CLI: a batch's one `session.log` with a summary can own omitted audit + context. `logic.revise`, audited `entry.rename`/`entry.remove`, + `paper.edit.audit`, `observation.mark_stale.audit` and reasoning + `record.append` may leave out `session`/`turn` (or `record.turn`) when they + follow that log. A log that omits `session` selects the one open session on + its date, or creates one with its summary; several open candidates are an + error that lists them, and other open sessions are reported in + `open_sessions`. +- Agent CLI: omitted node, observation, session-log, session-start and taste + timestamps (and the inline taste date) use one UTC clock value that the + writer reads once, after it takes the lock and recovers. Explicit values stay + exact. +- Merge: `merge resolve` and `merge repair` take an optional `--turn` (it must + equal the session's next turn), plus `--timestamp` and `--summary`, and report + the resolved `session` and `turn`. +- Agent CLI: a batch with a `session.log` derives its turn's mechanical + `events_logged` rows (from `node.add`, `observation.stage`, `claim.add`, + `heuristic.add` and `observation.promote`) and `claims_touched` rows + (`created`, `crystallized`, `revised`). Caller rows keep their summaries and + judgments; a judgment replaces the generic `revised` row. No-op operations + derive nothing. +- Agent CLI: event rows take an optional `target` selector naming the exact + destination of a concept, constraint or architecture promotion; `refs` + reports it. +- Agent CLI: write errors that involve two inputs report the other one as + `related_line` and `related_field`. +- Agent reads: `open` observation rows add `turns_since_reference`, + `session_days_since_reference`, `last_reference_turn`, + `last_reference_date`, `reference_basis`, `evidence_sources`, + `history_status` and `history_diagnostics`, counted from exact ID and + bound-node references on a validated session timeline. Unknown chronology is + `null` with a diagnostic; overlapping sessions keep the day count. Brief text + ends observation rows with the counts. +- Agent CLI: `observation.mark_stale` `session_days` is optional; the writer + derives and records the eligible logged days after the last reference, up to + the audit date, and refuses unknown day evidence with + `write.stale_history_unknown`. +- Agent CLI: `entry.rename`, `entry.remove` (with `redirect`) and a claim-merge + `logic.revise` (`Status: withdrawn` plus `Merged into`) accept + `rewrite_references: true`, which repairs typed citations in accepted + reference fields through exact audited edits and reports + `rewritten_references` and located `skipped_references`. A claim split is + `logic.revise` with `action: "split"`, `split_into` and a `references` row for + every current citing field. Remaining mentions, ambiguous history, + self-citations, merge cycles and unclassified citers refuse with + `details.locations`; historical records are never rewritten and must resolve + through the retained entry or the authenticated mutation ledger. +- Agent CLI: the source of an explicit merge derives `claims_touched` + `merged`, and a split's primary derives `split`; the primary's + `logic_revisions` rows may carry `action: split` and `split_into`. +- Agent CLI: restructure results list the historical citations they verified + as `historical_citations`; final validation also resolves them through the + read side's identity index. ### Changed +- Agent reads: an `ARA217`/`ARA218` warning about one optional-layer file + (`staging/observations.yaml`, `trace/taste_log.yaml`, `trace/sessions/*`, + `logic/experiments.md`, `logic/solution/heuristics.md`, or the PAPER + `knowledge_paths` registry) no longer refuses `ls`, `show` and `find` + (0.1.34, plan 23, #128). The read prints its result with `complete: false` + and `incomplete: [{path, codes, reason}]`, brief text adds an + `incomplete: ()` line, and the read exits 0 like any read + with warnings (`status` still exits 1 when incomplete). `status` keeps + its counts and withholds only the next ID of an affected prefix + (`next_id.incomplete_layer`). Node-scoped `ARA217`, `ARA222` and `ARA226` + still refuse with `incomplete_artifact`. +- Agent reads: bounded `find` (0.1.32, plan 22 part D). Brief `find` keeps + the first 3 matched lines of each hit and ends the hit with + `+K more matching lines`; `--lines-per-hit N` changes the cap and `0` + keeps every line (JSON keeps its 20-line cap unless the flag is given). + `--context` lines and `in:` lines go with their kept line. `--max-bytes` + bounds `find` as it bounds `show`, defaulting to 16 KiB for brief text: + whole hits are dropped from the end, and a closing line says + `N more hits; narrow with --type, --document or more specific terms` + (`truncation.omitted_hits` in JSON). A first hit that alone overflows + keeps fewer matched lines and the line starts + `first hit cut to fit the byte budget`; when one line does not fit, the + read fails with `output_limit_too_small`. `--document ` + (repeatable) keeps hits from those documents and refuses the paths + `show --document` refuses; `--all` keeps hits containing every query + term. Filters keep the unfiltered ranking order. The 0.1.31 marker + `… K more matching lines` becomes `+K more matching lines`. +- Agent reads: fewer failed and guessed addresses (0.1.31, plan 22 part C). + A multi-address `show` whose addresses partly fail prints every resolved + block and, in request order, an `==
[error]` block with the same + error text and `candidates:` that address prints alone; it exits 1. + `--json` adds an `errors` array (`position`, `address`, `error`) beside + `entries`. Read budgets count the error blocks. A single failing address, + and failures other than `unknown_id`, `ambiguous_heading`, + `invalid_address` or `invalid_document`, still reject the whole read. Each + matched line of a whole-document `find` hit under a heading gains the + address of its innermost section, printed as `in:
` when it + changes (`matches[].in` in JSON). A bare entry ID such as `O3`, `G1` or + `E01` that names no loaded entry selects the one knowledge-document + heading starting with `:` or ` —`; several such headings return + `ambiguous_heading` with their addresses. +- CLI reader skill: one-step startup (0.1.30, plan 22 part B). + `research-foresight-cli` replaces the boundary paragraphs of SKILL, RETRIEVE, + PREDICT and CONTRACT with one Access block in `SKILL.md` and a six-line + command card, reads RETRIEVE and PREDICT together, and opens + `references/cli-access.md` only when an `ara` error does not explain the fix. + RETRIEVE Step 2 sends `ara ls` with the first searches, sends one `find` per + need in one response and then one multi-address `show`, and pairs `ara find` + with a Grep of `rubric/`, `evidence/` and `src/` for whole-artifact searches. + Writer links, `status`, the `E01` batching example, provenance and pin notes + leave the reader pages. A test runs every command-card line on the binary. +- CLI reader skill: fewer model round trips. `references/cli-access.md` keeps + only boundary, shell-call, reading and read-only task guidance (44.3k → 10.4k + characters); writer guidance moves to `references/cli-write.md`, shipped only + with `research-manager-cli` and `compiler-cli`. `research-foresight-cli` + adopts the Files grounding rule (`show` the surrounding section when a hit is + too terse to judge) and teaches one multi-term `find`, multi-address `show` + and parallel `ara` shell calls in one response. On 60 development questions + this lowered requests per question from 13.73 to 10.67 and list-price agent + cost by 29% against unchanged 0.1.27 skills; see + `docs/agent-cli-interface/21-reader-round-trips.md`. +- Agent CLI: consolidate ancestry and citation reads into `show --with path,refs`, + unfinished work into `ls --unfinished`, and exact imported/retained identity + lookup into `show --identity`. Relation arrays stay complete under output + bounds; unsupported selector combinations reject explicitly. +- Live CLI skills and the offline acceptance runner use the simplified command + surface. Task-oriented skill sections teach typed `apply` workflows while + retaining direct setters, research judgment, and atomic audit protections. +- Core: replace the native single-target citation query with + `markdown_citations_many`, sharing the writer's token classification once per + multi-target request. The CLI dependency minimum is now `ara-core` 0.1.27. +- Command removal is a breaking public-interface change. Workspace 0.1.27 is an + unreleased engineering revision; the integration release must settle the + repository's major-version rule before publication. +- Agent reads: `refs` uses the writer's citation rules. For claims, + heuristics, experiment plans and concepts it lists the same Markdown + citations a restructure repairs (including qualified heading spellings); + tokens inside quotes, backticks or HTML comments are no longer listed; + `trace/aliases.yaml` alias targets are listed; a tree `concepts` name is + listed only when it resolves to exactly one concept heading. +- Agent reads default to brief address-led text; `--json` output keeps its + fields, with additive `find` hit lines and opt-in bounded `display` metadata. + Text diagnostics print once on stderr as counts and codes. +- Heading lookup is exact-first, then case-insensitive equality, unique prefix + and a trailing literal `...`. Read errors no longer expose `merge.*` codes; + broken identity records report `identity_lookup_failed`. +- Structural reads succeed on fully represented artifacts whose only errors are + dangling references (`ARA107`–`ARA109`); other errors still refuse, now with + `details.blocking` and `details.hint`. Writes reject unclosed front matter. +- CLI skills teach one quoted `ara` call per shell call, native bounds, and + orient/search/read/cite with printed addresses. +- `ara check --fix` shares the guarded writer's lock and durable recovery journal. +- Public Rust node constructors and typed bodies include the native agent fields; + JSON additions remain optional. The integration minor/major release decision + is pending; version 0.1.25 is the unreleased engineering revision. +- Native parsing and merge planning avoid repeated YAML work and unchanged-field + copies while preserving strict duplicate-key/resource guards, opaque historical + data, exact source bytes, and deterministic duplicate-candidate ordering. +- Native merge ledger captures use canonical padded RFC 4648 base64 strings for + revision files, transport bytes and imported-resolution evidence, retaining + exact decoded bytes and fingerprints. Native core adds the optional `base64` + dependency; public conflict/report byte arrays are unchanged. +- Native hashing enables RustCrypto's CPU-dispatched SHA-256 backend, retaining + the software fallback and identical fingerprints; `sha2-asm` is a native-only + transitive dependency. Flow-map child insertion preserves the JSON subset. +- Large native CLI merges overlap immutable duplicate advice with durable commit; + commit errors retain precedence and no advice changes knowledge bytes. Phase + elapsed times may overlap; every required final process budget passes. - CLI: update toml to 1.1.6+spec-1.1.0, including its parser and writer dependencies (#119). - CLI: update tokio to 1.53.2 for the local server runtime (#120). - Core: bump serde-saphyr to 1.3.0 (#90). @@ -50,6 +229,122 @@ All notable changes to this project are documented here. The format follows (`ARA105 error: nodes[N01]: duplicate node id`), and each `--json` `validate.errors`/`validate.warnings` entry gains a `rule` field. `ara validate` output is unchanged (#43). +- Agent CLI: `session log` without `--session` now requires `--summary`. The + writer picks or creates the session under its lock instead of the CLI + choosing a same-date session from an unlocked read. +- Merge: an omitted `--timestamp` on `merge resolve`/`merge repair` uses the + locked clock rather than the session's last turn time, so a session from an + earlier date needs an explicit timestamp on that date. +- Agent CLI (compatibility): in a batch with a `session.log`, a creation + without provenance needs its event row (`write.event_provenance`). An event + row for a concept, constraint or architecture promotion without `target`, or + a `crystallized` row naming the promotion's source observation, now rejects + (`write.event_conflict`), as does any caller row that disagrees with the + operation it names or two different rows for one event. A claim judgment + that contradicts the same turn's explicit Status change (`confirmed`, + `refuted`, `withdrawn`/`merged`), or `confirmed` with `refuted` without two + distinct Status changes, rejects (`write.claim_touch_conflict`). With several + logs, each new entry must be named in exactly one of them + (`write.owner_ambiguous`). Repeated identical rows are written once. +- Skills: `research-manager-cli` and the shared `cli-access.md` copies drop the + manual `Last revised`, `logic_revisions` copy, observation pointer and + `Crystallized via`/`From staging` steps, use the owner-anchor `session.log`, + and show which session rows the CLI derives. +- Agent CLI (compatibility): stale evidence no longer counts the stale + decision's own turn, so an audit that owned the third proving day now needs + another logged turn on that day or a later owner. A supplied `session_days` + entry that is not eligible reports `session_days[i]`. +- Skills: `research-manager-cli` reads turn and day counts from `ara open` + instead of counting by hand, and marks stale without `session_days`. + +### Removed +- Agent CLI: remove `add`, `stage`, `promote`, `session`, `link`, standalone + `path`, `refs`, `open`, and `resolve`, plus `claim add` and `heuristic add`. + Their typed writer operations remain available through `apply`; the + [migration guide](docs/agent-cli.md#command-simplification-migration) records + argument and result mappings. No compatibility aliases remain. +- Native PaperBench rubric handling: `rubric/requirements.md` is no longer + parsed, read, written or merged as native knowledge, and the public + `EntryKind::Requirement` variant and `R` IDs are gone. `rubric/` joins + `evidence/` and `src/` as a direct-file, external read-only merge root + (matched in any letter case); + `invalid_document` errors name these roots. Old rubric history stays readable. + +### Fixed +- Core reads: one mistyped value in a node text field no longer fails the + whole exploration tree with `ARA100` (0.1.35, plan 24, #130). `evidence:` + keeps a plain scalar's source spelling like every other text field, so an + all-digit commit SHA (`7258910`) or `0123456` stays text. A value the parser + cannot take as text (a bare numeric `evidence:` scalar, or a mapping or list + such as the plain item `- a (rejected: b)`) is read as its exact source text + and warns `ARA230 non-text-tree-field`; reads stay complete and exit 0. + Identity fields stay strict. New fixable format rule `ARA008 + unquoted-tree-scalar`: `ara check --fix` single-quotes one-line values. +- Core reads: experiment and heuristic headings accept the separators claims + accept (`## E01 — Title`, `## H03 – Title`, `## E02 - Title`) and a bracketed + status before the separator (`## E02 [in progress]: Title`), which becomes + the entry's `status` unless a `**Status**` field is present (0.1.34, #128). + One shared parser serves the reader, merge identity and CLI heading lookup. + The `malformed entry heading` warning now gives its line and heading. +- Core validation: the dependency-cycle check (`ARA110`, 0.1.33) orients + `also_depends_on` edges from dependency to dependent, the same direction as + `children:` nesting. A cross-branch diamond, such as a node depending on a + node elsewhere that itself depends on an ancestor, is no longer reported as + a cycle and no longer makes `ls`, `find` and `status` refuse the artifact. + A node that depends on its own descendant is now reported as a cycle. +- Core reads: `logic/experiments.md`, `logic/solution/heuristics.md` and + `logic/problem.md` that open with a stray, unclosed `---` line before a + level-one title and typed entries (`## E01: …`, `## H01: …`, `### O1: …`) + are recovered like `logic/claims.md`: their experiment plans, heuristics and + headings load and stay addressable, with warning `ARA228` instead of + `ARA229`. Other `logic/` documents (concepts, related work, untyped solution + documents) recover under a looser rule: a level-one title and a level-two + section after the opener, and text that does not load as a YAML mapping or + null. Metadata-like content still stays hidden, and writes still refuse the + unclosed fence. Seven paperbench artifacts had eight or nine documents each + hidden from `ls`, `find` addresses and `show`; none remain hidden. +- Agent CLI: projected non-JSON whole-document reads retain requested refs for + positional and `--document` selectors; reads without selected relations keep + exact raw content (#117). +- Agent CLI: `show --source` accepts one positional document + path in place of `--document`; file-access roots still return + `invalid_document`. CLI skills tell agents to list, search and read + `rubric/`, `src/` and `evidence/` with file tools rather than shell commands. +- Agent CLI: observation history no longer ignores reference-bearing YAML + aliases, redirects native continuation text through an imported session, or + treats scoped IDs/filenames as local references. Imported literal origins + use captured occurrence evidence; missing proof refuses stale writes (#115). +- Agent CLI: repeated imports use the latest same-source mutable session + capture, so superseded summaries no longer invalidate authenticated history + or block otherwise-valid stale decisions. Append-only and competing-source + origin checks remain strict (#115). +- Agent CLI: retained imported rolling fields remain unknown when a newer + source snapshot omits their value; committed mutable conflicts no longer + reclassify protected peer literals as local references (#115). +- Agent CLI: citation repair preserves inner quotations/backticks in native + JSON lists, keeps historical heading-array segments literal, resolves earlier + bindings in split/repair selectors, and refuses explicit repair rows that + introduce self-citations (#115). +- Agent CLI: selected-claim Body Status changes participate in same-turn + judgment checks; distinct merge/split actions each receive their derived + claim touch in operation order (#115). +- Agent reads: renaming one of two concept leaves that share a display key + (`Group A/Term`, `Group B/Term`) no longer makes `show`/`refs` fail with + "retired native identity was reused by live content". +- Agent reads: `show` follows an authenticated rename or removal mapping for + a retired nested heading's canonical `#h/...` address, its joined-path + `path#A/B` locator and the mapping's `path:A/B` origin. +- Agent reads and writes: copied audit text (revision before/after values, + archived rolling fields, stale-evidence records, the session index) no + longer counts as new activity for an observation; `open` and + `observation.mark_stale` share one explicit-reference history. +- Agent CLI: new claim and heuristic blocks (`claim add`, `heuristic add`, + promotion) list fields in the fixed schema order instead of alphabetically, + write single-line values inline, render Dependencies as `[C03, C04]`, and + keep other lists as lossless JSON arrays. +- Artifacts with a rubric rename record no longer fail `merge` and `show` with + `merge.redirect_data`; old rubric aliases and retained journals no longer + block reads, writes or merges. ## [0.1.16] - 2026-08-23 diff --git a/Cargo.lock b/Cargo.lock index bbf288d..13b1bb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -79,7 +79,7 @@ version = "1.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -90,7 +90,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" dependencies = [ "anstyle", "once_cell_polyfill", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -112,7 +112,7 @@ checksum = "2a4385e2e34eb35d6b3efe798b9eb88096925d87726c0798709bf56d9ed84af3" [[package]] name = "ara-cli" -version = "0.1.24" +version = "0.1.35" dependencies = [ "ara-core", "arc-swap", @@ -126,7 +126,9 @@ dependencies = [ "notify-debouncer-full", "predicates", "serde", + "serde-saphyr", "serde_json", + "sha2", "tempfile", "tokio", "toml", @@ -136,19 +138,23 @@ dependencies = [ [[package]] name = "ara-core" -version = "0.1.24" +version = "0.1.35" dependencies = [ + "base64", "dagre-dgl-rs", "insta", "serde", "serde-saphyr", "serde_json", + "serde_path_to_error", + "sha2", "tempfile", + "yaml-rust2", ] [[package]] name = "ara-viewer" -version = "0.1.24" +version = "0.1.35" dependencies = [ "ara-core", "console_error_panic_hook", @@ -166,7 +172,7 @@ dependencies = [ [[package]] name = "ara-wasm" -version = "0.1.24" +version = "0.1.35" [[package]] name = "arc-swap" @@ -770,7 +776,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -840,6 +846,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -1065,12 +1077,30 @@ version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17e2ac29387b1aa07a1e448f7bb4f35b500787971e965b02842b900afa5c8f6f" +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + [[package]] name = "heck" version = "0.5.0" @@ -1311,7 +1341,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", - "hashbrown", + "hashbrown 0.17.1", ] [[package]] @@ -1722,7 +1752,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -2173,7 +2203,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -2390,6 +2420,16 @@ dependencies = [ "cfg-if", "cpufeatures", "digest", + "sha2-asm", +] + +[[package]] +name = "sha2-asm" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b845214d6175804686b2bd482bcffe96651bb2d1200742b712003504a2dac1ab" +dependencies = [ + "cc", ] [[package]] @@ -2448,7 +2488,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -2544,7 +2584,7 @@ dependencies = [ "getrandom 0.4.3", "once_cell", "rustix", - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3075,7 +3115,7 @@ version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.61.2", + "windows-sys 0.60.2", ] [[package]] @@ -3194,6 +3234,17 @@ version = "0.8.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4d93c89cdc2d3a63c3ec48ffe926931bdc069eafa8e4402fe6d8f790c9d1e576" +[[package]] +name = "yaml-rust2" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2462ea039c445496d8793d052e13787f2b90e750b833afee748e601c17621ed9" +dependencies = [ + "arraydeque", + "encoding_rs", + "hashlink", +] + [[package]] name = "yoke" version = "0.8.3" diff --git a/Cargo.toml b/Cargo.toml index 8022b44..7bedbb2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/*"] [workspace.package] -version = "0.1.24" +version = "0.1.35" edition = "2024" license = "MPL-2.0" repository = "https://github.com/ARA-Labs/ara-cli" diff --git a/crates/ara-cli/Cargo.toml b/crates/ara-cli/Cargo.toml index 630fea8..3af3845 100644 --- a/crates/ara-cli/Cargo.toml +++ b/crates/ara-cli/Cargo.toml @@ -25,11 +25,14 @@ name = "ara" path = "src/main.rs" [dependencies] -ara-core = { path = "../ara-core", version = "0.1.22" } +ara-core = { path = "../ara-core", version = "0.1.29" } clap = { version = "4", features = ["derive"] } # `ara check --json` serializes a composed report struct via `#[derive(Serialize)]`. serde = { version = "1", features = ["derive"] } serde_json = "1" +sha2 = "0.10" +serde-saphyr = { version = "=1.3.0", default-features = false, features = ["deserialize"] } +tempfile = "3" # `ara check` reads its optional `.ara-check.toml` (#40); parse-only, no writer. toml = { version = "1", default-features = false, features = ["std", "parse", "serde"] } @@ -50,7 +53,6 @@ mime_guess = "2" [dev-dependencies] assert_cmd = "2" predicates = "3" -tempfile = "3" # HTTP-layer tests read bodies with http-body-util; `tower` (with `util` for # `ServiceExt::oneshot`) is a normal dependency, so it isn't repeated here. http-body-util = "0.1" diff --git a/crates/ara-cli/assets/viewer.source-hash b/crates/ara-cli/assets/viewer.source-hash index d83b272..f273187 100644 --- a/crates/ara-cli/assets/viewer.source-hash +++ b/crates/ara-cli/assets/viewer.source-hash @@ -1 +1 @@ -1a9bd27b3ca8f8a2b9a5f2c8988fa84abeee2a3a416073d1574e565c605ca643 +ec6e9e51dc50bc8c1215dec85c0fda912beb4aa71519a18d9978ae93a125fdaf diff --git a/crates/ara-cli/assets/viewer/ara-viewer-f2516cc8c2592820.js b/crates/ara-cli/assets/viewer/ara-viewer-e115729a4723a218.js similarity index 96% rename from crates/ara-cli/assets/viewer/ara-viewer-f2516cc8c2592820.js rename to crates/ara-cli/assets/viewer/ara-viewer-e115729a4723a218.js index 97fb846..58876f6 100644 --- a/crates/ara-cli/assets/viewer/ara-viewer-f2516cc8c2592820.js +++ b/crates/ara-cli/assets/viewer/ara-viewer-e115729a4723a218.js @@ -207,7 +207,7 @@ function __wbg_get_imports() { const ret = getObject(arg0).cancelBubble; return ret; }, - __wbg_cancelJob_49aef78f0136a80a: function(arg0) { + __wbg_cancelJob_6b02cf1034eb9705: function(arg0) { AraMath.cancelJob(getObject(arg0)); }, __wbg_checked_596d0d7b35f55a01: function(arg0) { @@ -286,7 +286,7 @@ function __wbg_get_imports() { const ret = getObject(arg0).createElement(getStringFromWasm0(arg1, arg2)); return addHeapObject(ret); }, arguments); }, - __wbg_createJob_cd0ad5216e8b7676: function() { return handleError(function (arg0, arg1, arg2) { + __wbg_createJob_320b40ac295013a2: function() { return handleError(function (arg0, arg1, arg2) { const ret = AraMath.createJob(getStringFromWasm0(arg0, arg1), arg2 !== 0); return addHeapObject(ret); }, arguments); }, @@ -310,7 +310,7 @@ function __wbg_get_imports() { const ret = getObject(arg0).deltaY; return ret; }, - __wbg_detail_063e41b57bbdb4da: function(arg0, arg1) { + __wbg_detail_49b78c044836f12a: function(arg0, arg1) { const ret = getObject(arg1).detail; const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2); const len1 = WASM_VECTOR_LEN; @@ -374,14 +374,14 @@ function __wbg_get_imports() { const ret = getObject(arg0).height; return ret; }, - __wbg_host_067ec725f43a3309: function(arg0) { - const ret = getObject(arg0).host; - return isLikeNone(ret) ? 0 : addHeapObject(ret); - }, __wbg_host_18450e7fb2bf2108: function(arg0) { const ret = getObject(arg0).host; return addHeapObject(ret); }, + __wbg_host_2096b9a19a15e9fe: function(arg0) { + const ret = getObject(arg0).host; + return isLikeNone(ret) ? 0 : addHeapObject(ret); + }, __wbg_host_8528938720b0ef01: function(arg0, arg1) { const ret = getObject(arg1).host; const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2); @@ -492,7 +492,7 @@ function __wbg_get_imports() { const ret = getObject(arg0).item(arg1 >>> 0); return isLikeNone(ret) ? 0 : addHeapObject(ret); }, - __wbg_jobPromise_073dd3d0f2f94686: function(arg0) { + __wbg_jobPromise_a1898ffaf648676a: function(arg0) { const ret = AraMath.jobPromise(getObject(arg0)); return addHeapObject(ret); }, @@ -562,7 +562,7 @@ function __wbg_get_imports() { const a = state0.a; state0.a = 0; try { - return __wasm_bindgen_func_elem_2651(a, state0.b, arg0, arg1); + return __wasm_bindgen_func_elem_2786(a, state0.b, arg0, arg1); } finally { state0.a = a; } @@ -767,17 +767,17 @@ function __wbg_get_imports() { getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); }, - __wbg_status_41510d24bc7a55f9: function(arg0, arg1) { + __wbg_status_c45b3b9b3033184a: function(arg0) { + const ret = getObject(arg0).status; + return ret; + }, + __wbg_status_f1e7f009c6558e96: function(arg0, arg1) { const ret = getObject(arg1).status; const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_export, wasm.__wbindgen_export2); const len1 = WASM_VECTOR_LEN; getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); }, - __wbg_status_c45b3b9b3033184a: function(arg0) { - const ret = getObject(arg0).status; - return ret; - }, __wbg_stopPropagation_4c4ff88c29f9bc38: function(arg0) { getObject(arg0).stopPropagation(); }, @@ -853,38 +853,38 @@ function __wbg_get_imports() { return ret; }, __wbindgen_cast_0000000000000001: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1324); + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 115, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1407); return addHeapObject(ret); }, __wbindgen_cast_0000000000000002: function(arg0, arg1) { // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [Externref], shim_idx: 339, ret: Result(Unit), inner_ret: Some(Result(Unit)) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_2590); + const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_2719); return addHeapObject(ret); }, __wbindgen_cast_0000000000000003: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("CloseEvent")], shim_idx: 113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1324_2); + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("CloseEvent")], shim_idx: 115, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1407_2); return addHeapObject(ret); }, __wbindgen_cast_0000000000000004: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1324_3); + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("Event")], shim_idx: 115, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1407_3); return addHeapObject(ret); }, __wbindgen_cast_0000000000000005: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("KeyboardEvent")], shim_idx: 113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1324_4); + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("KeyboardEvent")], shim_idx: 115, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1407_4); return addHeapObject(ret); }, __wbindgen_cast_0000000000000006: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("MessageEvent")], shim_idx: 113, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1324_5); + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [NamedExternref("MessageEvent")], shim_idx: 115, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_1407_5); return addHeapObject(ret); }, __wbindgen_cast_0000000000000007: function(arg0, arg1) { - // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 100, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. - const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_2541); + // Cast intrinsic for `Closure(Closure { owned: true, function: Function { arguments: [], shim_idx: 76, ret: Unit, inner_ret: Some(Unit) }, mutable: true }) -> Externref`. + const ret = makeMutClosure(arg0, arg1, __wasm_bindgen_func_elem_2677); return addHeapObject(ret); }, __wbindgen_cast_0000000000000008: function(arg0, arg1) { @@ -906,34 +906,34 @@ function __wbg_get_imports() { }; } -function __wasm_bindgen_func_elem_2541(arg0, arg1) { - wasm.__wasm_bindgen_func_elem_2541(arg0, arg1); +function __wasm_bindgen_func_elem_2677(arg0, arg1) { + wasm.__wasm_bindgen_func_elem_2677(arg0, arg1); } -function __wasm_bindgen_func_elem_1324(arg0, arg1, arg2) { - wasm.__wasm_bindgen_func_elem_1324(arg0, arg1, addHeapObject(arg2)); +function __wasm_bindgen_func_elem_1407(arg0, arg1, arg2) { + wasm.__wasm_bindgen_func_elem_1407(arg0, arg1, addHeapObject(arg2)); } -function __wasm_bindgen_func_elem_1324_2(arg0, arg1, arg2) { - wasm.__wasm_bindgen_func_elem_1324_2(arg0, arg1, addHeapObject(arg2)); +function __wasm_bindgen_func_elem_1407_2(arg0, arg1, arg2) { + wasm.__wasm_bindgen_func_elem_1407_2(arg0, arg1, addHeapObject(arg2)); } -function __wasm_bindgen_func_elem_1324_3(arg0, arg1, arg2) { - wasm.__wasm_bindgen_func_elem_1324_3(arg0, arg1, addHeapObject(arg2)); +function __wasm_bindgen_func_elem_1407_3(arg0, arg1, arg2) { + wasm.__wasm_bindgen_func_elem_1407_3(arg0, arg1, addHeapObject(arg2)); } -function __wasm_bindgen_func_elem_1324_4(arg0, arg1, arg2) { - wasm.__wasm_bindgen_func_elem_1324_4(arg0, arg1, addHeapObject(arg2)); +function __wasm_bindgen_func_elem_1407_4(arg0, arg1, arg2) { + wasm.__wasm_bindgen_func_elem_1407_4(arg0, arg1, addHeapObject(arg2)); } -function __wasm_bindgen_func_elem_1324_5(arg0, arg1, arg2) { - wasm.__wasm_bindgen_func_elem_1324_5(arg0, arg1, addHeapObject(arg2)); +function __wasm_bindgen_func_elem_1407_5(arg0, arg1, arg2) { + wasm.__wasm_bindgen_func_elem_1407_5(arg0, arg1, addHeapObject(arg2)); } -function __wasm_bindgen_func_elem_2590(arg0, arg1, arg2) { +function __wasm_bindgen_func_elem_2719(arg0, arg1, arg2) { try { const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - wasm.__wasm_bindgen_func_elem_2590(retptr, arg0, arg1, addHeapObject(arg2)); + wasm.__wasm_bindgen_func_elem_2719(retptr, arg0, arg1, addHeapObject(arg2)); var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true); var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true); if (r1) { @@ -944,8 +944,8 @@ function __wasm_bindgen_func_elem_2590(arg0, arg1, arg2) { } } -function __wasm_bindgen_func_elem_2651(arg0, arg1, arg2, arg3) { - wasm.__wasm_bindgen_func_elem_2651(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3)); +function __wasm_bindgen_func_elem_2786(arg0, arg1, arg2, arg3) { + wasm.__wasm_bindgen_func_elem_2786(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3)); } diff --git a/crates/ara-cli/assets/viewer/ara-viewer-e115729a4723a218_bg.wasm b/crates/ara-cli/assets/viewer/ara-viewer-e115729a4723a218_bg.wasm new file mode 100644 index 0000000..66d77b3 Binary files /dev/null and b/crates/ara-cli/assets/viewer/ara-viewer-e115729a4723a218_bg.wasm differ diff --git a/crates/ara-cli/assets/viewer/ara-viewer-f2516cc8c2592820_bg.wasm b/crates/ara-cli/assets/viewer/ara-viewer-f2516cc8c2592820_bg.wasm deleted file mode 100644 index 0420d04..0000000 Binary files a/crates/ara-cli/assets/viewer/ara-viewer-f2516cc8c2592820_bg.wasm and /dev/null differ diff --git a/crates/ara-cli/assets/viewer/index.html b/crates/ara-cli/assets/viewer/index.html index c753f40..efcfa0b 100644 --- a/crates/ara-cli/assets/viewer/index.html +++ b/crates/ara-cli/assets/viewer/index.html @@ -12,8 +12,8 @@ - + diff --git a/crates/ara-cli/src/agent.rs b/crates/ara-cli/src/agent.rs new file mode 100644 index 0000000..5787c0d --- /dev/null +++ b/crates/ara-cli/src/agent.rs @@ -0,0 +1,1401 @@ +//! Agent reads over one complete native load and a borrowing graph index. +use crate::output::{AgentError, excerpt}; +use ara_core::query::{QueryIndex, scan_tokens, token_may_refer}; +use ara_core::write::history; +use ara_core::write::positions::YamlDocument; +use ara_core::{Manifest, NodeFields, NodeKind, parse_dir_detailed}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; +use std::path::Path; +pub(crate) mod address; +mod boundary; +mod candidates; +mod display; +mod documents; +mod find; +mod headings; +mod hits; +mod references; +mod spans; +mod validity; +mod window; +use boundary::{invalid_document, knowledge_document}; +use documents::{Selected, show_document, show_source}; +pub use find::{FindArgs, find}; +use validity::representable; + +#[derive(Debug, Default, Clone, clap::Args)] +pub struct ReadOptions { + #[arg(long)] + pub json: bool, + #[arg(long)] + pub full: bool, + #[arg(long)] + pub fields: Option, +} +impl ReadOptions { + /// Brief text: no `--json`, and no `--fields`, which keeps the row text. + pub fn brief(&self) -> bool { + !self.json && self.fields.is_none() + } +} +#[derive(Debug, Default, Clone, clap::Args)] +pub struct ListArgs { + /// List one document's entries, or its headings when it has none. + pub path: Option, + #[command(flatten)] + pub output: ReadOptions, + #[arg(long = "type")] + pub kind: Option, + #[arg(long)] + pub under: Option, + #[arg(long)] + pub since: Option, + #[arg(long)] + pub status: Option, + #[arg(long)] + pub provenance: Option, + /// Intersect filters with unfinished-work predicates. + #[arg(long)] + pub unfinished: bool, +} +#[derive(Debug, Default, Clone, clap::Args)] +pub struct ShowArgs { + pub ids: Vec, + /// Resolve one exact qualified identity without loading current content. + #[arg(long, conflicts_with_all = ["document", "heading", "source", "lines", "relations"])] + pub identity: bool, + #[command(flatten)] + pub output: ReadOptions, + #[arg(long = "with", value_delimiter = ',')] + pub relations: Vec, + #[arg(long)] + pub document: Option, + #[arg(long)] + pub heading: Vec, + #[arg(long)] + pub source: bool, + /// One-based inclusive source lines `A:B`, `A:` or `:B` of each selection. + #[arg(long, allow_hyphen_values = true, conflicts_with = "fields")] + pub lines: Option, + /// Response byte budget; brief text defaults to 16 KiB. + #[arg(long, allow_hyphen_values = true, conflicts_with = "fields")] + pub max_bytes: Option, +} + +pub struct Artifact { + pub manifest: Manifest, + pub sources: BTreeMap, + pub root: std::path::PathBuf, + pub report: ara_core::ParseReport, + pub claim_redirects: BTreeMap, + snapshot: std::cell::OnceCell, +} +impl Artifact { + /// A structural read: a fully represented artifact, possibly with + /// dangling-reference errors kept in `report` ([`validity`]). + pub fn load(root: &Path) -> Result { + let loaded = parse_dir_detailed(root); + if !loaded.io_issues.is_empty() { + return Err(AgentError::io(format!( + "Cannot read artifact sources: {:?}", + loaded.io_issues + ))); + } + if let Some(refusal) = + validity::read_refusal(&loaded.report, &loaded.sources, loaded.manifest.as_ref()) + { + return Err(refusal); + } + let manifest = loaded.manifest.ok_or_else(|| { + AgentError::semantic( + "incomplete_artifact", + "The source cannot be represented completely; structural queries refused", + ) + })?; + Ok(Self { + manifest, + sources: loaded.sources, + root: root.to_path_buf(), + report: loaded.report, + claim_redirects: loaded.claim_redirects, + snapshot: std::cell::OnceCell::new(), + }) + } + /// The load's validation report, with original severities. + pub fn diagnostics(&self) -> Value { + diagnostics(&self.report) + } + /// [`Artifact::load`] for a write command: any validation error refuses. + pub fn load_valid(root: &Path) -> Result { + let artifact = Self::load(root)?; + if !artifact.report.is_ok() { + let blocking = artifact.report.errors().iter().map(|d| d.code).collect(); + return Err(validity::refusal( + "invalid_artifact", + &artifact.report, + blocking, + )); + } + Ok(artifact) + } + fn entries(&self) -> Vec> { + let mut result = entries(&self.manifest); + result.extend( + self.sources + .iter() + .filter(|(path, _)| self.is_knowledge(path)) + .map(|(path, content)| Entry::Document { path, content }), + ); + result + } + fn is_knowledge(&self, path: &str) -> bool { + knowledge_document(path) || !ara_core::file_access_path(path) + } + pub fn searchable_documents(&self) -> Vec<(&str, &str)> { + self.sources + .iter() + .filter(|(path, _)| path.ends_with(".md") && self.is_knowledge(path)) + .filter_map(|(path, text)| Some((path.as_str(), self.searchable_text(path, text)?))) + .collect() + } + /// The prefix of a Markdown document that search indexes as the document + /// itself: typed documents index only the text before their entries. + fn searchable_text<'a>(&self, path: &str, text: &'a str) -> Option<&'a str> { + if path != "logic/solution/heuristics.md" + && path + .strip_prefix("logic/solution/") + .and_then(|path| path.strip_suffix(".md")) + .is_some_and(|name| { + self.manifest + .recipes + .iter() + .any(|recipe| recipe.name == name) + }) + { + return None; + } + let typed = matches!( + path, + "logic/claims.md" + | "logic/concepts.md" + | "logic/related_work.md" + | "logic/experiments.md" + | "logic/solution/heuristics.md" + ); + let content = if typed { + let end = ara_core::markdown::document_sections(path, text) + .first() + .map_or(text.len(), |section| section.range.start); + &text[..end] + } else { + text + }; + (!content.trim().is_empty()).then_some(content) + } + fn snapshot(&self) -> Result<&ara_core::write::ArtifactSnapshot, AgentError> { + if self.snapshot.get().is_none() { + let snapshot = ara_core::write::ArtifactSnapshot::load_with_identities(&self.root) + .map_err(crate::write::convert_error)?; + for (path, source) in &self.sources { + if self.is_knowledge(path) + && !snapshot + .files + .get(path) + .is_some_and(|file| file.existed && file.bytes == source.as_bytes()) + { + return Err(AgentError::semantic( + "stale_read_snapshot", + format!("Source `{path}` changed while resolving identities"), + )); + } + } + let _ = self.snapshot.set(snapshot); + } + Ok(self.snapshot.get().expect("initialized")) + } + fn entry(&self, id: &str) -> Result, AgentError> { + self.lookup_entry(id)?.map_err(|miss| self.miss(id, miss)) + } + /// The outer error is a read failure; the inner one is a selection miss + /// whose ranked error is built only if the caller cannot recover. + fn lookup_entry(&self, id: &str) -> Result, candidates::Miss>, AgentError> { + // Without identity records there is nothing to redirect: native + // `path#ID`, `path:ID` and `trace:N01` forms resolve locally, so an + // unrelated document the merge index cannot represent never blocks them. + let resolved = if id.contains('@') + || self.sources.contains_key("trace/logic_mutations.yaml") + || self.sources.contains_key("trace/merge_log.yaml") + || id.contains([':', '#']) && self.has_identity_records() + { + let snapshot = self.snapshot()?; + match ara_core::merge::resolve_local(snapshot, id) { + Ok(resolved) => Some(resolved), + Err(error) => return Ok(Err(candidates::classify(error, snapshot)?)), + } + } else { + id.split_once(':') + .filter(|(document, entry)| { + !entry.is_empty() + && (*document == "trace" + || *document == "PAPER.md" + || document.contains('/') && self.is_knowledge(document)) + }) + .map(|(document, entry)| match document { + "trace" => format!("trace/exploration_tree.yaml#{entry}"), + _ => format!("{document}#{entry}"), + }) + }; + let resolved = resolved.as_deref().unwrap_or(id); + let native = id + .split_once(':') + .or_else(|| id.split_once('#')) + .filter(|(path, _)| self.is_knowledge(path) && path.contains('/')); + let (scope, key) = if let Some((path, key)) = resolved.split_once('#') { + (Some(path), key) + } else { + (native.map(|(path, _)| path), resolved) + }; + let recipe_key = key + .strip_prefix("logic/solution/") + .and_then(|path| path.strip_suffix(".md")); + // As in `entries`, the heuristics file is a document, not a recipe. + let has_recipe = recipe_key.is_some_and(|name| { + name != "heuristics" + && self + .manifest + .recipes + .iter() + .any(|recipe| recipe.name == name) + }); + let mut matching = self.entries().into_iter().filter(|entry|scope.is_none_or(|path|entry.source_matches(path))&&(entry.key()==key||matches!(entry,Entry::Recipe(recipe) if recipe_key==Some(recipe.name.as_str())))&&!(has_recipe&&matches!(entry,Entry::Document{..}))); + Ok(match (matching.next(), matching.next()) { + (Some(entry), None) => Ok(entry), + (Some(_), Some(_)) => Err(candidates::Miss::Ambiguous), + (None, _) => Err(candidates::Miss::Unknown), + }) + } +} +fn diagnostics(report: &ara_core::ParseReport) -> Value { + json!({"errors":report.errors().iter().map(|diagnostic|json!({"code":diagnostic.code,"severity":diagnostic.severity,"path":diagnostic.path,"message":diagnostic.message})).collect::>(),"warnings":report.warnings().iter().map(|diagnostic|json!({"code":diagnostic.code,"severity":diagnostic.severity,"path":diagnostic.path,"message":diagnostic.message})).collect::>()}) +} + +#[derive(Clone, Copy)] +enum Entry<'a> { + Node(&'a ara_core::Node), + Claim(&'a ara_core::Claim), + Observation(&'a ara_core::Observation), + Session(&'a ara_core::Session), + Heuristic(&'a ara_core::Heuristic), + Experiment(&'a ara_core::ExperimentPlan), + Taste(&'a ara_core::TasteComment), + Concept(&'a ara_core::Concept), + RelatedWork(&'a ara_core::RelatedWork), + Recipe(&'a ara_core::Recipe), + Exhibit(&'a ara_core::Exhibit), + Document { path: &'a str, content: &'a str }, +} +fn entries(manifest: &Manifest) -> Vec> { + manifest + .nodes + .iter() + .map(Entry::Node) + .chain(manifest.claims.iter().map(Entry::Claim)) + .chain(manifest.observations.iter().map(Entry::Observation)) + .chain(manifest.sessions.iter().map(Entry::Session)) + .chain(manifest.heuristics.iter().map(Entry::Heuristic)) + .chain(manifest.experiment_plans.iter().map(Entry::Experiment)) + .chain(manifest.taste_comments.iter().map(Entry::Taste)) + .chain(manifest.concepts.iter().map(Entry::Concept)) + .chain(manifest.related_work.iter().map(Entry::RelatedWork)) + .chain( + manifest + .recipes + .iter() + .filter(|recipe| recipe.name != "heuristics") + .map(Entry::Recipe), + ) + .chain(manifest.exhibits.iter().map(Entry::Exhibit)) + .collect() +} +impl<'a> Entry<'a> { + fn key(self) -> &'a str { + match self { + Self::Node(v) => v.id.as_str(), + Self::Claim(v) => v.id.as_str(), + Self::Observation(v) => v.id.as_str(), + Self::Session(v) => v.id.as_str(), + Self::Heuristic(v) => v.id.as_str(), + Self::Experiment(v) => v.id.as_str(), + Self::Taste(v) => v.id.as_str(), + Self::Concept(v) => &v.term, + Self::RelatedWork(v) => &v.id, + Self::Recipe(v) => &v.name, + Self::Exhibit(v) => &v.id, + Self::Document { path, .. } => path, + } + } + fn kind(self) -> &'a str { + match self { + Self::Node(v) => node_kind(&v.kind), + Self::Claim(_) => "claim", + Self::Observation(_) => "observation", + Self::Session(_) => "session", + Self::Heuristic(_) => "heuristic", + Self::Experiment(_) => "experiment_plan", + Self::Taste(_) => "taste", + Self::Concept(_) => "concept", + Self::RelatedWork(_) => "related_work", + Self::Recipe(_) => "solution", + Self::Exhibit(_) => "exhibit", + Self::Document { .. } => "source_document", + } + } + fn date(self) -> Option<&'a str> { + match self { + Self::Node(v) => v.timestamp.as_deref(), + Self::Observation(v) => v.timestamp.as_deref(), + Self::Session(v) => v.date.as_deref(), + Self::Taste(v) => v.timestamp.as_deref(), + _ => None, + } + } + fn status(self) -> Option<&'a str> { + match self { + Self::Node(v) => v.status.as_deref().or({ + if let NodeFields::Experiment { status, .. } = &v.fields { + status.as_deref() + } else { + None + } + }), + Self::Claim(v) => v.status.as_deref(), + Self::Heuristic(v) => v.status.as_deref(), + Self::Experiment(v) => v.status.as_deref(), + _ => None, + } + } + fn provenance(self) -> Option<&'a str> { + match self { + Self::Node(v) => v.provenance.as_deref(), + Self::Claim(v) => v.provenance.as_deref(), + Self::Observation(v) => v.provenance.as_deref(), + Self::Heuristic(v) => v.provenance.as_deref(), + Self::Experiment(v) => v.provenance.as_deref(), + _ => None, + } + } + fn source_matches(self, path: &str) -> bool { + match self { + Self::Node(_) => path == "trace/exploration_tree.yaml", + Self::Claim(_) => path == "logic/claims.md", + Self::Observation(entry) => path == entry.source_file, + Self::Session(entry) => path == entry.source_file, + Self::Heuristic(entry) => path == entry.source_file, + Self::Experiment(entry) => path == entry.source_file, + Self::Taste(entry) => path == entry.source_file, + Self::Concept(_) => path == "logic/concepts.md", + Self::RelatedWork(_) => path == "logic/related_work.md", + Self::Recipe(entry) => { + path.strip_prefix("logic/solution/") + .and_then(|path| path.strip_suffix(".md")) + == Some(entry.name.as_str()) + } + Self::Exhibit(entry) => path == entry.file, + Self::Document { path: source, .. } => path == source, + } + } + fn value(self, full: bool) -> Value { + let mut value = match self { + Self::Node(v) => serde_json::to_value(v), + Self::Claim(v) => serde_json::to_value(v), + Self::Observation(v) => serde_json::to_value(v), + Self::Session(v) => serde_json::to_value(v), + Self::Heuristic(v) => serde_json::to_value(v), + Self::Experiment(v) => serde_json::to_value(v), + Self::Taste(v) => serde_json::to_value(v), + Self::Concept(v) => serde_json::to_value(v), + Self::RelatedWork(v) => serde_json::to_value(v), + Self::Recipe(v) => serde_json::to_value(v), + Self::Exhibit(v) => serde_json::to_value(v), + Self::Document { content, .. } => Ok(json!({"content":content})), + } + .expect("entry serialization is infallible"); + let object = value.as_object_mut().expect("entry object"); + object.insert("kind".into(), json!(self.kind())); + if !object.contains_key("id") { + object.insert("key".into(), json!(self.key())); + } + if let Some(status) = self.status() { + object.insert("status".into(), json!(status)); + } + let source = self.source_path(); + object.insert("source".into(), json!(source)); + if matches!(self, Self::Recipe(_)) { + object.insert("key".into(), json!(source)); + } + if let Self::Node(node) = self { + object.insert("title".into(), json!(node.label)); + } + if !full { + shorten(&mut value); + } + value + } +} +/// Add the brief `address` of `entry` to its row; JSON rows stay unchanged. +fn addressed<'a>( + addresses: &Option>, + entry: Entry<'a>, + mut row: Value, +) -> Value { + if let Some(addresses) = addresses { + row["address"] = json!(addresses.address(entry)); + } + row +} +pub fn node_kind(kind: &NodeKind) -> &str { + match kind { + NodeKind::Question => "question", + NodeKind::Experiment => "experiment", + NodeKind::Decision => "decision", + NodeKind::DeadEnd => "dead_end", + NodeKind::Insight => "insight", + NodeKind::Pivot => "pivot", + NodeKind::Other(name) => name, + } +} +fn shorten(value: &mut Value) { + match value { + Value::Object(object) => { + for (key, value) in object { + if !matches!( + key.as_str(), + "id" | "key" + | "kind" + | "source" + | "source_file" + | "timestamp" + | "date" + | "promoted_to" + | "target" + | "provenance" + | "status" + ) { + shorten(value); + } + } + } + Value::Array(values) => { + for value in values { + shorten(value); + } + } + Value::String(text) => *text = excerpt(text), + _ => {} + } +} +fn validate_kind(artifact: &Artifact, kind: &str) -> Result<(), AgentError> { + if matches!( + kind, + "question" + | "experiment" + | "decision" + | "dead_end" + | "insight" + | "pivot" + | "claim" + | "heuristic" + | "observation" + | "session" + | "exhibit" + | "concept" + | "related_work" + | "solution" + | "experiment_plan" + | "taste" + | "source_document" + ) || artifact + .manifest + .nodes + .iter() + .any(|n| node_kind(&n.kind) == kind) + { + Ok(()) + } else { + Err(AgentError::semantic( + "unknown_type", + format!("Unknown entry type `{kind}`"), + )) + } +} +pub fn list(root: &Path, args: &ListArgs) -> Result { + let artifact = Artifact::load(root)?; + if let Some(kind) = &args.kind { + validate_kind(&artifact, kind)?; + } + if let Some(date) = &args.since { + validate_date(date)?; + } + let index = QueryIndex::new(&artifact.manifest); + let descendants = args + .under + .as_deref() + .map(|id| { + artifact.entry(id).and_then(|entry| { + index + .descendants(entry.key()) + .ok_or_else(|| AgentError::unknown(id)) + }) + }) + .transpose()?; + let document = args + .path + .as_deref() + .map(|path| artifact.list_document(path)) + .transpose()?; + let filtered = args.kind.is_some() + || args.under.is_some() + || args.since.is_some() + || args.status.is_some() + || args.provenance.is_some(); + if args.output.brief() && document.is_none() && !filtered && !args.unfinished { + return Ok(validity::with_coverage( + json!({"format":"ara.ls/v1","documents":artifact.document_summaries(),"file_access":ara_core::FILE_ACCESS_ROOTS,"diagnostics":diagnostics(&artifact.report)}), + &artifact.report, + )); + } + let matches_filters = |entry: &Entry<'_>| { + document.as_ref().is_none_or(|(path, _)| { + (args.unfinished || !matches!(entry, Entry::Document { .. } | Entry::Recipe(_))) + && entry.source_matches(path) + }) && args.kind.as_deref().is_none_or(|kind| entry.kind() == kind) + && descendants + .as_ref() + .is_none_or(|ids| matches!(entry, Entry::Node(_)) && ids.contains(entry.key())) + && args.since.as_deref().is_none_or(|since| { + entry + .date() + .and_then(|date| date.get(..10)) + .is_some_and(|date| date >= since) + }) + && args + .status + .as_deref() + .is_none_or(|status| entry.status() == Some(status)) + && args + .provenance + .as_deref() + .is_none_or(|provenance| entry.provenance() == Some(provenance)) + }; + let mut rows: Vec = if args.unfinished { + unfinished_loaded(&artifact, &args.output, &index)? + .into_iter() + .filter(|(entry, _)| matches_filters(entry)) + .map(|(_, row)| row) + .collect() + } else { + let addresses = args.output.brief().then(|| artifact.entry_addresses()); + artifact + .entries() + .into_iter() + .filter(matches_filters) + .map(|entry| addressed(&addresses, entry, entry.value(args.output.full))) + .collect() + }; + if let Some((path, text)) = document + && rows.is_empty() + && !filtered + && !args.unfinished + && path.ends_with(".md") + { + rows = display::heading_rows(&path, text); + } + Ok(validity::with_coverage( + json!({"format":"ara.ls/v1","entries":rows,"diagnostics":diagnostics(&artifact.report)}), + &artifact.report, + )) +} +pub fn show(root: &Path, args: &ShowArgs) -> Result { + if args.identity { + if args.ids.len() != 1 + || args.document.is_some() + || !args.heading.is_empty() + || args.source + || args.lines.is_some() + || !args.relations.is_empty() + { + return Err(AgentError::setup( + "argument_error", + "--identity requires exactly one address and cannot be combined with content selectors or relations", + )); + } + let bounds = window::Bounds::new(args)?; + let snapshot = ara_core::write::ArtifactSnapshot::load_with_identities(root) + .map_err(crate::write::convert_error)?; + let resolved = ara_core::merge::resolve(&snapshot, &args.ids[0]) + .map_err(crate::merge::convert_error)?; + let mut value = json!({"format":"ara.show/v1","entries":[{"kind":"identity","requested_address":args.ids[0],"resolved_target":resolved}]}); + bounds.apply(&mut value)?; + return Ok(value); + } + let bounds = window::Bounds::new(args)?; + let document = source_document(args); + // File-access roots are rejected by path alone, before any registry or + // artifact load can fail or serve them. + if document + .as_deref() + .is_some_and(ara_core::file_access_location) + { + return Err(invalid_document()); + } + if args.source { + let document = document.ok_or_else(|| { + AgentError::semantic( + "invalid_selector", + "--source requires --document or one document path", + ) + })?; + let positional = args.document.is_none(); + if (!positional && !args.ids.is_empty()) || !args.relations.is_empty() { + return Err(AgentError::semantic( + "invalid_selector", + "Source selection cannot be mixed with entry IDs or relations", + )); + } + let annotate = args.output.brief() || bounded(args); + let mut value = show_source(root, &document, &args.heading, annotate)?; + bounds.apply(&mut value)?; + return Ok(value); + } + let artifact = Artifact::load(root)?; + let mut value = show_loaded(&artifact, args)?; + bounds.apply(&mut value)?; + Ok(value) +} +/// The document a read names: `--document`, or for `--source` a lone +/// positional document path (`show logic/problem.md --source`). +fn source_document(args: &ShowArgs) -> Option { + if let Some(document) = &args.document { + return Some(document.clone()); + } + match (args.source, args.ids.as_slice(), args.relations.is_empty()) { + (true, [id], true) => match address::parse(id) { + Some(Ok(address::Address::Document { path })) => Some(path), + _ => None, + }, + _ => None, + } +} +/// Whether `--lines` or `--max-bytes` bounds this read. +fn bounded(args: &ShowArgs) -> bool { + args.lines.is_some() || args.max_bytes.is_some() +} +/// `show` over a loaded artifact. In brief mode ([`ReadOptions::brief`]), selections print in +/// full and carry brief display data ([`display`]). Explicit bounds also +/// read source selections in full and annotate them, and `--lines` selects +/// an entry's native section as brief mode does. +pub fn show_loaded(artifact: &Artifact, args: &ShowArgs) -> Result { + let brief = args.output.brief(); + let mut value = show_rows(artifact, args, brief)?; + if brief || bounded(args) { + artifact.annotate_rows(&mut value); + } + Ok(value) +} +fn show_rows(artifact: &Artifact, args: &ShowArgs, brief: bool) -> Result { + let full = args.output.full || brief; + let native = brief || args.lines.is_some(); + let source_full = full || bounded(args); + if let Some(document) = &args.document { + if !args.relations.is_empty() { + if !args.heading.is_empty() + || args.source + || !args.ids.is_empty() + || args.relations.iter().any(|relation| relation != "refs") + { + return Err(AgentError::semantic( + "invalid_selector", + "Whole-document selection supports only refs; headings and source selections cannot supply relations", + )); + } + let target = artifact.entry(document)?; + let inventory = references::Inventory::new(artifact, &[target])?; + let mut value = show_document(artifact, document, &[], false, source_full)?; + value["entries"][0]["relations"] = + json!({"refs":refs_loaded(artifact, target, &args.output, &inventory)?}); + return Ok(value); + } + return show_document(artifact, document, &args.heading, args.source, source_full); + } + if args.ids.is_empty() || !args.heading.is_empty() || args.source { + return Err(AgentError::semantic( + "invalid_selector", + "Supply entry IDs or --document; heading/source require a document", + )); + } + for relation in &args.relations { + if !matches!( + relation.as_str(), + "parents" + | "children" + | "claims" + | "sessions" + | "same_as" + | "depends_on" + | "path" + | "refs" + ) { + return Err(AgentError::semantic( + "unknown_relation", + format!("Unknown relation `{relation}`"), + )); + } + } + // With several addresses, a selection miss is reported for that address + // alone and the others still read; one address keeps the plain error. + let mut selected = Vec::with_capacity(args.ids.len()); + let mut failed = Vec::new(); + for (position, id) in args.ids.iter().enumerate() { + match documents::select(artifact, id, source_full) { + Ok(selection) => selected.push(selection), + Err(error) if args.ids.len() > 1 && address_failure(&error) => { + failed.push(json!({"position": position, "address": id, "error": error})); + } + Err(error) => return Err(error), + } + } + let mut targets = Vec::new(); + if !args.relations.is_empty() { + for selection in &selected { + let entry = match selection { + Selected::Entry(entry) => *entry, + Selected::Source(row) => { + if args.relations.iter().any(|relation| relation != "refs") + || row["heading_path"] + .as_array() + .is_some_and(|path| !path.is_empty()) + { + return Err(AgentError::semantic( + "invalid_selector", + "This selection cannot supply the requested relations", + )); + } + artifact.entry(row["document"].as_str().ok_or_else(|| { + AgentError::semantic( + "invalid_selector", + "refs requires an entry or whole document", + ) + })?)? + } + }; + if args.relations.iter().any(|relation| relation == "path") + && !matches!(entry, Entry::Node(_)) + { + return Err(AgentError::semantic( + "invalid_selector", + "path requires node selections", + )); + } + targets.push(entry); + } + } + let inventory = args + .relations + .iter() + .any(|relation| relation == "refs") + .then(|| references::Inventory::new(artifact, &targets)) + .transpose()?; + let index = QueryIndex::new(&artifact.manifest); + let addresses = brief.then(|| artifact.entry_addresses()); + let mut rows = Vec::with_capacity(selected.len()); + let requested: Vec<_> = selected + .iter() + .filter_map(|selected| { + if let Selected::Entry(Entry::Node(node)) = selected { + Some(node.id.as_str()) + } else { + None + } + }) + .collect(); + let raw_nodes = if args.output.full && !requested.is_empty() { + ara_core::source_node_fields( + artifact + .sources + .get("trace/exploration_tree.yaml") + .expect("loaded tree"), + &requested, + ) + .map_err(|message| AgentError::semantic("invalid_artifact", message))? + } else { + BTreeMap::new() + }; + for selected in selected { + let entry = match selected { + Selected::Entry(entry) => entry, + Selected::Source(mut row) => { + if !args.relations.is_empty() { + if args.relations.iter().any(|relation| relation != "refs") + || row["heading_path"] + .as_array() + .is_some_and(|path| !path.is_empty()) + { + return Err(AgentError::semantic( + "invalid_selector", + "This selection cannot supply the requested relations", + )); + } + let target = artifact.entry( + row["key"] + .as_str() + .or(row["source"].as_str()) + .ok_or_else(|| { + AgentError::semantic( + "invalid_selector", + "Reference target must be a whole document", + ) + })?, + )?; + row["relations"] = json!({"refs":refs_loaded(artifact, target, &args.output, inventory.as_ref().expect("refs inventory"))?}); + } + rows.push(row); + continue; + } + }; + let native = if native { + artifact.native_row(entry) + } else { + None + }; + let mut value = match native { + Some(row) => row, + None => addressed(&addresses, entry, entry.value(full)), + }; + if let Entry::Node(node) = entry + && let Some(raw) = raw_nodes.get(node.id.as_str()) + { + value.as_object_mut().unwrap().insert( + "source_fields".into(), + serde_json::to_value(raw).map_err(|error| { + AgentError::semantic("invalid_source_value", error.to_string()) + })?, + ); + } + let mut relations = serde_json::Map::new(); + for relation in args + .relations + .iter() + .collect::>() + { + let data = match relation.as_str() { + "path" => { + if !matches!(entry, Entry::Node(_)) { + return Err(AgentError::semantic( + "invalid_selector", + "path requires a node selection", + )); + } + json!( + index + .path(entry.key()) + .ok_or_else(|| AgentError::unknown(entry.key()))? + .into_iter() + .map(|node| { + let step = Entry::Node(node); + addressed(&addresses, step, step.value(args.output.full)) + }) + .collect::>() + ) + } + "refs" => refs_loaded( + artifact, + entry, + &args.output, + inventory.as_ref().expect("refs inventory"), + )?, + "parents" => json!(index.parent(entry.key()).into_iter().collect::>()), + "children" => json!(index.children(entry.key())), + "depends_on" => json!(index.dependencies(entry.key())), + "claims" => json!( + artifact + .manifest + .bindings + .iter() + .filter(|b| b.node.as_str() == entry.key()) + .map(|b| b.claim.as_str()) + .collect::>() + ), + "sessions" => json!( + artifact + .manifest + .sessions + .iter() + .filter(|s| scan_tokens(&s.body) + .iter() + .any(|t| t.literal == entry.key())) + .map(|s| s.id.as_str()) + .collect::>() + ), + "same_as" => same_as_relation(artifact, entry.key()), + _ => unreachable!(), + }; + relations.insert(relation.clone(), data); + } + if !relations.is_empty() { + value + .as_object_mut() + .unwrap() + .insert("relations".into(), Value::Object(relations)); + } + rows.push(value); + } + let mut value = validity::with_coverage( + json!({"format":"ara.show/v1","entries":rows,"diagnostics":diagnostics(&artifact.report)}), + &artifact.report, + ); + if !failed.is_empty() { + value["errors"] = json!(failed); + } + Ok(value) +} +/// A failure that belongs to one requested address: it does not resolve, +/// is ambiguous, is malformed or lies outside the knowledge boundary. Other +/// failures (I/O, identity records, a changed source) stop the whole read. +fn address_failure(error: &AgentError) -> bool { + matches!( + error.code.as_str(), + "unknown_id" | "ambiguous_heading" | "invalid_address" | "invalid_document" + ) +} +fn same_as_relation(artifact: &Artifact, id: &str) -> Value { + let outgoing = artifact + .manifest + .nodes + .iter() + .find(|node| node.id.as_str() == id) + .map(|node| &node.same_as); + let incoming = artifact + .manifest + .nodes + .iter() + .filter(|node| node.same_as.iter().any(|target| target.as_str() == id)) + .map(|node| node.id.as_str()) + .collect::>(); + json!({"outgoing":outgoing.into_iter().flatten().collect::>(),"incoming":incoming}) +} +/// In brief mode, `display` adds the rule codes behind the +/// diagnostic counts. +pub fn status(root: &Path, brief: bool) -> Result { + let loaded = parse_dir_detailed(root); + if !loaded.io_issues.is_empty() { + return Err(AgentError::io(format!( + "Cannot read artifact: {:?}", + loaded.io_issues + ))); + } + let complete = + loaded.report.is_ok() && loaded.manifest.is_some() && representable(&loaded.report); + // Optional-layer warnings keep `complete` false but leave counts and the + // unaffected next IDs available. + let counted = loaded.report.is_ok() + && loaded.manifest.is_some() + && validity::nodes_representable(&loaded.report); + let unknown_next = validity::incomplete_prefixes(&loaded.report); + let mut counts = BTreeMap::::new(); + let mut native_ids = BTreeMap::>::from([ + ('N', Vec::new()), + ('C', Vec::new()), + ('H', Vec::new()), + ('E', Vec::new()), + ('O', Vec::new()), + ('T', Vec::new()), + ]); + let mut latest: Option<&str> = None; + if let Some(manifest) = &loaded.manifest { + for entry in entries(manifest) { + *counts.entry(entry.kind().into()).or_default() += 1; + let prefix = match entry { + Entry::Node(_) => Some('N'), + Entry::Claim(_) => Some('C'), + Entry::Heuristic(_) => Some('H'), + Entry::Experiment(_) => Some('E'), + Entry::Observation(_) => Some('O'), + Entry::Taste(_) => Some('T'), + _ => None, + }; + if let Some(prefix) = prefix { + native_ids + .get_mut(&prefix) + .expect("native namespace") + .push(entry.key().into()); + } + } + latest = manifest.sessions.iter().map(|s| s.id.as_str()).max(); + } + let historical = counted + && (loaded.sources.contains_key("trace/logic_mutations.yaml") + || loaded.sources.contains_key("trace/merge_log.yaml")); + let working = if historical { + Some(ara_core::write::WorkingArtifact::new( + ara_core::write::ArtifactSnapshot::load(root).map_err(crate::write::convert_error)?, + )) + } else { + None + }; + let mut next_ids = BTreeMap::new(); + let mut next_id_errors = BTreeMap::new(); + if counted { + for (prefix, ids) in native_ids { + let next = if let Some(file) = unknown_next.get(&prefix) { + Err(ara_core::write::WriteError::semantic( + "next_id.incomplete_layer", + format!( + "`{file}` is not fully represented; run `ara check` and fix it before allocating the next {prefix} ID" + ), + )) + } else if let Some(working) = &working { + working.allocate_id(prefix, &ids, None) + } else { + ara_core::write::source::allocate_id(prefix, &ids, None) + }; + match next { + Ok(id) => { + next_ids.insert(prefix.to_string(), Some(id)); + } + Err(error) => { + next_ids.insert(prefix.to_string(), None); + next_id_errors.insert(prefix.to_string(), error); + } + } + } + } + let files = artifact_files(root)?; + let total_bytes = files + .iter() + .try_fold(0u64, |total, file| total.checked_add(file.bytes)) + .ok_or_else(|| AgentError::io("Artifact byte size exceeds u64"))?; + let mut value = json!({"format":"ara.status/v1","artifact_location":root.canonicalize().map_err(|error|AgentError::io(error.to_string()))?,"file_count":files.len(),"total_bytes":total_bytes,"files":files,"complete":complete,"counts":if counted {json!(counts)}else{Value::Null},"next_ids":if counted{json!(next_ids)}else{Value::Null},"next_id_errors":next_id_errors,"latest_session":latest,"diagnostics":{"errors":loaded.report.errors().len(),"warnings":loaded.report.warnings().len(),"report":loaded.report}}); + value = validity::with_coverage(value, &loaded.report); + if brief { + let codes = |diagnostics: &[ara_core::Diagnostic]| { + diagnostics + .iter() + .map(|d| json!(d.code)) + .collect::>() + }; + value["display"] = json!({ + "error_codes": codes(loaded.report.errors()), + "warning_codes": codes(loaded.report.warnings()), + }); + } + Ok(value) +} +#[derive(serde::Serialize)] +struct ArtifactFile { + path: String, + bytes: u64, + kind: &'static str, +} +fn artifact_files(root: &Path) -> Result, AgentError> { + let mut pending = vec![root.to_path_buf()]; + let mut files = Vec::new(); + while let Some(directory) = pending.pop() { + for entry in std::fs::read_dir(&directory) + .map_err(|error| AgentError::io(format!("{}: {error}", directory.display())))? + { + let entry = entry.map_err(|error| AgentError::io(error.to_string()))?; + if matches!(entry.file_name().to_str(), Some(".git" | ".ara")) + || entry + .file_name() + .to_str() + .is_some_and(ara_core::write::source::is_temporary_path) + { + continue; + } + let path = entry.path(); + let kind = entry + .file_type() + .map_err(|error| AgentError::io(format!("{}: {error}", path.display())))?; + if kind.is_dir() { + pending.push(path); + } else if kind.is_file() || kind.is_symlink() { + let relative = path + .strip_prefix(root) + .expect("child of artifact root") + .to_str() + .ok_or_else(|| AgentError::io("Artifact file paths must be UTF-8"))? + .to_owned(); + let bytes = entry + .metadata() + .map_err(|error| AgentError::io(format!("{}: {error}", path.display())))? + .len(); + files.push(ArtifactFile { + path: relative, + bytes, + kind: if kind.is_symlink() { "symlink" } else { "file" }, + }); + } else { + return Err(AgentError::io(format!( + "Unsupported special file: {}", + path.display() + ))); + } + } + } + files.sort_by(|a, b| a.path.cmp(&b.path)); + Ok(files) +} +fn refs_loaded( + artifact: &Artifact, + target: Entry<'_>, + options: &ReadOptions, + inventory: &references::Inventory<'_>, +) -> Result { + let structured = references::structured(artifact, target, inventory)?; + let mut prose = Vec::new(); + for (source, text) in &artifact.sources { + if !artifact.is_knowledge(source) { + continue; + } + for token in inventory + .tokens + .get(source.as_str()) + .into_iter() + .flatten() + .filter(|token| { + (token_may_refer(token.literal, target.key()) + || matches!(target, Entry::Claim(_)) + && artifact + .claim_redirects + .get(token.literal) + .is_some_and(|current| current == target.key())) + && !structured + .ranges + .get(source) + .and_then(|ranges| { + ranges.range(..=(token.range.start, usize::MAX)).next_back() + }) + .is_some_and(|(start, end)| { + *start <= token.range.start && *end >= token.range.end + }) + }) + { + let start = text[..token.range.start] + .char_indices() + .rev() + .nth(40) + .map_or(0, |(i, _)| i); + let end = text[token.range.end..] + .char_indices() + .nth(80) + .map_or(text.len(), |(i, _)| token.range.end + i); + prose.push(json!({"source":source,"field":"source_text","literal":token.literal,"range":token.range,"certainty":"possible","context":excerpt(&text[start..end])})); + } + } + let mut value = json!({"target":target.key(),"structured":structured.rows,"prose":prose}); + if options.brief() { + artifact.annotate_lines(&mut value); + let addresses = artifact.entry_addresses(); + value["display"] = json!({"target": addresses.address(target)}); + for row in value["structured"].as_array_mut().into_iter().flatten() { + if let (Some(owner), Some(source)) = (row["id"].as_str(), row["source"].as_str()) + && let Some(address) = addresses.owner(owner, source) + { + row["address"] = json!(address); + } + } + } + Ok(value) +} +fn unfinished_loaded<'a>( + artifact: &'a Artifact, + options: &ReadOptions, + index: &QueryIndex<'_>, +) -> Result, Value)>, AgentError> { + let mut rows = Vec::new(); + let history = (!artifact.manifest.observations.is_empty()) + .then(|| SessionHistory::new(artifact)) + .transpose()?; + let sources = history.as_ref().map(|history| history.sources(artifact)); + let timeline = history.as_ref().map(|history| { + history::Timeline::build( + sources.as_ref().expect("history sources"), + history.aliases.as_deref(), + history.merge_log.as_deref(), + ) + }); + let addresses = options.brief().then(|| artifact.entry_addresses()); + for entry in artifact.entries() { + let mut reasons = Vec::new(); + let mut inactivity = None; + match entry { + Entry::Node(n) + if n.kind == NodeKind::Question && index.children(n.id.as_str()).is_empty() => + { + reasons.push("childless_question") + } + Entry::Claim(c) if c.status.as_deref() == Some("hypothesis") => { + reasons.push("hypothesis_claim") + } + Entry::Observation(o) => { + if o.promoted != Some(true) { + reasons.push("unpromoted_observation"); + } + let measured = timeline.as_ref().expect("observation timeline").measure( + &history::Subject { + id: o.id.as_str(), + bound_to: o.bound_to.iter().map(|id| id.as_str()).collect(), + timestamp: o.timestamp.as_deref(), + }, + history::Window::default(), + ); + // A stored flag stays visible whatever the current history + // proves; a known day count of three or more is a hint only. + if o.stale == Some(true) + || measured + .session_days_since_reference + .is_some_and(|days| days >= 3) + { + reasons.push("stale_observation"); + } + inactivity = Some(measured); + } + _ => {} + } + let mut value = entry.value(true); + if contains_pending(&value) { + reasons.push("pending_binding"); + } + if !reasons.is_empty() { + if !options.full { + shorten(&mut value); + } + let mut value = addressed(&addresses, entry, value); + let object = value.as_object_mut().unwrap(); + object.insert("reasons".into(), json!(reasons)); + if let Some(measured) = inactivity + && let Value::Object(fields) = measured.to_json() + { + object.extend(fields); + } + rows.push((entry, value)); + } + } + Ok(rows) +} +fn contains_pending(value: &Value) -> bool { + match value { + Value::String(s) => s.contains("[pending]") || s == "pending", + Value::Array(v) => v.iter().any(contains_pending), + Value::Object(o) => o.values().any(contains_pending), + _ => false, + } +} +/// The read side of the shared explicit-reference history +/// (`ara_core::write::history`), built once per `open` and only when the +/// artifact has observations. Session records, the session index and the +/// reasoning log come from the sources this read already loaded; +/// merge aliases and their captured occurrence ledger are read as raw bytes, +/// so undecodable provenance makes inactivity unknown rather than failing +/// the whole read. +struct SessionHistory { + documents: Vec<(String, Result)>, + aliases: Option>, + merge_log: Option>, +} +impl SessionHistory { + fn new(artifact: &Artifact) -> Result { + if artifact.manifest.observations.is_empty() { + return Ok(Self { + documents: Vec::new(), + aliases: None, + merge_log: None, + }); + } + let documents = artifact + .sources + .iter() + .filter(|(path, _)| history::is_history_path(path)) + .map(|(path, text)| { + ( + path.clone(), + YamlDocument::parse(text).map_err(|error| error.message), + ) + }) + .collect(); + let aliases = match std::fs::read(artifact.root.join(history::ALIASES)) { + Ok(text) => Some(text), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => { + return Err(AgentError::io(format!( + "Cannot read {}: {error}", + history::ALIASES + ))); + } + }; + let merge_log = match std::fs::read(artifact.root.join(history::MERGE_LOG)) { + Ok(bytes) => Some(bytes), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => None, + Err(error) => { + return Err(AgentError::io(format!( + "Cannot read {}: {error}", + history::MERGE_LOG + ))); + } + }; + Ok(Self { + documents, + aliases, + merge_log, + }) + } + fn sources<'a>(&'a self, artifact: &'a Artifact) -> Vec> { + self.documents + .iter() + .map(|(path, parsed)| history::Source { + path, + text: artifact.sources[path].as_str(), + root: parsed + .as_ref() + .map(|document| &document.root) + .map_err(Clone::clone), + }) + .collect() + } +} +pub fn validate_date(date: &str) -> Result<(), AgentError> { + let valid = (|| { + let bytes = date.as_bytes(); + if !bytes.is_ascii() || bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' { + return false; + } + let year = date[..4].parse::().ok(); + let month = date[5..7].parse::().ok(); + let day = date[8..].parse::().ok(); + let (Some(year), Some(month), Some(day)) = (year, month, day) else { + return false; + }; + let days = match month { + 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, + 4 | 6 | 9 | 11 => 30, + 2 => { + if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0) { + 29 + } else { + 28 + } + } + _ => 0, + }; + year > 0 && day > 0 && day <= days + })(); + if valid { + Ok(()) + } else { + Err(AgentError::semantic( + "invalid_date", + format!("Invalid calendar date `{date}`; expected YYYY-MM-DD"), + )) + } +} diff --git a/crates/ara-cli/src/agent/address.rs b/crates/ara-cli/src/agent/address.rs new file mode 100644 index 0000000..5ef70c8 --- /dev/null +++ b/crates/ara-cli/src/agent/address.rs @@ -0,0 +1,192 @@ +//! Canonical read addresses: formatting and one-pass decoding. +//! +//! A document is its path; a heading is `path#h//` with the +//! full original heading vector and `;occurrence=N` when that vector repeats. +//! Path components and segments escape every byte outside the URI unreserved +//! set as uppercase `%XX`, so a literal `/` inside one heading is `%2F`. +//! Bare native IDs, `trace:N09` and `logic/claims.md#C04` stay entry selectors. +use crate::output::AgentError; +use std::fmt::Write; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Address { + Document { + path: String, + }, + Heading { + path: String, + heading: Vec, + occurrence: Option, + }, +} + +fn unreserved(byte: u8) -> bool { + byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') +} +fn encode(text: &str) -> String { + let mut encoded = String::with_capacity(text.len()); + for &byte in text.as_bytes() { + if unreserved(byte) { + encoded.push(char::from(byte)); + } else { + write!(encoded, "%{byte:02X}").expect("string write"); + } + } + encoded +} +pub fn document(path: &str) -> String { + path.split('/').map(encode).collect::>().join("/") +} +pub fn heading(path: &str, vector: &[&str], occurrence: Option) -> String { + let mut address = format!("{}#h", document(path)); + for segment in vector { + address.push('/'); + address.push_str(&encode(segment)); + } + if let Some(occurrence) = occurrence { + write!(address, ";occurrence={occurrence}").expect("string write"); + } + address +} + +fn invalid(input: &str, reason: &str) -> AgentError { + AgentError { + id: Some(input.into()), + ..AgentError::semantic("invalid_address", format!("Address `{input}` {reason}")) + } +} +fn decode(text: &str, input: &str) -> Result { + let bytes = text.as_bytes(); + let mut decoded = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + if bytes[index] != b'%' { + decoded.push(bytes[index]); + index += 1; + continue; + } + let byte = bytes + .get(index + 1..index + 3) + .filter(|hex| hex.iter().all(u8::is_ascii_hexdigit)) + .and_then(|hex| u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()) + .ok_or_else(|| invalid(input, "has a malformed percent escape"))?; + decoded.push(byte); + index += 3; + } + String::from_utf8(decoded).map_err(|_| invalid(input, "decodes to invalid UTF-8")) +} +fn occurrence(parameter: &str, input: &str) -> Result { + parameter + .strip_prefix("occurrence=") + .filter(|digits| { + !digits.starts_with('0') + && !digits.is_empty() + && digits.bytes().all(|b| b.is_ascii_digit()) + }) + .and_then(|digits| digits.parse().ok()) + .ok_or_else(|| invalid(input, "accepts only `;occurrence=N` with N >= 1")) +} + +/// Parse a canonical document or heading address. `None` leaves the input to +/// entry and legacy selector resolution. Decoding happens exactly once; the +/// caller applies the normal document boundary checks to the decoded path. +pub fn parse(input: &str) -> Option> { + let Some((path, fragment)) = input.split_once('#') else { + if input.contains([':', '@']) { + return None; + } + // A path by its raw or decoded spelling (`%2Fetc%2Fhosts` is one); + // a name with a stray `%` that is no path stays an entry selector. + let path_like = + |text: &str| text.contains('/') || text.ends_with(".md") || text.ends_with(".yaml"); + return match decode(input, input) { + Ok(path) if path_like(input) || path_like(&path) => { + Some(Ok(Address::Document { path })) + } + Err(error) if path_like(input) => Some(Err(error)), + _ => None, + }; + }; + let rest = fragment.strip_prefix("h/")?; + Some((|| { + let (segments, parameter) = match rest.split_once(';') { + Some((segments, parameter)) => (segments, Some(occurrence(parameter, input)?)), + None => (rest, None), + }; + Ok(Address::Heading { + path: decode(path, input)?, + heading: segments + .split('/') + .map(|segment| decode(segment, input)) + .collect::>()?, + occurrence: parameter, + }) + })()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn heading_addresses_round_trip_reserved_bytes_and_literal_slashes() { + let vector = ["Arch", "A/B", "Résumé; 50% ~ok_-."]; + let address = heading("logic/my notes.md", &vector, Some(2)); + assert_eq!( + address, + "logic/my%20notes.md#h/Arch/A%2FB/R%C3%A9sum%C3%A9%3B%2050%25%20~ok_-.;occurrence=2" + ); + assert_eq!( + parse(&address).unwrap().unwrap(), + Address::Heading { + path: "logic/my notes.md".into(), + heading: vector.iter().map(|s| s.to_string()).collect(), + occurrence: Some(2), + } + ); + assert_ne!( + heading("p.md", &["A/B"], None), + heading("p.md", &["A", "B"], None) + ); + } + + #[test] + fn non_canonical_inputs_stay_entry_selectors() { + for input in [ + "C04", + "trace:N09", + "logic/claims.md#C04", + "doc.md#A/B", + "Term", + "50% rule", + ] { + assert!(parse(input).is_none(), "{input}"); + } + assert_eq!( + parse("%2Fetc%2Fhosts").unwrap().unwrap(), + Address::Document { + path: "/etc/hosts".into() + } + ); + assert_eq!( + parse("PAPER.md").unwrap().unwrap(), + Address::Document { + path: "PAPER.md".into() + } + ); + } + + #[test] + fn malformed_escapes_and_parameters_reject() { + for input in [ + "p.md#h/A%2", + "p.md#h/A%+F", + "p.md#h/%C3", + "p.md#h/A;occurrence=", + "p.md#h/A;occurrence=1;occurrence=2", + "a%G1.md", + ] { + assert_eq!(parse(input).unwrap().unwrap_err().code, "invalid_address"); + } + } +} diff --git a/crates/ara-cli/src/agent/boundary.rs b/crates/ara-cli/src/agent/boundary.rs new file mode 100644 index 0000000..9c81217 --- /dev/null +++ b/crates/ara-cli/src/agent/boundary.rs @@ -0,0 +1,35 @@ +//! Native document boundary for reads and its `invalid_document` error. +use crate::output::AgentError; +use serde_json::json; + +/// Native document reads. `PAPER.md` `knowledge_paths` entries extend them. +const NATIVE_DOCUMENTS: [&str; 4] = [ + "PAPER.md", + "logic/**/*.md", + "trace/**/*.yaml", + "staging/observations.yaml", +]; + +pub fn knowledge_document(path: &str) -> bool { + path == "PAPER.md" + || path.starts_with("logic/") && path.ends_with(".md") + || path.starts_with("trace/") && path.ends_with(".yaml") + || path == "staging/observations.yaml" +} + +/// `invalid_document` with a machine-readable hint: which documents `ara` +/// reads natively and which roots belong to the agent's own file tools. +pub fn invalid_document() -> AgentError { + AgentError { + details: Some(Box::new(json!({ + "hint": "ara reads PAPER.md, logic/, trace/, staging/observations.yaml and paths registered in PAPER.md knowledge_paths. Read rubric/, evidence/ and src/ files directly with your file tools (grep, read).", + "native_documents": NATIVE_DOCUMENTS, + "registered_documents": "PAPER.md knowledge_paths", + "file_access": ara_core::FILE_ACCESS_ROOTS, + }))), + ..AgentError::semantic( + "invalid_document", + "Document outside the knowledge boundary", + ) + } +} diff --git a/crates/ara-cli/src/agent/candidates.rs b/crates/ara-cli/src/agent/candidates.rs new file mode 100644 index 0000000..17caa2a --- /dev/null +++ b/crates/ara-cli/src/agent/candidates.rs @@ -0,0 +1,144 @@ +//! Read-facing selection errors with ranked canonical candidates, and the +//! boundary that keeps merge-layer codes out of read errors. +use crate::output::AgentError; +use ara_core::merge::MergeError; +use ara_core::write::ArtifactSnapshot; +use serde_json::json; + +pub const MAX_CANDIDATES: usize = 40; +/// Characters compared per label; ranking cost stays bounded per candidate. +const RANK_CHARS: usize = 64; + +pub struct Candidates { + addresses: Vec, + capped: bool, +} +impl Candidates { + /// Keep `addresses` in the given order, capped at [`MAX_CANDIDATES`]. + pub fn ordered(addresses: impl IntoIterator) -> Self { + let mut addresses: Vec = addresses.into_iter().collect(); + let capped = addresses.len() > MAX_CANDIDATES; + addresses.truncate(MAX_CANDIDATES); + Self { addresses, capped } + } + /// Rank `(address, label)` pairs by edit distance between the normalized + /// label and `wanted`, then by the given (source) order. + pub fn ranked<'a>(wanted: &str, items: impl IntoIterator) -> Self { + let wanted = normalize(wanted); + let mut seen = std::collections::BTreeSet::new(); + let mut scored: Vec<(usize, usize, String)> = items + .into_iter() + .filter(|(address, _)| seen.insert(address.clone())) + .enumerate() + .map(|(order, (address, label))| (distance(&wanted, &normalize(label)), order, address)) + .collect(); + scored.sort(); + Self::ordered(scored.into_iter().map(|(_, _, address)| address)) + } + fn attach(self, error: AgentError) -> AgentError { + AgentError { + details: Some(Box::new( + json!({"candidates": self.addresses, "capped": self.capped}), + )), + ..error + } + } +} + +/// Locale-independent tolerant form: trimmed, Unicode lowercase, with no +/// accent stripping or Unicode normalization. +pub fn normalize(text: &str) -> String { + text.trim().to_lowercase() +} +fn distance(left: &str, right: &str) -> usize { + let left: Vec = left.chars().take(RANK_CHARS).collect(); + let right: Vec = right.chars().take(RANK_CHARS).collect(); + let mut previous: Vec = (0..=right.len()).collect(); + for (i, a) in left.iter().enumerate() { + let mut current = vec![i + 1]; + for (j, b) in right.iter().enumerate() { + current.push( + (previous[j] + usize::from(a != b)) + .min(previous[j + 1] + 1) + .min(current[j] + 1), + ); + } + previous = current; + } + previous[right.len()] +} + +pub fn unknown(id: &str, candidates: Candidates) -> AgentError { + candidates.attach(AgentError::unknown(id)) +} +pub fn ambiguous(id: &str, candidates: Candidates) -> AgentError { + candidates.attach(AgentError { + id: Some(id.into()), + ..AgentError::semantic( + "ambiguous_heading", + format!("Selector `{id}` matches more than one target; read a candidate address"), + ) + }) +} + +pub enum Miss { + Unknown, + Ambiguous, +} +/// Classify a merge-layer failure raised while resolving a read selector. +/// Only a failed selection becomes a miss, and only once the +/// request-independent identity records index cleanly. Corrupt or +/// unindexable records keep a truthful diagnostic without the internal +/// `merge.*` code. +pub fn classify(error: MergeError, snapshot: &ArtifactSnapshot) -> Result { + let miss = match error.code.as_str() { + "merge.unknown_identity" => Miss::Unknown, + "merge.redirect_ambiguous" | "merge.selector_ambiguous" => Miss::Ambiguous, + _ => return Err(lookup_failed(error)), + }; + ara_core::merge::check_identities(snapshot).map_err(lookup_failed)?; + Ok(miss) +} +fn lookup_failed(error: MergeError) -> AgentError { + AgentError { + exit: error.exit_code(), + details: error + .field + .as_ref() + .map(|path| Box::new(json!({ "path": path }))), + ..AgentError::semantic( + "identity_lookup_failed", + format!("Recorded identities cannot be consulted: {}", error.message), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ranking_is_stable_deduplicated_and_capped() { + let labels: Vec = (0..50).map(|i| format!("Item {i:02}")).collect(); + let ranked = Candidates::ranked( + "item 7", + labels + .iter() + .map(|label| (label.clone(), label.as_str())) + .chain([("Item 07".to_owned(), "Item 07")]), + ); + assert!(ranked.capped); + assert_eq!(ranked.addresses.len(), MAX_CANDIDATES); + assert_eq!(ranked.addresses[..2], ["Item 07", "Item 17"]); + assert_eq!( + ranked.addresses.iter().filter(|a| *a == "Item 07").count(), + 1 + ); + } + + #[test] + fn normalization_is_trim_and_unicode_lowercase_only() { + assert_eq!(normalize(" ÉTAPE Ä "), "étape ä"); + assert_ne!(normalize("Étape"), normalize("Etape")); + } +} diff --git a/crates/ara-cli/src/agent/display.rs b/crates/ara-cli/src/agent/display.rs new file mode 100644 index 0000000..066da3d --- /dev/null +++ b/crates/ara-cli/src/agent/display.rs @@ -0,0 +1,227 @@ +//! Display data computed only for brief text, or for a bounded JSON `show` +//! (`--lines`/`--max-bytes`): the write selector a source digest guards, the +//! native section of a heading-backed entry and per-document summaries. +//! Unbounded JSON reads never carry it. Also the heading rows `ls ` +//! lists in both modes. +use super::address; +use super::headings::{Sections, source_row}; +use super::hits::LineIndex; +use super::{Artifact, Entry}; +use serde_json::{Value, json}; +use std::collections::BTreeMap; + +/// Whether `document.replace` can target `path` +/// ([`ara_core::write::source::replaceable`]); an invalid registry cannot. +pub fn replaceable(path: &str, paper: Option<&str>) -> bool { + ara_core::write::source::replaceable(path, paper).unwrap_or(false) +} + +/// Add `display` to a source row of `text`: `scope`, the `document.replace` +/// `selector` whose digest equals the row's (the whole document, or the +/// section's full heading vector), and `cited`, the short `path#ID` form of a +/// section that heads an entry (`keys` are the document's entry keys). When +/// no write can use the selection, `selector` is null and `no_selector` +/// says why. +pub fn annotate(row: &mut Value, text: &str, keys: Vec<&str>, replaceable: bool) { + let document = row["document"].as_str().unwrap_or("").to_owned(); + let heading: Vec = row["heading_path"] + .as_array() + .into_iter() + .flatten() + .filter_map(|segment| segment.as_str().map(str::to_owned)) + .collect(); + let mut blocked = + (!replaceable).then_some("read-only document; document.replace cannot target it"); + let mut display = if heading.is_empty() { + json!({"scope":"whole_document"}) + } else { + let sections = Sections::new(&document, text).with_entries(keys); + let index = sections.index_of(row["address"].as_str().unwrap_or("")); + let mut display = json!({"scope": "heading_body"}); + if let Some(index) = index { + display["cited"] = json!(sections.cited(index)); + } + if ara_core::markdown::recovered_fence(&document, text) { + blocked = blocked.or(Some( + "an unclosed leading `---` hides this heading from writes (write.frontmatter); a whole-document replace that removes it is accepted", + )); + } + if !index.is_some_and(|index| sections.writable(index)) { + blocked = blocked.or(Some( + "the heading vector repeats; no write selector names one occurrence", + )); + } + display + }; + match blocked { + Some(reason) => { + display["selector"] = Value::Null; + display["no_selector"] = json!(reason); + } + None => display["selector"] = json!({"document": document, "heading": heading}), + } + row.as_object_mut() + .expect("source row object") + .insert("display".into(), display); +} + +/// The addresses reads print for loaded entries. Native namespaces can share +/// a key (claim `C01` and concept `C01`), so a key another entry also has is +/// qualified by its source to the address `show` resolves to that one entry. +pub(super) struct EntryAddresses<'a> { + artifact: &'a Artifact, + shared: BTreeMap<&'a str, usize>, +} +impl<'a> EntryAddresses<'a> { + fn unique(&self, entry: Entry<'a>) -> bool { + self.shared.get(entry.key()).is_none_or(|count| *count <= 1) + } + /// The entry selector `show` resolves to this entry's projection: its + /// key, or `path#key` when another entry shares the key. A document or + /// recipe is selected by its raw path. + pub fn selector(&self, entry: Entry<'a>) -> String { + if matches!(entry, Entry::Document { .. } | Entry::Recipe(_)) { + entry.source_path().into_owned() + } else if self.unique(entry) { + entry.key().to_owned() + } else { + format!("{}#{}", entry.source_path(), entry.key()) + } + } + /// The address brief text prints: a document path for a document or + /// recipe, a key no other entry has, else the section's cited address + /// for a heading-backed entry and `path#key` for any other. + pub fn address(&self, entry: Entry<'a>) -> String { + if matches!(entry, Entry::Document { .. } | Entry::Recipe(_)) { + return address::document(&entry.source_path()); + } + if self.unique(entry) { + return entry.key().to_owned(); + } + match self.artifact.entry_section(entry) { + Some((sections, index)) => sections + .with_entries(self.artifact.entry_keys(&entry.source_path())) + .cited(index), + None => self.selector(entry), + } + } + /// The address of the entry keyed `key` in `source`, when one is loaded. + pub fn owner(&self, key: &str, source: &str) -> Option { + self.artifact + .entries() + .into_iter() + .find(|entry| entry.key() == key && entry.source_matches(source)) + .map(|entry| self.address(entry)) + } +} + +impl Artifact { + /// Entry addresses over this artifact's loaded entries. + pub(super) fn entry_addresses(&self) -> EntryAddresses<'_> { + let mut shared = BTreeMap::new(); + for entry in self.entries() { + *shared.entry(entry.key()).or_default() += 1; + } + EntryAddresses { + artifact: self, + shared, + } + } + /// Annotate every source row of a `show` value. + pub(super) fn annotate_rows(&self, value: &mut Value) { + let paper = self.sources.get("PAPER.md").map(String::as_str); + for row in value["entries"].as_array_mut().into_iter().flatten() { + if row["kind"] == "source_document" + && let Some(document) = row["document"].as_str().map(str::to_owned) + && let Some(text) = self.sources.get(&document) + { + let keys = self.entry_keys(&document); + annotate(row, text, keys, replaceable(&document, paper)); + } + } + } + /// The exact native source of an entry that has one: its section body, + /// or its whole document for a recipe or document entry. + pub(super) fn native_row(&self, entry: Entry<'_>) -> Option { + let mut row = match entry { + Entry::Recipe(_) | Entry::Document { .. } => { + let path = entry.source_path(); + let text = self.sources.get(path.as_ref())?; + source_row(&path, text, true) + } + _ => { + let (sections, index) = self.entry_section(entry)?; + sections.section_row(index, §ions.path(index), true) + } + }; + let object = row.as_object_mut().expect("source row object"); + object.insert( + "entry".into(), + json!({"id": entry.key(), "kind": entry.kind()}), + ); + Some(row) + } + /// Add the one-based source `line` of each `refs` row. + pub(super) fn annotate_lines(&self, value: &mut Value) { + let mut indexes = BTreeMap::new(); + for key in ["structured", "prose"] { + for row in value[key].as_array_mut().into_iter().flatten() { + let (Some(text), Some(start)) = ( + row["source"] + .as_str() + .and_then(|path| self.sources.get(path)), + row["range"]["start"].as_u64(), + ) else { + continue; + }; + let index = indexes + .entry(row["source"].as_str().unwrap_or("").to_owned()) + .or_insert_with(|| LineIndex::new(text)); + row["line"] = json!(index.line(start as usize) + 1); + } + } + } + /// One summary per knowledge document: entry counts by kind, line count, + /// and heading count for Markdown with no typed entries. + pub(super) fn document_summaries(&self) -> Vec { + let entries = super::entries(&self.manifest); + self.sources + .iter() + .filter(|(path, _)| self.is_knowledge(path)) + .map(|(path, text)| { + let mut counts = BTreeMap::<&str, usize>::new(); + for entry in entries.iter().filter(|entry| entry.source_matches(path)) { + *counts.entry(entry.kind()).or_default() += 1; + } + let mut summary = json!({ + "path": path, + "address": address::document(path), + "counts": counts, + "lines": text.lines().count(), + }); + if counts.is_empty() && path.ends_with(".md") { + summary["headings"] = + json!(ara_core::markdown::document_headings(path, text).len()); + } + summary + }) + .collect() + } +} + +/// Heading rows of one Markdown document, for `ls ` without entries. +pub fn heading_rows(document: &str, text: &str) -> Vec { + let sections = Sections::new(document, text); + (0..sections.len()) + .map(|index| { + let path = sections.path(index); + json!({ + "kind": "heading", + "address": sections.address(index), + "heading_path": path, + "title": path.last(), + "source": document, + }) + }) + .collect() +} diff --git a/crates/ara-cli/src/agent/documents.rs b/crates/ara-cli/src/agent/documents.rs new file mode 100644 index 0000000..4361630 --- /dev/null +++ b/crates/ara-cli/src/agent/documents.rs @@ -0,0 +1,495 @@ +//! Source-document reads: whole documents, heading selections, canonical +//! addresses and legacy flattened locators. +use super::address::{self, Address}; +use super::boundary::{invalid_document, knowledge_document}; +use super::candidates::{self, Candidates, Miss}; +use super::headings::{Lookup, Sections, source_row}; +use super::{Artifact, Entry, diagnostics}; +use crate::output::AgentError; +use ara_core::write::EntrySelector; +use serde_json::{Value, json}; +use std::path::Path; + +/// Native identity records that can redirect an archived selector. +const IDENTITY_RECORDS: [&str; 3] = [ + "trace/logic_mutations.yaml", + "trace/merge_log.yaml", + "trace/aliases.yaml", +]; + +pub(super) enum Selected<'a> { + Entry(Entry<'a>), + Source(Value), +} + +fn valid_document_path(document: &str) -> bool { + !document.contains('\\')&&Path::new(document).components().all(|component|matches!(component,std::path::Component::Normal(name) if name!=".git"&&name!=".ara")) +} +fn label(headings: &[String]) -> &str { + headings.last().map_or("", String::as_str) +} + +impl Artifact { + /// The native load reads `trace/aliases.yaml` (and `merge_log.yaml` + /// without a mutation ledger) only through the identity snapshot, so + /// presence is checked on disk; any entry there routes through it. + pub(super) fn has_identity_records(&self) -> bool { + IDENTITY_RECORDS + .iter() + .any(|path| std::fs::symlink_metadata(self.root.join(path)).is_ok()) + } + fn document_text(&self, document: &str) -> Result<&str, AgentError> { + if !valid_document_path(document) + || !self.is_knowledge(document) + || ara_core::file_access_location(document) + { + return Err(invalid_document()); + } + self.sources + .get(document) + .map(String::as_str) + .ok_or_else(|| { + candidates::unknown( + document, + Candidates::ranked( + document, + self.sources + .keys() + .filter(|path| self.is_knowledge(path)) + .map(|path| (address::document(path), path.as_str())), + ), + ) + }) + } + /// The document `ls ` lists: a path, decoded once when it is + /// percent-encoded, inside the knowledge boundary. + pub(super) fn list_document(&self, input: &str) -> Result<(String, &str), AgentError> { + let path = match address::parse(input) { + Some(Err(error)) => return Err(error), + Some(Ok(Address::Document { path })) if self.sources.contains_key(&path) => path, + _ => input.to_owned(), + }; + let text = self.document_text(&path)?; + Ok((path, text)) + } + /// Sections of a knowledge document that know its loaded entries, so + /// candidates cite entry sections by `path#ID`. + pub(super) fn sections<'a>(&'a self, path: &'a str, text: &'a str) -> Sections<'a> { + Sections::new(path, text).with_entries(self.entry_keys(path)) + } + /// Keys of the entries a document holds, whole-document entries excluded. + pub(super) fn entry_keys<'a>(&'a self, path: &str) -> Vec<&'a str> { + self.entries() + .into_iter() + .filter(|entry| { + !matches!(entry, Entry::Document { .. } | Entry::Recipe(_)) + && entry.source_matches(path) + }) + .map(Entry::key) + .collect() + } + fn markdown_sections<'a>(&'a self, path: &'a str) -> Option> { + (path.ends_with(".md") && valid_document_path(path) && self.is_knowledge(path)) + .then(|| self.sources.get(path)) + .flatten() + .map(|text| self.sections(path, text)) + } + /// A read-facing miss for an entry selector, with canonical candidates + /// from loaded knowledge: the named document's headings for `path#...`, + /// entry addresses otherwise. + pub(super) fn miss(&self, id: &str, miss: Miss) -> AgentError { + if let Some((path, display)) = id.split_once('#') + && let Some(sections) = self.markdown_sections(path) + { + let ranked = || sections.ranked(display.rsplit('/').next().unwrap_or(display)); + return match (miss, sections.display(display)) { + (_, Lookup::Ambiguous(found)) => { + candidates::ambiguous(id, sections.matched(&found)) + } + (Miss::Ambiguous, _) => candidates::ambiguous(id, ranked()), + (Miss::Unknown, _) => candidates::unknown(id, ranked()), + }; + } + let addresses = self.entry_addresses(); + let ranked = Candidates::ranked( + id, + self.entries() + .into_iter() + .map(|entry| (addresses.address(entry), entry.key())), + ); + match miss { + Miss::Unknown => candidates::unknown(id, ranked), + Miss::Ambiguous => candidates::ambiguous(id, ranked), + } + } + /// A solution document read as its recipe entry. `heuristics.md` is not + /// one: its H entries replace the recipe ([`super::entries`]), so the + /// file reads as a document. + fn is_recipe_document(&self, path: &str) -> bool { + self.manifest.recipes.iter().any(|recipe| { + recipe.name != "heuristics" && format!("logic/solution/{}.md", recipe.name) == path + }) + } +} + +/// Resolve one positional `show` selector: a canonical address, an entry ID, +/// or a legacy `path#A/B` locator that identifies exactly one section. +pub(super) fn select<'a>( + artifact: &'a Artifact, + id: &str, + full: bool, +) -> Result, AgentError> { + match address::parse(id) { + Some(Err(error)) => return Err(error), + Some(Ok(Address::Heading { + path, + heading, + occurrence, + })) => { + let sections = artifact.sections(&path, artifact.document_text(&path)?); + let lookup = sections.canonical(&heading, occurrence); + // A retired heading vector follows its authenticated mapping. + if matches!(lookup, Lookup::Missing) + && occurrence.is_none() + && artifact.has_identity_records() + && let Some(row) = archived_row(artifact, §ions, &path, &heading, full)? + { + return Ok(Selected::Source(row)); + } + return sections + .row(lookup, id, label(&heading), &heading, full) + .map(Selected::Source); + } + Some(Ok(Address::Document { path })) => { + if !valid_document_path(&path) || ara_core::file_access_location(&path) { + return Err(invalid_document()); + } + // Decoded once; a raw path spelling stays readable when it names + // no decoded document. A valid path naming no document may still + // be an entry key, such as a concept spelled with `/`. A recipe + // document reads as its recipe entry, looked up by the path that + // named it, so an escaped recipe address resolves too. + for path in [path.as_str(), id] { + if !artifact.sources.contains_key(path) { + continue; + } + if !artifact.is_recipe_document(path) { + return document_row(artifact, path, &[], false, full).map(Selected::Source); + } + if let Ok(entry) = artifact.lookup_entry(path)? { + return Ok(Selected::Entry(entry)); + } + } + } + None => {} + } + let miss = match artifact.lookup_entry(id)? { + Ok(entry) => return Ok(Selected::Entry(entry)), + Err(miss) => miss, + }; + // A bare entry ID that names no loaded entry may still head a section + // (`### O3: …` in `logic/problem.md`). + if let Miss::Unknown = miss + && entry_id_shaped(id) + && let Some(selected) = id_heading(artifact, id, full) + { + return selected; + } + // Only a plain miss falls back to a legacy locator; an ambiguity the + // identity records reported is never overridden by a current match. + if let Miss::Unknown = miss + && let Some((path, display)) = id.split_once('#') + && let Some(sections) = artifact.markdown_sections(path) + && let Lookup::Found(index) = sections.display(display) + { + let heading = sections.path(index); + return Ok(Selected::Source( + sections.section_row(index, &heading, full), + )); + } + // A retired `path#A/B` or `path:A/B` locator (a recorded mapping's own + // spelling included) follows its authenticated mapping. + if let Miss::Unknown = miss + && id.contains(['#', ':']) + && artifact.has_identity_records() + { + let snapshot = artifact.snapshot()?; + match ara_core::merge::resolve_locator(snapshot, id) { + Ok(Some(resolved)) => { + if let Some(row) = redirected_row(artifact, resolved, full)? { + return Ok(Selected::Source(row)); + } + } + Ok(None) => {} + Err(error) => { + if let Miss::Ambiguous = candidates::classify(error, snapshot)? { + return Err(artifact.miss(id, Miss::Ambiguous)); + } + } + } + } + Err(artifact.miss(id, miss)) +} + +/// An entry-ID shape: ASCII uppercase letters, then ASCII digits (`E01`, +/// `O3`, `RW2`). +fn entry_id_shaped(id: &str) -> bool { + let digits = id.trim_start_matches(|c: char| c.is_ascii_uppercase()); + digits.len() < id.len() && !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) +} + +/// Whether a heading starts with entry ID `id` and a native separator: `:`, +/// or a spaced `-`, en dash or em dash (`O3: Title`, `E01 — Title`). +fn heads_with_id(heading: &str, id: &str) -> bool { + let Some(rest) = heading.strip_prefix(id) else { + return false; + }; + if rest.starts_with(':') { + return true; + } + let spaced = rest.trim_start(); + spaced.len() < rest.len() + && ['-', '\u{2013}', '\u{2014}'].into_iter().any(|dash| { + spaced + .strip_prefix(dash) + .is_some_and(|tail| tail.is_empty() || tail.starts_with(char::is_whitespace)) + }) +} + +/// The one section of a knowledge Markdown document headed by `id` +/// ([`heads_with_id`]), or `ambiguous_heading` listing every such section in +/// document and source order. `None` when no heading starts with it. +fn id_heading<'a>( + artifact: &'a Artifact, + id: &str, + full: bool, +) -> Option, AgentError>> { + let mut found = Vec::new(); + for path in artifact.sources.keys() { + let Some(sections) = artifact.markdown_sections(path) else { + continue; + }; + for index in 0..sections.len() { + if heads_with_id(sections.heading(index), id) { + found.push(( + sections.cited(index), + sections.section_row(index, §ions.path(index), full), + )); + } + } + } + match found.len() { + 0 => None, + 1 => found.pop().map(|(_, row)| Ok(Selected::Source(row))), + _ => Some(Err(candidates::ambiguous( + id, + Candidates::ordered(found.into_iter().map(|(address, _)| address)), + ))), + } +} + +pub(super) fn show_source( + root: &Path, + document: &str, + headings: &[String], + annotate: bool, +) -> Result { + if !valid_document_path(document) { + return Err(invalid_document()); + } + if !knowledge_document(document) { + let paper_path = ara_core::write::transaction::checked_destination(root, "PAPER.md") + .map_err(crate::write::convert_error)?; + let paper = std::fs::read_to_string(paper_path) + .map_err(|error| AgentError::io(error.to_string()))?; + if !ara_core::knowledge_paths(&paper) + .map_err(|message| AgentError::semantic("invalid_knowledge_registry", message))? + .iter() + .any(|path| path == document) + { + return Err(invalid_document()); + } + } + let path = ara_core::write::transaction::checked_destination(root, document) + .map_err(crate::write::convert_error)?; + let text = std::fs::read_to_string(path).map_err(|error| AgentError::io(error.to_string()))?; + let mut row = if headings.is_empty() { + source_row(document, &text, true) + } else { + let sections = Sections::new(document, &text); + let lookup = match sections.exact(headings) { + Lookup::Missing => sections.tolerant(headings), + lookup => lookup, + }; + sections.row( + lookup, + &headings.join(" / "), + label(headings), + headings, + true, + )? + }; + if annotate { + let paper = ara_core::write::transaction::checked_destination(root, "PAPER.md") + .ok() + .and_then(|path| std::fs::read_to_string(path).ok()); + let replaceable = super::display::replaceable(document, paper.as_deref()); + super::display::annotate(&mut row, &text, Vec::new(), replaceable); + } + Ok(json!({"format":"ara.show/v1","entries":[row],"artifact_validation":"not_run"})) +} + +pub(super) fn show_document( + artifact: &Artifact, + document: &str, + headings: &[String], + source: bool, + full: bool, +) -> Result { + let row = document_row(artifact, document, headings, source, full)?; + Ok(super::validity::with_coverage( + json!({"format":"ara.show/v1","entries":[row],"diagnostics":diagnostics(&artifact.report)}), + &artifact.report, + )) +} + +/// Exact tiers, then an archived identity redirect, then tolerant tiers. +fn document_row( + artifact: &Artifact, + document: &str, + headings: &[String], + source: bool, + full: bool, +) -> Result { + let text = artifact.document_text(document)?; + let full = source || full; + if headings.is_empty() { + return Ok(source_row(document, text, full)); + } + let sections = artifact.sections(document, text); + let id = headings.join(" / "); + match sections.exact(headings) { + Lookup::Missing => {} + lookup => return sections.row(lookup, &id, label(headings), headings, full), + } + if !source + && artifact.has_identity_records() + && let Some(row) = archived_row(artifact, §ions, document, headings, full)? + { + return Ok(row); + } + sections.row( + sections.tolerant(headings), + &id, + label(headings), + headings, + full, + ) +} + +/// Follow a recorded rename or merge redirect for an exact heading vector. +fn archived_row( + artifact: &Artifact, + sections: &Sections<'_>, + document: &str, + headings: &[String], + full: bool, +) -> Result, AgentError> { + let selector = EntrySelector::Document { + document: document.into(), + heading: headings.to_vec(), + entry: None, + }; + let snapshot = artifact.snapshot()?; + let resolved = match ara_core::merge::resolve_selector(snapshot, &selector) { + Ok(resolved) if resolved != selector => resolved, + Ok(_) => return Ok(None), + Err(error) => { + return match candidates::classify(error, snapshot)? { + Miss::Unknown => Ok(None), + Miss::Ambiguous => Err(candidates::ambiguous( + &headings.join(" / "), + sections.ranked(label(headings)), + )), + }; + } + }; + redirected_row(artifact, resolved, full) +} + +/// The current section a resolved redirect names. +fn redirected_row( + artifact: &Artifact, + resolved: EntrySelector, + full: bool, +) -> Result, AgentError> { + let (current, heading) = match resolved { + EntrySelector::Document { + document, + heading, + entry, + } => { + let heading = if heading.is_empty() { + entry.into_iter().collect() + } else { + heading + }; + (document, heading) + } + EntrySelector::Id { id } if id.starts_with('C') => ("logic/claims.md".into(), vec![id]), + EntrySelector::Id { id } if id.starts_with('H') => { + ("logic/solution/heuristics.md".into(), vec![id]) + } + EntrySelector::Id { .. } => return Ok(None), + }; + let redirected = artifact.sections(¤t, artifact.document_text(¤t)?); + let lookup = redirected.exact(&heading); + redirected + .row( + lookup, + &heading.join(" / "), + label(&heading), + &heading, + full, + ) + .map(Some) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn entry_ids_are_uppercase_letters_then_digits() { + for id in ["E01", "O3", "G1", "RW12"] { + assert!(entry_id_shaped(id), "{id}"); + } + for id in ["", "E", "01", "e01", "E01a", "E 01", "E-01", "logic/x.md"] { + assert!(!entry_id_shaped(id), "{id}"); + } + } + + #[test] + fn a_heading_starts_with_an_id_only_before_a_native_separator() { + for heading in [ + "O3: Title", + "O3:", + "O3 — Title", + "O3 – Title", + "O3 - Title", + "O3 —", + ] { + assert!(heads_with_id(heading, "O3"), "{heading}"); + } + for heading in [ + "O31: Title", + "O3 Title", + "O3—Title", + "O3 -x", + "O3", + "XO3: Title", + ] { + assert!(!heads_with_id(heading, "O3"), "{heading}"); + } + } +} diff --git a/crates/ara-cli/src/agent/find.rs b/crates/ara-cli/src/agent/find.rs new file mode 100644 index 0000000..367f597 --- /dev/null +++ b/crates/ara-cli/src/agent/find.rs @@ -0,0 +1,296 @@ +//! `ara find`: BM25 ranking with source-mapped hit lines. +use super::headings::Sections; +use super::hits::{self, LineIndex}; +use super::spans::SpanCache; +use super::{Artifact, Entry, ReadOptions, ShowArgs, show_loaded, window}; +use crate::output::AgentError; +use crate::search::{Filter, SearchHit}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +#[derive(Debug, Clone, clap::Args)] +pub struct FindArgs { + pub query: String, + #[arg(long = "type")] + pub kind: Option, + #[arg(long, default_value_t = 10)] + pub limit: usize, + /// Source lines around each matched line (long form only: `-C` selects + /// the artifact). `0` adds none. + #[arg(long)] + pub context: Option, + /// Matched lines kept per hit; `0` keeps all. Brief text defaults to 3, + /// JSON to 20. + #[arg(long)] + pub lines_per_hit: Option, + /// Response byte budget; brief text defaults to 16 KiB. Whole hits are + /// dropped from the end until the response fits. + #[arg(long, allow_hyphen_values = true, conflicts_with = "fields")] + pub max_bytes: Option, + /// Keep only hits whose source is this knowledge document (repeatable). + #[arg(long)] + pub document: Vec, + /// Keep only hits whose indexed text contains every query term. + #[arg(long)] + pub all: bool, + #[command(flatten)] + pub output: ReadOptions, +} + +/// Matched lines brief text keeps per hit without `--lines-per-hit`. +pub const BRIEF_LINES_PER_HIT: usize = 3; + +impl FindArgs { + /// Matched lines kept per hit; `None` keeps all. + fn cap(&self) -> Option { + match self.lines_per_hit { + Some(0) => None, + Some(lines) => Some(lines), + None if self.output.brief() => Some(BRIEF_LINES_PER_HIT), + None => Some(hits::MAX_MATCHES), + } + } + /// The response budget: explicit, or the brief default. + fn budget(&self) -> Result, AgentError> { + let explicit = self + .max_bytes + .as_deref() + .map(window::parse_max_bytes) + .transpose()?; + Ok(explicit.or(self.output.brief().then_some(window::DEFAULT_MAX_BYTES))) + } +} + +pub fn find(root: &Path, args: &FindArgs) -> Result { + let budget = args.budget()?; + let artifact = Artifact::load(root)?; + let documents = args + .document + .iter() + .map(|document| artifact.list_document(document).map(|(path, _)| path)) + .collect::, AgentError>>()?; + let filter = Filter { + sources: (!documents.is_empty()).then_some(&documents), + all_terms: args.all, + }; + let hits = crate::search::run_search_with_documents( + &artifact.manifest, + artifact.searchable_documents(), + &args.query, + args.kind.as_deref(), + args.limit, + filter, + ) + .map_err(|message| AgentError::semantic("invalid_search", message))?; + let mut results = Results { + artifact: &artifact, + entries: artifact.entries(), + addresses: artifact.entry_addresses(), + cache: SpanCache::default(), + lines: BTreeMap::new(), + args, + }; + let rows = hits + .iter() + .map(|hit| results.row(hit, args.cap())) + .collect::, _>>()?; + let mut value = super::validity::with_coverage( + json!({"format":"ara.find/v1","results":rows,"diagnostics":artifact.diagnostics()}), + &artifact.report, + ); + if let Some(budget) = budget { + fit(&mut value, budget, args.output.brief(), |cap| { + results.row(&hits[0], Some(cap)) + })?; + } + Ok(value) +} + +/// What one result row needs beyond its search hit. +struct Results<'a> { + artifact: &'a Artifact, + entries: Vec>, + addresses: super::display::EntryAddresses<'a>, + cache: SpanCache<'a>, + lines: BTreeMap, + args: &'a FindArgs, +} +impl Results<'_> { + /// The JSON row of one hit, keeping at most `cap` matched lines. + fn row(&mut self, hit: &SearchHit, cap: Option) -> Result { + let (artifact, args) = (self.artifact, self.args); + let mut result = serde_json::to_value(hit).expect("search result serialization"); + let object = result.as_object_mut().expect("search result object"); + let entry = located(&self.entries, hit); + if args.output.brief() + && let Some(entry) = entry + { + object.insert("address".into(), json!(self.addresses.address(entry))); + } + if let Some(span) = entry.and_then(|entry| artifact.search_span(entry, &mut self.cache)) { + let index = self + .lines + .entry(span.path.to_string()) + .or_insert_with(|| LineIndex::new(span.text)); + object.extend(hits::fields(&span, index, &hit.terms, args.context, cap)); + if let Some(Entry::Document { path, content }) = entry { + let sections = artifact.sections(path, content); + containing_sections(object, §ions, index); + } + } else { + object.insert("match_count".into(), json!(0)); + } + let selector = entry + .map(|entry| self.addresses.selector(entry)) + .or_else(|| hit.id.clone().or_else(|| hit.key.clone())); + if args.output.full + && let Some(id) = selector + { + // The embedded entry is the JSON projection, never brief data. + let mut show = show_loaded( + artifact, + &ShowArgs { + ids: vec![id], + output: ReadOptions { + full: true, + json: true, + ..Default::default() + }, + ..Default::default() + }, + )?; + object.insert( + "entry".into(), + show["entries"].as_array_mut().unwrap().remove(0), + ); + } + Ok(result) + } +} + +/// Fit a `find` response to `budget` bytes as it prints. Whole hits are +/// dropped from the end, and a `truncation` object counts them. When even +/// the first hit alone does not fit, `first` rebuilds it with fewer matched +/// lines; when one matched line does not fit, the read fails. +fn fit( + value: &mut Value, + budget: usize, + brief: bool, + mut first: impl FnMut(usize) -> Result, +) -> Result<(), AgentError> { + if window::measure(value, brief) <= budget { + return Ok(()); + } + let mut rows = match value["results"].take() { + Value::Array(rows) => rows, + _ => Vec::new(), + }; + let total = rows.len(); + if total == 0 { + let required = window::measure(value, brief); + let hint = format!( + "The empty result needs {required} bytes; rerun with --max-bytes {required} or more" + ); + return Err(window::too_small(None, budget, required, None, hint)); + } + // Response size with the first `kept` hits. Each added hit prints at + // least its header line, more than the omitted count loses in digits, + // so the size grows with `kept` and bisection finds the largest fit. + let size = |value: &mut Value, rows: &[Value], cut: bool| { + value["results"] = json!(rows); + value["truncation"] = json!({ + "omitted_hits": total - rows.len(), + "truncated_hit": cut, + }); + window::measure(value, brief) + }; + if total > 1 && size(value, &rows[..1], false) <= budget { + let (mut fitting, mut over) = (1, total); + while over - fitting > 1 { + let middle = fitting + (over - fitting) / 2; + if size(value, &rows[..middle], false) <= budget { + fitting = middle; + } else { + over = middle; + } + } + rows.truncate(fitting); + size(value, &rows, false); + return Ok(()); + } + // The first hit alone overflows: keep fewer of its matched lines. + let shown = rows[0]["matches"].as_array().map_or(0, Vec::len); + let mut cut = |value: &mut Value, lines: usize| -> Result { + let row = first(lines)?; + Ok(size(value, std::slice::from_ref(&row), true)) + }; + let required = if shown > 1 { + cut(value, 1)? + } else { + size(value, &rows[..1], false) + }; + if shown <= 1 || required > budget { + value["results"] = json!(rows); + value + .as_object_mut() + .expect("find value") + .remove("truncation"); + let label = rows[0]["address"] + .as_str() + .or_else(|| rows[0]["id"].as_str()) + .or_else(|| rows[0]["key"].as_str()) + .unwrap_or(""); + let hint = format!( + "The first hit and its first matched line need {required} bytes; rerun with --max-bytes {required} or more" + ); + return Err(window::too_small(Some(label), budget, required, None, hint)); + } + let (mut fitting, mut over) = (1, shown); + while over - fitting > 1 { + let middle = fitting + (over - fitting) / 2; + if cut(value, middle)? <= budget { + fitting = middle; + } else { + over = middle; + } + } + cut(value, fitting)?; + Ok(()) +} + +/// Give each matched line of a whole-document hit the address of the +/// innermost section holding it, as `in`; a line before the first heading +/// gets none. +fn containing_sections( + object: &mut serde_json::Map, + sections: &Sections<'_>, + lines: &LineIndex, +) { + for hit in object + .get_mut("matches") + .and_then(Value::as_array_mut) + .into_iter() + .flatten() + { + let Some(line) = hit["line"] + .as_u64() + .and_then(|line| usize::try_from(line).ok()) + else { + continue; + }; + if let Some(section) = sections.innermost(lines.start(line - 1)) { + hit["in"] = json!(sections.cited(section)); + } + } +} + +/// The loaded entry a search result was indexed from. +fn located<'a>(entries: &[Entry<'a>], hit: &SearchHit) -> Option> { + let key = hit.id.as_deref().or(hit.key.as_deref())?; + entries.iter().copied().find(|entry| match entry { + Entry::Document { path, .. } => hit.kind == "source_document" && *path == key, + Entry::Recipe(_) => hit.kind == "solution" && entry.source_path() == key, + _ => entry.kind() == hit.kind && entry.key() == key && entry.source_matches(&hit.source), + }) +} diff --git a/crates/ara-cli/src/agent/headings.rs b/crates/ara-cli/src/agent/headings.rs new file mode 100644 index 0000000..5a133a4 --- /dev/null +++ b/crates/ara-cli/src/agent/headings.rs @@ -0,0 +1,354 @@ +//! Tiered heading lookup over one Markdown source and its section rows. +//! +//! Exact tiers come first: the full vector, then a literal suffix, then the +//! native-ID shorthand suffix. Tolerant tiers compare [`normalize`]d +//! segments: equality, then a prefix, and last a real trailing `...` that +//! stands for a longer request. Every tier rejects multiple matches before a +//! weaker tier runs. +use super::address; +use super::candidates::{self, Candidates, normalize}; +use crate::output::{AgentError, excerpt}; +use ara_core::markdown::MarkdownHeading; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, BTreeSet}; + +pub enum Lookup { + Found(usize), + Missing, + Ambiguous(Vec), +} +type Same<'f> = &'f dyn Fn(&str, &str) -> bool; + +pub struct Sections<'a> { + document: &'a str, + text: &'a str, + items: Vec>, + /// One-based source-order occurrence among identical full vectors, when + /// the vector repeats. + occurrences: Vec>, + /// Keys of the loaded entries this document holds; see [`Sections::cited`]. + entries: BTreeSet<&'a str>, +} +impl<'a> Sections<'a> { + pub fn new(document: &'a str, text: &'a str) -> Self { + let items = ara_core::markdown::document_headings(document, text); + let mut counts = BTreeMap::<&[&str], usize>::new(); + for item in &items { + *counts.entry(&item.path).or_default() += 1; + } + let mut seen = BTreeMap::<&[&str], usize>::new(); + let occurrences = items + .iter() + .map(|item| { + let ordinal = seen.entry(&item.path).or_default(); + *ordinal += 1; + (counts[item.path.as_slice()] > 1).then_some(*ordinal) + }) + .collect(); + Self { + document, + text, + items, + occurrences, + entries: BTreeSet::new(), + } + } + /// Attach the keys of the loaded entries this document holds. + pub fn with_entries(mut self, keys: impl IntoIterator) -> Self { + self.entries = keys.into_iter().collect(); + self + } + /// The key of the loaded entry this section alone heads, when that key + /// needs no escaping (`C04` for `## C04: Title`). + fn cited_key(&self, index: usize) -> Option<&'a str> { + let heading = self.items[index].heading; + [heading_id(heading), Some(heading)] + .into_iter() + .flatten() + .find(|key| { + self.entries.contains(key) + && key + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b)) + }) + .filter(|key| matches!(self.entry(key), Lookup::Found(found) if found == index)) + } + /// The short cited address `path#ID` of a section that heads an entry + /// ([`Sections::cited_key`]), else the canonical address. `show` + /// resolves both to this section's entry. + pub fn cited(&self, index: usize) -> String { + match self.cited_key(index) { + Some(key) => format!("{}#{key}", address::document(self.document)), + None => self.address(index), + } + } + fn select(&self, keep: impl Fn(&MarkdownHeading<'_>) -> bool) -> Lookup { + let found: Vec = (0..self.items.len()) + .filter(|index| keep(&self.items[*index])) + .collect(); + match found.as_slice() { + [] => Lookup::Missing, + [index] => Lookup::Found(*index), + _ => Lookup::Ambiguous(found), + } + } + fn suffix_tiers(&self, wanted: &[String], tiers: &[Same<'_>]) -> Lookup { + for same in tiers { + let lookup = self.select(|section| { + section.path.len() >= wanted.len() + && section.path[section.path.len() - wanted.len()..] + .iter() + .zip(wanted) + .all(|(actual, wanted)| same(actual, wanted)) + }); + if !matches!(lookup, Lookup::Missing) { + return lookup; + } + } + Lookup::Missing + } + pub fn exact(&self, wanted: &[String]) -> Lookup { + let full = self.select(|section| section.path == wanted); + if !matches!(full, Lookup::Missing) { + return full; + } + self.suffix_tiers( + wanted, + &[&|actual, wanted| actual == wanted, &heading_matches], + ) + } + pub fn tolerant(&self, wanted: &[String]) -> Lookup { + let wanted: Vec = wanted.iter().map(|segment| normalize(segment)).collect(); + let equal = |actual: &str, wanted: &str| normalize(actual) == wanted; + let prefix = |actual: &str, wanted: &str| { + let actual = normalize(actual); + actual == wanted || !wanted.is_empty() && actual.starts_with(wanted) + }; + let ellipsis = |actual: &str, wanted: &str| { + prefix(actual, wanted) + || normalize(actual).strip_suffix("...").is_some_and(|stem| { + !stem.trim().is_empty() && wanted.len() > stem.len() && wanted.starts_with(stem) + }) + }; + self.suffix_tiers(&wanted, &[&equal, &prefix, &ellipsis]) + } + /// Canonical heading addresses resolve the exact full vector only. + pub fn canonical(&self, heading: &[String], occurrence: Option) -> Lookup { + let lookup = self.select(|section| section.path == heading); + match (lookup, occurrence) { + (Lookup::Found(index), None | Some(1)) => Lookup::Found(index), + (Lookup::Ambiguous(found), Some(n)) => found + .get(n - 1) + .map_or(Lookup::Missing, |index| Lookup::Found(*index)), + (Lookup::Ambiguous(found), None) => Lookup::Ambiguous(found), + _ => Lookup::Missing, + } + } + /// Legacy flattened `path#A/B` input: every section with a heading + /// suffix whose `/`-joined spelling equals `display`, each segment + /// spelled literally or by its native-ID shorthand. + pub fn display(&self, display: &str) -> Lookup { + self.select(|section| { + (0..section.path.len()).any(|start| spelled(§ion.path[start..], display)) + }) + } + /// The section headed by an entry: its native ID (`C04: Title`) or its + /// exact heading text (a concept term). + pub fn entry(&self, key: &str) -> Lookup { + self.select(|section| section.heading == key || heading_id(section.heading) == Some(key)) + } + /// A section's own heading text. + pub fn heading(&self, index: usize) -> &'a str { + self.items[index].heading + } + /// The innermost section holding byte `offset`: the last in source + /// order whose heading line and body contain it. + pub fn innermost(&self, offset: usize) -> Option { + (0..self.items.len()) + .rev() + .find(|index| self.items[*index].range.contains(&offset)) + } + pub fn len(&self) -> usize { + self.items.len() + } + /// The section a canonical address names in this source. + pub fn index_of(&self, address: &str) -> Option { + (0..self.items.len()).find(|index| self.address(*index) == address) + } + /// The heading line and body of a section. + pub fn range(&self, index: usize) -> std::ops::Range { + self.items[index].range.clone() + } + /// Whether the full vector, used as a write selector's suffix match, + /// names this section alone. + pub fn writable(&self, index: usize) -> bool { + let path = &self.items[index].path; + self.items + .iter() + .filter(|section| section.path.ends_with(path)) + .count() + == 1 + } + pub fn address(&self, index: usize) -> String { + address::heading( + self.document, + &self.items[index].path, + self.occurrences[index], + ) + } + pub fn path(&self, index: usize) -> Vec { + self.items[index] + .path + .iter() + .map(|h| h.to_string()) + .collect() + } + /// Every section, ranked against `label`. + pub fn ranked(&self, label: &str) -> Candidates { + Candidates::ranked( + label, + (0..self.items.len()).map(|index| { + let label = self.cited_key(index).unwrap_or(self.items[index].heading); + (self.cited(index), label) + }), + ) + } + /// The matched sections, in source order. + pub fn matched(&self, found: &[usize]) -> Candidates { + Candidates::ordered(found.iter().map(|index| self.cited(*index))) + } + /// Resolve a lookup to its source row or a read-facing error. + pub fn row( + &self, + lookup: Lookup, + id: &str, + label: &str, + heading: &[String], + full: bool, + ) -> Result { + match lookup { + Lookup::Found(index) => Ok(self.section_row(index, heading, full)), + Lookup::Ambiguous(found) => Err(candidates::ambiguous(id, self.matched(&found))), + Lookup::Missing => Err(candidates::unknown(id, self.ranked(label))), + } + } + /// A selected section. `heading` is the requested (or redirected) vector; + /// `heading_path` and `address` name the section's full source vector. + pub fn section_row(&self, index: usize, heading: &[String], full: bool) -> Value { + let section = &self.items[index]; + let mut row = source_row(self.document, &self.text[section.body_range.clone()], full); + let object = row.as_object_mut().expect("row object"); + object.insert("heading".into(), json!(heading)); + object.insert("heading_path".into(), json!(section.path)); + object.insert("address".into(), json!(self.address(index))); + row + } +} +/// Literal equality or the native-ID shorthand (`C04` names `C04: Title`). +pub fn heading_matches(actual: &str, wanted: &str) -> bool { + actual == wanted || native_shorthand(actual, wanted) +} +/// Whether `display` spells `segments` joined by `/`, trying each segment's +/// literal text and its native-ID shorthand. +fn spelled(segments: &[&str], display: &str) -> bool { + let Some((first, rest)) = segments.split_first() else { + return false; + }; + let shorthand = heading_id(first).filter(|id| native_shorthand(first, id)); + [Some(*first), shorthand] + .into_iter() + .flatten() + .filter_map(|form| display.strip_prefix(form)) + .any(|tail| match tail.strip_prefix('/') { + _ if rest.is_empty() => tail.is_empty(), + Some(tail) => spelled(rest, tail), + None => false, + }) +} +fn native_shorthand(actual: &str, wanted: &str) -> bool { + wanted + .as_bytes() + .first() + .is_some_and(|prefix| matches!(prefix, b'N' | b'C' | b'H' | b'E' | b'O' | b'T')) + && wanted.len() > 1 + && wanted[1..].bytes().all(|byte| byte.is_ascii_digit()) + && heading_id(actual) == Some(wanted) +} +/// A native entry heading's ID (any separator or bracketed status), else the +/// text before `:`. +pub(super) fn heading_id(heading: &str) -> Option<&str> { + ara_core::native_entry_heading(heading) + .map(|entry| entry.id) + .or_else(|| heading.split_once(':').map(|(id, _)| id.trim())) +} +/// A whole-document or selected-range row; the digest covers exactly the +/// selected source bytes. +pub fn source_row(document: &str, content: &str, full: bool) -> Value { + use sha2::{Digest, Sha256}; + let digest = format!("sha256:{:x}", Sha256::digest(content.as_bytes())); + json!({"key":document,"kind":"source_document","document":document,"heading":[],"source":document,"address":address::document(document),"content":if full{content.to_owned()}else{excerpt(content)},"digest":digest}) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn vector(parts: &[&str]) -> Vec { + parts.iter().map(|part| part.to_string()).collect() + } + fn found(lookup: Lookup) -> Option { + match lookup { + Lookup::Found(index) => Some(index), + _ => None, + } + } + + #[test] + fn exact_tiers_reject_duplicates_before_weaker_tiers() { + let sections = Sections::new("d.md", "# A\n## X\n## X\n## x: one\n"); + assert!(matches!( + sections.exact(&vector(&["X"])), + Lookup::Ambiguous(_) + )); + assert_eq!(found(sections.exact(&vector(&["A"]))), Some(0)); + assert_eq!(sections.address(1), "d.md#h/A/X;occurrence=1"); + assert_eq!(sections.address(3), "d.md#h/A/x%3A%20one"); + assert_eq!( + found(sections.canonical(&vector(&["A", "X"]), Some(2))), + Some(2) + ); + assert!(matches!( + sections.canonical(&vector(&["A", "X"]), Some(3)), + Lookup::Missing + )); + assert!(matches!( + sections.canonical(&vector(&["a"]), None), + Lookup::Missing + )); + } + + #[test] + fn shorthand_mixes_with_literal_segments() { + let sections = Sections::new("d.md", "# Top\n## C04: Alpha\n## C04b extra\n"); + assert_eq!(found(sections.exact(&vector(&["Top", "C04"]))), Some(1)); + assert_eq!(found(sections.display("Top/C04")), Some(1)); + assert_eq!(found(sections.display("Top/C04: Alpha")), Some(1)); + assert!(matches!(sections.display("Top/C0"), Lookup::Missing)); + } + + #[test] + fn tolerant_tiers_follow_equality_prefix_then_ellipsis() { + let sections = Sections::new("d.md", "# Top\n## Long run...\n## Long\n## Other\n"); + assert_eq!(found(sections.tolerant(&vector(&[" LONG "]))), Some(2)); + assert_eq!(found(sections.tolerant(&vector(&["long run"]))), Some(1)); + assert_eq!( + found(sections.tolerant(&vector(&["long running jobs"]))), + Some(1) + ); + assert!(matches!( + sections.tolerant(&vector(&["lon"])), + Lookup::Ambiguous(_) + )); + assert!(matches!(sections.tolerant(&vector(&[""])), Lookup::Missing)); + } +} diff --git a/crates/ara-cli/src/agent/hits.rs b/crates/ara-cli/src/agent/hits.rs new file mode 100644 index 0000000..cf51fd3 --- /dev/null +++ b/crates/ara-cli/src/agent/hits.rs @@ -0,0 +1,232 @@ +//! Source-mapped lexical hits: the lines of a search result's native source +//! span that contain one of the result's matched query terms, under the same +//! tokenization search uses, with optional merged context. +use super::spans::Span; +use serde_json::{Value, json}; +use std::collections::BTreeSet; + +/// Matching lines JSON reports per result unless `--lines-per-hit` is +/// given; `match_count` keeps the total. +pub const MAX_MATCHES: usize = 20; + +/// Byte offsets where each line of one document starts. +pub struct LineIndex(Vec); +impl LineIndex { + pub fn new(text: &str) -> Self { + Self( + std::iter::once(0) + .chain(text.match_indices('\n').map(|(offset, _)| offset + 1)) + .filter(|start| *start < text.len() || *start == 0) + .collect(), + ) + } + /// Zero-based line holding `offset`. + pub fn line(&self, offset: usize) -> usize { + self.0.partition_point(|start| *start <= offset) - 1 + } + /// Byte offset where zero-based `line` starts. + pub fn start(&self, line: usize) -> usize { + self.0[line] + } + /// A line's text without its line ending. + fn text<'a>(&self, text: &'a str, line: usize) -> &'a str { + let end = self.0.get(line + 1).copied().unwrap_or(text.len()); + text[self.0[line]..end].trim_end_matches(['\n', '\r']) + } + /// Whether a span holds a line: its last non-whitespace byte (its start, + /// when blank) lies in one of the span's ranges. A parent YAML line that + /// only introduces an excluded child (`- id: N02`) is not held. + fn held(&self, span: &Span<'_>, line: usize) -> bool { + let start = self.0[line]; + let content = self.text(span.text, line).trim_end(); + let probe = start + content.len().saturating_sub(1); + span.ranges.iter().any(|range| range.contains(&probe)) + } +} + +/// The additive `line`, `matches`, `match_count` and (when requested) +/// `context` fields of one search result. A result with no literal hit gets +/// `match_count: 0` and no `line`; its excerpt stays the only display. +/// `cap` keeps the first matched lines (all when `None`); context surrounds +/// only the kept ones. +pub fn fields( + span: &Span<'_>, + lines: &LineIndex, + terms: &[String], + context: Option, + cap: Option, +) -> serde_json::Map { + let terms: BTreeSet<&str> = terms.iter().map(String::as_str).collect(); + let mut matched = BTreeSet::new(); + for range in &span.ranges { + for (term, start, _) in crate::search::tokens(&span.text[range.clone()]) { + if terms.contains(term.as_str()) { + matched.insert(lines.line(range.start + start)); + } + } + } + let mut fields = serde_json::Map::new(); + fields.insert("match_count".into(), json!(matched.len())); + let shown: Vec = matched + .into_iter() + .take(cap.unwrap_or(usize::MAX)) + .collect(); + let Some(first) = shown.first() else { + return fields; + }; + fields.insert("line".into(), json!(first + 1)); + fields.insert( + "matches".into(), + json!( + shown + .iter() + .map(|line| json!({"line": line + 1, "text": lines.text(span.text, *line)})) + .collect::>() + ), + ); + if let Some(extra) = context { + let bounds = span_lines(span, lines); + let held = |line: usize| shown.contains(&line) || lines.held(span, line); + let blocks = clipped(merged(&shown, extra, bounds), held) + .into_iter() + .map(|(start, end)| { + json!({ + "start": start + 1, + "end": end + 1, + "lines": (start..=end).map(|line| lines.text(span.text, line)).collect::>(), + }) + }) + .collect::>(); + fields.insert("context".into(), json!(blocks)); + } + fields +} + +/// First and last zero-based lines of a span; context never leaves it. +fn span_lines(span: &Span<'_>, lines: &LineIndex) -> (usize, usize) { + let start = span.ranges.first().map_or(0, |range| range.start); + let end = span.ranges.last().map_or(0, |range| range.end); + ( + lines.line(start), + lines.line(end.saturating_sub(1).max(start)), + ) +} + +/// Inclusive line ranges around sorted `lines`, merged where they overlap or +/// touch, clipped to `bounds`. +fn merged(lines: &[usize], extra: usize, bounds: (usize, usize)) -> Vec<(usize, usize)> { + let mut blocks: Vec<(usize, usize)> = Vec::new(); + for &line in lines { + let start = line.saturating_sub(extra).max(bounds.0); + let end = line.saturating_add(extra).min(bounds.1).max(line); + match blocks.last_mut() { + Some(last) if start <= last.1 + 1 => last.1 = last.1.max(end), + _ => blocks.push((start, end)), + } + } + blocks +} + +/// Split blocks around lines `keep` rejects, dropping those lines. +fn clipped(blocks: Vec<(usize, usize)>, keep: impl Fn(usize) -> bool) -> Vec<(usize, usize)> { + let mut result = Vec::new(); + for (start, end) in blocks { + let mut open = None; + for line in start..=end { + match (keep(line), open) { + (true, None) => open = Some(line), + (false, Some(first)) => { + result.push((first, line - 1)); + open = None; + } + _ => {} + } + } + if let Some(first) = open { + result.push((first, end)); + } + } + result +} + +#[cfg(test)] +mod tests { + use super::*; + use std::borrow::Cow; + + fn span(text: &str) -> Span<'_> { + Span { + path: Cow::Borrowed("d.md"), + text, + ranges: super::super::spans::whole(text.len()), + } + } + + #[test] + fn lines_are_one_based_and_case_insensitive() { + let text = "alpha\r\nBeta gamma\nnone\nbeta\n"; + let fields = fields( + &span(text), + &LineIndex::new(text), + &["beta".into()], + None, + None, + ); + assert_eq!(fields["line"], 2); + assert_eq!( + fields["matches"], + json!([{"line":2,"text":"Beta gamma"},{"line":4,"text":"beta"}]) + ); + assert!(!fields.contains_key("context")); + } + + #[test] + fn context_merges_overlaps_and_zero_adds_nothing() { + assert_eq!(merged(&[2, 4, 9], 1, (0, 20)), [(1, 5), (8, 10)]); + assert_eq!(merged(&[2, 4], 0, (0, 20)), [(2, 2), (4, 4)]); + assert_eq!(merged(&[2, 3], 0, (0, 20)), [(2, 3)]); + assert_eq!(merged(&[0, 9], 3, (0, 10)), [(0, 3), (6, 10)]); + } + + #[test] + fn context_skips_lines_of_excluded_nested_entries() { + let text = "tree:\n - id: N01\n title: alpha\n children:\n - id: N02\n title: beta\n after: alpha\n"; + let child = text.find("id: N02").unwrap(); + let child_end = text.find("beta").unwrap() + 4; + let start = text.find("id: N01").unwrap(); + let span = Span { + path: Cow::Borrowed("t.yaml"), + text, + ranges: vec![start..child, child_end..text.len() - 1], + }; + let fields = fields( + &span, + &LineIndex::new(text), + &["alpha".into()], + Some(5), + None, + ); + let shown: Vec = fields["context"] + .as_array() + .unwrap() + .iter() + .flat_map(|block| block["start"].as_u64().unwrap()..=block["end"].as_u64().unwrap()) + .collect(); + assert_eq!(shown, [2, 3, 4, 7]); + assert_eq!(fields["context"].as_array().unwrap().len(), 2); + } + + #[test] + fn no_literal_hit_reports_no_line() { + let text = "nothing here\n"; + let fields = fields( + &span(text), + &LineIndex::new(text), + &["absent".into()], + Some(2), + None, + ); + assert_eq!(fields["match_count"], 0); + assert!(!fields.contains_key("line") && !fields.contains_key("matches")); + } +} diff --git a/crates/ara-cli/src/agent/references.rs b/crates/ara-cli/src/agent/references.rs new file mode 100644 index 0000000..363a340 --- /dev/null +++ b/crates/ara-cli/src/agent/references.rs @@ -0,0 +1,454 @@ +use super::{Artifact, Entry}; +use crate::output::AgentError; +use ara_core::write::citation_rules::{self, HistoryRole}; +use ara_core::write::positions::{YamlDocument, YamlKind, YamlNode}; +use ara_core::write::{EntrySelector, WorkingArtifact}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::Range; + +/// Parsed sources and the writer snapshot shared by all refs targets of one show. +pub(super) struct Inventory<'a> { + yaml: BTreeMap, + markdown: Vec<( + Entry<'a>, + Option>, + )>, + pub(super) tokens: BTreeMap<&'a str, Vec>>, +} +impl<'a> Inventory<'a> { + pub(super) fn new(artifact: &'a Artifact, targets: &[Entry<'a>]) -> Result { + let needs_writer = targets + .iter() + .any(|target| logic_selector(*target).is_some()) + || artifact.root.join("trace/aliases.yaml").is_file(); + let working = needs_writer + .then(|| { + artifact + .snapshot() + .map(|snapshot| WorkingArtifact::new(snapshot.clone())) + }) + .transpose()?; + let mut yaml = BTreeMap::new(); + for (source, text) in &artifact.sources { + if artifact.is_knowledge(source) + && citation_rules::is_history_source(source) + && (source.ends_with(".yaml") || source.ends_with(".yml")) + { + yaml.insert( + source.clone(), + YamlDocument::parse(text).map_err(crate::write::convert_error)?, + ); + } + } + if !yaml.contains_key("trace/aliases.yaml") + && let Some(working) = &working + && let Some(file) = working + .base + .files + .get("trace/aliases.yaml") + .filter(|file| file.existed) + && let Ok(text) = std::str::from_utf8(&file.bytes) + { + yaml.insert( + "trace/aliases.yaml".into(), + YamlDocument::parse(text).map_err(crate::write::convert_error)?, + ); + } + let mut selected = Vec::new(); + let mut selectors = Vec::new(); + for target in targets { + if let Some(selector) = logic_selector(*target) { + selected.push(*target); + selectors.push(selector); + } + } + let markdown = if selectors.is_empty() { + Vec::new() + } else { + let working = working.as_ref().expect("logic target snapshot"); + // Per-selector failures preserve the read-only fallback for recovered + // headings; a shared classification failure falls back for all targets. + match ara_core::write::logic::markdown_citations_many(working, &selectors) { + Ok(results) => selected + .into_iter() + .zip(results.into_iter().map(Result::ok)) + .collect(), + Err(_) => selected.into_iter().map(|entry| (entry, None)).collect(), + } + }; + let tokens = artifact + .sources + .iter() + .filter(|(source, _)| artifact.is_knowledge(source)) + .map(|(source, text)| (source.as_str(), ara_core::query::scan_tokens(text))) + .collect(); + Ok(Self { + yaml, + markdown, + tokens, + }) + } +} +pub struct References { + pub rows: Vec, + pub ranges: BTreeMap>, +} +impl References { + fn add( + &mut self, + source: &str, + owner: Option<&str>, + field: &str, + literal: &str, + range: Range, + ) { + let ranges = self.ranges.entry(source.into()).or_default(); + if !ranges.insert((range.start, range.end)) { + return; + } + self.rows.push(json!({"id":owner,"source":source,"field":field,"literal":literal,"range":range,"certainty":"certain"})); + } +} +fn get<'a>(node: &'a YamlNode, name: &str) -> Option<&'a YamlNode> { + match &node.kind { + YamlKind::Mapping(values) => values + .iter() + .find(|(key, _)| key.scalar() == Some(name)) + .map(|(_, value)| value), + _ => None, + } +} +fn rows(node: &YamlNode) -> impl DoubleEndedIterator { + let values = match &node.kind { + YamlKind::Sequence(values) => values.as_slice(), + _ => std::slice::from_ref(node), + }; + values.iter() +} +#[derive(Clone, Copy)] +struct Target<'a> { + entry: Entry<'a>, + artifact: &'a Artifact, + bare_unique: bool, +} +impl<'a> Target<'a> { + fn key(self) -> &'a str { + self.entry.key() + } + fn source_matches(self, path: &str) -> bool { + self.entry.source_matches(path) + } + fn key_matches(self, literal: &str) -> bool { + let current = if matches!(self.entry, Entry::Claim(_)) { + self.artifact + .claim_redirects + .get(literal) + .map_or(literal, String::as_str) + } else { + literal + }; + current == self.key() + } +} +fn matches(target: Target<'_>, literal: &str) -> bool { + if let Some((scope, key)) = literal.split_once(':').or_else(|| literal.split_once('#')) { + if matches!(target.entry,Entry::Document{path,..}if path==scope) { + return true; + } + if (target.source_matches(scope) + || scope == "trace" && matches!(target.entry, Entry::Node(_))) + && target.key_matches(key) + { + return true; + } + if matches!(target.entry, Entry::Session(_)) + && scope == target.key() + && key.bytes().all(|byte| byte.is_ascii_digit()) + && !key.is_empty() + { + return true; + } + return false; + } + target.bare_unique && target.key_matches(literal) +} +fn values( + result: &mut References, + source: &str, + owner: Option<&str>, + field: &str, + node: &YamlNode, + target: Target<'_>, +) { + let mut pending = vec![node]; + while let Some(node) = pending.pop() { + match &node.kind { + YamlKind::Scalar { value, .. } => { + if matches(target, value) { + result.add(source, owner, field, value, node.start..node.end); + } + } + YamlKind::Sequence(items) => pending.extend(items.iter().rev()), + YamlKind::Mapping(_) => { + // Revision selectors are structured native addresses, not arbitrary + // mappings whose unknown contents happen to look like identifiers. + if let Some(id) = get(node, "id") { + pending.push(id); + } else if let (Some(document), Some(heading)) = ( + get(node, "document").and_then(YamlNode::scalar), + get(node, "heading"), + ) { + let names: Vec<_> = rows(heading).filter_map(YamlNode::scalar).collect(); + if target.source_matches(document) + && names.last().is_some_and(|name| { + super::headings::heading_matches(name, target.key()) + || name + .split_once(':') + .is_some_and(|(id, _)| target.key_matches(id.trim())) + }) + { + result.add( + source, + owner, + field, + &format!("{document}#{}", names.join(" / ")), + node.start..node.end, + ); + } + if let Some(entry) = get(node, "entry") { + values(result, source, owner, field, entry, target); + } + } + } + YamlKind::Alias(_) => {} + } + } +} +fn yaml( + result: &mut References, + source: &str, + parsed: &YamlDocument, + target: Target<'_>, +) -> Result<(), AgentError> { + let concepts = concept_paths(target); + citation_rules::walk_history(source, &parsed.root, &mut |value| { + if value.role == HistoryRole::ConceptName { + if let Entry::Concept(concept) = target.entry { + concept_values(result, source, value, &concept.term, concepts.as_deref()); + } + return; + } + values(result, source, value.owner, value.field, value.node, target); + }); + Ok(()) +} +/// Concept headings of the current `logic/concepts.md` as (leaf, path). +fn concept_paths(target: Target<'_>) -> Option)>> { + let text = target.artifact.sources.get("logic/concepts.md")?; + Some( + ara_core::markdown::headings(text) + .into_iter() + .map(|h| { + ( + h.heading.to_owned(), + h.path.iter().map(|part| (*part).to_owned()).collect(), + ) + }) + .collect(), + ) +} +/// A bare tree concept name cites a concept only when it resolves to exactly +/// one concept heading, by the writer's rule ([`citation_rules::concept_name_targets`]). +fn concept_values( + result: &mut References, + source: &str, + value: citation_rules::HistoryValue<'_>, + term: &str, + paths: Option<&[(String, Vec)]>, +) { + let Some(paths) = paths else { + return; + }; + let shaped: Vec<(&str, &[String])> = paths + .iter() + .map(|(leaf, path)| (leaf.as_str(), path.as_slice())) + .collect(); + let mut pending = vec![value.node]; + while let Some(node) = pending.pop() { + match &node.kind { + YamlKind::Scalar { value: literal, .. } => { + let found = citation_rules::concept_name_targets(&shaped, literal); + if let [index] = found.as_slice() + && shaped[*index].0 == term + { + result.add( + source, + value.owner, + value.field, + literal, + node.start..node.end, + ); + } + } + YamlKind::Sequence(items) => pending.extend(items.iter().rev()), + _ => {} + } + } +} +/// The writer selector of a native logic entry, when it has one. +fn logic_selector(entry: Entry<'_>) -> Option { + let document = |document: &str, id: &str| EntrySelector::Document { + document: document.into(), + heading: Vec::new(), + entry: Some(id.into()), + }; + match entry { + Entry::Claim(claim) => Some(EntrySelector::Id { + id: claim.id.as_str().into(), + }), + Entry::Heuristic(heuristic) => { + Some(document(&heuristic.source_file, heuristic.id.as_str())) + } + Entry::Experiment(experiment) => { + Some(document(&experiment.source_file, experiment.id.as_str())) + } + Entry::Concept(concept) => Some(EntrySelector::Document { + document: "logic/concepts.md".into(), + heading: vec![concept.term.clone()], + entry: None, + }), + _ => None, + } +} +pub(super) fn structured( + artifact: &Artifact, + target: Entry<'_>, + inventory: &Inventory<'_>, +) -> Result { + let mut result = References { + rows: Vec::new(), + ranges: BTreeMap::new(), + }; + let target = Target { + entry: target, + artifact, + bare_unique: artifact + .entries() + .iter() + .filter(|entry| entry.key() == target.key()) + .count() + == 1, + }; + // Native logic entries share the writer's typed citation inventory, the + // same classifier C1 repairs with. + let shared = inventory + .markdown + .iter() + .find(|(entry, _)| { + entry.key() == target.key() + && entry.kind() == target.entry.kind() + && entry.source_matches(target.entry.source_path().as_ref()) + }) + .and_then(|(_, citations)| citations.as_ref()); + if let Some(citations) = shared { + for citation in citations { + result.add( + &citation.document, + Some(&citation.owner), + &citation.field, + &citation.literal, + citation.range.clone(), + ); + } + } + // History layers the read model does not load (the portable alias + // ledger) still carry citations; walk them from the exact snapshot. + if !artifact.sources.contains_key("trace/aliases.yaml") + && let Some(parsed) = inventory.yaml.get("trace/aliases.yaml") + { + yaml(&mut result, "trace/aliases.yaml", parsed, target)?; + } + for (source, text) in &artifact.sources { + if !artifact.is_knowledge(source) { + continue; + } + if source.ends_with(".yaml") || source.ends_with(".yml") { + if citation_rules::is_history_source(source) { + yaml( + &mut result, + source, + inventory.yaml.get(source).expect("parsed history"), + target, + )?; + } + continue; + } + if !source.ends_with(".md") || shared.is_some() { + continue; + } + for section in ara_core::markdown::document_sections(source, text) { + let owner = super::headings::heading_id(section.heading); + for field in ara_core::markdown::fields(text, section.body_range) { + if citation_rules::reference_field(field.name).is_none() { + continue; + } + // Quoted, backticked and commented tokens are not references. + let protected = citation_rules::protected_ranges(field.value); + if matches(target, field.value) { + result.add( + source, + owner, + field.name, + field.value, + field.value_range.clone(), + ); + continue; + } + for token in ara_core::query::scan_tokens(field.value) { + if matches(target, token.literal) + && !citation_rules::is_protected(&protected, &token.range) + { + result.add( + source, + owner, + field.name, + token.literal, + field.value_range.start + token.range.start + ..field.value_range.start + token.range.end, + ); + } + } + // Scoped locators are deliberately excluded by the bare-ID prose + // scanner. A qualified spelling is certain only in a declared field. + let mut offset = 0; + for part in field.value.split_inclusive(|character: char| { + character.is_whitespace() + || matches!(character, ',' | '[' | ']' | '(' | ')' | '`' | '\"' | '\'') + }) { + let literal = part.trim_matches(|character: char| { + character.is_whitespace() + || matches!(character, ',' | '[' | ']' | '(' | ')' | '`' | '\"' | '\'') + }); + let start = part.find(literal).unwrap_or(0); + let range = offset + start..offset + start + literal.len(); + if !literal.is_empty() + && matches(target, literal) + && !citation_rules::is_protected(&protected, &range) + { + result.add( + source, + owner, + field.name, + literal, + field.value_range.start + offset + start + ..field.value_range.start + offset + start + literal.len(), + ); + } + offset += part.len(); + } + } + } + } + Ok(result) +} diff --git a/crates/ara-cli/src/agent/spans.rs b/crates/ara-cli/src/agent/spans.rs new file mode 100644 index 0000000..6845556 --- /dev/null +++ b/crates/ara-cli/src/agent/spans.rs @@ -0,0 +1,183 @@ +//! Native source spans of loaded entries: the Markdown section that holds a +//! heading-backed entry, a whole document, or the YAML mapping of an entry +//! with its nested entries excluded. +use super::headings::{Lookup, Sections}; +use super::{Artifact, Entry}; +use ara_core::write::positions::{YamlDocument, YamlKind, YamlNode}; +use std::borrow::Cow; +use std::collections::BTreeMap; +use std::ops::Range; + +/// Byte ranges of one native document that hold an entry's source. +pub struct Span<'a> { + pub path: Cow<'a, str>, + pub text: &'a str, + pub ranges: Vec>, +} + +/// One range covering `0..len`. +pub fn whole(len: usize) -> Vec> { + std::iter::once(0..len).collect() +} + +impl<'a> Entry<'a> { + /// The native document an entry is read from. + pub(super) fn source_path(self) -> Cow<'a, str> { + match self { + Self::Node(_) => "trace/exploration_tree.yaml".into(), + Self::Claim(_) => "logic/claims.md".into(), + Self::Observation(v) => v.source_file.as_str().into(), + Self::Session(v) => v.source_file.as_str().into(), + Self::Heuristic(v) => v.source_file.as_str().into(), + Self::Experiment(v) => v.source_file.as_str().into(), + Self::Taste(v) => v.source_file.as_str().into(), + Self::Concept(_) => "logic/concepts.md".into(), + Self::RelatedWork(_) => "logic/related_work.md".into(), + Self::Recipe(v) => format!("logic/solution/{}.md", v.name).into(), + Self::Exhibit(v) => v.file.as_str().into(), + Self::Document { path, .. } => path.into(), + } + } +} + +impl Artifact { + /// The one Markdown section headed by a typed entry, if exactly one is. + /// The native Markdown document that holds a heading-backed entry. + fn entry_document<'a>(&'a self, entry: Entry<'a>) -> Option<(&'a str, &'a str)> { + if matches!(entry, Entry::Document { .. } | Entry::Recipe(_)) { + return None; + } + let (path, text) = match entry.source_path() { + Cow::Borrowed(path) => self.sources.get_key_value(path)?, + Cow::Owned(path) => self.sources.get_key_value(&path)?, + }; + (path.ends_with(".md") && self.is_knowledge(path)).then_some((path.as_str(), text.as_str())) + } + /// The one Markdown section headed by a typed entry, if exactly one is. + pub(super) fn entry_section<'a>(&'a self, entry: Entry<'a>) -> Option<(Sections<'a>, usize)> { + let (path, text) = self.entry_document(entry)?; + let sections = Sections::new(path, text); + match sections.entry(entry.key()) { + Lookup::Found(index) => Some((sections, index)), + _ => None, + } + } + /// The source a search result was indexed from, when it can be located. + /// `cache` keeps parsed documents for one command. + pub(super) fn search_span<'a>( + &'a self, + entry: Entry<'a>, + cache: &mut SpanCache<'a>, + ) -> Option> { + let path = entry.source_path(); + let text = self.sources.get(path.as_ref())?.as_str(); + if !self.is_knowledge(&path) { + return None; + } + let ranges = match entry { + Entry::Document { path, content } => whole(self.searchable_text(path, content)?.len()), + Entry::Recipe(_) | Entry::Session(_) => whole(text.len()), + Entry::Node(_) | Entry::Observation(_) | Entry::Taste(_) => { + let document = cache + .yaml + .entry(path.to_string()) + .or_insert_with(|| YamlDocument::parse(text).ok()) + .as_ref()?; + yaml_ranges(&document.root, entry.key())? + } + _ => { + let (document, text) = self.entry_document(entry)?; + let sections = cache + .sections + .entry(document) + .or_insert_with(|| Sections::new(document, text)); + match sections.entry(entry.key()) { + Lookup::Found(index) => vec![sections.range(index)], + _ => return None, + } + } + }; + Some(Span { path, text, ranges }) + } +} + +/// Parsed sources reused across the results of one `find`. +#[derive(Default)] +pub struct SpanCache<'a> { + yaml: BTreeMap>, + sections: BTreeMap<&'a str, Sections<'a>>, +} + +fn identity(node: &YamlNode) -> Option<&str> { + let YamlKind::Mapping(entries) = &node.kind else { + return None; + }; + entries + .iter() + .find(|(key, _)| key.scalar() == Some("id")) + .and_then(|(_, value)| value.scalar()) + .map(str::trim) +} +fn children(node: &YamlNode) -> Box + '_> { + match &node.kind { + YamlKind::Mapping(entries) => Box::new(entries.iter().map(|(_, value)| value)), + YamlKind::Sequence(items) => Box::new(items.iter()), + _ => Box::new(std::iter::empty()), + } +} +/// The one mapping whose `id` is `key`, minus nested mappings with their own +/// `id` (child nodes), as ascending byte ranges. +fn yaml_ranges(root: &YamlNode, key: &str) -> Option>> { + let mut found = Vec::new(); + let mut pending = vec![root]; + while let Some(node) = pending.pop() { + if identity(node) == Some(key) { + found.push(node); + } + pending.extend(children(node)); + } + let [node] = found.as_slice() else { + return None; + }; + let mut nested = Vec::new(); + let mut pending: Vec<&YamlNode> = children(node).collect(); + while let Some(child) = pending.pop() { + if identity(child).is_some() { + nested.push(child.start..child.end); + } else { + pending.extend(children(child)); + } + } + nested.sort_by_key(|range| range.start); + let mut ranges = Vec::new(); + let mut start = node.start; + for range in nested { + if range.start > start { + ranges.push(start..range.start); + } + start = start.max(range.end); + } + if start < node.end { + ranges.push(start..node.end); + } + Some(ranges) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn yaml_ranges_exclude_nested_entries() { + let text = "tree:\n - id: N01\n title: alpha\n children:\n - id: N02\n title: beta\n after: gamma\n"; + let document = YamlDocument::parse(text).unwrap(); + let ranges = yaml_ranges(&document.root, "N01").unwrap(); + let covered: String = ranges.iter().map(|range| &text[range.clone()]).collect(); + assert!(covered.contains("alpha") && covered.contains("gamma")); + assert!(!covered.contains("beta")); + let child = yaml_ranges(&document.root, "N02").unwrap(); + assert_eq!(child.len(), 1); + assert!(text[child[0].clone()].contains("beta")); + assert!(yaml_ranges(&document.root, "N03").is_none()); + } +} diff --git a/crates/ara-cli/src/agent/validity.rs b/crates/ara-cli/src/agent/validity.rs new file mode 100644 index 0000000..a3b291b --- /dev/null +++ b/crates/ara-cli/src/agent/validity.rs @@ -0,0 +1,387 @@ +//! Which validation results still allow structural reads. +//! +//! Structural reads (`find`, `ls`, `show`) need a +//! complete representation, not a valid artifact. An error is read through +//! only when its code is in [`READ_THROUGH`]: a dangling reference whose +//! source value is kept while no edge or binding is invented for it. Every +//! other error refuses, so parse loss, missing structure, duplicate or +//! ambiguous identities, cycles, contradictory parents and corrupt identity +//! history stay refusals, and a new rule refuses until it is classified here. +//! Read-through also needs every typed native document to be represented: no +//! `ARA229` fence hides one, no claim-like heading in `logic/claims.md` +//! fails to parse, and no code fence left open at EOF hides one, whether or +//! not any dangling ID names it. A dropped claim looks exactly like a dangling `ARA107` +//! reference, so that parse loss refuses as it did before. The report keeps +//! each diagnostic's original severity. Writes never use this tolerance. +//! +//! An `ARA217`/`ARA218` warning about one optional-layer file (observations, +//! taste log, sessions, experiments, heuristics, the knowledge registry) does +//! not refuse: the read goes ahead and [`with_coverage`] names the file under +//! `incomplete`. Node-scoped `ARA217`, `ARA222` and `ARA226` still refuse. +use crate::output::AgentError; +use ara_core::{ClaimId, Diagnostic, Manifest, ParseReport, RuleCode}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, BTreeSet}; + +/// Native documents whose level-two sections are entries. +const TYPED_DOCUMENTS: [&str; 5] = [ + "logic/claims.md", + "logic/solution/heuristics.md", + "logic/concepts.md", + "logic/related_work.md", + "logic/experiments.md", +]; + +/// Errors that leave every source entry represented. +const READ_THROUGH: [RuleCode; 3] = [ + // A node's `evidence:` names an absent claim. The node keeps the source + // value; only the binding is missing, as when `logic/claims.md` is absent. + RuleCode::UnknownEvidenceClaim, + // `also_depends_on:` names an absent node. The node keeps the source + // value; no dependency edge is created. + RuleCode::UnknownDependencyNode, + // A claim's `Dependencies:` names an absent claim. The claim keeps the ID + // verbatim; nothing resolves it. + RuleCode::UnknownClaimDependency, +]; + +/// Warnings meaning an optional layer or annotation was not fully represented. +const UNREPRESENTED: [RuleCode; 4] = [ + RuleCode::MalformedAgentLayer, + RuleCode::DuplicateAgentId, + RuleCode::MalformedSameAs, + RuleCode::MalformedNodeAnnotation, +]; + +/// Optional-layer files whose `ARA217`/`ARA218` warnings read through. +const OPTIONAL_LAYER_FILES: [&str; 5] = [ + "staging/observations.yaml", + "trace/taste_log.yaml", + "logic/experiments.md", + "logic/solution/heuristics.md", + // An invalid registry leaves the registered documents unloaded. + "PAPER.md.knowledge_paths", +]; + +/// Session records and their index, one optional layer. +const SESSIONS: &str = "trace/sessions/"; + +/// A diagnostic path without its `:line` suffix. +fn diagnostic_file(path: &str) -> &str { + match path.rsplit_once(':') { + Some((file, line)) if !line.is_empty() && line.bytes().all(|b| b.is_ascii_digit()) => file, + _ => path, + } +} + +/// The optional-layer file a warning leaves incomplete, if it reads through. +fn optional_layer(diagnostic: &Diagnostic) -> Option<&str> { + if !matches!( + diagnostic.code, + RuleCode::MalformedAgentLayer | RuleCode::DuplicateAgentId + ) { + return None; + } + let file = diagnostic_file(&diagnostic.path); + (OPTIONAL_LAYER_FILES.contains(&file) || file.starts_with(SESSIONS)).then_some(file) +} + +/// `{path, codes, reason}` for each optional-layer file a read could not +/// fully represent, in first-diagnostic order. `reason` joins the first line +/// of each distinct message. +pub fn incomplete(report: &ParseReport) -> Vec { + let mut files: Vec<(&str, Vec, Vec<&str>)> = Vec::new(); + for diagnostic in report.warnings() { + let Some(file) = optional_layer(diagnostic) else { + continue; + }; + let index = match files.iter().position(|(path, ..)| *path == file) { + Some(index) => index, + None => { + files.push((file, Vec::new(), Vec::new())); + files.len() - 1 + } + }; + let (_, codes, reasons) = &mut files[index]; + if !codes.contains(&diagnostic.code) { + codes.push(diagnostic.code); + } + let reason = diagnostic.message.lines().next().unwrap_or_default(); + if !reasons.contains(&reason) { + reasons.push(reason); + } + } + files + .into_iter() + .map( + |(path, codes, reasons)| json!({"path":path,"codes":codes,"reason":reasons.join("; ")}), + ) + .collect() +} + +/// A structural read result with `complete: false` and `incomplete` added +/// when an optional layer was not fully represented; unchanged otherwise. +pub fn with_coverage(mut value: Value, report: &ParseReport) -> Value { + let incomplete = incomplete(report); + if !incomplete.is_empty() + && let Value::Object(object) = &mut value + { + object.insert("complete".into(), json!(false)); + object.insert("incomplete".into(), json!(incomplete)); + } + value +} + +/// Whether every optional layer and node annotation was represented: none of +/// the [`UNREPRESENTED`] warnings is present. `status` uses this as part of +/// `complete`; structural reads refuse with `incomplete_artifact` without it. +pub fn representable(report: &ParseReport) -> bool { + !report + .warnings() + .iter() + .any(|diagnostic| UNREPRESENTED.contains(&diagnostic.code)) +} + +/// [`representable`], ignoring optional-layer warnings: every node and node +/// annotation was represented, so counts stay meaningful. +pub fn nodes_representable(report: &ParseReport) -> bool { + !report.warnings().iter().any(|diagnostic| { + UNREPRESENTED.contains(&diagnostic.code) && optional_layer(diagnostic).is_none() + }) +} + +/// Native ID prefixes whose next ID is unknown because their optional-layer +/// file is incomplete: a dropped entry may already hold the next number. +pub fn incomplete_prefixes(report: &ParseReport) -> BTreeMap { + let mut prefixes = BTreeMap::new(); + for diagnostic in report.warnings() { + let prefix = match optional_layer(diagnostic) { + Some("staging/observations.yaml") => 'O', + Some("trace/taste_log.yaml") => 'T', + Some("logic/experiments.md") => 'E', + Some("logic/solution/heuristics.md") => 'H', + _ => continue, + }; + prefixes + .entry(prefix) + .or_insert_with(|| diagnostic_file(&diagnostic.path)); + } + prefixes +} + +/// Distinct error codes in report order, filtered by `keep`. +fn error_codes(report: &ParseReport, keep: impl Fn(RuleCode) -> bool) -> Vec { + let mut codes = Vec::new(); + for diagnostic in report.errors() { + if keep(diagnostic.code) && !codes.contains(&diagnostic.code) { + codes.push(diagnostic.code); + } + } + codes +} + +/// `path:line: reason` for each typed document that lost entries. +fn unrepresented_documents( + report: &ParseReport, + sources: &BTreeMap, + manifest: Option<&Manifest>, +) -> Vec { + let mut reasons: Vec = report + .warnings() + .iter() + .filter(|d| { + d.code == RuleCode::UnclosedFrontmatter + && d.path + .rsplit_once(':') + .is_some_and(|(path, _)| TYPED_DOCUMENTS.contains(&path)) + }) + .map(|d| format!("{}: unclosed leading `---` hides its entries", d.path)) + .collect(); + if let Some(claims) = sources.get("logic/claims.md") { + reasons.extend(ara_core::unparsed_claim_headings(claims).into_iter().map( + |(line, heading)| { + format!("logic/claims.md:{line}: claim heading `{heading}` does not parse") + }, + )); + reasons.extend(ara_core::fenced_claim_headings(claims).into_iter().map( + |(line, heading)| { + format!( + "logic/claims.md:{line}: unclosed code fence hides claim heading `{}`", + heading.trim() + ) + }, + )); + } + let (dangling, unidentified) = dangling_claims(report, manifest); + reasons.extend(unidentified); + if let Some(claims) = sources.get("logic/claims.md") { + reasons.extend(dangling_claim_headings(&dangling, claims)); + } + reasons +} + +/// The claim ID a dangling-reference message names: its last backticked +/// token, when that is a canonical claim ID. +fn dangling_id(message: &str) -> Option<&str> { + message + .rsplit('`') + .nth(1) + .filter(|id| ClaimId::new(*id).is_canonical()) +} + +/// Dangling claim IDs, plus a reason for each ARA107/ARA109 diagnostic whose +/// ID cannot be identified, so a reworded message fails closed. Claim +/// dependencies come from the manifest; evidence IDs (whose bindings the +/// parser does not keep) come from the diagnostics. +fn dangling_claims( + report: &ParseReport, + manifest: Option<&Manifest>, +) -> (BTreeSet, Vec) { + let mut ids = BTreeSet::new(); + if let Some(manifest) = manifest { + let live: BTreeSet<&str> = manifest.claims.iter().map(|c| c.id.as_str()).collect(); + ids.extend( + manifest + .claims + .iter() + .flat_map(|claim| &claim.deps) + .map(ClaimId::as_str) + .filter(|id| !live.contains(id)) + .map(str::to_owned), + ); + } + let mut unidentified = Vec::new(); + for diagnostic in report.errors().iter().filter(|d| { + matches!( + d.code, + RuleCode::UnknownEvidenceClaim | RuleCode::UnknownClaimDependency + ) + }) { + match dangling_id(&diagnostic.message) { + Some(id) => { + ids.insert(id.to_owned()); + } + None => unidentified.push(format!( + "{}: cannot identify the dangling claim to rule out a dropped claim heading", + diagnostic.path + )), + } + } + (ids, unidentified) +} + +/// Heading-like lines of `logic/claims.md` that name a dangling claim ID. +/// +/// A claim the parser dropped (inside an unclosed code fence, lowercase, +/// bold, at level three, spaced `C 01`) is reported exactly like a dangling +/// reference. Any line starting with `#` (after leading whitespace) that has +/// the ID as a whole token, case-insensitively or with spaces removed, is +/// therefore treated as lost source. This includes a parsed claim heading +/// whose title names the dangling ID (`## C02: Extends C01`), which refuses +/// conservatively. Fences and indentation are ignored on purpose; prose and +/// field lines are not headings and never match. +fn dangling_claim_headings(dangling: &BTreeSet, claims: &str) -> Vec { + let names = |text: &str, id: &str| { + text.split(|c: char| !c.is_alphanumeric()) + .any(|token| token.eq_ignore_ascii_case(id)) + }; + claims + .lines() + .enumerate() + .filter(|(_, line)| line.trim_start().starts_with('#')) + .filter_map(|(index, line)| { + let compact: String = line.split_whitespace().collect(); + let id = dangling + .iter() + .find(|id| names(line, id) || names(&compact, id))?; + Some(format!( + "logic/claims.md:{}: heading-like line names dangling claim `{id}` but is not a claim", + index + 1 + )) + }) + .collect() +} + +/// The structural-read refusal for a load, if any: `invalid_artifact` for a +/// blocking error, or for a read-through error while a typed document lost +/// entries, and `incomplete_artifact` for an unrepresented node annotation. +/// Optional-layer warnings never refuse ([`with_coverage`]). +pub fn read_refusal( + report: &ParseReport, + sources: &BTreeMap, + manifest: Option<&Manifest>, +) -> Option { + let errors = error_codes(report, |code| !READ_THROUGH.contains(&code)); + if !errors.is_empty() { + return Some(refusal("invalid_artifact", report, errors)); + } + if !report.is_ok() { + let unrepresented = unrepresented_documents(report, sources, manifest); + if !unrepresented.is_empty() { + let mut error = refusal("invalid_artifact", report, error_codes(report, |_| true)); + if let Some(Value::Object(details)) = error.details.as_deref_mut() { + details.insert("unrepresented".into(), json!(unrepresented)); + } + return Some(error); + } + } + let unrepresented: Vec = UNREPRESENTED + .into_iter() + .filter(|code| { + report + .warnings() + .iter() + .any(|d| d.code == *code && optional_layer(d).is_none()) + }) + .collect(); + (!unrepresented.is_empty()).then(|| refusal("incomplete_artifact", report, unrepresented)) +} + +/// A refusal naming its blocking rule codes, with a next step. +pub fn refusal(code: &str, report: &ParseReport, blocking: Vec) -> AgentError { + AgentError { + details: Some(Box::new(json!({ + "blocking": blocking, + "hint": "Run `ara check` to list each diagnostic with its rule code and location. Dangling references alone do not block reads; a source read (`ara show --document --source`) still works.", + }))), + summary: Some(summary(report).into()), + ..AgentError::semantic(code, report.to_string()) + } +} + +/// Error and warning counts with their rule codes, for text output. +fn summary(report: &ParseReport) -> String { + let codes = |diagnostics: &[ara_core::Diagnostic]| { + diagnostics + .iter() + .map(|d| d.code.to_string()) + .collect::>() + }; + let (errors, warnings) = (codes(report.errors()), codes(report.warnings())); + let errors: Vec<&str> = errors.iter().map(String::as_str).collect(); + let warnings: Vec<&str> = warnings.iter().map(String::as_str).collect(); + format!( + "the artifact cannot be read structurally: {}", + crate::brief::summary(&errors, &warnings) + ) +} + +#[cfg(test)] +mod tests { + use super::dangling_id; + + #[test] + fn dangling_ids_come_only_from_backticked_canonical_claims() { + assert_eq!( + dangling_id("evidence references unknown claim `C01`"), + Some("C01") + ); + assert_eq!( + dangling_id("dependency references unknown claim `C98`"), + Some("C98") + ); + // Reworded or unexpected messages yield nothing, which fails closed. + assert_eq!(dangling_id("evidence references unknown claim C01"), None); + assert_eq!(dangling_id("unknown claim `N01`"), None); + } +} diff --git a/crates/ara-cli/src/agent/window.rs b/crates/ara-cli/src/agent/window.rs new file mode 100644 index 0000000..b12921d --- /dev/null +++ b/crates/ara-cli/src/agent/window.rs @@ -0,0 +1,490 @@ +//! Bounded and resumable `show` reads. +//! +//! `--lines A:B` keeps one-based inclusive lines of each native source +//! selection. A line ends after its `\n` (so `\r\n` stays whole), and a final +//! newline closes the last line instead of opening an empty one. A byte +//! budget covers the whole response exactly as it is written, headers and +//! metadata included. A single native selection that overflows pages at +//! whole lines and names the next window; any other overflow rejects with +//! the budget it needs. Every page keeps the full selection's `digest`. +use super::ShowArgs; +use crate::output::AgentError; +use serde_json::{Value, json}; +use std::io::Write; + +/// Brief `show` stdout budget when `--max-bytes` is absent. +pub const DEFAULT_MAX_BYTES: usize = 16 * 1024; + +/// A parsed `--lines` value; at least one end is present. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LineSpec { + start: Option, + end: Option, +} +impl LineSpec { + pub fn parse(text: &str) -> Result { + let invalid = || { + AgentError::setup( + "invalid_lines", + format!( + "--lines `{text}` must be A:B, A: or :B with one-based line numbers and A <= B" + ), + ) + }; + let (start, end) = text.split_once(':').ok_or_else(invalid)?; + let bound = |part: &str| match part { + "" => Ok(None), + part => positive(part).map(Some).ok_or_else(invalid), + }; + let spec = Self { + start: bound(start)?, + end: bound(end)?, + }; + match (spec.start, spec.end) { + (None, None) => Err(invalid()), + (Some(start), Some(end)) if start > end => Err(invalid()), + _ => Ok(spec), + } + } +} + +pub fn parse_max_bytes(text: &str) -> Result { + positive(text).ok_or_else(|| { + AgentError::setup( + "invalid_max_bytes", + format!("--max-bytes `{text}` must be a positive whole number of bytes"), + ) + }) +} + +/// A nonzero decimal number without sign or spaces that fits `usize`. +fn positive(text: &str) -> Option { + if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) { + return None; + } + text.parse().ok().filter(|value| *value > 0) +} + +/// The bounds of one `show`, parsed before anything is read. +pub struct Bounds { + lines: Option, + /// The response budget: explicit, or the brief default. + budget: Option, + /// Without `--json` the budget measures brief text, otherwise JSON. + brief: bool, +} +impl Bounds { + pub fn new(args: &ShowArgs) -> Result { + let lines = args.lines.as_deref().map(LineSpec::parse).transpose()?; + let explicit = args.max_bytes.as_deref().map(parse_max_bytes).transpose()?; + let brief = args.output.brief(); + // `--source --full` is the explicit unbounded read. + let default = (brief && !(args.source && args.output.full)).then_some(DEFAULT_MAX_BYTES); + Ok(Self { + lines, + budget: explicit.or(default), + brief, + }) + } + + /// Window each source row of a `show` value, then fit the response to + /// the budget by paging a single native selection or rejecting. + pub fn apply(&self, value: &mut Value) -> Result<(), AgentError> { + if self.lines.is_none() && self.budget.is_none() { + return Ok(()); + } + // JSON bounds always report the range; brief text only when asked + // for a window or when it pages. + let report = self.lines.is_some() || !self.brief; + let mut sources = Vec::new(); + for row in rows(value) { + if row["kind"] != "source_document" { + if self.lines.is_some() { + return Err(lines_unavailable(row)); + } + sources.push(None); + continue; + } + let source = Source::take(row); + let window = source.window(self.lines, row)?; + source.page(row, &window, window.len(), report); + sources.push(Some((source, window))); + } + let Some(budget) = self.budget else { + return Ok(()); + }; + let size = self.measure(value); + if size <= budget { + return Ok(()); + } + let count = sources.len(); + // Addresses that failed print their errors among the blocks; they + // count toward the response but have nothing to page. + let requested = count + value["errors"].as_array().map_or(0, Vec::len); + let (source, window) = match sources.pop() { + Some(Some(single)) if count == 1 => single, + Some(None) if count == 1 => { + let row = &rows(value)[0]; + let hint = projection_hint(row, size); + return Err(too_small(Some(label(row)), budget, size, None, hint)); + } + _ => { + let hint = format!( + "The {requested} selections need {size} bytes together; read each address separately to page through it, or rerun with --max-bytes {size}" + ); + return Err(too_small(None, budget, size, None, hint)); + } + }; + let total = window.len(); + let mut page_size = |lines: usize| { + source.page(&mut rows(value)[0], &window, lines, true); + self.measure(value) + }; + // Bisect over truncated pages of 1..total-1 lines. Their size never + // shrinks as lines are added: each line adds at least its own + // terminator or one byte, and the range and `next` numbers only gain + // digits. The complete page (`total` lines) is excluded because it + // drops the `truncated; next` text and can be smaller than a + // truncated page; it was measured above as `size` and did not fit. + let first = if total > 1 { page_size(1) } else { size }; + if total > 1 && first <= budget { + let (mut fitting, mut over) = (1, total); + while over - fitting > 1 { + let middle = fitting + (over - fitting) / 2; + if page_size(middle) <= budget { + fitting = middle; + } else { + over = middle; + } + } + page_size(fitting); + return Ok(()); + } + // No page fits. The cheapest response holding the first line is the + // one-line truncated page or, when that metadata costs more than the + // rest of the window, the complete page; `required` is the smaller. + let required = first.min(size); + let (line, hint) = if total == 0 { + ( + None, + format!( + "The selection's metadata needs {required} bytes; rerun with --max-bytes {required} or more" + ), + ) + } else { + ( + Some(window.start), + format!( + "Line {} and its metadata need {required} bytes; rerun with --max-bytes {required} or more", + window.start + ), + ) + }; + Err(too_small( + Some(label(&rows(value)[0])), + budget, + required, + line, + hint, + )) + } + + /// Bytes this value prints on stdout. + fn measure(&self, value: &Value) -> usize { + measure(value, self.brief) + } +} + +/// Bytes a read value prints on stdout: its brief text, or its JSON line. +pub fn measure(value: &Value, brief: bool) -> usize { + let mut count = Count(0); + if brief { + crate::brief::render(value, &mut count).expect("counting cannot fail"); + } else { + serde_json::to_writer(&mut count, value).expect("counting cannot fail"); + count.0 += 1; + } + count.0 +} + +fn rows(value: &mut Value) -> &mut Vec { + value["entries"].as_array_mut().expect("show entries") +} + +/// A writer that only counts bytes. +struct Count(usize); +impl Write for Count { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0 += buf.len(); + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// One-based inclusive lines `start..=end` of `total`, empty when +/// `end < start`; `upper` is the requested end a continuation keeps. +#[derive(Debug, PartialEq, Eq)] +struct Window { + start: usize, + end: usize, + total: usize, + upper: Option, +} +impl Window { + fn len(&self) -> usize { + (self.end + 1).saturating_sub(self.start) + } +} + +/// The full content of a source selection and the byte offsets that end +/// its lines: line `n` is `text[breaks[n - 1]..breaks[n]]`. +struct Source { + text: String, + breaks: Vec, +} +impl Source { + fn new(text: String) -> Self { + let mut breaks = vec![0]; + breaks.extend(text.match_indices('\n').map(|(at, _)| at + 1)); + if breaks.last() != Some(&text.len()) { + breaks.push(text.len()); + } + Self { text, breaks } + } + fn take(row: &mut Value) -> Self { + let text = match row["content"].take() { + Value::String(text) => text, + _ => String::new(), + }; + Self::new(text) + } + fn window(&self, spec: Option, row: &Value) -> Result { + let total = self.breaks.len() - 1; + let spec = spec.unwrap_or(LineSpec { + start: None, + end: None, + }); + let start = spec.start.unwrap_or(1); + if spec.start.is_some() && start > total { + return Err(out_of_range(row, start, total)); + } + Ok(Window { + start, + end: spec.end.map_or(total, |end| end.min(total)), + total, + upper: spec.end, + }) + } + /// Show the first `lines` lines of `window` in `row`; `report` adds the + /// range, which a truncated page always has. + fn page(&self, row: &mut Value, window: &Window, lines: usize, report: bool) { + let first = window.start; + let content = &self.text[self.breaks[first - 1]..self.breaks[first - 1 + lines]]; + row["content"] = json!(content); + let truncated = lines < window.len(); + if !(report || truncated) { + return; + } + let next = truncated.then(|| { + let upper = window.upper.map_or_else(String::new, |end| end.to_string()); + format!("{}:{upper}", first + lines) + }); + let display = &mut row["display"]; + if !display.is_object() { + *display = json!({}); + } + display["lines"] = json!({"start": first, "end": first + lines - 1, "total": window.total}); + display["truncated"] = json!(truncated); + display["next"] = json!(next); + } +} + +/// The address a reader would type: the cited `path#ID` of an entry +/// section, else the entry ID, canonical address or key. +fn label(row: &Value) -> &str { + row["display"]["cited"] + .as_str() + .or_else(|| { + ["id", "address", "key"] + .iter() + .find_map(|key| row[*key].as_str()) + }) + .unwrap_or("") +} + +fn out_of_range(row: &Value, start: usize, total: usize) -> AgentError { + let address = label(row); + AgentError { + id: Some(address.to_owned()), + details: Some(Box::new(json!({ + "start": start, + "total": total, + "hint": format!("`{address}` has {total} lines; start at line {total} or earlier, or omit the start"), + }))), + ..AgentError::semantic( + "line_out_of_range", + format!("--lines starts at line {start}, beyond the {total} lines of `{address}`"), + ) + } +} + +fn exact_source(row: &Value) -> String { + let source = row["source"].as_str().unwrap_or(""); + format!( + "ara show --document {} --source", + crate::brief::quote(source) + ) +} + +fn lines_unavailable(row: &Value) -> AgentError { + let address = label(row); + AgentError { + id: Some(address.to_owned()), + details: Some(Box::new(json!({ + "hint": format!( + "`{address}` is a projection without native source lines; read its source with `{} --lines A:B`", + exact_source(row) + ), + }))), + ..AgentError::semantic( + "lines_unavailable", + format!("--lines needs a native source selection; `{address}` is a projection"), + ) + } +} + +fn projection_hint(row: &Value, size: usize) -> String { + if row.get("relations").is_some() || row["kind"] == "identity" { + return format!( + "The complete relations or identity mapping and required metadata need {size} bytes; rerun with --max-bytes {size} or more" + ); + } + format!( + "`{}` is a projection with no native line range to page through; read the exact source with `{} --lines A:B`, or rerun with --max-bytes {size}", + label(row), + exact_source(row) + ) +} + +/// `id` names the one selection that did not fit; a multi-address +/// overflow has none. +pub fn too_small( + id: Option<&str>, + budget: usize, + required: usize, + line: Option, + hint: String, +) -> AgentError { + let mut details = json!({"required": required, "max_bytes": budget, "hint": hint}); + if let Some(line) = line { + details["line"] = json!(line); + } + AgentError { + id: id.map(str::to_owned), + details: Some(Box::new(details)), + ..AgentError::semantic( + "output_limit_too_small", + format!("The response needs at least {required} bytes; the budget is {budget}"), + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spec(text: &str) -> Option<(Option, Option)> { + LineSpec::parse(text) + .ok() + .map(|spec| (spec.start, spec.end)) + } + + #[test] + fn line_specs_need_one_positive_ordered_bound() { + assert_eq!(spec("2:5"), Some((Some(2), Some(5)))); + assert_eq!(spec("3:"), Some((Some(3), None))); + assert_eq!(spec(":4"), Some((None, Some(4)))); + assert_eq!(spec("4:4"), Some((Some(4), Some(4)))); + for bad in [ + ":", "", "4", "0:1", "1:0", "5:4", "-1:2", "+1:2", "1:2:3", "a:", " 1:2", + ] { + assert_eq!(spec(bad), None, "{bad}"); + } + let overflow = format!("{}0:", usize::MAX); + assert_eq!(spec(&overflow), None); + assert_eq!(parse_max_bytes("16").unwrap(), 16); + for bad in ["0", "-1", "", "1e3", "+5", "99999999999999999999999"] { + assert!(parse_max_bytes(bad).is_err(), "{bad}"); + } + } + + #[test] + fn lines_keep_their_terminators_and_a_final_newline_ends_the_last() { + let lines = |text: &str| { + let source = Source::new(text.to_owned()); + (1..source.breaks.len()) + .map(|n| source.text[source.breaks[n - 1]..source.breaks[n]].to_owned()) + .collect::>() + }; + assert_eq!(lines("a\r\nb\nc"), ["a\r\n", "b\n", "c"]); + assert_eq!(lines("a\n"), ["a\n"]); + assert_eq!(lines("\n\n"), ["\n", "\n"]); + assert!(lines("").is_empty()); + assert_eq!(lines("é😀\r"), ["é😀\r"]); + } + + #[test] + fn windows_clamp_the_end_and_reject_a_start_beyond_eof() { + let source = Source::new("a\nb\nc\n".to_owned()); + let row = json!({"address": "d.md"}); + let window = |text: &str| source.window(Some(LineSpec::parse(text).unwrap()), &row); + assert_eq!( + window("2:9").unwrap(), + Window { + start: 2, + end: 3, + total: 3, + upper: Some(9) + } + ); + assert_eq!(window(":2").unwrap().len(), 2); + assert_eq!(window("4:").unwrap_err().code, "line_out_of_range"); + let empty = Source::new(String::new()); + assert_eq!( + empty + .window(LineSpec::parse(":3").ok(), &row) + .unwrap() + .len(), + 0 + ); + assert!(empty.window(LineSpec::parse("1:").ok(), &row).is_err()); + } + + #[test] + fn a_page_names_the_next_window_with_the_original_upper_bound() { + let source = Source::new("a\nb\nc\nd\n".to_owned()); + let row_of = |spec: &str, lines: usize| { + let mut row = json!({"address": "d.md"}); + let window = source + .window(Some(LineSpec::parse(spec).unwrap()), &row) + .unwrap(); + source.page(&mut row, &window, lines, false); + row + }; + let row = row_of("2:9", 1); + assert_eq!(row["content"], "b\n"); + assert_eq!(row["display"]["next"], "3:9"); + assert_eq!( + row["display"]["lines"], + json!({"start":2,"end":2,"total":4}) + ); + let row = row_of("2:", 2); + assert_eq!(row["display"]["next"], "4:"); + // A complete window that was not asked to report adds nothing. + let row = row_of("1:", 4); + assert_eq!(row["content"], "a\nb\nc\nd\n"); + assert!(row.get("display").is_none()); + } +} diff --git a/crates/ara-cli/src/brief/lists.rs b/crates/ara-cli/src/brief/lists.rs new file mode 100644 index 0000000..f715640 --- /dev/null +++ b/crates/ara-cli/src/brief/lists.rs @@ -0,0 +1,331 @@ +//! Address-led list output and complete relation sections. +use crate::agent::address; +use serde_json::Value; +use std::collections::{BTreeMap, BTreeSet}; +use std::io::{Result, Write}; + +fn text(value: &Value) -> &str { + value.as_str().unwrap_or("") +} +/// The address a caller passes back to `show`: a native ID, a heading +/// address, or a document path. +fn row_address(row: &Value) -> String { + if let Some(address) = row["address"].as_str() { + return address.to_owned(); + } + match (row["id"].as_str(), row["key"].as_str()) { + (Some(id), _) => id.to_owned(), + (None, Some(key)) if matches!(text(&row["kind"]), "source_document" | "solution") => { + address::document(key) + } + (None, key) => key.unwrap_or("").to_owned(), + } +} +fn title(row: &Value) -> String { + [ + "title", + "term", + "cite", + "name", + "statement", + "summary", + "content", + ] + .iter() + .find_map(|key| row[*key].as_str()) + .map_or_else(String::new, crate::output::excerpt) +} +fn rows<'a>(value: &'a Value, key: &str) -> impl Iterator { + value[key].as_array().into_iter().flatten() +} +/// Print `note` when `value[key]` is empty, so an empty result is visible. +/// Returns whether it was empty. +fn none(value: &Value, key: &str, note: &str, out: &mut impl Write) -> Result { + let empty = rows(value, key).next().is_none(); + if empty { + writeln!(out, "{note}")?; + } + Ok(empty) +} + +pub fn find(value: &Value, out: &mut impl Write) -> Result<()> { + if none(value, "results", "no results", out)? { + return Ok(()); + } + for result in rows(value, "results") { + writeln!( + out, + "{} [{}] {}", + row_address(result), + text(&result["kind"]), + text(&result["source"]) + )?; + let matched: BTreeSet = rows(result, "matches") + .filter_map(|hit| hit["line"].as_u64()) + .collect(); + if matched.is_empty() { + writeln!(out, " excerpt: {}", text(&result["excerpt"]))?; + continue; + } + // A whole-document hit names the section of each matched line as + // `in:
` when it changes. + let sections: BTreeMap = rows(result, "matches") + .filter_map(|hit| Some((hit["line"].as_u64()?, hit["in"].as_str()?))) + .collect(); + let mut current = None; + let mut section = |number: u64, out: &mut dyn Write| -> Result<()> { + if let Some(&address) = sections.get(&number) + && current != Some(address) + { + current = Some(address); + writeln!(out, " in: {address}")?; + } + Ok(()) + }; + if let Some(blocks) = result["context"].as_array() { + for (index, block) in blocks.iter().enumerate() { + if index > 0 { + writeln!(out, " --")?; + } + let start = block["start"].as_u64().unwrap_or(1); + for (offset, line) in rows(block, "lines").enumerate() { + let number = start + offset as u64; + let mark = if matched.contains(&number) { ':' } else { '-' }; + section(number, out)?; + writeln!(out, " {number}{mark} {}", text(line))?; + } + } + } else { + for hit in rows(result, "matches") { + section(hit["line"].as_u64().unwrap_or(0), out)?; + writeln!(out, " {}: {}", hit["line"], text(&hit["text"]))?; + } + } + let total = result["match_count"].as_u64().unwrap_or(0); + if total > matched.len() as u64 { + writeln!( + out, + " +{} more matching lines", + total - matched.len() as u64 + )?; + } + } + truncation(&value["truncation"], out) +} + +/// The line a byte budget adds when it cut a `find` response. +fn truncation(truncation: &Value, out: &mut impl Write) -> Result<()> { + let Some(omitted) = truncation["omitted_hits"].as_u64() else { + return Ok(()); + }; + let mut parts = Vec::new(); + if truncation["truncated_hit"] == true { + parts.push("first hit cut to fit the byte budget".into()); + } + if omitted > 0 { + let plural = if omitted == 1 { "" } else { "s" }; + parts.push(format!("{omitted} more hit{plural}")); + } + parts.push("narrow with --type, --document or more specific terms".into()); + writeln!(out, "{}", parts.join("; ")) +} + +pub fn ls(value: &Value, out: &mut impl Write) -> Result<()> { + if let Some(documents) = value["documents"].as_array() { + for document in documents { + let counts = document["counts"] + .as_object() + .filter(|counts| !counts.is_empty()) + .map(|counts| { + counts + .iter() + .map(|(kind, count)| format!("{kind}={count}")) + .collect::>() + .join(" ") + }); + let kind = match (counts, document["headings"].as_u64()) { + (Some(counts), _) => counts, + (None, Some(headings)) => format!("document headings={headings}"), + (None, None) => "document".into(), + }; + writeln!( + out, + "{}\t{kind}\tlines={}", + text(&document["address"]), + document["lines"] + )?; + } + let roots: Vec<&str> = rows(value, "file_access").map(text).collect(); + writeln!( + out, + "direct files: {} are not ara documents; read and search them with your file tools", + roots.join(" ") + )?; + return Ok(()); + } + if none(value, "entries", "no entries", out)? { + return Ok(()); + } + for row in rows(value, "entries") { + if row.get("reasons").is_some() { + unfinished_row(row, out)?; + continue; + } + writeln!( + out, + "{}\t{}\t{}", + row_address(row), + text(&row["kind"]), + title(row) + )?; + } + Ok(()) +} + +fn unfinished_row(row: &Value, out: &mut impl Write) -> Result<()> { + let reasons: Vec<&str> = rows(row, "reasons").map(text).collect(); + write!( + out, + "{}\t{}\t{}\t{}", + row_address(row), + text(&row["kind"]), + reasons.join(","), + title(row) + )?; + // Observation rows end with their measured inactivity; an unknown + // count prints `unknown`, never zero. + if let Some(status) = row["history_status"].as_str() { + let count = |key: &str| { + row[key] + .as_u64() + .map_or_else(|| "unknown".to_owned(), |n| n.to_string()) + }; + write!( + out, + "\tturns={} days={} last_reference={} history={status}", + count("turns_since_reference"), + count("session_days_since_reference"), + row["last_reference_turn"] + .as_str() + .or_else(|| row["last_reference_date"].as_str()) + .unwrap_or("unknown"), + )?; + } + if let Some(evidence) = row.get("evidence_sources") { + write!(out, "\tevidence={evidence}")?; + } + writeln!(out)?; + Ok(()) +} + +pub(super) fn path(value: &Value, out: &mut impl Write) -> Result<()> { + for (depth, step) in value.as_array().into_iter().flatten().enumerate() { + writeln!( + out, + "{}{}\t{}\t{}", + " ".repeat(depth), + row_address(step), + text(&step["kind"]), + title(step) + )?; + } + Ok(()) +} + +pub(super) fn refs(value: &Value, out: &mut impl Write) -> Result<()> { + let location = |row: &Value| match row["line"].as_u64() { + Some(line) => format!("{}:{line}", text(&row["source"])), + None => text(&row["source"]).to_owned(), + }; + let target = value["display"]["target"] + .as_str() + .unwrap_or_else(|| text(&value["target"])); + writeln!(out, "target: {target}")?; + for row in rows(value, "structured") { + writeln!( + out, + "{}\t{}\t{}\t{}", + row["address"].as_str().unwrap_or_else(|| text(&row["id"])), + text(&row["field"]), + location(row), + text(&row["literal"]) + )?; + } + for row in rows(value, "prose") { + writeln!( + out, + "{}\tpossible mention\t{}\t{}", + location(row), + text(&row["literal"]), + text(&row["context"]) + )?; + } + Ok(()) +} + +pub fn status(value: &Value, out: &mut impl Write) -> Result<()> { + let complete = value["complete"] == true; + writeln!(out, "complete\t{}", if complete { "yes" } else { "no" })?; + let pairs = |object: &Value| { + object.as_object().map(|object| { + object + .iter() + .map(|(key, value)| { + format!( + "{key}={}", + value + .as_str() + .map_or_else(|| value.to_string(), str::to_owned) + ) + }) + .collect::>() + .join(" ") + }) + }; + match pairs(&value["counts"]) { + Some(counts) => writeln!(out, "counts\t{counts}")?, + None => writeln!(out, "counts\tunavailable while errors exist")?, + } + match value["next_ids"].as_object() { + Some(next) => { + let mut reasons = std::collections::BTreeMap::>::new(); + let ids: Vec = next + .iter() + .map(|(prefix, id)| match id.as_str() { + Some(id) => format!("{prefix}={id}"), + None => { + let error = &value["next_id_errors"][prefix]; + let reason = + format!("{}: {}", text(&error["code"]), text(&error["message"])); + reasons.entry(reason).or_default().push(prefix); + format!("{prefix}=unavailable") + } + }) + .collect(); + writeln!(out, "next_ids\t{}", ids.join(" "))?; + for (reason, prefixes) in reasons { + writeln!( + out, + "next_ids_unavailable\t{} ({reason})", + prefixes.join(" ") + )?; + } + } + None => writeln!(out, "next_ids\tunavailable while errors exist")?, + } + if let Some(session) = value["latest_session"].as_str() { + writeln!(out, "latest_session\t{session}")?; + } + writeln!( + out, + "files\t{} ({} bytes)", + value["file_count"], value["total_bytes"] + )?; + let codes = |key: &str| -> Vec<&str> { rows(&value["display"], key).map(text).collect() }; + writeln!( + out, + "diagnostics\t{}", + super::summary(&codes("error_codes"), &codes("warning_codes")) + )?; + Ok(()) +} diff --git a/crates/ara-cli/src/brief/mod.rs b/crates/ara-cli/src/brief/mod.rs new file mode 100644 index 0000000..bc3446c --- /dev/null +++ b/crates/ara-cli/src/brief/mod.rs @@ -0,0 +1,270 @@ +//! Brief default text for agent reads. +//! +//! Each read command builds its `ara./v1` value; without `--json` +//! this module renders that value as address-led text. Data that only the +//! text needs (a native section for `show C04`, write selectors, document +//! summaries, status rule codes) is computed only in brief mode, or for +//! `show` when `--lines`/`--max-bytes` bound a JSON read, and lives in +//! `display` objects. Unbounded JSON reads never carry them. Diagnostics +//! print once per command on stderr as counts and codes. +mod lists; +mod show; + +use crate::output::AgentError; +use serde_json::Value; +pub(crate) use show::quote; +use std::collections::BTreeMap; +use std::io::Write; + +/// Ranked candidates a text error lists; `--json` keeps the full list. +const TEXT_CANDIDATES: usize = 10; +/// Distinct rule codes a text summary names per severity; counts stay exact. +const TEXT_CODES: usize = 12; + +/// Read formats rendered as brief text; other commands keep their text. +pub(crate) fn handles(format: &str) -> bool { + matches!( + format, + "ara.status/v1" | "ara.ls/v1" | "ara.show/v1" | "ara.find/v1" + ) +} + +/// Write a read result to stdout and its diagnostics summary to stderr. +pub(crate) fn print(value: &Value) { + let stdout = std::io::stdout(); + let mut out = std::io::BufWriter::new(stdout.lock()); + // A reader that stops early (`| head`) is not an error. + if let Err(error) = render(value, &mut out).and_then(|()| out.flush()) + && error.kind() != std::io::ErrorKind::BrokenPipe + { + panic!("stdout output: {error}"); + } + print_diagnostics(value); +} + +/// The once-per-command diagnostics summary on stderr for a text read, +/// including `--fields` projections; `status` prints its codes on stdout. +pub(crate) fn print_diagnostics(value: &Value) { + if value["format"] != "ara.status/v1" + && let Some(summary) = diagnostics(&value["diagnostics"]) + { + eprintln!("{summary}"); + } + for line in incomplete(value) { + eprintln!("{line}"); + } +} + +/// One `incomplete: path (codes)` line per optional-layer file a read could +/// not fully represent. +fn incomplete(value: &Value) -> Vec { + let Some(files) = value["incomplete"].as_array() else { + return Vec::new(); + }; + files + .iter() + .map(|file| { + let codes: Vec<&str> = file["codes"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + format!( + "incomplete: {} ({})", + file["path"].as_str().unwrap_or_default(), + codes.join(", ") + ) + }) + .collect() +} + +pub(crate) fn render(value: &Value, out: &mut impl Write) -> std::io::Result<()> { + match value["format"].as_str().unwrap_or("") { + "ara.show/v1" => { + for block in show::blocks(value) { + block.write(out)?; + } + Ok(()) + } + "ara.find/v1" => lists::find(value, out), + "ara.ls/v1" => lists::ls(value, out), + "ara.status/v1" => lists::status(value, out), + _ => writeln!(out, "{value:#}"), + } +} + +/// Rule codes with repeat counts, sorted by code: `ARA206×2, ARA208`. +/// Past [`TEXT_CODES`] distinct codes, the rest are counted, not named. +fn codes(codes: &[&str]) -> String { + let mut counts = BTreeMap::<&str, usize>::new(); + for code in codes { + *counts.entry(code).or_default() += 1; + } + let omitted = counts.len().saturating_sub(TEXT_CODES); + let mut named: Vec = counts + .into_iter() + .take(TEXT_CODES) + .map(|(code, count)| { + if count > 1 { + format!("{code}×{count}") + } else { + code.to_owned() + } + }) + .collect(); + if omitted > 0 { + named.push(format!("… {omitted} more codes")); + } + named.join(", ") +} + +/// `N errors (codes), M warnings (codes)` from rule codes, one per +/// diagnostic, ending in a pointer to `ara check` when there is any. +pub(crate) fn summary(errors: &[&str], warnings: &[&str]) -> String { + let part = |found: &[&str], name: &str| { + if found.is_empty() { + format!("0 {name}") + } else { + format!("{} {name} ({})", found.len(), codes(found)) + } + }; + let mut text = format!("{}, {}", part(errors, "errors"), part(warnings, "warnings")); + if !errors.is_empty() || !warnings.is_empty() { + text.push_str("; run `ara check` for locations"); + } + text +} + +/// The `code` of each diagnostic row under `key`. +fn row_codes<'a>(diagnostics: &'a Value, key: &str) -> Vec<&'a str> { + diagnostics[key] + .as_array() + .into_iter() + .flatten() + .map(|row| row["code"].as_str().unwrap_or("?")) + .collect() +} +/// One line naming error and warning counts and codes, or `None` when the +/// load reported nothing. +pub(crate) fn diagnostics(diagnostics: &Value) -> Option { + let errors = row_codes(diagnostics, "errors"); + let warnings = row_codes(diagnostics, "warnings"); + (!errors.is_empty() || !warnings.is_empty()) + .then(|| format!("diagnostics: {}", summary(&errors, &warnings))) +} + +/// A text error: the code and message, then the actionable details a JSON +/// caller would read (hint, candidates, blocking codes, file-access roots). +pub(crate) fn error(error: &AgentError) -> String { + let message = error.summary.as_deref().unwrap_or(&error.message); + error_text(&error.code, message, error.details.as_deref()) +} + +/// [`error`] for the JSON form of an error, as a partial `show` reports +/// each address that failed. +pub(crate) fn error_value(error: &Value) -> String { + error_text( + error["code"].as_str().unwrap_or(""), + error["message"].as_str().unwrap_or(""), + error.get("details"), + ) +} + +fn error_text(code: &str, message: &str, details: Option<&Value>) -> String { + let mut text = format!("error [{code}]: {message}"); + let Some(details) = details else { + return text; + }; + let list = |key: &str| { + details[key].as_array().map(|items| { + items + .iter() + .map(|item| { + item.as_str() + .map_or_else(|| item.to_string(), str::to_owned) + }) + .collect::>() + }) + }; + if let Some(hint) = details["hint"].as_str() { + text.push_str(&format!("\n hint: {hint}")); + } + if let Some(candidates) = list("candidates") { + if candidates.is_empty() { + text.push_str("\n candidates: none"); + } else { + text.push_str("\n candidates:"); + for candidate in candidates.iter().take(TEXT_CANDIDATES) { + text.push_str(&format!("\n {candidate}")); + } + let hidden = candidates.len().saturating_sub(TEXT_CANDIDATES); + if hidden > 0 || details["capped"] == true { + let more = if details["capped"] == true { "+" } else { "" }; + text.push_str(&format!( + "\n … {hidden}{more} more (`--json` lists up to 40)" + )); + } + } + } + for key in ["blocking", "file_access"] { + if let Some(items) = list(key) { + text.push_str(&format!("\n {key}: {}", items.join(" "))); + } + } + if let Some(items) = list("unrepresented") { + for item in items { + text.push_str(&format!("\n unrepresented: {item}")); + } + } + text +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn diagnostics_deduplicate_display_but_keep_counts() { + let value = json!({ + "errors": [{"code":"ARA107"},{"code":"ARA107"},{"code":"ARA109"}], + "warnings": [{"code":"ARA206"}], + }); + let summary = diagnostics(&value).unwrap(); + assert!(summary.contains("3 errors (ARA107×2, ARA109)"), "{summary}"); + assert!(summary.contains("1 warnings (ARA206)"), "{summary}"); + assert_eq!(summary.matches("ARA107").count(), 1); + assert!(diagnostics(&json!({"errors":[],"warnings":[]})).is_none()); + } + + #[test] + fn diagnostic_summaries_name_a_bounded_number_of_codes() { + let many: Vec = (100..130).map(|code| format!("ARA{code}")).collect(); + let mut rows: Vec = many.iter().map(|code| json!({"code": code})).collect(); + rows.push(json!({"code": "ARA100"})); + let summary = diagnostics(&json!({"errors": rows, "warnings": []})).unwrap(); + // The count keeps every diagnostic; the names stop at the cap. + assert!(summary.contains("31 errors (ARA100×2, "), "{summary}"); + assert_eq!(summary.matches("ARA1").count(), TEXT_CODES); + assert!(summary.contains(&format!("… {} more codes", 30 - TEXT_CODES))); + } + + #[test] + fn text_errors_keep_actionable_details() { + let error = AgentError { + details: Some(Box::new(json!({ + "candidates": ["C04", "logic/claims.md#h/Claims/C05"], + "capped": true, + "blocking": ["ARA100"], + "hint": "Run ara check", + }))), + ..AgentError::semantic("unknown_id", "Unknown") + }; + let text = super::error(&error); + let lines: Vec<&str> = text.lines().map(str::trim).collect(); + assert!(lines.contains(&"C04")); + assert!(lines.contains(&"logic/claims.md#h/Claims/C05")); + assert!(text.contains("ARA100") && text.contains("Run ara check")); + } +} diff --git a/crates/ara-cli/src/brief/show.rs b/crates/ara-cli/src/brief/show.rs new file mode 100644 index 0000000..2081790 --- /dev/null +++ b/crates/ara-cli/src/brief/show.rs @@ -0,0 +1,412 @@ +//! `show` blocks: a labeled header, the selected body and trailing metadata. +//! +//! A native source selection prints its exact bytes under a `source_digest` +//! with the write selector and scope that digest guards. An entry with no +//! native section prints a projection without any digest. +use serde_json::Value; +use std::io::Write; + +/// One selection's display. A byte budget pages the row's `content` before +/// rendering ([`crate::agent`] `window`), and each candidate page is +/// measured by rendering its blocks again. +pub struct Block { + pub header: Vec, + pub body: String, + pub trailer: Vec, +} +impl Block { + pub fn write(&self, out: &mut impl Write) -> std::io::Result<()> { + for line in &self.header { + writeln!(out, "{line}")?; + } + out.write_all(self.body.as_bytes())?; + if !self.body.is_empty() && !self.body.ends_with('\n') { + writeln!(out)?; + } + for line in &self.trailer { + writeln!(out, "{line}")?; + } + Ok(()) + } +} + +/// The blocks of a `show` value in request order: each selection, and an +/// `error` block for each address that failed in a partial read. +pub fn blocks(value: &Value) -> Vec { + let mut blocks = selections(value); + for failure in value["errors"].as_array().into_iter().flatten() { + // Failures are in request order, so every earlier address is + // already placed when this one is inserted. + let position = failure["position"].as_u64().unwrap_or(u64::MAX); + let at = usize::try_from(position).map_or(blocks.len(), |at| at.min(blocks.len())); + blocks.insert(at, failed(failure)); + } + blocks +} + +/// `==
[error]`, then the text the same error prints alone. +fn failed(failure: &Value) -> Block { + Block { + header: vec![format!( + "== {} [error]", + failure["address"].as_str().unwrap_or("") + )], + body: format!("{}\n", super::error_value(&failure["error"])), + trailer: vec![], + } +} + +fn selections(value: &Value) -> Vec { + value["entries"] + .as_array() + .into_iter() + .flatten() + .map(|row| { + if row["kind"] == "identity" { + return Block { + header: vec![], + body: format!( + "{} -> {}\n", + row["requested_address"].as_str().unwrap_or(""), + row["resolved_target"].as_str().unwrap_or("") + ), + trailer: vec![], + }; + } + let mut block = if row["kind"] == "source_document" { + source(row) + } else { + projection(row) + }; + if let Some(relations) = row["relations"].as_object() { + for (name, relation) in relations { + block.trailer.push(format!("{name}:")); + let mut rendered = Vec::new(); + match name.as_str() { + "path" => { + super::lists::path(relation, &mut rendered).expect("memory writer") + } + "refs" => { + super::lists::refs(relation, &mut rendered).expect("memory writer") + } + _ => block.trailer.push(format!(" {relation}")), + } + block.trailer.extend( + String::from_utf8(rendered) + .expect("text") + .lines() + .map(str::to_owned), + ); + } + } + block + }) + .collect() +} + +/// `--name value`, or `--name=value` when the value starts with `-` so a +/// parser cannot read it as a flag. +fn flag(name: &str, value: &Value) -> String { + let value = value.as_str().unwrap_or(""); + if value.starts_with('-') { + format!("--{name}={}", quote(value)) + } else { + format!("--{name} {}", quote(value)) + } +} + +/// Shell-quote one argument when it needs quoting. +pub fn quote(text: &str) -> String { + if !text.is_empty() + && text + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"_-./:@%+=,".contains(&b)) + { + text.to_owned() + } else { + format!("'{}'", text.replace('\'', r"'\''")) + } +} + +fn source(row: &Value) -> Block { + let display = &row["display"]; + let address = display["cited"] + .as_str() + .or(row["address"].as_str()) + .unwrap_or(""); + let label = match (&row["entry"], row["heading_path"].as_array()) { + (Value::Object(entry), _) => format!( + "{} {}", + entry["kind"].as_str().unwrap_or(""), + entry["id"].as_str().unwrap_or("") + ), + (_, Some(path)) if !path.is_empty() => "heading".into(), + _ => "document".into(), + }; + let mut header = vec![format!("== {address} [{label}]")]; + let path: Vec<&str> = row["heading_path"] + .as_array() + .into_iter() + .flatten() + .filter_map(Value::as_str) + .collect(); + if !path.is_empty() { + header.push(format!("heading: {}", path.join(" > "))); + } + let selector = match &display["selector"] { + Value::Object(selector) => { + let mut text = flag("document", selector.get("document").unwrap_or(&Value::Null)); + for segment in selector + .get("heading") + .and_then(Value::as_array) + .into_iter() + .flatten() + { + text.push(' '); + text.push_str(&flag("heading", segment)); + } + text + } + _ => format!( + "none ({})", + display["no_selector"] + .as_str() + .unwrap_or("no write selector") + ), + }; + if let Some(digest) = row["digest"].as_str() { + header.push(format!( + "source_digest={digest} scope={} selector: {selector}", + display["scope"].as_str().unwrap_or("selection") + )); + } + let mut trailer = Vec::new(); + trailer.extend(range(display)); + Block { + header, + body: row["content"].as_str().unwrap_or("").to_owned(), + trailer, + } +} + +/// `lines: S-E of N` for a windowed or paged selection, adding +/// `; truncated; next: --lines A:B` when lines remain. +fn range(display: &Value) -> Option { + let lines = display.get("lines")?; + let number = |key: &str| lines[key].as_u64().unwrap_or(0); + let (start, end, total) = (number("start"), number("end"), number("total")); + let mut text = if end < start { + format!("lines: none of {total}") + } else { + format!("lines: {start}-{end} of {total}") + }; + if let Some(next) = display["next"].as_str() { + text.push_str(&format!("; truncated; next: --lines {next}")); + } + Some(text) +} + +fn projection(row: &Value) -> Block { + let address = row["address"] + .as_str() + .or(row["id"].as_str()) + .or(row["key"].as_str()) + .unwrap_or(""); + let kind = row["kind"].as_str().unwrap_or(""); + let source = row["source"].as_str().unwrap_or(""); + let mut lines = Vec::new(); + if kind == "session" { + // A session's `body` is its whole YAML file, which the structured + // fields already show; the exact-source hint names the file. + let mut row = row.clone(); + if let Some(object) = row.as_object_mut() { + object.remove("body"); + } + fields(&row, 0, &mut lines); + } else { + fields(row, 0, &mut lines); + } + let mut body = lines.join("\n"); + if !body.is_empty() { + body.push('\n'); + } + Block { + header: vec![format!( + "== {address} [{kind}] projection of {source}; no source digest" + )], + body, + trailer: vec![format!( + "exact source: ara show --document {} --source", + quote(source) + )], + } +} + +/// `key: value` lines for an object; nested values indent by two spaces. +fn fields(value: &Value, depth: usize, lines: &mut Vec) { + let Some(object) = value.as_object() else { + return; + }; + let indent = " ".repeat(depth); + for (key, value) in object { + if depth == 0 + && matches!( + key.as_str(), + "id" | "key" | "kind" | "source" | "address" | "relations" + ) + { + continue; + } + match value { + Value::String(text) if text.contains('\n') => { + lines.push(format!("{indent}{key}: |")); + for line in text.lines() { + lines.push(format!("{indent} {line}")); + } + } + _ if empty(value) => {} + Value::Array(items) if items.iter().all(inline) => { + let items: Vec = items.iter().map(plain).collect(); + lines.push(format!("{indent}{key}: [{}]", items.join(", "))); + } + Value::Array(items) => { + lines.push(format!("{indent}{key}:")); + list(items, depth, lines); + } + Value::Object(_) => { + lines.push(format!("{indent}{key}:")); + fields(value, depth + 1, lines); + } + _ => lines.push(format!("{indent}{key}: {}", plain(value))), + } + } +} +/// `- item` lines two spaces under `depth`; a nested list renders +/// recursively so none of its values are dropped. +fn list(items: &[Value], depth: usize, lines: &mut Vec) { + let indent = " ".repeat(depth); + for item in items.iter().filter(|item| !empty(item)) { + match item { + _ if scalar(item) => lines.push(format!("{indent} - {}", plain(item))), + Value::String(text) => { + lines.push(format!("{indent} - |")); + for line in text.lines() { + lines.push(format!("{indent} {line}")); + } + } + Value::Array(inner) if inner.iter().all(inline) => { + let inner: Vec = inner.iter().map(plain).collect(); + lines.push(format!("{indent} - [{}]", inner.join(", "))); + } + Value::Array(inner) => { + lines.push(format!("{indent} -")); + list(inner, depth + 1, lines); + } + _ => { + lines.push(format!("{indent} -")); + fields(item, depth + 2, lines); + } + } + } +} +fn empty(value: &Value) -> bool { + match value { + Value::Null => true, + Value::String(text) => text.is_empty(), + Value::Array(items) => items.is_empty(), + Value::Object(items) => items.values().all(empty), + _ => false, + } +} +fn scalar(value: &Value) -> bool { + !value.is_array() && !value.is_object() && !value.as_str().is_some_and(|s| s.contains('\n')) +} +/// A scalar that reads unambiguously inside `[a, b]`. +fn inline(value: &Value) -> bool { + scalar(value) && !plain(value).contains([',', '[', ']']) +} +fn plain(value: &Value) -> String { + value + .as_str() + .map_or_else(|| value.to_string(), str::to_owned) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn rendered(value: Value) -> Vec { + let mut lines = Vec::new(); + fields(&value, 0, &mut lines); + lines + } + + #[test] + fn list_items_keep_multiline_text_and_ambiguous_scalars_become_lists() { + assert_eq!( + rendered(json!({"evidence": ["first line\nsecond line", "one"]})), + [ + "evidence:", + " - |", + " first line", + " second line", + " - one" + ] + ); + assert_eq!(rendered(json!({"tags": ["a", "b"]})), ["tags: [a, b]"]); + assert_eq!( + rendered(json!({"tags": ["a, b", "c"]})), + ["tags:", " - a, b", " - c"] + ); + assert_eq!(rendered(json!({"tags": ["[x]"]})), ["tags:", " - [x]"]); + } + + #[test] + fn nested_list_items_keep_their_values() { + assert_eq!( + rendered(json!({"events": [["a", "b"], ["c", ["d", "e, f"], {"k": "v"}]]})), + [ + "events:", + " - [a, b]", + " -", + " - c", + " -", + " - d", + " - e, f", + " -", + " k: v", + ] + ); + } + + #[test] + fn source_blocks_keep_exact_bodies_and_projections_have_no_digest() { + let body = "line one\r\nline two"; + let source = blocks(&json!({"entries":[{ + "kind":"source_document","address":"d.md#h/A","heading_path":["A"], + "document":"d.md","digest":"sha256:ab","content":body, + "display":{"scope":"heading_body","selector":{"document":"d.md","heading":["A b"]}}, + }]})); + assert_eq!(source[0].body, body); + assert!(source[0].header.iter().any( + |line| line.contains("source_digest=sha256:ab") && line.contains("--heading 'A b'") + )); + let projection = blocks(&json!({"entries":[{ + "id":"N01","kind":"question","source":"trace/exploration_tree.yaml","title":"T", + }]})); + let text: String = projection[0].header.join("\n") + &projection[0].body; + assert!(!text.contains("source_digest") && !text.contains("sha256:")); + assert!(projection[0].trailer[0].contains("--source")); + } + + #[test] + fn quoting_round_trips_through_a_posix_shell_reader() { + assert_eq!(quote("C04"), "C04"); + assert_eq!(quote("it's"), r"'it'\''s'"); + assert_eq!(quote(""), "''"); + assert_eq!(flag("heading", &json!("-foo")), "--heading=-foo"); + assert_eq!(flag("heading", &json!("- a")), "--heading='- a'"); + assert_eq!(flag("document", &json!("d.md")), "--document d.md"); + } +} diff --git a/crates/ara-cli/src/context.rs b/crates/ara-cli/src/context.rs new file mode 100644 index 0000000..73cf56e --- /dev/null +++ b/crates/ara-cli/src/context.rs @@ -0,0 +1,100 @@ +//! Shared discovery for agent commands. Reads never provision operational files. +use std::path::{Path, PathBuf}; + +use crate::output::AgentError; + +pub fn discover(explicit: Option<&Path>) -> Result { + discover_with_mode(explicit, false) +} + +pub fn discover_writer(explicit: Option<&Path>) -> Result { + discover_with_mode(explicit, true) +} +/// Explicit source inspection also supports a partially initialized knowledge +/// root; structural discovery still requires an exploration tree. +pub fn discover_source(explicit: Option<&Path>) -> Result { + let cwd = std::env::current_dir().map_err(|error| AgentError::io(error.to_string()))?; + let selected = explicit + .map(Path::to_path_buf) + .or_else(|| std::env::var_os("ARA_DIR").map(PathBuf::from)); + if let Some(selected) = selected { + let selected = cwd.join(selected); + let metadata = std::fs::symlink_metadata(&selected) + .map_err(|error| AgentError::io(format!("{}: {error}", selected.display())))?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(AgentError::setup( + "invalid_artifact_path", + "Source root must be a real directory", + )); + } + let root = selected + .canonicalize() + .map_err(|error| AgentError::io(error.to_string()))?; + ensure_no_pending_transaction(&root)?; + Ok(root) + } else { + discover(None) + } +} + +fn discover_with_mode(explicit: Option<&Path>, writer: bool) -> Result { + let cwd = std::env::current_dir().map_err(|e| AgentError::io(e.to_string()))?; + if let Some(path) = explicit { + return validate_with_mode(&cwd.join(path), writer); + } + if let Some(path) = std::env::var_os("ARA_DIR") { + return validate_with_mode(&cwd.join(path), writer); + } + for ancestor in cwd.ancestors() { + for candidate in [ancestor.to_path_buf(), ancestor.join("ara")] { + if candidate.join("trace/exploration_tree.yaml").is_file() { + return validate_with_mode(&candidate, writer); + } + } + } + Err(AgentError::setup( + "discovery_failed", + "No ARA found; use -C or ARA_DIR", + )) +} + +pub fn validate(path: &Path) -> Result { + validate_with_mode(path, false) +} + +fn validate_with_mode(path: &Path, writer: bool) -> Result { + let metadata = std::fs::symlink_metadata(path) + .map_err(|error| AgentError::io(format!("{}: {error}", path.display())))?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(AgentError::setup( + "invalid_artifact_path", + "Artifact root must be a real directory", + )); + } + let root = path + .canonicalize() + .map_err(|e| AgentError::io(format!("{}: {e}", path.display())))?; + if !root.join("trace/exploration_tree.yaml").is_file() { + return Err(AgentError::setup( + "invalid_artifact_path", + format!( + "{} does not contain trace/exploration_tree.yaml", + root.display() + ), + )); + } + if !writer { + ensure_no_pending_transaction(&root)?; + } + Ok(root) +} + +pub fn ensure_no_pending_transaction(root: &Path) -> Result<(), AgentError> { + if ara_core::write::journal::pending_prepared(root).map_err(crate::write::convert_error)? { + return Err(AgentError::setup( + "pending_transaction", + "A prepared transaction requires recovery by an ara writer before reading", + )); + } + Ok(()) +} diff --git a/crates/ara-cli/src/lib.rs b/crates/ara-cli/src/lib.rs new file mode 100644 index 0000000..e3178da --- /dev/null +++ b/crates/ara-cli/src/lib.rs @@ -0,0 +1,8 @@ +//! Reusable native agent interface. Command parsing and printing remain adapters. +pub mod agent; +mod brief; +pub mod context; +pub mod merge; +pub mod output; +pub mod search; +pub mod write; diff --git a/crates/ara-cli/src/main.rs b/crates/ara-cli/src/main.rs index 786a60c..1b3fba3 100644 --- a/crates/ara-cli/src/main.rs +++ b/crates/ara-cli/src/main.rs @@ -8,6 +8,7 @@ mod check; mod check_config; mod serve; +use ara_cli::{agent, context, merge, output, write}; use std::path::PathBuf; use std::process::ExitCode; @@ -18,6 +19,9 @@ use clap::{Parser, Subcommand}; #[derive(Parser)] #[command(name = "ara", version, about = "ARA viewer runtime")] struct Cli { + /// Select the ARA directory for agent commands. + #[arg(short = 'C', global = true)] + directory: Option, #[command(subcommand)] command: Command, } @@ -32,6 +36,24 @@ enum Command { Check(check::CheckArgs), /// Serve an ARA directory with a live-reloading web viewer. Serve(serve::ServeArgs), + /// Summarize layer counts, diagnostics, and next-ID advice. + Status(agent::ReadOptions), + /// List source-order entries with intersecting structural filters. + Ls(agent::ListArgs), + /// Retrieve complete entries or bounded source documents. + Show(agent::ShowArgs), + /// Rank knowledge entries with offline BM25 keyword search. + Find(agent::FindArgs), + /// Edit mutable logic or permitted metadata fields. + Edit(write::EditArgs), + /// Update claims. + Claim(write::LogicArgs), + /// Update heuristics. + Heuristic(write::LogicArgs), + /// Apply an all-or-none typed JSONL batch. + Apply(write::ApplyArgs), + /// Merge complete knowledge layers from directories or local Git objects. + Merge(merge::MergeArgs), } #[derive(clap::Args)] @@ -58,13 +80,159 @@ struct LayoutArgs { json: bool, } +fn agent_command( + directory: Option<&std::path::Path>, + format: &str, + options: &agent::ReadOptions, + writer: bool, + command: impl FnOnce(&std::path::Path) -> Result, +) -> ExitCode { + let result = if writer { + context::discover_writer(directory) + } else { + context::discover(directory) + } + .and_then(|root| command(&root)); + // A structural read over an incomplete optional layer is a warning: its + // `complete: false` and `incomplete` report the gap without failing. + let incomplete = result.as_ref().is_ok_and(|value| { + format == "ara.status/v1" && value.get("complete") == Some(&serde_json::Value::Bool(false)) + || format == "ara.show/v1" + && value + .get("errors") + .and_then(serde_json::Value::as_array) + .is_some_and(|errors| !errors.is_empty()) + || value + .get("unresolved_count") + .and_then(serde_json::Value::as_u64) + .is_some_and(|count| count > 0) + }); + let exit = output::emit(format, result, options.json, options.fields.as_deref()); + if exit == ExitCode::SUCCESS && incomplete { + ExitCode::FAILURE + } else { + exit + } +} + +fn argument_command(args: &[std::ffi::OsString]) -> Option<&str> { + let mut arguments = args.iter().skip(1); + while let Some(argument) = arguments.next() { + let argument = argument.to_str()?; + if argument == "-C" { + arguments.next(); + continue; + } + if !argument.starts_with('-') { + return Some(argument); + } + } + None +} + fn main() -> ExitCode { - let cli = Cli::parse(); + let cli = match Cli::try_parse() { + Ok(cli) => cli, + Err(error) => { + let args = std::env::args_os().collect::>(); + let command = argument_command(&args).unwrap_or("cli"); + let legacy = matches!(command, "validate" | "layout" | "check" | "serve"); + if error.exit_code() != 0 && !legacy && args.iter().any(|arg| arg == "--json") { + return output::emit( + &format!("ara.{command}/v1"), + Err(output::AgentError::setup( + "argument_error", + error.to_string(), + )), + true, + None, + ); + } + error.exit(); + } + }; + let directory = cli.directory.as_deref(); + let heuristic = matches!(&cli.command, Command::Heuristic(_)); match cli.command { Command::Validate(args) => validate(args), Command::Layout(args) => layout_cmd(args), Command::Check(args) => check::run(args), Command::Serve(args) => serve::run(args), + Command::Status(args) => agent_command(directory, "ara.status/v1", &args, false, |root| { + agent::status(root, args.brief()) + }), + Command::Ls(args) => agent_command(directory, "ara.ls/v1", &args.output, false, |root| { + agent::list(root, &args) + }), + Command::Show(args) => { + if args.identity && args.ids.len() != 1 { + return output::emit( + "ara.show/v1", + Err(output::AgentError::setup( + "argument_error", + "--identity requires exactly one positional address", + )), + args.output.json, + args.output.fields.as_deref(), + ); + } + if args.source { + let result = + context::discover_source(directory).and_then(|root| agent::show(&root, &args)); + output::emit( + "ara.show/v1", + result, + args.output.json, + args.output.fields.as_deref(), + ) + } else { + agent_command(directory, "ara.show/v1", &args.output, false, |root| { + agent::show(root, &args) + }) + } + } + Command::Find(args) => { + agent_command(directory, "ara.find/v1", &args.output, false, |root| { + agent::find(root, &args) + }) + } + Command::Edit(args) => { + agent_command(directory, "ara.edit/v1", &args.output, true, |root| { + write::edit(root, &args) + }) + } + Command::Claim(args) | Command::Heuristic(args) => { + let options = match &args.command { + write::LogicCommand::Set(set) => &set.output, + }; + agent_command( + directory, + if heuristic { + "ara.heuristic/v1" + } else { + "ara.claim/v1" + }, + options, + true, + |root| write::logic(root, &args, heuristic), + ) + } + Command::Apply(args) => output::emit( + "ara.apply/v1", + write::apply_discover(directory, &args), + args.output.json, + args.output.fields.as_deref(), + ), + Command::Merge(args) => { + let options = match args.command.as_deref() { + Some(merge::MergeCommand::Resolve(resolution)) => &resolution.output, + Some(merge::MergeCommand::Repair(repair)) => &repair.output, + None => &args.output, + }; + agent_command(directory, "ara.merge/v1", options, !args.dry_run, |root| { + merge::run(root, &args) + }) + } } } diff --git a/crates/ara-cli/src/merge.rs b/crates/ara-cli/src/merge.rs new file mode 100644 index 0000000..189e2dc --- /dev/null +++ b/crates/ara-cli/src/merge.rs @@ -0,0 +1,399 @@ +//! Native inputs and transaction adapter for one source-aware merge planner. +pub mod git; +use crate::agent::ReadOptions; +use crate::output::AgentError; +use ara_core::merge::{self, MergeOptions}; +use ara_core::write::{ArtifactLock, ArtifactSnapshot}; +use serde_json::{Value, json}; +use std::path::{Path, PathBuf}; + +#[derive(Debug, clap::Args)] +pub struct MergeArgs { + // Conflict-only payloads must not inflate every read or ordinary merge. + #[command(subcommand)] + pub command: Option>, + #[arg(long, conflicts_with = "git", requires = "theirs")] + pub base: Option, + #[arg(long, conflicts_with = "git", requires = "base")] + pub theirs: Option, + #[arg(long,conflicts_with_all=["base","theirs"])] + pub git: Option, + #[arg(long = "as")] + pub label: Option, + #[arg(long)] + pub source_key: Option, + #[arg(long)] + pub dry_run: bool, + #[arg(long)] + pub no_duplicate_check: bool, + #[command(flatten)] + pub output: ReadOptions, +} +#[derive(Debug, clap::Subcommand)] +pub enum MergeCommand { + Resolve(ConflictArgs), + Repair(RepairArgs), +} +#[derive(Debug, clap::Args)] +pub struct ConflictArgs { + pub conflict: String, + #[arg(long,value_parser=["ours","theirs","base"])] + pub take: String, + #[command(flatten)] + pub audit: AuditArgs, + #[command(flatten)] + pub output: ReadOptions, +} +/// Owning-turn context shared by `merge resolve` and `merge repair`. +#[derive(Debug, clap::Args)] +pub struct AuditArgs { + /// Open session that owns the audit turn (never selected or created). + #[arg(long)] + pub session: String, + /// Optional; when given it must equal the session's next turn. + #[arg(long)] + pub turn: Option, + /// Turn timestamp; defaults to the writer's locked UTC clock. + #[arg(long)] + pub timestamp: Option, + /// New rolling session summary; omitted keeps the current one. + #[arg(long)] + pub summary: Option, + #[arg(long)] + pub signal: String, + #[arg(long)] + pub provenance: String, +} +impl AuditArgs { + fn owner(&self) -> merge::AuditOwner { + merge::AuditOwner { + session: self.session.clone(), + turn: self.turn, + timestamp: self.timestamp.clone(), + summary: self.summary.clone(), + signal: self.signal.clone(), + provenance: self.provenance.clone(), + } + } +} +#[derive(Debug, clap::Args)] +pub struct RepairArgs { + #[arg(long)] + pub conflict_file: PathBuf, + #[arg(long,value_parser=["reject_incoming","restore_base"])] + pub decision: String, + #[arg(long)] + pub expected_current: String, + #[command(flatten)] + pub audit: AuditArgs, + #[arg(long)] + pub reason: String, + #[command(flatten)] + pub output: ReadOptions, +} +pub fn convert_error(error: merge::MergeError) -> AgentError { + let exit = error.exit_code(); + let details = serde_json::to_value(&error).ok().map(Box::new); + AgentError { + exit, + code: error.code, + message: error.message, + id: None, + line: None, + details, + summary: None, + } +} +fn fingerprint(snapshot: &ArtifactSnapshot) -> Vec<(&str, &str)> { + snapshot + .files + .iter() + .map(|(path, file)| (path.as_str(), file.digest.as_str())) + .collect() +} +fn disjoint_roots(roots: &[&Path]) -> Result<(), AgentError> { + for (i, left) in roots.iter().enumerate() { + for right in roots.iter().skip(i + 1) { + if left.starts_with(right) || right.starts_with(left) { + return Err(AgentError::semantic( + "overlapping_inputs", + "Base, ours, and theirs must be nonoverlapping roots", + )); + } + } + } + Ok(()) +} +pub fn run(root: &Path, args: &MergeArgs) -> Result { + if let Some(command) = args.command.as_deref() { + return match command { + MergeCommand::Resolve(resolution) => resolve_conflict(root, resolution), + MergeCommand::Repair(repair) => repair_protected(root, repair), + }; + } + let operation_started = std::time::Instant::now(); + let git_inputs = args + .git + .as_deref() + .map(|reference| git::prepare_git_inputs(root, reference)) + .transpose()?; + let (base_root, theirs_root) = if let Some(inputs) = &git_inputs { + (inputs.base_dir.clone(), inputs.theirs_dir.clone()) + } else { + let base = args.base.as_deref().ok_or_else(|| { + AgentError::semantic("missing_merge_mode", "Supply --base and --theirs, or --git") + })?; + let theirs = args + .theirs + .as_deref() + .ok_or_else(|| AgentError::semantic("missing_merge_mode", "Supply --theirs"))?; + ( + crate::context::validate(base)?, + crate::context::validate(theirs)?, + ) + }; + disjoint_roots(&[root, &base_root, &theirs_root])?; + crate::context::ensure_no_pending_transaction(&base_root)?; + crate::context::ensure_no_pending_transaction(&theirs_root)?; + let base = ArtifactSnapshot::load_complete(&base_root).map_err(crate::write::convert_error)?; + let theirs = + ArtifactSnapshot::load_complete(&theirs_root).map_err(crate::write::convert_error)?; + let lock = if args.dry_run { + None + } else { + Some(ArtifactLock::acquire(root).map_err(crate::write::convert_error)?) + }; + if args.dry_run { + crate::context::ensure_no_pending_transaction(root)?; + } else { + ara_core::write::journal::recover(root).map_err(crate::write::convert_error)?; + } + let ours = ArtifactSnapshot::load_complete(root).map_err(crate::write::convert_error)?; + if let Some(inputs) = &git_inputs { + git::recheck_head(inputs)?; + } + let source_key = args.source_key.as_ref().ok_or_else(|| { + AgentError::semantic( + "source_identity_required", + "Use --source-key with a stable fork identity; --as is only a display label", + ) + })?; + let history = merge::source_history(&ours, source_key).map_err(convert_error)?; + let predecessor = if let Some(history) = history { + if let Some(inputs) = &git_inputs { + if let Some(previous) = history.git.as_ref() { + git::check_source_lineage(inputs, previous)?; + } else { + return Err(AgentError::semantic( + "source_identity_conflict", + "Source was enrolled without Git provenance; explicit reviewed reenrollment required", + )); + } + Some(history.fingerprint) + } else { + None + } + } else { + None + }; + let label = args + .label + .clone() + .or_else(|| args.git.clone()) + .or_else(|| { + theirs_root + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + }) + .ok_or_else(|| AgentError::semantic("invalid_label", "Supply --as"))?; + let options = MergeOptions { + source_key: source_key.clone(), + label, + time: ara_core::write::clock::system_utc().map_err(crate::write::convert_error)?, + git: git_inputs.as_ref().map(|inputs| inputs.provenance.clone()), + predecessor, + }; + let loaded_at = std::time::Instant::now(); + let mut planned_at = None; + let mut validated_at = None; + let mut plan = + merge::plan_merge_with_observer(&base, &ours, &theirs, &options, |phase| match phase { + merge::MergePhase::PlanningFinished => planned_at = Some(std::time::Instant::now()), + merge::MergePhase::ValidationFinished => validated_at = Some(std::time::Instant::now()), + }) + .map_err(convert_error)?; + let plan_returned = std::time::Instant::now(); + let planned_at = planned_at.unwrap_or(plan_returned); + let validated_at = validated_at.unwrap_or(plan_returned); + let recheck_started = std::time::Instant::now(); + let fresh_base = + ArtifactSnapshot::load_complete(&base_root).map_err(crate::write::convert_error)?; + let fresh_theirs = + ArtifactSnapshot::load_complete(&theirs_root).map_err(crate::write::convert_error)?; + if fingerprint(&base) != fingerprint(&fresh_base) + || fingerprint(&theirs) != fingerprint(&fresh_theirs) + { + return Err(AgentError::semantic( + "stale_merge_input", + "A source changed during capture; no destination changes committed", + )); + } + if let Some(inputs) = &git_inputs { + git::recheck_head(inputs)?; + } + plan.working + .plan_missing_directories() + .map_err(crate::write::convert_error)?; + let rechecked_at = std::time::Instant::now(); + let should_commit = !args.dry_run + && (!plan.working.changed_paths().is_empty() || !plan.working.created_dirs.is_empty()); + if should_commit { + plan.working + .include_operational_ignore() + .map_err(crate::write::convert_error)?; + } + let duplicate_check = + !args.no_duplicate_check && std::env::var("ARA_NO_DUPLICATE_CHECK").as_deref() != Ok("1"); + let validation = &plan.validation; + let advice = || { + let started = std::time::Instant::now(); + let candidates = duplicate_check.then(|| { + crate::write::duplicate_candidates_from_manifests( + validation.base_manifest.as_ref(), + &validation.candidate_manifest, + ) + }); + (candidates, started.elapsed().as_secs_f64() * 1000.0) + }; + let commit = || { + let started = std::time::Instant::now(); + if should_commit { + ara_core::write::transaction::commit(&plan.working) + .map_err(crate::write::convert_error)?; + Ok(started.elapsed().as_secs_f64() * 1000.0) + } else { + Ok(0.0) + } + }; + let (commit_ms, candidates, advisory_ms) = + if should_commit && duplicate_check && validation.candidate_manifest.nodes.len() >= 1000 { + std::thread::scope(|scope| { + let worker = scope.spawn(advice); + let committed = commit(); + let advised = worker.join(); + let commit_ms = committed?; + let (candidates, advisory_ms) = + advised.unwrap_or_else(|panic| std::panic::resume_unwind(panic)); + Ok::<_, AgentError>((commit_ms, candidates, advisory_ms)) + })? + } else { + let commit_ms = commit()?; + let (candidates, advisory_ms) = advice(); + (commit_ms, candidates, advisory_ms) + }; + plan.report.committed = !args.dry_run; + plan.report.dry_run = args.dry_run; + let mut report = serde_json::to_value(&plan.report).expect("merge report serialization"); + if !plan.working.created_dirs.is_empty() { + report.as_object_mut().unwrap().insert( + "created_directories".into(), + json!(plan.working.created_dirs), + ); + } + if let Some(candidates) = candidates { + match candidates { + Ok(candidates) => { + report + .as_object_mut() + .unwrap() + .insert("duplicate_candidates".into(), json!(candidates)); + } + Err(error) => { + report.as_object_mut().unwrap().insert( + "advisories".into(), + json!([format!("duplicate_advisory_unavailable: {error}")]), + ); + } + } + } + report.as_object_mut().unwrap().insert("timings".into(),json!({ + "load_ms":loaded_at.duration_since(operation_started).as_secs_f64()*1000.0, + "planning_ms":planned_at.duration_since(loaded_at).as_secs_f64()*1000.0, + "validation_ms":validated_at.duration_since(planned_at).as_secs_f64()*1000.0, + "input_recheck_ms":rechecked_at.duration_since(recheck_started).as_secs_f64()*1000.0, + "commit_ms":commit_ms,"advisory_ms":advisory_ms,"operation_ms":operation_started.elapsed().as_secs_f64()*1000.0, + })); + if let Some(inputs) = &git_inputs { + report.as_object_mut().unwrap().insert( + "git_timings".into(), + serde_json::to_value(&inputs.timings).expect("Git timings serialize"), + ); + } + drop(lock); + Ok(report) +} +fn resolve_conflict(root: &Path, args: &ConflictArgs) -> Result { + let (lock, batch_time) = + ara_core::write::lock_and_capture(root, ara_core::write::clock::system_utc) + .map_err(crate::write::convert_error)?; + let snapshot = ArtifactSnapshot::load_complete(root).map_err(crate::write::convert_error)?; + let merge::AuditedResolution { + mut working, + session, + turn, + } = merge::plan_resolution( + &snapshot, + &args.conflict, + &args.take, + &args.audit.owner(), + &batch_time, + ) + .map_err(convert_error)?; + working + .include_operational_ignore() + .map_err(crate::write::convert_error)?; + working + .plan_missing_directories() + .map_err(crate::write::convert_error)?; + ara_core::write::transaction::commit(&working).map_err(crate::write::convert_error)?; + let changed_paths = working.changed_paths(); + drop(lock); + Ok( + json!({"format":"ara.merge/v1","committed":true,"conflict":args.conflict,"take":args.take,"session":session,"turn":turn,"changed_paths":changed_paths}), + ) +} +fn repair_protected(root: &Path, args: &RepairArgs) -> Result { + let bytes = std::fs::read(&args.conflict_file).map_err(|e| AgentError::io(e.to_string()))?; + let conflict: merge::MergeConflict = serde_json::from_slice(&bytes) + .map_err(|e| AgentError::semantic("invalid_conflict_record", e.to_string()))?; + let (lock, batch_time) = + ara_core::write::lock_and_capture(root, ara_core::write::clock::system_utc) + .map_err(crate::write::convert_error)?; + let snapshot = ArtifactSnapshot::load_complete(root).map_err(crate::write::convert_error)?; + let merge::AuditedResolution { + mut working, + session, + turn, + } = merge::plan_protected_resolution( + &snapshot, + &conflict, + &args.decision, + &args.expected_current, + &args.audit.owner(), + &args.reason, + &batch_time, + ) + .map_err(convert_error)?; + working + .include_operational_ignore() + .map_err(crate::write::convert_error)?; + working + .plan_missing_directories() + .map_err(crate::write::convert_error)?; + ara_core::write::transaction::commit(&working).map_err(crate::write::convert_error)?; + let changed_paths = working.changed_paths(); + drop(lock); + Ok( + json!({"format":"ara.merge/v1","committed":true,"decision":args.decision,"session":session,"turn":turn,"changed_paths":changed_paths}), + ) +} diff --git a/crates/ara-cli/src/merge/git.rs b/crates/ara-cli/src/merge/git.rs new file mode 100644 index 0000000..a3d4fb4 --- /dev/null +++ b/crates/ara-cli/src/merge/git.rs @@ -0,0 +1,917 @@ +//! Local-only Git plumbing for the directory merger. Never reconstructs ours. +use std::collections::BTreeSet; +use std::ffi::OsStr; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::path::{Component, Path, PathBuf}; +use std::process::{Child, ChildStdout, Command, ExitStatus, Stdio}; +use std::thread::{self, JoinHandle}; +use std::time::Instant; + +use ara_core::merge::GitMergeProvenance; +use serde::Serialize; +use tempfile::TempDir; + +use crate::output::AgentError; + +// Git 2.45 introduced --no-lazy-fetch; it sets fetch_if_missing=0 as well as +// GIT_NO_LAZY_FETCH. Earlier Git must not be allowed to contact promisor remotes. +// https://github.com/git/git/blob/v2.45.0/Documentation/RelNotes/2.45.0.txt +const MIN_GIT_VERSION: (u32, u32) = (2, 45); +const STDERR_LIMIT: usize = 4096; +const RECORD_LIMIT: usize = 64 * 1024; +const QUERY_LIMIT: usize = 1024 * 1024; +const TREE_FILE: &str = "trace/exploration_tree.yaml"; + +/// Measured native input-capture wall spans, never source identity metadata. +/// +/// Tree capture and blob materialization run concurrently for each snapshot. +/// Their cumulative spans overlap and include stream backpressure; adding them +/// does not give total elapsed time. Use total_materialize_ms/total_setup_ms for +/// enclosing durations. merge_base_ms includes the complete ancestry traversal. +#[derive(Debug, Clone, Default, Serialize)] +pub struct GitInputTimings { + pub ref_resolution_ms: f64, + pub merge_base_ms: f64, + pub tree_capture_ms: f64, + pub blob_materialize_ms: f64, + pub total_materialize_ms: f64, + pub total_setup_ms: f64, +} + +fn elapsed_ms(start: Instant) -> f64 { + start.elapsed().as_secs_f64() * 1_000.0 +} + +/// Owns both private input trees for the entire planning/commit lifetime. +#[derive(Debug)] +pub struct GitMergeInputs { + pub base_dir: PathBuf, + pub theirs_dir: PathBuf, + pub provenance: GitMergeProvenance, + pub timings: GitInputTimings, + repository: PathBuf, + _temporary_root: TempDir, +} + +/// Pins ancestry, validates local history, and extracts raw committed bytes. +/// The destination, index, refs, and Git merge state are never written. +pub fn prepare_git_inputs( + destination: &Path, + reference: &str, +) -> Result { + let setup_started = Instant::now(); + let mut timings = GitInputTimings::default(); + let destination = fs::canonicalize(destination) + .map_err(|_| AgentError::io("Cannot open the destination artifact directory"))?; + if !destination.is_dir() { + return Err(AgentError::setup( + "git_worktree_required", + "Git merge requires an artifact directory inside a non-bare Git working tree", + )); + } + check_version(&destination)?; + let inside = query(&destination, &["rev-parse", "--is-inside-work-tree"])?; + if trim_line(&inside)? != b"true" { + return Err(AgentError::setup( + "git_worktree_required", + "Git merge requires a non-bare Git working tree", + )); + } + let top = query( + &destination, + &["rev-parse", "--path-format=absolute", "--show-toplevel"], + )?; + let repository = fs::canonicalize(path_from_bytes(trim_line(&top)?)?) + .map_err(|_| AgentError::io("Cannot open the Git working-tree root"))?; + let relative = destination.strip_prefix(&repository).map_err(|_| { + AgentError::setup( + "git_worktree_required", + "The selected artifact is outside the Git working tree", + ) + })?; + let repo_relative_root = relative_path(relative)?; + let superproject = query( + &repository, + &["rev-parse", "--show-superproject-working-tree"], + )?; + if !superproject.is_empty() && !trim_line(&superproject)?.is_empty() { + return Err(AgentError::semantic( + "git_submodule", + "An artifact inside a submodule is not supported by Git merge", + )); + } + require_complete_history(&repository)?; + let resolution_started = Instant::now(); + let head = resolve_commit(&repository, "HEAD", "HEAD is unborn or unavailable locally")?; + let theirs = resolve_commit( + &repository, + reference, + "The requested Git revision is not a locally available commit", + )?; + timings.ref_resolution_ms = elapsed_ms(resolution_started); + let ancestry_started = Instant::now(); + // Walking both complete ancestor graphs catches missing commits even when + // merge-base could answer before encountering an absent ancestor. + let mut history = GitChild::spawn(&repository, &["rev-list", &head, &theirs, "--"], false)?; + io::copy(&mut history.stdout, &mut io::sink()) + .map_err(|_| AgentError::io("Cannot read local Git ancestry"))?; + history.finish("Local Git ancestry is incomplete or unreadable")?; + let mut bases = GitChild::spawn(&repository, &["merge-base", "--all", &head, &theirs], false)?; + let data = read_bounded(&mut bases.stdout, QUERY_LIMIT, "Git merge-base output")?; + let (status, stderr) = bases.complete()?; + if status.code() == Some(1) && data.is_empty() { + return Err(AgentError::semantic( + "git_unrelated_history", + "HEAD and the pinned source commit have no common ancestor", + )); + } + require_success(status, &stderr, "Cannot obtain a local Git merge base")?; + let base_ids: Vec<&[u8]> = data + .split(|byte| *byte == b'\n') + .filter(|line| !line.is_empty()) + .collect(); + if base_ids.len() != 1 { + return Err(AgentError::semantic( + "git_ambiguous_base", + "Git merge requires exactly one merge base; criss-cross ancestry is unsupported", + )); + } + let base = object_id(base_ids[0])?; + timings.merge_base_ms = elapsed_ms(ancestry_started); + check_unmerged(&repository, &repo_relative_root)?; + + let materialization_started = Instant::now(); + // Validate the OS temporary location before creating anything. In particular, + // an inherited TMPDIR inside the artifact cannot cause a dry-run mutation. + let temporary_parent = fs::canonicalize(std::env::temp_dir()) + .map_err(|_| AgentError::io("Cannot open the OS temporary directory"))?; + if temporary_parent.starts_with(&repository) + || temporary_parent.starts_with(&destination) + || temporary_parent + .components() + .any(|part| part.as_os_str() == OsStr::new(".git")) + { + return Err(AgentError::setup( + "unsafe_temporary_directory", + "Git merge needs an OS temporary directory outside the repository and artifact", + )); + } + let temporary_root = tempfile::Builder::new() + .prefix("ara-git-") + .tempdir_in(temporary_parent) + .map_err(|_| AgentError::io("Cannot create private Git input storage"))?; + set_private_permissions(temporary_root.path())?; + let base_dir = temporary_root.path().join("base"); + let theirs_dir = temporary_root.path().join("theirs"); + fs::create_dir(&base_dir) + .and_then(|()| fs::create_dir(&theirs_dir)) + .map_err(|_| AgentError::io("Cannot create private Git input trees"))?; + materialize( + &repository, + &base, + &repo_relative_root, + &base_dir, + &mut timings, + )?; + materialize( + &repository, + &theirs, + &repo_relative_root, + &theirs_dir, + &mut timings, + )?; + timings.total_materialize_ms = elapsed_ms(materialization_started); + timings.total_setup_ms = elapsed_ms(setup_started); + Ok(GitMergeInputs { + base_dir, + theirs_dir, + provenance: GitMergeProvenance { + repo_relative_root, + head, + theirs, + base, + }, + timings, + repository, + _temporary_root: temporary_root, + }) +} + +/// Call under the destination writer lock, and again immediately before commit. +/// Movement of the source ref is harmless; movement of HEAD invalidates ancestry. +pub fn recheck_head(inputs: &GitMergeInputs) -> Result<(), AgentError> { + let current = resolve_commit( + &inputs.repository, + "HEAD", + "HEAD became unavailable during Git merge", + )?; + if current != inputs.provenance.head { + return Err(AgentError::semantic( + "git_head_changed", + "HEAD changed after Git merge inputs were captured; no merge may be committed", + )); + } + check_unmerged(&inputs.repository, &inputs.provenance.repo_relative_root) +} + +/// Proves advancement of an already enrolled source key without treating a ref +/// name, filesystem location, or repository URL as portable fork identity. +pub fn check_source_advancement( + inputs: &GitMergeInputs, + previous_theirs: &str, +) -> Result<(), AgentError> { + validated_object_id(previous_theirs.as_bytes())?; + if previous_theirs == inputs.provenance.theirs { + return Ok(()); + } + require_complete_history(&inputs.repository)?; + let previous = resolve_commit( + &inputs.repository, + previous_theirs, + "The enrolled source commit is unavailable locally; its ancestry cannot be proved", + )?; + if previous != previous_theirs { + return Err(AgentError::semantic( + "git_source_lineage", + "The recorded source revision is not a full immutable commit ID", + )); + } + // prepare_git_inputs already traversed the complete pinned source graph. + // Do not walk its entire history a second time for source-key enrollment. + let mut child = GitChild::spawn( + &inputs.repository, + &[ + "merge-base", + "--is-ancestor", + &previous, + &inputs.provenance.theirs, + ], + false, + )?; + io::copy(&mut child.stdout, &mut io::sink()) + .map_err(|_| AgentError::io("Cannot read Git source ancestry proof"))?; + let (status, stderr) = child.complete()?; + if status.code() == Some(1) { + return Err(AgentError::semantic( + "git_source_lineage", + "The pinned source does not descend from the previously imported commit; reset, rebase, or source-key reuse requires explicit new enrollment", + )); + } + require_success(status, &stderr, "Cannot prove local Git source advancement") +} + +/// Checks the artifact context as well as the immutable source revision. +pub fn check_source_lineage( + inputs: &GitMergeInputs, + previous: &GitMergeProvenance, +) -> Result<(), AgentError> { + if previous.repo_relative_root != inputs.provenance.repo_relative_root { + return Err(AgentError::semantic( + "git_source_lineage", + "The enrolled Git source used a different repository-relative artifact root", + )); + } + check_source_advancement(inputs, &previous.theirs) +} + +fn check_version(directory: &Path) -> Result<(), AgentError> { + // Do not pass the new --no-lazy-fetch flag until the executable version is + // known. --version cannot resolve objects or invoke repository machinery. + let mut command = git_command(directory, false); + command.arg("--version"); + let mut child = GitChild::from_command(command, false)?; + let bytes = read_bounded(&mut child.stdout, RECORD_LIMIT, "Git version output")?; + child.finish("Cannot determine the Git executable version")?; + let text = std::str::from_utf8(&bytes).map_err(|_| malformed("Git version"))?; + let version = text + .strip_prefix("git version ") + .and_then(|s| s.split_whitespace().next()) + .ok_or_else(|| malformed("Git version"))?; + let mut components = version.split('.'); + let major = components.next().and_then(|s| s.parse::().ok()); + let minor = components.next().and_then(|s| s.parse::().ok()); + if major.zip(minor).is_none_or(|pair| pair < MIN_GIT_VERSION) { + return Err(AgentError::setup( + "git_version_unsupported", + "Git merge requires Git 2.45 or newer to guarantee that missing objects cannot trigger lazy fetching", + )); + } + Ok(()) +} + +fn require_complete_history(repository: &Path) -> Result<(), AgentError> { + let shallow = query(repository, &["rev-parse", "--is-shallow-repository"])?; + match trim_line(&shallow)? { + b"false" => Ok(()), + b"true" => Err(AgentError::semantic( + "git_shallow_history", + "Git merge requires complete local ancestry; shallow repositories are unsupported and will not be fetched", + )), + _ => Err(malformed("Git shallow-history response")), + } +} + +fn resolve_commit(repository: &Path, reference: &str, context: &str) -> Result { + // --end-of-options prevents a reference from becoming a command option. + let expression = format!("{reference}^{{commit}}"); + let mut child = GitChild::spawn( + repository, + &["rev-parse", "--verify", "--end-of-options", &expression], + false, + )?; + let bytes = read_bounded(&mut child.stdout, RECORD_LIMIT, "Git commit resolution")?; + child.finish(context)?; + object_id(trim_line(&bytes)?) +} + +fn check_unmerged(repository: &Path, prefix: &str) -> Result<(), AgentError> { + let mut child = GitChild::spawn( + repository, + &["ls-files", "--unmerged", "-z", "--full-name"], + false, + )?; + let mut record = Vec::new(); + let mut inside = false; + while read_record(&mut child.stdout, 0, &mut record)? { + let tab = record + .iter() + .position(|byte| *byte == b'\t') + .ok_or_else(|| malformed("unmerged Git index record"))?; + let path = &record[tab + 1..]; + if descendant(path, prefix.as_bytes()).is_some() || path == prefix.as_bytes() { + inside = true; + } + } + child.finish("Cannot inspect Git index conflicts")?; + if inside { + return Err(AgentError::semantic( + "git_unmerged_index", + "The selected artifact has unmerged index entries; resolve them before an ARA merge", + )); + } + Ok(()) +} + +fn materialize( + repository: &Path, + commit: &str, + prefix: &str, + root: &Path, + timings: &mut GitInputTimings, +) -> Result<(), AgentError> { + let tree_started = Instant::now(); + let mut tree = GitChild::spawn( + repository, + &["ls-tree", "-r", "-z", "--full-tree", commit, "--"], + false, + )?; + let blobs_started = Instant::now(); + let mut batch = GitChild::spawn(repository, &["cat-file", "--batch"], true)?; + let mut input = batch + .child + .stdin + .take() + .ok_or_else(|| AgentError::io("Cannot open Git blob input"))?; + let mut directories = BTreeSet::new(); + directories.insert(root.to_path_buf()); + let mut record = Vec::new(); + let mut header = Vec::new(); + let mut found_tree = false; + // Stream tree metadata and blob payloads; only created directory names + // remain in memory for host-filesystem collision checks. + while read_record(&mut tree.stdout, 0, &mut record)? { + let tab = record + .iter() + .position(|byte| *byte == b'\t') + .ok_or_else(|| malformed("Git tree record"))?; + let [mode, kind, oid] = + three_fields(&record[..tab]).ok_or_else(|| malformed("Git tree metadata"))?; + let path = &record[tab + 1..]; + let selected = descendant(path, prefix.as_bytes()); + // A symlink/gitlink at an ancestor cannot be silently mistaken for a + // missing historical artifact. No object outside the prefix is copied. + let ancestor = !prefix.is_empty() + && (path == prefix.as_bytes() || descendant(prefix.as_bytes(), path).is_some()); + if ancestor { + return Err(AgentError::semantic( + "git_unsafe_mode", + "The historical artifact root traverses a symlink, gitlink, or non-directory entry", + )); + } + let Some(relative) = selected else { + continue; + }; + let path = safe_blob_path(relative)?; + if path.components().any(|part| { + part.as_os_str() + .to_str() + .is_some_and(ara_core::write::source::is_temporary_path) + }) { + continue; + } + let executable = match (mode, kind) { + (b"100644", b"blob") => false, + (b"100755", b"blob") => true, + _ => { + return Err(AgentError::semantic( + "git_unsafe_mode", + "Git inputs support only regular 100644/100755 blobs, not symlinks, gitlinks, or special modes", + )); + } + }; + let oid = validated_object_id(oid)?; + found_tree |= relative == TREE_FILE.as_bytes(); + ensure_parents(root, &path, &mut directories)?; + let target = root.join(&path); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&target) + .map_err(|error| materialization_error(error, "Cannot create a private Git blob"))?; + writeln!(input, "{oid}") + .and_then(|()| input.flush()) + .map_err(|_| AgentError::io("Cannot request a local Git blob"))?; + if !read_record(&mut batch.stdout, b'\n', &mut header)? { + return Err(AgentError::setup( + "git_object_unavailable", + "Git stopped before returning the requested local blob", + )); + } + if header.strip_suffix(b" missing") == Some(oid.as_bytes()) { + return Err(AgentError::setup( + "git_object_unavailable", + format!("Required blob {oid} is unavailable locally; fetching is disabled"), + )); + } + let [returned, kind, size] = + three_fields(&header).ok_or_else(|| malformed("Git blob frame"))?; + if returned != oid.as_bytes() || kind != b"blob" { + return Err(malformed("Git blob frame")); + } + let size = std::str::from_utf8(size) + .ok() + .and_then(|value| value.parse::().ok()) + .ok_or_else(|| malformed("Git blob size"))?; + let copied = io::copy(&mut (&mut batch.stdout).take(size), &mut file) + .map_err(|_| AgentError::io("Cannot stream a local Git blob into private storage"))?; + if copied != size { + return Err(AgentError::setup( + "git_object_unavailable", + "Git returned an incomplete local blob payload", + )); + } + let mut terminator = [0]; + batch + .stdout + .read_exact(&mut terminator) + .map_err(|_| malformed("Git blob terminator"))?; + if terminator[0] != b'\n' { + return Err(malformed("Git blob terminator")); + } + file.flush() + .map_err(|_| AgentError::io("Cannot finish writing a private Git blob"))?; + set_blob_permissions(&file, executable)?; + } + tree.finish("A committed Git tree is missing or unreadable locally")?; + timings.tree_capture_ms += elapsed_ms(tree_started); + if !found_tree { + let display_root = if prefix.is_empty() { "." } else { prefix }; + return Err(AgentError::semantic( + "git_artifact_missing", + format!( + "The committed artifact at repository-relative root {display_root:?} is missing {TREE_FILE}" + ), + )); + } + // Closing stdin asks batch to finish; consume EOF and verify its exit status. + drop(input); + let mut extra = [0]; + if batch + .stdout + .read(&mut extra) + .map_err(|_| AgentError::io("Cannot finish reading Git blob output"))? + != 0 + { + return Err(malformed("unexpected Git blob output")); + } + batch.finish("A local Git blob could not be materialized")?; + timings.blob_materialize_ms += elapsed_ms(blobs_started); + Ok(()) +} + +fn descendant<'a>(path: &'a [u8], prefix: &[u8]) -> Option<&'a [u8]> { + if prefix.is_empty() { + return Some(path); + } + path.strip_prefix(prefix)?.strip_prefix(b"/") +} + +fn safe_blob_path(bytes: &[u8]) -> Result { + let text = std::str::from_utf8(bytes).map_err(|_| { + AgentError::semantic("git_unsafe_path", "Git artifact paths must be valid UTF-8") + })?; + if text.is_empty() + || text.contains('\\') + || text.contains(':') + || text.split('/').any(|part| { + part.is_empty() || part == "." || part == ".." || part.eq_ignore_ascii_case(".git") + }) + { + return Err(AgentError::semantic( + "git_unsafe_path", + "A committed artifact path is absolute, reserved, or contains traversal components", + )); + } + let path = PathBuf::from(text); + if path + .components() + .any(|part| !matches!(part, Component::Normal(_))) + { + return Err(AgentError::semantic( + "git_unsafe_path", + "A committed artifact path escapes its private input tree", + )); + } + Ok(path) +} + +fn relative_path(path: &Path) -> Result { + let mut parts = Vec::new(); + for part in path.components() { + let Component::Normal(part) = part else { + return Err(AgentError::semantic( + "git_unsafe_path", + "The artifact root must have a safe repository-relative path", + )); + }; + let text = part.to_str().ok_or_else(|| { + AgentError::semantic( + "git_unsafe_path", + "The artifact root must have a UTF-8 repository-relative path", + ) + })?; + parts.push(text); + } + Ok(parts.join("/")) +} + +fn ensure_parents( + root: &Path, + relative: &Path, + directories: &mut BTreeSet, +) -> Result<(), AgentError> { + let parent = relative + .parent() + .ok_or_else(|| malformed("Git blob parent path"))?; + let mut path = root.to_path_buf(); + for part in parent.components() { + path.push(part); + if !directories.contains(&path) { + // create_dir (not create_dir_all) detects host case/normalization + // aliases even when two logical names have disjoint descendants. + fs::create_dir(&path).map_err(|error| { + materialization_error(error, "Cannot create a private Git input directory") + })?; + directories.insert(path.clone()); + } + let metadata = fs::symlink_metadata(&path) + .map_err(|_| AgentError::io("Cannot inspect a private Git input directory"))?; + if !metadata.is_dir() || metadata.file_type().is_symlink() { + return Err(AgentError::semantic( + "git_unsafe_path", + "A private Git input parent is not a regular directory", + )); + } + } + Ok(()) +} + +fn materialization_error(error: io::Error, context: &str) -> AgentError { + if error.kind() == io::ErrorKind::AlreadyExists { + AgentError::semantic( + "git_path_collision", + "Committed Git paths collide on the host filesystem", + ) + } else { + AgentError::io(context) + } +} + +#[cfg(unix)] +fn set_private_permissions(path: &Path) -> Result<(), AgentError> { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(path, fs::Permissions::from_mode(0o700)) + .map_err(|_| AgentError::io("Cannot secure private Git input storage")) +} +#[cfg(not(unix))] +fn set_private_permissions(_: &Path) -> Result<(), AgentError> { + Err(AgentError::setup( + "git_platform_unsupported", + "Git snapshot privacy currently requires a Unix host", + )) +} + +#[cfg(unix)] +fn set_blob_permissions(file: &File, executable: bool) -> Result<(), AgentError> { + use std::os::unix::fs::PermissionsExt; + file.set_permissions(fs::Permissions::from_mode(if executable { + 0o755 + } else { + 0o644 + })) + .map_err(|_| AgentError::io("Cannot preserve committed Git blob permissions")) +} +#[cfg(not(unix))] +fn set_blob_permissions(_: &File, _: bool) -> Result<(), AgentError> { + Err(AgentError::setup( + "git_platform_unsupported", + "Git snapshot permission preservation currently requires a Unix host", + )) +} + +fn object_id(bytes: &[u8]) -> Result { + validated_object_id(bytes).map(str::to_owned) +} + +fn validated_object_id(bytes: &[u8]) -> Result<&str, AgentError> { + if !matches!(bytes.len(), 40 | 64) || !bytes.iter().all(u8::is_ascii_hexdigit) { + return Err(malformed("immutable Git object ID")); + } + std::str::from_utf8(bytes).map_err(|_| malformed("immutable Git object ID")) +} + +fn three_fields(bytes: &[u8]) -> Option<[&[u8]; 3]> { + let mut fields = bytes.split(|byte| *byte == b' '); + let result = [fields.next()?, fields.next()?, fields.next()?]; + fields.next().is_none().then_some(result) +} + +fn trim_line(bytes: &[u8]) -> Result<&[u8], AgentError> { + // Remove exactly Git's output newline, not whitespace in a pathname. + bytes + .strip_suffix(b"\n") + .ok_or_else(|| malformed("Git line response")) +} + +#[cfg(unix)] +fn path_from_bytes(bytes: &[u8]) -> Result { + use std::os::unix::ffi::OsStrExt; + Ok(PathBuf::from(OsStr::from_bytes(bytes))) +} +#[cfg(not(unix))] +fn path_from_bytes(bytes: &[u8]) -> Result { + Ok(PathBuf::from( + std::str::from_utf8(bytes).map_err(|_| malformed("Git working-tree path"))?, + )) +} + +fn malformed(context: &str) -> AgentError { + AgentError::setup( + "git_invalid_output", + format!("Malformed or incomplete {context}"), + ) +} + +fn query(directory: &Path, arguments: &[&str]) -> Result, AgentError> { + let mut child = GitChild::spawn(directory, arguments, false)?; + let bytes = read_bounded(&mut child.stdout, QUERY_LIMIT, "Git discovery output")?; + child.finish("Cannot read the required local Git repository data")?; + Ok(bytes) +} + +fn read_bounded( + reader: &mut impl Read, + limit: usize, + context: &str, +) -> Result, AgentError> { + let mut bytes = Vec::new(); + reader + .take(limit as u64 + 1) + .read_to_end(&mut bytes) + .map_err(|_| AgentError::io(format!("Cannot read {context}")))?; + if bytes.len() > limit { + return Err(malformed(context)); + } + Ok(bytes) +} + +fn read_record( + reader: &mut impl BufRead, + delimiter: u8, + record: &mut Vec, +) -> Result { + record.clear(); + let count = reader + .take(RECORD_LIMIT as u64 + 1) + .read_until(delimiter, record) + .map_err(|_| AgentError::io("Cannot read Git plumbing output"))?; + if count == 0 { + return Ok(false); + } + if count > RECORD_LIMIT || record.last().copied() != Some(delimiter) { + return Err(malformed("Git plumbing record")); + } + record.pop(); + Ok(true) +} + +fn git_command(directory: &Path, no_lazy_fetch: bool) -> Command { + let mut command = Command::new("git"); + command.current_dir(directory).env_clear(); + // Only OS executable lookup/platform bootstrap survives. No GIT_*, SSH_*, + // trace, index/object redirection, config injection, loader, or prompt env. + for name in ["PATH", "SystemRoot", "WINDIR"] { + if let Some(value) = std::env::var_os(name) { + command.env(name, value); + } + } + let null = if cfg!(windows) { "NUL" } else { "/dev/null" }; + command + .env("LC_ALL", "C") + .env("GIT_CONFIG_NOSYSTEM", "1") + .env("GIT_CONFIG_SYSTEM", null) + .env("GIT_CONFIG_GLOBAL", null) + .env("GIT_GRAFT_FILE", null) + .env("GIT_NO_LAZY_FETCH", "1") + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_NO_REPLACE_OBJECTS", "1") + .env("GIT_OPTIONAL_LOCKS", "0") + .env("GIT_ALLOW_PROTOCOL", "") + .env("GIT_PROTOCOL_FROM_USER", "0") + .env("GIT_ATTR_NOSYSTEM", "1") + .env("GIT_PAGER", "") + .arg("--no-pager") + .arg("--no-replace-objects") + .arg("--no-optional-locks"); + if no_lazy_fetch { + command.arg("--no-lazy-fetch"); + } + for setting in [ + "protocol.allow=never", + "credential.helper=", + "credential.interactive=false", + "core.fsmonitor=false", + "core.untrackedCache=false", + "gc.auto=0", + "maintenance.auto=false", + "core.commitGraph=false", + "advice.graftFileDeprecated=false", + ] { + command.args(["-c", setting]); + } + command.arg("-c").arg(format!("core.hooksPath={null}")); + command.arg("-c").arg(format!("core.attributesFile={null}")); + command +} + +/// Drains bounded stderr concurrently and kills/reaps on every early return. +struct GitChild { + child: Child, + stdout: BufReader, + stderr: Option>>>, + reaped: bool, +} +impl GitChild { + fn spawn(directory: &Path, arguments: &[&str], input: bool) -> Result { + let mut command = git_command(directory, true); + command.args(arguments); + Self::from_command(command, input) + } + fn from_command(mut command: Command, input: bool) -> Result { + command + .stdin(if input { Stdio::piped() } else { Stdio::null() }) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let mut child = command.spawn().map_err(|error| { + if error.kind() == io::ErrorKind::NotFound { + AgentError::setup( + "git_unavailable", + "Git merge requires the Git executable (version 2.45 or newer) on PATH", + ) + } else { + AgentError::io("Cannot launch the local Git executable") + } + })?; + let stdout = match child.stdout.take() { + Some(stdout) => stdout, + None => { + let _ = child.kill(); + let _ = child.wait(); + return Err(AgentError::io("Cannot open Git output")); + } + }; + let Some(mut stderr) = child.stderr.take() else { + let _ = child.kill(); + let _ = child.wait(); + return Err(AgentError::io("Cannot open Git diagnostics")); + }; + let drain = thread::Builder::new() + .name("ara-git-stderr".into()) + .spawn(move || { + let mut captured = Vec::with_capacity(STDERR_LIMIT); + let mut block = [0; 4096]; + loop { + let count = stderr.read(&mut block)?; + if count == 0 { + break; + } + let keep = count.min(STDERR_LIMIT - captured.len()); + captured.extend_from_slice(&block[..keep]); + } + Ok(captured) + }); + match drain { + Ok(stderr) => Ok(Self { + child, + stdout: BufReader::new(stdout), + stderr: Some(stderr), + reaped: false, + }), + Err(_) => { + let _ = child.kill(); + let _ = child.wait(); + Err(AgentError::io("Cannot capture Git diagnostics")) + } + } + } + fn complete(&mut self) -> Result<(ExitStatus, Vec), AgentError> { + let status = self + .child + .wait() + .map_err(|_| AgentError::io("Cannot reap the Git subprocess"))?; + self.reaped = true; + let stderr = self + .stderr + .take() + .ok_or_else(|| AgentError::io("Git diagnostics were already consumed"))? + .join() + .map_err(|_| AgentError::io("Cannot join the Git diagnostic reader"))? + .map_err(|_| AgentError::io("Cannot read Git diagnostics"))?; + Ok((status, stderr)) + } + fn finish(&mut self, context: &str) -> Result<(), AgentError> { + let (status, stderr) = self.complete()?; + require_success(status, &stderr, context) + } +} +impl Drop for GitChild { + fn drop(&mut self) { + if !self.reaped { + // Batch stdin lives in the caller; killing rather than waiting for + // EOF avoids an early-error deadlock even before its local drop. + let _ = self.child.kill(); + let _ = self.child.wait(); + } + if let Some(stderr) = self.stderr.take() { + let _ = stderr.join(); + } + } +} + +fn require_success(status: ExitStatus, stderr: &[u8], context: &str) -> Result<(), AgentError> { + if status.success() { + return Ok(()); + } + let detail = sanitized_stderr(stderr); + let message = if detail.is_empty() { + context.to_owned() + } else { + format!("{context}: {detail}") + }; + Err(AgentError::setup("git_object_unavailable", message)) +} + +fn sanitized_stderr(bytes: &[u8]) -> String { + // Never expose arbitrary paths (including private input paths) or controls. + // Keep only a small useful subset of Git's fixed diagnostics; otherwise the + // operation context is sufficient and cannot leak a credential or URL. + let text = String::from_utf8_lossy(bytes); + for (needle, message) in [ + ( + "not a git repository", + "destination is not a Git repository", + ), + ("bad object", "a required local object is missing"), + ("missing blob", "a required local blob is missing"), + ("could not read", "required local Git data is unreadable"), + ( + "unknown revision", + "the requested local revision is unavailable", + ), + ( + "Needed a single revision", + "the requested local revision is unavailable", + ), + ( + "dubious ownership", + "Git rejected repository ownership; configure Git safe.directory explicitly", + ), + ("transport", "remote transport is disabled"), + ] { + if text.contains(needle) { + return message.into(); + } + } + String::new() +} diff --git a/crates/ara-cli/src/output.rs b/crates/ara-cli/src/output.rs new file mode 100644 index 0000000..0fe3f0b --- /dev/null +++ b/crates/ara-cli/src/output.rs @@ -0,0 +1,437 @@ +//! Versioned output and the agent-command 0/1/2 exit contract. +use serde::Serialize; +use serde_json::{Value, json}; +use std::{ + io::{BufWriter, Write}, + process::ExitCode, +}; + +pub const EXCERPT_CHARS: usize = 160; + +#[derive(Debug, Clone, Serialize)] +pub struct AgentError { + pub code: String, + pub message: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub line: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub details: Option>, + #[serde(skip)] + pub exit: u8, + /// Replaces `message` in text output when the message is long, such as + /// a refusal's full validation report. JSON keeps `message`. + #[serde(skip)] + pub summary: Option>, +} +impl AgentError { + pub fn semantic(code: impl Into, message: impl Into) -> Self { + Self { + code: code.into(), + message: message.into(), + id: None, + line: None, + details: None, + exit: 1, + summary: None, + } + } + pub fn setup(code: impl Into, message: impl Into) -> Self { + Self { + exit: 2, + ..Self::semantic(code, message) + } + } + pub fn io(message: impl Into) -> Self { + Self::setup("io_error", message) + } + pub fn unknown(id: &str) -> Self { + Self { + id: Some(id.into()), + ..Self::semantic( + "unknown_id", + format!("Unknown or ambiguous selector `{id}`"), + ) + } + } +} +impl std::fmt::Display for AgentError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} +impl std::error::Error for AgentError {} + +pub fn excerpt(text: &str) -> String { + let mut output = String::with_capacity(text.len().min(EXCERPT_CHARS * 4)); + let mut count = 0; + let mut space = false; + for character in text.chars() { + if character.is_whitespace() { + space = !output.is_empty(); + continue; + } + for next in space + .then_some(' ') + .into_iter() + .chain(std::iter::once(character)) + { + if count == EXCERPT_CHARS { + let end = output + .char_indices() + .nth(EXCERPT_CHARS - 1) + .map_or(output.len(), |(offset, _)| offset); + output.truncate(end); + output.push('…'); + return output; + } + output.push(next); + count += 1; + } + space = false; + } + output +} + +pub fn project(value: &mut Value, fields: Option<&str>) -> Result<(), AgentError> { + let Some(fields) = fields else { + return Ok(()); + }; + let names = fields.split(',').map(str::trim).collect::>(); + if names.iter().any(|name| name.is_empty()) { + return Err(AgentError::semantic( + "unknown_field", + "--fields requires nonempty field names", + )); + } + let object = value.as_object_mut().ok_or_else(|| { + AgentError::semantic("invalid_projection", "Projection requires an object") + })?; + if names.iter().all(|name| object.contains_key(*name)) { + object.retain(|name, _| { + matches!( + name.as_str(), + "format" + | "id" + | "key" + | "committed" + | "dry_run" + | "operations" + | "bindings" + | "changed_paths" + | "created_directories" + | "no_op" + | "turn" + | "target" + | "unresolved_count" + | "complete" + | "incomplete" + | "diagnostics" + | "advisories" + | "duplicate_candidates" + | "display" + ) || names.contains(&name.as_str()) + }); + return Ok(()); + } + let arrays = ["entries", "results"]; + if !arrays + .iter() + .any(|key| object.get(*key).is_some_and(Value::is_array)) + { + return Err(AgentError::semantic( + "unknown_field", + "Unknown projected field", + )); + } + let format = object.get("format").and_then(Value::as_str).unwrap_or(""); + for name in &names { + let present = arrays + .iter() + .filter_map(|key| object.get(*key).and_then(Value::as_array)) + .flatten() + .any(|row| row.get(*name).is_some()); + if !present && !known_row_field(format, name) { + return Err(AgentError::semantic( + "unknown_field", + format!("Unknown projected field `{name}`"), + )); + } + } + for key in arrays { + if let Some(rows) = object.get_mut(key).and_then(Value::as_array_mut) { + for row in rows { + if let Some(row) = row.as_object_mut() { + row.retain(|name, _| { + matches!( + name.as_str(), + "id" | "key" + | "kind" + | "source" + | "requested_address" + | "resolved_target" + ) || names.contains(&name.as_str()) + }); + } + } + } + } + Ok(()) +} +fn known_row_field(format: &str, name: &str) -> bool { + if format == "ara.find/v1" { + return matches!( + name, + "id" | "key" + | "kind" + | "source" + | "score" + | "excerpt" + | "entry" + | "line" + | "matches" + | "match_count" + | "context" + ); + } + let node = matches!( + name, + "id" | "key" + | "kind" + | "source" + | "label" + | "title" + | "support_level" + | "source_refs" + | "description" + | "thinking" + | "provenance" + | "timestamp" + | "fields" + | "evidence_notes" + | "isolated" + | "pos" + | "same_as" + | "artifacts" + | "concepts" + | "source_fields" + | "relations" + ); + node || matches!( + name, + "statement" + | "status" + | "proof" + | "deps" + | "proof_content" + | "falsification" + | "conditions" + | "sources" + | "tags" + | "last_revised" + | "body" + | "source_file" + | "content" + | "context" + | "potential_type" + | "promoted_to" + | "crystallized_via" + | "bound_to" + | "promoted" + | "stale" + | "turns_since_reference" + | "session_days_since_reference" + | "last_reference_turn" + | "last_reference_date" + | "reference_basis" + | "evidence_sources" + | "history_status" + | "history_diagnostics" + | "extra" + | "date" + | "started" + | "last_turn" + | "summary" + | "turn_count" + | "events_logged" + | "ai_actions" + | "claims_touched" + | "logic_revisions" + | "key_context" + | "open_threads" + | "ai_suggestions_pending" + | "metadata_extra" + | "rationale" + | "sensitivity" + | "code_ref" + | "evidence_output" + | "question" + | "setup" + | "prediction" + | "target" + | "comment" + | "tag" + | "object" + | "term" + | "notation" + | "definition" + | "boundary" + | "related" + | "cite" + | "doi" + | "what_changed" + | "why" + | "adopted" + | "claims_affected" + | "name" + | "file" + | "image" + | "claims" + | "document" + | "heading" + | "heading_path" + | "address" + | "digest" + | "reasons" + | "requested_address" + | "resolved_target" + ) +} + +pub fn emit( + format: &str, + result: Result, + json_mode: bool, + fields: Option<&str>, +) -> ExitCode { + let result = result.and_then(|mut value| { + project(&mut value, fields)?; + Ok(value) + }); + match result { + Ok(value) => { + if json_mode { + let stdout = std::io::stdout(); + let mut writer = BufWriter::new(stdout.lock()); + serde_json::to_writer(&mut writer, &value).expect("JSON output"); + writer.write_all(b"\n").expect("stdout output"); + writer.flush().expect("stdout output"); + } else if !crate::brief::handles(format) { + print_human(&value, true); + } else if fields.is_none() { + crate::brief::print(&value); + } else { + // Projected rows keep their meaning; diagnostics (errors + // included) still print once as the read summary. + print_human(&value, false); + crate::brief::print_diagnostics(&value); + } + ExitCode::SUCCESS + } + Err(error) => { + if json_mode { + eprintln!("{}", json!({"format":format,"error":error})); + } else { + eprintln!("{}", crate::brief::error(&error)); + } + ExitCode::from(error.exit) + } + } +} + +/// Text for non-brief results. `warnings` prints each diagnostic warning; +/// a read summarizes its diagnostics separately instead. +fn print_human(value: &Value, warnings: bool) { + if let Some(warnings) = value["diagnostics"]["warnings"] + .as_array() + .filter(|_| warnings) + { + for warning in warnings { + eprintln!( + "warning [{}] {}: {}", + warning["code"].as_str().unwrap_or(""), + warning["path"].as_str().unwrap_or(""), + warning["message"].as_str().unwrap_or("") + ); + } + } + if let Some(candidates) = value["duplicate_candidates"].as_array() { + for candidate in candidates { + eprintln!( + "warning: {} and {} may repeat the same finding (lexical similarity {:.3}; not equivalence)", + candidate["left"].as_str().unwrap_or(""), + candidate["right"].as_str().unwrap_or(""), + candidate["similarity"].as_f64().unwrap_or(0.0) + ); + } + } + if let Some(advisories) = value["advisories"].as_array() { + for advisory in advisories { + eprintln!( + "warning: {}", + advisory.as_str().unwrap_or("Advisory unavailable") + ); + } + } + if value.get("operations").is_some() + && let Some(id) = value["id"].as_str() + { + println!("{id}"); + return; + } + if let Some(rows) = ["entries", "steps", "items", "results"] + .into_iter() + .find_map(|name| value.get(name).and_then(Value::as_array)) + { + if value["format"] == "ara.show/v1" { + for row in rows { + if row["kind"] == "source_document" + && row.get("relations").is_none() + && let Some(content) = row["content"].as_str() + { + print!("{content}"); + } else { + println!( + "{}", + serde_json::to_string_pretty(row).expect("entry serialization") + ); + } + } + for failure in value["errors"].as_array().into_iter().flatten() { + println!( + "{}", + serde_json::to_string_pretty(failure).expect("error serialization") + ); + } + return; + } + for row in rows { + let id = row + .get("id") + .or_else(|| row.get("key")) + .and_then(Value::as_str) + .unwrap_or(""); + let kind = row.get("kind").and_then(Value::as_str).unwrap_or(""); + let title = [ + "title", + "term", + "cite", + "name", + "excerpt", + "statement", + "summary", + "content", + ] + .iter() + .find_map(|key| row.get(*key).and_then(Value::as_str)) + .unwrap_or(""); + println!("{id}\t{kind}\t{title}"); + } + return; + } + println!( + "{}", + serde_json::to_string_pretty(value).expect("JSON value serialization") + ); +} diff --git a/crates/ara-cli/src/search.rs b/crates/ara-cli/src/search.rs new file mode 100644 index 0000000..8405f17 --- /dev/null +++ b/crates/ara-cli/src/search.rs @@ -0,0 +1,1471 @@ +//! Stateless keyword ranking and advisory lexical duplicate similarity. +//! Tokens are maximal Unicode alphanumeric runs, lowercased with Unicode's +//! deterministic lowercase mapping. Punctuation separates tokens (`N12` stays +//! intact); no stemming, accent folding, locale, model, or network is involved. +use ara_core::Manifest; +use serde::Serialize; +use std::borrow::Cow; +use std::cmp::Ordering; +use std::collections::{BTreeMap, BTreeSet, BinaryHeap}; +use std::ops::Range; +use std::sync::OnceLock; + +const K1: f64 = 1.2; +const B: f64 = 0.75; +pub const DEFAULT_DUPLICATE_THRESHOLD: f64 = 0.8; +pub const DEFAULT_DUPLICATE_LIMIT: usize = 10; +const RETRIEVAL_LIMIT: usize = 64; +const MAX_LIMIT: usize = 10_000; + +#[derive(Debug, Clone, Serialize)] +pub struct SearchHit { + #[serde(skip_serializing_if = "Option::is_none")] + pub id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub key: Option, + pub kind: String, + pub source: String, + pub score: f64, + pub excerpt: String, + /// Query terms this result's indexed text contains, in lexical order. + #[serde(skip)] + pub terms: Vec, +} + +struct Document<'a> { + id: Option, + key: Option, + kind: String, + source: String, + text: Cow<'a, str>, + terms: BTreeMap, + length: usize, + term_range: Range, +} +impl<'a> Document<'a> { + fn new( + id: Option, + key: Option, + kind: String, + source: String, + text: String, + ) -> Self { + Self::with_text(id, key, kind, source, Cow::Owned(text)) + } + fn with_text( + id: Option, + key: Option, + kind: String, + source: String, + text: Cow<'a, str>, + ) -> Self { + let mut terms = BTreeMap::new(); + let mut length = 0; + for (token, _, _) in tokens(&text) { + *terms.entry(token).or_default() += 1; + length += 1; + } + Self { + id, + key, + kind, + source, + text, + terms, + length, + term_range: 0..0, + } + } + fn identity(&self) -> &str { + self.id.as_deref().or(self.key.as_deref()).unwrap_or("") + } +} + +/// Lowercased maximal alphanumeric runs with their byte ranges. +pub(crate) fn tokens(text: &str) -> impl Iterator + '_ { + let mut start = None; + text.char_indices() + .chain(std::iter::once((text.len(), ' '))) + .filter_map(move |(offset, character)| { + if character.is_alphanumeric() { + start.get_or_insert(offset); + None + } else { + start + .take() + .map(|begin| (text[begin..offset].to_lowercase(), begin, offset)) + } + }) +} + +#[derive(Default)] +struct TermFrequency { + count: usize, + weight: OnceLock, +} + +struct Corpus<'a> { + documents: Vec>, + term_positions: BTreeMap, + frequencies: Vec, + document_terms: Vec, + postings: BTreeMap>, + average_length: f64, + total_length: usize, + normalizations: OnceLock>, +} +impl<'a> Corpus<'a> { + fn new(documents: Vec>) -> Self { + let (total_length, term_count) = + documents.iter().fold((0, 0), |(length, terms), document| { + (length + document.length, terms + document.terms.len()) + }); + let average_length = if documents.is_empty() { + 1.0 + } else { + (total_length as f64 / documents.len() as f64).max(1.0) + }; + let mut corpus = Self { + documents, + term_positions: BTreeMap::new(), + frequencies: Vec::new(), + document_terms: Vec::with_capacity(term_count), + postings: BTreeMap::new(), + average_length, + total_length, + normalizations: OnceLock::new(), + }; + for position in 0..corpus.documents.len() { + corpus.index_document(position); + } + corpus + } + fn index_document(&mut self, position: usize) { + let document = &mut self.documents[position]; + let start = self.document_terms.len(); + // Stable term positions follow each document's lexical key order. + for (term, frequency) in &document.terms { + let term_position = *self.term_positions.entry(term.clone()).or_insert_with(|| { + let position = self.frequencies.len(); + self.frequencies.push(TermFrequency::default()); + position + }); + self.frequencies[term_position].count += 1; + self.document_terms.push(term_position); + self.postings + .entry(term.clone()) + .or_default() + .push((position, *frequency)); + } + document.term_range = start..self.document_terms.len(); + } + fn weight(&self, term: &str) -> f64 { + match self.term_positions.get(term) { + Some(&position) => self.term_weight(position), + None => self.frequency_weight(0), + } + } + fn term_weight(&self, position: usize) -> f64 { + let frequency = &self.frequencies[position]; + *frequency + .weight + .get_or_init(|| self.frequency_weight(frequency.count)) + } + fn frequency_weight(&self, frequency: usize) -> f64 { + let frequency = frequency as f64; + (1.0 + (self.documents.len() as f64 - frequency + 0.5) / (frequency + 0.5)).ln() + } + fn append(&mut self, document: Document<'a>) { + // IDF always changes. Length normalizations depend only on the average. + let old_average = self.average_length; + let added_length = document.length; + for frequency in &mut self.frequencies { + frequency.weight.take(); + } + self.total_length += document.length; + self.documents.push(document); + self.index_document(self.documents.len() - 1); + self.average_length = (self.total_length as f64 / self.documents.len() as f64).max(1.0); + if self.average_length == old_average { + if let Some(normalizations) = self.normalizations.get_mut() { + normalizations.push(K1 * (1.0 - B + B * added_length as f64 / self.average_length)); + } + } else { + self.normalizations.take(); + } + } + fn ranked( + &self, + query: &BTreeSet, + kind: Option<&str>, + limit: usize, + ) -> Vec> { + self.ranked_filtered(query, kind, limit, Filter::default()) + } + /// [`Corpus::ranked`] over the documents `filter` admits. Scores keep + /// the whole corpus's statistics, so admitted documents keep their + /// unfiltered order. + fn ranked_filtered( + &self, + query: &BTreeSet, + kind: Option<&str>, + limit: usize, + filter: Filter<'_>, + ) -> Vec> { + let mut heap = BinaryHeap::with_capacity(limit.min(self.documents.len())); + let normalizations = self.normalizations.get_or_init(|| { + self.documents + .iter() + .map(|document| K1 * (1.0 - B + B * document.length as f64 / self.average_length)) + .collect() + }); + let mut scores = vec![0.0; self.documents.len()]; + // Preserve the original lexical term summation order and exact formula. + for term in query { + let weight = self.weight(term); + if let Some(postings) = self.postings.get(term) { + for &(position, frequency) in postings { + let frequency = frequency as f64; + scores[position] += + weight * frequency * (K1 + 1.0) / (frequency + normalizations[position]); + } + } + } + for (document, score) in self.documents.iter().zip(scores) { + if kind.is_some_and(|kind| kind != document.kind) { + continue; + } + if score <= 0.0 || !score.is_finite() || !filter.admits(document, query) { + continue; + } + let candidate = Ranked { score, document }; + if heap.len() < limit { + heap.push(candidate); + } else if heap.peek().is_some_and(|worst| candidate < *worst) { + *heap.peek_mut().expect("bounded ranking heap is nonempty") = candidate; + } + } + let mut ranked = heap.into_vec(); + ranked.sort(); + ranked + } +} +/// Restrictions on which indexed documents a search may return. +#[derive(Debug, Default, Clone, Copy)] +pub struct Filter<'f> { + /// Only documents whose source path is one of these. + pub sources: Option<&'f BTreeSet>, + /// Only documents containing every query term. + pub all_terms: bool, +} +impl Filter<'_> { + fn admits(&self, document: &Document<'_>, query: &BTreeSet) -> bool { + self.sources + .is_none_or(|sources| sources.contains(&document.source)) + && (!self.all_terms || query.iter().all(|term| document.terms.contains_key(term))) + } +} +struct Ranked<'a> { + score: f64, + document: &'a Document<'a>, +} +impl PartialEq for Ranked<'_> { + fn eq(&self, other: &Self) -> bool { + self.cmp(other) == Ordering::Equal + } +} +impl Eq for Ranked<'_> {} +impl PartialOrd for Ranked<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} +impl Ord for Ranked<'_> { + fn cmp(&self, other: &Self) -> Ordering { + other + .score + .total_cmp(&self.score) + .then_with(|| self.document.kind.cmp(&other.document.kind)) + .then_with(|| self.document.source.cmp(&other.document.source)) + .then_with(|| self.document.identity().cmp(other.document.identity())) + } +} + +fn excerpt(text: &str, query: &BTreeSet) -> String { + let first = tokens(text) + .find(|(term, _, _)| query.contains(term)) + .map_or(0, |(_, start, _)| start); + let start = text[..first] + .char_indices() + .rev() + .nth(59) + .map_or(0, |(offset, _)| offset); + let leading = start > 0; + let available = crate::output::EXCERPT_CHARS - usize::from(leading); + let mut end = text[start..] + .char_indices() + .nth(available) + .map_or(text.len(), |(offset, _)| start + offset); + let trailing = end < text.len(); + if trailing { + end = text[start..end] + .char_indices() + .next_back() + .map_or(start, |(offset, _)| start + offset); + } + let mut result = + String::with_capacity(end - start + usize::from(leading) + usize::from(trailing)); + if leading { + result.push('…'); + } + let mut space = false; + for character in text[start..end].chars() { + if character.is_whitespace() { + space = !result.is_empty(); + continue; + } + if space { + result.push(' '); + space = false; + } + result.push(character); + } + if trailing { + result.push('…'); + } + result +} + +pub fn run_search( + manifest: &Manifest, + query: &str, + kind: Option<&str>, + limit: usize, +) -> Result, String> { + rank(documents(manifest)?, query, kind, limit, Filter::default()) +} +pub fn run_search_with_documents<'a>( + manifest: &'a Manifest, + source_documents: impl IntoIterator, + query: &str, + kind: Option<&str>, + limit: usize, + filter: Filter<'_>, +) -> Result, String> { + let mut corpus: Vec> = documents(manifest)?; + for (source, text) in source_documents { + if !source.ends_with(".md") + || source + .split('/') + .any(|part| matches!(part, ".." | "." | ".git" | ".ara" | "src" | "evidence")) + { + return Err("source document outside knowledge boundary".into()); + } + let document = Document::with_text( + None, + Some(source.into()), + "source_document".into(), + source.into(), + Cow::Borrowed(text), + ); + if let Some(position) = corpus.iter().position(|entry| { + entry.kind == "source_document" && entry.key.as_deref() == Some(source) + }) { + corpus[position] = document; + } else { + corpus.push(document); + } + } + rank(corpus, query, kind, limit, filter) +} +fn rank( + documents: Vec>, + query: &str, + kind: Option<&str>, + limit: usize, + filter: Filter<'_>, +) -> Result, String> { + validate_limit(limit).map_err(|error| error.message)?; + let query: BTreeSet<_> = tokens(query).map(|(term, _, _)| term).collect(); + if query.is_empty() { + return Err("search query must contain a Unicode letter or number".into()); + } + let corpus = Corpus::new(documents); + if let Some(kind) = kind + && !supported_kind(kind) + && !corpus + .documents + .iter() + .any(|document| document.kind == kind) + { + return Err(format!("unknown search kind: {kind}")); + } + Ok(corpus + .ranked_filtered(&query, kind, limit, filter) + .into_iter() + .map(|ranked| SearchHit { + id: ranked.document.id.clone(), + key: ranked.document.key.clone(), + kind: ranked.document.kind.clone(), + source: ranked.document.source.clone(), + score: ranked.score, + excerpt: excerpt(&ranked.document.text, &query), + terms: query + .iter() + .filter(|term| ranked.document.terms.contains_key(*term)) + .cloned() + .collect(), + }) + .collect()) +} + +#[derive(Debug, Clone, Serialize)] +pub struct AdvisoryUnavailable { + pub code: &'static str, + pub message: String, +} +impl std::fmt::Display for AdvisoryUnavailable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.message) + } +} +impl std::error::Error for AdvisoryUnavailable {} +fn unavailable(message: impl Into) -> AdvisoryUnavailable { + AdvisoryUnavailable { + code: "duplicate_advisory_unavailable", + message: message.into(), + } +} +fn validate_limit(limit: usize) -> Result<(), AdvisoryUnavailable> { + if !(1..=MAX_LIMIT).contains(&limit) { + return Err(unavailable(format!( + "limit must be between 1 and {MAX_LIMIT}" + ))); + } + Ok(()) +} +fn validate_duplicate(threshold: f64, limit: usize) -> Result<(), AdvisoryUnavailable> { + validate_limit(limit)?; + if !threshold.is_finite() || !(0.0..=1.0).contains(&threshold) { + return Err(unavailable( + "similarity threshold must be finite and between 0 and 1", + )); + } + Ok(()) +} +#[derive(Debug, Clone, Serialize)] +pub struct DuplicateCandidate { + pub id: String, + pub similarity: f64, +} +#[derive(Debug, Clone, Serialize)] +pub struct DuplicatePair { + pub left: String, + pub right: String, + pub similarity: f64, +} +#[derive(Debug, Clone)] +pub struct DuplicateText { + pub id: String, + pub title: String, + pub body: String, +} + +/// Exact normalized title and substantive typed body used by duplicate scoring. +/// Identifiers, timestamps, provenance and evidence pointers are not similarity. +pub fn node_duplicate_text(node: &ara_core::Node) -> Result { + let mut text = String::new(); + for value in [node.description.as_deref(), node.thinking.as_deref()] + .into_iter() + .flatten() + { + if !text.is_empty() { + text.push('\n'); + } + text.push_str(value); + } + let fields = serde_json::to_value(&node.fields) + .map_err(|error| format!("cannot index entry: {error}"))?; + if !fields.is_string() { + append_text(&fields, &mut text); + } + Ok(text) +} + +/// Snapshot-owned index. Similarity is lexical weighted Jaccard, NOT a probability. +pub struct DuplicateIndex { + corpus: Corpus<'static>, +} +impl DuplicateIndex { + pub fn new(manifest: &Manifest) -> Result { + let documents = manifest + .nodes + .iter() + .map(|node| { + entry_document( + node, + Some(node.id.as_str()), + None, + "node", + "trace/exploration_tree.yaml", + &["label", "description", "thinking", "fields"], + ) + }) + .collect::, _>>() + .map_err(unavailable)?; + Ok(Self { + corpus: Corpus::new(documents), + }) + } + pub fn from_texts(texts: &[DuplicateText]) -> Self { + let documents = texts + .iter() + .map(|text| { + Document::new( + Some(text.id.clone()), + None, + "node".into(), + "trace/exploration_tree.yaml".into(), + format!("{}\n{}", text.title, text.body), + ) + }) + .collect(); + Self { + corpus: Corpus::new(documents), + } + } + pub fn candidates( + &self, + proposed_text: &str, + exclude_id: Option<&str>, + threshold: f64, + limit: usize, + ) -> Result, AdvisoryUnavailable> { + validate_duplicate(threshold, limit)?; + let terms: BTreeSet<_> = tokens(proposed_text).map(|(term, _, _)| term).collect(); + if terms.is_empty() { + return Ok(Vec::new()); + } + let query_weight = terms.iter().map(|term| self.corpus.weight(term)).sum(); + let mut candidates = Vec::new(); + for ranked in self.corpus.ranked( + &terms, + None, + RETRIEVAL_LIMIT + usize::from(exclude_id.is_some()), + ) { + let id = ranked.document.identity(); + if exclude_id == Some(id) { + continue; + } + let positions = &self.corpus.document_terms[ranked.document.term_range.clone()]; + let similarity = weighted_jaccard( + &terms, + query_weight, + ranked + .document + .terms + .keys() + .zip(positions) + .map(|(term, &position)| (term, self.corpus.term_weight(position))), + ); + if similarity > 0.0 && similarity >= threshold { + candidates.push(DuplicateCandidate { + id: id.into(), + similarity, + }); + } + } + candidates.sort_by(|a, b| { + b.similarity + .total_cmp(&a.similarity) + .then_with(|| a.id.cmp(&b.id)) + }); + candidates.truncate(limit); + Ok(candidates) + } +} +fn weighted_jaccard<'a>( + left: &BTreeSet, + mut union: f64, + right: impl Iterator, +) -> f64 { + let mut intersection = 0.0; + for (term, weight) in right { + if left.contains(term) { + intersection += weight; + } else { + union += weight; + } + } + if union == 0.0 { + return 0.0; + } + (intersection / union).clamp(0.0, 1.0) +} + +/// Compare additions to committed entries and earlier additions, emitting each +/// unordered identity pair once. The output and retrieval working set are bounded. +pub fn duplicate_pairs( + existing: &[DuplicateText], + added: &[DuplicateText], + threshold: f64, + limit: usize, +) -> Result, AdvisoryUnavailable> { + validate_duplicate(threshold, limit)?; + let mut index = DuplicateIndex::from_texts(existing); + let identities: BTreeSet<_> = existing + .iter() + .chain(added) + .map(|text| text.id.as_str()) + .collect(); + if identities.len() != existing.len() + added.len() { + return Err(unavailable( + "duplicate pair input contains repeated identities; exclude mapped or repeated imports before scoring", + )); + } + let mut pairs = Vec::new(); + for text in added { + let proposed = format!("{}\n{}", text.title, text.body); + for candidate in index.candidates(&proposed, None, threshold, RETRIEVAL_LIMIT)? { + let (left, right) = if text.id < candidate.id { + (text.id.clone(), candidate.id) + } else { + (candidate.id, text.id.clone()) + }; + pairs.push(DuplicatePair { + left, + right, + similarity: candidate.similarity, + }); + pairs.sort_by(|a, b| { + b.similarity + .total_cmp(&a.similarity) + .then_with(|| a.left.cmp(&b.left)) + .then_with(|| a.right.cmp(&b.right)) + }); + pairs.truncate(limit); + } + let document = Document::new( + Some(text.id.clone()), + None, + "node".into(), + "trace/exploration_tree.yaml".into(), + proposed, + ); + index.corpus.append(document); + } + Ok(pairs) +} + +fn supported_kind(kind: &str) -> bool { + matches!( + kind, + "question" + | "experiment" + | "decision" + | "dead_end" + | "insight" + | "pivot" + | "other" + | "claim" + | "related_work" + | "concept" + | "source_document" + | "solution" + | "exhibit" + | "observation" + | "session" + | "heuristic" + | "experiment_plan" + | "taste" + ) +} + +fn node_document(node: &ara_core::Node) -> Result, String> { + let kind = match &node.kind { + ara_core::NodeKind::Question => "question", + ara_core::NodeKind::Experiment => "experiment", + ara_core::NodeKind::Decision => "decision", + ara_core::NodeKind::DeadEnd => "dead_end", + ara_core::NodeKind::Insight => "insight", + ara_core::NodeKind::Pivot => "pivot", + ara_core::NodeKind::Other(name) => name.as_str(), + }; + entry_document( + node, + Some(node.id.as_str()), + None, + kind, + "trace/exploration_tree.yaml", + &[ + "id", + "label", + "description", + "thinking", + "fields", + "evidence_notes", + "source_refs", + "support_level", + "provenance", + "timestamp", + ], + ) +} + +// Only explicitly supported fields enter the index. Serialization is confined +// to each typed entry, never the manifest, and never reads any referenced file. +fn entry_document( + value: &impl Serialize, + id: Option<&str>, + key: Option<&str>, + kind: &str, + source: &str, + fields: &[&str], +) -> Result, String> { + Ok(Document::new( + id.map(str::to_owned), + key.map(str::to_owned), + kind.into(), + source.into(), + entry_text(value, fields)?, + )) +} +fn entry_text(value: &impl Serialize, fields: &[&str]) -> Result { + let value = + serde_json::to_value(value).map_err(|error| format!("cannot index entry: {error}"))?; + let mut text = String::new(); + for field in fields { + if let Some(value) = value.get(*field) + && (*field != "fields" || !value.is_string()) + { + append_text(value, &mut text); + } + } + Ok(text) +} + +fn append_text(value: &serde_json::Value, text: &mut String) { + match value { + serde_json::Value::String(value) => { + if !text.is_empty() { + text.push('\n'); + } + text.push_str(value); + } + serde_json::Value::Array(values) => { + for value in values { + append_text(value, text); + } + } + serde_json::Value::Object(values) => { + for value in values.values() { + append_text(value, text); + } + } + _ => {} + } +} + +fn canonical_document<'a>(id: &str, body: &'a str, kind: &str, source: &str) -> Document<'a> { + Document::with_text( + Some(id.into()), + None, + kind.into(), + source.into(), + Cow::Borrowed(body), + ) +} +fn documents(manifest: &Manifest) -> Result>, String> { + let mut result = Vec::new(); + for node in &manifest.nodes { + result.push(node_document(node)?); + } + for claim in &manifest.claims { + if let Some(body) = &claim.body { + result.push(canonical_document( + claim.id.as_str(), + body, + "claim", + "logic/claims.md", + )); + } else { + result.push(entry_document( + claim, + Some(claim.id.as_str()), + None, + "claim", + "logic/claims.md", + &[ + "id", + "title", + "statement", + "status", + "proof", + "deps", + "proof_content", + "provenance", + "falsification", + "conditions", + "sources", + "tags", + "last_revised", + ], + )?); + } + } + for work in &manifest.related_work { + result.push(entry_document( + work, + Some(&work.id), + None, + "related_work", + "logic/related_work.md", + &[ + "id", + "cite", + "doi", + "kind", + "what_changed", + "why", + "adopted", + "claims_affected", + ], + )?); + } + for concept in &manifest.concepts { + result.push(entry_document( + concept, + None, + Some(&concept.term), + "concept", + "logic/concepts.md", + &["term", "notation", "definition", "boundary", "related"], + )?); + } + if let Some(problem) = &manifest.problem { + result.push(entry_document( + problem, + None, + Some("logic/problem.md"), + "source_document", + "logic/problem.md", + &["statement", "observations", "gaps", "insights"], + )?); + } + if let Some(paper) = &manifest.paper { + result.push(entry_document( + paper, + None, + Some("PAPER.md"), + "source_document", + "PAPER.md", + &[ + "title", "authors", "year", "venue", "doi", "abstract", "keywords", + ], + )?); + } + for recipe in &manifest.recipes { + // Typed H entries take the place of the raw heuristic file. + if recipe.name == "heuristics" { + continue; + } + let source = format!("logic/solution/{}.md", recipe.name); + result.push(entry_document( + recipe, + None, + Some(&source), + "solution", + &source, + &["name", "title", "body"], + )?); + } + for exhibit in &manifest.exhibits { + result.push(entry_document( + exhibit, + Some(&exhibit.id), + None, + "exhibit", + "evidence/README.md", + &[ + "id", + "file", + "kind", + "source", + "description", + "claims", + "image", + ], + )?); + } + for entry in &manifest.observations { + result.push(entry_document( + entry, + Some(entry.id.as_str()), + None, + "observation", + &entry.source_file, + &[ + "id", + "content", + "timestamp", + "provenance", + "context", + "potential_type", + "promoted_to", + "crystallized_via", + "bound_to", + "extra", + ], + )?); + } + for entry in &manifest.sessions { + if !entry.body.is_empty() { + result.push(canonical_document( + entry.id.as_str(), + &entry.body, + "session", + &entry.source_file, + )); + } else { + result.push(entry_document( + entry, + Some(entry.id.as_str()), + None, + "session", + &entry.source_file, + &[ + "id", + "date", + "started", + "last_turn", + "summary", + "events_logged", + "ai_actions", + "claims_touched", + "logic_revisions", + "key_context", + "open_threads", + "ai_suggestions_pending", + "metadata_extra", + "extra", + ], + )?); + } + } + for entry in &manifest.heuristics { + if !entry.body.is_empty() { + result.push(canonical_document( + entry.id.as_str(), + &entry.body, + "heuristic", + &entry.source_file, + )); + } else { + result.push(entry_document( + entry, + Some(entry.id.as_str()), + None, + "heuristic", + &entry.source_file, + &[ + "id", + "title", + "rationale", + "sources", + "status", + "provenance", + "sensitivity", + "code_ref", + "last_revised", + ], + )?); + } + } + for entry in &manifest.experiment_plans { + if !entry.body.is_empty() { + result.push(canonical_document( + entry.id.as_str(), + &entry.body, + "experiment_plan", + &entry.source_file, + )); + } else { + result.push(entry_document( + entry, + Some(entry.id.as_str()), + None, + "experiment_plan", + &entry.source_file, + &[ + "id", + "title", + "status", + "evidence_output", + "question", + "setup", + "prediction", + "falsification", + "provenance", + "last_revised", + ], + )?); + } + } + for entry in &manifest.taste_comments { + result.push(entry_document( + entry, + Some(entry.id.as_str()), + None, + "taste", + &entry.source_file, + &[ + "id", + "target", + "comment", + "timestamp", + "tag", + "object", + "extra", + ], + )?); + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn document(id: &str, kind: &str, text: &str) -> Document<'static> { + Document::new( + Some(id.into()), + None, + kind.into(), + "trace/exploration_tree.yaml".into(), + text.into(), + ) + } + fn query(text: &str) -> BTreeSet { + tokens(text).map(|(term, _, _)| term).collect() + } + + #[test] + fn posting_scores_match_full_scan_formula_and_tie_order_exactly() { + let corpus = Corpus::new(vec![ + Document::new( + Some("N03".into()), + None, + "node".into(), + "trace".into(), + "雪 rare rare common".into(), + ), + Document::new( + Some("N01".into()), + None, + "node".into(), + "trace".into(), + "common long repeated repeated words".into(), + ), + Document::new( + Some("N02".into()), + None, + "node".into(), + "trace".into(), + "雪 rare rare common".into(), + ), + ]); + let query = tokens("rare 雪 common") + .map(|(term, _, _)| term) + .collect::>(); + let mut reference = corpus + .documents + .iter() + .filter_map(|document| { + let normalization = + K1 * (1.0 - B + B * document.length as f64 / corpus.average_length); + let mut score = 0.0; + for term in &query { + let frequency = *document.terms.get(term).unwrap_or(&0) as f64; + if frequency != 0.0 { + score += corpus.weight(term) * frequency * (K1 + 1.0) + / (frequency + normalization); + } + } + (score > 0.0).then_some(Ranked { score, document }) + }) + .collect::>(); + reference.sort(); + let observed = corpus.ranked(&query, None, 10); + assert_eq!( + observed + .iter() + .map(|ranked| (ranked.document.identity(), ranked.score)) + .collect::>(), + reference + .iter() + .map(|ranked| (ranked.document.identity(), ranked.score)) + .collect::>() + ); + } + + #[test] + fn rare_terms_length_and_repetition_affect_order() { + let corpus = Corpus::new(vec![ + document("N1", "question", "common common common"), + document("N2", "question", "rare"), + document( + "N3", + "question", + "common padding padding padding padding padding", + ), + ]); + let ranked = corpus.ranked(&query("common rare"), None, 3); + assert_eq!( + ranked + .iter() + .map(|entry| entry.document.identity()) + .collect::>(), + ["N2", "N1", "N3"] + ); + let corpus = Corpus::new(vec![ + document("N1", "question", "target filler"), + document("N2", "question", "target target"), + ]); + assert_eq!( + corpus.ranked(&query("target"), None, 2)[0] + .document + .identity(), + "N2" + ); + } + + #[test] + fn unicode_punctuation_ids_and_exact_snippets() { + assert_eq!(query("N12—CAFÉ/实验"), query("n12 café 实验")); + let text = format!("{}\\nCAFÉ—实验", "é".repeat(100)); + let snippet = excerpt(&text, &query("café")); + assert!(snippet.contains("CAFÉ—实验")); + assert!(!snippet.contains('\n')); + assert!(!snippet.contains('\u{fffd}')); + } + + #[test] + fn filtering_preserves_scores_and_ties_are_stable() { + let corpus = Corpus::new(vec![ + document("N2", "question", "same"), + document("N1", "question", "same"), + document("N3", "experiment", "same"), + ]); + let all = corpus.ranked(&query("same"), None, 3); + let filtered = corpus.ranked(&query("same"), Some("question"), 1); + assert_eq!(filtered[0].document.identity(), "N1"); + assert_eq!( + filtered[0].score, + all.iter() + .find(|entry| entry.document.identity() == "N1") + .unwrap() + .score + ); + assert!(corpus.ranked(&query("absent"), None, 1).is_empty()); + assert!( + Corpus::new(Vec::new()) + .ranked(&query("same"), None, 1) + .is_empty() + ); + } + + #[test] + fn overlap_is_bounded_and_not_a_probability() { + let same = query("same text"); + let different = query("different words"); + assert_eq!( + weighted_jaccard(&same, 2.0, same.iter().map(|term| (term, 1.0))), + 1.0 + ); + assert_eq!( + weighted_jaccard(&same, 2.0, different.iter().map(|term| (term, 1.0))), + 0.0 + ); + assert_eq!( + weighted_jaccard( + &query("a b"), + 2.0, + query("b c").iter().map(|term| (term, 1.0)) + ), + 1.0 / 3.0 + ); + assert_eq!(weighted_jaccard(&query(""), 0.0, std::iter::empty()), 0.0); + assert!(validate_duplicate(f64::NAN, 1).is_err()); + assert!(validate_duplicate(0.8, 0).is_err()); + } + + #[test] + fn batch_pairs_include_prior_added_entries_once_and_bound_output() { + let existing = [DuplicateText { + id: "N1".into(), + title: "cache invalidation".into(), + body: "source hashes invalidate stale artifacts".into(), + }]; + let added = [ + DuplicateText { + id: "N2".into(), + title: existing[0].title.clone(), + body: existing[0].body.clone(), + }, + DuplicateText { + id: "N3".into(), + title: existing[0].title.clone(), + body: existing[0].body.clone(), + }, + ]; + let pairs = duplicate_pairs(&existing, &added, 0.8, 10).unwrap(); + assert_eq!( + pairs + .iter() + .map(|pair| (pair.left.as_str(), pair.right.as_str())) + .collect::>(), + [("N1", "N2"), ("N1", "N3"), ("N2", "N3")] + ); + assert!(pairs.iter().all(|pair| pair.similarity == 1.0)); + assert_eq!( + duplicate_pairs(&existing, &added, 0.8, 1).unwrap()[0].right, + "N2" + ); + assert!(duplicate_pairs(&existing, &existing, 0.8, 1).is_err()); + assert_eq!(existing[0].id, "N1"); + assert!( + serde_json::to_string(&pairs) + .unwrap() + .contains("\"similarity\":1.0") + ); + } + + #[test] + fn duplicate_candidates_match_full_scan_after_snapshot_appends() { + let texts = (0..72) + .map(|position| DuplicateText { + id: format!("N{position:02}"), + title: "alpha 雪".into(), + body: format!( + "{} unique{position} {}", + "alpha ".repeat(position % 7), + if position < 60 { "rare" } else { "other" } + ), + }) + .collect::>(); + let uniform = (0..72) + .map(|position| DuplicateText { + id: format!("N{position:02}"), + title: "alpha".into(), + body: "rare".into(), + }) + .collect::>(); + for texts in [texts, uniform] { + let mut index = DuplicateIndex::from_texts(&texts); + let additions = [ + document("N72", "node", "雪 rare"), + document( + "N73", + "node", + &format!("{} newterm", "alpha 雪 rare ".repeat(80)), + ), + document("N74", "node", ""), + document("N75", "node", "雪 rare newterm newterm"), + ]; + for addition in std::iter::once(None).chain(additions.into_iter().map(Some)) { + if let Some(document) = addition { + index.corpus.append(document); + } + let terms = query("alpha 雪 rare newterm missing"); + let weight = |term: &str| { + let frequency = index + .corpus + .documents + .iter() + .filter(|document| document.terms.contains_key(term)) + .count() as f64; + (1.0 + (index.corpus.documents.len() as f64 - frequency + 0.5) + / (frequency + 0.5)) + .ln() + }; + let mut reference = index + .corpus + .documents + .iter() + .filter_map(|document| { + let normalization = K1 + * (1.0 - B + B * document.length as f64 / index.corpus.average_length); + let mut score = 0.0; + for term in &terms { + let frequency = *document.terms.get(term).unwrap_or(&0) as f64; + if frequency != 0.0 { + score += weight(term) * frequency * (K1 + 1.0) + / (frequency + normalization); + } + } + (score > 0.0).then_some(Ranked { score, document }) + }) + .collect::>(); + reference.sort(); + reference.truncate(RETRIEVAL_LIMIT + 1); + let mut expected = reference + .iter() + .filter(|ranked| ranked.document.identity() != "N00") + .filter_map(|ranked| { + let mut union = terms.iter().map(|term| weight(term)).sum::(); + let mut intersection = 0.0; + for term in ranked.document.terms.keys() { + if terms.contains(term) { + intersection += weight(term); + } else { + union += weight(term); + } + } + let similarity = (intersection / union).clamp(0.0, 1.0); + (similarity > 0.0).then_some((ranked.document.identity(), similarity)) + }) + .collect::>(); + expected.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(b.0))); + expected.truncate(10); + for _ in 0..2 { + let ranked = index.corpus.ranked(&terms, None, RETRIEVAL_LIMIT + 1); + assert_eq!( + ranked + .iter() + .map(|ranked| (ranked.document.identity(), ranked.score)) + .collect::>(), + reference + .iter() + .map(|ranked| (ranked.document.identity(), ranked.score)) + .collect::>() + ); + let observed = index + .candidates("alpha 雪 rare newterm missing", Some("N00"), 0.0, 10) + .unwrap(); + assert_eq!( + observed + .iter() + .map(|candidate| (candidate.id.as_str(), candidate.similarity)) + .collect::>(), + expected + ); + } + } + } + } + + #[test] + fn same_title_and_contradictory_results_remain_distinct_candidates() { + let texts = [DuplicateText { + id: "N1".into(), + title: "verification run".into(), + body: "the treatment improves accuracy".into(), + }]; + let index = DuplicateIndex::from_texts(&texts); + assert!( + index + .candidates( + "verification run the treatment reduces accuracy", + None, + 0.95, + 10 + ) + .unwrap() + .is_empty() + ); + assert_eq!( + index + .candidates( + "verification run the treatment improves accuracy", + None, + 0.95, + 10 + ) + .unwrap()[0] + .id, + "N1" + ); + assert!(index.candidates("", None, 0.8, 10).unwrap().is_empty()); + assert!( + index + .candidates( + "verification run the treatment improves accuracy", + Some("N1"), + 0.8, + 10 + ) + .unwrap() + .is_empty() + ); + } + + fn fixture() -> Manifest { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../ara-core/tests/fixtures/agent-cli"); + ara_core::parse_dir(&path) + .expect("pinned real artifact must parse") + .0 + } + + #[test] + fn development_queries_find_attributed_native_identities() { + let manifest = fixture(); + let labels: serde_json::Value = serde_json::from_str(include_str!( + "../../ara-core/tests/fixtures/agent-cli/search/relevance.json" + )) + .unwrap(); + for example in labels["development"].as_array().unwrap() { + let query = example["query"].as_str().unwrap(); + let hits = run_search(&manifest, query, None, 10).unwrap(); + for identity in example["relevant_ids"].as_array().unwrap() { + assert!( + hits.iter() + .any(|hit| hit.id.as_deref() == identity.as_str()), + "{query}: missing {identity}" + ); + } + } + } + + #[test] + fn errors_empty_results_and_type_limits_follow_library_contract() { + let manifest = fixture(); + assert!(run_search(&manifest, "paper", None, 0).is_err()); + assert!(run_search(&manifest, "paper", Some("imaginary"), 10).is_err()); + assert!(run_search(&manifest, "---", None, 10).is_err()); + assert!( + run_search(&manifest, "zzzzunmatchabletoken", None, 10) + .unwrap() + .is_empty() + ); + let hits = run_search(&manifest, "PaperBench", Some("decision"), 1).unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].kind, "decision"); + assert!(hits[0].score.is_finite()); + let json = serde_json::to_value(hits).unwrap(); + assert!(json[0]["id"].as_str().unwrap().starts_with('N')); + assert_eq!(json[0]["source"], "trace/exploration_tree.yaml"); + } + + #[test] + fn evidence_body_is_never_searchable_but_metadata_is() { + let mut manifest = fixture(); + manifest.exhibits = vec![ara_core::Exhibit { + id: "E999".into(), + file: "evidence/results/private.md".into(), + kind: ara_core::ExhibitKind::Result, + source: None, + description: Some("metadataonlyneedle".into()), + claims: Vec::new(), + body: "privatebodyneedle".into(), + image: None, + }]; + assert!( + run_search(&manifest, "privatebodyneedle", None, 10) + .unwrap() + .is_empty() + ); + let hits = run_search(&manifest, "metadataonlyneedle", Some("exhibit"), 10).unwrap(); + assert_eq!(hits[0].id.as_deref(), Some("E999")); + } +} diff --git a/crates/ara-cli/src/write.rs b/crates/ara-cli/src/write.rs new file mode 100644 index 0000000..4f8d6db --- /dev/null +++ b/crates/ara-cli/src/write.rs @@ -0,0 +1,439 @@ +//! Thin CLI authoring adapters; library planners own policy and transactions. +use crate::agent::ReadOptions; +use crate::output::AgentError; +use ara_core::write::{self, ApplyMode, EntrySelector, Fields, WriteOperation}; +use serde_json::{Value, json}; +use std::collections::{BTreeMap, BTreeSet}; +use std::io::Read; +use std::path::{Path, PathBuf}; + +#[derive(Debug, clap::Args)] +pub struct EditArgs { + pub id: Option, + #[arg(long)] + pub document: Option, + #[arg(long)] + pub heading: Vec, + #[arg(long)] + pub entry: Option, + #[arg(long = "set", required = true)] + pub set: Vec, + #[command(flatten)] + pub output: ReadOptions, +} +#[derive(Debug, clap::Args)] +pub struct LogicArgs { + #[command(subcommand)] + pub command: LogicCommand, +} +#[derive(Debug, clap::Subcommand)] +pub enum LogicCommand { + Set(LogicSetArgs), +} +#[derive(Debug, clap::Args)] +pub struct LogicSetArgs { + pub id: String, + #[arg(long = "set", required = true)] + pub set: Vec, + #[command(flatten)] + pub output: ReadOptions, +} +#[derive(Debug, clap::Args)] +pub struct ApplyArgs { + pub file: PathBuf, + #[arg(long)] + pub dry_run: bool, + #[arg(long)] + pub no_duplicate_check: bool, + #[command(flatten)] + pub output: ReadOptions, +} + +pub fn convert_error(error: write::WriteError) -> AgentError { + let details = serde_json::to_value(&error).ok().map(Box::new); + AgentError { + exit: error.exit_code(), + code: error.code, + message: error.message, + id: None, + line: error.line, + details, + summary: None, + } +} +fn read_input(value: &str, used_stdin: &mut bool) -> Result { + if let Some(literal) = value.strip_prefix("@@") { + return Ok(format!("@{literal}")); + } + if value == "@-" { + if *used_stdin { + return Err(AgentError::semantic( + "duplicate_stdin", + "At most one field may consume stdin", + )); + } + *used_stdin = true; + let mut text = String::new(); + std::io::stdin() + .read_to_string(&mut text) + .map_err(|e| AgentError::io(e.to_string()))?; + return Ok(text); + } + if let Some(path) = value.strip_prefix('@') { + return std::fs::read_to_string(path).map_err(|e| AgentError::io(format!("{path}: {e}"))); + } + Ok(value.into()) +} +pub fn resolve_fields(assignments: &[String]) -> Result { + resolve_fields_with_stdin(assignments, &mut false) +} +fn resolve_fields_with_stdin( + assignments: &[String], + stdin: &mut bool, +) -> Result { + let mut fields = BTreeMap::new(); + let mut canonical = BTreeSet::new(); + for assignment in assignments { + let (key, input) = assignment.split_once('=').ok_or_else(|| { + AgentError::semantic( + "invalid_assignment", + format!("Expected key=value: `{assignment}`"), + ) + })?; + let normalized = key.to_ascii_lowercase().replace([' ', '-'], "_"); + let normalized = if normalized == "falsification_criteria" { + "falsification".to_owned() + } else { + normalized + }; + if key.is_empty() || !canonical.insert(normalized.clone()) { + return Err(AgentError::semantic( + "duplicate_field", + format!("Repeated or empty canonical field `{key}`"), + )); + } + let input = read_input(input, stdin)?; + let value = if matches!( + normalized.as_str(), + "evidence" + | "code_ref" + | "sources" + | "proof" + | "tags" + | "appears_in" + | "related" + | "verifies" + | "run" + | "procedure" + | "metrics" + | "expected_outcome" + | "baselines" + | "claims_affected" + | "adopted_elements" + ) { + if input.trim_start().starts_with('[') { + let value: Value = serde_json::from_str(&input).map_err(|error| { + AgentError::semantic( + "invalid_field_type", + format!("{key}: invalid JSON sequence: {error}"), + ) + })?; + if !value.is_array() { + return Err(AgentError::semantic( + "invalid_field_type", + format!("{key}: expected JSON array"), + )); + } + value + } else { + Value::String(input) + } + } else if matches!( + normalized.as_str(), + "dependencies" + | "also_depends_on" + | "same_as" + | "source_refs" + | "bound_to" + | "alternatives" + | "artifacts" + | "concepts" + ) { + let value: Value = serde_json::from_str(&input).map_err(|e| { + AgentError::semantic( + "invalid_field_type", + format!("{key}: expected JSON array: {e}"), + ) + })?; + if !value.is_array() { + return Err(AgentError::semantic( + "invalid_field_type", + format!("{key}: expected JSON array"), + )); + } + value + } else if matches!(normalized.as_str(), "promoted" | "stale" | "isolated") { + let value: bool = input.parse().map_err(|_| { + AgentError::semantic( + "invalid_field_type", + format!("{key}: expected true or false"), + ) + })?; + json!(value) + } else { + Value::String(input) + }; + fields.insert(key.into(), value); + } + Ok(fields) +} +fn execute( + root: &Path, + operations: &[WriteOperation], + mode: ApplyMode, + format: &str, + no_duplicate_check: bool, +) -> Result { + let scoring = !no_duplicate_check + && std::env::var("ARA_NO_DUPLICATE_CHECK").as_deref() != Ok("1") + && operations.iter().any(|op| match op { + WriteOperation::NodeAdd { .. } => true, + WriteOperation::ObservationPromote { to, .. } => to == "dead_end", + _ => false, + }); + let (report, duplicates) = + write::execute_with_observer(root, operations, mode, |working, _| { + if scoring { + duplicate_candidates(working) + } else { + Ok(Vec::new()) + } + }) + .map_err(convert_error)?; + let mut value = serde_json::to_value(&report).expect("write report serialization"); + let object = value.as_object_mut().unwrap(); + object.insert("format".into(), json!(format)); + if report.operations.len() == 1 { + let operation = &report.operations[0]; + if let Some(id) = &operation.id { + object.insert("id".into(), json!(id)); + } + if let Some(turn) = operation.turn { + object.insert("turn".into(), json!(turn)); + } + object.insert("no_op".into(), json!(operation.no_op)); + } + let (candidates, advisories) = match duplicates { + Ok(candidates) => (candidates, Vec::new()), + Err(error) => ( + Vec::new(), + vec![format!("duplicate_advisory_unavailable: {error}")], + ), + }; + object.insert("duplicate_candidates".into(), json!(candidates)); + if !advisories.is_empty() { + object.insert("advisories".into(), json!(advisories)); + } + Ok(value) +} +pub fn duplicate_candidates( + working: &write::WorkingArtifact, +) -> Result, AgentError> { + let before = if let Some(file) = working.base.files.get("trace/exploration_tree.yaml") { + let tree = + std::str::from_utf8(&file.bytes).map_err(|error| AgentError::io(error.to_string()))?; + Some( + ara_core::parse_sources(tree, None) + .map_err(|report| { + AgentError::semantic("duplicate_advisory_unavailable", report.to_string()) + })? + .0, + ) + } else { + None + }; + let after = ara_core::parse_sources( + working + .text("trace/exploration_tree.yaml") + .map_err(convert_error)?, + None, + ) + .map_err(|report| AgentError::semantic("duplicate_advisory_unavailable", report.to_string()))? + .0; + duplicate_candidates_from_manifests(before.as_ref(), &after) +} + +pub(crate) fn duplicate_candidates_from_manifests( + before: Option<&ara_core::Manifest>, + after: &ara_core::Manifest, +) -> Result, AgentError> { + let old_ids = before + .into_iter() + .flat_map(|manifest| manifest.nodes.iter().map(|node| node.id.as_str())) + .collect::>(); + let convert = |node: &ara_core::Node| -> Result { + Ok(crate::search::DuplicateText { + id: node.id.to_string(), + title: node.label.clone().unwrap_or_default(), + body: crate::search::node_duplicate_text(node).map_err(|message| { + AgentError::semantic("duplicate_advisory_unavailable", message) + })?, + }) + }; + let existing = before + .into_iter() + .flat_map(|manifest| &manifest.nodes) + .map(convert) + .collect::, _>>()?; + let added = after + .nodes + .iter() + .filter(|node| !old_ids.contains(node.id.as_str())) + .map(convert) + .collect::, _>>()?; + crate::search::duplicate_pairs( + &existing, + &added, + crate::search::DEFAULT_DUPLICATE_THRESHOLD, + crate::search::DEFAULT_DUPLICATE_LIMIT, + ) + .map_err(|error| AgentError::semantic("duplicate_advisory_unavailable", format!("{error:?}"))) +} +pub fn edit(root: &Path, args: &EditArgs) -> Result { + let target = match (&args.id, &args.document) { + (Some(id), None) if args.heading.is_empty() && args.entry.is_none() => { + EntrySelector::Id { id: id.clone() } + } + (None, Some(document)) => EntrySelector::Document { + document: document.clone(), + heading: args.heading.clone(), + entry: args.entry.clone(), + }, + _ => { + return Err(AgentError::semantic( + "invalid_selector", + "Choose one ID or document selector", + )); + } + }; + execute( + root, + &[WriteOperation::EntryEdit { + target, + set: resolve_fields(&args.set)?, + }], + ApplyMode::Commit, + "ara.edit/v1", + true, + ) +} +pub fn logic(root: &Path, args: &LogicArgs, heuristic: bool) -> Result { + let operation = match &args.command { + LogicCommand::Set(args) => WriteOperation::EntryEdit { + target: EntrySelector::Id { + id: args.id.clone(), + }, + set: resolve_fields(&args.set)?, + }, + }; + execute( + root, + &[operation], + ApplyMode::Commit, + if heuristic { + "ara.heuristic/v1" + } else { + "ara.claim/v1" + }, + true, + ) +} +fn read_batch(args: &ApplyArgs) -> Result<(Vec, Vec), AgentError> { + let bytes = if args.file == Path::new("-") { + let mut bytes = Vec::new(); + std::io::stdin() + .read_to_end(&mut bytes) + .map_err(|e| AgentError::io(e.to_string()))?; + bytes + } else { + std::fs::read(&args.file).map_err(|e| AgentError::io(e.to_string()))? + }; + Ok(write::batch::parse_batch_located(&bytes) + .map_err(convert_error)? + .into_iter() + .map(|(line, operation)| (operation, line)) + .unzip()) +} +fn physical_error(mut error: AgentError, lines: &[usize]) -> AgentError { + if let Some(line) = error + .line + .and_then(|line| line.checked_sub(1)) + .and_then(|index| lines.get(index)) + .copied() + { + error.line = Some(line); + if let Some(details) = error.details.as_deref_mut().and_then(Value::as_object_mut) { + details.insert("line".into(), json!(line)); + } + } + // A two-input conflict names its other operation with the same numbering. + if let Some(details) = error.details.as_deref_mut().and_then(Value::as_object_mut) + && let Some(line) = details + .get("related_line") + .and_then(Value::as_u64) + .and_then(|line| (line as usize).checked_sub(1)) + .and_then(|index| lines.get(index)) + .copied() + { + details.insert("related_line".into(), json!(line)); + } + error +} +pub fn apply(root: &Path, args: &ApplyArgs) -> Result { + let (operations, lines) = read_batch(args)?; + execute( + root, + &operations, + if args.dry_run { + ApplyMode::DryRun + } else { + ApplyMode::Commit + }, + "ara.apply/v1", + args.no_duplicate_check, + ) + .map_err(|error| physical_error(error, &lines)) +} +pub fn apply_discover(explicit: Option<&Path>, args: &ApplyArgs) -> Result { + let (operations, lines) = read_batch(args)?; + let initialization = operations + .iter() + .any(|operation| matches!(operation, WriteOperation::ArtifactInit { .. })); + let root = if initialization { + let root = explicit.ok_or_else(|| { + AgentError::setup( + "explicit_root_required", + "artifact.init requires explicit -C for a new or empty root", + ) + })?; + std::env::current_dir() + .map_err(|e| AgentError::io(e.to_string()))? + .join(root) + } else if args.dry_run { + crate::context::discover(explicit)? + } else { + crate::context::discover_writer(explicit)? + }; + execute( + &root, + &operations, + if args.dry_run { + ApplyMode::DryRun + } else { + ApplyMode::Commit + }, + "ara.apply/v1", + args.no_duplicate_check, + ) + .map_err(|error| physical_error(error, &lines)) +} diff --git a/crates/ara-cli/tests/agent_addresses.rs b/crates/ara-cli/tests/agent_addresses.rs new file mode 100644 index 0000000..5f126aa --- /dev/null +++ b/crates/ara-cli/tests/agent_addresses.rs @@ -0,0 +1,687 @@ +//! Heading resolution tiers, canonical read addresses and read-facing errors. +use assert_cmd::Command; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use std::path::Path; +use tempfile::TempDir; + +const DOC: &str = "logic/solution/method.md"; + +fn put(root: &Path, path: &str, text: &str) { + let file = root.join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(file, text).unwrap(); +} +fn artifact(document: &str) -> TempDir { + let dir = TempDir::new().unwrap(); + put( + dir.path(), + "trace/exploration_tree.yaml", + "tree:\n - id: N01\n type: question\n title: Root\n", + ); + put( + dir.path(), + "logic/claims.md", + "# Claims\n\n## C01: Mechanism\n- **Statement**: Known.\n- **Status**: hypothesis\n", + ); + put(dir.path(), DOC, document); + dir +} +fn ara(root: &Path) -> Command { + let mut command = Command::cargo_bin("ara").unwrap(); + command.env_remove("ARA_DIR").arg("-C").arg(root); + command +} +fn show(root: &Path, args: &[&str]) -> Value { + let output = ara(root) + .arg("show") + .args(args) + .args(["--full", "--json"]) + .assert() + .success() + .get_output() + .clone(); + serde_json::from_slice(&output.stdout).unwrap() +} +fn reject(root: &Path, args: &[&str]) -> Value { + let output = ara(root) + .arg("show") + .args(args) + .arg("--json") + .assert() + .code(1) + .stdout("") + .get_output() + .clone(); + let value: Value = serde_json::from_slice(&output.stderr).unwrap(); + value["error"].clone() +} +fn heading(root: &Path, parts: &[&str]) -> Value { + let mut args = vec!["--document", DOC]; + for part in parts { + args.extend(["--heading", *part]); + } + show(root, &args)["entries"][0].clone() +} +fn heading_error(root: &Path, parts: &[&str]) -> Value { + let mut args = vec!["--document", DOC]; + for part in parts { + args.extend(["--heading", *part]); + } + reject(root, &args) +} +fn digest(text: &str) -> String { + format!("sha256:{:x}", Sha256::digest(text.as_bytes())) +} +fn candidates(error: &Value) -> Vec<&str> { + error["details"]["candidates"] + .as_array() + .unwrap() + .iter() + .map(|value| value.as_str().unwrap()) + .collect() +} + +#[test] +fn exact_full_vector_and_exact_suffix_win_before_tolerant_tiers() { + let dir = artifact( + "# Method\n## B\nsuffix\n## Results\nupper\n## results\nlower\n# B\ntop\n## Step 3: Train\ntrain\n", + ); + // The full vector ['B'] names the top-level section, not the suffix match. + assert_eq!( + heading(dir.path(), &["B"])["content"], + "top\n## Step 3: Train\ntrain\n" + ); + assert_eq!(heading(dir.path(), &["Method", "B"])["content"], "suffix\n"); + // Exact case wins over the case-insensitive collision. + assert_eq!(heading(dir.path(), &["results"])["content"], "lower\n"); + assert_eq!(heading(dir.path(), &["Results"])["content"], "upper\n"); + // Without an exact match, normalized equality collides and rejects. + let error = heading_error(dir.path(), &["RESULTS"]); + assert_eq!(error["code"], "ambiguous_heading"); + assert_eq!( + candidates(&error), + [ + "logic/solution/method.md#h/Method/Results", + "logic/solution/method.md#h/Method/results" + ] + ); + assert_eq!(error["details"]["capped"], false); + // Trimmed, case-insensitive unique prefix. + let train = heading(dir.path(), &[" step 3 "]); + assert_eq!(train["content"], "train\n"); + assert_eq!(train["digest"], digest("train\n")); + assert_eq!(train["heading"], json!([" step 3 "])); + assert_eq!(train["heading_path"], json!(["B", "Step 3: Train"])); + assert_eq!( + train["address"], + "logic/solution/method.md#h/B/Step%203%3A%20Train" + ); + // Native-ID shorthand still selects claims. + let claim = show( + dir.path(), + &["--document", "logic/claims.md", "--heading", "C01"], + ); + assert!( + claim["entries"][0]["content"] + .as_str() + .unwrap() + .contains("Known.") + ); +} + +#[test] +fn trailing_ellipsis_matches_only_in_the_final_tier() { + let dir = artifact( + "# Method\n## Eval on long...\nlong\n## Results...\nliteral\n## Results on short inputs\nshort\n## ...\nbare\n", + ); + assert_eq!( + heading(dir.path(), &["Eval on long sequences"])["content"], + "long\n" + ); + // An exact heading containing `...` wins first. + assert_eq!(heading(dir.path(), &["Results..."])["content"], "literal\n"); + // A unique prefix is a stronger tier than the ellipsis tier. + assert_eq!( + heading(dir.path(), &["results on short"])["content"], + "short\n" + ); + // A bare `...` has an empty prefix and never matches a longer request. + assert_eq!( + heading_error(dir.path(), &["Unrelated"])["code"], + "unknown_id" + ); +} + +#[test] +fn literal_slash_vectors_have_distinct_canonical_addresses_that_round_trip() { + let dir = artifact("# Arch\n## A/B\nliteral\n## A\n### B\nnested\n"); + let literal = heading(dir.path(), &["Arch", "A/B"]); + let nested = heading(dir.path(), &["Arch", "A", "B"]); + assert_eq!(literal["content"], "literal\n"); + assert_eq!(nested["content"], "nested\n"); + assert_eq!(literal["address"], "logic/solution/method.md#h/Arch/A%2FB"); + assert_eq!(nested["address"], "logic/solution/method.md#h/Arch/A/B"); + for read in [&literal, &nested] { + let address = read["address"].as_str().unwrap(); + let again = show(dir.path(), &[address])["entries"][0].clone(); + assert_eq!(again["content"], read["content"]); + assert_eq!(again["digest"], read["digest"]); + assert_eq!(again["heading"], read["heading_path"]); + assert_eq!(again["address"], address); + } + // Legacy flattened input resolves only when it identifies one section. + let error = reject(dir.path(), &["logic/solution/method.md#Arch/A/B"]); + assert_eq!(error["code"], "ambiguous_heading"); + assert_eq!( + candidates(&error), + [ + "logic/solution/method.md#h/Arch/A%2FB", + "logic/solution/method.md#h/Arch/A/B" + ] + ); + let unique = artifact("# Method\n## Step 3\nthree\n"); + let read = show(unique.path(), &["logic/solution/method.md#Method/Step 3"]); + assert_eq!(read["entries"][0]["content"], "three\n"); + assert_eq!( + read["entries"][0]["address"], + "logic/solution/method.md#h/Method/Step%203" + ); + // Entry IDs, native forms and whole documents stay accepted positionally. + for id in ["C01", "logic/claims.md#C01", "trace:N01", "N01"] { + assert!( + show(unique.path(), &[id])["entries"][0] + .get("kind") + .is_some() + ); + } + let whole = show(unique.path(), &["logic/claims.md"]); + assert_eq!(whole["entries"][0]["address"], "logic/claims.md"); +} + +#[test] +fn percent_escaping_encodes_reserved_bytes_and_rejects_malformed_addresses() { + let dir = artifact("# Arch\n## Résumé; 50% done\nescaped\n"); + put(dir.path(), "logic/my notes.md", "# Notes\n## Plan\nplan\n"); + let read = heading(dir.path(), &["Arch", "Résumé; 50% done"]); + assert_eq!( + read["address"], + "logic/solution/method.md#h/Arch/R%C3%A9sum%C3%A9%3B%2050%25%20done" + ); + let again = show(dir.path(), &[read["address"].as_str().unwrap()]); + assert_eq!(again["entries"][0]["content"], "escaped\n"); + let notes = show(dir.path(), &["logic/my%20notes.md#h/Notes/Plan"]); + assert_eq!(notes["entries"][0]["content"], "plan\n"); + assert_eq!( + notes["entries"][0]["address"], + "logic/my%20notes.md#h/Notes/Plan" + ); + let whole = show(dir.path(), &["logic/my%20notes.md"]); + assert_eq!(whole["entries"][0]["address"], "logic/my%20notes.md"); + assert_eq!(whole["entries"][0]["content"], "# Notes\n## Plan\nplan\n"); + for malformed in [ + "logic/solution/method.md#h/Arch/A%2", + "logic/solution/method.md#h/Arch/%ZZ", + "logic/solution/method.md#h/Arch/%FF", + "logic/solution/method.md#h/Arch;occurrence=0", + "logic/solution/method.md#h/Arch;occurrence=01", + "logic/solution/method.md#h/Arch;sort=1", + ] { + assert_eq!(reject(dir.path(), &[malformed])["code"], "invalid_address"); + } + for outside in [ + "%2E%2E/outside.md#h/A", + "../outside.md#h/A", + "/etc/outside.md#h/A", + "rubric/requirements.md#h/R01", + ] { + assert_eq!(reject(dir.path(), &[outside])["code"], "invalid_document"); + } +} + +#[test] +fn duplicate_full_vectors_need_an_occurrence() { + let dir = artifact("# M\n## Dup\none\n## Dup\ntwo\n"); + let error = heading_error(dir.path(), &["Dup"]); + assert_eq!(error["code"], "ambiguous_heading"); + let expected = [ + "logic/solution/method.md#h/M/Dup;occurrence=1", + "logic/solution/method.md#h/M/Dup;occurrence=2", + ]; + assert_eq!(candidates(&error), expected); + let unqualified = reject(dir.path(), &["logic/solution/method.md#h/M/Dup"]); + assert_eq!(unqualified["code"], "ambiguous_heading"); + assert_eq!(candidates(&unqualified), expected); + for (address, body) in expected.iter().zip(["one\n", "two\n"]) { + let read = show(dir.path(), &[address])["entries"][0].clone(); + assert_eq!(read["content"], body); + assert_eq!(read["digest"], digest(body)); + assert_eq!(read["address"], *address); + assert_eq!(read["heading"], json!(["M", "Dup"])); + } + assert_eq!( + reject( + dir.path(), + &["logic/solution/method.md#h/M/Dup;occurrence=3"] + )["code"], + "unknown_id" + ); + // Native cited forms do not depend on the merge index representing + // every unrelated document. + for id in ["logic/claims.md#C01", "logic/claims.md:C01", "trace:N01"] { + assert!( + show(dir.path(), &[id])["entries"][0].get("id").is_some(), + "{id}" + ); + } + let legacy = reject(dir.path(), &["logic/solution/method.md#M/Dup"]); + assert_eq!(legacy["code"], "ambiguous_heading"); + assert_eq!(candidates(&legacy), expected); + // Canonical addresses never fall back to tolerant matching. + assert_eq!( + reject( + dir.path(), + &["logic/solution/method.md#h/m/dup;occurrence=1"] + )["code"], + "unknown_id" + ); +} + +#[test] +fn candidates_are_capped_ranked_and_deterministic() { + let mut document = String::from("# Items\n"); + for index in 1..=45 { + document.push_str(&format!("## Item {index:02}\nbody {index}\n")); + } + let dir = artifact(&document); + let first = heading_error(dir.path(), &["Item 7"]); + assert_eq!(first["code"], "unknown_id"); + assert_eq!(first["details"]["capped"], true); + let listed = candidates(&first); + assert_eq!(listed.len(), 40); + assert_eq!(listed[0], "logic/solution/method.md#h/Items/Item%2007"); + assert_eq!(heading_error(dir.path(), &["Item 7"]), first); + let entry = reject(dir.path(), &["C1"]); + assert_eq!(entry["code"], "unknown_id"); + assert_eq!(candidates(&entry)[0], "C01"); + assert_eq!(entry["details"]["capped"], false); +} + +#[test] +fn heading_misses_in_ledger_artifacts_do_not_leak_merge_codes() { + let dir = artifact("# Method\n## Step 3: Train\ntrain\n"); + put(dir.path(), "trace/logic_mutations.yaml", "mutations: []\n"); + let miss = heading_error(dir.path(), &["Missing"]); + assert_eq!(miss["code"], "unknown_id"); + assert_eq!( + candidates(&miss), + [ + "logic/solution/method.md#h/Method", + "logic/solution/method.md#h/Method/Step%203%3A%20Train" + ] + ); + assert_eq!(reject(dir.path(), &["C99"])["code"], "unknown_id"); + assert_eq!( + heading(dir.path(), &["step 3"])["content"], + "train\n", + "tolerant tiers still run after the archived lookup misses" + ); + // A corrupt alias index keeps a truthful, non-merge diagnostic, with or + // without a mutation ledger beside it. + put(dir.path(), "trace/aliases.yaml", "aliases: 7\n"); + let aliases_only = artifact("# Method\n"); + put(aliases_only.path(), "trace/aliases.yaml", "aliases: 7\n"); + assert_eq!( + reject(aliases_only.path(), &["trace:N01"])["code"], + "identity_lookup_failed" + ); + for error in [ + heading_error(dir.path(), &["Missing"]), + reject(dir.path(), &["C99"]), + ] { + let code = error["code"].as_str().unwrap(); + assert_eq!(code, "identity_lookup_failed", "{error}"); + assert!(!error.to_string().contains("merge."), "{error}"); + } + // Exact reads never consult the identity records. + assert_eq!( + heading(dir.path(), &["Method"])["heading"], + json!(["Method"]) + ); +} + +#[test] +fn native_shorthand_mixes_with_literal_segments_in_vectors_and_legacy_fragments() { + let dir = artifact("# Top\n## C04: Alpha\nalpha\n## C04b extra\nbeta\n"); + // Literal `Top` plus shorthand `C04` is an exact tier, ahead of the + // tolerant prefix that would also match `C04b extra`. + assert_eq!(heading(dir.path(), &["Top", "C04"])["content"], "alpha\n"); + assert_eq!( + show(dir.path(), &["logic/solution/method.md#Top/C04"])["entries"][0]["content"], + "alpha\n" + ); + put( + dir.path(), + "logic/problem.md", + "# Problem\n## O1: First observation\nfirst\n## O2: Second\nsecond\n## O2\nliteral\n", + ); + let structured = show( + dir.path(), + &["--document", "logic/problem.md", "--heading", "O1"], + ); + let legacy = show(dir.path(), &["logic/problem.md#O1"]); + assert_eq!(legacy["entries"][0]["content"], "first\n"); + assert_eq!( + legacy["entries"][0]["digest"], + structured["entries"][0]["digest"] + ); + // A legacy fragment still has to identify exactly one section. + let error = reject(dir.path(), &["logic/problem.md#O2"]); + assert_eq!(error["code"], "ambiguous_heading"); + assert_eq!( + candidates(&error), + [ + "logic/problem.md#h/Problem/O2%3A%20Second", + "logic/problem.md#h/Problem/O2" + ] + ); +} + +#[test] +fn positional_document_paths_pass_the_document_boundary() { + let dir = artifact("# Method\n"); + for outside in [ + "/etc/hosts", + "../outside.md", + "logic/%2E%2E/PAPER.md", + "%2Fetc%2Fhosts", + "rubric/requirements.md", + ] { + let error = reject(dir.path(), &[outside]); + assert_eq!(error["code"], "invalid_document", "{outside}"); + assert!(error["details"]["file_access"].is_array(), "{outside}"); + } + // A valid path naming no document is an ordinary miss. + assert_eq!( + reject(dir.path(), &["logic/missing.md"])["code"], + "unknown_id" + ); +} + +#[test] +fn occurrence_one_names_a_unique_vector_and_higher_occurrences_miss() { + let dir = artifact("# M\n## Only\nonly\n"); + let read = show( + dir.path(), + &["logic/solution/method.md#h/M/Only;occurrence=1"], + ); + assert_eq!(read["entries"][0]["content"], "only\n"); + assert_eq!( + read["entries"][0]["address"], + "logic/solution/method.md#h/M/Only" + ); + assert_eq!( + reject( + dir.path(), + &["logic/solution/method.md#h/M/Only;occurrence=2"] + )["code"], + "unknown_id" + ); +} + +#[test] +fn colliding_entry_keys_report_an_ambiguity() { + let dir = artifact("# M\n"); + put( + dir.path(), + "logic/concepts.md", + "# Concepts\n\n## N01\n\n- **Definition**: Named like a node.\n", + ); + let error = reject(dir.path(), &["N01"]); + assert_eq!(error["code"], "ambiguous_heading"); + assert!(!error["message"].as_str().unwrap().contains("section")); + // Scoped native forms still select one namespace each. + assert_eq!( + show(dir.path(), &["trace:N01"])["entries"][0]["kind"], + "question" + ); + assert_eq!( + show(dir.path(), &["logic/concepts.md#N01"])["entries"][0]["kind"], + "concept" + ); +} + +#[test] +fn recorded_ambiguity_is_not_overridden_by_a_unique_current_section() { + use ara_core::write::{self, ArtifactSnapshot, EntrySelector, WorkingArtifact, WriteOperation}; + const ARCH: &str = "logic/solution/architecture.md"; + let dir = artifact("# M\n"); + put(dir.path(), ARCH, "# Top\n## A\n### B\nnested\n"); + let mut working = WorkingArtifact::new(ArtifactSnapshot::load(dir.path()).unwrap()); + for value in [ + json!({"op":"session.start","id":"2026-10-01_001","date":"2026-10-01","started":"2026-10-01T10:00","summary":"Rename fixture"}), + json!({"op":"session.log","session":"2026-10-01_001","timestamp":"2026-10-01T10:01"}), + ] { + write::plan_operation(&mut working, &serde_json::from_value(value).unwrap()).unwrap(); + } + let target = EntrySelector::Document { + document: ARCH.into(), + heading: vec!["Top".into(), "A".into()], + entry: None, + }; + let range = write::logic::resolve(&working, &target).unwrap().range; + let expected = write::source::digest(working.text(ARCH).unwrap()[range].as_bytes()); + write::plan_operation( + &mut working, + &WriteOperation::EntryRename { + target, + name: "Q".into(), + expected, + references: vec![], + session: Some("2026-10-01_001".into()), + turn: Some(1), + signal: Some("user-directive".into()), + provenance: Some("user".into()), + rewrite_references: false, + }, + ) + .unwrap(); + for revision in std::mem::take(&mut working.revisions) { + write::sessions::append_revision( + &mut working, + &revision.session, + revision.turn, + &revision.record, + ) + .unwrap(); + } + for (path, bytes) in &working.files { + put(dir.path(), path, std::str::from_utf8(bytes).unwrap()); + } + // One current section spells `A/B`; the archived vector ['Top','A','B'] + // spells it too, so the recorded identities call `#A/B` ambiguous. + let renamed = std::fs::read_to_string(dir.path().join(ARCH)).unwrap(); + assert!(renamed.contains("## Q\n"), "{renamed}"); + put(dir.path(), ARCH, &format!("{renamed}## A/B\nliteral\n")); + let error = reject(dir.path(), &["logic/solution/architecture.md#A/B"]); + assert_eq!(error["code"], "ambiguous_heading", "{error}"); + // The structured selector and the canonical address still read it. + assert_eq!( + show(dir.path(), &["logic/solution/architecture.md#h/Top/A%2FB"])["entries"][0]["content"], + "literal\n" + ); +} + +/// Stdout of a successful brief (default text) read. +fn brief(root: &Path, args: &[&str]) -> String { + let output = ara(root).args(args).assert().success().get_output().clone(); + String::from_utf8(output.stdout).unwrap() +} +/// The address that leads a brief list or relation row. +fn addresses(stdout: &str) -> Vec { + stdout + .lines() + .filter(|line| !line.starts_with(' ') && !line.starts_with("target: ")) + .filter(|line| !line.starts_with("direct files: ")) + // A prose mention leads with `source:line`, not an address. + .filter(|line| !line.contains("\tpossible mention\t")) + .map(|line| { + let line = line.trim_start(); + let end = [line.find('\t'), line.find(" [")] + .into_iter() + .flatten() + .min() + .unwrap_or(line.len()); + line[..end].to_owned() + }) + .collect() +} +/// The `==
[