Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat: answer trust - verified quotes, claim provenance and durable source evidence (v1.81.0) (#249)
Serg Eroshe323fb9e4da30
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 6a71e71f..5af94f15 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.80.0",+ "version": "1.81.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 257100bb..6a9ec0c3 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.80.0",+ "version": "1.81.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/.gitignore b/.gitignoreindex d90e03a1..ac720a8f 100644--- a/.gitignore+++ b/.gitignore@@ -45,3 +45,6 @@ sandbox-vault/# Personal editor ignore files (ZCode and similar): per-machine, never committed..zcodeignore++# Operator-handed external review scratch: never tracked (security reproductions stay out of the public repository)+.reviews/diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 901b10b8..a6226e41 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,27 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.81.0] - 2026-10-11++Open Second Brain 1.81.0 is the answer-trust release: it narrows the gap between what an agent was given and what its answer can be believed on. A Stop-hook step now checks the quotations in the assistant's own answer against the note cited for them or the evidence the injection ledger actually delivered, a stated claim can name the context-pack sample it drew on and read the receipt and outcome provenance back, trusted local-file ingest keeps the source's bytes in a durable content-addressed archive instead of trusting a file to stay where it was, and a record with no session is read as no-session everywhere instead of pooling into one phantom bucket. A repair lane closes the outstanding review findings: attribute narrowing in search no longer silently excludes documents whose indexed snapshot has gone stale, and the wave's own review hardened the annotation channel, the provenance reach and the archive's write path.++### Added++- **Answer-time quote verification, shadow by default.** A new Stop-hook step registered after the stop-log guardrail walks the last assistant messages of the turn, finds quoted spans with the distill lane's quote helpers (imported, never forked), resolves each span's evidence - a note named in the span's context by wikilink or vault-relative path, else membership in the injection ledger's delivered notes for the phases actually running - and checks it through a pure module over five verdicts: `verified`, `not-in-note`, `source-truncated`, `note-unavailable` and `not-text`. Degradation never upgrades a verdict: a note whose body reached context truncated is matched against the prefix that was delivered, and a miss there is `source-truncated`, never `not-in-note`; a note that cannot be read is `note-unavailable`, because "we could not check" is a finding, not an all-clear. One `additionalContext` annotation per turn lists the unverified spans as flattened, capped previews; Claude Code renders it and the other registered runtimes stay silent. The step never blocks, never edits a transcript, and reads a bounded message window under character and wall-clock caps, failing open with exit 0. Configuration is per phase in the `quote_check` block of `Brain/_brain.yaml` - `recall`, `active` and `subagent`, each `off|shadow|enforce`, default `shadow` (annotate-only), scoped to the phases whose injection the vault enabled - and `enforce` additionally appends exactly one Brain-log `note` event per turn carrying the counts and the finding lines, so findings survive the session.+- **Statement-level claim attribution.** `brain_truth state` and `o2b brain truth state` accept an optional opaque `sample_id` (CLI `--sample-id`) frozen on the committed claim event - schema version unchanged, omitted when absent, never invented - and claim reads hydrate the provenance behind it: the named context receipt's items plus the context-pack outcome row, joined read-only, one ledger read per report. Provenance is shaped by the caller's reach - below local reach, receipt items whose injections came from operator rules and item paths the caller cannot read stay hidden, so a claim's `sample_id` never leaks what the receipts surface refuses to say directly - and the join is omit-don't-invent in both directions: a claim whose outcome never arrived reports "receipt known, outcome unknown", a claim timestamped before its claimed receipt is flagged as an inversion rather than silently joined, and a row without a `sample_id` renders byte-identically to before.+- **A durable source archive behind trusted local ingest.** Ingesting a trusted local source now reads the file once and archives its bytes content-addressed at `Brain/.archives/<sha256>.txt` - redacted before persist so credentials never land in a second file, refused past a 1 MiB ceiling rather than truncated (an oversized source is simply not captured, and absence on the page still means exactly "not captured"), deduplicated by its own hash, and never TTL-pruned: evidence, not scratch. Success stamps `source_archive_hash` and `source_archive_bytes` on the summary page and returns `source_archive_hash` on the ingest result; visibility tokens hold, so a source whose digest is refused to remote readers is never archived and remote reach never reads archived bytes. The capture-scope hygiene detector names a page whose archive is missing or no longer matches its stamp, `o2b brain doctor` prints a count-only archive section (entries, bytes, missing, mismatched, uncited - no fix verb, pruning and recapture are operator calls), `brain_hygiene` gains `archive_get`, which resolves a summary page's stamp to its archived bytes at local reach only, and delete-by-source cleanup removes the source's orphaned entries best-effort.+- **Explicit no-session identity.** A missing or non-string `session_id` is treated as no-session explicitly at every reader: scoped recall excludes the record, grouping sites skip it instead of lumping it into a shared bucket, and the session-summary digest omits the key rather than answering `""` - dissolving the phantom session that quietly collected every unattributed record from every unrelated lane. A new count-only, fail-soft doctor check, `blank-session-identity`, reports one issue per affected record kind with a count; no payload is rewritten and no repair verb ships, because the continuity store is append-only and repair belongs to a backup-gated posture.++### Changed++- **Docs:** `docs/cli-reference.md` documents the `truth events`/`truth state` verbs with `--sample-id` and provenance-hydrated reads, the widened capture-scope detector and the doctor's archive section; `docs/mcp.md` covers `archive_get` on `brain_hygiene`, the archive stamp on the ingest result and the claim provenance hydration; `docs/observability.md` documents the quote-check surface and the no-session rule with its doctor count; `hooks/README.md` gains the new Stop step; the README names the release and extends the claim-ledger capability.++### Fixed++- **A stale attribute snapshot no longer silently excludes a document from search.** The property pushdown narrowed the candidate pool against the indexed `document_attributes` snapshot while advertising the live file as the final judge, so a document whose indexed snapshot no longer matched its file - a draft flipped to done - dropped out of a `status=done` query before the live post-rank filter ever saw it. A store-level freshness gate now compares a candidate's indexed snapshot against the live document during narrowing: a proven-fresh candidate keeps its SQL exclusion without touching the filesystem, a stale one falls through to the lane read without the exclusion fragment and is judged by the live filter, and absent filters still compile byte-identical SQL.+- **Review hardening across the wave.** The external reviews of this wave hardened what landed: the annotation's findings render as flattened previews under a character cap, the cited-note read is bounded and the transcript tail-window read advances in pages instead of scanning whole files, the archive stats path resolves its root through the containment check before it stats anything, and the archive stamp's single-writer assumption is pinned as an architecture census beside the claim-attribution one.+- **Two damaged CHANGELOG entries read as written again.** Whitespace that had collapsed inside the v1.72.0 cost entry (words running together around `estimated_cost_usd` and `search status`) and the v1.19.0 post-compact-audit block (a lost indent) is repaired; prose only, no claim changed.+## [1.80.0] - 2026-10-11Open Second Brain 1.80.0 raises what recall can reach and what the store can answer for itself, on both ends of the pipeline: what enters the graph is gated by what the vault itself has learned, and what the store can filter is answered by the index instead of by per-row file reads. Entity creation consults a store-learned lexicon with two new structural verdicts, session imports mine precision mentions into a hallways graph an operator reviews before anything is promoted, the search store's v14 migration pushes `kind` and promoted frontmatter keys into SQL on both lanes and hydrates in two tiers, the rerank eval reports per language, and recall telemetry names its dead weight. A repair lane closes every outstanding operator-review finding from the two previous release reviews, and two release-note claims those reviews falsified are corrected here.@@ -261,7 +282,7 @@ Open Second Brain now prices embedding spend honestly: every estimate names wher### Changed-- **An unknown price reads as unknown, never as $0.** The maintenance banner, the backfill dry run and `search status` print `price unknown` where they used to print `$0.0000` for an unlisted model, and the JSON estimates (`estimated_cost_usd`, `estimated_usd`, the status refresh estimate) are `null`. The backfill's `estimated_cost_usd`used to be omitted for an unknown price and is now always present. A fully embedded index has nothing pending, so`search status`then prints no`refresh_cost_est`line and its JSON estimate is`0`.+- **An unknown price reads as unknown, never as $0.** The maintenance banner, the backfill dry run and `search status` print `price unknown` where they used to print `$0.0000` for an unlisted model, and the JSON estimates (`estimated_cost_usd`, `estimated_usd`, the status refresh estimate) are `null`. The backfill's `estimated_cost_usd` used to be omitted for an unknown price and is now always present. A fully embedded index has nothing pending, so `search status` then prints no `refresh_cost_est` line and its JSON estimate is `0`.- **A positive cost gate now refuses an unpriced model.** Before this release a model missing from the price table was priced at $0, so a positive `embedding_cost_gate_usd` never stopped it; local servers (Ollama, LM Studio, llama.cpp) and any unlisted model are now refused with `EMBEDDING_COST_UNPRICED` until their price is declared or the run is forced. With the gate at 0, the default, nothing is refused.- **Spend receipts carry the price source.** Receipts, the `maintenance_spend` metric, the backfill JSON and the status JSON (`refresh_price_source`) gain `price_source`, and `o2b brain maintenance status` lists each receipt with it; journal rows written before this release read `unrecorded`, and a journaled receipt without a numeric estimate reads `price unknown` instead of failing the whole listing. `brain_maintenance` spend receipts carry a null `estimated_usd` for an unknown price.- **`brain_context_pack` caps `query` at 2000 characters.** The cap is declared in the schema and enforced in every query mode, counted in Unicode code points as the schema's `maxLength` counts them, and a blank `query` is refused with `INVALID_PARAMS` in `semantic` mode. `brain_search` now counts its 2000-character cap the same way, so a query of characters outside the Basic Multilingual Plane is no longer refused at half the advertised length. `brain_recall_feedback`, which advertised the same `maxLength` without checking it, now refuses a longer `query` with the same `INVALID_PARAMS` error before it records anything.@@ -2447,7 +2468,7 @@ byte-identical until opted in. The kernel still calls no LLM.re-asserted via `appendPinnedContext`, so survivors cost zero tokens.Fail-open throughout (every recoverable error lands in `errors`, neverthrown), with a bounded drift log. Surfaced as the `o2b brain-post-compact-audit` CLI verb and gated by `post_compact_survival_audit`+ post-compact-audit` CLI verb and gated by `post_compact_survival_audit`(default OFF, env/config), with `--force` for diagnostics; unchangedinstalls stay byte-identical.@@ -8428,6 +8449,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.81.0]: https://github.com/itechmeat/open-second-brain/compare/v1.80.0...v1.81.0[1.80.0]: https://github.com/itechmeat/open-second-brain/compare/v1.79.0...v1.80.0[1.79.0]: https://github.com/itechmeat/open-second-brain/compare/v1.78.0...v1.79.0[1.78.0]: https://github.com/itechmeat/open-second-brain/compare/v1.77.0...v1.78.0diff --git a/README.md b/README.mdindex ddee3ba6..7b4834d1 100644--- a/README.md+++ b/README.md@@ -101,7 +101,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi- **Search.** Keyword search with an optional semantic lane, result explanations, recall profiles and compact cards: [search CLI](docs/cli-reference.md#search), [ranking](docs/how-it-works.md#full-text-search).- **Session recall.** Import agent transcripts already on disk and search them: [session logs](docs/cli-reference.md#session-logs-this-machine-already-has-since-v1500).- **Hygiene.** `o2b brain hygiene scan` finds contested, duplicate, stale and unused memories; `apply` runs only the findings you pick: [maintenance](docs/cli-reference.md#maintenance-and-operator-surfaces).-- **Claim ledger.** `o2b brain truth ingest` records an entity claim with an optional validity window (`--valid-from`/`--valid-until`; with the flags absent, a window on the source record's frontmatter is adopted and frozen at ingest), `truth events` recalls a windowed slice of the ledger, and `truth state` grounds an agent-stated claim with an anchoring verdict - committed, or reported back with reason codes: [entity truth CLI](docs/cli-reference.md#entity-truth-and-self-improving-dream-since-v0430).+- **Claim ledger.** `o2b brain truth ingest` records an entity claim with an optional validity window (`--valid-from`/`--valid-until`; with the flags absent, a window on the source record's frontmatter is adopted and frozen at ingest), `truth events` recalls a windowed slice of the ledger, and `truth state` grounds an agent-stated claim with an anchoring verdict - committed, or reported back with reason codes. `truth state` accepts an optional opaque `--sample-id` naming the context-pack sample the claim drew on, and claim reads report the receipt and outcome provenance behind it at the caller's reach - "receipt known, outcome unknown", never an invented verdict: [entity truth CLI](docs/cli-reference.md#entity-truth-and-self-improving-dream-since-v0430).- **Corrections.** `o2b brain lifecycle correct <target>` reports a correction's blast radius and retires the affected records - validity-closed by default, tombstoned with `--flatly-wrong`, dry run by default and `--apply` to write. A retired record that recall can still serve is served only beside its correction, never alone: [belief lifecycle CLI](docs/cli-reference.md#belief-lifecycle-and-decision-memory-since-v1330).- **Sharing and backup.** Knowledge packs export a chosen subset; `o2b brain bank-export` writes a one-file backup bundle: [knowledge packs](docs/cli-reference.md#knowledge-packs).- **Secret custody.** Credentials live encrypted in the vault's state dir behind a capability-gated store; `$secret:NAME` references resolve at the use sites, `o2b brain secret unlock` wraps the keyfile under a passphrase, and `secret export`/`import` move the store between installs as one passphrase-encrypted bundle: [custody CLI](docs/cli-reference.md#write-time-integrity-and-governance-since-v0440).@@ -123,7 +123,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi## What is new-1.80.0 raises what recall can reach and what the store can answer for itself. Entity creation learns from the vault: a store-learned lexicon (`o2b brain entity lexicon rebuild`) feeds tightened admission verdicts for all-caps headings and common-word labels, while code-shaped and caseless-script labels keep admitting, and a stale artifact degrades fail-open. Session imports mine precision mentions - code symbols, URLs, paths, qualified identifiers - into a ledger that `o2b brain hallways mine|show|promote|dismiss` folds into reviewable associations; promotion through the admission gate is the only bridge into the registry. Open Second Brain's v14 store migration pushes `kind` (`page`/`section`) into SQL on both lanes and pushes the promoted frontmatter keys where the push is faithful to the live filter (`type` scalar values, `pinned: true`, `visibility`; `tags` and non-scalar shapes stay post-rank), while unpromoted property keys narrow the candidate pool against the indexed attribute snapshot with the live file as the arbiter - answered as indexed, a documented divergence - with sargable path prefixes and a two-tier hydration cut. `o2b search rerank-eval` splits its report per language for bilingual datasets, and `brain_recall_telemetry` gains a `dead_weight` view (CLI `o2b brain recall-telemetry dead-weight`) naming in-scope pages no recorded recall ever surfaced. A repair lane closes the outstanding review findings: permission-rule targets canonicalize across path spellings, an ingest `stage` verdict now stages the entity pages and the manifest row it creates (not just the summary page), `delete_by_source` and schema mutations consult the permissions document and refuse on deny, the research pool reads the vault-resolved configuration, the unlock flow nudges toward export-before-wrap, and a bundle allowlist of `*` warns by name. Every release is described in the [CHANGELOG](CHANGELOG.md).+1.81.0 is the answer-trust release: it narrows the gap between what an agent was given and what its answer can be believed on. A Stop-hook step verifies the quotations in the assistant's answer against the note cited for them or the evidence recall actually injected (`quote_check.recall|active|subagent` in `Brain/_brain.yaml`, each `off|shadow|enforce`, default `shadow` - annotate-only, one `additionalContext` note per turn; `enforce` adds one Brain-log record per turn). `o2b brain truth state` accepts an optional opaque `--sample-id` naming the context-pack sample a claim drew on, and claim reads report the receipt and outcome provenance behind it at the caller's reach. Trusted local-file ingest now archives a source's bytes content-addressed under `Brain/.archives/` (redacted before persist, refused past 1 MiB, never pruned) with the hash stamped on the summary page; the capture-scope hygiene detector and a count-only doctor section name missing or mismatched evidence, and `brain_hygiene` `archive_get` reads an entry back at local reach. A record with no session id is read as no-session everywhere - scoped recall excludes it, grouping skips it, the session digest omits the key - dissolving the phantom blank-session bucket, with a count-only `blank-session-identity` doctor check for what older writers left behind. A repair lane closes the outstanding review findings: attribute narrowing in search falls a document whose indexed snapshot went stale through to the live filter instead of silently excluding it. Every release is described in the [CHANGELOG](CHANGELOG.md).## Documentationdiff --git a/docs/brainstorm/answer-trust/cli-output/consultant.md b/docs/brainstorm/answer-trust/cli-output/consultant.mdnew file mode 100644index 00000000..284d995e--- /dev/null+++ b/docs/brainstorm/answer-trust/cli-output/consultant.md@@ -0,0 +1,38 @@+### Variant 1: Independent lanes at natural seams+- **Approach**: Each card lands exactly where its verified premises point, with no shared machinery beyond the existing vault layout: A as a new Stop-hook step plus src/core/brain/answer-quotes/check.ts with a per-phase quote_check resolver (off|shadow|enforce, shadow default); B as the optional sample_id field frozen on ClaimEvent plus the read-only claim-provenance.ts join; C as provenance/source-archive.ts wired into the distill intake path; D as explicit no-session semantics in the five reader sites plus the count-only blank-session-identity doctor check. Config stays per-feature in src/core/config.ts, doctor checks register individually in DOCTOR_CHECKS, and each card carries its own census test. The repair lane (property-pushdown freshness gate, CHANGELOG whitespace) rides along independently of all four.+- **Trade-offs**:+ - Matches the house parallel-lane process: disjoint file ownership, each card testable and revertible in isolation.+ - The hot path is touched by exactly one component (the A hook step), bounded and fail-open as the constraints require.+ - No sequencing constraints between lanes, so the PR assembles at merge time with minimal coordination.+ - Wave coherence is editorial, not structural: nothing in the code expresses claim → receipt → note → archived source as one chain.+ - Small risk of duplicated utility logic (hashing, redaction interplay, span normalization) across lanes that a shared home would consolidate.+ - A later cross-card feature, such as quote verification against archived bytes, would need a second pass.+- **Complexity**: small+- **Risk**: low++### Variant 2: Provenance spine (B and C fuse into one chain)+- **Approach**: Make src/core/brain/provenance/ the structural center of the wave: C's source-archive.ts and B's claim-provenance.ts live there under one integrity contract (content-addressed, redacted-before-persist, doctor-verified presence), so the read-time join resolves claim → receipt → note → source_archive_hash as a single chain terminating in durable bytes. A and D keep their prescribed shapes unchanged, with A's hook step still bounded and fail-open, but the doctor family and census tests guard the whole chain invariant instead of per-card fragments. The repair lane still rides along independently.+- **Trade-offs**:+ - The wave spine becomes literal: a claim's provenance can end at content-addressed bytes that survive link rot, the strongest trust story available this wave.+ - One integrity contract and one doctor family avoid scattered, inconsistent verify logic and duplicated hashing/redaction utilities.+ - Seeds future work cleanly: A verifying against archived bytes later is additive, not a redesign.+ - Lanes B and C share the provenance home, breaking strict disjoint file ownership and forcing C's format to land before B's join consumers.+ - Coupling crosses card boundaries: a regression in C's capture marks B's chain incomplete, widening the blast radius of each lane.+ - More up-front design for a chain whose only consumer this wave is doctor/CLI reporting, since OSB never sees answer text.+- **Complexity**: medium+- **Risk**: medium++### Variant 3: Unified answer-trust phase ladder+- **Approach**: Compose the wave around one config namespace, answer_trust, with a single per-phase ladder (off|shadow|enforce) governing all cards at once: A's quote checking, C's capture scope (shadow = best-effort capture, enforce = refuse-not-truncate ingest without an archive entry), and B's join surfacing (shadow = doctor/CLI report, enforce = provenance annotations on claim reads). D sits outside the ladder because its decision is semantic and fixed, and the repair lane is unaffected. This trades per-feature resolvers for one operational dial across the whole trust surface.+- **Trade-offs**:+ - One mental model for operators: a single phase readout answers "how much trust machinery is on" without consulting four resolvers.+ - Shadow-by-default propagates consistently, and per-phase switchability is preserved across the wave.+ - Conflates independent failure domains: one mis-set phase silently degrades capture, verification, and join surfacing together, which the per-feature resolver house rule exists to prevent.+ - D does not fit the ladder, so the unified story needs an exception on day one, weakening the abstraction immediately.+ - Gating C's intake behavior on a wave-wide phase entangles the write path with A/B posture changes, and future cards must negotiate the ladder's semantics.+ - Largest config and test surface: the ladder itself needs its own resolver, census coverage, and phase-matrix tests before any card value ships.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 1+**Rationale**: Every card's verified premise already fixes its shape and seam, so Variant 1 is the faithful composition and the only one that preserves strict disjoint lane ownership, per-feature config resolvers, and a hot path touched by exactly one bounded, fail-open component. Variant 2 buys a literal trust chain at the cost of lane coupling and sequencing that the parallel-lane process cannot absorb in this wave, and Variant 3's wave-wide ladder conflates failure domains against the house resolver rule and guarded architecture. Variant 1 also keeps the spine cheap to grow later, since both B's optional sample_id field and C's source_archive_hash stamp are additive, schema-compatible fields that a future provenance home can adopt without rework.diff --git a/docs/brainstorm/answer-trust/cli-output/prompt.md b/docs/brainstorm/answer-trust/cli-output/prompt.mdnew file mode 100644index 00000000..24df1510--- /dev/null+++ b/docs/brainstorm/answer-trust/cli-output/prompt.md@@ -0,0 +1,43 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++Open Second Brain release wave "answer-trust": four kanban cards plus a small repair lane, one coherent PR on the current main (v1.80.0). Product: a local-first memory/knowledge vault for AI agents (TypeScript, Bun, MCP server + CLI + hooks). The wave spine: the brain's answers are only as trustworthy as their ties to stored sources.++Card A (t_245378f9) - verify answer-time quotations against source notes; unsupported quotes are marked unverified; on by default where the underlying lane is enabled, per-phase switchable, graceful degradation on truncated context. Verified premises: the distill lane already verifies its own quotes (pure reusable helpers in src/core/brain/distill/quote-spans.ts: findQuoteSpans, normalizeForQuoteComparison, spanOccursIn, quoteHaystack); answers are produced by the HOST agent, so OSB owns (a) what enters context (injection hooks + injection-ledger.ts records injected notes per session) and (b) turn-end observation (Stop hook with transcript_path; precedent hooks/stop-log-guardrail.ts). A new Stop-hook step + a src/core/brain/answer-quotes/check.ts module is the natural shape; config via _brain.yaml quote_check: per-phase off|shadow|enforce, shadow default; never blocks, annotates via additionalContext.++Card B (t_2ffffd28) - statement-level attribution: join stated claims to the recall receipt they drew on. Verified premises: receipts (context-receipts.ts, items named, durable receiptId) and outcomes (context-pack-outcome.ts, three rows keyed by sample_id) already exist; the claim ledger (truth/store.ts ClaimEvent) has NO linkage to either. Chosen direction: read-time join - optional sample_id threaded through brain_truth state, frozen on the ClaimEvent (optional field, schema-compatible), new read-only join helper claim-provenance.ts; zero new answer-time writes. Alternative rejected for cause: per-statement provenance rows (duplicates claim ledger, unbounded continuity growth, OSB never sees answer text anyway).++Card C (t_9b835c8f) - durable raw-source capture at intake so provenance survives link rot. Verified premises: intake discards source bytes today (classifySourceOrigin is byte-discarding; readSourceOrigin keeps bytes but only distill calls it); distill stores a 64 KiB excerpt + excerpt_hash on the page; artifact store is ephemeral scratch. Proposed shape: new src/core/brain/provenance/source-archive.ts, content-addressed Brain/.archives/<sha256>.txt, trusted local-file lane only, <=1 MiB refuse-not-truncate, redact (redactRawOutput) before persist, stamp source_archive_hash on the ingest summary page, capture-scope hygiene detector + doctor verify presence/integrity; no TTL (evidence, not scratch); delete-by-source cleanup gains an archive-entry kind.++Card D (t_22d58fa7) - blank session identity. Verified premises: payload records written by lanes with no session in scope omit session_id; five reader sites coerce the absence to "" (session-recall.ts:577, session-summary.ts:243/339/375, idea-lineage.ts:120/198), lumping unrelated lanes into one shared "" group; scoped recall silently drops them. Decision: absence stays absence (precedent orphan-session-check.ts:37-40 "session:unknown is a statement there was no session, not a pointer to a missing one") - readers treat missing/non-string as no-session explicitly; grouping sites skip rather than lump; new count-only informational doctor check blank-session-identity (no fix verb - repair belongs to t_6cc80627's backup-gated posture); NO payload rewrites.++Repair lane (from the post-merge external review, verified): M1 - stale-index attribute narrowing silently excludes documents whose indexed snapshot no longer matches the file (property-pushdown.ts EXISTS...OR NOT EXISTS fragment has no freshness gate) despite advertised "judged live" semantics; fix = freshness gate so stale candidates fall through to the live filter. L12 - CHANGELOG whitespace damage at lines 264 and 2450. Everything else from that review is already fixed on main.++# Project context++Open Second Brain: TypeScript on Bun, local vault (Obsidian-style markdown + JSONL continuity logs + SQLite search store), MCP tools + CLI verbs + hooks. Recent waves: v1.77 correctable truth layer, v1.78 credential custody, v1.79 write-side trust, v1.80 recall quality (SQL pushdown, entity lexicon, hallways PMI graph). House rules: no silent fallbacks (errors surface by name), no stubs, no hardcoded natural-language phrases, constants over literals, TDD, per-feature config resolvers in src/core/config.ts, doctor checks registered in DOCTOR_CHECKS, census tests guard architecture invariants. A PR carries about 30-50 changed files with tests; implementation runs in parallel lanes with disjoint file ownership.++Constraints:+- No new external dependencies.+- Do not break existing pinned test semantics without reason.+- Read-time joins preferred over new write-path machinery when data already exists.+- The answer path is hot: Stop-hook work must be bounded (chars, wall clock) and fail-open.+- Redaction/visibility rules from v1.78-v1.79 apply to anything that persists bytes.++# Required output format++Produce exactly 3 distinct architectural variants for the WHOLE wave (how the four cards compose into one architecture). For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/answer-trust/design.md b/docs/brainstorm/answer-trust/design.mdnew file mode 100644index 00000000..2590b236--- /dev/null+++ b/docs/brainstorm/answer-trust/design.md@@ -0,0 +1,86 @@+# Answer trust: verified answer-time quotes, statement-level claim attribution, durable raw-source archives, and explicit no-session identity semantics++**Status:** draft+**Author:** design orchestrator (feature-release-playbook, phases 0-1)+**Audience:** implementation++## Problem statement++An operator reading an Open Second Brain answer today cannot tell whether the quotation marks in it were earned. Recall injection puts vault notes into agent context (`hooks/recall-inject.ts:6`, opt-in via `recall_inject_enabled`, resolved at `src/core/config.ts:1185-1188`), the host agent answers with quoted spans drawn from those notes, and nothing checks that a quoted string actually occurs in the note it is cited against. The comparison machinery already exists and is pure: the distill lane has verified every quotation on a distillation page since v1.67.0 (`src/core/brain/distill/quote-spans.ts:173` `findQuoteSpans`, `:278` `unquoteSpans`, `:410` `normalizeForQuoteComparison`, `:466` `quoteHaystack`, `:486` `spanOccursIn`, with the verdict vocabulary in `src/core/brain/distill/quote-verdict.ts`). The gap is the answer boundary, and Open Second Brain owns both of its ends: what enters context (the injection ledger `hooks/lib/injection-ledger.ts:23-36` records injected notes per phase, 24 h TTL, 2000-entry set cap) and turn-end observation (the Stop hook family at `hooks/hooks.json:112`, the `additionalContext` precedent in `hooks/stop-log-guardrail.ts:10`, and `transcript_path` on hook stdin at `hooks/lib/stdin.ts:33`).++Stated claims carry no pointer to the recall they drew on. The substrate for such a pointer is complete: context receipts name every injected item (`src/core/brain/context-receipts.ts:120-135`), keep only a hash of the final answer (`:139`), and a durable `receiptId` rides the context-pack report (`src/core/brain/context-pack.ts:929-955`, surfaced as `receipt_id` at `src/mcp/brain/pack-tools.ts:403`); outcome rows are posted per pack under a `sample_id` key with first-pass-versus-repair verdicts (`src/core/brain/context-pack-outcome.ts:164-259`). But the claim ledger's `ClaimEvent` (`src/core/brain/truth/types.ts:50-71`) has neither field, `brain_truth state` (`src/mcp/brain/knowledge-tools.ts:751-812`, persisted through `appendStatedClaims` at `src/core/brain/truth/stated-claims.ts:158-235`) freezes claims with no linkage, and receipts being hash-only means Open Second Brain never sees answer text - so any attribution must be threaded at write time from the caller that does, and joined at read time.++Provenance rots because intake throws the bytes away. Intake commits stated-level provenance - source references only (`src/mcp/brain/intake-args.ts:184`, the rebuilt form at `src/core/brain/ingest/ingest.ts:265`) - through a classifier that reads a source and keeps only trust plus hash (`classifySourceOrigin`, `src/core/brain/intake/source-trust.ts:418-420`), while the byte-keeping form `readSourceOrigin` (`:430-458`) has exactly one caller, in distill intake (`src/core/brain/intake/extract-intake.ts:322`). The artifact store is 24 h-TTL scratch (`src/mcp/artifact-store.ts:110`), and the distill capture scope keeps a 64 KiB excerpt plus digest on the page (`src/core/brain/provenance/capture-scope.ts:83`, `:165`) - so a full-local source whose file decays falls back to url-only at the next sweep with no bytes behind it, which is precisely the condition the capture-scope hygiene detector names and nothing can repair. A trusted source whose digest is refused to remote readers (`src/core/brain/intake/extract-intake.ts:332-336`) shows the rule the archive must inherit: bytes persist only under the visibility rules, never past them.++Session identity is a coercion bug with a grouping symptom. Writers stamp `session_id` conditionally - lanes with no session in scope write records with the key absent (`src/core/brain/recall-telemetry.ts:453`, `src/core/brain/gate-telemetry.ts:76,127`, `src/core/brain/observed-use.ts:120`, `src/core/brain/recent-turns.ts:96-97`, `src/core/brain/token-impact.ts:279,321`, `src/core/brain/context-pack-evidence.ts:282`) - and five readers coerce the absence to the empty string with `String(payload["session_id"] ?? "")` (`src/core/brain/session-recall.ts:577`, `src/core/brain/session-summary.ts:243,339,375`, `src/core/brain/idea-lineage.ts:120,198`). The effect cuts both ways: scoped recall silently drops unattributed records (the lineage ledger already omits blank declarations, `src/core/brain/session-recall.ts:619-627`, so the scope set can never contain `""`), while unscoped grouping lumps every unattributed record from every unrelated lane into one shared `""` bucket. The repo has already answered the semantic question once: `session:unknown` "is a statement that there was no session, not a pointer to a missing one" (`src/core/brain/doctor/orphan-session-check.ts:37-40`).++## Scope++Four cards and one repair lane, one PR on `feat/answer-trust`:++- **Answer-time quote verification (t_245378f9)** - a new Stop-hook step that walks the last assistant messages of the turn, finds quoted spans with the existing distill helpers (imported, never forked), resolves each span's cited note (a wikilink or path in the span's context, else membership in the injection ledger), and checks it with a new pure module `src/core/brain/answer-quotes/check.ts` over verdicts `verified | not-in-note | source-truncated | note-unavailable | not-text`. One `additionalContext` annotation per turn lists unverified spans. Never blocks, never edits transcripts, fail-open exit 0. Config: `quote_check.recall|active|subagent`, each `off|shadow|enforce`, default `shadow` (annotate-only), scoped to phases whose injection is enabled.+- **Statement-level claim attribution (t_2ffffd28)** - an optional `sample_id` on the claim path: `brain_truth state` accepts it, the `ClaimEvent` freezes it (optional field, schema version unchanged, omit-don't-invent), and a new read-only join module `src/core/brain/truth/claim-provenance.ts` resolves a claim's `sample_id` to its receipt items and outcome row at read time. Zero new answer-time writes; claims whose outcome never arrived render "receipt known, outcome unknown" and never an invented verdict.+- **Durable raw-source archive (t_9b835c8f)** - a new content-addressed store `src/core/brain/provenance/source-archive.ts` at `Brain/.archives/<sha256>.txt`: the ingest trusted-local branch reads the source once (`readSourceOrigin`-style), redacts, refuses past 1 MiB rather than truncating, persists, and stamps `source_archive_hash` (plus `source_archive_bytes`) on the summary page on success only. No TTL - evidence, not scratch. The capture-scope hygiene detector gains a missing/mismatched-archive finding, delete-by-source cleanup gains an archive-entry kind, and an `archive_get` read on the existing `brain_hygiene` tool (modeled on `brain_artifact_get`, local reach only) fetches bytes.+- **Blank session identity (t_22d58fa7)** - absence stays absence: the five coercion sites treat a missing or non-string `session_id` as "no session" explicitly, scoped recall excludes such records, and grouping sites skip or emit undefined rather than lumping under `""`. A new count-only, fail-soft doctor check `blank-session-identity` reports one issue per affected kind with a count. No payload rewrites, no repair verb.+- **Repair lane (post-merge external review, verified)** - M1: a freshness gate on stale-index attribute narrowing so a document whose indexed snapshot no longer matches its file falls through to the live post-rank filter (`src/core/search/property-pushdown.ts:303-321`, applied `:386`, against the advertised "judged live" semantics at `src/mcp/search-tools.ts:293`). L12: CHANGELOG whitespace damage at `CHANGELOG.md:264` and `CHANGELOG.md:2450`, docs-only.++## Out of scope++- **Distill-lane changes.** The distill quote check (`src/core/brain/distill/quote-check.ts`) and its capture scope stay untouched; `checkClaimQuotes` is not extended and `quote-spans.ts` is consumed in place by import.+- **Paraphrase and semantic checks.** The verifier is literal-only: a span occurs in the note's normalized haystack or it does not. Semantic entailment is a different, larger card.+- **Transcript rewriting.** The hook annotates; it never strips quotation marks from an answer the host wrote, unlike the distill lane which strips on its own pages.+- **Blocking refusals.** No Stop hook in this repo blocks (`tests/hooks/hooks-json-shape.test.ts` pins the `exit 0` shape), and `enforce` in this wave means annotate plus one durable Brain-log record, never a blocked answer.+- **Per-statement provenance rows (rejected).** One continuity row per statement duplicates the claim ledger, grows the append-only continuity store without bound, and is unfillable anyway - receipts keep the answer hash-only, so Open Second Brain never sees the text a row would quote.+- **Remote URL fetch and archival.** Url-only sources keep being served by distill's 64 KiB excerpt; archiving remote content is a fetch-trust design of its own.+- **Session payload rewrites and a repair verb.** The continuity store is append-only per-device shards; in-place edits and a backup-gated repair posture are t_6cc80627's territory. The doctor check this wave is informational and count-only, with no `fix` field.+- **A unified wave-wide phase ladder (rejected).** One `off|shadow|enforce` dial across all four cards conflates independent failure domains against the per-feature resolver house rule, excludes D on day one (its decision is semantic and fixed, not a posture), and would demand the largest config and test surface before any card ships value.+- **Review items L3 (unused taxonomy indexes) and L15 (no `hallways.json` consumer).** Both are measurement and design questions, not repairs; they wait for a wave that measures first.++## Chosen approach++Variant 1, independent lanes at natural seams. Each card lands exactly where its verified premises point: A as a Stop-hook step beside `stop-log-guardrail` plus a pure check module; B as an additive field on the claim path plus a read-only join; C as a new provenance module wired into the one branch of ingest that already reads trusted local files; D as reader-site semantics plus one registered doctor check; the repair lane as two independent fixes. No shared machinery is introduced beyond the vault layout itself. The hot path - the answer the host produces - is touched by exactly one component, the A hook step, which is bounded (named constants for characters and wall clock) and fail-open. Config stays per-feature (`quote_check.*` resolvers beside `resolveRecallInjectEnabled`, `src/core/config.ts:1185`), doctor checks register individually in `DOCTOR_CHECKS` (`src/core/brain/doctor.ts:174-201`), and each card carries its own census test. Wave coherence is editorial, not structural, and that is accepted deliberately: both of the wave's additive schema fields - B's optional `sample_id` and C's `source_archive_hash` stamp - are exactly the shape a future provenance home would adopt without rework.++The rejected alternatives are rejected for cause, not taste. Variant 2 (a provenance spine fusing B and C under one integrity contract) buys a literal claim-to-bytes chain but couples two lanes that the parallel process needs disjoint, forces C's format to land before B's join consumers, and widens blast radius for a chain whose only consumer this wave is doctor and CLI reporting. Variant 3 (one wave-wide `answer_trust` phase ladder) trades the per-feature resolver house rule for one operational dial, conflates independent failure domains, and needs an exception for D immediately.++## Premise verification++Every card premise was re-verified against the branch point a00fa3f5 (v1.80.0). The table records what changed and what held; anchors below are live as of this design.++| Card | Premise as mined | Verdict | Live evidence |+|---|---|---|---|+| t_245378f9 | Validator anchor `src/core/brain/host-facts.ts:710` | Refuted | No such file exists; the live file is `src/core/runtime/host-facts.ts`, which attaches citations to built-in host facts and does no quote verification. The gap statement survives; the anchor was never real. |+| t_245378f9 | Distill quote-check exists and its helpers are pure-reusable | Confirmed | `src/core/brain/distill/quote-spans.ts:173,278,410,466,486`; verdict vocabulary `src/core/brain/distill/quote-verdict.ts`; shipped v1.67.0. |+| t_245378f9 | "On by default" | Corrected | Recall injection itself is opt-in (`hooks/recall-inject.ts:6`, `src/core/config.ts:1188`), so default-on can only scope to phases whose injection the operator enabled. The card's intent lands as per-phase `shadow` default. |+| t_2ffffd28 | Receipts and outcomes are complete; the claim ledger has no linkage | Confirmed | `src/core/brain/context-receipts.ts:120-135,139`; `src/core/brain/context-pack.ts:929-955`; `src/mcp/brain/pack-tools.ts:403,459`; `src/core/brain/context-pack-outcome.ts:164-259`; `src/core/brain/truth/types.ts:50-71` (no `session_id`/`sample_id`). |+| t_2ffffd28 | Card's eval anchors (`retrieval-trail.ts:227,346`, `search-tools.ts:1786`) | Stale | Live anchors are `src/core/search/retrieval-trail.ts:323,504` and `brain_eval` at `src/mcp/search-tools.ts:2003`. The gap the card names survives unchanged. |+| t_9b835c8f | Intake commits stated-level provenance and discards bytes; the artifact store is ephemeral | Confirmed | `src/mcp/brain/intake-args.ts:184`; `src/core/brain/ingest/ingest.ts:265`; byte-discarding `classifySourceOrigin` at `src/core/brain/intake/source-trust.ts:418-420` vs byte-keeping `readSourceOrigin` at `:430-458` (only distill calls it, `src/core/brain/intake/extract-intake.ts:322`); TTL prune at `src/mcp/artifact-store.ts:110`; 64 KiB excerpt at `src/core/brain/provenance/capture-scope.ts:83`. |+| t_22d58fa7 | Blank coercion lives at `src/core/brain/session-recall.ts:470` | Stale | The coercion moved: it now lives at `src/core/brain/session-recall.ts:577`, in the read-path scope filter. The defect is unchanged. |+| t_22d58fa7 | `resolveSessionScope` throws on blank; the lineage ledger omits blank ids; no session table exists | Confirmed | `src/core/brain/session-scope.ts:35-39`; `src/core/brain/session-recall.ts:619-627`; continuity is an append-only JSONL store, so there is no session row to rewrite - the card's migration subject never existed. |++## Design decisions++1. **The quote check is per-phase, `shadow` by default, and scoped to phases whose injection is enabled.** Three keys - `quote_check.recall`, `quote_check.active`, `quote_check.subagent` in the `quote_check` block of `Brain/_brain.yaml`, each `off|shadow|enforce`, default `shadow` - each with its own resolver in `src/core/config.ts` (`resolveAnswerQuoteCheckRecall|Active|Subagent`), following both the per-feature resolver convention (`resolveRecallInjectEnabled`, `src/core/config.ts:1185`) and the decision-model per-use `off|shadow|enforce` switch (`src/core/decision-model/config-types.ts:62-85`, `answerable.ts:12`). The card's "on by default" becomes shadow-by-default for a reason the premise verification surfaced: injection itself is opt-in (`hooks/recall-inject.ts:6`), so a default that changed answer behavior for vaults that never enabled any injection would be a default-changing flag wearing a default-preserving name. `shadow` annotates only; `enforce` annotates and appends one Brain-log event per turn with unverified spans (via `appendLogEvent`, `src/core/brain/log.ts:289`) so findings survive the session - and never blocks.+2. **The injection ledger is ground truth for what was available, and degradation never upgrades a verdict.** A span is checked only against evidence the turn actually had: the note named in the span's context (wikilink or vault-relative path), else membership in the ledger's phase keys (`LEDGER_KEY_RECALL|ACTIVE|REGROUND|SUBAGENT_INJECT`, `hooks/lib/injection-ledger.ts:23-26`). A note that cannot be read yields `note-unavailable` with the annotation kept - "we could not check" is a finding, not an all-clear. A note whose body reached context truncated (`ContextPackItem.trimmed`, `src/core/brain/context-pack.ts:156`; receipt `truncated` flags at `src/core/brain/context-receipts.ts:336,447`) is matched against the available prefix, and a miss is `source-truncated`, never `not-in-note` - a truncated source can under-deliver evidence but never acquits a span.+3. **`sample_id` is an optional `ClaimEvent` field, frozen at write, joined at read.** `truth/store.ts` extends `AppendClaimInput`/`ClaimEvent` with optional `sample_id` - omitted when absent, never invented - leaving the schema version unchanged exactly as the optional `extractor` tag did (`src/core/brain/truth/types.ts:64-69`); `truth/stated-claims.ts` accepts an optional `sampleId` on `StatedClaimsPayload` that must be trimmed and non-empty when present. The new `truth/claim-provenance.ts` is read-only and composes existing readers: receipt items by receipt id (`listContextReceipts`, `src/mcp/brain/pack-tools.ts:459`) and outcome rows by `sample_id` (`listContextPackOutcomes`, `src/core/brain/context-pack-outcome.ts:293-305`). The correlation guard is omit-don't-invent both ways: a claim with a `sample_id` and no outcome row renders "receipt known, outcome unknown"; a claim timestamped before its claimed receipt is flagged as an inversion rather than silently joined.+4. **The source archive is content-addressed, redacted before persist, refused not truncated, and evidence rather than scratch.** `put(vault, bytes) -> sha256` writes `Brain/.archives/<sha256>.txt` - a dot-directory excluded from the walker exactly like `.snapshots` and `.artifacts` (`src/core/brain/path-constants.ts:109-116` precedent), which is also the dedup: identical bytes persist once. `ARCHIVE_MAX_BYTES` is 1 MiB, reusing the `PRE_EXTRACT_MAX_SOURCE_BYTES` ceiling (`src/core/brain/ingest/ingest.ts:437`) with the capture-scope refusal posture (`src/core/brain/provenance/capture-scope.ts:243-248`) - an oversized source is not captured, and absence on the page still means exactly "not captured". Redaction runs `redactRawOutput` (`src/core/redactor.ts:971`) before persist so credentials captured in v1.78-v1.79 terms never land in a second file, and visibility tokens hold: a source whose digest is refused to remote readers (`src/core/brain/intake/extract-intake.ts:332-336`) is never archived, and remote reach never reads archived bytes. No TTL - this is evidence, the direct contrast to the artifact store's prune (`src/mcp/artifact-store.ts:110`); retention is explicit operator pruning, and delete-by-source cleanup gains an archive-entry kind so orphaned archives do not accumulate (`src/mcp/brain/ingest-tools.ts:218-260`).+5. **Absence stays absence for session identity.** The five coercion sites (`src/core/brain/session-recall.ts:577`, `src/core/brain/session-summary.ts:243,339,375`, `src/core/brain/idea-lineage.ts:120,198`) treat a missing or non-string `session_id` as no-session explicitly - no `String(... ?? "")`, no fabricated bucket - so scoped recall excludes the record (matching what the lineage ledger already does, `src/core/brain/session-recall.ts:619-627`) and grouping sites skip rather than lump unrelated lanes into one shared `""` group. This is the orphan-session precedent applied at the reader (`src/core/brain/doctor/orphan-session-check.ts:37-40`): mapping absence to `""` manufactured a phantom session that no writer ever created. The public-ish digest shape changes deliberately: `SessionSummaryDigest.sessionId` becomes presence-gated (key omitted when absent), and its consumers are swept in the same task.+6. **Doctor checks this wave are informational and count-only.** `blank-session-identity` is a fail-soft check in `src/core/brain/doctor/session-identity-check.ts`: one pass over `listContinuityRecords`, one issue per affected record kind with a count, no `fix` field - repair belongs to t_6cc80627's backup-gated posture, and an in-place rewrite of append-only per-device shards is out of scope by the store's own contract. It registers in `DOCTOR_CHECKS` adjacent to `orphanSessionCheck` (`src/core/brain/doctor.ts:174-201`). The same informational posture governs C's surfaces: the hygiene finding names the page, and the doctor CLI prints counts.+7. **Stale-index narrowing gets a freshness gate instead of weaker narrowing.** The `EXISTS ... OR NOT EXISTS` fragment (`src/core/search/property-pushdown.ts:303-321`, applied at `:386`) narrows on the attribute snapshot while the contract says values are "narrow on the attribute snapshot, judged live" (`src/mcp/search-tools.ts:293`). The gate compares the candidate's indexed snapshot against the live document and lets stale candidates fall through to the existing live post-rank filter, so a draft-then-done document stops vanishing from `status=done` queries. No new store machinery: the check rides the index rows `store.ts` already maintains.++## File changes++New core: `src/core/brain/answer-quotes/check.ts` (pure quote verdicts over distill helpers), `src/core/brain/provenance/source-archive.ts` (content-addressed put/verify/stats, redaction, 1 MiB refusal), `src/core/brain/truth/claim-provenance.ts` (read-only claim-to-receipt-to-outcome join), `src/core/brain/doctor/session-identity-check.ts` (count-only blank-session check), `hooks/answer-quote-check.ts` (bounded, fail-open Stop-hook step).+Extended core: `src/core/brain/truth/store.ts` + `truth/stated-claims.ts` (optional `sample_id`, trim-and-refuse validation), `src/core/brain/ingest/ingest.ts` (trusted-branch archive capture, page stamp on success only), `src/core/brain/session-recall.ts`, `session-summary.ts`, `idea-lineage.ts` (explicit no-session semantics at the five coercion sites), `src/core/brain/doctor.ts` (`blank-session-identity` registration), `src/core/brain/path-constants.ts` (`BRAIN_ARCHIVES_DIR`/`BRAIN_ARCHIVES_REL`), `src/core/state/surfaces.ts` (`.archives` row), `src/core/config.ts` (`quote_check.*` resolvers), `src/core/search/property-pushdown.ts` + `src/core/search/store.ts` (freshness gate), `src/core/brain/hygiene/detectors/capture-scope.ts` (missing/mismatched-archive finding).+MCP: `src/mcp/brain/knowledge-tools.ts` (`brain_truth state` accepts and echoes `sample_id`; read op hydrates provenance), `src/mcp/brain/ingest-tools.ts` (`source_archive_hash` on the ingest result; archive-entry kind in delete-by-source cleanup), `src/mcp/brain/hygiene-tools.ts` (`archive_get` op, local reach).+Hooks + CLI: `hooks/hooks.json` (one Stop entry after `stop-log-guardrail`), `src/cli/brain/verbs/truth.ts` (`state --sample-id`, claim-read hydration), `src/cli/brain/verbs/doctor.ts` (informational archive section).+Tests: `tests/core/brain/answer-quotes/check.test.ts`, `tests/core/config-answer-quote-check.test.ts`, `tests/hooks/answer-quote-check.test.ts`, `tests/core/brain/truth/claim-provenance.test.ts` plus the store/stated-claims suite extensions, `tests/core/brain/provenance/source-archive.test.ts`, `tests/core/brain/session-identity-check.test.ts`, `tests/core/architecture/claim-attribution-census.test.ts`, and the extensions the plan names per task (`tests/mcp/ingest-tool.test.ts`, `tests/mcp/hygiene-capture-scope-reach.test.ts`, `tests/cli/brain-hygiene.test.ts`, `tests/core/search/kind-attributes-pushdown.test.ts`, `tests/hooks/hooks-json-shape.test.ts`).+Docs: `docs/observability.md` (quote-check annotation and the blank-session count), `CHANGELOG.md` under the release heading plus the L12 whitespace repair.++## Risks and open questions++- **Stop-hook latency bounds.** The check runs inside the turn-end Stop pipeline (`hooks/hooks.json:112`) where `timeout: 10` already governs; the step reads only the last assistant messages under named character and wall-clock constants and gives up by returning `verified`-nothing rather than by running long. The risk to watch in review is a transcript reader that scans the whole file - the bounded-window read is the acceptance criterion, not an implementation detail.+- **False-positive quote normalization residuals.** The distill helpers' normalization (`normalizeForQuoteComparison`, `src/core/brain/distill/quote-spans.ts:410`) is tuned for distillation pages; answers may paraphrase whitespace, ligatures or punctuation differently. The upstream card itself reports non-zero false-positive rates, which is exactly why the default is `shadow`: the annotation wording says "unverified", not "fabricated", and the mirror suite pins that supported quotes pass at least as well as the distill lane's own suite (`tests/core/brain/distill/quote-check.test.ts` is the bar).+- **Vault bloat and secrets in raw captures.** `Brain/.archives/` is the first durable byte store with no TTL; a chatty ingest lane grows it without bound, and a redaction gap would duplicate a secret into a second file after v1.78-v1.79 taught the rest of the tree to hold credentials in one custody store. The 1 MiB refuse-not-truncate ceiling and the `redactRawOutput`-before-persist ordering are the mitigations; the doctor's informational archive section is the operator's visibility into growth.+- **The `session-summary` digest shape has consumers.** `SessionSummaryDigest.sessionId: ""` (`src/core/brain/session-summary.ts:375`) reaches `src/cli/brain/verbs/session-summary.ts` and `src/mcp/brain/synthesis-tools.ts`; flipping to presence-gated is swept in the same task, and a consumer that cannot tolerate the absent key stops the lane for a design check rather than papering over it with a fallback.+- **Correlation quality when outcomes never arrive.** `sample_id` is caller-supplied and optional; a caller that mints ids without ever posting the outcome row (`postContextPackOutcome`, `src/core/brain/context-pack-outcome.ts:164-259`) leaves every claim at "receipt known, outcome unknown" forever. The join renders that honestly and flags timestamp inversions, but the wave does not add a write-time check that the id corresponds to a real sample - the caller's contract, documented on the tool.+- **Freshness-gate performance.** The gate adds a per-candidate liveness comparison inside attribute narrowing (`src/core/search/property-pushdown.ts:386`); on a large index with narrow filters this must not turn a SQL-side filter into a per-row file read. The gate rides the snapshot metadata the store already indexes, and the extended suite pins both the correctness case (draft-to-done flips the result) and the no-regression case (fresh candidates never touch the filesystem).diff --git a/docs/brainstorm/answer-trust/plan.md b/docs/brainstorm/answer-trust/plan.mdnew file mode 100644index 00000000..24a09f25--- /dev/null+++ b/docs/brainstorm/answer-trust/plan.md@@ -0,0 +1,155 @@+# Answer trust: verified quotes, claim attribution, source archives, session identity - implementation plan++Feature branch: `feat/answer-trust` (checked out from `origin/main` at v1.80.0, a00fa3f5). TDD per task, one atomic conventional commit per task, `bun run fmt` + `bun run lint` green before every commit. Work is organized as five implementation lanes in separate worktrees with STRICTLY DISJOINT file ownership: a file is edited by exactly one lane. Within a lane, tasks are ordered substrate-first (pure modules and config before wiring and surfaces). There are NO cross-lane dependencies by design - the four cards and the repair lane land independently and assemble at merge time.++This wave adds NO new MCP tool, NO new CLI verb, and NO new continuity record kind. Every surface change is a field on an existing tool result, an op on an existing tool, a flag on an existing verb, or one registered doctor check, so the tool-name pins (`tests/mcp/mcp.test.ts`, `tests/mcp/brain-tools-parity.test.ts`, `tests/mcp/agent-scope-matrix.test.ts`, `docs/mcp.md`) do not move. Any census that must change for a lane to proceed is a design error and stops that lane.++House rules this wave:++- New verdict vocabularies (Lane A's five quote verdicts, Lane C's archive refusals if vocabulary-shaped): frozen object + companion member list + type guard, registered in `tests/core/architecture/verdict-vocabulary-census.test.ts`. That file is SHARED-APPEND: each lane appends only its own vocabulary block; the census asserts membership per vocabulary, not a wave-global count, so appends never collide.+- New durable Brain directory `Brain/.archives/`: a `STATE_SURFACE_ID` entry and `STATE_SURFACES` row in `src/core/state/surfaces.ts` plus the `DECLARED_SURFACE_COUNT` bump in `tests/core/architecture/state-surface-census.test.ts` (Lane C, Task C1).+- `hooks/hooks.json` is mirrored into the Codex plugin: after editing it, run `bun run sync-plugin-mirrors` (CI and the pre-commit hook gate on `sync-plugin-mirrors:check`; never hand-edit `plugins/codex/hooks/hooks.json`). Every command must keep the resilient shape the `tests/hooks/hooks-json-shape.test.ts` census pins: `$CLAUDE_PLUGIN_ROOT` wrapper, PATH fallback, trailing `exit 0`.+- No identifier containing `secret` before a quoted value anywhere in src or tests; the plugin scanner flags the `const secret = "..."` form. Tests never depend on directory iteration order; every listing sorts deterministically.++## Cross-lane contract (pinned)++| Owner | Files |+|---|---|+| Lane A | `hooks/answer-quote-check.ts` (new); `hooks/hooks.json`; `src/core/brain/answer-quotes/check.ts` (new); `src/core/config.ts`; `tests/core/brain/answer-quotes/**`; `tests/hooks/answer-quote-check.test.ts` (new); `tests/core/config-answer-quote-check.test.ts` (new); the `tests/hooks/hooks-json-shape.test.ts` Stop-order extension and A's verdict-vocabulary census block |+| Lane B | `src/core/brain/truth/store.ts`; `src/core/brain/truth/stated-claims.ts`; `src/core/brain/truth/claim-provenance.ts` (new); `src/core/brain/context-receipts.ts` (`ContextReceiptFilter.receiptId` field only); `src/mcp/brain/knowledge-tools.ts`; `src/cli/brain/verbs/truth.ts`; `tests/core/brain/truth/**`; `tests/core/architecture/claim-attribution-census.test.ts` (new); the existing truth and CLI truth suite extensions |+| Lane C | `src/core/brain/provenance/source-archive.ts` (new); `src/core/brain/ingest/ingest.ts`; `src/mcp/brain/ingest-tools.ts`; `src/mcp/brain/hygiene-tools.ts`; `src/core/brain/hygiene/detectors/capture-scope.ts`; `src/core/brain/path-constants.ts`; `src/core/state/surfaces.ts`; `src/cli/brain/verbs/doctor.ts`; `tests/core/brain/provenance/source-archive.test.ts` (new); `tests/mcp/ingest-tool.test.ts`; `tests/mcp/hygiene-capture-scope-reach.test.ts`; `tests/cli/brain-hygiene.test.ts`; the `tests/core/architecture/state-surface-census.test.ts` count and C's verdict-vocabulary census block; the index-admission walker-exclusion extension |+| Lane D | `src/core/brain/session-recall.ts`; `src/core/brain/session-summary.ts`; `src/core/brain/idea-lineage.ts`; `src/core/brain/doctor/session-identity-check.ts` (new); `src/core/brain/doctor.ts`; `src/cli/brain/verbs/session-summary.ts`; `src/mcp/brain/synthesis-tools.ts` (digest-shape sweep); `tests/core/brain/session-identity-check.test.ts` (new); the session-recall, session-summary and idea-lineage suite extensions |+| Lane R | `src/core/search/property-pushdown.ts`; `src/core/search/store.ts`; `tests/core/search/kind-attributes-pushdown.test.ts`; `CHANGELOG.md` (the two whitespace-damaged lines only) |++Shared files, collisions resolved by assignment:++- `src/core/config.ts` - Lane A's `quote_check.*` resolvers own it; no other lane touches it (Lane C's ceilings are constants, not config).+- `hooks/hooks.json` - Lane A owns it (one Stop entry); the Codex mirror is regenerated, never hand-edited.+- `src/core/brain/doctor.ts` - Lane D owns the `DOCTOR_CHECKS` registration edit. Lane C's archive findings ride the hygiene detector and the doctor CLI verb, never the registry.+- `src/core/search/store.ts` - Lane R owns it; Lanes B, C and D must not touch it (they read through existing store APIs without edits).+- `tests/core/architecture/verdict-vocabulary-census.test.ts` - shared-append as above; the only test file two lanes both append to.+- `CHANGELOG.md` - Lane R touches only the whitespace-damaged lines; the release entry itself belongs to the release phase after this plan.++## Lane A config surface (pin - one vocabulary per key, no second reader)++| Key | Home | Values | Default | Resolver |+|---|---|---|---|---|+| `quote_check.recall` | `Brain/_brain.yaml`, `quote_check` block | `off \| shadow \| enforce` | `shadow` | `resolveAnswerQuoteCheckRecall(configPath?)` |+| `quote_check.active` | `Brain/_brain.yaml`, `quote_check` block | `off \| shadow \| enforce` | `shadow` | `resolveAnswerQuoteCheckActive(configPath?)` |+| `quote_check.subagent` | `Brain/_brain.yaml`, `quote_check` block | `off \| shadow \| enforce` | `shadow` | `resolveAnswerQuoteCheckSubagent(configPath?)` |++Resolver semantics, pinned for all three: unknown or wrongly typed values are field-named config errors naming `quote_check.<phase>` (never silently `off`); unknown keys inside the `quote_check` block warn per the strict-block convention. The hook runs a phase's check only when BOTH hold: the phase's injection is enabled (recall requires `recall_inject_enabled`, `src/core/config.ts:1185-1188`; active and subagent their own injection gates) and the resolver returns more than `off`. `shadow` annotates only; `enforce` annotates and appends exactly one Brain-log event per turn.++Hook constants, pinned as named exports in `hooks/answer-quote-check.ts`: `ANSWER_QUOTE_MAX_MESSAGES` (last assistant messages read), `ANSWER_QUOTE_MAX_CHARS` (per-message char budget), `ANSWER_QUOTE_BUDGET_MS` (wall-clock budget) - the bounded, fail-open contract the wave requires on the hot path.++## Tasks++### Task A1: Quote verdict module (Lane A, substrate)+- **Lane**: A. **Files**: new `src/core/brain/answer-quotes/check.ts`; `tests/core/brain/answer-quotes/check.test.ts`; A's block in `tests/core/architecture/verdict-vocabulary-census.test.ts`.+- **Acceptance**: `checkAnswerQuotes({spans, evidence})` composes `quoteHaystack`/`spanOccursIn` over the distill helpers imported in place (`findQuoteSpans`, `normalizeForQuoteComparison`, `src/core/brain/distill/quote-spans.ts:410,466,486` - no fork, no copy; `checkClaimQuotes` unextended) and returns exactly the five verdicts `verified | not-in-note | source-truncated | note-unavailable | not-text`, pinned table-style; the vocabulary is a frozen object + companion list + type guard, census-registered; the false-positive bar is the distill suite itself (`tests/core/brain/distill/quote-check.test.ts`): every span that suite verifies must verify here under the same evidence.+- **Depends on**: none++### Task A2: quote_check config resolvers (Lane A, substrate)+- **Lane**: A. **Files**: `src/core/config.ts`; `tests/core/config-answer-quote-check.test.ts`.+- **Acceptance**: the three resolvers land beside `resolveRecallInjectEnabled` (`src/core/config.ts:1185`) with the exact semantics of the config surface table above: default `shadow` per phase, `off|shadow|enforce` accepted, any other value a field-named error naming `quote_check.<phase>`, unknown block keys warning; resolvers are pure (`configPath` in, mode out) and read nothing else.+- **Depends on**: none++### Task A3: Stop-hook step and hooks.json entry (Lane A)+- **Lane**: A. **Files**: new `hooks/answer-quote-check.ts`; `hooks/hooks.json` (one Stop entry, ordered after `stop-log-guardrail`, `hooks/hooks.json:112`); `tests/hooks/answer-quote-check.test.ts` (synthetic transcript + injection ledger); the `tests/hooks/hooks-json-shape.test.ts` Stop-order extension.+- **Acceptance**: reads only the last assistant messages under the three named constants; finds quoted spans with `findQuoteSpans`; resolves each span's cited note from the span context (wikilink or vault-relative path) else ledger membership across `LEDGER_KEY_RECALL|ACTIVE|REGROUND|SUBAGENT_INJECT` (`hooks/lib/injection-ledger.ts:23-26`); phase gating consults the injection gate AND the Task A2 resolver; emits exactly ONE `hookSpecificOutput.additionalContext` annotation listing unverified spans with their verdicts (the `hooks/stop-log-guardrail.ts:10` precedent); never blocks, never edits the transcript; any error exits 0 with exactly one stderr audit line; `bun run sync-plugin-mirrors` run and green.+- **Depends on**: Tasks A1, A2++### Task A4: Degradation matrix and the enforce trail (Lane A)+- **Lane**: A. **Files**: `src/core/brain/answer-quotes/check.ts` (truncation and unavailability arms); `hooks/answer-quote-check.ts` (enforce log event); extensions of both A test suites.+- **Acceptance**: the degradation matrix is pinned end-to-end - note unavailable yields `note-unavailable` with the annotation kept; a truncated source (`ContextPackItem.trimmed`, `src/core/brain/context-pack.ts:156`; receipt `truncated` at `src/core/brain/context-receipts.ts:336,447`) is matched against the available prefix, a miss is `source-truncated`, and marks are never stripped on truncated evidence; `shadow` writes nothing to the vault; `enforce` additionally appends exactly one Brain-log event per turn via `appendLogEvent` (`src/core/brain/log.ts:289`) and never more; the hook exits 0 in every arm.+- **Depends on**: Task A3++### Task B1: sample_id on the claim event (Lane B, substrate)+- **Lane**: B. **Files**: `src/core/brain/truth/store.ts`; the truth store test suite.+- **Acceptance**: `AppendClaimInput` and `ClaimEvent` (`src/core/brain/truth/types.ts:50-71`) carry optional `sample_id`; omitted when absent, never invented; present values are stored verbatim and treated as opaque (privacy: receipts store hashes only, so the id discloses nothing); the schema version is unchanged and old ledgers read unchanged, exactly the optional-`extractor` forward-compatibility (`src/core/brain/truth/types.ts:64-69`); roundtrip pinned.+- **Depends on**: none++### Task B2: sampleId threading in stated claims (Lane B, substrate)+- **Lane**: B. **Files**: `src/core/brain/truth/stated-claims.ts`; the stated-claims test suite.+- **Acceptance**: `StatedClaimsPayload` gains optional `sampleId` (`src/core/brain/truth/stated-claims.ts:158-235` is the append path); the value is trimmed and must be non-empty when present - an empty or whitespace-only `sampleId` is a named refusal, never coerced, never stored; threading reaches `AppendClaimInput`; the no-sampleId path is byte-identical to today.+- **Depends on**: Task B1++### Task B3: Read-only claim-provenance join (Lane B)+- **Lane**: B. **Files**: new `src/core/brain/truth/claim-provenance.ts`; `src/core/brain/context-receipts.ts` (`ContextReceiptFilter` gains `receiptId`, matched before the limit, `src/core/brain/context-receipts.ts:84-95,181`); `tests/core/brain/truth/claim-provenance.test.ts` beside `tests/core/brain/context-pack-outcome.test.ts`.+- **Acceptance**: a claim's `sample_id` resolves to `{receipt items, outcome first_pass/evidence verdict}` using `listContextReceipts` by receipt id and `listContextPackOutcomes` by `sampleId` (`src/core/brain/context-pack-outcome.ts:108-118,293-305`); a `sample_id` with a receipt but no outcome row renders "receipt known, outcome unknown" - absent, never invented; a claim timestamped before its claimed receipt's `created_at` carries an inversion flag; the module performs no vault writes (enforced by the Task B6 census); the join widens nothing the caller could not already read at its reach.+- **Depends on**: Tasks B1, B2++### Task B4: brain_truth state accepts sample_id and hydrates reads (Lane B)+- **Lane**: B. **Files**: `src/mcp/brain/knowledge-tools.ts`; the knowledge tool test suite.+- **Acceptance**: `brain_truth state` (`src/mcp/brain/knowledge-tools.ts:751-812`) accepts optional `sample_id` per claim and echoes it per-claim commit exactly as the claim committed; the read op hydrates committed claims through `claim-provenance.ts` when `sample_id` is present; claims without `sample_id` render exactly as today; a missing outcome row renders the "receipt known, outcome unknown" marker, never a fabricated verdict.+- **Depends on**: Task B3++### Task B5: CLI truth --sample-id (Lane B)+- **Lane**: B. **Files**: `src/cli/brain/verbs/truth.ts`; the CLI truth test suite.+- **Acceptance**: `o2b brain truth state --sample-id <id>` threads the id through Task B2's validation; claim reads hydrate provenance identically to the MCP read op; omitting the flag is byte-identical to today; the flag value is validated by the same named refusal as the MCP path.+- **Depends on**: Task B4++### Task B6: Attribution census (Lane B)+- **Lane**: B. **Files**: new `tests/core/architecture/claim-attribution-census.test.ts`.+- **Acceptance**: pins, as architecture invariants: (a) the continuity record-kind vocabulary is unchanged by the wave - the join reads existing `context_receipt` and `brain_context_pack_outcome` rows and introduces no new kind; (b) no recall-time writes - the `truth/` modules and `claim-provenance.ts` import no continuity append path. Either invariant failing stops the lane.+- **Depends on**: Task B3++### Task C1: .archives path constants and state surface (Lane C, substrate)+- **Lane**: C. **Files**: `src/core/brain/path-constants.ts` (`BRAIN_ARCHIVES_DIR` = `".archives"` + `BRAIN_ARCHIVES_REL`, with the dot-dir walker-exclusion doc following the `.artifacts` precedent, `src/core/brain/path-constants.ts:109-116`); `src/core/state/surfaces.ts` (`STATE_SURFACE_ID` entry + `STATE_SURFACES` row); `tests/core/architecture/state-surface-census.test.ts` (`DECLARED_SURFACE_COUNT` +1).+- **Acceptance**: the surface row derives `Brain/.archives/`, `carries_memory: true`, with a reason stating it is durable evidence - deleting it destroys re-verification ability, not current vault content (the deliberate contrast to the artifact store's prune, `src/mcp/artifact-store.ts:110`); the census count matches; nothing else in the tree builds the path by hand (the census's naive-path-builder sweep passes).+- **Depends on**: none++### Task C2: Source-archive store (Lane C, substrate)+- **Lane**: C. **Files**: new `src/core/brain/provenance/source-archive.ts`; `tests/core/brain/provenance/source-archive.test.ts`; C's block in `tests/core/architecture/verdict-vocabulary-census.test.ts` (if refusals are vocabulary-shaped).+- **Acceptance**: `put(vault, bytes) -> sha256` writes `Brain/.archives/<sha256>.txt`, content-addressed so identical bytes persist once (dedup pinned); `ARCHIVE_MAX_BYTES = 1_048_576` with refuse-not-truncate - a past-ceiling input raises the named error, never a truncated write (the `CaptureExcerptError` posture, `src/core/brain/provenance/capture-scope.ts:243-248`); redaction runs BEFORE persist via `redactRawOutput` (`src/core/redactor.ts:971`), pinned by a test that a credential-shaped input never lands on disk; `verify(vault, hash)` re-hashes and reports match/mismatch; `stats(vault)` feeds the Task C6 doctor section.+- **Depends on**: Task C1++### Task C3: Ingest trusted-branch capture and page stamp (Lane C)+- **Lane**: C. **Files**: `src/core/brain/ingest/ingest.ts` (trusted branch, `src/core/brain/ingest/ingest.ts:390-396`); the ingest suite and `tests/mcp/ingest-tool.test.ts`.+- **Acceptance**: the trusted-local branch reads the source once, `readSourceOrigin`-style (`src/core/brain/intake/source-trust.ts:430-458` - not the byte-discarding `classifySourceOrigin`, `:418-420`), archives the bytes, and stamps `source_archive_hash` + `source_archive_bytes` on the summary page ON SUCCESS ONLY; an archive failure leaves the page unstamped and never fails the ingest (absence still means exactly "not captured"); a source whose digest is refused to remote readers (`src/core/brain/intake/extract-intake.ts:332-336`) is never archived; an oversized source skips capture with the named refusal recorded; untrusted and non-local sources behave byte-identically to today.+- **Depends on**: Task C2++### Task C4: Ingest result field and delete-by-source cleanup (Lane C)+- **Lane**: C. **Files**: `src/mcp/brain/ingest-tools.ts`; `tests/mcp/ingest-tool.test.ts`.+- **Acceptance**: the `brain_ingest_source` result gains `source_archive_hash` following the `capture_scope` field pattern - always present, null when not captured (`src/mcp/brain/ingest-tools.ts:148`) so absence never reads as a missing key to a caller; delete-by-source cleanup (`src/mcp/brain/ingest-tools.ts:218-260`) gains an archive-entry kind so removing a source's last citing page removes its now-orphaned archive entry, reported as its own kind in the cleanup result.+- **Depends on**: Task C3++### Task C5: Hygiene detector missing/mismatched-archive finding (Lane C)+- **Lane**: C. **Files**: `src/core/brain/hygiene/detectors/capture-scope.ts`; `tests/mcp/hygiene-capture-scope-reach.test.ts`; `tests/cli/brain-hygiene.test.ts`.+- **Acceptance**: an ingest summary stamped `source_archive_hash` whose archive entry is absent or re-hashes differently yields the named finding (one per page, `review` proposed action, the detector's existing shape); a page with no stamp is unchanged - absence means not captured, never a finding; findings flow through the existing hygiene surfaces (`brain_hygiene` tool, `o2b brain hygiene scan`, the Stop hygiene-digest hook) with no registry edits; reach rules hold - a caller who may not read the page learns nothing new from the finding.+- **Depends on**: Tasks C2, C3++### Task C6: Archive read surface and doctor section (Lane C)+- **Lane**: C. **Files**: `src/mcp/brain/hygiene-tools.ts` (`archive_get` op); `src/cli/brain/verbs/doctor.ts` (informational archive section); the hygiene tool and doctor verb tests.+- **Acceptance**: `archive_get` on the existing `brain_hygiene` tool resolves a hash to the archived bytes, modeled on `brain_artifact_get`'s bounded-fetch posture and LOCAL reach only - a remote-reach caller gets the same answer an absent entry gives, never the bytes (the visibility rule the design pins); an unknown hash is a named miss; the doctor CLI section is count-only informational (entry count, total bytes, missing/mismatched count) with no fix verb; no new tool and no new verb, so the tool-name pins stay unmoved.+- **Depends on**: Tasks C2, C5++### Task D1: Explicit no-session semantics in recall (Lane D)+- **Lane**: D. **Files**: `src/core/brain/session-recall.ts`; the session-recall test suite.+- **Acceptance**: the read-path coercion at `src/core/brain/session-recall.ts:577` treats a missing or non-string `session_id` as no-session explicitly (no `String(... ?? "")`); a record without `session_id` is excluded from scoped recall and from `lineageScope`; the lineage ledger's blank-id omission (`:619-627`) is pinned unchanged; unscoped reads still return the record; a non-string value (number, null) is excluded, not coerced.+- **Depends on**: none++### Task D2: Grouping sites and the digest shape sweep (Lane D)+- **Lane**: D. **Files**: `src/core/brain/session-summary.ts` (the filter at `:243`, the scope compare at `:339`, the digest at `:375`); `src/cli/brain/verbs/session-summary.ts`; `src/mcp/brain/synthesis-tools.ts`; the session-summary test suite plus consumer rendering cases.+- **Acceptance**: grouping at `:243` and `:339` skips no-session records rather than matching them against `""` (the shared-bucket defect); `SessionSummaryDigest.sessionId` becomes presence-gated (key omitted when absent); the CLI verb and the synthesis surface render a no-session summary without crashing and without fabricating an id; a consumer that cannot tolerate the absent key stops the lane for a design check - no fallback to `""` is acceptable anywhere.+- **Depends on**: none++### Task D3: Idea-lineage no-session semantics (Lane D)+- **Lane**: D. **Files**: `src/core/brain/idea-lineage.ts` (the turn index at `:120`, the source resolution at `:198`); the idea-lineage test suite.+- **Acceptance**: the turn-index grouping skips no-session records rather than keying them by `""`; the source resolution emits undefined rather than `""` for a record with no session; lineage output never merges two unrelated no-session records into one group (pinned by a two-record case).+- **Depends on**: none++### Task D4: blank-session-identity doctor check (Lane D)+- **Lane**: D. **Files**: new `src/core/brain/doctor/session-identity-check.ts`; `src/core/brain/doctor.ts` (`DOCTOR_CHECKS` registration adjacent to `orphanSessionCheck`, `src/core/brain/doctor.ts:174-201`); `tests/core/brain/session-identity-check.test.ts`.+- **Acceptance**: count-only and fail-soft - one pass over `listContinuityRecords`, one issue per affected record kind carrying the count, NO `fix` field (repair belongs to t_6cc80627's backup-gated posture); an unreadable ledger yields the uncertain-stream outcome, mirroring the orphan-session patterns (`src/core/brain/doctor/orphan-session-check.ts:37-40`); the check runs in `o2b brain doctor` and the `brain_doctor` tool with zero config; no payload is ever rewritten.+- **Depends on**: Task D1 (shares the no-session predicate's definition; reads only)++### Task R1: Freshness gate on attribute narrowing (Lane R)+- **Lane**: R. **Files**: `src/core/search/property-pushdown.ts`; `src/core/search/store.ts`; `tests/core/search/kind-attributes-pushdown.test.ts`.+- **Acceptance**: the pinned case passes - a document indexed as `status: draft`, edited to `status: done`, filtered `status=done`, is returned; stale candidates fall through to the live post-rank filter instead of being silently excluded by the `EXISTS ... OR NOT EXISTS` fragment (`src/core/search/property-pushdown.ts:303-321`, applied at `:386`); fresh candidates take the SQL path unchanged (the no-per-row-file-read case is pinned alongside); the advertised "narrow on the attribute snapshot, judged live" semantics (`src/mcp/search-tools.ts:293`) hold for every narrowed key.+- **Depends on**: none++### Task R2: CHANGELOG whitespace repair (Lane R)+- **Lane**: R. **Files**: `CHANGELOG.md` (the damaged lines at `CHANGELOG.md:264` and `CHANGELOG.md:2450` only).+- **Acceptance**: the missing spaces at `:264` and the broken list indentation at `:2450` are repaired; the diff touches no other line; docs-only, no code paths, no behavior.+- **Depends on**: nonediff --git a/docs/brainstorm/answer-trust/variants.md b/docs/brainstorm/answer-trust/variants.mdnew file mode 100644index 00000000..116f44e0--- /dev/null+++ b/docs/brainstorm/answer-trust/variants.md@@ -0,0 +1,48 @@+# Answer trust: verified quotes, claim attribution, source archives, session identity - brainstorm audit trail++Consultant: variant analysis run against the branch point a00fa3f5 (v1.80.0) with the verified-premises brief; the variants below are the consultant output verbatim, mirrored in `cli-output/consultant.md`. Prompt at `cli-output/prompt.md`.++## Variants as returned++### Variant 1: Independent lanes at natural seams+- **Approach**: Each card lands exactly where its verified premises point, with no shared machinery beyond the existing vault layout: A as a new Stop-hook step plus src/core/brain/answer-quotes/check.ts with a per-phase quote_check resolver (off|shadow|enforce, shadow default); B as the optional sample_id field frozen on ClaimEvent plus the read-only claim-provenance.ts join; C as provenance/source-archive.ts wired into the distill intake path; D as explicit no-session semantics in the five reader sites plus the count-only blank-session-identity doctor check. Config stays per-feature in src/core/config.ts, doctor checks register individually in DOCTOR_CHECKS, and each card carries its own census test. The repair lane (property-pushdown freshness gate, CHANGELOG whitespace) rides along independently of all four.+- **Trade-offs**:+ - Matches the house parallel-lane process: disjoint file ownership, each card testable and revertible in isolation.+ - The hot path is touched by exactly one component (the A hook step), bounded and fail-open as the constraints require.+ - No sequencing constraints between lanes, so the PR assembles at merge time with minimal coordination.+ - Wave coherence is editorial, not structural: nothing in the code expresses claim → receipt → note → archived source as one chain.+ - Small risk of duplicated utility logic (hashing, redaction interplay, span normalization) across lanes that a shared home would consolidate.+ - A later cross-card feature, such as quote verification against archived bytes, would need a second pass.+- **Complexity**: small+- **Risk**: low++### Variant 2: Provenance spine (B and C fuse into one chain)+- **Approach**: Make src/core/brain/provenance/ the structural center of the wave: C's source-archive.ts and B's claim-provenance.ts live there under one integrity contract (content-addressed, redacted-before-persist, doctor-verified presence), so the read-time join resolves claim → receipt → note → source_archive_hash as a single chain terminating in durable bytes. A and D keep their prescribed shapes unchanged, with A's hook step still bounded and fail-open, but the doctor family and census tests guard the whole chain invariant instead of per-card fragments. The repair lane still rides along independently.+- **Trade-offs**:+ - The wave spine becomes literal: a claim's provenance can end at content-addressed bytes that survive link rot, the strongest trust story available this wave.+ - One integrity contract and one doctor family avoid scattered, inconsistent verify logic and duplicated hashing/redaction utilities.+ - Seeds future work cleanly: A verifying against archived bytes later is additive, not a redesign.+ - Lanes B and C share the provenance home, breaking strict disjoint file ownership and forcing C's format to land before B's join consumers.+ - Coupling crosses card boundaries: a regression in C's capture marks B's chain incomplete, widening the blast radius of each lane.+ - More up-front design for a chain whose only consumer this wave is doctor/CLI reporting, since OSB never sees answer text.+- **Complexity**: medium+- **Risk**: medium++### Variant 3: Unified answer-trust phase ladder+- **Approach**: Compose the wave around one config namespace, answer_trust, with a single per-phase ladder (off|shadow|enforce) governing all cards at once: A's quote checking, C's capture scope (shadow = best-effort capture, enforce = refuse-not-truncate ingest without an archive entry), and B's join surfacing (shadow = doctor/CLI report, enforce = provenance annotations on claim reads). D sits outside the ladder because its decision is semantic and fixed, and the repair lane is unaffected. This trades per-feature resolvers for one operational dial across the whole trust surface.+- **Trade-offs**:+ - One mental model for operators: a single phase readout answers "how much trust machinery is on" without consulting four resolvers.+ - Shadow-by-default propagates consistently, and per-phase switchability is preserved across the wave.+ - Conflates independent failure domains: one mis-set phase silently degrades capture, verification, and join surfacing together, which the per-feature resolver house rule exists to prevent.+ - D does not fit the ladder, so the unified story needs an exception on day one, weakening the abstraction immediately.+ - Gating C's intake behavior on a wave-wide phase entangles the write path with A/B posture changes, and future cards must negotiate the ladder's semantics.+ - Largest config and test surface: the ladder itself needs its own resolver, census coverage, and phase-matrix tests before any card value ships.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 1+**Rationale**: Every card's verified premise already fixes its shape and seam, so Variant 1 is the faithful composition and the only one that preserves strict disjoint lane ownership, per-feature config resolvers, and a hot path touched by exactly one bounded, fail-open component. Variant 2 buys a literal trust chain at the cost of lane coupling and sequencing that the parallel-lane process cannot absorb in this wave, and Variant 3's wave-wide ladder conflates failure domains against the house resolver rule and guarded architecture. Variant 1 also keeps the spine cheap to grow later, since both B's optional sample_id field and C's source_archive_hash stamp are additive, schema-compatible fields that a future provenance home can adopt without rework.++## Orchestrator decision++Variant 1 is accepted. The verified premises already fix each card's shape and seam, so the faithful composition is also the cheapest one, and its strict disjoint lane ownership is exactly what the five-way parallel implementation process requires. The rejected variants fail on process grounds the wave cannot absorb: Variant 2 couples B and C into shared ownership with landing-order constraints, and Variant 3 conflates independent failure domains against the per-feature resolver house rule while needing a day-one exception for D. The coherence Variant 1 defers is cheap to recover later, because B's optional `sample_id` and C's `source_archive_hash` stamp are additive, schema-compatible fields a future provenance home can adopt without rework.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 599fd721..b9798c83 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -440,7 +440,7 @@ o2b brain export Read-only dump of active preferences, or (since v1o2b brain bank-export (CLI-only) One-file backup bundle: preferences, the page graph, page contracts, the sources dashboard. Redacted on the way out; refuses with exit 1 on an unreadable `pref-*.md` (since v1.49.0)o2b brain bank-import (CLI-only) Restore a bank bundle (--mode skip|overwrite|merge) [--trusted-restore]. Preference rows restore UNTRUSTED by default: every row lands `unconfirmed`, unpinned, at low confidence, on a fresh trial window dated from the restore - including a row the bundle already marked unconfirmed - and the run names each row it reset; `--trusted-restore` keeps the carried status, confidence, pin and window verbatim, for a backup you vouch for. A malformed preference already in the DESTINATION does not abort the import: the rows restore and the run prints `topic-key check incomplete: <path>` for each rule the topic-collision scan could not read, because that list is then a partial answer (since v1.49.0)o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence. Double-click a node to open it in Obsidian (live mode). Since v1.49.0 BOTH modes refuse a Brain file they cannot parse - `--export` writes nothing and exits 1, and live mode does not start, because a browser showing a silently smaller graph is the same lie as a written file - and `--export` runs the shared redactor over the graph, so its output differs from a pre-v1.49.0 export on any vault holding a credential-shaped value-o2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, ...). --remediate [--dry-run] plans a dependency-ordered repair and applies auto-safe content-hash re-stamps+o2b brain doctor Check Brain-specific invariants (status-vs-folder, broken wikilinks, ...). --remediate [--dry-run] plans a dependency-ordered repair and applies auto-safe content-hash re-stamps. Since v1.81.0 the report also prints a count-only archive section over Brain/.archives/ (entries, combined bytes, stamped pages whose entry is missing or mismatched, entries no page cites; silent on a vault that never archived a source) and runs the fail-soft `blank-session-identity` check, counting continuity records still carrying the legacy blank session id; both are informational and neither repairso2b brain health Semantic-health report (since v0.14.0): contradictory confirmed preferences, recurring concepts with no dedicated preference, stale claims, plus a clean | watch | investigate verdicto2b brain history Render a preference's edit-history timeline (since v0.14.0): one entry per content mutation (principle / scope / status before -> after)o2b brain audit Render a preference's full mutation audit trail (since v0.21.0): create / promote / update / retire / merge with agent, reason, revision + content-hash before/after. ret- or bare-slug arg resolves to the same trail@@ -533,7 +533,7 @@ o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [o2b brain session-describe --session-id <id> [--json]o2b brain session-expand <record-id> [--raw-limit <n>] [--cursor <offset>] [--json]o2b brain handoff <session-file> [--session-id <id>] [--format auto|claude|codex|hermes] [--json] - write Brain/handoffs/<date>-<scope>.md (since v0.37.0)-o2b brain hygiene scan | apply --ids <id,...> [--detectors conflicts,dedup,freshness,usefulness,slug-collisions,tags,capture-scope] [--dry-run] [--json] - hygiene findings pipeline; review findings never execute (since v1.3.0); the default sweep runs every detector except the opt-in ones (since v1.64.0: `slug-collisions` is default-on and reports same-stem groups such as topic.md beside topic-2.md as info findings, `tags` is opt-in and audits inline body tags only - frontmatter tags arrays are out of scope; since v1.67.0 `capture-scope` is default-on and warns, with proposed action review, when a retrievable page of active knowledge cites only sources that are currently url-only)+o2b brain hygiene scan | apply --ids <id,...> [--detectors conflicts,dedup,freshness,usefulness,slug-collisions,tags,capture-scope] [--dry-run] [--json] - hygiene findings pipeline; review findings never execute (since v1.3.0); the default sweep runs every detector except the opt-in ones (since v1.64.0: `slug-collisions` is default-on and reports same-stem groups such as topic.md beside topic-2.md as info findings, `tags` is opt-in and audits inline body tags only - frontmatter tags arrays are out of scope; since v1.67.0 `capture-scope` is default-on and warns, with proposed action review, when a retrievable page of active knowledge cites only sources that are currently url-only; since v1.81.0 the detector also names a cited source whose durable archive entry under Brain/.archives/ is missing or no longer matches the hash stamped on the page)o2b brain hygiene scan: with the optional `dedup` decision-model use in enforce, dedup findings carry an advisory `decision_model` verdict and a confident `different` is listed last; `o2b brain doctor` annotates `entity-alias-candidate` warnings the same way; `apply` ignores verdictso2b brain refresh --stale [--dry-run] [--json] - targeted recompile of stale derived pages; orphans archive into Brain/.snapshots (since v1.3.0)o2b brain anticipate --session <id> [--refresh] [--signal <text>] [--json] - read or warm the anticipatory context cache for the session's lineage root (since v1.3.0)@@ -629,13 +629,15 @@ o2b brain truth ingest --entity E --aspect A --value V --source Sconflicts [--window-days N] - value conflicts (independent sources within the window; resolution always ask_user)aggregate --action W [--unit U] [--entity E] - sum exact (entity, action, unit) quantity matchescollisions [--window-days N] - cross-agent convergence on one entity+ events [--entity E] [--since X] [--until Y] [--limit N] - recall a windowed slice of the ledger (since v1.77.0); since v1.81.0 a row carrying a `sample_id` hydrates the provenance behind it - the named context receipt's items and the context-pack outcome row, resolved at the caller's reach, with "receipt known, outcome unknown" rendered rather than invented+ state --subject S --relation R --object O --text T --source S [--agent N] [--sample-id ID] - commit an agent-stated claim through the anchoring verdict (since v1.77.0); the optional opaque `--sample-id` (since v1.81.0) names the context-pack sample the claim drew on and is frozen on the committed eventsweep [--max-events N] - keep the newest N claim events and refoldo2b brain facts decompose (--file <path> | --text <text>) [--ingest --entity E] - deterministic atomic assertions; --ingest appends structured-family claimso2b brain dead-end record --approach T --reason T [--context T] | list - negative-knowledge registry under Brain/dead-ends/o2b brain foresight [--horizon-days N] [--write] - forward projection: routines coming due, open commitments, open questions```-Claims live as device-sharded append-only JSONL under `Brain/truth/` with a recomputable `state.json` fold - deleting the cache loses nothing. The merge guard rides `o2b brain merge` (an `entity-guard` refusal when the two preferences anchor disjoint people/orgs; `--force` bypasses). `o2b brain apply-evidence` accepts `--outcome success|failure|unknown`; the dream pass stages `outcome_regressions` with a deterministic confidence penalty when applied events carry repeated failures. `brain_review_candidates` annotates inbox signals with `signal_novelty` when the vault has indexed embeddings.+Claims live as device-sharded append-only JSONL under `Brain/truth/` with a recomputable `state.json` fold - deleting the cache loses nothing. The merge guard rides `o2b brain merge` (an `entity-guard` refusal when the two preferences anchor disjoint people/orgs; `--force` bypasses). `o2b brain apply-evidence` accepts `--outcome success|failure|unknown`; the dream pass stages `outcome_regressions` with a deterministic confidence penalty when applied events carry repeated failures. `brain_review_candidates` annotates inbox signals with `signal_novelty` when the vault has indexed embeddings. Since v1.81.0 the provenance join behind a claim's `sample_id` is reach-shaped: one ledger read per report, rule-only receipt items and item paths the caller cannot read stay hidden below local reach, a claim timestamped before its claimed receipt is flagged as an inversion, and a row without a `sample_id` renders byte-identically to before.### Write-time integrity and governance (since v0.44.0)diff --git a/docs/mcp.md b/docs/mcp.mdindex f628d906..b0e8fa0d 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -394,7 +394,7 @@ flags for a narrower per-process full server.| `brain_agenda` | Stateless agenda synthesis over caller-provided calendar events (the host fetches them; the Brain never calls a calendar API): overlap conflicts, free focus blocks (optionally clipped to a workday window), and events organised outside the operator's own email domain(s). No vault writes. | `events` || `brain_context_presets` | Show, suggest, or diff read-only context budget presets (`tight-context`, `long-context`) without writing config. | `operation` || `brain_pre_compact_extract` | Extract decision/commitment/outcome/rule/open-question records from bounded text into continuity storage. | `session_id`, `turn_start`, `turn_end`, `text` |-| `brain_hygiene` | Memory hygiene: `scan` findings (conflicts, dedup, freshness, usefulness; since v1.64.0 `slug-collisions` is default-on — same-stem allocation residue such as `topic.md` beside `topic-2.md` — and `tags` is opt-in, auditing inline body tags only, never frontmatter tags arrays; since v1.67.0 `capture-scope` is default-on and warns when active knowledge rests only on `url-only` sources; the default is the sweep of every registered detector except the opt-in ones), `apply` selected ids, `refresh` stale pages. Resolver command comes from `_brain.yaml` only. When `hygiene_digest_enabled` is on in the machine config, the same default-sweep findings are also pushed at turn end as a one-line digest (Stop hook, once per change), so this pull surface doubles as a push channel. With the optional `dedup` decision-model use in enforce, `scan` dedup findings carry an advisory `decision_model` verdict; `apply` never reads it. | `mode` |+| `brain_hygiene` | Memory hygiene: `scan` findings (conflicts, dedup, freshness, usefulness; since v1.64.0 `slug-collisions` is default-on — same-stem allocation residue such as `topic.md` beside `topic-2.md` — and `tags` is opt-in, auditing inline body tags only, never frontmatter tags arrays; since v1.67.0 `capture-scope` is default-on and warns when active knowledge rests only on `url-only` sources; the default is the sweep of every registered detector except the opt-in ones), `apply` selected ids, `refresh` stale pages; since v1.81.0 `archive_get` resolves an ingest summary's `source_archive_hash` to its archived bytes under `Brain/.archives/` (local reach only, and the `capture-scope` scan also names a cited source whose archive entry is missing or mismatched). Resolver command comes from `_brain.yaml` only. When `hygiene_digest_enabled` is on in the machine config, the same default-sweep findings are also pushed at turn end as a one-line digest (Stop hook, once per change), so this pull surface doubles as a push channel. With the optional `dedup` decision-model use in enforce, `scan` dedup findings carry an advisory `decision_model` verdict; `apply` never reads it. | `mode` || `brain_anticipatory_context` | Turn-specific context bundle kept warm by lifecycle hooks, keyed by the session's lineage root; reports `cache_state` warm / stale / miss. | `session_id` || `brain_session_grep` | Search imported session recall raw turns and deterministic summary nodes. | `query` || `brain_session_describe` | Describe raw-turn counts and summary depths for one imported session recall DAG. | `session_id` |@@ -523,6 +523,22 @@ walk, windowed by `since`/`until`, with the observation window, a cappeddead-page list, and the gate caveat (telemetry is opt-in and records onlysurfaced top rows, so the report claims "no recorded retrieval surface",never absolute never) in every payload.+Since v1.81.0 `brain_truth` `state` accepts an optional opaque `sample_id`+(echoed verbatim on the committed event) and the `events` report hydrates+the provenance behind it: the named context receipt's items plus the+context-pack outcome row, resolved at the caller's reach - below local+reach, receipt items whose injections came from operator rules stay+hidden, a claim whose outcome never arrived renders "receipt known,+outcome unknown", and rows without a `sample_id` stay byte-identical to+before. `brain_ingest_source` in the trusted local lane archives the+source's bytes content-addressed under `Brain/.archives/` (redacted+before persist, refused past 1 MiB rather than truncated, never+TTL-pruned), stamps `source_archive_hash` and `source_archive_bytes` on+the summary page and returns `source_archive_hash`; delete-by-source+cleanup removes the source's orphaned archive entries best-effort, and+`brain_session_summary` `get` and `list` omit the `session_id` key of a+digest that has no session instead of answering `""`, matching the+no-session read rule every continuity reader applies.`brain_context_presets` supports `operation: "show"|"suggest"|"diff"`; and`brain_generation_reports` supports `action: "record"|"list"|"summary"` -`record` is gated (default off) by a per-call `enable` flag or thediff --git a/docs/observability.md b/docs/observability.mdindex 7e234dc0..b0174511 100644--- a/docs/observability.md+++ b/docs/observability.md@@ -49,7 +49,7 @@ The `prompt_prefix` metric surface measures STRUCTURAL prompt-prefix stability (| `freeze`, `unfreeze` | an operator stopped or reopened the content lane for every device that syncs the vault (`o2b brain freeze` / `o2b brain unfreeze`). One event per real transition only - a second freeze, or an unfreeze on an open vault, writes nothing. `freeze` carries the `reason` and the `device_id` it was set from; `unfreeze` carries the `frozen_at`, `by` and `reason` read off the marker before it was removed, which is the only place they survive the file || `write-refused` | a write was refused because the vault is frozen. Appended at the MCP tool boundary - the guard that refuses sits below the log module and cannot append without closing an import cycle - one per refused call, carrying the `tool`, the `agent` and the marker's `reason`. The Brain log itself keeps writing while frozen (the audit write lane, `WRITE_LANE.audit` in `src/core/brain/freeze-marker.ts`), because a freeze that silenced the log would erase the record of itself || `scan-inline`, `import-session`, `import-claude-memory` | capture and import operations |-| `note` | a narrative milestone is recorded (`brain_note`) |+| `note` | a narrative milestone is recorded (`brain_note`); since v1.81.0 also the answer-quote-check Stop hook's enforce trail - exactly one event per turn that found unverified quoted spans, carrying `hook: answer-quote-check`, the phases that ran, the checked and unverified counts, and the findings as capped one-line previews || `note-write` | a vault note is created, updated, appended to, or reverted || `session-lifecycle` | a captured lifecycle event also produced Brain writes || `decision-open` | a question was parked with enumerated options at `Brain/decisions/open-<slug>.md`, ahead of the decision it may become. Payload carries the `open` wikilink, the `title`, the option `count` and the `agent`. Distinct from `decision-record` because nothing has been decided yet |@@ -175,6 +175,8 @@ Since v0.39.0 every new continuity record is stamped `schema: "o2b.continuity.v1Multi-agent vaults attribute writers via per-agent identity (`brain_agent_query`). Delegated sub-agents are correlated as of v1.49.0, and by the additive route this sentence used to promise: `SessionTurn` carries an optional `agentId` and an optional `isSidechain: true`, both emitted only where the transcript records them, so a flat transcript keeps its pre-delegation shape byte for byte. A sub-agent transcript reuses its PARENT's session id, so those two fields are the only thing separating the two agents' turns. The `SubagentStop` hook records the close under `<delegator>-sub-<agent-id>`; the `agent_transcript_path` the event also carries is deliberately not persisted, being a machine-local host path.+**Absence is its own identity.** Since v1.81.0 a payload with no string `session_id` is a no-session record, never a member of a blank bucket: the readers no longer coerce the missing key to `""`, so scoped recall excludes such records (the lineage ledger already omitted blank declarations, so the scope set never held them), grouping sites skip them instead of lumping every unattributed record from every unrelated lane together, and the `brain_session_summary` digest omits its `session_id` key rather than answering `""`. `o2b brain doctor` counts the rows older writers left under the legacy coercion with the count-only, fail-soft `blank-session-identity` check - one issue per affected record kind, no `fix` field: the continuity store is append-only, and rewriting it is a backup-gated design, not a doctor step.+## Payload safetyEvery continuity payload passes `safeContinuityPayload()` (`src/core/brain/continuity/redaction.ts`) before it reaches disk:@@ -210,6 +212,7 @@ No-consumer regression tests cover each gated surface, so a future call site can- `brain_recall_telemetry` `operation: "cost"` (MCP) and `o2b brain recall-telemetry cost` fold WRITE volume against the read telemetry above: memory-write ops (Brain-log `feedback`/`apply-evidence`/`note` verbs plus `host_memory_write` continuity records) are counted per period and reported alongside reads as a write-vs-read ratio, a `write_heavy` flag, and a rough weighted cost signal. Weights (`--write-cost`/`--read-cost`, default 1 each) model "some tools charge on write, some on read"; `--write-heavy-ratio` (default 1) sets the write-heavy threshold. Read-only; period-scoped by `--since`/`--until`. `brain_create_note` file creation emits no telemetry event today and is not counted.- `brain_recall_telemetry` `operation: "dead_weight"` (MCP) and `o2b brain recall-telemetry dead-weight` (since v1.80.0) read the other side of the same records: pages currently in scope that no recorded recall within the telemetry window ever surfaced. The denominator is the vault walk's included paths (current on-disk truth), not the index's document table, so a deleted-but-indexed page is never reported as dead weight; the retrieved set is the union of recorded `top_artifacts` and observed-use source references, windowed by `--since`/`--until` (the report states the earliest matching record). The payload carries `pages_total`, `pages_retrieved`, `dead_count` and a capped `dead` list behind the usual `vault_path` envelope, plus a `gate_caveat`: telemetry is opt-in and records only surfaced top rows, so the report claims "no recorded retrieval surface within telemetry history", never absolute never. Read-only; at remote reach hidden rows are dropped before `total`.- `brain_context_receipts` and `o2b brain context-receipts` inspect served-context receipts.+- The answer-quote-check Stop hook (since v1.81.0) is the answer-boundary counterpart of the receipts above: it verifies the quoted spans in the assistant's own answer against the evidence the turn actually had - the note a span's context names, else the injection ledger's delivered notes - and annotates the unverified ones. Verdicts: `verified`, `not-in-note`, `source-truncated`, `note-unavailable`, `not-text`; degradation never upgrades a verdict, so a truncated source arms `source-truncated` on a miss and an unreadable note arms `note-unavailable`, never an all-clear. The annotation rides the Stop `additionalContext` channel Claude Code renders; the other registered runtimes stay silent. Gated per phase by `quote_check.recall|active|subagent` in `_brain.yaml`, each `off|shadow|enforce`, default `shadow`; in `enforce` the turn also lands one Brain-log `note` event (the enforce trail in the table above), so findings survive the session. The check reads only the transcript's bounded tail window and writes nothing else; it never blocks and never edits a transcript.- The SessionStart hook writes one `context_receipt` per injection (`host: "hook"`, `trigger: "session_inject"`) with one item per source it injected. On a measured run its `budget` block carries `inject_budget_chars` (the configured value), `budgeted_source_count` and, since v1.70.0, `scoped_rules_chars`: the length of the rendered scoped operator rules block, `0` when none rendered. The scoped block is a budgeted source named `scoped-rules`, but it is subtracted from the budget rather than charged against the full ceiling: the active body was budgeted to `inject_budget_chars` minus `scoped_rules_chars` (never below zero). The `budget` block is present whenever the scoped block rendered, also when there is no `active.md`. A run that fell back to the last good cache records no `budget` block, as before, but keeps the `standing-rules` and `scoped-rules` items, which are produced outside the fail-open boundary. See "Scoped operator rules" in [`how-it-works.md`](how-it-works.md).- With `reground_parts_enabled` on, the same receipt's `extra.injection` gains the chunked re-grounding fields: `utf16_chars` (the joined payload length in UTF-16 code units), `part_ceiling_chars` (the per-part ceiling it was cut to, `null` on a runtime without the `reground-deliver` carrier or without a session id), `parts_total`, `parts_dropped` (parts past the 8-part maximum that were never queued; when it is above zero the last delivered part ends with `(context truncated: N further part(s) not delivered)`) and `over_budget` (`true` when parts were dropped, when a part is still longer than the ceiling, or when the queue could not be written and the whole payload went out as one part). That last case also sets `reground_fallback: "ledger_write_failed"`, which no other path writes, so a failed queue write is told apart from a plain over-budget payload. A part-ceiling key (`reground_part_chars`, `reground_part_chars_claudecode`, `reground_part_chars_codex`) whose value is out of range or not an integer falls through to the next level and is named in `config_invalid` (by its environment variable, such as `OPEN_SECOND_BRAIN_REGROUND_PART_CHARS`, when the rejected value came from the environment), present only then. With the flag off none of these fields appears and the receipt keeps its shape. Each part the `reground-deliver` hook hands out writes one hook-audit line (`actor: reground-deliver`, `action: reground_part_delivered`, `target` the host event `PostToolUse` or `UserPromptSubmit`) with `part` (the 1-based part number), `total`, `epoch` (the SessionStart that queued it, as `<source>:<epoch-ms>` with the source one of `startup`, `resume`, `clear` or `compact`, any other value recorded as `unknown`), `bytes` (UTF-8), `utf16_chars`, `part_ceiling_chars` and `over_budget` (the part alone is longer than the ceiling). A take that fails for a reason other than lock contention (an unreadable state directory, a full disk) writes `action: reground_take_failed` with `ok: false`, no part and `epoch` (the queue's SessionStart, `null` when unreadable), once per epoch on each machine: a state write that keeps failing leaves the queue undrained, and the repeats on later tool calls write no further line. A tool call inside a delegated sub-agent (the payload carries `agent_id`) takes no part and writes no line. A process-ceiling exit writes `action: hook_ceiling_exceeded`, `target: reground`.- `brain_route_metrics` (MCP, `operation: "list"|"summary"`) reads route-level MCP tool latency. `list` returns raw `mcp_route_latency` records (filter by `tool`/`status`/`since`/`until`/`limit`); `summary` rolls each tool up into count, error count, and min/avg/max plus p50/p95/p99 latency, ordered slowest-first so an operator can identify which endpoint blocks an agent turn by route rather than by aggregate benchmark. A route whose records carry `stages` also gets a `stages` roll-up - per stage name, in `ROUTE_STAGE` order, the count, the average and the nearest-rank p95 in ms - and a route without stages has no `stages` key. Records are emitted only when `mcp_route_metrics_enabled` is on (default off); read-only.diff --git a/hooks/README.md b/hooks/README.mdindex e8a9a139..24bd0ba7 100644--- a/hooks/README.md+++ b/hooks/README.md@@ -30,6 +30,7 @@ hook payload shape, not on the runtime.| `SubagentStart` | `*` | Primary carrier: delivers the operator's context payload into a delegated sub-agent's context at its conversation start, before its first prompt, and again if the subagent compacts - the host re-fires the event then, and the re-injection lands only if this hook answers that later event. The payload is what the session-start lane composes, through the same assembly: the standing rules, the scoped operator rules for this project and device, and the budgeted `Brain/active.md` + `Brain/lessons.md` digest under the same `active.inject_budget_chars` ceiling (runtime notices ride along when that channel is on). No tool gating - the event itself marks the sub-agent - and no ledger suppression: every SubagentStart for the id re-delivers, while the ledger it feeds after each delivery keeps the PostToolUse fallback row above to once per sub-agent per session. Runtimes without a SubagentStart event never fire this row; the fallback covers them. || `PostCompact` | `manual\|auto` | Records a post-compact lifecycle observation only. Current Claude Code has no PostCompact hook event and rejects `additionalContext` under that name - re-injection moved to the SessionStart `compact` matcher; the registration stays as a silent no-op for older runtimes. || `Stop` | (every Stop) | If the turn produced a durable artifact and none of `brain_feedback` / `brain_apply_evidence` / `brain_note` landed, continues the turn once with a one-line reminder, then lets the second Stop pass. Claude Code gets `hookSpecificOutput.additionalContext` (shown as "Stop hook feedback", not a hook error); Codex, Grok Build and unrecognised runtimes get `decision: "block"` with the same line as `reason`. |+| `Stop` | (every Stop) | `answer-quote-check` verifies the quoted spans in the assistant's answer against the evidence the turn actually had: the note a span's context names (wikilink or vault-relative path), else membership in the injection ledger's delivered notes for the phases running. Five verdicts - `verified`, `not-in-note`, `source-truncated`, `note-unavailable`, `not-text` - and degradation never upgrades one: a note whose body reached context truncated arms `source-truncated` on a miss, an unreadable note arms `note-unavailable`, never an all-clear. Per-phase config in `_brain.yaml` (`quote_check.recall`, `quote_check.active`, `quote_check.subagent`, each `off\|shadow\|enforce`, default `shadow`); `enforce` also appends exactly one Brain-log `note` event per turn so findings survive the session. One non-blocking `hookSpecificOutput.additionalContext` annotation per turn lists the unverified spans as flattened, capped previews; Claude Code renders it, other runtimes stay silent. Never blocks, never edits a transcript: bounded message-window and character reads, fail-open exit 0. || `Stop` | (every Stop) | Opt-in (`hygiene_digest_enabled`, default off): `hygiene-digest` surfaces pending Brain hygiene findings as one line, once per change. Artifact-writing turns run the default sweep plus the dangling-link count; findings of warning and action severity fold into counts per detector, and a hash ledger keeps an unchanged set silent. Claude Code only: the line rides its non-blocking `hookSpecificOutput.additionalContext` Stop feedback, and on runtimes where a Stop block would force a continuation turn (Codex, Grok Build, unrecognised) the hook stays silent - an opt-in digest never buys a continuation. Checked before the vault, so it is cheap when off. || `SubagentStop` | `*` | Records a non-blocking lifecycle observation for a delegated sub-agent's close, attributed to `<delegator>-sub-<agent-id>` from the `agent_id` the event carries. The sibling `agent_transcript_path` is deliberately not persisted - it is a machine-local host path, and the sub-agent's turns reach memory through `o2b brain import-session`, which reads `isSidechain` and `agentId` off the transcript itself. || `SessionEnd` | `*` | Records a non-blocking lifecycle observation for session close. |@@ -110,6 +111,14 @@ call would.scripts. They are tiny by design: they parse stdin, query`lib/transcript.ts` and `lib/detect.ts`, and emit the hook's JSONresponse on stdout. Never block on errors.+- `answer-quote-check.ts` — Bun entry script for the Stop hook's+ answer-time quote verification (since v1.81.0). It reads the+ transcript's bounded tail window, resolves each quoted span's cited+ note or injection-ledger evidence, checks it through+ `src/core/brain/answer-quotes/check.ts`, and answers with one+ `additionalContext` annotation listing the unverified spans; in+ `enforce` it also appends one Brain-log event. Never blocks, never+ edits a transcript, fail-open.- `lib/stdin.ts` — read the single JSON object both runtimes send onstdin.- `lib/transcript.ts` — JSONL parser that recognises both thediff --git a/hooks/answer-quote-check.ts b/hooks/answer-quote-check.tsnew file mode 100644index 00000000..a73489ba--- /dev/null+++ b/hooks/answer-quote-check.ts@@ -0,0 +1,930 @@+#!/usr/bin/env -S bun+/**+ * Stop hook: answer-time quote verification (answer-trust wave, Lane A).+ *+ * At turn end this step reads the LAST assistant messages of the turn,+ * finds their quoted spans with the distill lane's own+ * `findQuoteSpans`, and checks each span against the evidence the turn+ * actually had:+ *+ * - the note the span cites - a wikilink target or a vault-relative+ * path in the message text, resolved against the vault; and+ * - otherwise the notes the injection ledger says entered context this+ * session, across the four phase keys (recall keys, the active+ * digest's emitted paths plus its queued re-delivery parts, and the+ * note paths the sub-agent carrier recorded with its deliveries).+ *+ * Each span gets one verdict from+ * `src/core/brain/answer-quotes/check.ts` - `verified`, `not-in-note`,+ * `source-truncated`, `note-unavailable` or `not-text` - and the+ * unverified ones are listed in exactly ONE+ * `hookSpecificOutput.additionalContext` annotation (the+ * `hooks/stop-log-guardrail.ts` precedent). The hook NEVER blocks and+ * NEVER edits the transcript: a verdict is reported, not enforced.+ *+ * Phases. A phase runs only when BOTH hold: the phase's injection is+ * enabled (recall requires `recall_inject_enabled`; active and subagent+ * require a live injection ledger for the session) and its+ * `quote_check.<phase>` resolver returns more than `off`.+ * `shadow` annotates only; `enforce` additionally appends exactly one+ * Brain-log event per turn with the unverified spans, so findings survive+ * the session - and never blocks.+ *+ * Channel. The annotation rides `hookSpecificOutput.additionalContext`+ * on the Stop event, which Claude Code renders into the turn. Codex and+ * grok accept the registration but render no Stop annotation - and grok+ * ships no `transcript_path` at all - so the check is silently inert on+ * them: fail-open silence, kept deliberately, with the `enforce`+ * Brain-log trail as the one finding surface that survives the session.+ *+ * Bounded, fail-open. The step reads at most+ * {@link ANSWER_QUOTE_TAIL_BYTES} of the transcript, the last+ * {@link ANSWER_QUOTE_MAX_MESSAGES} assistant messages of the turn,+ * {@link ANSWER_QUOTE_MAX_CHARS} characters of each, and gives up by+ * checking nothing further once {@link ANSWER_QUOTE_BUDGET_MS} have+ * passed - unchecked spans are dropped rather than run long. Every error+ * path exits 0 with exactly one stderr audit line, producing nothing.+ * Fires at most once per turn: when the runtime reports+ * `stop_hook_active === true` (this turn was already continued by a Stop+ * hook) the hook exits 0 silently.+ */++import {+ closeSync,+ existsSync,+ fstatSync,+ openSync,+ readFileSync,+ readSync,+ statSync,+} from "node:fs";++import {+ resolveAnswerQuoteCheckActive,+ resolveAnswerQuoteCheckRecall,+ resolveAnswerQuoteCheckSubagent,+ resolveAgentName,+ resolveRecallInjectEnabled,+ resolveVault,+ type AnswerQuoteCheckMode,+ type AnswerQuoteCheckPhase,+ ANSWER_QUOTE_CHECK_PHASES,+} from "../src/core/config.ts";+import {+ ANSWER_QUOTE_VERDICT,+ checkAnswerQuotes,+ mergeAnswerQuoteVerdicts,+ previewAnswerQuoteSpan,+ type AnswerQuoteEvidence,+ type AnswerQuoteVerdict,+} from "../src/core/brain/answer-quotes/check.ts";+import { findQuoteSpans } from "../src/core/brain/distill/quote-spans.ts";+import { brainConfigPath } from "../src/core/brain/paths.ts";+import { appendLogEvent } from "../src/core/brain/log.ts";+import { BRAIN_LOG_EVENT_KIND } from "../src/core/brain/types.ts";+import { isoSecond } from "../src/core/brain/time.ts";+import { ensureInsideVault } from "../src/core/path-safety.ts";+import { asHookPayload, readHookInput } from "./lib/stdin.ts";+import {+ isRealSessionId,+ LEDGER_KEY_REGROUND,+ readActiveEmittedPaths,+ readRecallInjected,+ readSubagentDeliveredPaths,+} from "./lib/injection-ledger.ts";+import { readHookStamp } from "./lib/session-state.ts";++/**+ * The last assistant messages of the turn the check reads. Everything+ * older is another turn's answer.+ */+export const ANSWER_QUOTE_MAX_MESSAGES = 6;++/** Per-message character budget: the prefix of a message that is checked. */+export const ANSWER_QUOTE_MAX_CHARS = 4000;++/** Wall-clock budget for the whole check; past it, unchecked spans are dropped. */+export const ANSWER_QUOTE_BUDGET_MS = 1500;++/**+ * Ceiling on findings rendered in one annotation - and in one enforce+ * event: past it the tail of the list collapses into one "and N more"+ * line, so a pathological answer annotates its first spans instead of+ * flooding the context channel.+ */+export const ANSWER_QUOTE_MAX_FINDINGS = 20;++/**+ * Byte window of the bounded transcript tail read. Small enough that a+ * huge transcript cannot slow the Stop path, large enough to hold the+ * current turn's answers; the reader drops the one line the window may+ * have cut in half.+ */+export const ANSWER_QUOTE_TAIL_BYTES = 262_144;++/**+ * Ceiling on how much of one cited note the check reads, on the 1 MiB+ * scale of the ingest archive ceiling. Past it only the head of the file+ * is read and the evidence is named truncated - a miss against it is+ * `source-truncated`, never `not-in-note` - and a pointer that names a+ * line range is refused as `unavailable` rather than served a slice of+ * the prefix as if it were the named lines.+ */+export const ANSWER_QUOTE_NOTE_MAX_BYTES = 1_048_576;++/** Stderr audit prefix: every error arm prints exactly one line with it. */+const AUDIT_PREFIX = "answer-quote-check:";++/** One quoted span to check: its text and where it sits in its message. */+interface QuotedSpan {+ readonly message: number;+ readonly inner: string;+ readonly open: number;+ readonly close: number;+}++/** One citation mark found in a message: a note reference and its offset. */+interface CitationMark {+ readonly at: number;+ /** Vault-relative note path, `.md`-complete. */+ readonly path: string;+ /** 1-based inclusive line range, when the pointer names one. */+ readonly startLine?: number;+ readonly endLine?: number;+}++/**+ * A vault-relative `.md` path pointer, optionally naming a line range the+ * way every recall pointer renders it (`Brain/notes/x.md:L3-L9`). Requires+ * at least one directory separator, so a bare word before `.md` is prose,+ * not a pointer.+ *+ * The repeated class MUST exclude `/`. A class that can match the+ * separator itself segments a run of N slashes 2^(N-1) ways, and the scan+ * a hook feeds it routinely fails (a base64 blob in an answer carries+ * hundreds of slashes and no `.md`), so the engine walks every+ * segmentation and the Stop hook stalls past its 10 s timeout - the+ * CodeQL high on this file. With `/` excluded the scan is linear in the+ * text; the one reading that changes is `a//b/c.md`, now `b/c.md`.+ */+const PATH_POINTER_RE = /(?:[^\s:|[\]()#/]+\/)+[^\s:|[\]()#/]*\.md(?::L(\d+)-L(\d+))?/g;++/**+ * A `.md` path token, for scanning ledger member strings that are prose.+ * Excludes `/` for the same reason as {@link PATH_POINTER_RE}.+ */+const PATH_TOKEN_RE = /(?:[^\s:|[\]()#/]+\/)+[^\s:|[\]()#/]*\.md/g;++// ----- transcript tail -----------------------------------------------------++/**+ * Fill `length` bytes of `fd` from `start`, looping on `readSync` until+ * the window is filled or EOF: a single positional read may return+ * short, and a short read would silently shrink the window.+ */+function readWindow(fd: number, start: number, length: number): Buffer {+ const buffer = Buffer.alloc(length);+ let filled = 0;+ while (filled < buffer.length) {+ const moved = readSync(fd, buffer, filled, buffer.length - filled, start + filled);+ if (moved <= 0) break;+ filled += moved;+ }+ return filled === buffer.length ? buffer : buffer.subarray(0, filled);+}++/**+ * The last {@link ANSWER_QUOTE_TAIL_BYTES} of the transcript as text. One+ * bounded positional read; the caller drops the line the window may have+ * cut in half.+ */+function readTail(path: string): { readonly text: string; readonly cutStart: boolean } {+ const fd = openSync(path, "r");+ try {+ const stat = fstatSync(fd);+ // POSIX refuses to open a directory; Windows opens it and reports size+ // 0, which would read as an empty transcript - silence where every+ // platform must see one audit line. Name the failure identically+ // everywhere instead: only a regular file is a transcript.+ if (!stat.isFile()) throw new Error(`transcript is not a regular file: ${path}`);+ const start = Math.max(0, stat.size - ANSWER_QUOTE_TAIL_BYTES);+ return { text: readWindow(fd, start, stat.size - start).toString("utf8"), cutStart: start > 0 };+ } finally {+ closeSync(fd);+ }+}++/** First string `value`'s text blocks join to, or `""`. */+function textBlocks(content: unknown): string {+ if (typeof content === "string") return content;+ if (!Array.isArray(content)) return "";+ return content+ .filter(+ (block): block is { readonly text: string } =>+ typeof block === "object" &&+ block !== null &&+ typeof (block as { text?: unknown }).text === "string",+ )+ .map((block) => block.text)+ .join("\n");+}++/** A real user turn boundary in either transcript shape (not a tool result). */+function isUserBoundary(record: Record<string, unknown>): boolean {+ const message = record["message"] as Record<string, unknown> | undefined;+ if (+ record["type"] === "user" &&+ message !== null &&+ typeof message === "object" &&+ message["role"] === "user"+ ) {+ const content = message["content"];+ // Tool results ride user-role records too; they are not a turn boundary.+ const toolResultsOnly =+ Array.isArray(content) &&+ content.length > 0 &&+ content.every(+ (block) => typeof block === "object" && block !== null && block["type"] === "tool_result",+ );+ return !toolResultsOnly;+ }+ const payload = record["payload"] as Record<string, unknown> | undefined;+ if (record["type"] === "response_item" && payload !== null && typeof payload === "object") {+ if (payload["type"] !== "message" || payload["role"] !== "user") return false;+ const text = textBlocks(payload["content"]);+ // Codex prepends synthetic envelopes; they are not a user prompt.+ return !text.startsWith("<environment_context>") && !text.startsWith("<user_instructions>");+ }+ return false;+}++/** Assistant message text of one record, or `""` when the record has none. */+function assistantText(record: Record<string, unknown>): string {+ const message = record["message"] as Record<string, unknown> | undefined;+ if (record["type"] === "assistant" && message !== null && typeof message === "object") {+ return textBlocks(message["content"]);+ }+ const payload = record["payload"] as Record<string, unknown> | undefined;+ if (+ record["type"] === "response_item" &&+ payload !== null &&+ typeof payload === "object" &&+ payload["type"] === "message" &&+ payload["role"] === "assistant"+ ) {+ return textBlocks(payload["content"]);+ }+ return "";+}++/**+ * The last assistant messages of the turn, in answer order: the records+ * after the newest real user message inside the tail window, capped to+ * {@link ANSWER_QUOTE_MAX_MESSAGES} messages and+ * {@link ANSWER_QUOTE_MAX_CHARS} characters each. A window that holds no+ * user boundary contributes its newest assistant messages - the tail of+ * the current turn - which is what the check wants.+ */+function lastAssistantMessages(transcriptPath: string): ReadonlyArray<string> {+ const { text, cutStart } = readTail(transcriptPath);+ const lines = text.split(/\r?\n/).filter((line) => line.length > 0);+ // The first line of a mid-file window is cut in half by the window, not+ // written broken by the host.+ const whole = cutStart ? lines.slice(1) : lines;+ const records: ReadonlyArray<Record<string, unknown>> = whole.flatMap((line) => {+ try {+ const parsed = JSON.parse(line) as unknown;+ return parsed !== null && typeof parsed === "object"+ ? [parsed as Record<string, unknown>]+ : [];+ } catch {+ return [];+ }+ });+ const messages: string[] = [];+ for (let i = records.length - 1; i >= 0 && messages.length < ANSWER_QUOTE_MAX_MESSAGES; i--) {+ const record = records[i]!;+ if (isUserBoundary(record)) break;+ const body = assistantText(record);+ if (body.length === 0) continue;+ messages.push(+ body.length > ANSWER_QUOTE_MAX_CHARS ? body.slice(0, ANSWER_QUOTE_MAX_CHARS) : body,+ );+ }+ return messages.toReversed();+}++// ----- citations and evidence ----------------------------------------------++/** Wikilink targets of `text`, as citation marks at their offsets. */+function wikilinkMarks(text: string): CitationMark[] {+ const marks: CitationMark[] = [];+ for (const match of text.matchAll(/\[\[([^\]|#]+)(?:[#|][^\]]*)?\]\]/g)) {+ const target = match[1]?.trim();+ if (target === undefined || target.length === 0) continue;+ marks.push({+ at: match.index!,+ path: target.endsWith(".md") ? target : `${target}.md`,+ });+ }+ return marks;+}++/** Vault-relative path pointers of `text`, with any line range they name. */+function pathPointerMarks(text: string): CitationMark[] {+ const marks: CitationMark[] = [];+ for (const match of text.matchAll(PATH_POINTER_RE)) {+ const startLine = match[1] === undefined ? undefined : Number(match[1]);+ const endLine = match[2] === undefined ? undefined : Number(match[2]);+ marks.push({+ at: match.index!,+ path:+ startLine === undefined || endLine === undefined+ ? match[0]+ : match[0].slice(0, match[0].lastIndexOf(":L")),+ ...(startLine !== undefined && endLine !== undefined ? { startLine, endLine } : {}),+ });+ }+ return marks;+}++/** The citation marks of one message: offset-sorted, duplicate-free. */+function citationMarks(text: string): ReadonlyArray<CitationMark> {+ const byKey = new Map<string, CitationMark>();+ for (const mark of [...wikilinkMarks(text), ...pathPointerMarks(text)]) {+ const key = `${mark.path}\0${mark.startLine ?? ""}-${mark.endLine ?? ""}`;+ const existing = byKey.get(key);+ if (existing === undefined || mark.at < existing.at) byKey.set(key, mark);+ }+ return [...byKey.values()].toSorted((a, b) => a.at - b.at);+}++/**+ * Vault-absolute path of a cited note, or `null` when the reference+ * escapes the vault. Exists-checking is the caller's concern.+ */+function resolveNotePath(vault: string, relativePath: string): string | null {+ try {+ return ensureInsideVault(`${vault}/${relativePath}`, vault);+ } catch {+ return null;+ }+}++/**+ * The evidence one cited note offers: the exact bytes the context had -+ * the named line range when the pointer carries one (truncated: a+ * pointer that names a range names a partial view), the whole file+ * otherwise, and past `maxBytes` only the head of the file, decoded+ * non-fatally and named truncated. Every failure to read names itself as+ * `unavailable` / `not-text` evidence rather than throwing. Exported for+ * the bounded-read pins; the ceiling is injectable so a test needs no+ * multi-megabyte fixture.+ */+export function evidenceFor(+ vault: string,+ mark: CitationMark,+ maxBytes: number = ANSWER_QUOTE_NOTE_MAX_BYTES,+): AnswerQuoteEvidence {+ const absolute = resolveNotePath(vault, mark.path);+ if (absolute === null || !existsSync(absolute)) {+ return { kind: "unavailable" };+ }+ let limited: boolean;+ try {+ const stat = statSync(absolute);+ if (!stat.isFile()) return { kind: "unavailable" };+ limited = stat.size > maxBytes;+ } catch {+ return { kind: "unavailable" };+ }+ let whole: string;+ try {+ if (limited) {+ const fd = openSync(absolute, "r");+ try {+ // Non-fatal: a ceiling cut can split a multi-byte character, and+ // a valid UTF-8 note must not read as not-text for it.+ whole = new TextDecoder("utf-8").decode(readWindow(fd, 0, maxBytes));+ } finally {+ closeSync(fd);+ }+ } else {+ whole = new TextDecoder("utf-8", { fatal: true }).decode(readFileSync(absolute));+ }+ } catch {+ return { kind: "not-text" };+ }+ if (mark.startLine === undefined || mark.endLine === undefined) {+ return { kind: "text", text: whole, truncated: limited };+ }+ // A pointer that names a line range past the ceiling names lines the+ // bounded read did not fetch: refuse the evidence rather than serve a+ // slice of the prefix as if it were the named range.+ if (limited) return { kind: "unavailable" };+ const lines = whole.split("\n");+ const slice = lines.slice(mark.startLine - 1, mark.endLine).join("\n");+ return { kind: "text", text: slice, truncated: true };+}++// ----- the injection ledger's candidate notes ------------------------------++/**+ * One candidate note view the ledger offers as evidence: the note path,+ * the lines the injection named when it delivered only a range, the+ * phase whose ledger offered it, and whether the injection delivered+ * that note truncated (a clipped body is evidence of the delivered+ * prefix only).+ */+interface LedgerCandidate {+ readonly path: string;+ readonly startLine?: number;+ readonly endLine?: number;+ readonly phase: AnswerQuoteCheckPhase;+ readonly truncated?: boolean;+}++/** Answer order for candidate views: by path, then by named range. */+function compareCandidates(+ a: { readonly path: string; readonly startLine?: number; readonly endLine?: number },+ b: { readonly path: string; readonly startLine?: number; readonly endLine?: number },+): number {+ if (a.path !== b.path) return a.path < b.path ? -1 : 1;+ return (a.startLine ?? 0) - (b.startLine ?? 0) || (a.endLine ?? 0) - (b.endLine ?? 0);+}++/** The dedup key of one candidate view: the path, plus any range it names. */+function candidateKey(candidate: LedgerCandidate): string {+ return candidate.startLine === undefined || candidate.endLine === undefined+ ? candidate.path+ : `${candidate.path}\0${candidate.startLine}-${candidate.endLine}`;+}++/**+ * One merged candidate in the turn's evidence pool: the note view plus+ * every phase whose ledger offered it. The phases are the finding's+ * attribution - a miss is reported only when a phase that offered the+ * deciding evidence is itself running, and enforced only when one of+ * those phases enforces.+ */+interface MergedCandidate {+ readonly path: string;+ readonly startLine?: number;+ readonly endLine?: number;+ readonly truncated?: boolean;+ readonly phases: ReadonlyArray<AnswerQuoteCheckPhase>;+}++/**+ * Merge candidate view groups, per note path: a whole-file view wins over+ * that path's line ranges (the whole note reached context through one of+ * the groups), and identical ranges collapse - but several DISTINCT+ * ranges of one note all stand, each its own evidence. Collapsing them to+ * one range (or to the path) would check a correct quote of an earlier+ * range against only the latest one and report a miss the turn's+ * evidence actually refutes. A merged view carries the union of the+ * offering phases and the union of their truncation flags. Sorted by+ * path, then range.+ */+function mergeCandidateViews(+ groups: ReadonlyArray<ReadonlyArray<LedgerCandidate>>,+): ReadonlyArray<MergedCandidate> {+ const whole = new Map<string, Set<AnswerQuoteCheckPhase>>();+ const wholeTruncated = new Set<string>();+ const ranges = new Map<+ string,+ { candidate: LedgerCandidate; phases: Set<AnswerQuoteCheckPhase> }+ >();+ for (const group of groups) {+ for (const candidate of group) {+ if (candidate.startLine === undefined || candidate.endLine === undefined) {+ const phases = whole.get(candidate.path) ?? new Set<AnswerQuoteCheckPhase>();+ phases.add(candidate.phase);+ whole.set(candidate.path, phases);+ if (candidate.truncated === true) wholeTruncated.add(candidate.path);+ } else {+ const key = candidateKey(candidate);+ const entry = ranges.get(key);+ if (entry === undefined) {+ ranges.set(key, { candidate, phases: new Set([candidate.phase]) });+ } else {+ entry.phases.add(candidate.phase);+ if (candidate.truncated === true)+ entry.candidate = { ...entry.candidate, truncated: true };+ }+ }+ }+ }+ const mergedRanges = [...ranges.values()]+ .filter(({ candidate }) => !whole.has(candidate.path))+ .map(({ candidate, phases }) => ({+ path: candidate.path,+ ...(candidate.startLine !== undefined ? { startLine: candidate.startLine } : {}),+ ...(candidate.endLine !== undefined ? { endLine: candidate.endLine } : {}),+ ...(candidate.truncated === true ? { truncated: true } : {}),+ phases: [...phases],+ }));+ const mergedWhole = [...whole.entries()]+ .toSorted(([a], [b]) => (a < b ? -1 : 1))+ .map(([path, phases]) => ({+ path,+ ...(wholeTruncated.has(path) ? { truncated: true } : {}),+ phases: [...phases],+ }));+ return [...mergedRanges, ...mergedWhole].toSorted(compareCandidates);+}++/**+ * Note path + line range one recall ledger key names. Recall keys render+ * `<origin>:<vault-relative path>#L<start>-L<end>` (`recallInjectNoteKey`),+ * where the origin is a search-origin label+ * (`src/core/brain/portability/origins.ts`): the bare `local` of the+ * active vault, or a kind-namespaced origin whose label carries a slash -+ * `profile/<name>`, `source/<alias>` - for a note recalled from another+ * vault. Splitting on the LAST colon before the `#L` anchor puts the+ * whole label on the left, slash-bearing or not, and the path - always+ * carrying a `/` - on the right; the label is dropped. The cross-origin+ * note itself still cannot be read under the active vault - it is+ * evidence outside this vault - so its spans resolve as+ * `note-unavailable` deliberately, never as an all-clear.+ */+function recallKeyCandidate(+ key: string,+): { readonly path: string; readonly startLine: number; readonly endLine: number } | null {+ const hash = key.lastIndexOf("#L");+ if (hash === -1) return null;+ const range = /^L(\d+)-L(\d+)$/.exec(key.slice(hash + 1));+ if (range === null) return null;+ const body = key.slice(0, hash);+ const colon = body.lastIndexOf(":");+ const label = colon === -1 ? null : body.slice(0, colon);+ const rest = colon === -1 ? body : body.slice(colon + 1);+ // `<origin>:<path>`: the right side is a vault-relative path, whatever+ // the left side looks like. A colon with no slash on either side is+ // not a recognized key shape and the body stays whole.+ const path = rest.includes("/") || (label !== null && label.includes("/")) ? rest : body;+ return { path, startLine: Number(range[1]), endLine: Number(range[2]) };+}++/** `.md` path tokens in one ledger member string, without line ranges. */+function pathTokens(member: string): ReadonlyArray<string> {+ return [...member.matchAll(PATH_TOKEN_RE)].map((match) => match[0]);+}++/**+ * The candidate note paths of one phase's ledger: recall keys parse to+ * path + line range, the active ledger names paths directly, the queued+ * re-delivery parts are prose scanned for path tokens, and the sub-agent+ * delivery ledger names the paths the delivered payloads were built from+ * (a row recorded before that field existed contributes nothing - an old+ * ledger row is silence for this phase, never an error). Sorted,+ * deduplicated; empty when the session has no ledger (a sessionless host+ * has none at all).+ */+function ledgerCandidates(+ vault: string,+ sessionId: string | null,+ phase: AnswerQuoteCheckPhase,+ nowMs: number,+): ReadonlyArray<LedgerCandidate> {+ if (sessionId === null) return [];+ // Several DISTINCT line ranges of one note all stand: each names the+ // part of the note that actually reached context, and collapsing them+ // to the last range would check a correct quote of an earlier range+ // against the wrong lines. Whole-file views (no range) are deduped by+ // path; the merge across phases applies the whole-wins-over-ranges+ // rule (mergeCandidateViews).+ const seen = new Set<string>();+ const candidates: LedgerCandidate[] = [];+ const add = (candidate: Omit<LedgerCandidate, "phase">): void => {+ const key = candidateKey({ ...candidate, phase });+ if (seen.has(key)) return;+ seen.add(key);+ candidates.push({ ...candidate, phase });+ };+ if (phase === "recall") {+ for (const key of readRecallInjected(vault, sessionId, nowMs)) {+ const parsed = recallKeyCandidate(key);+ if (parsed === null) continue;+ add({ path: parsed.path, startLine: parsed.startLine, endLine: parsed.endLine });+ }+ }+ if (phase === "active") {+ for (const path of readActiveEmittedPaths(vault, sessionId, nowMs)) {+ add({ path });+ }+ const parts = readHookStamp(vault, sessionId, LEDGER_KEY_REGROUND, nowMs)?.data?.["parts"];+ if (Array.isArray(parts)) {+ for (const part of parts) {+ if (typeof part !== "string") continue;+ for (const path of pathTokens(part)) add({ path });+ }+ }+ }+ if (phase === "subagent") {+ for (const delivered of readSubagentDeliveredPaths(vault, sessionId, nowMs)) {+ add(+ typeof delivered === "string"+ ? { path: delivered }+ : { path: delivered.path, truncated: delivered.truncated },+ );+ }+ }+ return candidates.toSorted(compareCandidates);+}++// ----- the check ------------------------------------------------------------++/** One span's outcome under the resolved evidence, inside the budget. */+interface SpanOutcome {+ readonly verdict: AnswerQuoteVerdict;+ /**+ * The span as the check module previews it - length-capped, code-point+ * safe. Findings render only this form, never the raw span: a span is+ * answer text, and the annotation's line structure is the hook's voice.+ */+ readonly preview: string;+ /**+ * The phases of the candidates that decided this outcome - the verdict+ * source when the span verified, every candidate checked when it did+ * not. A finding is reported only when a running phase is among them,+ * and enforced only when one of those running phases enforces.+ */+ readonly decidingPhases: ReadonlyArray<AnswerQuoteCheckPhase>;+}++/** One span's verdict under the resolved evidence, inside the budget. */+function checkSpan(+ span: QuotedSpan,+ marks: ReadonlyArray<CitationMark>,+ candidates: ReadonlyArray<MergedCandidate>,+ vault: string,+ deadline: number,+): SpanOutcome {+ // The cited note: the nearest mark before the span, else the first one+ // after it. A mark inside the span is span content, never a citation.+ const before = marks.filter((mark) => mark.at < span.open);+ const after = marks.filter((mark) => mark.at > span.close);+ if (before.length > 0 || after.length > 0) {+ const mark = before.length > 0 ? before[before.length - 1]! : after[0]!;+ const { outcomes } = checkAnswerQuotes({+ spans: [span.inner],+ evidence: evidenceFor(vault, mark),+ });+ return {+ verdict: outcomes[0]!.verdict,+ preview: outcomes[0]!.span,+ decidingPhases: [],+ };+ }+ if (candidates.length === 0) {+ return {+ verdict: mergeAnswerQuoteVerdicts([]),+ preview: previewAnswerQuoteSpan(span.inner),+ decidingPhases: [],+ };+ }+ const verdicts: AnswerQuoteVerdict[] = [];+ const decidingPhases: AnswerQuoteCheckPhase[] = [];+ let preview = previewAnswerQuoteSpan(span.inner);+ for (const candidate of candidates) {+ if (Date.now() > deadline) {+ // Budget spent with unread candidates left: the check did not+ // finish, so it never reports a readable-miss verdict.+ return { verdict: ANSWER_QUOTE_VERDICT.noteUnavailable, preview, decidingPhases };+ }+ const mark: CitationMark = {+ at: -1,+ path: candidate.path,+ ...(candidate.startLine !== undefined ? { startLine: candidate.startLine } : {}),+ ...(candidate.endLine !== undefined ? { endLine: candidate.endLine } : {}),+ };+ let evidence = evidenceFor(vault, mark);+ // The injection delivered only a prefix of this note: evidence is the+ // delivered prefix, whatever the file holds today. A miss under+ // clipped evidence is `source-truncated`, never a readable miss - a+ // truncated source never acquits a span, and never convicts one the+ // delivered text cannot judge.+ if (candidate.truncated === true && evidence.kind === "text") {+ evidence = { ...evidence, truncated: true };+ }+ const { outcomes } = checkAnswerQuotes({+ spans: [span.inner],+ evidence,+ });+ const verdict = outcomes[0]!.verdict;+ preview = outcomes[0]!.span;+ verdicts.push(verdict);+ for (const phase of candidate.phases) decidingPhases.push(phase);+ if (verdict === ANSWER_QUOTE_VERDICT.verified) break;+ }+ return { verdict: mergeAnswerQuoteVerdicts(verdicts), preview, decidingPhases };+}++/**+ * One rendered finding line. The span renders flattened - CR/LF and+ * whitespace runs collapsed to single spaces, inside the check module's+ * preview cap - so answer text can never introduce annotation-shaped+ * lines of its own.+ */+function findingLine(span: string, verdict: AnswerQuoteVerdict): string {+ return `- [${verdict}] "${span.replace(/\s+/g, " ").trim()}"`;+}++/** One unverified span, as the annotation and the enforce trail name it. */+interface AnswerQuoteSpanFinding {+ readonly span: string;+ readonly verdict: AnswerQuoteVerdict;+}++/** Duplicate findings collapse to their first occurrence, answer order kept. */+function dedupeFindings(+ findings: ReadonlyArray<AnswerQuoteSpanFinding>,+): ReadonlyArray<AnswerQuoteSpanFinding> {+ const seen = new Set<string>();+ const unique: AnswerQuoteSpanFinding[] = [];+ for (const finding of findings) {+ const key = findingLine(finding.span, finding.verdict);+ if (seen.has(key)) continue;+ seen.add(key);+ unique.push(finding);+ }+ return unique;+}++/**+ * The findings one annotation - and one enforce event - render: the+ * first {@link ANSWER_QUOTE_MAX_FINDINGS}, answer order kept. The header+ * and the enforce counters still state the true total.+ */+function listedFindings(+ findings: ReadonlyArray<AnswerQuoteSpanFinding>,+): ReadonlyArray<AnswerQuoteSpanFinding> {+ return findings.slice(0, ANSWER_QUOTE_MAX_FINDINGS);+}++/**+ * The annotation: exactly one line block listing the unverified spans+ * with their verdicts, duplicate-free, in answer order, under the+ * findings cap.+ */+function annotation(findings: ReadonlyArray<AnswerQuoteSpanFinding>): string {+ const listed = listedFindings(findings);+ const lines = [+ `Open Second Brain quote check: ${findings.length} quoted span(s) were not found in the notes this turn had:`,+ ...listed.map((finding) => findingLine(finding.span, finding.verdict)),+ ];+ if (listed.length < findings.length) {+ lines.push(`... and ${findings.length - listed.length} more unverified span(s) not listed.`);+ }+ lines.push(+ "Advisory only; the answer is not blocked. Verify the quotes against the note, or reword.",+ );+ return lines.join("\n");+}++async function main(): Promise<void> {+ let payload;+ try {+ payload = asHookPayload(await readHookInput());+ } catch (err) {+ // An unparseable payload is a host fault: one audit line, the same+ // prefix as every other error arm, and never a block.+ process.stderr.write(`${AUDIT_PREFIX} ${err instanceof Error ? err.message : String(err)}\n`);+ return;+ }+ // Once per turn: the runtime already continued this turn on a Stop+ // hook's output, so re-annotating would loop.+ if (payload.stop_hook_active === true) return;+ const transcriptPath = payload.transcript_path;+ if (typeof transcriptPath !== "string" || transcriptPath.length === 0) return;+ // A transcript the host has not created yet is a fresh session, not an+ // error: silence, like every other empty-handed arm.+ if (!existsSync(transcriptPath)) return;+ const vault = resolveVault();+ if (vault === null) return;+ const sessionId = isRealSessionId(payload.session_id) ? payload.session_id : null;+ const started = Date.now();+ const deadline = started + ANSWER_QUOTE_BUDGET_MS;+ const now = started;++ const configPath = brainConfigPath(vault);+ const modes: Readonly<Record<AnswerQuoteCheckPhase, AnswerQuoteCheckMode>> = {+ recall: resolveAnswerQuoteCheckRecall(configPath),+ active: resolveAnswerQuoteCheckActive(configPath),+ subagent: resolveAnswerQuoteCheckSubagent(configPath),+ };+ // Every phase `off` reports nothing and enforces nothing, so the run+ // pays no ledger read at all: the injection ledgers - whose member+ // strings are prose that gets path-scanned - stay unopened.+ if (ANSWER_QUOTE_CHECK_PHASES.every((phase) => modes[phase] === "off")) return;+ const ledgerNotes: Readonly<Record<AnswerQuoteCheckPhase, ReturnType<typeof ledgerCandidates>>> =+ {+ recall: ledgerCandidates(vault, sessionId, "recall", now),+ active: ledgerCandidates(vault, sessionId, "active", now),+ subagent: ledgerCandidates(vault, sessionId, "subagent", now),+ };+ // A phase contributes evidence when its injection happened (recall's+ // gate is the recall-inject flag; active and subagent have a live+ // ledger of their own); its MODE decides only whether a finding the+ // phase's evidence decided is reported - and enforced. Building the+ // pool from every injected ledger keeps a phase switched to `off` from+ // turning its delivered notes into false `[not-in-note]` findings for+ // spans another phase still checks.+ const gates: Readonly<Record<AnswerQuoteCheckPhase, boolean>> = {+ recall: resolveRecallInjectEnabled(),+ active: ledgerNotes.active.length > 0,+ subagent: ledgerNotes.subagent.length > 0,+ };+ const running = ANSWER_QUOTE_CHECK_PHASES.filter(+ (phase) => gates[phase] && modes[phase] !== "off",+ );+ if (running.length === 0) return;+ const candidates = mergeCandidateViews(+ ANSWER_QUOTE_CHECK_PHASES.filter((phase) => gates[phase]).map((phase) => ledgerNotes[phase]),+ );++ const messages = lastAssistantMessages(transcriptPath);+ const findings: Array<AnswerQuoteSpanFinding> = [];+ let checked = 0;+ let enforceable = 0;+ outer: for (const [messageIndex, message] of messages.entries()) {+ // Before the scans of this message, not only before its spans: the+ // span and path scans themselves cost the budget they precede.+ if (Date.now() > deadline) break outer;+ const scan = findQuoteSpans(message);+ if (scan.spans.length === 0) continue;+ const marks = citationMarks(message);+ for (const span of scan.spans) {+ if (Date.now() > deadline) break outer;+ checked++;+ const quoted: QuotedSpan = {+ message: messageIndex,+ inner: span.inner,+ open: span.open,+ close: span.close,+ };+ const outcome = checkSpan(quoted, marks, candidates, vault, deadline);+ if (outcome.verdict !== ANSWER_QUOTE_VERDICT.verified) {+ // Attribution: the phases whose candidates decided this miss. A+ // miss decided only by a phase switched to `off` is not this+ // turn's report - the operator disabled that phase's findings,+ // and its delivered notes are still evidence for the phases+ // that remain on. A span with an explicit citation mark (or no+ // candidate at all) is not ledger-attributable: every running+ // phase's check covers it, exactly as before the attribution.+ const deciding = outcome.decidingPhases.length > 0 ? outcome.decidingPhases : running;+ const contributing = deciding.filter((phase) => modes[phase] !== "off");+ if (contributing.length === 0) continue;+ if (contributing.some((phase) => modes[phase] === "enforce")) enforceable++;+ findings.push({ span: outcome.preview, verdict: outcome.verdict });+ }+ }+ }+ const unique = dedupeFindings(findings);+ if (unique.length === 0) return;++ if (enforceable > 0) {+ // Exactly one Brain-log event per turn, best-effort: a failed append+ // names itself on the audit line and the annotation still goes out.+ // The findings ride the same capped, flattened lines the annotation+ // renders; the counter states the true total of the enforceable+ // findings - the ones a running `enforce` phase's evidence decided.+ try {+ appendLogEvent(vault, {+ timestamp: isoSecond(new Date()),+ // The `note` kind is the Brain log's designated audit-line home;+ // the pinned `session-lifecycle` shape belongs to the lifecycle+ // capture and is not this event's shape to borrow.+ eventType: BRAIN_LOG_EVENT_KIND.note,+ agent: resolveAgentName(),+ body: {+ hook: "answer-quote-check",+ phases: running.join(","),+ checked: String(checked),+ unverified: String(enforceable),+ findings: listedFindings(unique).map((finding) =>+ findingLine(finding.span, finding.verdict),+ ),+ },+ });+ } catch (err) {+ process.stderr.write(`${AUDIT_PREFIX} ${err instanceof Error ? err.message : String(err)}\n`);+ }+ }++ process.stdout.write(+ `${JSON.stringify({+ hookSpecificOutput: { hookEventName: "Stop", additionalContext: annotation(unique) },+ })}\n`,+ );+}++// Run only as the hook process itself (the `o2b-hook` shim execs this+// file), not when the module is imported for its constants in tests.+if (import.meta.main) {+ main().catch((err: unknown) => {+ // Never deadlock on a hook crash: one stderr audit line, exit 0.+ process.stderr.write(`${AUDIT_PREFIX} ${err instanceof Error ? err.message : String(err)}\n`);+ });+}diff --git a/hooks/hooks.json b/hooks/hooks.jsonindex 03d856a4..992f1b08 100644--- a/hooks/hooks.json+++ b/hooks/hooks.json@@ -125,6 +125,12 @@"timeout": 10,"statusMessage": "OSB: checking stop log guardrail"},+ {+ "type": "command",+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" answer-quote-check; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook answer-quote-check; exit 0",+ "timeout": 10,+ "statusMessage": "OSB: verifying quoted spans against this turn's notes"+ },{"type": "command","command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" hygiene-digest; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook hygiene-digest; exit 0",diff --git a/hooks/lib/injection-ledger.ts b/hooks/lib/injection-ledger.tsindex 5d33260d..025173f4 100644--- a/hooks/lib/injection-ledger.ts+++ b/hooks/lib/injection-ledger.ts@@ -11,7 +11,10 @@* - {@link LEDGER_KEY_ACTIVE}: vault paths the SessionStart digest emitted.* - {@link LEDGER_KEY_REGROUND}: digest parts 2..n plus a delivery cursor.* - {@link LEDGER_KEY_SUBAGENT_INJECT}: sub-agent ids the PostToolUse- * carrier already delivered the standing rules to.+ * carrier already delivered the standing rules to, plus the+ * vault-relative note paths the delivered payload was built from (the+ * evidence an answer-time quote check may verify that sub-agent's+ * quoted spans against).** Every entry carries a {@link LEDGER_TTL_MS} expiry refreshed on each write.* Readers degrade to "empty" on any failure and never throw; writers return@@ -46,6 +49,15 @@ export const RECALL_SET_MAX = 2000;*/export const SUBAGENT_SET_MAX = 200;+/**+ * Ceiling on the delivered-evidence path set recorded beside the ids: one+ * delivery names a handful of note files, but a session that spawns many+ * sub-agents across a large vault must not grow the scope file that every+ * lock-free reader re-parses. Past the cap the oldest paths drop first,+ * like the ids beside them.+ */+export const SUBAGENT_PATHS_MAX = 200;+/*** True only for a string session id with at least one ASCII alphanumeric, the* same floor `resolveSessionScope` needs; anything less would collapse to the@@ -62,6 +74,19 @@ function stringList(value: unknown): string[] {return value.filter((item): item is string => typeof item === "string");}+/** Read one ledger key's raw array field; empty when absent or expired. */+function readRawList(+ vault: string,+ sessionId: string,+ key: string,+ field: string,+ nowMs: number,+): unknown[] {+ const stamp = readHookStamp(vault, sessionId, key, nowMs);+ const value = stamp?.data?.[field];+ return Array.isArray(value) ? value : [];+}+/** Read one ledger key's string-array field as a set; empty when absent or expired. */function readStringSet(vault: string,@@ -123,15 +148,67 @@ export function readSubagentDeliveredIds(}/**- * Merge `agentId` into the session's delivered set and refresh its expiry.- * An expired set is dropped rather than merged. Past {@link SUBAGENT_SET_MAX}- * ids the oldest drop first (a re-delivered id keeps its first position, which- * is enough for a dedupe hint). Returns `false` on any failure.+ * Vault-relative note paths the delivered carrier payloads were built from+ * this session (answer-trust wave): the evidence a sub-agent turn can be+ * quoted against. A truncated delivery - the payload carried only a+ * prefix of the note - records `{ path, truncated: true }`, because the+ * evidence is the prefix, not the file; a plain string names a whole-note+ * delivery. Rows recorded before the paths field existed - and deliveries+ * whose payload carried no note content - read as an empty list, so an+ * old ledger row is silence for the quote check, never an error.+ */+export type SubagentEvidencePath = string | { readonly path: string; readonly truncated: boolean };++function evidencePathEntry(value: unknown): SubagentEvidencePath | null {+ if (typeof value === "string" && value.length > 0) return value;+ if (typeof value === "object" && value !== null && "path" in value) {+ const record = value as { path: unknown; truncated?: unknown };+ if (typeof record.path === "string" && record.path.length > 0) {+ return { path: record.path, truncated: record.truncated === true };+ }+ }+ return null;+}++export function readSubagentDeliveredPaths(+ vault: string,+ sessionId: string,+ nowMs: number = Date.now(),+): ReadonlyArray<SubagentEvidencePath> {+ const raw = readRawList(vault, sessionId, LEDGER_KEY_SUBAGENT_INJECT, "paths", nowMs);+ const byPath = new Map<string, SubagentEvidencePath>();+ for (const item of raw) {+ const entry = evidencePathEntry(item);+ if (entry === null) continue;+ const path = typeof entry === "string" ? entry : entry.path;+ const prior = byPath.get(path);+ // Truncation is sticky: once a delivery named a clipped prefix of a+ // note, later whole-string rows cannot widen the evidence back.+ if (prior === undefined) {+ byPath.set(path, entry);+ } else if (typeof entry === "object" && entry.truncated) {+ byPath.set(path, entry);+ }+ }+ return [...byPath.values()];+}++/**+ * Merge `agentId` - and the `evidencePaths` the delivered payload was+ * built from, when the carrier names any - into the session's delivered+ * record and refresh its expiry. Paths are a second list beside the ids+ * and merge the same way: a re-delivery without paths keeps what earlier+ * deliveries merged, so evidence already handed to this session's+ * sub-agents stays named. An expired record is dropped rather than+ * merged. Past {@link SUBAGENT_SET_MAX} ids and {@link SUBAGENT_PATHS_MAX}+ * paths the oldest drop first (a re-delivered id keeps its first position,+ * which is enough for a dedupe hint). Returns `false` on any failure.*/export function recordSubagentDeliveredId(vault: string,sessionId: string,agentId: string,+ evidencePaths: ReadonlyArray<SubagentEvidencePath> = [],nowMs: number = Date.now(),): boolean {const outcome = updateHookState(@@ -139,11 +216,34 @@ export function recordSubagentDeliveredId(sessionId,(state, now) => {const prior = liveData(state[LEDGER_KEY_SUBAGENT_INJECT], now);- const merged = new Set([...stringList(prior?.["ids"]), agentId]);- const all = [...merged];+ const mergedIds = new Set([...stringList(prior?.["ids"]), agentId]);+ const allIds = [...mergedIds];+ // Path-keyed merge; a truncated entry (the payload carried only a+ // prefix) is sticky over a plain whole-note row of the same path.+ const merged = new Map<string, SubagentEvidencePath>();+ for (const item of [+ ...(Array.isArray(prior?.["paths"]) ? prior["paths"] : []),+ ...evidencePaths,+ ]) {+ const entry = evidencePathEntry(item);+ if (entry === null) continue;+ const path = typeof entry === "string" ? entry : entry.path;+ const priorEntry = merged.get(path);+ if (priorEntry === undefined) {+ merged.set(path, entry);+ } else if (typeof entry === "object" && entry.truncated) {+ merged.set(path, entry);+ }+ }+ const allPaths = [...merged.values()];state[LEDGER_KEY_SUBAGENT_INJECT] = {expiresAt: now + LEDGER_TTL_MS,- data: { ids: all.slice(Math.max(0, all.length - SUBAGENT_SET_MAX)) },+ data: {+ ids: allIds.slice(Math.max(0, allIds.length - SUBAGENT_SET_MAX)),+ ...(allPaths.length > 0+ ? { paths: allPaths.slice(Math.max(0, allPaths.length - SUBAGENT_PATHS_MAX)) }+ : {}),+ },};return { state, result: true };},diff --git a/hooks/subagent-inject.ts b/hooks/subagent-inject.tsindex b812af38..ed0ffbaf 100644--- a/hooks/subagent-inject.ts+++ b/hooks/subagent-inject.ts@@ -58,10 +58,13 @@** The delivered agent ids live in the per-session hook-state ledger* (`osb.subagent_inject.delivered`, capped, 24 h TTL); the fallback- * consults it before emitting, the primary channel does not. The id is- * recorded AFTER the stdout write on both channels - lose-not-duplicate,- * like every carrier in this tree - so a crash between write and record- * re-delivers rather than losing the payload.+ * consults it before emitting, the primary channel does not. Each record+ * also names the vault-relative note paths the delivered payload was+ * built from, so the answer-time quote check (answer-trust wave) can+ * verify that sub-agent's quoted spans against the evidence it actually+ * had. The id is recorded AFTER the stdout write on both channels -+ * lose-not-duplicate, like every carrier in this tree - so a crash+ * between write and record re-delivers rather than losing the payload.** Silent on every empty-handed path, exit 0: no non-empty `agent_id`* (the main thread is served by active-inject), on PostToolUse a tool@@ -80,6 +83,7 @@*/import { writeSync } from "node:fs";+import { posix } from "node:path";import { asHookPayload, readHookInput } from "./lib/stdin.ts";import { isArtifactToolName } from "./lib/detect.ts";@@ -87,9 +91,12 @@ import {isRealSessionId,readSubagentDeliveredIds,recordSubagentDeliveredId,+ type SubagentEvidencePath,} from "./lib/injection-ledger.ts";import { renderStandingBlock } from "./lib/standing-block.ts";import {+ SOURCE_ACTIVE_BODY,+ SOURCE_LESSONS_BODY,assembleActiveContext,createInjectionMeter,joinBlocks,@@ -97,6 +104,15 @@ import {resolveInjectionLimits,scopedSectionCap,} from "./lib/active-context.ts";+import {+ BRAIN_ACTIVE_FILE,+ BRAIN_LESSONS_FILE,+ BRAIN_ROOT_REL,+ BRAIN_STANDING_RULES_FILE,+} from "../src/core/brain/path-constants.ts";+import { readScopedRules } from "../src/core/brain/scoped-rules.ts";+import { resolveHostScope, resolveProjectScope } from "../src/core/brain/scope-identity.ts";+import { readStandingRules } from "../src/core/brain/standing-rules.ts";import { resolveVault } from "../src/core/config.ts";/**@@ -139,17 +155,89 @@ function subagentInjectOutput(event: CarrierEvent, block: string): SubagentInjecreturn { hookSpecificOutput: { hookEventName: event, additionalContext: block } };}+/**+ * The carrier's payload plus the note evidence it was built from. The+ * evidence paths feed the delivery ledger so the answer-time quote check+ * can verify this sub-agent's quoted spans against the notes the payload+ * actually carried (answer-trust wave).+ */+interface CarrierPayload {+ readonly block: string;+ /**+ * Vault-relative note paths whose content the payload carries. A+ * truncated delivery - the payload carries only the note's prefix -+ * records `{ path, truncated: true }`, so the quote check judges+ * spans against the delivered prefix, never the whole file.+ */+ readonly evidencePaths: ReadonlyArray<SubagentEvidencePath>;+}++/**+ * The vault-relative standing-rules path, when a real read fed the+ * block. An absent or empty file renders no block at all, and a read+ * that FAILED renders the explicit failure block - the payload then+ * carries a notice ABOUT the file, not the file's content, so neither+ * case is delivered evidence. A read that hit the character cap+ * delivered a prefix: the entry is marked truncated so a quote of the+ * undelivered tail reads `source-truncated`, never silence.+ */+function standingEvidencePaths(+ vault: string,+ maxChars: number,+): ReadonlyArray<SubagentEvidencePath> {+ try {+ const rules = readStandingRules(vault, { maxChars });+ if (rules === null) return [];+ const path = posix.join(BRAIN_ROOT_REL, BRAIN_STANDING_RULES_FILE);+ return rules.truncated ? [{ path, truncated: true }] : [path];+ } catch {+ return [];+ }+}++/**+ * The vault-relative scoped-rule file paths this session's scope+ * matched. The identity mirrors `renderScopedBlock`'s so the reported+ * paths and the delivered block cannot disagree; the harness axis is+ * always null on this surface (both injection lanes are shared by Claude+ * Code and Codex through one `o2b-hook` shim and have no harness signal).+ */+function scopedEvidencePaths(+ vault: string,+ workspaceDir: string,+ maxChars: number,+): ReadonlyArray<string> {+ try {+ let host: { readonly host: string | null; readonly unreadable: boolean };+ try {+ host = resolveHostScope(undefined);+ } catch {+ host = { host: null, unreadable: true };+ }+ return readScopedRules(+ vault,+ { project: resolveProjectScope(workspaceDir, vault), harness: null, host: host.host },+ { maxChars, hostUnreadable: host.unreadable },+ ).files.map((file) => file.path);+ } catch {+ return [];+ }+}+/*** Compose the carrier's payload: the same three lanes, joined the same* way, as the session-start preamble. The meter exists because the- * assembly records its sub-bodies there; the carrier never reads it- * back - it feeds the session-start receipt, not a carrier emission.+ * assembly records its sub-bodies there - the memory note paths are read+ * back off it (a rendered `Brain/active.md` or `Brain/lessons.md` body is+ * delivered evidence), while the rules lanes report their consumed paths+ * directly. Runtime notices are generated state, not a note.*/-function composeCarrierPayload(vault: string, workspaceDir: string): string {+function composeCarrierPayload(vault: string, workspaceDir: string): CarrierPayload {const limits = resolveInjectionLimits(vault);const meter = createInjectionMeter(limits.injectBudgetChars);const standingBlock = renderStandingBlock(vault, limits.standingRulesMaxChars, meter);- const scopedBlock = renderScopedBlock(vault, workspaceDir, scopedSectionCap(limits), meter);+ const sectionCap = scopedSectionCap(limits);+ const scopedBlock = renderScopedBlock(vault, workspaceDir, sectionCap, meter);const memoryBudget = Math.max(0, limits.injectBudgetChars - scopedBlock.length);// No last-good cache on this surface: a genuine read error inside the// assembly degrades the memory lane to empty rather than emitting a@@ -160,7 +248,16 @@ function composeCarrierPayload(vault: string, workspaceDir: string): string {} catch {memoryContext = "";}- return joinBlocks([standingBlock, scopedBlock, memoryContext]);+ const emitted = (name: string): boolean => meter.sources.some((s) => s.name === name);+ return {+ block: joinBlocks([standingBlock, scopedBlock, memoryContext]),+ evidencePaths: [+ ...standingEvidencePaths(vault, limits.standingRulesMaxChars),+ ...scopedEvidencePaths(vault, workspaceDir, sectionCap),+ ...(emitted(SOURCE_ACTIVE_BODY) ? [posix.join(BRAIN_ROOT_REL, BRAIN_ACTIVE_FILE)] : []),+ ...(emitted(SOURCE_LESSONS_BODY) ? [posix.join(BRAIN_ROOT_REL, BRAIN_LESSONS_FILE)] : []),+ ],+ };}async function main(): Promise<void> {@@ -220,10 +317,10 @@ async function main(): Promise<void> {// resolves the same field the same way).const workspaceDir =typeof payload.cwd === "string" && payload.cwd.length > 0 ? payload.cwd : process.cwd();- const block = composeCarrierPayload(vault, workspaceDir);+ const carrier = composeCarrierPayload(vault, workspaceDir);// Silent only when the ENTIRE payload is empty: an absent rules file is// no longer silence on a vault whose operator has learned preferences.- if (block.length === 0) return;+ if (carrier.block.length === 0) return;// One blocking write to fd 1, not process.stdout.write: a write error// must surface HERE, at the emit. Bun and Node deliver stdout errors@@ -233,13 +330,16 @@ async function main(): Promise<void> {// instead, the id is never recorded, and the next carrier event for// this sub-agent re-delivers - the lose-not-duplicate order made real,// not just ordered.- writeSync(1, `${JSON.stringify(subagentInjectOutput(event, block))}\n`);+ writeSync(1, `${JSON.stringify(subagentInjectOutput(event, carrier.block))}\n`);// Recorded after stdout on both channels: a crash or a failed state// write in between re-delivers the payload on the next carrier event,// and on the primary channel the record is what keeps the PostToolUse- // fallback silent once this sub-agent's payload has landed.- recordSubagentDeliveredId(vault, payload.session_id, agentId);+ // fallback silent once this sub-agent's payload has landed. The record+ // names the note paths the payload was built from, so the answer-time+ // quote check can verify this sub-agent's quoted spans against the+ // evidence it actually had.+ recordSubagentDeliveredId(vault, payload.session_id, agentId, carrier.evidencePaths);}main().catch(() => {diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 6dacf049..24f80613 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.80.0",+ "version": "1.81.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex 5f0345e9..ad9cd916 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -1935,6 +1935,276 @@ var init_pointer = __esm(() => {init_fs_utils();});+// src/core/brain/yaml-parse.ts+function parseBrainYaml(text) {+ const lines = splitLines(text);+ const out = {};+ let i = 0;+ while (i < lines.length) {+ const line = lines[i];+ if (line.indent !== 0) {+ throw new Error(`line ${line.lineNumber}: unexpected indentation at top level`);+ }+ const kv = splitKeyValue(line);+ if (kv.value === "") {+ const child = {};+ i++;+ const blockIndent = detectBlockIndent(lines, i);+ while (i < lines.length && lines[i].indent >= blockIndent && blockIndent > 0) {+ const inner = lines[i];+ if (inner.indent !== blockIndent) {+ throw new Error(`line ${inner.lineNumber}: inconsistent indentation in block '${kv.key}' ` + `(expected ${blockIndent} spaces, got ${inner.indent})`);+ }+ const innerKv = splitKeyValue(inner);+ if (innerKv.value === "") {+ i++;+ const listIndent = detectBlockIndent(lines, i);+ if (listIndent <= blockIndent) {+ if (innerKv.key in child) {+ throw new Error(`line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`);+ }+ child[innerKv.key] = [];+ continue;+ }+ const items = [];+ while (i < lines.length && lines[i].indent >= listIndent) {+ const listLine = lines[i];+ if (listLine.indent !== listIndent) {+ throw new Error(`line ${listLine.lineNumber}: inconsistent indentation in list '${innerKv.key}' ` + `(expected ${listIndent} spaces, got ${listLine.indent})`);+ }+ if (!listLine.content.startsWith("- ") && listLine.content !== "-") {+ if (/^[A-Za-z_][A-Za-z0-9_-]*\s*:/.test(listLine.content)) {+ throw new Error(`line ${listLine.lineNumber}: nested blocks deeper than one level are not supported`);+ }+ throw new Error(`line ${listLine.lineNumber}: expected list item starting with '- ' ` + `in '${kv.key}.${innerKv.key}'`);+ }+ const itemText = listLine.content.startsWith("- ") ? listLine.content.slice(2).trim() : "";+ const item = parseScalar(itemText, listLine.lineNumber);+ if (Array.isArray(item)) {+ throw new Error(`line ${listLine.lineNumber}: nested inline arrays are not supported`);+ }+ items.push(item);+ i++;+ }+ if (innerKv.key in child) {+ throw new Error(`line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`);+ }+ child[innerKv.key] = items;+ continue;+ }+ if (innerKv.key in child) {+ throw new Error(`line ${inner.lineNumber}: duplicate key '${innerKv.key}' in block '${kv.key}'`);+ }+ child[innerKv.key] = parseScalar(innerKv.value, inner.lineNumber);+ i++;+ }+ if (kv.key in out) {+ throw new Error(`duplicate top-level key '${kv.key}'`);+ }+ out[kv.key] = child;+ continue;+ }+ if (kv.key in out) {+ throw new Error(`duplicate top-level key '${kv.key}'`);+ }+ out[kv.key] = parseScalar(kv.value, line.lineNumber);+ i++;+ }+ return out;+}+function splitLines(text) {+ const out = [];+ let lineNumber = 0;+ for (const raw of text.split(/\r?\n/)) {+ lineNumber++;+ const stripped = raw.replace(/\s+$/, "");+ if (stripped.trim() === "")+ continue;+ if (stripped.trimStart().startsWith("#"))+ continue;+ let content = stripped;+ if (!/['"]/.test(stripped)) {+ const hashIdx = stripped.indexOf(" #");+ if (hashIdx >= 0)+ content = stripped.slice(0, hashIdx).replace(/\s+$/, "");+ }+ const indent = content.length - content.trimStart().length;+ out.push({+ raw,+ indent,+ content: content.slice(indent),+ lineNumber+ });+ }+ return out;+}+function splitKeyValue(line) {+ const idx = line.content.indexOf(":");+ if (idx <= 0) {+ throw new Error(`line ${line.lineNumber}: expected 'key: value', got: ${JSON.stringify(line.raw)}`);+ }+ const key = line.content.slice(0, idx).trim();+ if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key)) {+ throw new Error(`line ${line.lineNumber}: invalid key name: ${JSON.stringify(key)}`);+ }+ if (key === "__proto__" || key === "constructor" || key === "prototype") {+ throw new Error(`line ${line.lineNumber}: reserved key name: ${JSON.stringify(key)}`);+ }+ const value = line.content.slice(idx + 1).trim();+ return { key, value };+}+function detectBlockIndent(lines, cursor) {+ if (cursor >= lines.length)+ return 0;+ const first = lines[cursor];+ if (first.indent === 0)+ return 0;+ return first.indent;+}+function parseScalar(text, lineNumber) {+ if (text.startsWith("[") && text.endsWith("]")) {+ return parseInlineArray(text.slice(1, -1), lineNumber);+ }+ if (text.length >= 2 && (text.startsWith('"') && text.endsWith('"') || text.startsWith("'") && text.endsWith("'"))) {+ return text.slice(1, -1);+ }+ if (text === "true")+ return true;+ if (text === "false")+ return false;+ if (text === "null" || text === "~")+ return null;+ if (/^-?\d+$/.test(text)) {+ const n = parseInt(text, 10);+ return n;+ }+ if (/^-?\d+\.\d+$/.test(text)) {+ const n = parseFloat(text);+ if (!Number.isFinite(n)) {+ throw new Error(`line ${lineNumber}: non-finite number: ${text}`);+ }+ return n;+ }+ return text;+}+function parseInlineArray(innerRaw, lineNumber) {+ const inner = innerRaw.trim();+ if (inner === "")+ return [];+ const out = [];+ let current = "";+ let inQuote = false;+ let quoteChar = "";+ for (let i = 0;i < inner.length; i++) {+ const ch = inner[i];+ if (inQuote) {+ current += ch;+ if (ch === quoteChar) {+ inQuote = false;+ quoteChar = "";+ }+ continue;+ }+ if (ch === '"' || ch === "'") {+ inQuote = true;+ quoteChar = ch;+ current += ch;+ continue;+ }+ if (ch === ",") {+ out.push(parseInlineArrayItem(current, lineNumber));+ current = "";+ continue;+ }+ current += ch;+ }+ if (inQuote) {+ throw new Error(`line ${lineNumber}: unterminated quoted string in inline array`);+ }+ out.push(parseInlineArrayItem(current, lineNumber));+ return out;+}+function parseInlineArrayItem(text, lineNumber) {+ const trimmed = text.trim();+ if (trimmed === "") {+ throw new Error(`line ${lineNumber}: empty item in inline array`);+ }+ const parsed = parseScalar(trimmed, lineNumber);+ if (Array.isArray(parsed)) {+ throw new Error(`line ${lineNumber}: nested inline arrays are not supported`);+ }+ return parsed;+}++// src/core/brain/policy/errors.ts+var BrainConfigError;+var init_errors = __esm(() => {+ BrainConfigError = class BrainConfigError extends Error {+ field;+ source;+ constructor(message, field, source) {+ super(field ? `${source ?? "<config>"}: ${field}: ${message}` : `${source ?? "<config>"}: ${message}`);+ this.name = "BrainConfigError";+ this.field = field;+ this.source = source;+ }+ };+});++// src/core/brain/path-constants.ts+import { posix } from "node:path";+var BRAIN_ROOT_REL = "Brain", BRAIN_INBOX_REL, BRAIN_PROCESSED_REL, BRAIN_ARCHIVED_SIGNALS_REL, BRAIN_PENDING_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL, BRAIN_SKILL_PROPOSALS_REL, BRAIN_SKILL_PROPOSALS_PENDING_REL, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, BRAIN_SKILL_PROPOSALS_REJECTED_REL, BRAIN_SKILL_ACCEPT_JOURNAL_REL, BRAIN_PROCEDURES_REL, BRAIN_PROCEDURAL_MEMORY_REL, BRAIN_ATTENTION_REL, BRAIN_OBLIGATIONS_REL, BRAIN_THESES_REL, BRAIN_DECISIONS_REL, BRAIN_GAP_TASKS_REL, BRAIN_TENSIONS_REL, BRAIN_LOG_DIR = "log", BRAIN_LOG_REL, BRAIN_CAPTURES_REL, BRAIN_CAPTURES_PROCESSED_REL, BRAIN_ENTITIES_REL, BRAIN_STATE_REL, BRAIN_INTERNAL_STATE_DIR = ".state", BRAIN_INTERNAL_STATE_REL, BRAIN_BASES_REL, BRAIN_SOURCES_REL, BRAIN_REPORTS_REL, BRAIN_DISTILLATIONS_REL, BRAIN_SNAPSHOTS_DIR = ".snapshots", BRAIN_SNAPSHOTS_REL, BRAIN_ARTIFACTS_DIR = ".artifacts", BRAIN_ARTIFACTS_REL, BRAIN_ARCHIVES_DIR = ".archives", BRAIN_ARCHIVES_REL, BRAIN_PAYLOADS_DIR = ".payloads", BRAIN_PAYLOADS_REL, BRAIN_WRITE_IMAGES_DIR = "write-images", BRAIN_WRITE_IMAGES_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, JSONL_LEDGER_EXT = "jsonl", BRAIN_CONFIG_FILE = "_brain.yaml", BRAIN_ACTIVE_FILE = "active.md", BRAIN_LESSONS_FILE = "lessons.md", BRAIN_COMPILED_DIGEST_RELS, BRAIN_INDEX_FILE = "_INDEX.md", BRAIN_INDEX_REL, BRAIN_PAGE_LANES_REL;+var init_path_constants = __esm(() => {+ BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");+ BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");+ BRAIN_ARCHIVED_SIGNALS_REL = posix.join(BRAIN_INBOX_REL, "archived");+ BRAIN_PENDING_REL = posix.join(BRAIN_ROOT_REL, "pending");+ BRAIN_PREFERENCES_REL = posix.join(BRAIN_ROOT_REL, "preferences");+ BRAIN_RETIRED_REL = posix.join(BRAIN_ROOT_REL, "retired");+ BRAIN_SKILL_PROPOSALS_REL = posix.join(BRAIN_ROOT_REL, "skill-proposals");+ BRAIN_SKILL_PROPOSALS_PENDING_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "pending");+ BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");+ BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");+ BRAIN_SKILL_ACCEPT_JOURNAL_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accept-journal");+ BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");+ BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");+ BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");+ BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");+ BRAIN_THESES_REL = posix.join(BRAIN_ROOT_REL, "theses");+ BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");+ BRAIN_GAP_TASKS_REL = posix.join(BRAIN_ROOT_REL, "gap-tasks");+ BRAIN_TENSIONS_REL = posix.join(BRAIN_ROOT_REL, "tensions");+ BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, BRAIN_LOG_DIR);+ BRAIN_CAPTURES_REL = posix.join(BRAIN_ROOT_REL, "captures");+ BRAIN_CAPTURES_PROCESSED_REL = posix.join(BRAIN_CAPTURES_REL, "processed");+ BRAIN_ENTITIES_REL = posix.join(BRAIN_ROOT_REL, "entities");+ BRAIN_STATE_REL = posix.join(BRAIN_ROOT_REL, "state");+ BRAIN_INTERNAL_STATE_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INTERNAL_STATE_DIR);+ BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");+ BRAIN_SOURCES_REL = posix.join(BRAIN_ROOT_REL, "sources");+ BRAIN_REPORTS_REL = posix.join(BRAIN_ROOT_REL, "reports");+ BRAIN_DISTILLATIONS_REL = posix.join(BRAIN_ROOT_REL, "distillations");+ BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_SNAPSHOTS_DIR);+ BRAIN_ARTIFACTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARTIFACTS_DIR);+ BRAIN_ARCHIVES_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARCHIVES_DIR);+ BRAIN_PAYLOADS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_PAYLOADS_DIR);+ BRAIN_WRITE_IMAGES_REL = posix.join(BRAIN_INTERNAL_STATE_REL, BRAIN_WRITE_IMAGES_DIR);+ BRAIN_SNAPSHOT_EXCLUDED_ENTRIES = Object.freeze([+ BRAIN_SNAPSHOTS_DIR,+ BRAIN_ARTIFACTS_DIR+ ]);+ BRAIN_COMPILED_DIGEST_RELS = Object.freeze([+ posix.join(BRAIN_ROOT_REL, BRAIN_ACTIVE_FILE),+ posix.join(BRAIN_ROOT_REL, BRAIN_LESSONS_FILE)+ ]);+ BRAIN_INDEX_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);+ BRAIN_PAGE_LANES_REL = Object.freeze([+ BRAIN_SOURCES_REL,+ BRAIN_REPORTS_REL,+ BRAIN_DISTILLATIONS_REL+ ]);+});+// src/core/brain/wikilink.tsvar init_wikilink = () => {};@@ -1956,6 +2226,8 @@ var init_format_wikilink = __esm(() => {// src/core/config.tsvar exports_config = {};__export(exports_config, {+ ANSWER_QUOTE_CHECK_MODES: () => ANSWER_QUOTE_CHECK_MODES,+ ANSWER_QUOTE_CHECK_PHASES: () => ANSWER_QUOTE_CHECK_PHASES,ConfigReadError: () => ConfigReadError,DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY: () => DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY,DECISION_RECALL_MAX_PER_SESSION_ENV_KEY: () => DECISION_RECALL_MAX_PER_SESSION_ENV_KEY,@@ -1979,11 +2251,15 @@ __export(exports_config, {defaultConfigPath: () => defaultConfigPath,discoverConfig: () => discoverConfig,installNamedSecretResolver: () => installNamedSecretResolver,+ isAnswerQuoteCheckMode: () => isAnswerQuoteCheckMode,isConfiguredAgentName: () => isConfiguredAgentName,isValidDeviceId: () => isValidDeviceId,isValidInstallationSecret: () => isValidInstallationSecret,parseSimpleYaml: () => parseSimpleYaml,resolveAgentName: () => resolveAgentName,+ resolveAnswerQuoteCheckActive: () => resolveAnswerQuoteCheckActive,+ resolveAnswerQuoteCheckRecall: () => resolveAnswerQuoteCheckRecall,+ resolveAnswerQuoteCheckSubagent: () => resolveAnswerQuoteCheckSubagent,resolveBenchJudgeCmd: () => resolveBenchJudgeCmd,resolveContextPackOutcomeEnabled: () => resolveContextPackOutcomeEnabled,resolveDecisionRecallMaxPerSession: () => resolveDecisionRecallMaxPerSession,@@ -2436,6 +2712,76 @@ function resolveContextPackOutcomeEnabled(configPath) {function resolveRecallInjectEnabled(configPath) {return resolveConfigFlag("OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED", "recall_inject_enabled", configPath);}+function isAnswerQuoteCheckMode(value) {+ return typeof value === "string" && ANSWER_QUOTE_CHECK_MODES.includes(value);+}+function readQuoteCheckBlock(path) {+ let stat;+ try {+ const probed = statSync3(path, { throwIfNoEntry: false });+ if (probed === undefined)+ return null;+ stat = probed;+ } catch (err) {+ throw new BrainConfigError(`failed to stat: ${err.message}`, QUOTE_CHECK_BLOCK, path);+ }+ if (!stat.isFile()) {+ throw new BrainConfigError("path exists but is not a regular file; its settings are not in force and are not read as absent", QUOTE_CHECK_BLOCK, path);+ }+ let parsed;+ try {+ parsed = parseBrainYaml(new TextDecoder("utf-8", { fatal: true }).decode(readFileSync4(path)));+ } catch (err) {+ throw new BrainConfigError(`failed to parse: ${err.message}`, QUOTE_CHECK_BLOCK, path);+ }+ const block = parsed[QUOTE_CHECK_BLOCK];+ if (block === undefined)+ return null;+ if (typeof block !== "object" || block === null || Array.isArray(block)) {+ throw new BrainConfigError(`expected a block of per-phase modes, got ${Array.isArray(block) ? "an array" : typeof block}`, QUOTE_CHECK_BLOCK, path);+ }+ return block;+}+function warnUnknownQuoteCheckKeys(path, block) {+ for (const key of Object.keys(block)) {+ if (ANSWER_QUOTE_CHECK_PHASES.includes(key))+ continue;+ const stamp = `${path}\x00${key}`;+ if (quoteCheckWarnedUnknownKeys.has(stamp))+ continue;+ quoteCheckWarnedUnknownKeys.add(stamp);+ process.stderr.write(`${QUOTE_CHECK_BLOCK}.${key}: unknown field ignored (forward-compat)+`);+ }+}+function resolveAnswerQuoteCheckPhase(phase, path) {+ if (path === null)+ return QUOTE_CHECK_DEFAULT;+ const block = readQuoteCheckBlock(path);+ if (block === null)+ return QUOTE_CHECK_DEFAULT;+ warnUnknownQuoteCheckKeys(path, block);+ const raw = block[phase];+ if (raw === undefined)+ return QUOTE_CHECK_DEFAULT;+ if (!isAnswerQuoteCheckMode(raw)) {+ throw new BrainConfigError(`unsupported value ${JSON.stringify(raw)}; expected one of ${ANSWER_QUOTE_CHECK_MODES.join(", ")}`, `${QUOTE_CHECK_BLOCK}.${phase}`, path);+ }+ return raw;+}+function defaultAnswerQuoteCheckConfigPath() {+ const vault = resolveVault();+ return vault === null ? null : join5(vault, BRAIN_ROOT_REL, BRAIN_CONFIG_FILE);+}+function resolveAnswerQuoteCheckRecall(configPath) {+ return resolveAnswerQuoteCheckPhase("recall", configPath ?? defaultAnswerQuoteCheckConfigPath());+}+function resolveAnswerQuoteCheckActive(configPath) {+ return resolveAnswerQuoteCheckPhase("active", configPath ?? defaultAnswerQuoteCheckConfigPath());+}+function resolveAnswerQuoteCheckSubagent(configPath) {+ return resolveAnswerQuoteCheckPhase("subagent", configPath ?? defaultAnswerQuoteCheckConfigPath());+}function parseBounded(raw, min, max, integer) {const value = Number(raw);if (!Number.isFinite(value) || integer && !Number.isInteger(value))@@ -2592,13 +2938,15 @@ function expandTilde(p, platform = process.platform, home = homedir2()) {return join5(home, p.slice(2));return p;}-var import_proper_lockfile2, namedSecretResolver, CONFIG_VALUE_REJECTED_CHARS, UNSUPPORTED_CONFIG_PLATFORMS, UnsupportedPlatformError, ConfigReadError, UNCONFIGURED_AGENT_NAME = "agent", SHARED_NAMESPACE_KEY = "shared_namespace", DEVICE_ID_RE, INSTALLATION_SECRET_CONFIG_KEY = "installation_secret", INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET", INSTALLATION_SECRET_RE, VAULT_STORE_REF_PREFIX = "vault://", VAULT_STORE_REF_HEX_LEN = 32, DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY = "decision_recall.max_per_session", DECISION_RECALL_MAX_PER_SESSION_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION", DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min_spacing_turns", DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS", RECALL_INJECT_CAP_SPECS, REGROUND_PART_CHARS_DEFAULT = 9000, MAINTENANCE_EMBEDDINGS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_EMBEDDINGS", MAINTENANCE_EMBEDDINGS_CONFIG_KEY = "maintenance_embeddings", MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS", MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks", PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED", PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled", SESSION_CAPTURE_ROLES;+var import_proper_lockfile2, namedSecretResolver, CONFIG_VALUE_REJECTED_CHARS, UNSUPPORTED_CONFIG_PLATFORMS, UnsupportedPlatformError, ConfigReadError, UNCONFIGURED_AGENT_NAME = "agent", SHARED_NAMESPACE_KEY = "shared_namespace", DEVICE_ID_RE, INSTALLATION_SECRET_CONFIG_KEY = "installation_secret", INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET", INSTALLATION_SECRET_RE, VAULT_STORE_REF_PREFIX = "vault://", VAULT_STORE_REF_HEX_LEN = 32, DECISION_RECALL_MAX_PER_SESSION_CONFIG_KEY = "decision_recall.max_per_session", DECISION_RECALL_MAX_PER_SESSION_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MAX_PER_SESSION", DECISION_RECALL_MIN_SPACING_TURNS_CONFIG_KEY = "decision_recall.min_spacing_turns", DECISION_RECALL_MIN_SPACING_TURNS_ENV_KEY = "OPEN_SECOND_BRAIN_DECISION_RECALL_MIN_SPACING_TURNS", ANSWER_QUOTE_CHECK_MODES, QUOTE_CHECK_BLOCK = "quote_check", ANSWER_QUOTE_CHECK_PHASES, QUOTE_CHECK_DEFAULT = "shadow", quoteCheckWarnedUnknownKeys, RECALL_INJECT_CAP_SPECS, REGROUND_PART_CHARS_DEFAULT = 9000, MAINTENANCE_EMBEDDINGS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_EMBEDDINGS", MAINTENANCE_EMBEDDINGS_CONFIG_KEY = "maintenance_embeddings", MAINTENANCE_CUSTOM_TASKS_ENV = "OPEN_SECOND_BRAIN_MAINTENANCE_CUSTOM_TASKS", MAINTENANCE_CUSTOM_TASKS_CONFIG_KEY = "maintenance_custom_tasks", PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED", PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled", SESSION_CAPTURE_ROLES;var init_config = __esm(() => {init_fs_atomic();init_secret_ref();init_platform_dirs();init_profiles();init_pointer();+ init_errors();+ init_path_constants();init_format_wikilink();import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", `@@ -2622,6 +2970,9 @@ var init_config = __esm(() => {};DEVICE_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;INSTALLATION_SECRET_RE = /^[0-9a-f]{32}$/;+ ANSWER_QUOTE_CHECK_MODES = Object.freeze(["off", "shadow", "enforce"]);+ ANSWER_QUOTE_CHECK_PHASES = Object.freeze(["recall", "active", "subagent"]);+ quoteCheckWarnedUnknownKeys = new Set;RECALL_INJECT_CAP_SPECS = [{field: "maxNotes",@@ -3024,59 +3375,6 @@ ${SCAN_TRUNCATED_SENTINEL} [redactor scan window exceeded (> 1 MiB); the unscannVENDOR_TOKEN_TEST_RE = new RegExp(VENDOR_TOKEN_RE.source);});-// src/core/brain/path-constants.ts-import { posix } from "node:path";-var BRAIN_ROOT_REL = "Brain", BRAIN_INBOX_REL, BRAIN_PROCESSED_REL, BRAIN_ARCHIVED_SIGNALS_REL, BRAIN_PENDING_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL, BRAIN_SKILL_PROPOSALS_REL, BRAIN_SKILL_PROPOSALS_PENDING_REL, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, BRAIN_SKILL_PROPOSALS_REJECTED_REL, BRAIN_SKILL_ACCEPT_JOURNAL_REL, BRAIN_PROCEDURES_REL, BRAIN_PROCEDURAL_MEMORY_REL, BRAIN_ATTENTION_REL, BRAIN_OBLIGATIONS_REL, BRAIN_THESES_REL, BRAIN_DECISIONS_REL, BRAIN_GAP_TASKS_REL, BRAIN_TENSIONS_REL, BRAIN_LOG_DIR = "log", BRAIN_LOG_REL, BRAIN_CAPTURES_REL, BRAIN_CAPTURES_PROCESSED_REL, BRAIN_ENTITIES_REL, BRAIN_STATE_REL, BRAIN_INTERNAL_STATE_DIR = ".state", BRAIN_INTERNAL_STATE_REL, BRAIN_BASES_REL, BRAIN_SOURCES_REL, BRAIN_REPORTS_REL, BRAIN_DISTILLATIONS_REL, BRAIN_SNAPSHOTS_DIR = ".snapshots", BRAIN_SNAPSHOTS_REL, BRAIN_ARTIFACTS_DIR = ".artifacts", BRAIN_ARTIFACTS_REL, BRAIN_PAYLOADS_DIR = ".payloads", BRAIN_PAYLOADS_REL, BRAIN_WRITE_IMAGES_DIR = "write-images", BRAIN_WRITE_IMAGES_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, JSONL_LEDGER_EXT = "jsonl", BRAIN_ACTIVE_FILE = "active.md", BRAIN_LESSONS_FILE = "lessons.md", BRAIN_COMPILED_DIGEST_RELS, BRAIN_INDEX_FILE = "_INDEX.md", BRAIN_INDEX_REL, BRAIN_PAGE_LANES_REL;-var init_path_constants = __esm(() => {- BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");- BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");- BRAIN_ARCHIVED_SIGNALS_REL = posix.join(BRAIN_INBOX_REL, "archived");- BRAIN_PENDING_REL = posix.join(BRAIN_ROOT_REL, "pending");- BRAIN_PREFERENCES_REL = posix.join(BRAIN_ROOT_REL, "preferences");- BRAIN_RETIRED_REL = posix.join(BRAIN_ROOT_REL, "retired");- BRAIN_SKILL_PROPOSALS_REL = posix.join(BRAIN_ROOT_REL, "skill-proposals");- BRAIN_SKILL_PROPOSALS_PENDING_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "pending");- BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");- BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");- BRAIN_SKILL_ACCEPT_JOURNAL_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accept-journal");- BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");- BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");- BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");- BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");- BRAIN_THESES_REL = posix.join(BRAIN_ROOT_REL, "theses");- BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");- BRAIN_GAP_TASKS_REL = posix.join(BRAIN_ROOT_REL, "gap-tasks");- BRAIN_TENSIONS_REL = posix.join(BRAIN_ROOT_REL, "tensions");- BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, BRAIN_LOG_DIR);- BRAIN_CAPTURES_REL = posix.join(BRAIN_ROOT_REL, "captures");- BRAIN_CAPTURES_PROCESSED_REL = posix.join(BRAIN_CAPTURES_REL, "processed");- BRAIN_ENTITIES_REL = posix.join(BRAIN_ROOT_REL, "entities");- BRAIN_STATE_REL = posix.join(BRAIN_ROOT_REL, "state");- BRAIN_INTERNAL_STATE_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INTERNAL_STATE_DIR);- BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");- BRAIN_SOURCES_REL = posix.join(BRAIN_ROOT_REL, "sources");- BRAIN_REPORTS_REL = posix.join(BRAIN_ROOT_REL, "reports");- BRAIN_DISTILLATIONS_REL = posix.join(BRAIN_ROOT_REL, "distillations");- BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_SNAPSHOTS_DIR);- BRAIN_ARTIFACTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARTIFACTS_DIR);- BRAIN_PAYLOADS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_PAYLOADS_DIR);- BRAIN_WRITE_IMAGES_REL = posix.join(BRAIN_INTERNAL_STATE_REL, BRAIN_WRITE_IMAGES_DIR);- BRAIN_SNAPSHOT_EXCLUDED_ENTRIES = Object.freeze([- BRAIN_SNAPSHOTS_DIR,- BRAIN_ARTIFACTS_DIR- ]);- BRAIN_COMPILED_DIGEST_RELS = Object.freeze([- posix.join(BRAIN_ROOT_REL, BRAIN_ACTIVE_FILE),- posix.join(BRAIN_ROOT_REL, BRAIN_LESSONS_FILE)- ]);- BRAIN_INDEX_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);- BRAIN_PAGE_LANES_REL = Object.freeze([- BRAIN_SOURCES_REL,- BRAIN_REPORTS_REL,- BRAIN_DISTILLATIONS_REL- ]);-});-// src/core/brain/ledger-shards.tsfunction shardedFileName(base, shardId, ext) {if (shardId !== "" && !LEDGER_SHARD_ID_RE.test(shardId)) {diff --git a/package.json b/package.jsonindex 8b6291ba..7c9ce3be 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.80.0",+ "version": "1.81.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 147f101d..679885b6 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.80.0"+version: "1.81.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 1c658476..da528a10 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.80.0",+ "version": "1.81.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/codex/README.md b/plugins/codex/README.mdindex 1b6ebaf8..975be39c 100644--- a/plugins/codex/README.md+++ b/plugins/codex/README.md@@ -101,7 +101,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite- **Search.** Keyword search with an optional semantic lane, result explanations, recall profiles and compact cards: [search CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#search), [ranking](https://github.com/itechmeat/open-second-brain/blob/main/docs/how-it-works.md#full-text-search).- **Session recall.** Import agent transcripts already on disk and search them: [session logs](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#session-logs-this-machine-already-has-since-v1500).- **Hygiene.** `o2b brain hygiene scan` finds contested, duplicate, stale and unused memories; `apply` runs only the findings you pick: [maintenance](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#maintenance-and-operator-surfaces).-- **Claim ledger.** `o2b brain truth ingest` records an entity claim with an optional validity window (`--valid-from`/`--valid-until`; with the flags absent, a window on the source record's frontmatter is adopted and frozen at ingest), `truth events` recalls a windowed slice of the ledger, and `truth state` grounds an agent-stated claim with an anchoring verdict - committed, or reported back with reason codes: [entity truth CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#entity-truth-and-self-improving-dream-since-v0430).+- **Claim ledger.** `o2b brain truth ingest` records an entity claim with an optional validity window (`--valid-from`/`--valid-until`; with the flags absent, a window on the source record's frontmatter is adopted and frozen at ingest), `truth events` recalls a windowed slice of the ledger, and `truth state` grounds an agent-stated claim with an anchoring verdict - committed, or reported back with reason codes. `truth state` accepts an optional opaque `--sample-id` naming the context-pack sample the claim drew on, and claim reads report the receipt and outcome provenance behind it at the caller's reach - "receipt known, outcome unknown", never an invented verdict: [entity truth CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#entity-truth-and-self-improving-dream-since-v0430).- **Corrections.** `o2b brain lifecycle correct <target>` reports a correction's blast radius and retires the affected records - validity-closed by default, tombstoned with `--flatly-wrong`, dry run by default and `--apply` to write. A retired record that recall can still serve is served only beside its correction, never alone: [belief lifecycle CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#belief-lifecycle-and-decision-memory-since-v1330).- **Sharing and backup.** Knowledge packs export a chosen subset; `o2b brain bank-export` writes a one-file backup bundle: [knowledge packs](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#knowledge-packs).- **Secret custody.** Credentials live encrypted in the vault's state dir behind a capability-gated store; `$secret:NAME` references resolve at the use sites, `o2b brain secret unlock` wraps the keyfile under a passphrase, and `secret export`/`import` move the store between installs as one passphrase-encrypted bundle: [custody CLI](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#write-time-integrity-and-governance-since-v0440).@@ -123,7 +123,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite## What is new-1.80.0 raises what recall can reach and what the store can answer for itself. Entity creation learns from the vault: a store-learned lexicon (`o2b brain entity lexicon rebuild`) feeds tightened admission verdicts for all-caps headings and common-word labels, while code-shaped and caseless-script labels keep admitting, and a stale artifact degrades fail-open. Session imports mine precision mentions - code symbols, URLs, paths, qualified identifiers - into a ledger that `o2b brain hallways mine|show|promote|dismiss` folds into reviewable associations; promotion through the admission gate is the only bridge into the registry. Open Second Brain's v14 store migration pushes `kind` (`page`/`section`) into SQL on both lanes and pushes the promoted frontmatter keys where the push is faithful to the live filter (`type` scalar values, `pinned: true`, `visibility`; `tags` and non-scalar shapes stay post-rank), while unpromoted property keys narrow the candidate pool against the indexed attribute snapshot with the live file as the arbiter - answered as indexed, a documented divergence - with sargable path prefixes and a two-tier hydration cut. `o2b search rerank-eval` splits its report per language for bilingual datasets, and `brain_recall_telemetry` gains a `dead_weight` view (CLI `o2b brain recall-telemetry dead-weight`) naming in-scope pages no recorded recall ever surfaced. A repair lane closes the outstanding review findings: permission-rule targets canonicalize across path spellings, an ingest `stage` verdict now stages the entity pages and the manifest row it creates (not just the summary page), `delete_by_source` and schema mutations consult the permissions document and refuse on deny, the research pool reads the vault-resolved configuration, the unlock flow nudges toward export-before-wrap, and a bundle allowlist of `*` warns by name. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).+1.81.0 is the answer-trust release: it narrows the gap between what an agent was given and what its answer can be believed on. A Stop-hook step verifies the quotations in the assistant's answer against the note cited for them or the evidence recall actually injected (`quote_check.recall|active|subagent` in `Brain/_brain.yaml`, each `off|shadow|enforce`, default `shadow` - annotate-only, one `additionalContext` note per turn; `enforce` adds one Brain-log record per turn). `o2b brain truth state` accepts an optional opaque `--sample-id` naming the context-pack sample a claim drew on, and claim reads report the receipt and outcome provenance behind it at the caller's reach. Trusted local-file ingest now archives a source's bytes content-addressed under `Brain/.archives/` (redacted before persist, refused past 1 MiB, never pruned) with the hash stamped on the summary page; the capture-scope hygiene detector and a count-only doctor section name missing or mismatched evidence, and `brain_hygiene` `archive_get` reads an entry back at local reach. A record with no session id is read as no-session everywhere - scoped recall excludes it, grouping skips it, the session digest omits the key - dissolving the phantom blank-session bucket, with a count-only `blank-session-identity` doctor check for what older writers left behind. A repair lane closes the outstanding review findings: attribute narrowing in search falls a document whose indexed snapshot went stale through to the live filter instead of silently excluding it. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).## Documentationdiff --git a/plugins/codex/hooks/hooks.json b/plugins/codex/hooks/hooks.jsonindex de7b19ee..d340e081 100644--- a/plugins/codex/hooks/hooks.json+++ b/plugins/codex/hooks/hooks.json@@ -139,6 +139,13 @@"timeout": 10,"statusMessage": "OSB: checking stop log guardrail"},+ {+ "type": "command",+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" answer-quote-check; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook answer-quote-check; exit 0",+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook answer-quote-check & exit /b 0",+ "timeout": 10,+ "statusMessage": "OSB: verifying quoted spans against this turn's notes"+ },{"type": "command","command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" hygiene-digest; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook hygiene-digest; exit 0",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 147f101d..679885b6 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.80.0"+version: "1.81.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 849e21ec..b8578f8c 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.80.0"+version = "1.81.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/verbs/doctor.ts b/src/cli/brain/verbs/doctor.tsindex 492636b4..c8707186 100644--- a/src/cli/brain/verbs/doctor.ts+++ b/src/cli/brain/verbs/doctor.ts@@ -1,5 +1,21 @@+import { join } from "node:path";+import { resolveSearchConfig } from "../../../core/search/index.ts";import { runDoctor } from "../../../core/brain/doctor.ts";+import {+ reportSweptFailure,+ SWEEP_ORIGIN,+ type SweptPath,+} from "../../../core/brain/doctor/unreadable-path.ts";+import { BRAIN_ARCHIVES_REL } from "../../../core/brain/path-constants.ts";+import {+ auditArchiveStamps,+ type ArchiveStampAudit,+} from "../../../core/brain/hygiene/detectors/capture-scope.ts";+import {+ sourceArchiveStats,+ type ArchiveStats,+} from "../../../core/brain/provenance/source-archive.ts";import { annotateEntityAliasIssues } from "../../../core/brain/doctor/entity-alias-verdicts.ts";import { verdictFields, verdictLine } from "../../../core/decision-model/pair-verdict.ts";import { applyRepair, type RepairOutcome } from "../../../core/brain/diagnostics.ts";@@ -72,6 +88,43 @@ function explainMissingExits(codes: Iterable<string>, stream: AdvisoryStream): vfor (const [code, reason] of noExitReasons(codes)) info(`no exit: ${code} - ${reason}`);}+/**+ * One archive section: the counts, or the named unavailability when the+ * store itself could not be read.+ */+type ArchiveSection = (ArchiveStats & ArchiveStampAudit) | { readonly unavailable: true };++/**+ * The informational archive section (answer trust): counts only - how many+ * entries the durable source archive holds, their combined size, how many+ * stamped pages lost their entry or disagree with it, and how many entries+ * no page cites anymore. No fix verb: an archive is evidence, so pruning+ * and recapture are operator calls, and the named findings live on the+ * hygiene scan. Count-only also keeps this section from becoming a second+ * finding surface the scans would have to agree with.+ *+ * Fail-soft: the section runs AFTER the fail-soft check pass, and an+ * unreadable `Brain/.archives` used to throw past it - in `--json` mode+ * printing nothing at all. An informational section's failure is+ * uncertainty, not a failed run: the read is wrapped, the skip is named in+ * the pass's `uncertain` stream exactly as the doctor's own sweeps name+ * one, and the JSON answers `archives: { unavailable: true }`.+ */+function archiveSection(vault: string, swept: SweptPath): ArchiveSection {+ try {+ return { ...sourceArchiveStats(vault), ...auditArchiveStamps(vault) };+ } catch (err) {+ reportSweptFailure(+ join(vault, BRAIN_ARCHIVES_REL),+ "directory listing failed",+ err,+ swept,+ SWEEP_ORIGIN.root,+ );+ return { unavailable: true };+ }+}+export async function cmdBrainDoctor(argv: string[]): Promise<number> {const { flags } = parse(argv, {vault: { type: "string" },@@ -163,7 +216,21 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {// deliberately does not feed the exit code: uncertainty is not a// failure, and folding it into `--strict` would turn an unreadable// field into a broken build.- const uncertain = result.uncertain ?? [];+ // A mutable copy of the pass's stream: the archive section below appends+ // its own skip to it, and `runDoctor` returned the array frozen.+ const uncertain = [...(result.uncertain ?? [])];+ // The sweep identity the archive section reports its skips under - the+ // consequence names the question an unreadable store leaves open.+ const swept: SweptPath = {+ site: "brain.doctor.archiveSection",+ consequence: "the archive counts could not be taken",+ uncertain,+ };+ // The archive section is taken ONCE, before anything is rendered or+ // derived from the streams: an unreadable store names its skip in the+ // stream above, so the failure feeds the exit census and is visible in+ // the same pass instead of one key (or one line) late.+ const section = archiveSection(vault, swept);// Every code the three streams reported, in the order an operator reads// them. Feeds both the rail and the explanation of what the rail could@@ -201,6 +268,11 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {// every issue record: a reason is about a CLASS, unlike a next// command, and two hundred malformed timestamps share one....(noExit.size > 0 ? { [NO_EXIT_KEY]: Object.fromEntries(noExit) } : {}),+ // Count-only informational archive section (answer trust): the+ // key is always present, so a caller never infers the section's+ // existence from a missing key - and when the store could not be+ // read, the key names the unavailability instead of a count.+ archives: section,},null,2,@@ -217,6 +289,25 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {if (result.errors.length === 0 && result.warnings.length === 0 && uncertain.length === 0) {ok("brain doctor: clean");}+ // One line, and only when there is something to describe: a vault that+ // has never archived a source gains no line at all, and an orphaned+ // entry - evidence no page cites - is something to describe. An+ // unreadable store is already named by its `[UNSURE]` line above, so+ // it gains no counts line either.+ const archives = "unavailable" in section ? null : section;+ if (+ archives !== null &&+ (archives.entries > 0 ||+ archives.missing > 0 ||+ archives.mismatched > 0 ||+ archives.uncited > 0)+ ) {+ process.stdout.write(+ `archives: ${archives.entries} entries, ${archives.totalBytes} bytes, ` ++ `${archives.missing} missing, ${archives.mismatched} mismatched, ` ++ `${archives.uncited} uncited\n`,+ );+ }}// no-dead-ends, task 4: the exits, after the diagnosis. Errors first,diff --git a/src/cli/brain/verbs/session-summary.ts b/src/cli/brain/verbs/session-summary.tsindex a0aac52a..0dbff927 100644--- a/src/cli/brain/verbs/session-summary.ts+++ b/src/cli/brain/verbs/session-summary.ts@@ -29,6 +29,14 @@ const USAGE =" o2b brain session-summary get --session <id> [--json]\n" +" o2b brain session-summary list [--session <id>] [--json]";+/**+ * The text-mode stand-in for a digest whose record names no session+ * (t_22d58fa7). A dash, not an id and not the empty string the old+ * `String(... ?? "")` coercion manufactured - a no-session record is+ * rendered as having none, never as belonging to some session.+ */+const NO_SESSION_RENDER = "-";+export async function cmdBrainSessionSummary(argv: string[]): Promise<number> {const subcommand = argv[0];if (subcommand === "write") return writeSummary(argv.slice(1));@@ -160,8 +168,9 @@ function listSummaries(argv: string[]): number {}process.stdout.write(`${digests.length} session summary record(s)\n`);for (const digest of digests) {+ const session = digest.sessionId ?? NO_SESSION_RENDER;process.stdout.write(- ` ${digest.createdAt} ${digest.sessionId} d=${digest.decisions.length} l=${digest.learnings.length} n=${digest.nextSteps.length}\n`,+ ` ${digest.createdAt} ${session} d=${digest.decisions.length} l=${digest.learnings.length} n=${digest.nextSteps.length}\n`,);}return 0;@@ -170,7 +179,9 @@ function listSummaries(argv: string[]): number {function serialize(digest: SessionSummaryDigest): Record<string, unknown> {return {id: digest.id,- session_id: digest.sessionId,+ // Presence-gated with the digest shape (t_22d58fa7): a record naming+ // no session carries no session_id key, never a fabricated "".+ ...(digest.sessionId !== undefined ? { session_id: digest.sessionId } : {}),request: digest.request,decisions: digest.decisions,learnings: digest.learnings,@@ -184,7 +195,7 @@ function serialize(digest: SessionSummaryDigest): Record<string, unknown> {}function renderDigest(digest: SessionSummaryDigest): string {- const lines = [`session ${digest.sessionId} (${digest.createdAt})`];+ const lines = [`session ${digest.sessionId ?? NO_SESSION_RENDER} (${digest.createdAt})`];if (digest.request !== null) lines.push(` request: ${digest.request}`);appendCategory(lines, "decisions", digest.decisions);appendCategory(lines, "learnings", digest.learnings);diff --git a/src/cli/brain/verbs/truth.ts b/src/cli/brain/verbs/truth.tsindex b6af68bf..d87c821c 100644--- a/src/cli/brain/verbs/truth.ts+++ b/src/cli/brain/verbs/truth.ts@@ -59,7 +59,7 @@ const USAGE =" collisions [--window-days N]\n" +" events [--entity E] [--since X] [--until Y] [--limit N]\n" +" state --subject S --relation R --object O --text T --source S\n" +- " [--agent N]\n" ++ " [--agent N] [--sample-id ID]\n" +" sweep [--max-events N]\n" +" common [--vault <path>] [--json]";@@ -88,6 +88,7 @@ export async function cmdBrainTruth(argv: string[]): Promise<number> {relation: { type: "string" },object: { type: "string" },text: { type: "string" },+ "sample-id": { type: "string" },since: { type: "string" },until: { type: "string" },limit: { type: "string" },@@ -339,6 +340,13 @@ export async function cmdBrainTruth(argv: string[]): Promise<number> {agent: resolveBrainAgent(flags, config),ts: isoSecond(new Date()),source: requireString(flags, "source"),+ // Answer-trust (task B5): an optional attribution id,+ // validated by the same payload-boundary refusal the MCP+ // state operation answers (mapped to the usage-error+ // class below); committed events echo it verbatim.+ ...(flags["sample-id"] !== undefined+ ? { sampleId: flags["sample-id"] as string }+ : {}),},{ entities: statedClaimEntities(vault), configPath: config },);diff --git a/src/core/brain/answer-quotes/check.ts b/src/core/brain/answer-quotes/check.tsnew file mode 100644index 00000000..2d292ffb--- /dev/null+++ b/src/core/brain/answer-quotes/check.ts@@ -0,0 +1,182 @@+/**+ * The answer-time quote check: the verdict on each quoted span of a host+ * answer, against the evidence the turn actually had. Pure; no I/O.+ *+ * The distill lane verifies every quotation on a page it writes itself+ * (`src/core/brain/distill/quote-check.ts`). This module runs the SAME+ * helpers - `normalizeForQuoteComparison`, `quoteHaystack` and+ * `spanOccursIn`, imported in place from `quote-spans.ts`, never forked -+ * over evidence the host did not write: the note a span cites, or the+ * notes the injection ledger says entered context. It differs from the+ * distill check in the two ways its subject forces:+ *+ * - IT NEVER EDITS THE ANSWER. A failed span keeps its quotation marks;+ * the verdict is reported and the hook annotates. `unquoteSpans` and+ * `checkClaimQuotes` stay unextended and uncalled here.+ * - DEGRADATION NEVER UPGRADES A VERDICT. Evidence the turn had only in+ * part is named apart: a span missing from a truncated note is+ * `source-truncated`, never `not-in-note`, and a note that could not be+ * read is `note-unavailable` - "we could not check" is a finding, not+ * an all-clear.+ *+ * The verdict table, pinned by the test suite:+ *+ * evidence span occurs | verdict+ * ------------------------|------------|------------------+ * text (complete) | yes | verified+ * text (complete) | no | not-in-note+ * text (truncated) | yes | verified+ * text (truncated) | no | source-truncated+ * unavailable | - | note-unavailable+ * not-text | - | not-text+ *+ * The vocabulary follows the census trio convention: frozen object,+ * companion member list, type guard; registered in+ * `tests/core/architecture/verdict-vocabulary-census.test.ts`.+ */++import {+ normalizeForQuoteComparison,+ quoteHaystack,+ spanOccursIn,+} from "../distill/quote-spans.ts";+import { QUOTE_SPAN_PREVIEW_MAX_CHARS } from "../distill/quote-verdict.ts";++/** The closed vocabulary of per-span verdicts. */+export const ANSWER_QUOTE_VERDICT = Object.freeze({+ /** The span occurs in the evidence the turn had. */+ verified: "verified",+ /** The evidence was fully readable, and the span is not in it. */+ notInNote: "not-in-note",+ /** The evidence reached context only in part, and the span is not in the part. */+ sourceTruncated: "source-truncated",+ /** The note the span is cited against could not be read (or none resolved). */+ noteUnavailable: "note-unavailable",+ /** The evidence bytes are not valid UTF-8 text. */+ notText: "not-text",+} as const);++/** Closed union over {@link ANSWER_QUOTE_VERDICT}. */+export type AnswerQuoteVerdict = (typeof ANSWER_QUOTE_VERDICT)[keyof typeof ANSWER_QUOTE_VERDICT];++/** Membership list, in verdict-table order. */+export const ANSWER_QUOTE_VERDICTS: ReadonlyArray<AnswerQuoteVerdict> = Object.freeze(+ Object.values(ANSWER_QUOTE_VERDICT),+);++/** Narrow a verdict read back off a payload or an annotation. */+export function isAnswerQuoteVerdict(value: unknown): value is AnswerQuoteVerdict {+ return (+ typeof value === "string" && (ANSWER_QUOTE_VERDICTS as ReadonlyArray<string>).includes(value)+ );+}++/**+ * What the turn had behind one candidate note. `truncated` marks evidence+ * the context received only in part - a `ContextPackItem.trimmed` body, a+ * receipt flagged `truncated`, or a pointer that names a line range - so+ * a miss against it can never read as `not-in-note`.+ */+export type AnswerQuoteEvidence =+ | { readonly kind: "text"; readonly text: string; readonly truncated: boolean }+ | { readonly kind: "unavailable" }+ | { readonly kind: "not-text" };++export interface AnswerQuoteCheckInput {+ /**+ * The quoted span texts (between the marks, verbatim), in answer order.+ * The caller finds them with `findQuoteSpans`; this module checks+ * verdicts, not mark pairing.+ */+ readonly spans: ReadonlyArray<string>;+ readonly evidence: AnswerQuoteEvidence;+}++/** One span's verdict, in the report's order. */+export interface AnswerQuoteSpanOutcome {+ /** 0-based position of the span in the input. */+ readonly index: number;+ /** The span's text, capped at {@link QUOTE_SPAN_PREVIEW_MAX_CHARS}. */+ readonly span: string;+ readonly verdict: AnswerQuoteVerdict;+}++export interface AnswerQuoteCheckResult {+ /** One outcome per input span, in input order. */+ readonly outcomes: ReadonlyArray<AnswerQuoteSpanOutcome>;+ /** Spans whose verdict is {@link ANSWER_QUOTE_VERDICT.verified}. */+ readonly verified: number;+ readonly unverified: number;+}++/**+ * The span's own text, cut at the preview cap without splitting a code+ * point. This is the only form a span renders in - the outcome's `span`+ * field, and anything a consumer prints about a span - so answer text is+ * bounded wherever it is echoed back.+ */+export function previewAnswerQuoteSpan(inner: string): string {+ const codePoints = Array.from(inner);+ return codePoints.length <= QUOTE_SPAN_PREVIEW_MAX_CHARS+ ? inner+ : codePoints.slice(0, QUOTE_SPAN_PREVIEW_MAX_CHARS).join("");+}++/** One span against one evidence body, both already settled. */+function textVerdict(inner: string, text: string, truncated: boolean): AnswerQuoteVerdict {+ return spanOccursIn(inner, quoteHaystack(normalizeForQuoteComparison(text)))+ ? ANSWER_QUOTE_VERDICT.verified+ : truncated+ ? ANSWER_QUOTE_VERDICT.sourceTruncated+ : ANSWER_QUOTE_VERDICT.notInNote;+}++/**+ * Check every span against one evidence body. Every span gets exactly one+ * verdict; nothing here touches the answer text.+ */+export function checkAnswerQuotes(input: AnswerQuoteCheckInput): AnswerQuoteCheckResult {+ const evidence = input.evidence;+ const outcomes = input.spans.map((span, index) => {+ const verdict =+ evidence.kind === "text"+ ? textVerdict(span, evidence.text, evidence.truncated)+ : evidence.kind === "unavailable"+ ? ANSWER_QUOTE_VERDICT.noteUnavailable+ : ANSWER_QUOTE_VERDICT.notText;+ return { index, span: previewAnswerQuoteSpan(span), verdict };+ });+ const verified = outcomes.filter((o) => o.verdict === ANSWER_QUOTE_VERDICT.verified).length;+ return { outcomes, verified, unverified: outcomes.length - verified };+}++/**+ * Merge the per-candidate verdicts of one span checked against several+ * evidence bodies (the no-citation case: every note the running phases'+ * ledger says entered context). The ladder is pinned:+ *+ * 1. a hit anywhere verifies - the evidence the turn had supports the+ * span, however the other candidates answered;+ * 2. no candidates at all is `note-unavailable` - nothing to check+ * against is a finding, not an all-clear;+ * 3. otherwise degradation outranks a readable miss, and the partial+ * evidence outranks the absent: `source-truncated`, then+ * `not-text`, then `note-unavailable`;+ * 4. readable misses only are `not-in-note`.+ */+export function mergeAnswerQuoteVerdicts(+ verdicts: ReadonlyArray<AnswerQuoteVerdict>,+): AnswerQuoteVerdict {+ if (verdicts.includes(ANSWER_QUOTE_VERDICT.verified)) return ANSWER_QUOTE_VERDICT.verified;+ const partial = verdicts.filter((verdict) => verdict !== ANSWER_QUOTE_VERDICT.notInNote);+ if (partial.length === 0) {+ return verdicts.length === 0+ ? ANSWER_QUOTE_VERDICT.noteUnavailable+ : ANSWER_QUOTE_VERDICT.notInNote;+ }+ if (partial.includes(ANSWER_QUOTE_VERDICT.sourceTruncated)) {+ return ANSWER_QUOTE_VERDICT.sourceTruncated;+ }+ if (partial.includes(ANSWER_QUOTE_VERDICT.notText)) return ANSWER_QUOTE_VERDICT.notText;+ return ANSWER_QUOTE_VERDICT.noteUnavailable;+}diff --git a/src/core/brain/context-receipts.ts b/src/core/brain/context-receipts.tsindex d57bf5a5..37ad4b12 100644--- a/src/core/brain/context-receipts.ts+++ b/src/core/brain/context-receipts.ts@@ -85,6 +85,14 @@ export interface ContextReceiptFilter {readonly trigger?: ContextReceiptTrigger;readonly host?: string;readonly sessionId?: string;+ /**+ * Exact receipt id (answer-trust, task B3): the one-record lookup the+ * claim-provenance join uses to resolve a claim's `sample_id` to the+ * receipt it names. Matched BEFORE the limit, like every other filter+ * field, so a receipt lookup answers the store's answer for that id+ * and never whichever receipts happen to be newest.+ */+ readonly receiptId?: string;readonly limit?: number;/*** Receipts the caller may not see at all. They are left out before the@@ -514,6 +522,7 @@ export const CONTEXT_RECEIPT_TRIGGERS: ReadonlyArray<ContextReceiptTrigger> = Obfunction matchesReceiptFilter(record: ContinuityRecord, filter: ContextReceiptFilter): boolean {const payload = record.payload;+ if (filter.receiptId !== undefined && record.id !== filter.receiptId) return false;if (filter.trigger !== undefined && payload["trigger"] !== filter.trigger) return false;if (filter.host !== undefined && payload["host"] !== filter.host) return false;if (filter.sessionId !== undefined && payload["session_id"] !== filter.sessionId) return false;diff --git a/src/core/brain/destructive-sites.ts b/src/core/brain/destructive-sites.tsindex 5d2e7ff6..bdb93407 100644--- a/src/core/brain/destructive-sites.ts+++ b/src/core/brain/destructive-sites.ts@@ -441,6 +441,18 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati"PARTIAL rather than covered because `--include-originals` removes the imported file " +"outside `Brain/`, which no archive has ever held.",},+ "src/core/brain/provenance/source-archive.ts": {+ calls: ["rmSync"],+ recovery: UNARCHIVED_BRAIN,+ reason:+ "`discardSourceArchive` removes one content-addressed entry from `Brain/.archives/` " ++ "only when delete-by-source has established that its LAST citing page is in the same " ++ "confirmed deletion - the caller owns that decision and this module cannot check it, " ++ "which is the claim written down here. The confirmed delete-by-source run beside which " ++ "the discard fires takes its D1 snapshot first, and `Brain/.archives/` is deliberately " ++ "NOT a snapshot-excluded entry, so the bytes the removal takes are inside that run's " ++ "recovery point even though this primitive never takes one of its own.",+ },"src/core/brain/notes/write-record.ts": {calls: ["unlinkSync"],recovery: UNARCHIVED_BRAIN,diff --git a/src/core/brain/doctor-exits.ts b/src/core/brain/doctor-exits.tsindex 0eeea471..a08ddb6c 100644--- a/src/core/brain/doctor-exits.ts+++ b/src/core/brain/doctor-exits.ts@@ -288,6 +288,18 @@ const EXCLUSIONS: ReadonlyArray<DoctorExitExclusion> = ["rather than damage - every row still reads - so whether that cost is worth a rewrite is " +"the operator's call, and no command makes it for them",},+ {+ // The blank-session-identity count (t_22d58fa7). A session no writer+ // stamped cannot be restored from the record: assigning one would+ // fabricate provenance over append-only history.+ code: "blank-session-identity",+ reason:+ "the finding is a count of records whose payload names no session, which is a fact about " ++ "the writers, not a defect in any one row. Stamping an identity after the fact would " ++ "fabricate provenance over append-only history that peers merge by content id, so the " ++ "only honest exit is the count itself - the condition is worth knowing about, and any " ++ "rewrite belongs to a restore from backup, not to a command this table could name",+ },{code: "recovery-point-unmeasured",reason:diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex e315f585..c6778784 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -57,6 +57,7 @@ import { brokenBacklinkCheck } from "./doctor/link-checks.ts";import { mergeChainDanglingCheck } from "./doctor/merge-chain-check.ts";import { orphanSessionCheck } from "./doctor/orphan-session-check.ts";import { permissionsDocumentCheck } from "./doctor/permissions-check.ts";+import { sessionIdentityCheck } from "./doctor/session-identity-check.ts";import { evidenceRangeCheck, logShardCheck, orphanEvidenceCheck } from "./doctor/log-checks.ts";import {contentHashDriftCheck,@@ -199,6 +200,10 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([evidenceRangeCheck,orphanEvidenceCheck,orphanSessionCheck,+ // The blank-identity count reads the same ledger the orphan check's+ // resolution half reads, so the two session-identity checks report+ // adjacently.+ sessionIdentityCheck,entityRegistryCheck,capturePatternCheck,syncConflictLogCheck,diff --git a/src/core/brain/doctor/session-identity-check.ts b/src/core/brain/doctor/session-identity-check.tsnew file mode 100644index 00000000..8fad0989--- /dev/null+++ b/src/core/brain/doctor/session-identity-check.ts@@ -0,0 +1,142 @@+/**+ * Blank session identity, counted (t_22d58fa7).+ *+ * Writers across the continuity surface stamp `session_id`+ * conditionally - a lane with no session in scope writes the record with+ * the key absent - and the readers used to coerce that absence to the+ * empty string, manufacturing a phantom session no writer ever created+ * (the reader-side repair is `sessionIdOf` in `session-recall.ts`, built+ * on the orphan-session reading that a missing identity is a statement+ * that there was no session, never a pointer to a missing one). This+ * check is the vault-level mirror of that decision: one pass over the+ * continuity ledger, one issue per affected record kind carrying the+ * count of records that name no session - the key absent, a non-string+ * value, or the empty string.+ *+ * The census is scoped to the kinds whose writers stamp a session on+ * EVERY record they write (below). A record of one of those kinds that+ * names no session is a defect in the write that produced it. The rest+ * of the ledger is sessionless BY DESIGN and counts nothing: the+ * telemetry lanes run with no session in scope and stamp the key only+ * when one exists (`gate-telemetry.ts`, `recall-telemetry.ts`,+ * `observed-use.ts`, `recent-turns.ts`, `token-impact.ts`,+ * `context-pack-evidence.ts`, `context-pack-outcome.ts`,+ * `context-receipts.ts`), `appendContinuitySourceInvalidation` writes+ * only `{reason}`, and the remaining kinds correlate their session+ * outside the payload key entirely (source refs, `session_ref`,+ * `sample_id`). Warning on those would put a permanent finding on every+ * used vault, so they are excluded by name - the census over the+ * classification lives in `session-identity-check.test.ts`.+ *+ * The count is the whole finding. The check carries no `fix` and+ * rewrites nothing: a session no writer stamped cannot be restored from+ * the record, and assigning one would fabricate provenance over+ * append-only history - the repair such a rewrite would need is the+ * backup-gated posture the continuity repairs already require.+ *+ * Fail-soft: a ledger this module cannot read must cost the pass an+ * uncertainty, never a throw - and never a finding either, since a count+ * over a partial read would dress a gap in the store up as a measured+ * condition. An ABSENT ledger is the ordinary fresh-vault case and stays+ * quiet, the same absent/failed split every doctor sweep draws.+ */++import { continuityLogDir, listContinuityRecords } from "../continuity/store.ts";+import type { ContinuityRecord, ContinuityRecordKind } from "../continuity/types.ts";+import { sessionIdOf } from "../session-recall.ts";+import type { DoctorIssue } from "../types.ts";+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";+import { reportSweptFailure, SWEEP_ORIGIN, type SweptPath } from "./unreadable-path.ts";++/** A continuity record names no session where the writers stamped one conditionally. */+export const SESSION_IDENTITY_CHECK_CODE = "blank-session-identity";++/** Subsystem name the check's sweeps report an unreadable path under. */+export const SESSION_IDENTITY_SITE = "brain.doctor.sessionIdentity";++/**+ * The kinds this census counts: the kinds whose writer carries a+ * session-scoped payload, stamping `session_id` unconditionally from a+ * REQUIRED input, so an unnamed session is a defect rather than a lane+ * running without one:+ *+ * - `session_turn` / `session_summary_node` - `session-recall.ts`+ * (`importRawTurn` / `appendTurnRow` and the node builder; the session+ * id is a required parameter and the payload key is unconditional).+ * - `session_summary_digest` - `session-summary.ts` (refuses a blank id+ * before writing).+ * - `pre_compact_extract` - `pre-compact-extract.ts` (required+ * `sessionId`, stamped into every payload).+ * - `post_compact_audit` - `post-compact-audit.ts` (required+ * `sessionId`, stamped into every payload).+ * - `decision_model_extract_commit` - `extract-signals-prefilter.ts`+ * (stamped from the commit result's required session id).+ *+ * The writer-shape census that keeps this list honest over the full+ * `ContinuityRecordKind` population lives in the check's test file.+ */+export const SESSION_IDENTITY_CHECKED_KINDS: ReadonlyArray<ContinuityRecordKind> = Object.freeze([+ "decision_model_extract_commit",+ "post_compact_audit",+ "pre_compact_extract",+ "session_summary_digest",+ "session_summary_node",+ "session_turn",+]);++const CHECKED_KINDS: ReadonlySet<string> = new Set(SESSION_IDENTITY_CHECKED_KINDS);++/** What the check can no longer claim for a ledger it could not read. */+const LEDGER_CONSEQUENCE =+ "no record in it had its session identity counted, so a blank-identity count for its kinds is missing from this report";++/**+ * The registered check. Count-only and fail-soft: one pass, one issue+ * per affected kind (deterministic kind order), no `fix` field, no+ * payload rewritten. Kinds whose writers are sessionless by design+ * produce no issue at all.+ */+export const sessionIdentityCheck: DoctorCheck = {+ failSoft: true,+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {+ const swept: SweptPath = {+ site: SESSION_IDENTITY_SITE,+ consequence: LEDGER_CONSEQUENCE,+ uncertain: out.uncertain,+ };+ let records: ReadonlyArray<ContinuityRecord>;+ try {+ records = listContinuityRecords(ctx.vault);+ } catch (err) {+ reportSweptFailure(+ continuityLogDir(ctx.vault),+ "continuity ledger read failed",+ err,+ swept,+ SWEEP_ORIGIN.root,+ );+ return;+ }+ const counts = new Map<string, number>();+ for (const record of records) {+ if (!CHECKED_KINDS.has(record.kind)) continue;+ if (sessionIdOf(record.payload) !== undefined) continue;+ counts.set(record.kind, (counts.get(record.kind) ?? 0) + 1);+ }+ const dir = continuityLogDir(ctx.vault);+ for (const [kind, count] of [...counts].toSorted((left, right) =>+ left[0].localeCompare(right[0]),+ )) {+ out.issues.push({+ severity: "warning",+ code: SESSION_IDENTITY_CHECK_CODE,+ path: dir,+ message:+ `${count} ${kind} continuity record(s) name no session ` ++ "(session_id absent, non-string, or empty; this kind's writer stamps one on " ++ "every record); informational count only - reads treat them as unattributed " ++ "and no payload is rewritten",+ } satisfies DoctorIssue);+ }+ },+};diff --git a/src/core/brain/hygiene/detectors/capture-scope.ts b/src/core/brain/hygiene/detectors/capture-scope.tsindex 8dc1a899..9447762a 100644--- a/src/core/brain/hygiene/detectors/capture-scope.ts+++ b/src/core/brain/hygiene/detectors/capture-scope.ts@@ -1,5 +1,6 @@/**- * Capture-scope detector: active knowledge that rests on url-only sources.+ * Capture-scope detector: active knowledge that rests on url-only sources,+ * and pages whose claimed durable archive is gone or no longer matches.** A page whose every cited source has no local bytes behind it rests on a* locator that may rot, and nothing on the page says so once the untrusted@@ -8,6 +9,20 @@* page, `review` proposed action - deciding whether to capture the source,* re-cite a local one or retire the page is an operator call.*+ * The archive arm (answer trust) is the second condition, and the sharper+ * one: an ingest summary stamped `source_archive_hash` claims durable+ * evidence behind it, and a stamp whose entry is absent - or present but+ * re-hashing differently - is exactly the rot this detector exists to name,+ * with the difference that the page SAID the evidence was there. It fires+ * however fresh the live source file is: the claim under test is the+ * archive's, not the file's.+ *+ * One finding per page: when both arms fire for the same page (a vanished+ * file whose archive entry went too), the archive finding wins - it+ * subsumes the url-only condition under the stronger statement that claimed+ * evidence is gone - and the per-page finding id stays unique, which the+ * apply plan's selection requires.+ ** Inspected: retrievable pages (the retrieval trust gate does not* quarantine them) of the four knowledge kinds - distillations, ingest* summaries, research reports, and entities in the canonical status scope.@@ -26,6 +41,13 @@* read at its reach counts as url-only, the answer an absent file gives, so* a finding never tells a narrower caller that a hidden page exists.*+ * The archive arm answers from the store, not from any caller's reach: the+ * verification is a fact about `Brain/.archives/` and the page's own stamp,+ * and the caller who may not read the page never sees the finding (the+ * scan's artifact-reference view withholds it with the page). A stamp that+ * is not a hash names no entry the store could hold, so it verifies as+ * `missing` - the stamp cannot be true.+ ** Cited sources are read with the shared source-link readers: the page's* `source_path` plus the targets under its `## Sources` heading.*/@@ -57,6 +79,12 @@ import {resolveCaptureScope,type CaptureScope,} from "../../provenance/capture-scope.ts";+import {+ ARCHIVE_VERIFICATION,+ SOURCE_ARCHIVE_HASH_KEY,+ sourceArchiveUncitedHashes,+ verifySourceArchive,+} from "../../provenance/source-archive.ts";import { SourceTrustError, isSourceHidden } from "../../intake/source-trust.ts";import { sourcesSectionTargets } from "../../source-links.ts";import { hygieneFindingId } from "./id.ts";@@ -64,9 +92,13 @@ import type { HygieneFinding } from "../types.ts";export const CAPTURE_SCOPE_DETECTOR_ID = "capture-scope" as const;-/** One-line summary every finding of this detector carries. */+/** One-line summary every url-only finding of this detector carries. */export const CAPTURE_SCOPE_FINDING_TITLE = "Active knowledge rests on url-only sources";+/** One-line summary every archive-stamp finding of this detector carries. */+export const CAPTURE_SCOPE_ARCHIVE_FINDING_TITLE =+ "A page's durable source archive is missing or no longer matches its stamp";+/** Frontmatter key holding a single-source page's source identity. */const SOURCE_PATH_KEY = "source_path";@@ -154,6 +186,11 @@ function inspectPage(vault: string, page: string, readable: Readable): HygieneFiif (!isRetrievableKnowledge(meta)) return null;const sources = citedSources(meta, body);+ // The archive arm first, so a page failing BOTH conditions reports the+ // sharper archive finding once - never two findings with one id.+ const archiveFinding = inspectArchiveStamp(vault, page, meta, sources);+ if (archiveFinding !== null) return archiveFinding;+if (sources.length === 0) return null;const allUrlOnly = sources.every((source) => isUrlOnly(vault, source, readable));if (!allUrlOnly) return null;@@ -173,6 +210,41 @@ function inspectPage(vault: string, page: string, readable: Readable): HygieneFi});}+/**+ * The archive arm: does the page's claimed durable evidence still hold?+ * `null` for a page with no stamp (absence means "not captured", never a+ * finding) and for a stamp whose entry verifies; otherwise one finding per+ * page carrying the named verification state.+ */+function inspectArchiveStamp(+ vault: string,+ page: string,+ meta: FrontmatterMap,+ sources: ReadonlyArray<string>,+): HygieneFinding | null {+ const hash = stringValue(meta, SOURCE_ARCHIVE_HASH_KEY);+ if (hash === null) return null;+ // A malformed stamp verifies as `missing` - it names no entry the store+ // could hold, which is the state it is in.+ const state = verifySourceArchive(vault, hash).state;+ if (state === ARCHIVE_VERIFICATION.verified) return null;++ const targets = Object.freeze([page]);+ return Object.freeze({+ id: hygieneFindingId(CAPTURE_SCOPE_DETECTOR_ID, targets),+ detector: CAPTURE_SCOPE_DETECTOR_ID,+ severity: "warning" as const,+ title: CAPTURE_SCOPE_ARCHIVE_FINDING_TITLE,+ targets,+ proposed_action: "review" as const,+ evidence: Object.freeze({+ archive: state,+ hash,+ sources: Object.freeze([...sources]),+ }),+ });+}+/*** Every finding in the vault. `readable` is the caller's reach (see* `HygieneDetectorContext.readable`); a local caller passes nothing.@@ -194,3 +266,50 @@ export function detectCaptureScope(}return Object.freeze(findings);}++/** What {@link auditArchiveStamps} counted. */+export interface ArchiveStampAudit {+ /** Stamped pages whose archive entry is absent. */+ readonly missing: number;+ /** Stamped pages whose entry is there but re-hashes differently. */+ readonly mismatched: number;+ /**+ * Store entries NO page cites - the structurally unreachable leftovers+ * the two counts above cannot see: a re-stamped page orphans the entry+ * the old stamp named, and a staged ingest rejected by review leaves+ * its entry behind. Evidence, not scratch, so the audit names them+ * rather than pruning them; release is an operator call made through+ * delete-by-source cleanup.+ */+ readonly uncited: number;+}++/**+ * Count the archive's rot, on both of its populations: the stamped pages+ * whose entry is gone or disagrees, and the store entries no page cites.+ * One walk over `Brain/sources/` for the stamps, one over the stamp roots+ * and the store for the uncited entries. Every stamp counted: unlike the+ * scan's finding list, no page is skipped for quarantine or reach,+ * because the doctor runs locally and reports a count, not a disclosure.+ * Integers, never a page list - recapture and pruning are operator calls+ * made from the hygiene scan's findings, not from these numbers.+ */+export function auditArchiveStamps(vault: string): ArchiveStampAudit {+ const counts = {+ missing: 0,+ mismatched: 0,+ uncited: sourceArchiveUncitedHashes(vault).length,+ };+ const abs = join(vault, BRAIN_SOURCES_REL);+ if (!existsSync(abs)) return counts;+ for (const rel of listVaultNotePaths(abs)) {+ const page = posix.join(BRAIN_SOURCES_REL, rel.split("\\").join("/"));+ const [meta] = parseFrontmatter(join(vault, page));+ const hash = stringValue(meta, SOURCE_ARCHIVE_HASH_KEY);+ if (hash === null) continue;+ const state = verifySourceArchive(vault, hash).state;+ if (state === ARCHIVE_VERIFICATION.missing) counts.missing += 1;+ else if (state === ARCHIVE_VERIFICATION.mismatched) counts.mismatched += 1;+ }+ return counts;+}diff --git a/src/core/brain/idea-lineage.ts b/src/core/brain/idea-lineage.tsindex a3665a94..270c174a 100644--- a/src/core/brain/idea-lineage.ts+++ b/src/core/brain/idea-lineage.ts@@ -24,6 +24,7 @@import { listContinuityRecords } from "./continuity/store.ts";import type { ContinuityRecord } from "./continuity/types.ts";+import { sessionIdOf } from "./session-recall.ts";import { buildTimelineIndex } from "./temporal/build-index.ts";import { buildBeliefEvolution } from "./temporal/belief-evolution.ts";@@ -117,8 +118,11 @@ function continuityLineage(const turnId = String(record.payload["turn_id"] ?? "");if (turnId.length === 0) continue;if (!byTurnId.has(turnId)) byTurnId.set(turnId, record);- const sessionId = String(record.payload["session_id"] ?? "");- if (sessionId.length > 0) {+ // A record naming no session joins only the global turn index -+ // never the session-scoped one, where a coerced "" or a stringified+ // non-string id would merge unrelated records into one group.+ const sessionId = sessionIdOf(record.payload);+ if (sessionId !== undefined) {const scoped = sessionTurnKey(sessionId, turnId);if (!bySessionTurnId.has(scoped)) bySessionTurnId.set(scoped, record);}@@ -195,7 +199,10 @@ function sessionTurnKey(sessionId: string, turnId: string): string {function resolveSources(record: ContinuityRecord, lookup: Lookup): ResolvedSource[] {const sources: ResolvedSource[] = [];const claimed = new Set<string>();- const recordSessionId = String(record.payload["session_id"] ?? "");+ // Undefined - never "" - when the record names no session: the scoped+ // lookup is then unreachable and the global turn index (first record in+ // store order) is the documented fallback for an unknown session.+ const recordSessionId = sessionIdOf(record.payload);for (const ref of record.sourceRefs) {const refId = typeof ref.id === "string" ? ref.id : "";if (refId.length === 0 || refId === record.id) continue;@@ -203,7 +210,7 @@ function resolveSources(record: ContinuityRecord, lookup: Lookup): ResolvedSourc// referring record's own session before falling back to the global// turn index (only reachable when the session is unknown).const scoped =- recordSessionId.length > 0+ recordSessionId !== undefined? lookup.bySessionTurnId.get(sessionTurnKey(recordSessionId, refId)): undefined;const candidate = lookup.byId.get(refId) ?? scoped ?? lookup.byTurnId.get(refId);diff --git a/src/core/brain/ingest/ingest.ts b/src/core/brain/ingest/ingest.tsindex 57102e7f..959dd26b 100644--- a/src/core/brain/ingest/ingest.ts+++ b/src/core/brain/ingest/ingest.ts@@ -49,13 +49,32 @@ import {type ExtractionIntake,type IntakeRelation,} from "../intake/extract-intake.ts";-import { normalizeSourceIdentity } from "../intake/source-trust.ts";-import { INTAKE_TRUST, untrustedSourceFrontmatter } from "../trust/untrusted-provenance.ts";+import {+ SourceTrustError,+ errnoCode,+ isSourceHidden,+ normalizeSourceIdentity,+ readSourceOrigin,+} from "../intake/source-trust.ts";+import {+ INTAKE_TRUST,+ untrustedSourceFrontmatter,+ type IntakeTrust,+} from "../trust/untrusted-provenance.ts";import {captureScopeForTrust,captureScopeFrontmatter,type CaptureScope,} from "../provenance/capture-scope.ts";+import {+ SOURCE_ARCHIVE_BYTES_KEY,+ SOURCE_ARCHIVE_HASH_KEY,+ SourceArchiveError,+ putSourceArchive,+} from "../provenance/source-archive.ts";+import type { FrontmatterCache } from "../../search/result-filters.ts";+import { isPathReadableAtReach } from "../../search/result-filters.ts";+import { TRANSPORT_REACH } from "../../graph/transport-reach.ts";import {renderProvenanceSection,sourceIdentityHash,@@ -153,6 +172,31 @@ export interface IngestSourceResult {* paraphrase, not a capture.*/readonly captureScope: CaptureScope;+ /**+ * Digest of the durable archive entry holding this source's bytes+ * (redacted, content-addressed under `Brain/.archives/`), present only+ * when the trusted-local branch captured them - the same value the+ * summary page stamps as `source_archive_hash`. Absent means exactly+ * "not archived": an unstamped page is a state, never a failure.+ */+ readonly sourceArchiveHash?: string;+ /** UTF-8 byte count of the archived (redacted) entry, with the hash. */+ readonly sourceArchiveBytes?: number;+ /**+ * The named reason an ELIGIBLE capture FAILED - a past-ceiling input the+ * archive refused, or an archive write that could not land. Recorded so+ * the skip is not silent; the page stays unstamped either way. A source+ * that vanished between classification and the capture read is the+ * deliberate silent arm: neither stamp nor refusal (absence stays+ * absence), because a source that is gone is no longer trusted-local,+ * not a failed capture. Nor is this field ever present when the source+ * was simply not capture-eligible (untrusted, non-local, withheld from+ * remote readers): those behave exactly as before this field existed.+ * The text is identifiers only - a vault-relative source identity, byte+ * counts, an errno code - never a host path, since the field crosses to+ * the wire (see {@link archiveRefusalMessage}).+ */+ readonly sourceArchiveRefusal?: string;/*** Code-structure pre-extraction seeds (P4), present only when the pass was* requested via {@link IngestSourceOptions.preExtract}. `extracted: false`@@ -289,6 +333,11 @@ export function ingestSource(// After the intake, which decided the lane: the derived section reads the// source only in the trusted lane and only at the caller's reach.const derivation = deriveSourceSection(vault, canonicalSource, trust, opts.readable);+ // The durable archive: the trusted-local branch reads its source ONCE,+ // redacts, and persists the bytes BEFORE the page write, so the stamp in+ // the frontmatter below can only land on a page whose evidence is already+ // on disk.+ const archive = captureTrustedSourceArchive(vault, canonicalSource, trust);const withheld = existsSync(absPath) && opts.readable?.(summaryPath) === false;const existed = !withheld && existsSync(absPath);@@ -316,6 +365,16 @@ export function ingestSource(// the digest of the bytes the section was derived from, and its own// keys. Every other source adds nothing....derivation?.frontmatter,+ // Durable evidence: the digest of the archived (redacted) source bytes+ // and their count, ON SUCCESS ONLY. A page whose source was not archived+ // adds nothing, so an unstamped page still reads as exactly "not+ // captured" - absence is a state, never a failure.+ ...(archive.hash !== undefined+ ? {+ [SOURCE_ARCHIVE_HASH_KEY]: archive.hash,+ [SOURCE_ARCHIVE_BYTES_KEY]: archive.bytes,+ }+ : {}),created_at: kept.createdAt,updated_at: stamp,tags: ["brain", "brain/source"],@@ -419,6 +478,10 @@ export function ingestSource(entitiesUpdated: intake.entitiesUpdated,connections,captureScope,+ ...(archive.hash !== undefined+ ? { sourceArchiveHash: archive.hash, sourceArchiveBytes: archive.bytes }+ : {}),+ ...(archive.refusal !== undefined ? { sourceArchiveRefusal: archive.refusal } : {}),...(stagedFields !== undefined ? { staged: true, pendingId: stagedFields.pendingId } : {}),...(intake.deferredRelations !== undefined? { deferredRelations: intake.deferredRelations }@@ -436,6 +499,76 @@ export function ingestSource(*/export const PRE_EXTRACT_MAX_SOURCE_BYTES = 1_048_576;+/** What the trusted-local branch's archive attempt concluded. */+interface ArchiveCapture {+ /** Digest of the persisted (redacted) entry, on success only. */+ readonly hash?: string;+ /** Its UTF-8 byte count, beside the digest. */+ readonly bytes?: number;+ /** The named refusal, when an eligible source could not be archived. */+ readonly refusal?: string;+}++/** May a remote reader read the vault file at this vault-relative path? */+function remotelyReadable(vault: string): (rel: string) => boolean {+ const cache: FrontmatterCache = new Map();+ return (rel) => isPathReadableAtReach(vault, rel, TRANSPORT_REACH.remote, cache);+}++/**+ * The refusal text the capture records. `SourceArchiveError` and+ * `SourceTrustError` carry identifiers and integers only, by contract;+ * anything else reaching this catch is a host fs error whose own message+ * embeds the absolute path the call failed on, so only its errno code (or+ * error class) is kept - the same identifiers-only composition+ * `source-trust`'s refusals use. The refusal rides the ingest result, so+ * it never names a host path.+ */+function archiveRefusalMessage(error: unknown): string {+ if (error instanceof SourceArchiveError || error instanceof SourceTrustError) {+ return error.message;+ }+ return `source archive failed (${errnoCode(error)})`;+}++/**+ * Archive the trusted source's bytes for re-verification, or say why not.+ *+ * Eligibility is the digest's own visibility rule, inherited: a trusted+ * local source whose bytes are withheld from remote readers is never+ * archived, or the archive would make the bytes MORE reachable than the+ * digest that names them (the rule `extract-intake` applies to the content+ * hash). Untrusted and non-local sources are not capture-eligible and+ * behave byte-identically to before this lane existed.+ *+ * The read is the byte-keeping one (`readSourceOrigin`), so the digest and+ * the archived bytes come off ONE descriptor and cannot describe two+ * versions of the source. A capture failure - a past-ceiling refusal, a+ * permission denial, a race with a deleting writer - never fails an ingest+ * that already committed its knowledge: the named refusal is recorded on+ * the result and the page simply stays unstamped.+ */+function captureTrustedSourceArchive(+ vault: string,+ canonicalSource: string,+ trust: IntakeTrust,+): ArchiveCapture {+ if (trust !== INTAKE_TRUST.trusted) return {};+ if (!resolvesInsideVault(vault, canonicalSource)) return {};+ if (isSourceHidden(vault, canonicalSource, remotelyReadable(vault))) return {};+ try {+ const origin = readSourceOrigin(vault, canonicalSource);+ // The silent arm: a vanished source is no longer trusted-local, not a+ // failed capture - so neither stamp nor refusal (absence stays+ // absence; see `sourceArchiveRefusal`'s contract).+ if (origin.bytes === undefined) return {};+ const put = putSourceArchive(vault, origin.bytes);+ return { hash: put.hash, bytes: put.bytes };+ } catch (error) {+ return { refusal: archiveRefusalMessage(error) };+ }+}+/** Why a source read yields no text, apart from a thrown error. */const SOURCE_UNREAD = Object.freeze({notAFile: "not a regular file",diff --git a/src/core/brain/intake/source-trust.ts b/src/core/brain/intake/source-trust.tsindex b3d26859..8abcc8ed 100644--- a/src/core/brain/intake/source-trust.ts+++ b/src/core/brain/intake/source-trust.ts@@ -311,8 +311,13 @@ function isAbsenceErrno(cause: unknown): boolean {return code === ERRNO_NO_SUCH_ENTRY || code === ERRNO_NOT_A_DIRECTORY;}-/** The errno code alone, or the error's class when the kernel named none. */-function errnoCode(cause: unknown): string {+/**+ * The errno code alone, or the error's class when the kernel named none.+ * Exported for sibling refusals that must name a host fs failure without+ * its message: a Node fs error's `message` embeds the absolute path the+ * call failed on, which never crosses a wire surface.+ */+export function errnoCode(cause: unknown): string {const code = (cause as NodeJS.ErrnoException | null)?.code;if (typeof code === "string" && code.length > 0) return code;const name = (cause as Error | null)?.name;diff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.tsindex 64a3a1a2..8109523f 100644--- a/src/core/brain/path-constants.ts+++ b/src/core/brain/path-constants.ts@@ -115,6 +115,24 @@ export const BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_SNAPSHOTS_DIexport const BRAIN_ARTIFACTS_DIR = ".artifacts";export const BRAIN_ARTIFACTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARTIFACTS_DIR);+/**+ * Durable raw-source archive (answer trust): `Brain/.archives/<sha256>.txt`.+ * The ingest trusted-local branch persists the bytes a summary page's+ * knowledge was read from - redacted, content-addressed - so a source whose+ * file later decays can still be re-verified against what the page claimed.+ *+ * Dot-directory so the vault walker excludes it from search/indexing exactly+ * like `.snapshots` and `.artifacts`, and the index-admission predicate+ * refuses it by name besides (its entries are `.txt`, which the `.md` walkers+ * already skip - the stated rule keeps that from being an accident of the+ * extension). Deliberately NOT in {@link BRAIN_SNAPSHOT_EXCLUDED_ENTRIES},+ * unlike `.artifacts`: this is evidence rather than scratch, so a restore+ * must bring the bytes back - the same reading that keeps `.payloads` in the+ * snapshots. There is no TTL; retention is explicit operator pruning.+ */+export const BRAIN_ARCHIVES_DIR = ".archives";+export const BRAIN_ARCHIVES_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARCHIVES_DIR);+/*** Externalized oversized session content (payload registry, t_35440e83):* `Brain/.payloads/<sha256>.txt`. Session import moves data URIs, longdiff --git a/src/core/brain/provenance/source-archive.ts b/src/core/brain/provenance/source-archive.tsnew file mode 100644index 00000000..12808e6e--- /dev/null+++ b/src/core/brain/provenance/source-archive.ts@@ -0,0 +1,408 @@+/**+ * The durable raw-source archive (answer trust, t_9b835c8f).+ *+ * Provenance rots because intake throws the bytes away: a summary page+ * records a digest of the source it was read from, and when the file behind+ * that digest decays nothing can re-verify the page against what it claimed.+ * This store keeps the bytes. The ingest trusted-local branch persists its+ * source here - ONCE, redacted, content-addressed - and stamps the entry's+ * digest on the summary page, so the page carries a pointer to evidence that+ * outlives the source file.+ *+ * The contract, each clause load-bearing:+ *+ * - **Content-addressed.** An entry is `Brain/.archives/<sha256>.txt`,+ * the digest of the persisted bytes. Identical bytes persist once -+ * the address IS the dedup - and a re-ingest of an unchanged source+ * re-lands the same entry it already has.+ * - **Redacted BEFORE persist.** The bytes run through `redactRawOutput`+ * before anything touches disk, so a credential captured in the source+ * never lands in a second file after v1.78-v1.79 taught the rest of the+ * tree to hold credentials in one custody store. The digest is computed+ * over the REDACTED bytes - the address names exactly what is on disk,+ * which is what lets {@link verifySourceArchive} re-hash the file it+ * finds.+ * - **Refused, never truncated.** A past-ceiling input raises+ * {@link SourceArchiveError} and writes nothing: a truncated archive+ * would no longer be the source's bytes, which is the one property it+ * exists to keep (the `CaptureExcerptError` posture beside this module).+ * - **Evidence, not scratch.** No TTL, no prune - the deliberate contrast+ * to the artifact store. Retention is explicit operator pruning, and+ * delete-by-source cleanup drops an entry only when its LAST citing page+ * goes with it.+ * - **Never wider than the page.** The stamp is written only on success,+ * so an unstamped page means exactly "not captured" - absence is a+ * state, never a failure. A source whose bytes are refused to remote+ * readers is never archived at all; the visibility rule the digest+ * already obeys is the one the archive inherits.+ *+ * Paths are built from the {@link BRAIN_ARCHIVES_REL} name constant and the+ * entry filename is a validated 64-hex digest before any join, so a+ * caller-supplied hash cannot traverse out of the store.+ */++import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";+import { join, posix } from "node:path";++import { ensureInsideVault } from "../../path-safety.ts";+import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { redactRawOutput } from "../../redactor.ts";+import { listVaultNotePaths, parseFrontmatter } from "../../vault.ts";+import type { FrontmatterMap } from "../../types.ts";+import { BRAIN_ARCHIVES_REL, BRAIN_PENDING_REL, BRAIN_SOURCES_REL } from "../path-constants.ts";++/**+ * Largest input an archive entry will hold, in UTF-8 bytes: 1 MiB, the+ * `PRE_EXTRACT_MAX_SOURCE_BYTES` ceiling. An archive is a re-verification+ * copy of a source an agent read into a bounded context, not a mirror of+ * the vault; a larger input is refused by {@link SourceArchiveError} rather+ * than truncated, because a truncated archive would no longer be the bytes+ * its address names.+ */+export const ARCHIVE_MAX_BYTES = 1_048_576;++/**+ * An input the store must not hold. The message carries identifiers and+ * integers only - the byte counts and the ceiling - never input text.+ */+export class SourceArchiveError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "SourceArchiveError";+ }+}++/** Shape of an archive entry's filename stem: the digest of its own bytes. */+const ARCHIVE_HASH_RE = /^[0-9a-f]{64}$/;++/** Extension every archive entry carries. */+const ARCHIVE_ENTRY_EXT = ".txt";++/** Is this string shaped like the entry digest the store mints? */+export function isArchiveHash(value: unknown): value is string {+ return typeof value === "string" && ARCHIVE_HASH_RE.test(value);+}++/**+ * The closed vocabulary of an archive verification: what comparing a+ * stamped digest against the entry it names concluded. `missing` and+ * `mismatched` are separate members because "the evidence is gone" and+ * "the evidence disagrees" are different repairs, and a boolean would+ * collapse them. The values cross to the wire - they ride the+ * capture-scope detector's finding evidence and the `archive_get` result -+ * so a member must survive the round trip through a string.+ */+export const ARCHIVE_VERIFICATION = Object.freeze({+ /** The entry is there and re-hashes to exactly the stamped digest. */+ verified: "verified",+ /** The entry is there but its bytes no longer hash to the stamp. */+ mismatched: "mismatched",+ /** No entry answers to the stamp. */+ missing: "missing",+} as const);++/** Closed union over {@link ARCHIVE_VERIFICATION}. */+export type ArchiveVerification = (typeof ARCHIVE_VERIFICATION)[keyof typeof ARCHIVE_VERIFICATION];++/** Membership list, best-news-first. */+export const ARCHIVE_VERIFICATIONS: ReadonlyArray<ArchiveVerification> = Object.freeze(+ Object.values(ARCHIVE_VERIFICATION),+);++/** Narrow a verification read back off a wire payload. */+export function isArchiveVerification(value: unknown): value is ArchiveVerification {+ return (+ typeof value === "string" && (ARCHIVE_VERIFICATIONS as ReadonlyArray<string>).includes(value)+ );+}++/** Frontmatter key of the archive digest stamped on a summary page. */+export const SOURCE_ARCHIVE_HASH_KEY = "source_archive_hash";++/** Frontmatter key of the archived entry's byte count, beside the digest. */+export const SOURCE_ARCHIVE_BYTES_KEY = "source_archive_bytes";++/** The store root: `<vault>/Brain/.archives/`, contained. */+export function sourceArchivesDir(vault: string): string {+ return ensureInsideVault(join(vault, BRAIN_ARCHIVES_REL), vault);+}++/**+ * Vault-relative path of one entry, from its digest - the spelling every+ * wire surface reports, so no host path and no second suffix spelling can+ * drift. The digest is validated before the join.+ */+export function sourceArchiveEntryRel(hash: string): string {+ if (!isArchiveHash(hash)) {+ // The negative branch of the guard narrows a `string` parameter to+ // `never`; widen before quoting so the refusal can still name the+ // argument, truncated, without echoing arbitrary length.+ const shown = String(hash);+ throw new SourceArchiveError(+ `archive entry refused: ${JSON.stringify(shown.slice(0, 72))} is not a 64-hex sha-256 digest`,+ );+ }+ return posix.join(BRAIN_ARCHIVES_REL, `${hash}${ARCHIVE_ENTRY_EXT}`);+}++/**+ * One entry's path. The digest is validated BEFORE the join, so a+ * caller-supplied hash cannot traverse out of the store the way an+ * unvalidated filename could.+ */+export function sourceArchivePath(vault: string, hash: string): string {+ return ensureInsideVault(join(vault, sourceArchiveEntryRel(hash)), vault);+}++/** What {@link putSourceArchive} persisted. */+export interface ArchivePutResult {+ /** Digest of the REDACTED bytes on disk - the entry's address. */+ readonly hash: string;+ /** UTF-8 byte count of the persisted (redacted) entry. */+ readonly bytes: number;+}++/**+ * Redact, then persist, then return the address. Idempotent by+ * construction: the address is the digest of the persisted bytes, so the+ * second put of the same bytes finds its own entry already there and+ * leaves it untouched when it still verifies - one file per distinct+ * source text, however many pages cite it. An entry that no longer+ * verifies (truncated or edited on disk, the state the hygiene scan+ * reports as `mismatched`) is rewritten with the same atomic write: the+ * re-ingest of the source is the natural repair, and skipping the write+ * behind an existing entry would leave the mismatch standing forever.+ *+ * The redaction is the artifact-store posture: the whole input scanned+ * with no scan-window cap (the archive IS the recoverable bytes), and the+ * infra-topology pass on, because a bare internal hostname in a captured+ * source is a likelier leak than a key=value token.+ */+export function putSourceArchive(vault: string, bytes: Uint8Array | string): ArchivePutResult {+ const raw = typeof bytes === "string" ? bytes : Buffer.from(bytes).toString("utf8");+ const redacted = redactRawOutput(raw, { maxInput: Number.POSITIVE_INFINITY, redactInfra: true });+ const persisted = Buffer.from(redacted, "utf8");+ if (persisted.length > ARCHIVE_MAX_BYTES) {+ throw new SourceArchiveError(+ `source archive refused: the redacted source is ${persisted.length} bytes, past the ` ++ `${ARCHIVE_MAX_BYTES}-byte ceiling; nothing was written`,+ );+ }+ const hash = createHash("sha256").update(redacted, "utf8").digest("hex");+ const path = sourceArchivePath(vault, hash);+ if (!existsSync(path)) {+ mkdirSync(sourceArchivesDir(vault), { recursive: true });+ // Identical bytes persist once: the write happens only when no entry+ // with this address is already there, so a re-ingest never churns the+ // entry's mtime (and never doubles it under concurrency - the bytes+ // an idempotent re-land would write are the bytes already on disk).+ atomicWriteFileSync(path, redacted);+ } else if (entryMismatched(path, hash)) {+ // The repair arm: same address, disagreeing bytes. Written with the+ // store's atomic write, so the entry is never observed half-replaced.+ atomicWriteFileSync(path, redacted);+ }+ return { hash, bytes: persisted.length };+}++/**+ * Does the entry file at `path` still hash to the digest it is addressed+ * by? A file that vanished mid-check is no mismatch - there is nothing+ * here to repair, and the next put will find the store empty.+ */+function entryMismatched(path: string, hash: string): boolean {+ const text = readFileSync(path, "utf8");+ return createHash("sha256").update(text, "utf8").digest("hex") !== hash;+}++/** What {@link verifySourceArchive} concluded. */+export interface ArchiveVerificationResult {+ readonly state: ArchiveVerification;+ /** The digest the caller asked about, verbatim. */+ readonly hash: string;+}++/**+ * Re-hash the entry a stamp names and compare. A malformed stamp names no+ * entry the store could hold, so it answers {@link ARCHIVE_VERIFICATION.missing}+ * - the stamp cannot be true - rather than an error; the boundaries that+ * take a hash from a CALLER (not off a page) validate the argument first+ * and refuse it as their own concern.+ */+export function verifySourceArchive(vault: string, hash: string): ArchiveVerificationResult {+ if (!isArchiveHash(hash)) return { state: ARCHIVE_VERIFICATION.missing, hash };+ const entry = readSourceArchiveEntry(vault, hash);+ return entry === null+ ? { state: ARCHIVE_VERIFICATION.missing, hash }+ : { state: entry.state, hash };+}++/** One entry read back: its verification against its own address, and its bytes. */+export interface SourceArchiveEntry {+ /** `verified` or `mismatched` - a read entry is never `missing`. */+ readonly state: ArchiveVerification;+ /** The digest the entry was addressed by, verbatim. */+ readonly hash: string;+ /** UTF-8 byte count of the stored text. */+ readonly bytes: number;+ /** The stored (redacted) text. */+ readonly text: string;+}++/**+ * Read the entry addressed by `hash`: `null` when no such entry exists or+ * the stamp is malformed (the caller decides what a malformed argument+ * deserves), otherwise the stored text with its re-hash verdict attached.+ */+export function readSourceArchiveEntry(vault: string, hash: string): SourceArchiveEntry | null {+ const path = sourceArchivePath(vault, hash);+ if (!existsSync(path)) return null;+ const text = readFileSync(path, "utf8");+ const actual = createHash("sha256").update(text, "utf8").digest("hex");+ return {+ state: actual === hash ? ARCHIVE_VERIFICATION.verified : ARCHIVE_VERIFICATION.mismatched,+ hash,+ bytes: Buffer.byteLength(text, "utf8"),+ text,+ };+}++/** What {@link sourceArchiveStats} measured about the store. */+export interface ArchiveStats {+ /** Entries held: `<64-hex>.txt` regular files, however stale. */+ readonly entries: number;+ /** Their combined size in bytes - the growth number the doctor reports. */+ readonly totalBytes: number;+}++/**+ * Measure the store. Never throws for an absent store - a vault that has+ * never captured a source has an empty one - and counts nothing it does+ * not recognize (a stray non-entry file is not an archive entry).+ */+export function sourceArchiveStats(vault: string): ArchiveStats {+ const root = sourceArchivesDir(vault);+ if (!existsSync(root)) return { entries: 0, totalBytes: 0 };+ let entries = 0;+ let totalBytes = 0;+ for (const name of readdirSync(root).toSorted()) {+ if (!name.endsWith(ARCHIVE_ENTRY_EXT)) continue;+ if (!isArchiveHash(name.slice(0, -ARCHIVE_ENTRY_EXT.length))) continue;+ let size: number;+ try {+ const stat = statSync(join(root, name));+ if (!stat.isFile()) continue;+ size = stat.size;+ } catch {+ continue; // Vanished or unreadable mid-walk: not an entry this run counted.+ }+ entries += 1;+ totalBytes += size;+ }+ return { entries, totalBytes };+}++/**+ * Remove the entry addressed by `hash`, when there is one and nothing else+ * has decided to keep it - the caller owns the last-citing-page question.+ * False when there was nothing to remove; true only when bytes went away.+ */+export function discardSourceArchive(vault: string, hash: string): boolean {+ const path = sourceArchivePath(vault, hash);+ if (!existsSync(path)) return false;+ rmSync(path);+ return true;+}++/**+ * The only pages a stamp is written on: `Brain/sources/` and its staged+ * counterparts under `Brain/pending/`. The citation probe walks exactly+ * these, which makes the one-writer assumption load-bearing: a stamped+ * page anywhere else would cite an entry the probe cannot see. That+ * assumption is architecture, not convention - it is pinned by the+ * source-archive stamp census (`tests/core/architecture/source-archive-+ * stamp-census.test.ts`), which fails by name when a second writer of+ * the `source_archive_hash` key appears outside the ingest lane.+ */+const STAMP_ROOTS: ReadonlyArray<string> = Object.freeze([BRAIN_SOURCES_REL, BRAIN_PENDING_REL]);++/** Visit every stampable page's frontmatter, once per page. */+function walkStampedPages(+ vault: string,+ visit: (root: string, rel: string, meta: FrontmatterMap) => void,+): void {+ for (const root of STAMP_ROOTS) {+ const dir = join(vault, root);+ if (!existsSync(dir)) continue;+ for (const rel of listVaultNotePaths(dir)) {+ const abs = join(dir, rel);+ // `parseFrontmatter` never throws (it reads inside its own try and+ // answers an empty map for a failed read), so a page that will not+ // parse falls out as citing nothing - the fail-safe answer for an+ // entry-removal decision.+ const [meta] = parseFrontmatter(abs);+ visit(root, rel, meta);+ }+ }+}++/**+ * Every ingest summary page stamping `hash` as its archive digest,+ * vault-relative and sorted. The inverse index of the stamp, for the+ * delete path that must remove an entry only when its LAST citing page+ * goes. A staged page counts as citing: rejecting it removes the citation+ * with the page, but publishing it would revive a stamp whose entry must+ * still be there.+ */+export function sourceArchiveCitingPages(vault: string, hash: string): ReadonlyArray<string> {+ const pages: string[] = [];+ walkStampedPages(vault, (root, rel, meta) => {+ if (meta[SOURCE_ARCHIVE_HASH_KEY] === hash) {+ pages.push(posix.join(root, rel.split("\\").join("/")));+ }+ });+ return pages.toSorted();+}++/**+ * The digests of every entry the store holds, sorted - the entry stems of+ * the `<64-hex>.txt` files {@link sourceArchiveStats} counts, so a stray+ * file is never mistaken for an entry and a vanished one is never named.+ */+export function sourceArchiveEntryHashes(vault: string): ReadonlyArray<string> {+ const root = sourceArchivesDir(vault);+ if (!existsSync(root)) return [];+ const hashes: string[] = [];+ for (const name of readdirSync(root)) {+ if (!name.endsWith(ARCHIVE_ENTRY_EXT)) continue;+ const stem = name.slice(0, -ARCHIVE_ENTRY_EXT.length);+ if (!isArchiveHash(stem)) continue;+ try {+ if (!statSync(join(root, name)).isFile()) continue;+ } catch {+ continue; // Vanished or unreadable mid-walk: not an entry this run named.+ }+ hashes.push(stem);+ }+ return hashes.toSorted();+}++/**+ * The store's entries that NO page cites - the leftovers the citation+ * probe cannot reach through a page: a re-stamped page orphans the entry+ * the old stamp named, and a staged ingest rejected by review leaves its+ * entry behind. One walk over the stamp roots builds the set of stamps+ * any page carries, so the verdict is the exact answer the per-entry+ * probe ({@link sourceArchiveCitingPages} empty) would give, without+ * re-walking the pages once per entry. Sorted, so audit output is+ * deterministic.+ */+export function sourceArchiveUncitedHashes(vault: string): ReadonlyArray<string> {+ const cited = new Set<string>();+ walkStampedPages(vault, (_root, _rel, meta) => {+ const value = meta[SOURCE_ARCHIVE_HASH_KEY];+ if (typeof value === "string") cited.add(value);+ });+ return sourceArchiveEntryHashes(vault).filter((hash) => !cited.has(hash));+}diff --git a/src/core/brain/session-recall.ts b/src/core/brain/session-recall.tsindex 5dd1a66f..ed1c8d2d 100644--- a/src/core/brain/session-recall.ts+++ b/src/core/brain/session-recall.ts@@ -10,6 +10,8 @@ import {} from "./continuity/store.ts";import {CONTINUITY_AGENT_ID_KEY,+ CONTINUITY_SESSION_ID_KEY,+ type ContinuityPayload,type ContinuityRecord,type ContinuitySourceRef,} from "./continuity/types.ts";@@ -188,6 +190,21 @@ const DEFAULT_GROUP_SIZE = 8;const DEFAULT_LIMIT = 10;const DEFAULT_SNIPPET_CHARS = 160;+/**+ * The session id a continuity payload names, or `undefined` when it names+ * no session: the key absent, a non-string value, or the empty string+ * (t_22d58fa7). Absence stays absence - the reader-side reading of the+ * orphan-session precedent, where `session:unknown` is a statement that+ * there was no session rather than a pointer to a missing one. The+ * `String(... ?? "")` coercion this replaces manufactured both a phantom+ * `""` identity for unattributed records and a string match for a+ * non-string one.+ */+export function sessionIdOf(payload: ContinuityPayload): string | undefined {+ const value = payload[CONTINUITY_SESSION_ID_KEY];+ return typeof value === "string" && value.length > 0 ? value : undefined;+}+export function importSessionRecall(vault: string,input: ImportSessionRecallInput,@@ -574,7 +591,15 @@ function sessionRecallRecords(let scoped = records;if (sessionId !== undefined) {const scope = lineageScope(vault, records, sessionId);- scoped = records.filter((record) => scope.has(String(record.payload["session_id"] ?? "")));+ // A record naming no session is excluded from a scoped read: the scope+ // set only ever holds real ids (the lineage ledger omits blank+ // declarations), so matching against a coerced "" or a stringified+ // non-string could only ever exclude by accident or match by invention.+ // Unscoped reads still return the record.+ scoped = records.filter((record) => {+ const sid = sessionIdOf(record.payload);+ return sid !== undefined && scope.has(sid);+ });}return scoped.sort((left, right) => compareRecords(left, right));}diff --git a/src/core/brain/session-summary.ts b/src/core/brain/session-summary.tsindex b089937f..941855df 100644--- a/src/core/brain/session-summary.ts+++ b/src/core/brain/session-summary.ts@@ -36,6 +36,7 @@ import { createHash } from "node:crypto";import { compositeScopeKey } from "../scope-key.ts";import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";+import { sessionIdOf } from "./session-recall.ts";import { resolveSessionScope, SessionScopeError } from "./session-scope.ts";export class SessionSummaryError extends Error {@@ -67,7 +68,14 @@ export interface SessionSummaryInput {export interface SessionSummaryDigest {readonly id: string;- readonly sessionId: string;+ /**+ * The session the digest is scoped to, presence-gated (t_22d58fa7):+ * omitted when the record names no session - the key absent, a+ * non-string value, or the empty string. Absence stays absence; the+ * `String(... ?? "")` coercion this replaces manufactured a `""`+ * identity no writer ever stamped.+ */+ readonly sessionId?: string;readonly request: string | null;readonly decisions: ReadonlyArray<string>;readonly learnings: ReadonlyArray<string>;@@ -239,8 +247,11 @@ export function getSessionSummaryReport(sessionId: string,): SessionSummaryReport | null {const id = sessionId.trim();+ // A record naming no session is skipped, never matched: the reads used+ // to coerce the missing key to "" and answer a `""`-scoped read with+ // every unrelated no-session digest lumped into one phantom session.const records = sessionDigestRecords(vault).filter(- (record) => String(record.payload["session_id"] ?? "") === id,+ (record) => sessionIdOf(record.payload) === id,);if (records.length === 0) return null;const revisions = records.length;@@ -335,9 +346,10 @@ export function listSessionSummaries(const project = normalizeProject(opts.project);return Object.freeze(sessionDigestRecords(vault)- .filter(- (record) => scope === undefined || String(record.payload["session_id"] ?? "") === scope,- )+ // Same skip-not-match rule as the single-session read: a record+ // naming no session is not in the asked-for session, and a coerced+ // "" must never make it look like it is.+ .filter((record) => scope === undefined || sessionIdOf(record.payload) === scope).filter((record) => project === undefined || readProject(record.payload) === project).map(toDigest),);@@ -370,9 +382,10 @@ function toDigest(record: ContinuityRecord): SessionSummaryDigest {const payload = record.payload;const host = typeof payload["host"] === "string" ? (payload["host"] as string) : undefined;const project = readProject(payload);+ const sessionId = sessionIdOf(payload);return Object.freeze({id: record.id,- sessionId: String(payload["session_id"] ?? ""),+ ...(sessionId !== undefined ? { sessionId } : {}),request: typeof payload["request"] === "string" ? (payload["request"] as string) : null,decisions: readList(payload["decisions"]),learnings: readList(payload["learnings"]),diff --git a/src/core/brain/truth/claim-provenance.ts b/src/core/brain/truth/claim-provenance.tsnew file mode 100644index 00000000..845ad602--- /dev/null+++ b/src/core/brain/truth/claim-provenance.ts@@ -0,0 +1,346 @@+/**+ * Read-only claim-to-provenance join (answer-trust, tasks B3/B6).+ *+ * A claim's optional `sample_id` names the recall/context-pack+ * quality-sample the claim was stated against - usually a context+ * receipt id, sometimes an opaque request hash. This module resolves+ * that id at READ time by composing the existing readers:+ *+ * - receipt items, by receipt id (`listContextReceipts`);+ * - the outcome row posted against the sample (`listContextPackOutcomes`),+ * with the evidence verdict recorded beside it+ * (`listContextPackEvidence`).+ *+ * Omit-don't-invent governs every half. A sample id with a receipt but+ * no outcome row is "receipt known, outcome unknown": the outcome field+ * is null and no caller may fabricate a verdict for it. The same honesty+ * extends to "receipt unreadable": a receipt record whose `created_at`+ * fails the canonical-timestamp check (the continuity reader validates+ * that stamp on append only, so a hand-edited or foreign-synced shard+ * can carry one no append would accept) is skipped at index load, and a+ * claim naming it answers "receipt unknown" instead of failing the whole+ * read. A claim timestamped BEFORE its claimed receipt's `created_at`+ * carries an inversion flag instead of being silently joined - a receipt+ * the claim predates cannot have informed it.+ *+ * The module performs NO vault writes and imports no continuity append+ * path; the claim-attribution census pins that invariant+ * architecturally. It reads through the existing readers at their+ * existing visibility and widens nothing: a receipt whose record is+ * private or redacted is reported KNOWN but its items are never+ * unfolded (the receipts-fold rule), so redacted content cannot+ * re-enter the vault through a claim's provenance. What the caller may+ * not see at its reach arrives as the caller's own filters - the same+ * `exclude` / `excludeItem` hooks the receipts list and fold take - so+ * the join never needs transport vocabulary of its own.+ *+ * The sample id is OPAQUE throughout: echoed verbatim, never+ * normalized, never logged beside answer or source text.+ */++import { listContextPackEvidence } from "../context-pack-evidence.ts";+import { listContextPackOutcomes } from "../context-pack-outcome.ts";+import { isContextReceiptTrigger, listContextReceipts } from "../context-receipts.ts";+import { isCanonicalUtcTimestamp } from "../continuity/store.ts";+import type { ContinuityRecord } from "../continuity/types.ts";++/** One injected item a claimed receipt accounts for. */+export interface ClaimProvenanceReceiptItem {+ readonly id: string;+ /** Vault-relative path, when the receipt recorded one. */+ readonly path?: string;+ /** Whether the receipt recorded the item as trimmed, when recorded. */+ readonly trimmed?: boolean;+}++/**+ * The receipt half of the join: what the claimed sample injected.+ * `items` is empty exactly when `withheld` is true - a private or+ * redacted receipt is known but never unfolded.+ */+export interface ClaimProvenanceReceipt {+ readonly id: string;+ readonly created_at: string;+ readonly trigger: string | null;+ readonly items: ReadonlyArray<ClaimProvenanceReceiptItem>;+ readonly withheld: boolean;+}++/** The outcome half of the join: what the sample led to. */+export interface ClaimProvenanceOutcome {+ readonly id: string;+ readonly created_at: string;+ /**+ * The row's own first-pass verdict. Null when the row carries no+ * boolean - a hand-edited or forward-compat row renders unknown,+ * never a coerced "failed".+ */+ readonly first_pass_success: boolean | null;+ /** The evidence row's verdict for this sample, when that row exists. */+ readonly evidence_verdict?: string;+}++/** The resolved provenance for one claim's `sample_id`. */+export interface ClaimProvenance {+ /** The claim's sample id, verbatim (opaque). */+ readonly sample_id: string;+ /** Null when no receipt names this id: the receipt half is unknown. */+ readonly receipt: ClaimProvenanceReceipt | null;+ /**+ * Null when no outcome row was posted against this id - "receipt+ * known, outcome unknown" when the receipt half is present. Never a+ * fabricated verdict.+ */+ readonly outcome: ClaimProvenanceOutcome | null;+ /** True when the claim's assertion ts predates its claimed receipt. */+ readonly timestamp_inverted: boolean;+}++/**+ * What the caller may not see, as filters rather than as a reach level.+ * Both hooks take the shape the receipts list and receipts fold already+ * define, so a surface binds its transport's rules once and the join+ * stays reach-blind.+ */+export interface ClaimProvenanceOptions {+ /**+ * Receipts the caller may not see at all. An excluded receipt renders+ * as the unknown-id answer - `receipt` is null, exactly as a store+ * without that receipt answers - never a `withheld` marker that would+ * confirm the receipt exists.+ */+ readonly exclude?: (record: ContinuityRecord) => boolean;+ /**+ * Receipt items the caller may not see. They leave the unfolded items+ * before the answer is built, so a claim's provenance never discloses+ * an item the caller could not read at its reach.+ */+ readonly excludeItem?: (item: unknown) => boolean;+}++/**+ * The three ledgers the join composes, read once and indexed for many+ * resolutions. The maps keep, per key, the same record the filtered+ * list functions answer first - they list newest-first, so the index is+ * built newest-wins - making an indexed resolution row-for-row the+ * single-call answer. Hydrating a page of claims through one index+ * costs one read per ledger instead of three full-ledger reads per+ * claim.+ */+export interface ClaimProvenanceIndex {+ /** Receipts by their record id (the receiptId lookup's key). */+ readonly receiptsByReceiptId: ReadonlyMap<string, ContinuityRecord>;+ /** Outcome rows by the sample id their payload posts against. */+ readonly outcomesBySampleId: ReadonlyMap<string, ContinuityRecord>;+ /** Evidence rows by the sample id their payload posts against. */+ readonly evidenceBySampleId: ReadonlyMap<string, ContinuityRecord>;+}++/**+ * Read each provenance ledger once and index it. Newest-wins per key:+ * the list functions answer newest-first, so the FIRST record under a+ * key is the one a filtered lookup returns, and later (older) records+ * under the same key never displace it. A receipt record whose+ * `createdAt` is not canonical UTC is UNREADABLE, never merely+ * uninverting: the continuity reader validates that stamp on append+ * only, so a hand-edited or foreign-synced shard can carry one no+ * append would accept. Skipping it here degrades PER CLAIM - the claim+ * naming it answers "receipt unknown", exactly as an absent id would -+ * instead of failing the whole events read for every unrelated claim on+ * the page.+ */+export function loadClaimProvenanceIndex(vault: string): ClaimProvenanceIndex {+ const receiptsByReceiptId = newestWinsById(listContextReceipts(vault), (record) =>+ isCanonicalUtcTimestamp(record.createdAt) ? record.id : null,+ );+ const outcomesBySampleId = newestWinsById(listContextPackOutcomes(vault), (record) =>+ payloadSampleId(record),+ );+ const evidenceBySampleId = newestWinsById(listContextPackEvidence(vault), (record) =>+ payloadSampleId(record),+ );+ return { receiptsByReceiptId, outcomesBySampleId, evidenceBySampleId };+}++function payloadSampleId(record: ContinuityRecord): string | null {+ const sampleId = record.payload["sample_id"];+ return typeof sampleId === "string" ? sampleId : null;+}++/**+ * Index one newest-first record list by key, keeping the first record+ * under each key - the same record a filtered lookup answers first.+ */+function newestWinsById(+ records: ReadonlyArray<ContinuityRecord>,+ keyOf: (record: ContinuityRecord) => string | null,+): ReadonlyMap<string, ContinuityRecord> {+ const index = new Map<string, ContinuityRecord>();+ for (const record of records) {+ const key = keyOf(record);+ if (key === null || index.has(key)) continue;+ index.set(key, record);+ }+ return index;+}++function receiptItems(+ record: ContinuityRecord,+ excludeItem: ((item: unknown) => boolean) | undefined,+): ReadonlyArray<ClaimProvenanceReceiptItem> {+ const stored = record.payload["items"];+ if (!Array.isArray(stored)) return [];+ const visible = excludeItem === undefined ? stored : stored.filter((item) => !excludeItem(item));+ const items: ClaimProvenanceReceiptItem[] = [];+ for (const raw of visible) {+ if (raw === null || typeof raw !== "object") continue;+ const item = raw as Record<string, unknown>;+ const id = item["id"];+ if (typeof id !== "string" || id === "") continue;+ const path = item["path"];+ const trimmed = item["trimmed"];+ items.push(+ Object.freeze({+ id,+ ...(typeof path === "string" && path !== "" ? { path } : {}),+ ...(typeof trimmed === "boolean" ? { trimmed } : {}),+ }),+ );+ }+ return Object.freeze(items);+}++function joinReceipt(+ record: ContinuityRecord,+ excludeItem: ((item: unknown) => boolean) | undefined,+): ClaimProvenanceReceipt {+ const withheld = record.private || record.redacted;+ return Object.freeze({+ id: record.id,+ created_at: record.createdAt,+ trigger: isContextReceiptTrigger(record.payload["trigger"]) ? record.payload["trigger"] : null,+ // A withheld receipt stays known but is never unfolded, so its item+ // list cannot carry private content back to the reader.+ items: withheld ? Object.freeze([]) : receiptItems(record, excludeItem),+ withheld,+ });+}++function joinOutcome(+ record: ContinuityRecord,+ evidence: ContinuityRecord | undefined,+): ClaimProvenanceOutcome {+ // The evidence verdict is read off its own row, joined on the same+ // sample id; absent when no evidence row exists - never inferred from+ // the outcome row.+ const evidenceVerdict = evidence?.payload["verdict"];+ // Omit-don't-invent: a row without its own boolean renders unknown -+ // null - never a coerced "false" inventing a failed verdict for a row+ // that said nothing (review L2.3).+ const firstPassSuccess = record.payload["first_pass_success"];+ return Object.freeze({+ id: record.id,+ created_at: record.createdAt,+ first_pass_success: typeof firstPassSuccess === "boolean" ? firstPassSuccess : null,+ ...(typeof evidenceVerdict === "string" ? { evidence_verdict: evidenceVerdict } : {}),+ });+}++/**+ * Resolve one claim's `sample_id` from a prebuilt {@link ClaimProvenanceIndex}.+ *+ * The row-for-row equivalent of {@link resolveClaimProvenance} at a+ * fraction of the cost whenever more than a claim or two needs+ * resolving: one index build (one read per ledger) covers every+ * resolution taken from it.+ *+ * @throws when `sampleId` is blank - the same never-coerced discipline+ * the write boundary applies, so silence can never read as an answer.+ * The inversion compare runs on parsed instants, and both sides+ * reaching it are validated canonical first: the claim store validates+ * the claim ts on read, and this module's index admits only receipt+ * records whose `createdAt` passes the canonical-timestamp check (the+ * continuity reader validates that stamp on APPEND only, so a+ * hand-edited shard could otherwise fail the whole read here). A+ * receipt that fails the check is unreadable, and the claim naming it+ * answers "receipt unknown" instead of throwing.+ */+export function resolveClaimProvenanceFromIndex(+ index: ClaimProvenanceIndex,+ sampleId: string,+ claimTs: string,+ options?: ClaimProvenanceOptions,+): ClaimProvenance {+ if (sampleId.trim() === "") {+ throw new Error("claim provenance: sample_id must be a non-empty string");+ }+ let receiptRecord = index.receiptsByReceiptId.get(sampleId) ?? null;+ if (receiptRecord !== null && options?.exclude !== undefined && options.exclude(receiptRecord)) {+ // The excluded receipt is not the caller's answer at all: a store+ // without it answers "no receipt names this id", so the receipt+ // half renders unknown - never a marker confirming it exists.+ receiptRecord = null;+ }+ const outcomeRecord = index.outcomesBySampleId.get(sampleId) ?? null;+ // The evidence row joins on the same sample id: the outcome record was+ // indexed under the id its payload posts against, so re-reading that+ // payload here could only ever return the id already in hand.+ const outcomeEvidence =+ outcomeRecord === null ? undefined : index.evidenceBySampleId.get(sampleId);+ return Object.freeze({+ sample_id: sampleId,+ ...(receiptRecord !== null+ ? { receipt: joinReceipt(receiptRecord, options?.excludeItem) }+ : { receipt: null }),+ ...(outcomeRecord !== null+ ? { outcome: joinOutcome(outcomeRecord, outcomeEvidence) }+ : { outcome: null }),+ timestamp_inverted:+ receiptRecord !== null &&+ stampInstant("claim", claimTs) < stampInstant("receipt", receiptRecord.createdAt),+ });+}++/**+ * Resolve one claim's `sample_id` to its receipt and outcome halves.+ *+ * `claimTs` is the claim's canonical UTC assertion timestamp, compared+ * against the receipt's `created_at` as PARSED INSTANTS. The lexical+ * compare this replaces mis-orders a sub-second claim stamp against a+ * second-precision receipt stamp - `...:00.500Z` sorts before `...:00Z`+ * because "." < "Z" - and flagged a claim written half a second after+ * its receipt as inverted. Strict: a claim AT its receipt's instant was+ * informed by it; only a claim written BEFORE the receipt existed is an+ * inversion.+ */+export function resolveClaimProvenance(+ vault: string,+ sampleId: string,+ claimTs: string,+ options?: ClaimProvenanceOptions,+): ClaimProvenance {+ return resolveClaimProvenanceFromIndex(+ loadClaimProvenanceIndex(vault),+ sampleId,+ claimTs,+ options,+ );+}++/**+ * Parse one side of the inversion compare into its instant, refusing a+ * stamp that has none. Both sides reaching here were validated canonical+ * before the compare - the claim ts by the claim store's read boundary,+ * the receipt's `created_at` by the index admission check - so a parse+ * failure names the side whose ledger is corrupt rather than answering+ * the compare with `NaN`'s silent "false".+ */+function stampInstant(side: string, ts: string): number {+ const instant = Date.parse(ts);+ if (Number.isNaN(instant)) {+ throw new Error(+ `claim provenance: ${side} timestamp is not a parseable UTC instant: ${JSON.stringify(ts)}`,+ );+ }+ return instant;+}diff --git a/src/core/brain/truth/stated-claims.ts b/src/core/brain/truth/stated-claims.tsindex b9dc3c3a..0aad4c14 100644--- a/src/core/brain/truth/stated-claims.ts+++ b/src/core/brain/truth/stated-claims.ts@@ -36,7 +36,12 @@ import { anchorEntityForms, type AtomicEntityLike } from "../atomic-facts.ts";import { normalizeEntityName, type EntityLexiconHandle } from "../entities/canonical.ts";import { resolveEntityLexicon } from "../entities/lexicon.ts";import type { AppendClaimInput, AppendClaimResult } from "./store.ts";-import { appendClaimEvent, ISO_UTC_TS_RE } from "./store.ts";+import {+ appendClaimEvent,+ ISO_UTC_TS_RE,+ isValidClaimSampleId,+ SAMPLE_ID_MAX_LENGTH,+} from "./store.ts";import type { ClaimExtractor } from "./types.ts";/** How this release tags agent-stated claims. */@@ -59,6 +64,17 @@ export interface StatedClaimsPayload {readonly ts: string;/** Provenance wikilink or vault-relative path. */readonly source: string;+ /**+ * Optional attribution id (answer-trust, task B2): the recall/+ * context-pack quality-sample id these claims were stated against.+ * Trimmed and shape-checked when present - non-empty, at most 256+ * characters, no control characters; anything else is a named+ * refusal, never coerced to absent - and threaded trimmed onto every+ * committed event as `sample_id` (the store stores the same trimmed+ * form). Opaque: treated as an opaque token end to end and never+ * logged beside answer or source text.+ */+ readonly sampleId?: string;}export interface StatedClaimsOptions {@@ -187,6 +203,19 @@ export function appendStatedClaims(`stated claims: ts must be canonical ISO-8601 UTC: ${JSON.stringify(payload.ts)}`,);}+ // Sample id (answer-trust, task B2): presence-gated, part of the+ // whole-call promise. The value is trimmed and must pass the same+ // shape check the store append applies - non-empty, at most 256+ // characters, no control characters (review L2.1) - so an unacceptable+ // id refuses HERE, before the first write, through the typed refusal+ // channel like the agent and ts checks above, never coerced to absent+ // and never surfacing mid-loop as the store's plain error.+ const sampleId = payload.sampleId === undefined ? undefined : payload.sampleId.trim();+ if (sampleId !== undefined && !isValidClaimSampleId(sampleId)) {+ throw new StatedClaimsRefusal(+ `stated claims: sample_id must be a non-empty string of at most ${SAMPLE_ID_MAX_LENGTH} characters without control characters`,+ );+ }const entities = opts.entities ?? [];// The same store-learned lexicon the creation gate resolves (fail-open@@ -211,6 +240,7 @@ export function appendStatedClaims(value: claim.object.trim(),extractor: AGENT_STATED,source,+ ...(sampleId !== undefined ? { sample_id: sampleId } : {}),};committed.push(appendClaimEvent(vault, input, {diff --git a/src/core/brain/truth/store.ts b/src/core/brain/truth/store.tsindex 95d2c54a..4977ec43 100644--- a/src/core/brain/truth/store.ts+++ b/src/core/brain/truth/store.ts@@ -65,6 +65,29 @@ import { assertVaultIdentityForWrite } from "../vault-identity.ts";/** Default cap on retained claim events (explicit sweep only). */export const CLAIM_EVENT_MAX_COUNT = 10000;+/**+ * Cap on a caller-supplied `sample_id` (answer-trust review L2.1): the+ * id is copied onto every claim stated against the sample, so an+ * unbounded one could multiply one call's payload across the whole+ * ledger.+ */+export const SAMPLE_ID_MAX_LENGTH = 256;++/** Control characters (C0 plus DEL) an opaque sample id may not carry. */+const SAMPLE_ID_CONTROL_CHARS_RE = /[\u0000-\u001F\u007F]/;++/**+ * Whether a TRIMMED `sample_id` is acceptable at the write boundary:+ * non-empty, at most {@link SAMPLE_ID_MAX_LENGTH} characters, and free+ * of control characters. Shared by the store append and the stated+ * boundary so both surfaces refuse identically.+ */+export function isValidClaimSampleId(value: string): boolean {+ return (+ value !== "" && value.length <= SAMPLE_ID_MAX_LENGTH && !SAMPLE_ID_CONTROL_CHARS_RE.test(value)+ );+}+// Same canonical UTC shape the log writer emits; see ISO_UTC_TS_RE in// log-jsonl.ts for why this stays strict.export const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;@@ -214,6 +237,18 @@ export interface AppendClaimInput {* compatibility.*/readonly extractor?: ClaimExtractor;+ /**+ * Presence-gated attribution id (schema v1): the caller-supplied+ * recall/context-pack quality-sample id this claim was stated against.+ * Opaque - stored TRIMMED (the same normalization the stated-claims+ * path applies, so a threaded id and its stored form always match),+ * never otherwise normalized, never logged beside answer or source+ * text. A present-but-blank, over-long or control-character-bearing+ * value refuses the append by name (a blank id means nothing and is+ * not coerced to absent); an absent one serializes nothing,+ * byte-identical to the pre-attribution ledger.+ */+ readonly sample_id?: string;readonly source: string;}@@ -305,6 +340,18 @@ export function appendClaimEvent(if (input.extractor !== undefined && input.extractor !== "agent_stated") {throw new Error(`claim extractor must be agent_stated: ${JSON.stringify(input.extractor)}`);}+ // Sample id (answer-trust, task B1): presence-gated, opaque, stored+ // TRIMMED - the same normalization the stated path applies - so a+ // threaded id and its stored form always match and the provenance join+ // resolves what was threaded. A present-but-blank, over-long or+ // control-character-bearing value refuses the append by name, naming+ // the cap (review L2.1); an absent one serializes nothing.+ const sampleId = input.sample_id === undefined ? undefined : input.sample_id.trim();+ if (sampleId !== undefined && !isValidClaimSampleId(sampleId)) {+ throw new Error(+ `claim sample_id must be a non-empty string of at most ${SAMPLE_ID_MAX_LENGTH} characters without control characters`,+ );+ }const event: ClaimEvent = Object.freeze({v: TRUTH_SCHEMA_VERSION,@@ -319,6 +366,7 @@ export function appendClaimEvent(...(resolved.validUntil !== undefined ? { validUntil: resolved.validUntil } : {}),source: input.source.trim(),...(input.extractor !== undefined ? { extractor: input.extractor } : {}),+ ...(sampleId !== undefined ? { sample_id: sampleId } : {}),});mkdirSync(truthDir(vault), { recursive: true });@@ -515,6 +563,19 @@ function coerceClaim(return null;}const extractor = rawExtractor as ClaimExtractor | undefined;+ // Sample id (answer-trust, task B1): tolerated when absent (old+ // lines), validated as a non-empty string when present, passed through+ // verbatim - the id is opaque. Annotation only.+ const rawSampleId = obj["sample_id"];+ if (rawSampleId !== undefined && (typeof rawSampleId !== "string" || rawSampleId.trim() === "")) {+ warnings.push({+ path,+ lineNumber,+ message: `invalid claim sample_id: ${String(rawSampleId)}`,+ });+ return null;+ }+ const sampleId = rawSampleId as string | undefined;return Object.freeze({v: TRUTH_SCHEMA_VERSION,ts,@@ -528,6 +589,7 @@ function coerceClaim(...(validUntil !== undefined ? { validUntil } : {}),...(extractor !== undefined ? { extractor } : {}),source: obj["source"] as string,+ ...(sampleId !== undefined ? { sample_id: sampleId } : {}),});}diff --git a/src/core/brain/truth/types.ts b/src/core/brain/truth/types.tsindex a8cc336a..55460857 100644--- a/src/core/brain/truth/types.ts+++ b/src/core/brain/truth/types.ts@@ -67,6 +67,18 @@ export interface ClaimEvent {* contest, never re-ranks conflict priority, and never resolves one.*/readonly extractor?: ClaimExtractor;+ /**+ * Presence-gated attribution id (schema v1): the caller-supplied+ * recall/context-pack quality-sample id this claim was stated against+ * (a context-receipt id or an opaque request hash). Opaque and frozen+ * trimmed at write (the store-level trim the stated path threads);+ * the claim-to-outcome join resolves it at read time+ * (`claim-provenance.ts`). Absent on every line written before the+ * field existed, and omitted - never invented - when the caller+ * supplies none. Annotation only: the id never changes which pairs+ * contest, and it is never logged beside answer or source text.+ */+ readonly sample_id?: string;/** Provenance wikilink or vault-relative path. */readonly source: string;}diff --git a/src/core/config.ts b/src/core/config.tsindex f076fd84..e51414b9 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -19,6 +19,9 @@ import { isSecretReferenceValue, SecretReferenceError } from "./secret-ref.ts";import { APP_DIR_NAME, configBaseDir } from "./platform-dirs.ts";import { resolveActiveProfileVault } from "./brain/portability/profiles.ts";import { resolvePointerVault } from "./brain/portability/pointer.ts";+import { parseBrainYaml } from "./brain/yaml-parse.ts";+import { BrainConfigError } from "./brain/policy/errors.ts";+import { BRAIN_CONFIG_FILE, BRAIN_ROOT_REL } from "./brain/path-constants.ts";import {isWikiLinkFormat,WIKI_LINK_FORMATS,@@ -1190,6 +1193,185 @@ export function resolveRecallInjectEnabled(configPath?: string): boolean {);}+/**+ * The per-phase answer-time quote-check modes (answer-trust wave, Lane A).+ *+ * Three keys - `quote_check.recall`, `quote_check.active`,+ * `quote_check.subagent` - live in the `quote_check` block of+ * `Brain/_brain.yaml`, each `off|shadow|enforce`, default `shadow`, each+ * with its own resolver and no second reader. The shape follows the+ * decision-model per-use mode switch+ * (`src/core/decision-model/contract.ts`, `DECISION_MODEL_MODES`).+ *+ * Channel honesty: the Stop hook's annotation renders on Claude Code+ * only. The other registered runtimes render no Stop annotation - and+ * grok ships no `transcript_path` at all - so there the check is+ * silently inert, and a non-`off` mode promises findings that only a+ * Claude Code session (or the `enforce` Brain-log trail, where a+ * transcript is read at all) delivers.+ */+export const ANSWER_QUOTE_CHECK_MODES = Object.freeze(["off", "shadow", "enforce"] as const);++/** Closed union over {@link ANSWER_QUOTE_CHECK_MODES}. */+export type AnswerQuoteCheckMode = (typeof ANSWER_QUOTE_CHECK_MODES)[number];++/** Narrow a mode read back off a payload or a fixture. */+export function isAnswerQuoteCheckMode(value: unknown): value is AnswerQuoteCheckMode {+ return (+ typeof value === "string" && (ANSWER_QUOTE_CHECK_MODES as ReadonlyArray<string>).includes(value)+ );+}++/** The `_brain.yaml` block the three keys live in, and its phase keys. */+const QUOTE_CHECK_BLOCK = "quote_check";++/** The phases the quote check runs on, in their pinned listing order. */+export const ANSWER_QUOTE_CHECK_PHASES = Object.freeze(["recall", "active", "subagent"] as const);++/** Closed union over {@link ANSWER_QUOTE_CHECK_PHASES}. */+export type AnswerQuoteCheckPhase = (typeof ANSWER_QUOTE_CHECK_PHASES)[number];++/** The mode every phase resolves to when nothing is configured. */+const QUOTE_CHECK_DEFAULT: AnswerQuoteCheckMode = "shadow";++/** Paths and keys whose unknown-field warning already fired in this process. */+const quoteCheckWarnedUnknownKeys = new Set<string>();++/**+ * The `quote_check` block parsed off `path`, or `null` when the file or+ * the block is absent - the one condition resolved to defaults, because+ * there are no operator settings to contradict. A file (or block) that+ * EXISTS but cannot be honored raises by name instead: read like+ * `loadBrainConfig`'s absent/present split, so a typo can never silently+ * turn a configured `enforce` into the default.+ */+function readQuoteCheckBlock(path: string): Record<string, unknown> | null {+ let stat: Stats;+ try {+ const probed = statSync(path, { throwIfNoEntry: false });+ if (probed === undefined) return null;+ stat = probed;+ } catch (err) {+ throw new BrainConfigError(+ `failed to stat: ${(err as Error).message}`,+ QUOTE_CHECK_BLOCK,+ path,+ );+ }+ if (!stat.isFile()) {+ throw new BrainConfigError(+ "path exists but is not a regular file; its settings are not in force and are not read as absent",+ QUOTE_CHECK_BLOCK,+ path,+ );+ }+ let parsed: Record<string, unknown>;+ try {+ parsed = parseBrainYaml(+ new TextDecoder("utf-8", { fatal: true }).decode(readFileSync(path)),+ ) as Record<string, unknown>;+ } catch (err) {+ throw new BrainConfigError(+ `failed to parse: ${(err as Error).message}`,+ QUOTE_CHECK_BLOCK,+ path,+ );+ }+ const block = parsed[QUOTE_CHECK_BLOCK];+ if (block === undefined) return null;+ if (typeof block !== "object" || block === null || Array.isArray(block)) {+ throw new BrainConfigError(+ `expected a block of per-phase modes, got ${Array.isArray(block) ? "an array" : typeof block}`,+ QUOTE_CHECK_BLOCK,+ path,+ );+ }+ return block as Record<string, unknown>;+}++/**+ * Unknown keys inside the `quote_check` block warn per the strict-block+ * convention (`warnUnknownKeys` in the policy validator), once per key+ * per process on stderr - the audit channel every consumer of these+ * resolvers (the Stop hook) already keeps. A warning never changes the+ * resolved mode.+ */+function warnUnknownQuoteCheckKeys(path: string, block: Record<string, unknown>): void {+ for (const key of Object.keys(block)) {+ if ((ANSWER_QUOTE_CHECK_PHASES as ReadonlyArray<string>).includes(key)) continue;+ const stamp = `${path}\0${key}`;+ if (quoteCheckWarnedUnknownKeys.has(stamp)) continue;+ quoteCheckWarnedUnknownKeys.add(stamp);+ process.stderr.write(`${QUOTE_CHECK_BLOCK}.${key}: unknown field ignored (forward-compat)\n`);+ }+}++/** One phase's mode off the block; every exported resolver is this read. */+function resolveAnswerQuoteCheckPhase(+ phase: AnswerQuoteCheckPhase,+ path: string | null,+): AnswerQuoteCheckMode {+ if (path === null) return QUOTE_CHECK_DEFAULT;+ const block = readQuoteCheckBlock(path);+ if (block === null) return QUOTE_CHECK_DEFAULT;+ warnUnknownQuoteCheckKeys(path, block);+ const raw = block[phase];+ if (raw === undefined) return QUOTE_CHECK_DEFAULT;+ if (!isAnswerQuoteCheckMode(raw)) {+ throw new BrainConfigError(+ `unsupported value ${JSON.stringify(raw)}; expected one of ${ANSWER_QUOTE_CHECK_MODES.join(+ ", ",+ )}`,+ `${QUOTE_CHECK_BLOCK}.${phase}`,+ path,+ );+ }+ return raw;+}++/**+ * The brain config file the resolvers read when the caller names none:+ * the standard vault's `Brain/_brain.yaml`. `null` when no vault+ * resolves, which leaves every phase at its default - a vaultless install+ * has no operator settings to contradict.+ */+function defaultAnswerQuoteCheckConfigPath(): string | null {+ const vault = resolveVault();+ return vault === null ? null : join(vault, BRAIN_ROOT_REL, BRAIN_CONFIG_FILE);+}++/**+ * Mode of `quote_check.recall` (answer-trust wave, Lane A): whether the+ * Stop hook checks quoted spans against recall-injected notes, and what+ * it may do about them. See {@link resolveAnswerQuoteCheckPhase} for the+ * shared semantics; the hook additionally gates this phase on+ * {@link resolveRecallInjectEnabled}.+ */+export function resolveAnswerQuoteCheckRecall(configPath?: string): AnswerQuoteCheckMode {+ return resolveAnswerQuoteCheckPhase("recall", configPath ?? defaultAnswerQuoteCheckConfigPath());+}++/**+ * Mode of `quote_check.active`: the same check over the notes the+ * SessionStart active digest emitted. The hook gates this phase on a live+ * active-injection ledger (`osb.active_inject.emitted`).+ */+export function resolveAnswerQuoteCheckActive(configPath?: string): AnswerQuoteCheckMode {+ return resolveAnswerQuoteCheckPhase("active", configPath ?? defaultAnswerQuoteCheckConfigPath());+}++/**+ * Mode of `quote_check.subagent`: the same check over the context the+ * sub-agent carrier delivered. The hook gates this phase on a live+ * sub-agent delivery ledger.+ */+export function resolveAnswerQuoteCheckSubagent(configPath?: string): AnswerQuoteCheckMode {+ return resolveAnswerQuoteCheckPhase(+ "subagent",+ configPath ?? defaultAnswerQuoteCheckConfigPath(),+ );+}+/** Recall-inject cap overrides that passed validation (absent = hook default). */export interface RecallInjectCapsResolution {readonly caps: {diff --git a/src/core/install/grok-asset.ts b/src/core/install/grok-asset.tsindex e09815c4..429d5804 100644--- a/src/core/install/grok-asset.ts+++ b/src/core/install/grok-asset.ts@@ -113,7 +113,20 @@ const HOOK_SPEC: ReadonlyArray<{ event: string; groups: ReadonlyArray<HookGroupS},{event: "Stop",- groups: [{ hooks: ["session-capture", "stop-log-guardrail", "hygiene-digest"] }],+ groups: [+ {+ hooks: [+ "session-capture",+ "stop-log-guardrail",+ // The answer-trust quote check rides the same Stop pipeline: it is+ // annotation-only, fail-open exit 0, and reads the transcript the+ // same way the guardrail does, so grok gets the same unverified-+ // quote annotation Claude Code does.+ "answer-quote-check",+ "hygiene-digest",+ ],+ },+ ],},// The delegated sub-agent's close. Without it a grok install records the// parent's turns and drops every sub-agent's, and a sub-agent transcriptdiff --git a/src/core/search/property-pushdown.ts b/src/core/search/property-pushdown.tsindex 28f67459..34be72b3 100644--- a/src/core/search/property-pushdown.ts+++ b/src/core/search/property-pushdown.ts@@ -37,6 +37,17 @@* The promoted keys never narrow: the side table deliberately skips them,* so there are no rows to read.*+ * The narrowing's exclusion arm carries one further bound, the freshness+ * gate (answer-trust repair, M1): the stored rows are a snapshot taken at+ * index time, so an exclusion is only provable while the live file still+ * matches the snapshot it was taken from. The gate lives at the store+ * facade ({@link withoutAttributeNarrowing} names the probe half): a+ * candidate the fragment would exclude is kept anyway when its live stat+ * fingerprint no longer matches the indexed one, and the live post-rank+ * filter - which reads the file and owns the "judged live" contract - gets+ * the final word. This module stays pure SQL: the fragment never touches+ * the filesystem.+ ** A promoted key is pushed only when the push is FAITHFUL to the live* filter's verdict for every value the caller asked for; anything else* falls back rather than silently diverging:@@ -291,8 +302,11 @@ function placeholders(count: number): string {* Values are matched verbatim in the stored scalar `String(value)` form* (`documentAttributesFromFrontmatter` stores numbers and booleans exactly* as the live filter stringifies them), so a stored row answers only what- * the live filter would have answered for the same row. Null when there is- * nothing to narrow with.+ * the live filter would have answered for the same row. The exclusion arm+ * is further bounded by the store-level freshness gate - see+ * {@link withoutAttributeNarrowing} - which keeps every candidate whose+ * indexed snapshot may be stale. Null when there is nothing to narrow+ * with.*/export function attributeNarrowingFragment(entries: ReadonlyArray<AttributeNarrowing>,@@ -314,6 +328,40 @@ export function attributeNarrowingFragment(return { sql: clauses.join(" AND "), bindings };}+/**+ * The freshness gate's probe half (answer-trust repair, M1): the pushdown+ * with its attribute narrowing stripped, or null when nothing is left.+ *+ * The narrowing fragment excludes on the attribute SNAPSHOT, and a+ * snapshot can silently lag its file - a document indexed `status: draft`+ * and edited to `status: done` must not vanish from a `status=done` query+ * when the contract says "narrow on the attribute snapshot, judged live"+ * (`brain_search`'s own `properties` schema). So the store facade re-runs+ * the lane read through this probe (the promoted predicates unchanged, the+ * narrowing lifted, the same window) and treats the difference as the set+ * of candidates the narrowing would exclude; each of those gets one+ * liveness check against the indexed stat fingerprint (the Store's+ * freshness gate in `src/core/search/store.ts`), and the stale ones fall+ * through to the live post-rank filter as candidates. A candidate whose+ * fingerprint still matches is proven fresh, its SQL exclusion stands, and+ * the path is byte-identical to the ungated read - the gate never reads+ * file contents, and neither does this half.+ */+export function withoutAttributeNarrowing(pushdown: PropertyPushdown): PropertyPushdown | null {+ const promoted: PropertyPushdown = {+ ...(pushdown.pageTypes !== undefined ? { pageTypes: pushdown.pageTypes } : {}),+ ...(pushdown.pinned === true ? { pinned: true } : {}),+ ...(pushdown.visibilityTokens !== undefined+ ? { visibilityTokens: pushdown.visibilityTokens }+ : {}),+ };+ const hasPromoted =+ promoted.pageTypes !== undefined ||+ promoted.pinned === true ||+ promoted.visibilityTokens !== undefined;+ return hasPromoted ? Object.freeze(promoted) : null;+}+/*** The documents the narrowing would exclude: for any entry, the documents* carrying at least one stored row for its key and none of the accepted@@ -382,7 +430,12 @@ export function pushdownSqlFragment(if (pushdown.attributeNarrowing !== undefined) {// Candidate narrowing only (recall-quality): the fragment keeps every// document the bounded table cannot speak for, and the keys stay in the- // post-rank fallback, so this never decides a row on its own.+ // post-rank fallback, so this never decides a row on its own. The+ // snapshot the rows hold can also lag the file it was taken from; the+ // store's freshness gate ({@link withoutAttributeNarrowing}) re-runs+ // the lane read without this fragment and falls stale candidates+ // through to the live filter instead of letting the SQL exclusion+ // stand. This module stays pure SQL - no filesystem access here.const narrowing = attributeNarrowingFragment(pushdown.attributeNarrowing);if (narrowing !== null) {clauses.push(narrowing.sql);diff --git a/src/core/search/store.ts b/src/core/search/store.tsindex e7370f11..774b9c6f 100644--- a/src/core/search/store.ts+++ b/src/core/search/store.ts@@ -18,6 +18,8 @@*/import { Database } from "bun:sqlite";+import { statSync } from "node:fs";+import { join } from "node:path";import { registerWriterDb, unregisterWriterDb } from "./store-exit.ts";@@ -33,7 +35,8 @@ import { SearchError } from "./types.ts";import type { ResolvedSearchConfig } from "./types.ts";import type { EventAnchor } from "./event-anchor.ts";import { readSchemaVersion, type DocumentAttribute } from "./schema.ts";-import type { PropertyPushdown } from "./property-pushdown.ts";+import { withoutAttributeNarrowing, type PropertyPushdown } from "./property-pushdown.ts";+import { pathIsInside } from "../path-safety.ts";import * as aliases from "./store/aliases.ts";import * as chunkEntities from "./store/chunk-entities.ts";@@ -118,6 +121,30 @@ export interface StoreOpenOptions {readonly loadVec?: boolean;}+/**+ * The freshness verdict the attribute-narrowing gate asks of every+ * candidate it would otherwise exclude (answer-trust repair, M1): does the+ * live file's stat fingerprint still match the one the index recorded?+ *+ * `documents.mtime` (unix seconds - the indexer's own floor of the file's+ * mtime) and `documents.size` are the exact pair the indexer's fastpath+ * already treats as "content unchanged" (`make`'s trade-off), so the gate+ * reuses that definition instead of inventing a second one. The signature+ * is the no-file-read pin: the whole liveness judgement is a comparison of+ * two stat fingerprints, never a content read - the one file read a+ * narrowed search pays stays the live post-rank filter's own, over the+ * surfaced rows, exactly as before the gate existed. A candidate whose+ * fingerprint matches is proven fresh and its SQL exclusion stands; any+ * mismatch is STALE and the candidate falls through to the live filter,+ * which owns the "judged live" contract (see {@link Store.gateAttributeNarrowing}).+ */+export function indexedSnapshotStale(+ indexed: { readonly mtime: number; readonly size: number },+ live: { readonly mtimeMs: number; readonly size: number },+): boolean {+ return Math.floor(live.mtimeMs / 1000) !== indexed.mtime || live.size !== indexed.size;+}+// ─────────────────────────────────────────────────────────────────────────────// Store// ─────────────────────────────────────────────────────────────────────────────@@ -590,11 +617,122 @@ export class Store {);}+ /**+ * The freshness gate on attribute narrowing (answer-trust repair, M1).+ *+ * `attributeNarrowingFragment` excludes a candidate when the attributes+ * side table holds rows for a key and none of them is accepted - but+ * those rows are a snapshot taken at index time, so the exclusion is+ * only provable while the live file still matches it. The advertised+ * contract is "narrow on the attribute snapshot, judged live"+ * (`brain_search`'s `properties` schema), so a narrowed lane read is+ * paired with a probe: the same lane read through+ * {@link withoutAttributeNarrowing} (promoted predicates unchanged,+ * narrowing lifted, same window). Candidates the probe surfaces and the+ * narrowed read dropped are exactly the narrowing's exclusions; each+ * gets one liveness check ({@link indexedSnapshotStale}) against the+ * indexed stat fingerprint, and the stale ones are appended so the live+ * post-rank filter - the arbiter - judges them. A fingerprint match+ * proves the snapshot current, the SQL exclusion stands, and nothing is+ * appended: the fresh path stays byte-identical to the ungated read.+ *+ * The gate's filesystem budget is one `statSync` per would-be-excluded+ * candidate inside the lane window, bounded by the window itself; it+ * never reads file contents. The `path` column is the index's own+ * record, and it is trusted only as far as the vault it serves: a row+ * whose path does not resolve inside the vault is never statted at all -+ * the same lexical containment the live filter applies - and is ruled+ * STALE by the shared rule below, which is the safe arm (the candidate+ * falls through to the live filter and is judged by its unreadable-file+ * semantics). An unstatable file cannot be proven+ * current either, so its verdict is STALE by the same rule - that is a+ * named arbitration, not a swallowed error: the live filter's+ * unreadable-file semantics (`CachedFrontmatter.unreadable`, an empty+ * frontmatter map that matches no accepted value) decide the row.+ */+ private gateAttributeNarrowing<+ T extends { readonly documentId: number; readonly chunkId: number },+ >(+ hits: T[],+ pushdown: PropertyPushdown | null | undefined,+ probeLane: (probePushdown: PropertyPushdown | null) => T[],+ ): T[] {+ if (pushdown?.attributeNarrowing === undefined) return hits;+ const probeHits = probeLane(withoutAttributeNarrowing(pushdown));+ const keptChunks = new Set(hits.map((h) => h.chunkId));+ const excluded = probeHits.filter((h) => !keptChunks.has(h.chunkId));+ if (excluded.length === 0) return hits;+ const keptDocs = new Set(hits.map((h) => h.documentId));+ const excludedDocs = [...new Set(excluded.map((h) => h.documentId))].filter(+ (id) => !keptDocs.has(id),+ );+ if (excludedDocs.length === 0) return hits;+ const staleDocs = this.staleSnapshotDocumentIds(excludedDocs);+ if (staleDocs.size === 0) return hits;+ return [...hits, ...excluded.filter((h) => staleDocs.has(h.documentId))];+ }++ /**+ * The stale half of the given documents, judged by+ * {@link indexedSnapshotStale}: one indexed-fingerprint row per document+ * (never a chunk body) and one `statSync` per document - stat metadata+ * only, never a content read. A document whose row is missing yields no+ * verdict and no rescue, which is the narrowed read's own answer.+ */+ private staleSnapshotDocumentIds(documentIds: ReadonlyArray<number>): Set<number> {+ const placeholders = documentIds.map(() => "?").join(", ");+ const rows = this.db+ .query<{ id: number; path: string; mtime: number; size: number }, number[]>(+ `SELECT id, path, mtime, size FROM documents WHERE id IN (${placeholders})`,+ )+ .all(...documentIds);+ const stale = new Set<number>();+ for (const row of rows) {+ // The index's path column is not trusted past the vault it serves: a+ // row whose path escapes the vault is not a file this gate may stat,+ // so it is ruled stale without touching the filesystem - the same+ // lexical containment the live filter applies, and the safe arm (the+ // candidate falls through to the live filter, which judges it+ // unreadable rather than reading outside the vault).+ if (!pathIsInside(join(this.config.vault, row.path), this.config.vault)) {+ stale.add(row.id);+ continue;+ }+ let liveSize: number;+ let liveMtimeMs: number;+ try {+ const live = statSync(join(this.config.vault, row.path));+ liveSize = live.size;+ liveMtimeMs = live.mtimeMs;+ } catch {+ // Unstatable: the snapshot cannot be proven current. Named+ // arbitration (see {@link gateAttributeNarrowing}), never silent.+ stale.add(row.id);+ continue;+ }+ if (+ indexedSnapshotStale(+ { mtime: row.mtime, size: row.size },+ { mtimeMs: liveMtimeMs, size: liveSize },+ )+ ) {+ stale.add(row.id);+ }+ }+ return stale;+ }+semanticTopK(queryVector: ReadonlyArray<number> | Float32Array,opts: vectors.SemanticTopKOptions,): vectors.SemanticHit[] {- return vectors.semanticTopK(this.db, this.vecExtensionLoaded, queryVector, opts);+ const hits = vectors.semanticTopK(this.db, this.vecExtensionLoaded, queryVector, opts);+ return this.gateAttributeNarrowing(hits, opts.pushdown, (probe) =>+ vectors.semanticTopK(this.db, this.vecExtensionLoaded, queryVector, {+ ...opts,+ pushdown: probe,+ }),+ );}// ── links ──────────────────────────────────────────────────────────────────@@ -831,10 +969,14 @@ export class Store {/*** Top-K BM25 keyword hits. `fts5Query` is an already-escaped FTS5- * MATCH expression; building it is fts.ts's job.+ * MATCH expression; building it is fts.ts's job. A narrowed pushdown+ * rides the freshness gate ({@link gateAttributeNarrowing}).*/keywordTopK(fts5Query: string, opts: keyword.KeywordTopKOptions): keyword.KeywordHit[] {- return keyword.keywordTopK(this.db, fts5Query, opts);+ const hits = keyword.keywordTopK(this.db, fts5Query, opts);+ return this.gateAttributeNarrowing(hits, opts.pushdown, (probe) =>+ keyword.keywordTopK(this.db, fts5Query, { ...opts, pushdown: probe }),+ );}/**@@ -853,7 +995,15 @@ export class Store {readonly pushdown?: PropertyPushdown | null;},): trigram.TrigramCandidateOutcome {- return trigram.trigramCandidates(this.db, trigramQuery, opts);+ const outcome = trigram.trigramCandidates(this.db, trigramQuery, opts);+ const hits = this.gateAttributeNarrowing(+ outcome.hits,+ opts.pushdown ?? null,+ (probe) =>+ trigram.trigramCandidates(this.db, trigramQuery, { ...opts, pushdown: probe }).hits,+ );+ if (hits === outcome.hits) return outcome;+ return { ...outcome, hits };}// ── entities ─────────────────────────────────────────────────────────────diff --git a/src/core/search/visibility-surface-registry.ts b/src/core/search/visibility-surface-registry.tsindex fe67af94..d3eeb858 100644--- a/src/core/search/visibility-surface-registry.ts+++ b/src/core/search/visibility-surface-registry.ts@@ -205,6 +205,54 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>"under readdirSync, with no visibility check - the field is not part of a signal's schema " +"and the reader never looks at a general vault page.",},+ {+ // The four source-ingest-suite tools joined the swept population when+ // ingest-tools.ts began reading page frontmatter for the archive-orphan+ // decision (answer trust), which made the whole file a note-content+ // importer under the census's file-level rule. All four were already+ // asking a read root at their read sites; the rows below are that fact+ // written down per surface, not a behavior change.+ surface: "brain_ingest_source",+ kind: K.mcpTool,+ category: C.covered,+ reason:+ "the handler hands the ingest `readable: readableAtContextReach(ctx)` " ++ "(ingest-tools.ts), so a summary page the caller may not read at its reach " ++ "answers exactly as an absent one - never staged, never named in the " ++ "result, and the review-queue disposition is decided for the credential-" ++ "minted subject rather than the caller-named agent.",+ },+ {+ surface: "brain_search_by_source",+ kind: K.mcpTool,+ category: C.covered,+ reason:+ "every hit is filtered through the same `readable(entry.path)` predicate " ++ "before serialization, then through `isPathOwnerVisible` under the caller's " ++ "owner scope with a fail-closed frontmatter parse, and `total` counts only " ++ "what is returned, so a hidden page contributes neither an entry nor a count.",+ },+ {+ surface: "brain_delete_by_source",+ kind: K.mcpTool,+ category: C.covered,+ reason:+ "the plan is built with `include: readableAtContextReach(ctx)`, so an " ++ "original or derived page the caller may not read at its reach is planned " ++ "and deleted exactly as an absent one - never confirmed, never named in " ++ "match_list, never removed; the archive-orphan decision reads only stamps " ++ "on pages this same run is already deleting.",+ },+ {+ surface: "brain_ingest_batch_plan",+ kind: K.mcpTool,+ category: C.covered,+ reason:+ "`planBatches` and its reconcile pass take the same " ++ "`readableAtContextReach(ctx)` predicate, so a source file the caller may " ++ "not read at its reach is planned as an absent one - not batched, not " ++ "counted, and not named in any batch's file list.",+ },{surface: "brain_audit",kind: K.mcpTool,diff --git a/src/core/state/surfaces.ts b/src/core/state/surfaces.tsindex 5c5054e2..2dc003fd 100644--- a/src/core/state/surfaces.ts+++ b/src/core/state/surfaces.ts@@ -72,6 +72,7 @@ import { lstatSync, readdirSync, statSync } from "node:fs";import { basename, dirname, join } from "node:path";import {+ BRAIN_ARCHIVES_REL,BRAIN_ARTIFACTS_REL,BRAIN_CAPTURES_REL,BRAIN_CLAIM_GRAPH_FILE,@@ -156,6 +157,7 @@ export const STATE_SURFACE_ID = Object.freeze({proposalWatermark: "proposal_watermark",captureWatermark: "capture_watermark",decisionLedger: "decision_ledger",+ sourceArchives: "source_archives",} as const);export type StateSurfaceId = (typeof STATE_SURFACE_ID)[keyof typeof STATE_SURFACE_ID];@@ -1067,6 +1069,22 @@ export const STATE_SURFACES: ReadonlyArray<StateSurface> = Object.freeze(["was never appended.",sources: ["src/core/brain/permissions/ledger.ts"],},+ {+ id: STATE_SURFACE_ID.sourceArchives,+ label: "source archives",+ tier: STATE_TIER.vaultContent,+ derive: (vault) => join(vault, BRAIN_ARCHIVES_REL),+ override_env: null,+ override_config_key: null,+ carries_memory: true,+ reason:+ "The redacted bytes an ingest summary page's knowledge was read from, one content-addressed " ++ "file per distinct source text. This is durable evidence, not scratch: deleting an entry " ++ "destroys the ability to re-verify the page against its source - the current vault content " ++ "is untouched, which is exactly what separates it from a rebuildable derived store, and " ++ "there is no TTL to bring it back.",+ sources: ["src/core/brain/provenance/source-archive.ts"],+ },]);/**diff --git a/src/core/vault-scope/index-admission.ts b/src/core/vault-scope/index-admission.tsindex d43529bc..874fc005 100644--- a/src/core/vault-scope/index-admission.ts+++ b/src/core/vault-scope/index-admission.ts@@ -15,7 +15,12 @@* canonicalises). The predicate is pure and does no I/O.*/-import { BRAIN_PENDING_REL, BRAIN_PAYLOADS_REL, BRAIN_STATE_REL } from "../brain/paths.ts";+import {+ BRAIN_ARCHIVES_REL,+ BRAIN_PENDING_REL,+ BRAIN_PAYLOADS_REL,+ BRAIN_STATE_REL,+} from "../brain/paths.ts";import { pathCovers } from "./defaults.ts";export interface AdmissionVerdict {@@ -48,6 +53,16 @@ export function admitToIndex(relPath: string): AdmissionVerdict {if (pathCovers(BRAIN_PAYLOADS_REL, relPath)) {return Object.freeze({ admit: false, reason: "payload-store" });}+ // The durable source archive, same extension situation as the payload+ // store above: its entries are `<sha256>.txt`, which the `.md` walkers+ // skip anyway, so this is the stated rule rather than the accident. The+ // store holds the redacted bytes an ingest summary page was read from -+ // evidence a re-verification consults directly, never a note recall+ // should surface, and the dot-directory the walker skips is the same+ // exclusion by the other route.+ if (pathCovers(BRAIN_ARCHIVES_REL, relPath)) {+ return Object.freeze({ admit: false, reason: "source-archive-store" });+ }// The write-approval review lane: a document staged into `Brain/pending/`// is exactly the content no operator has admitted yet, so recall must not// surface it (write-side trust, Task 5). Before this exclusion a stageddiff --git a/src/mcp/brain/hygiene-tools.ts b/src/mcp/brain/hygiene-tools.tsindex 5b262f84..295c4d94 100644--- a/src/mcp/brain/hygiene-tools.ts+++ b/src/mcp/brain/hygiene-tools.ts@@ -1,16 +1,22 @@/**- * Hygiene surface: scan / apply / refresh over the findings pipeline- * (continuity-hygiene-freshness suite; kanban t_698db8f7, t_da3f138f,- * t_db375a60, t_d9624ef6, t_fe490119).+ * Hygiene surface: scan / apply / refresh / archive_get over the findings+ * pipeline (continuity-hygiene-freshness suite; kanban t_698db8f7,+ * t_da3f138f, t_db375a60, t_d9624ef6, t_fe490119; archive_get from the+ * answer-trust wave).*- * One tool, three modes:+ * One tool, four modes:* - `scan` (default): read-only digest of detector findings, with* resolver verdicts attached when the operator configured* `hygiene.resolver_cmd` in `_brain.yaml`;* - `apply`: execute an explicit plan selected by finding ids -* ids are REQUIRED, a bare apply never runs everything blindly;* - `refresh`: the targeted-recompile path for stale derived pages- * (`dry_run` previews with zero writes).+ * (`dry_run` previews with zero writes);+ * - `archive_get`: resolve an ingest summary's `source_archive_hash` to+ * the archived (redacted) source bytes. LOCAL reach only - a remote+ * caller gets the answer an absent entry gives, never the bytes, so+ * the archive can never make a withheld source more reachable than+ * the digest that names it.** The resolver command comes exclusively from operator config - it is* never accepted as a tool argument, so an MCP caller cannot make this@@ -42,13 +48,19 @@ import {} from "../../core/brain/hygiene/types.ts";import { executeRecompile, planRecompile } from "../../core/brain/recompile.ts";import { resolveSearchConfig } from "../../core/search/index.ts";+import {+ ARCHIVE_VERIFICATION,+ isArchiveHash,+ readSourceArchiveEntry,+ sourceArchiveCitingPages,+} from "../../core/brain/provenance/source-archive.ts";import {DANGLING_LINK_DEFINITION,measureFromIndex,type LinkRatchetMeasurement,type LinkRatchetUnmeasurableReason,} from "../../core/search/link-ratchet.ts";-import { coerceBool } from "../coerce.ts";+import { coerceBool, coerceStr } from "../coerce.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";@@ -225,9 +237,46 @@ async function toolBrainHygiene(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const mode = args["mode"] ?? "scan";- if (mode !== "scan" && mode !== "apply" && mode !== "refresh") {- throw new MCPError(INVALID_PARAMS, "'mode' must be one of: scan, apply, refresh");+ if (mode !== "scan" && mode !== "apply" && mode !== "refresh" && mode !== "archive_get") {+ throw new MCPError(INVALID_PARAMS, "'mode' must be one of: scan, apply, refresh, archive_get");+ }++ if (mode === "archive_get") {+ // The bounded-fetch posture of brain_artifact_get, one visibility rule+ // tighter: the hash is the caller's argument and is validated as one+ // before it names a path, an unknown hash is a NAMED miss (never an+ // error a caller would retry), and the store answers at LOCAL reach+ // only - a remote caller gets the answer an absent entry gives, so the+ // response can neither confirm an entry's existence nor carry bytes.+ const hash = coerceStr(args, "hash", true)!;+ if (!isArchiveHash(hash)) {+ throw new MCPError(INVALID_PARAMS, "'hash' must be a 64-hex sha-256 digest");+ }+ if (contextReach(ctx) !== TRANSPORT_REACH.local) {+ return { hash, archive: ARCHIVE_VERIFICATION.missing };+ }+ // The owner boundary, the same one the scan applies to its report: a+ // caller under an enforced owner scope reads pages only through the+ // per-path view, so an entry whose every citing page is withheld+ // answers exactly as an absent one. Answering its state or its bytes+ // would let a scoped agent confirm a guess about evidence it may not+ // read - the scan withholds those citing pages through the gated view,+ // and this read would otherwise stand beside it as a confirm-a-guess+ // oracle (the leak the design cites for refusing digests).+ const readable = readableAtContextReachOrUndefined(ctx);+ if (readable !== undefined && !sourceArchiveCitingPages(ctx.vault, hash).some(readable)) {+ return { hash, archive: ARCHIVE_VERIFICATION.missing };+ }+ const entry = readSourceArchiveEntry(ctx.vault, hash);+ if (entry === null) return { hash, archive: ARCHIVE_VERIFICATION.missing };+ return {+ hash,+ archive: entry.state,+ bytes: entry.bytes,+ content: entry.text,+ };}+const now = new Date();const dryRun = coerceBool(args, "dry_run") === true;@@ -375,14 +424,19 @@ export const HYGIENE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([name: "brain_hygiene",previewBudget: MCP_PREVIEW_BUDGET,description:- "Memory hygiene pipeline. `scan`: read-only digest of contested truth slots, near-duplicate preferences, stale/orphaned pages, low-usefulness candidates, knowledge resting on url-only sources. `apply`: run selected finding ids (review findings never run). `refresh`: recompile stale pages.",+ "Memory hygiene. `scan`: contested truth slots, near-duplicate preferences, stale or orphaned pages, low-usefulness candidates, knowledge resting on url-only sources. `apply`: run selected finding ids. `refresh`: recompile stale pages. `archive_get`: archived source bytes by hash, local only.",inputSchema: {type: "object",properties: {mode: {type: "string",- enum: ["scan", "apply", "refresh"],- description: "Pipeline stage. Default `scan` (read-only).",+ enum: ["scan", "apply", "refresh", "archive_get"],+ description: "Pipeline stage: scan, apply, refresh, archive_get. Default `scan`.",+ },+ hash: {+ type: "string",+ description:+ "The source_archive_hash to fetch (archive_get mode): the digest an ingest summary page stamps.",},detectors: {type: "array",diff --git a/src/mcp/brain/ingest-tools.ts b/src/mcp/brain/ingest-tools.tsindex 3fff4f06..81d2996a 100644--- a/src/mcp/brain/ingest-tools.ts+++ b/src/mcp/brain/ingest-tools.ts@@ -9,6 +9,9 @@* Idempotent on the source path.*/+import { existsSync } from "node:fs";+import { join } from "node:path";+import { serializeImportCensus } from "../../core/brain/import-census.ts";import { planBatches, type BatchPlan } from "../../core/brain/ingest/batch-plan.ts";import { clearCheckpoint, PLAN_ID_LABEL } from "../../core/brain/ingest/checkpoint.ts";@@ -18,6 +21,14 @@ import type { PartsOutcome, TableOutcome } from "../../core/brain/ingest/extractimport type { CodeEdgeSeed, PreExtractResult } from "../../core/brain/ingest/pre-extract.ts";import { reconcilePlan } from "../../core/brain/ingest/reconcile.ts";import { IntakeValidationError } from "../../core/brain/intake/extract-intake.ts";+import {+ discardSourceArchive,+ isArchiveHash,+ SOURCE_ARCHIVE_HASH_KEY,+ sourceArchiveCitingPages,+ sourceArchiveEntryRel,+} from "../../core/brain/provenance/source-archive.ts";+import { parseFrontmatter } from "../../core/vault.ts";import {deleteBySource,searchBySourceFile,@@ -146,6 +157,19 @@ async function toolBrainIngestSource(// it. Always present: absence would read as "full-local" to a caller// that never learned the key exists.capture_scope: res.captureScope,+ // The durable archive stamp (answer trust, Task C4), following the+ // capture_scope pattern: the hash is ALWAYS present, null when the+ // source was not archived, so absence never reads as a missing key.+ // The byte count rides only with a hash, mirroring the page's+ // frontmatter; the named refusal rides only when an ELIGIBLE source+ // could not be archived.+ source_archive_hash: res.sourceArchiveHash ?? null,+ ...(res.sourceArchiveHash !== undefined+ ? { source_archive_bytes: res.sourceArchiveBytes }+ : {}),+ ...(res.sourceArchiveRefusal !== undefined+ ? { source_archive_refusal: res.sourceArchiveRefusal }+ : {}),// Write-side trust (Task 9): a first publish of the summary page// stages under the review gate while registration completes. The// receipt names the queue entry and the command that publishes it,@@ -226,7 +250,82 @@ function serializeEntry(entry: SourceCleanupEntry): Record<string, unknown> {};}-function serializePlan(plan: SourceCleanupPlan): Record<string, unknown> {+/**+ * One archive entry a source cleanup takes with it (answer trust, Task C4),+ * reported as its own kind beside the page entries - the hash and the+ * vault-relative path, never a host path.+ */+interface ArchiveCleanupEntry {+ readonly hash: string;+ readonly path: string;+}++/**+ * Harvest the archive digests stamped on the plan's summary pages, sorted.+ * Read BEFORE a confirmed deletion runs: once the pages are gone their+ * stamps are gone with them, and the entry orphan decision needs them.+ */+function stampedArchiveHashes(vault: string, plan: SourceCleanupPlan): ReadonlyArray<string> {+ const hashes = new Set<string>();+ for (const entry of plan.derived) {+ if (entry.kind !== "summary" || !existsSync(join(vault, entry.path))) continue;+ const [meta] = parseFrontmatter(join(vault, entry.path));+ const value = meta[SOURCE_ARCHIVE_HASH_KEY];+ if (typeof value === "string" && isArchiveHash(value)) hashes.add(value);+ }+ return [...hashes].toSorted();+}++/**+ * Which of the plan's stamped entries this deletion orphans: an entry goes+ * only when EVERY page citing it is in the deleted set - removing a source+ * whose summary shares an entry with another source's page (identical+ * bytes, content-addressed dedup) leaves the entry standing. Vacuously+ * true when no citing page remains: the hash got here from the plan's own+ * pages, so an empty citation list means the last citing page is exactly+ * what this run deleted. A page the caller may not read is not in the+ * deleted set, so a hidden citation keeps the entry too: the fail-safe+ * direction.+ */+function orphanedArchiveEntries(+ vault: string,+ hashes: ReadonlyArray<string>,+ deletedPaths: ReadonlySet<string>,+): ReadonlyArray<ArchiveCleanupEntry> {+ const out: ArchiveCleanupEntry[] = [];+ for (const hash of hashes) {+ const citing = sourceArchiveCitingPages(vault, hash);+ if (citing.every((page) => deletedPaths.has(page))) {+ out.push({ hash, path: sourceArchiveEntryRel(hash) });+ }+ }+ return out;+}++/**+ * Best-effort removal of one orphaned entry: false both when there was+ * nothing to remove and when the removal itself failed. The confirmed+ * deletion has already completed by the time this runs, so a cleanup that+ * throws - a permission denial, an entry replaced by something rmSync+ * cannot remove - must not fail the tool after the fact, and its error+ * message carries a host path this surface never reports. What is+ * tolerated here is exactly the transient half: the page deletion is done+ * and correct, and the leftover entry is durable evidence, not a lost+ * deletion - the doctor's archive section names it in its `uncited`+ * count, and a retry of the cleanup is harmless.+ */+function discardOrphanedArchiveEntry(vault: string, hash: string): boolean {+ try {+ return discardSourceArchive(vault, hash);+ } catch {+ return false;+ }+}++function serializePlan(+ plan: SourceCleanupPlan,+ archiveEntries: ReadonlyArray<ArchiveCleanupEntry>,+): Record<string, unknown> {return {source: plan.source,confirmed: plan.confirmed,@@ -243,6 +342,14 @@ function serializePlan(plan: SourceCleanupPlan): Record<string, unknown> {deleted: [...plan.deleted],manifest_entry_removed: plan.manifestEntryRemoved,audit_record_id: plan.auditRecordId,+ // The archive-entry cleanup kind (answer trust, Task C4), reported as+ // its own kind rather than folded into the page entries: on a dry run,+ // the entries removing the source's last citing page WOULD orphan; on+ // confirm, the entries actually removed. They are deterministic+ // consequences of the page deletion, never targets of their own, so+ // they sit outside the count guard's blast radius. Emitted only when+ // non-empty, so a plan over an unstamped source is byte-identical.+ ...(archiveEntries.length > 0 ? { archive_entries: archiveEntries } : {}),// The D1 recovery point. Only the run id is surfaced here (not the// absolute archive path) so the response stays free of host paths; the// archive lives at the deterministic `Brain/.snapshots/<run_id>.tar.zst`.@@ -328,11 +435,26 @@ async function toolBrainDeleteBySource(willMutate: confirm,matchList: planMatchList(preview),});+ // The stamps must be read BEFORE a confirmed deletion erases the pages+ // that carry them; the orphan decision then runs against whichever set+ // this run actually removed (a dry run answers with what confirm would+ // remove).+ const stamped = stampedArchiveHashes(ctx.vault, preview);try {- const plan = confirm- ? deleteBySource(ctx.vault, sourceFile, { confirm: true, ...baseOpts })- : preview;- return serializePlan(plan);+ let archiveEntries: ReadonlyArray<ArchiveCleanupEntry> = [];+ if (confirm) {+ const plan = deleteBySource(ctx.vault, sourceFile, { confirm: true, ...baseOpts });+ archiveEntries = orphanedArchiveEntries(ctx.vault, stamped, new Set(plan.deleted)).filter(+ (entry) => discardOrphanedArchiveEntry(ctx.vault, entry.hash),+ );+ return serializePlan(plan, archiveEntries);+ }+ archiveEntries = orphanedArchiveEntries(+ ctx.vault,+ stamped,+ new Set(preview.derived.map((entry) => entry.path)),+ );+ return serializePlan(preview, archiveEntries);} catch (err) {// Write-side trust (Task 12): a permissions document rule denied the// confirmed cleanup. Named code, the rule that decided, and thediff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.tsindex ebbe2a19..3f10c2ec 100644--- a/src/mcp/brain/knowledge-tools.ts+++ b/src/mcp/brain/knowledge-tools.ts@@ -38,7 +38,7 @@ import { diarize, DiarizationError } from "../../core/brain/diarization.ts";import { discoverIdeas, ideaCandidates } from "../../core/brain/idea-discovery.ts";import { auditMoc, MocAuditError } from "../../core/brain/link-graph/moc-audit.ts";import { reachView } from "../../core/brain/reach-view.ts";-import { everyArtifactRefView } from "../../core/brain/artifact-ref-view.ts";+import { everyArtifactRefView, type ArtifactRefView } from "../../core/brain/artifact-ref-view.ts";import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import { recordRefs } from "../../core/brain/log-events-at-reach.ts";import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";@@ -67,6 +67,13 @@ import {readClaimEvents,} from "../../core/brain/truth/store.ts";import { claimEventLimit, matchClaimEvents } from "../../core/brain/truth/events-window.ts";+import {+ loadClaimProvenanceIndex,+ resolveClaimProvenanceFromIndex,+ type ClaimProvenance,+ type ClaimProvenanceOptions,+} from "../../core/brain/truth/claim-provenance.ts";+import type { ClaimEvent } from "../../core/brain/truth/types.ts";import {allClaims,buildClaimGraph,@@ -81,7 +88,7 @@ import {} from "../../core/brain/claim-graph.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import { contextReach } from "../tool-contract.ts";-import type { TransportReach } from "../../core/graph/transport-reach.ts";+import { TRANSPORT_REACH, type TransportReach } from "../../core/graph/transport-reach.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";@@ -94,6 +101,7 @@ import {} from "../coerce.ts";import { coercePositiveInteger, toolSafeguard, vaultRelativeSafe } from "./shared.ts";import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";+import { isOperatorRuleItem, isRuleOnlyInjection } from "./pack-tools.ts";import { resolveTimeBounds } from "./time-bounds.ts";/**@@ -782,6 +790,13 @@ function toolBrainTruth(const agent =normalizeAgentArgument(typeof agentArg === "string" ? agentArg : null) ??resolveAgentName(ctx.configPath ?? undefined);+ // Sample id (answer-trust, task B4): an optional call-level id naming+ // the recall/context-pack quality-sample these claims were stated+ // against. A non-string type is refused here as a mistyped parameter;+ // a blank string flows to the payload boundary's named refusal below+ // (mapped to the same failure class), so an empty id is never coerced+ // to an absent one. Committed events echo the id verbatim.+ const sampleId = optionalStr("sample_id");// The source's frontmatter window resolves at the CALLER's reach,// exactly as ingest gates it: a withheld source freezes a windowless// event and the committed rows carry no validity keys, so the state@@ -797,6 +812,7 @@ function toolBrainTruth(agent,ts: isoSecond(new Date()),source: requireStr("source"),+ ...(sampleId !== undefined ? { sampleId } : {}),},{entities: statedClaimEntities(ctx.vault),@@ -1064,7 +1080,8 @@ export function statedClaimEntities(vault: string): ReadonlyArray<{* the caller that a claim it may not see exists, and per entity or* window would let it measure the hidden population). A filtered answer* is therefore byte-identical to the answer over a vault that never- * held the withheld rows.+ * held the withheld rows. The same reach governs the provenance join+ * (see {@link claimProvenanceForPage}).*/export function claimEventsReport(vault: string,@@ -1086,16 +1103,96 @@ export function claimEventsReport(untilMs: query.untilMs,});const gated = view.filtersNothing ? matched : matched.filter((event) => view.row(event.source));+ const page = gated.slice(0, query.limit);+ const provenance = claimProvenanceForPage(vault, reach, view, page);return {ok: true,operation: "events",entity: entityFilter === undefined ? null : normalizeEntityName(entityFilter),- events: gated.slice(0, query.limit),+ events: page.map((event, position) =>+ event.sample_id === undefined || provenance === null+ ? // A claim without a sample id renders exactly as today: no+ // provenance key, byte-identical row.+ event+ : {+ ...event,+ // Answer-trust (task B4): the claim's sample id resolves to+ // its receipt and outcome halves at read time. A missing+ // outcome half is null - "receipt known, outcome unknown" -+ // never a fabricated verdict.+ provenance: provenance[position]!,+ },+ ),total: gated.length,truncated: gated.length > query.limit,};}+/**+ * The provenance half of one events page, resolved at the CALLER's+ * reach over ONE read per ledger.+ *+ * The resolutions come back aligned with the page by POSITION, one per+ * row: the inversion flag compares each claim's OWN assertion ts+ * against the claimed receipt, so two claims sharing one `sample_id`+ * (one stated before the receipt it names, one after) must resolve+ * independently - a per-id cache would hand both rows the last+ * claim's flag. Resolution from the prebuilt index is map lookups, so+ * resolving per event keeps the one-read-per-ledger bound the scans+ * suite pins.+ *+ * The receipts surface withholds the operator's rule injections below+ * local reach (list excludes them, show refuses them, receipts are+ * stripped of their items); this join answers for the same records, so+ * it binds the same rules here instead of leaking through a claim's+ * `sample_id` what `brain_context_receipts` refuses to say directly. A+ * rule-only receipt renders as the unknown-id answer; a mixed receipt+ * keeps its non-rule items; and a receipt item whose recorded path+ * names a page the caller may not read at its reach leaves the items+ * under the same visibility rule the event rows of this report are+ * gated by.+ *+ * Null when no row on the page carries a sample id: the ledgers are+ * never read and every row renders byte-identically to the+ * pre-attribution answer. Otherwise the array holds one entry per page+ * row, null at the unsampled positions.+ */+function claimProvenanceForPage(+ vault: string,+ reach: TransportReach,+ view: ArtifactRefView,+ page: ReadonlyArray<ClaimEvent>,+): ReadonlyArray<ClaimProvenance | null> | null {+ if (!page.some((event) => event.sample_id !== undefined)) return null;+ const local = reach === TRANSPORT_REACH.local;+ const options: ClaimProvenanceOptions = {+ ...(local ? {} : { exclude: isRuleOnlyInjection }),+ ...(view.filtersNothing+ ? {}+ : {+ excludeItem: (item: unknown): boolean =>+ (!local && isOperatorRuleItem(item)) || itemPathHidden(item, view),+ }),+ };+ const index = loadClaimProvenanceIndex(vault);+ return page.map((event) =>+ event.sample_id === undefined+ ? null+ : resolveClaimProvenanceFromIndex(index, event.sample_id, event.ts, options),+ );+}++/**+ * A receipt item whose recorded path names a page the caller may not+ * read at its reach. An item with no path names no page and stays; an+ * extensionless or wikilink spelling resolves through the same+ * reference grammar the event-row gate uses.+ */+function itemPathHidden(item: unknown, view: ArtifactRefView): boolean {+ const path = (item as { path?: unknown } | null)?.path;+ return typeof path === "string" && path !== "" && !view.visible(path);+}+export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_claims",@@ -1374,6 +1471,11 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "string",description: "state: the assertion text every claim is anchored against.",},+ sample_id: {+ type: "string",+ description:+ "state: the quality-sample id (a context receipt id or opaque hash) these claims were stated against; frozen per claim, reads hydrate it into provenance.",+ },},required: ["operation"],additionalProperties: false,diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.tsindex 89b0702e..c557b0a0 100644--- a/src/mcp/brain/pack-tools.ts+++ b/src/mcp/brain/pack-tools.ts@@ -516,7 +516,13 @@ const OPERATOR_RULE_ITEM_IDS: ReadonlySet<string> = new Set([RECEIPT_ITEM_SCOPED_RULES,]);-const isOperatorRuleItem = itemIdIn(OPERATOR_RULE_ITEM_IDS);+/**+ * One operator-rule receipt item. Exported beside+ * {@link isRuleOnlyInjection} for the brain_truth provenance join, which+ * strips these items from a mixed receipt below local reach - the same+ * shaping `receiptAtReach` applies to the receipts this tool serves.+ */+export const isOperatorRuleItem = itemIdIn(OPERATOR_RULE_ITEM_IDS);/*** A measured injection receipt whose every item was an operator-rule@@ -524,8 +530,13 @@ const isOperatorRuleItem = itemIdIn(OPERATOR_RULE_ITEM_IDS);* no `active.md` body to inject). Below local reach it* is withheld whole - left out of list and summary, refused by show -* since even its empty remainder would say that rules applied.+ *+ * Exported for the surfaces that must answer the same question the+ * receipts surface answers: the brain_truth provenance join excludes+ * these receipts below local reach, so a claim's provenance confirms no+ * more about the operator's rules than this tool does.*/-function isRuleOnlyInjection(record: ContinuityRecord): boolean {+export function isRuleOnlyInjection(record: ContinuityRecord): boolean {if (record.payload["trigger"] !== "session_inject") return false;// A degraded injection that served a cached body beside the rules is// recorded whether or not rules applied: it stays, emptied of them. Onediff --git a/src/mcp/brain/synthesis-tools.ts b/src/mcp/brain/synthesis-tools.tsindex 7dceb75a..feac8795 100644--- a/src/mcp/brain/synthesis-tools.ts+++ b/src/mcp/brain/synthesis-tools.ts@@ -74,7 +74,9 @@ const PROJECT_SCOPE_MAX_LEN = 128;function serializeDigest(digest: SessionSummaryDigest): Record<string, unknown> {return {id: digest.id,- session_id: digest.sessionId,+ // Presence-gated with the digest shape (t_22d58fa7): a record naming+ // no session carries no session_id key, never a fabricated "".+ ...(digest.sessionId !== undefined ? { session_id: digest.sessionId } : {}),request: digest.request,decisions: digest.decisions,learnings: digest.learnings,diff --git a/tests/cli/brain-doctor-next-step.test.ts b/tests/cli/brain-doctor-next-step.test.tsindex 2c59606f..596b7510 100644--- a/tests/cli/brain-doctor-next-step.test.ts+++ b/tests/cli/brain-doctor-next-step.test.ts@@ -218,11 +218,29 @@ describe("brain doctor - byte-identical when there is nothing to point at", () =expect(r.stdout).toBe("brain doctor: clean\n");});- test("a clean vault's JSON payload is the pre-task shape", async () => {+ test("a clean vault's JSON payload carries no findings and the count-only archive section", async () => {const r = await runCli(["brain", "doctor", "--vault", vault, "--json"], {env: { OPEN_SECOND_BRAIN_CONFIG: config },});expect(r.returncode).toBe(0);- expect(r.stdout).toBe(JSON.stringify({ warnings: [], errors: [] }, null, 2) + "\n");+ // The answer-trust wave adds one informational, count-only archive+ // section to the doctor's JSON payload, and its key is deliberately+ // ALWAYS present (the capture_scope field pattern: a caller never+ // infers the section's existence from a missing key). What the+ // byte-identical promise continues to guard is the finding surface: a+ // clean vault carries no warnings, no errors, and none of the+ // next-command or no-exit noise - and the human-readable path stays+ // fully byte-identical (the test above).+ expect(r.stdout).toBe(+ JSON.stringify(+ {+ warnings: [],+ errors: [],+ archives: { entries: 0, totalBytes: 0, missing: 0, mismatched: 0, uncited: 0 },+ },+ null,+ 2,+ ) + "\n",+ );});});diff --git a/tests/cli/brain-hygiene.test.ts b/tests/cli/brain-hygiene.test.tsindex 245911d2..f8627373 100644--- a/tests/cli/brain-hygiene.test.ts+++ b/tests/cli/brain-hygiene.test.ts@@ -14,12 +14,13 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { brainDirs } from "../../src/core/brain/paths.ts";+import { ingestSource as ingestCore } from "../../src/core/brain/ingest/ingest.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { resetVaultIdentityPins } from "../../src/core/brain/vault-identity.ts";import { HYGIENE_TOOLS } from "../../src/mcp/brain/hygiene-tools.ts";@@ -274,3 +275,177 @@ describe("the capture-scope detector on the hygiene surfaces", () => {expect(tool.description.length).toBeLessThanOrEqual(TOOL_DESCRIPTION_MAX);});});++/**+ * The archive finding (answer trust, Task C5) rides the same CLI scan: a+ * summary page stamped with an archive digest whose entry is gone is a+ * named finding in the default sweep, and the scan stays read-only about+ * it. An intact entry and an unstamped page are not findings.+ */+describe("the capture-scope archive finding on the CLI scan", () => {+ const DETECTOR = "capture-scope";+ const SOURCE = "Articles/keep.md";+ const ingestSource = (contents: string): { summaryPath: string; hash: string } => {+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, SOURCE), contents, "utf8");+ const res = ingestCore(+ vault,+ {+ sourcePath: SOURCE,+ summary: "Kept durable.",+ extraction: { entities: [{ category: "concept", name: "Keep" }], relations: [] },+ },+ { agent: "test-agent", now: new Date("2026-02-02T00:00:00Z") },+ );+ if (res.sourceArchiveHash === undefined) throw new Error("expected an archive stamp");+ return { summaryPath: res.summaryPath, hash: res.sourceArchiveHash };+ };++ test("a missing entry is a finding in the default sweep; an intact one is not", async () => {+ const { hash } = ingestSource("kept bytes\n");+ expect((await scan()).findings).toEqual([]);++ rmSync(join(vault, "Brain", ".archives", `${hash}.txt`));+ const report = await scan();+ const finding = report.findings.find((f) => f.detector === DETECTOR);+ expect(finding).toBeDefined();+ expect(finding!.proposed_action).toBe("review");+ expect(report.counts[DETECTOR]).toBeGreaterThanOrEqual(1);+ });++ test("the finding names the summary page and the scan stays read-only", async () => {+ const { summaryPath, hash } = ingestSource("other bytes\n");+ rmSync(join(vault, "Brain", ".archives", `${hash}.txt`));+ const before = digestVaultTree(vault);++ const report = await scan("--detectors", DETECTOR);+ const finding = report.findings.find((f) => f.detector === DETECTOR);+ expect(finding).toBeDefined();+ expect(JSON.stringify(finding)).toContain(summaryPath);+ expect(digestVaultTree(vault)).toBe(before);+ });+});++/**+ * The doctor's informational archive section (answer trust, Task C6):+ * count-only - entry count, total bytes, missing/mismatched counts - always+ * present in the JSON, a line in the human output only when there is+ * something to describe, and no fix verb anywhere.+ */+describe("the doctor archive section", () => {+ interface ArchivesJson {+ readonly archives: {+ readonly entries: number;+ readonly totalBytes: number;+ readonly missing: number;+ readonly mismatched: number;+ readonly uncited: number;+ };+ }+ const doctorJson = async (): Promise<ArchivesJson> => {+ const out = await runCli(["brain", "doctor", "--vault", vault, "--json"], { env: env() });+ expect(out.returncode).toBe(0);+ return JSON.parse(out.stdout) as ArchivesJson;+ };++ const ingestOne = (+ contents: string,+ rel = "Articles/counted.md",+ ): { hash: string; summaryPath: string } => {+ mkdirSync(join(vault, rel, ".."), { recursive: true });+ writeFileSync(join(vault, rel), contents, "utf8");+ const res = ingestCore(+ vault,+ {+ sourcePath: rel,+ summary: "Counted.",+ extraction: { entities: [{ category: "concept", name: "Counted" }], relations: [] },+ },+ { agent: "test-agent", now: new Date("2026-02-03T00:00:00Z") },+ );+ if (res.sourceArchiveHash === undefined) throw new Error("expected an archive stamp");+ return { hash: res.sourceArchiveHash, summaryPath: res.summaryPath };+ };++ test("a vault that never archived reports an all-zero section, and prints no line", async () => {+ expect(await doctorJson()).toMatchObject({+ archives: { entries: 0, totalBytes: 0, missing: 0, mismatched: 0, uncited: 0 },+ });+ const human = await runCli(["brain", "doctor", "--vault", vault], { env: env() });+ expect(human.returncode).toBe(0);+ expect(human.stdout).not.toContain("archives:");+ });++ test("an ingested source is one entry with its bytes, on both surfaces", async () => {+ ingestOne("counted bytes\n");+ // Whole-object, not a subset match: a key smuggled into the section+ // (or an old shape drifting back) fails here.+ expect((await doctorJson()).archives).toEqual({+ entries: 1,+ totalBytes: Buffer.byteLength("counted bytes\n", "utf8"),+ missing: 0,+ mismatched: 0,+ uncited: 0,+ });++ const human = await runCli(["brain", "doctor", "--vault", vault], { env: env() });+ expect(human.stdout).toContain(+ `archives: 1 entries, ${Buffer.byteLength("counted bytes\n", "utf8")} bytes, 0 missing, 0 mismatched, 0 uncited`,+ );+ });++ test("a removed entry counts as missing; a tampered one as mismatched", async () => {+ const { hash } = ingestOne("audited bytes\n");+ const entry = join(vault, "Brain", ".archives", `${hash}.txt`);++ rmSync(entry);+ expect((await doctorJson()).archives).toMatchObject({ entries: 0, missing: 1 });++ writeFileSync(entry, "rewritten", "utf8");+ expect((await doctorJson()).archives).toMatchObject({ entries: 1, mismatched: 1 });+ });++ test("a page deleted out-of-band leaves its entry counted as uncited", async () => {+ // Two sources, two distinct entries. Removing the first summary page+ // out-of-band - the state a re-stamped page or a review-rejected staged+ // ingest leaves behind - leaves its entry in the store, cited by+ // nothing, while the second entry keeps its page.+ const first = ingestOne("orphaned bytes\n", "Articles/orphaned.md");+ const second = ingestOne("still cited bytes\n", "Articles/cited.md");+ expect(first.hash).not.toBe(second.hash);+ rmSync(join(vault, first.summaryPath));++ expect((await doctorJson()).archives).toMatchObject({+ entries: 2,+ uncited: 1,+ missing: 0,+ mismatched: 0,+ });++ const human = await runCli(["brain", "doctor", "--vault", vault], { env: env() });+ expect(human.stdout).toContain(", 1 uncited");+ });++ test("an unreadable archive store is an uncertain section, not a failed run", async () => {+ // Platform-neutral refusal: a FILE standing where the store directory+ // belongs. A chmod cannot deny on Windows.+ writeFileSync(join(vault, "Brain", ".archives"), "not a directory", "utf8");++ // A completed run, not a throw - and the human surface names the skip.+ const human = await runCli(["brain", "doctor", "--vault", vault], { env: env() });+ expect(human.returncode).toBe(0);+ expect(human.stdout).toContain("[UNSURE] vault-walk-entry-skipped");+ expect(human.stdout).not.toContain("archives: ");++ // The JSON payload stays parseable, answers the unavailability by name,+ // and carries the skip in the uncertainty stream.+ const out = await runCli(["brain", "doctor", "--vault", vault, "--json"], { env: env() });+ expect(out.returncode).toBe(0);+ const payload = JSON.parse(out.stdout) as {+ archives: Record<string, unknown>;+ uncertain?: ReadonlyArray<{ code: string; path?: string }>;+ };+ expect(payload.archives).toEqual({ unavailable: true });+ expect(payload.uncertain?.some((u) => u.code === "vault-walk-entry-skipped")).toBe(true);+ });+});diff --git a/tests/cli/brain-session-summary.test.ts b/tests/cli/brain-session-summary.test.tsindex 1004b87b..75387f3e 100644--- a/tests/cli/brain-session-summary.test.ts+++ b/tests/cli/brain-session-summary.test.ts@@ -21,6 +21,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { appendSessionSummary } from "../../src/core/brain/session-summary.ts";+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";import { runCli } from "../helpers/run-cli.ts";let tmp: string;@@ -214,3 +215,31 @@ test("get for an unknown session --json prints exactly the found:false envelope"expect(r.returncode).toBe(0);expect(r.stdout).toBe(`${JSON.stringify({ found: false }, null, 2)}\n`);});++test("list renders a no-session digest without crashing and without fabricating an id", async () => {+ // Seeded directly, the way a writer that stamps `session_id`+ // conditionally leaves the key absent.+ appendContinuityRecord(vault, {+ kind: "session_summary_digest",+ createdAt: "2026-06-14T10:00:00.000Z",+ sourceRefs: [{ id: "s-none", kind: "session" }],+ payload: { decisions: ["unattributed"], content_hash: "0123456789abcdef" },+ });++ const json = await run(["list", "--json"]);+ expect(json.returncode).toBe(0);+ const payload = JSON.parse(json.stdout) as {+ count: number;+ digests: Array<Record<string, unknown>>;+ };+ expect(payload.count).toBe(1);+ expect("session_id" in payload.digests[0]!).toBe(false);+ expect(payload.digests[0]!.decisions).toEqual(["unattributed"]);++ const text = await run(["list"]);+ expect(text.returncode).toBe(0);+ expect(text.stdout).toContain("1 session summary record(s)");+ // The session column holds the no-session stand-in, never a fabricated+ // id and never the empty string the old coercion produced.+ expect(text.stdout).toContain(" - d=1");+});diff --git a/tests/cli/brain-truth.test.ts b/tests/cli/brain-truth.test.tsindex 3231a072..f9fd006b 100644--- a/tests/cli/brain-truth.test.ts+++ b/tests/cli/brain-truth.test.ts@@ -12,6 +12,7 @@ import { join } from "node:path";import { appendClaimEvent, readClaimEvents } from "../../src/core/brain/truth/store.ts";import { upsertEntity } from "../../src/core/brain/entities/registry.ts";+import { emitContextReceipt } from "../../src/core/brain/context-receipts.ts";import { runCli } from "../helpers/run-cli.ts";let tmp: string;@@ -559,3 +560,213 @@ test("facts decompose without --ingest leaves the ledger untouched", async () =>expect(res.returncode).toBe(0);expect(readClaimEvents(vault).events).toHaveLength(0);});++// ----- --sample-id + provenance-hydrated reads (answer-trust, task B5) -----++function writeCliSourcePage(name: string): void {+ const dir = join(vault, "Brain", "notes");+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, name), `---\nkind: note\n---\n\n${name} source page\n`);+}++test("truth state --sample-id threads the id and the ledger freezes it", async () => {+ seedCliRegistry();+ const res = await runCli(+ stateArgs(vault, [+ "--subject",+ "Alice Mason",+ "--relation",+ "extends",+ "--object",+ "Atlas",+ "--text",+ "Alice Mason said the Atlas extension plan is ready for review today.",+ "--source",+ "[[Brain/notes/session.md]]",+ "--sample-id",+ "rcpt-2026-0601-abcd",+ ]),+ );+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as unknown as StateBody;+ expect(body.committed).toHaveLength(1);+ const row = body.committed[0] as Record<string, unknown>;+ expect(row["sample_id"]).toBe("rcpt-2026-0601-abcd");+ const [stored] = readClaimEvents(vault).events;+ expect(stored!.sample_id).toBe("rcpt-2026-0601-abcd");+});++test("truth state refuses a blank --sample-id as a usage error, writing nothing", async () => {+ // The same named refusal the MCP path answers, mapped to the+ // usage-error class; a blank id is never coerced to an absent one.+ seedCliRegistry();+ const res = await runCli(+ stateArgs(vault, [+ "--subject",+ "Alice Mason",+ "--relation",+ "extends",+ "--object",+ "Atlas",+ "--text",+ "Alice Mason said the Atlas extension plan is ready for review today.",+ "--source",+ "[[Brain/notes/session.md]]",+ "--sample-id",+ " ",+ ]),+ );+ expect(res.returncode).toBe(2);+ expect(res.stderr).toMatch(/sample_id/);+ expect(readClaimEvents(vault).events).toHaveLength(0);+});++test("truth state refuses an over-long or control-character --sample-id, naming the limit", async () => {+ // L2.1 regression: the stated boundary's shape check - at most 256+ // characters, no control characters - surfaces as the same usage-error+ // class as the blank-id refusal, on the CLI path too.+ seedCliRegistry();+ for (const bad of ["r".repeat(300), "rcpt\u0000-1", "rcpt\u0007-1"]) {+ const res = await runCli(+ stateArgs(vault, [+ "--subject",+ "Alice Mason",+ "--relation",+ "extends",+ "--object",+ "Atlas",+ "--text",+ "Alice Mason said the Atlas extension plan is ready for review today.",+ "--source",+ "[[Brain/notes/session.md]]",+ "--sample-id",+ bad,+ ]),+ );+ expect(res.returncode).toBe(2);+ expect(res.stderr).toMatch(+ /sample_id must be a non-empty string of at most 256 characters without control characters/,+ );+ }+ expect(readClaimEvents(vault).events).toHaveLength(0);+});++test("truth state --sample-id threads a padded id trimmed, matching the stored form", async () => {+ // L2.2 regression: both paths apply the same trim, so the threaded id+ // and the stored id are identical whatever padding the caller sent.+ seedCliRegistry();+ const res = await runCli(+ stateArgs(vault, [+ "--subject",+ "Alice Mason",+ "--relation",+ "extends",+ "--object",+ "Atlas",+ "--text",+ "Alice Mason said the Atlas extension plan is ready for review today.",+ "--source",+ "[[Brain/notes/session.md]]",+ "--sample-id",+ " rcpt-2026-0601-abcd ",+ ]),+ );+ expect(res.returncode).toBe(0);+ const row = (JSON.parse(res.stdout) as unknown as StateBody).committed[0] as Record<+ string,+ unknown+ >;+ expect(row["sample_id"]).toBe("rcpt-2026-0601-abcd");+ const [stored] = readClaimEvents(vault).events;+ expect(stored!.sample_id).toBe("rcpt-2026-0601-abcd");+});++test("truth events hydrates provenance for a claim carrying a sample id", async () => {+ seedCliRegistry();+ writeCliSourcePage("session.md");+ // An explicit past stamp: a defaulted `now` receipt can land up to a+ // second AFTER the claim's floored assertion stamp, which is a genuine+ // timestamp inversion the join must flag - the fixture keeps the+ // receipt unambiguously before the claim.+ const receipt = emitContextReceipt(vault, {+ options: { host: "cli", trigger: "context_pack", createdAt: "2026-06-02T09:00:00.000Z" },+ items: [{ id: "note-alpha", path: "Brain/notes/alpha.md", tokens: 40 }],+ finalText: "the final answer text",+ });+ const stated = await runCli(+ stateArgs(vault, [+ "--subject",+ "Alice Mason",+ "--relation",+ "extends",+ "--object",+ "Atlas",+ "--text",+ "Alice Mason said the Atlas extension plan is ready for review today.",+ "--source",+ "[[Brain/notes/session.md]]",+ "--sample-id",+ receipt.id,+ ]),+ );+ expect(stated.returncode).toBe(0);+ const res = await runCli(["brain", "truth", "events", "--vault", vault, "--json"]);+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as unknown as {+ events: ReadonlyArray<+ Record<string, unknown> & {+ provenance?: {+ sample_id: string;+ receipt: { id: string } | null;+ outcome: unknown | null;+ timestamp_inverted: boolean;+ };+ }+ >;+ };+ expect(body.events).toHaveLength(1);+ const provenance = body.events[0]!.provenance!;+ expect(provenance.sample_id).toBe(receipt.id);+ expect(provenance.receipt!.id).toBe(receipt.id);+ // Outcome unknown - absent, never invented.+ expect(provenance.outcome).toBeNull();+ expect(provenance.timestamp_inverted).toBe(false);+});++test("truth state without --sample-id leaves the row and events byte-identical to today", async () => {+ // The CLI mirror of the MCP-side pin: omitting the flag commits a row+ // carrying NO sample_id, and the events payload for that row carries+ // neither sample_id nor a provenance key - the join hydrates nothing+ // for a claim with no attribution id.+ seedCliRegistry();+ writeCliSourcePage("session.md");+ const res = await runCli(+ stateArgs(vault, [+ "--subject",+ "Alice Mason",+ "--relation",+ "extends",+ "--object",+ "Atlas",+ "--text",+ "Alice Mason said the Atlas extension plan is ready for review today.",+ "--source",+ "[[Brain/notes/session.md]]",+ ]),+ );+ expect(res.returncode).toBe(0);+ const body = JSON.parse(res.stdout) as unknown as StateBody;+ expect(body.committed).toHaveLength(1);+ const row = body.committed[0] as Record<string, unknown>;+ expect("sample_id" in row).toBe(false);+ const [stored] = readClaimEvents(vault).events;+ expect("sample_id" in stored!).toBe(false);+ const events = await runCli(["brain", "truth", "events", "--vault", vault, "--json"]);+ expect(events.returncode).toBe(0);+ const eventsBody = JSON.parse(events.stdout) as unknown as {+ events: ReadonlyArray<Record<string, unknown>>;+ };+ expect(eventsBody.events).toHaveLength(1);+ expect("sample_id" in eventsBody.events[0]!).toBe(false);+ expect("provenance" in eventsBody.events[0]!).toBe(false);+});diff --git a/tests/core/architecture/claim-attribution-census.test.ts b/tests/core/architecture/claim-attribution-census.test.tsnew file mode 100644index 00000000..f82c2d00--- /dev/null+++ b/tests/core/architecture/claim-attribution-census.test.ts@@ -0,0 +1,191 @@+/**+ * Claim-attribution census (answer-trust, task B6).+ *+ * The claim-attribution card adds an optional `sample_id` to the claim+ * path and a READ-ONLY join (`truth/claim-provenance.ts`) that resolves+ * it at read time. Two invariants make that card safe, and either+ * failing stops the lane:+ *+ * (a) The continuity record-kind vocabulary is unchanged by the wave.+ * The join reads existing `context_receipt` and+ * `context_pack_outcome` rows (and the `context_pack_evidence`+ * verdict row posted beside them) and introduces no new kind. A+ * per-statement provenance row was the rejected design - this+ * census is the guard that keeps the rejection binding: parse the+ * `ContinuityRecordKind` union out of its source and pin its+ * exact member set.+ *+ * (b) No recall-time writes. The `truth/` modules - the ledger store,+ * the stated-claims boundary, and the provenance join - import no+ * continuity append path. Reading a claim's provenance can never+ * become a write, no matter the caller or the reach, because no+ * module in the subsystem can even name the append surface.+ *+ * Like its sibling censuses, this one reads a LEXED view of each module+ * (`tests/helpers/source-lexer.ts`), so an append path named in a+ * docblock is not an import and a call inside a string literal is not a+ * site.+ */++import { describe, expect, test } from "bun:test";+import { readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";++import { lexSource } from "../../helpers/source-lexer.ts";++const TRUTH_DIR = join(import.meta.dir, "..", "..", "..", "src", "core", "brain", "truth");+const CONTINUITY_TYPES_PATH = join(+ import.meta.dir,+ "..",+ "..",+ "..",+ "src",+ "core",+ "brain",+ "continuity",+ "types.ts",+);+const CLAIM_PROVENANCE_PATH = join(TRUTH_DIR, "claim-provenance.ts");++/**+ * The append surface of the continuity store and its emit helpers, plus+ * every typed writer that lands a continuity row behind a gate. Any of+ * these identifiers appearing in a `truth/` module's code view is a+ * recall-time write.+ */+const CONTINUITY_APPEND_IDENTIFIERS: ReadonlyArray<string> = Object.freeze([+ "appendContinuityRecord",+ "emitGatedTelemetry",+ "appendLogEvent",+ "emitContextReceipt",+ "emitContextPackOutcome",+ "postContextPackOutcome",+ "recordContextPackEvidence",+ "recordTokenImpactOutcome",+]);++/**+ * Vault write primitives the provenance join must never touch: it+ * performs NO vault writes, so it may not even bind `node:fs`.+ */+const CLAIM_PROVENANCE_FORBIDDEN_WRITE_CALLS: ReadonlyArray<string> = Object.freeze([+ "appendFileSync",+ "writeFileSync",+ "mkdirSync",+ "rmSync",+ "unlinkSync",+ "appendFile",+ "writeFile",+ "mkdir",+ "rm",+ "cpSync",+]);++/** The kind vocabulary exactly as the wave found it (see invariant (a)). */+const PINNED_CONTINUITY_KINDS: ReadonlyArray<string> = Object.freeze([+ "context_receipt",+ "recall_telemetry",+ "gate_telemetry",+ "pre_compact_extract",+ "post_compact_audit",+ "session_turn",+ "recent_turn",+ "session_summary_node",+ "session_summary_digest",+ "generation_report",+ "ingest_dedup",+ "mcp_route_latency",+ "token_impact",+ "token_impact_outcome",+ "context_pack_outcome",+ "context_pack_evidence",+ "host_memory_write",+ "recall_observed_use",+ "skill_invoked",+ "source_invalidation",+ "negative_recall",+ "decision_model_call",+ "decision_model_extract_commit",+ "session_entity_mention",+]);++function truthModulePaths(): ReadonlyArray<string> {+ return readdirSync(TRUTH_DIR)+ .filter((name) => name.endsWith(".ts"))+ .toSorted()+ .map((name) => join(TRUTH_DIR, name));+}++function truthModuleNames(): ReadonlyArray<string> {+ return readdirSync(TRUTH_DIR)+ .filter((name) => name.endsWith(".ts"))+ .toSorted();+}++/** Parse the `ContinuityRecordKind` union's string members out of source. */+function continuityKindVocabulary(): ReadonlyArray<string> {+ const text = readFileSync(CONTINUITY_TYPES_PATH, "utf8");+ // The union's docblocks quote words ("no") that are not members; parse+ // the comment-blanked view so a quotation in a comment is not a kind -+ // the same discipline the sibling censuses document.+ const code = lexSource(text).withoutComments;+ const marker = "export type ContinuityRecordKind =";+ const start = code.indexOf(marker);+ expect(start).toBeGreaterThanOrEqual(0);+ const end = code.indexOf(";", start);+ expect(end).toBeGreaterThan(start);+ const segment = code.slice(start, end);+ return [...segment.matchAll(/"([a-z_]+)"/g)].map((match) => match[1]!);+}++describe("claim-attribution census", () => {+ test("the sweep sees the truth subsystem, join included", () => {+ // A census over an empty directory is a claim about a census; pin+ // the population and the join's presence in it.+ const names = truthModuleNames();+ expect(names.length).toBeGreaterThanOrEqual(10);+ expect(names).toContain("store.ts");+ expect(names).toContain("stated-claims.ts");+ expect(names).toContain("claim-provenance.ts");+ });++ test("(a) the continuity record-kind vocabulary is unchanged by the wave", () => {+ // The wave introduces no new kind; the join reads existing+ // `context_receipt` and `context_pack_outcome` rows. A new member+ // here means a lane is minting a record kind the plan refused.+ const kinds = continuityKindVocabulary();+ expect(kinds.toSorted()).toEqual(PINNED_CONTINUITY_KINDS.toSorted());+ });++ test("(a) the pinned vocabulary contains the kinds the join reads", () => {+ // The join's inputs must stay existing, named kinds - if one of+ // these leaves the vocabulary the join reads nothing and the card+ // has silently rotted.+ const kinds = continuityKindVocabulary();+ for (const kind of ["context_receipt", "context_pack_outcome", "context_pack_evidence"]) {+ expect(kinds).toContain(kind);+ }+ });++ test("(b) no truth module imports or calls a continuity append path", () => {+ // Checked on the code view (comments and literal contents blanked):+ // an append path discussed in a docblock is not an import, and the+ // match covers every import shape - named, renamed, namespace,+ // dynamic - because it matches the identifier itself.+ const offenders: string[] = [];+ for (const path of truthModulePaths()) {+ const code = lexSource(readFileSync(path, "utf8")).code;+ for (const identifier of CONTINUITY_APPEND_IDENTIFIERS) {+ if (code.includes(identifier)) offenders.push(`${path}: ${identifier}`);+ }+ }+ expect(offenders).toEqual([]);+ });++ test("(b) claim-provenance.ts performs no vault writes and binds no fs module", () => {+ const code = lexSource(readFileSync(CLAIM_PROVENANCE_PATH, "utf8")).code;+ expect(code).not.toMatch(/node:fs/);+ const offenders = CLAIM_PROVENANCE_FORBIDDEN_WRITE_CALLS.filter((call) => code.includes(call));+ expect(offenders).toEqual([]);+ });+});diff --git a/tests/core/architecture/source-archive-stamp-census.test.ts b/tests/core/architecture/source-archive-stamp-census.test.tsnew file mode 100644index 00000000..41b33d89--- /dev/null+++ b/tests/core/architecture/source-archive-stamp-census.test.ts@@ -0,0 +1,171 @@+/**+ * Source-archive stamp census (answer trust, security F5).+ *+ * The delete-by-source citation probe (`sourceArchiveCitingPages`) sees+ * only `Brain/sources/` and `Brain/pending/` - the two directories the+ * ingest lane stamps. A frontmatter-bearing COPY of a stamped page+ * anywhere else would cite an entry the probe misses, and a confirmed+ * deletion would then remove an entry another page still names. The cheap+ * honest guard is this census: the `source_archive_hash` frontmatter key+ * has exactly ONE writer - the ingest lane's stamp site, which composes+ * the key from the store's own constant - so the two-directory walk is+ * exhaustive by construction, and any second writer of the key fails+ * here, by file name, before it can silence a cleanup.+ *+ * Like its sibling censuses, this one reads a LEXED view of each module+ * (`tests/helpers/source-lexer.ts`), so the key discussed in a docblock+ * is not a reference and a page-write named in a string literal is not a+ * site.+ */++import { describe, expect, test } from "bun:test";+import { readdirSync, readFileSync, statSync } from "node:fs";+import { join, posix, relative, sep, win32 } from "node:path";++import { lexSource } from "../../helpers/source-lexer.ts";++const SRC_ROOT = join(import.meta.dir, "..", "..", "..", "src");++/**+ * One walked entry, as a POSIX path relative to `root`.+ *+ * The PLATFORM `relative`, never `posix.relative`: a walker on Windows+ * yields drive-prefixed absolute entries (`D:\a\...`), which+ * `posix.relative` treats as one segment - it answered `../D:\a\...`, and+ * `join(SRC_ROOT, ...)` doubled the root back on, naming files that do+ * not exist (`...\open-second-brain\D:\a\...\src\...`) and red on every+ * shard. The platform answer is split on the platform separator and+ * re-joined with `/`, so every consumer - on either platform - sees the+ * POSIX spellings the closed sets below are written in. Both arguments+ * are absolute on the host, and an absolute path is exactly what the+ * walker hands over, so the same call relativizes it.+ */+function relativize(+ root: string,+ abs: string,+ path: Pick<typeof posix, "relative" | "sep"> = { relative, sep },+): string {+ return path.relative(root, abs).split(path.sep).join("/");+}++/** The frontmatter key, in both of its spellings. */+const STAMP_KEY_IDENTIFIER = "SOURCE_ARCHIVE_HASH_KEY";+const STAMP_KEY_LITERAL = "source_archive_hash";++/**+ * The closed set of modules allowed to reference the stamp key at all:+ * the store that defines the constant and answers the citation probe, the+ * ingest lane that is the ONE writer, the hygiene detector that verifies+ * stamps, and the two MCP surfaces that read stamps for cleanup and name+ * the key in the archive_get schema.+ */+const STAMP_KEY_FILES: ReadonlyArray<string> = Object.freeze([+ posix.join("core", "brain", "hygiene", "detectors", "capture-scope.ts"),+ posix.join("core", "brain", "ingest", "ingest.ts"),+ posix.join("core", "brain", "provenance", "source-archive.ts"),+ posix.join("mcp", "brain", "hygiene-tools.ts"),+ posix.join("mcp", "brain", "ingest-tools.ts"),+]);++/** The one writer among them - the ingest lane's stamp site. */+const STAMP_WRITER = posix.join("core", "brain", "ingest", "ingest.ts");++/** The constant's definition site - the only home of the literal spelling. */+const STAMP_CONSTANT_HOME = posix.join("core", "brain", "provenance", "source-archive.ts");++/**+ * The page-write primitives. Binding one beside the stamp key is what+ * makes a module a WRITER of the stamp; a reader (detector, cleanup,+ * schema prose) binds none of them.+ */+const PAGE_WRITE_PRIMITIVES: ReadonlyArray<string> = Object.freeze([+ "writeFrontmatterAtomic",+ "formatFrontmatter",+]);++/** Every .ts file under src, as POSIX paths relative to it, sorted. */+function srcModulePaths(): ReadonlyArray<string> {+ const out: string[] = [];+ const walk = (dir: string): void => {+ for (const name of readdirSync(dir).toSorted()) {+ const abs = join(dir, name);+ if (statSync(abs).isDirectory()) {+ walk(abs);+ continue;+ }+ if (name.endsWith(".ts")) out.push(relativize(SRC_ROOT, abs));+ }+ };+ walk(SRC_ROOT);+ return out;+}++/** Does this module reference the stamp key - identifier or literal? */+function referencesStampKey(path: string): boolean {+ const views = lexSource(readFileSync(join(SRC_ROOT, path), "utf8"));+ // `code` keeps identifiers and blanks string contents; `withoutComments`+ // keeps string contents - so the identifier is read off the code view,+ // the literal spelling off the view that carries strings.+ return (+ views.code.includes(STAMP_KEY_IDENTIFIER) || views.withoutComments.includes(STAMP_KEY_LITERAL)+ );+}++describe("source-archive stamp census", () => {+ test("the sweep sees the vault-facing src tree", () => {+ // A census over an empty sweep is a claim about a census; pin the+ // population's scale and the two load-bearing members' presence.+ const paths = srcModulePaths();+ expect(paths.length).toBeGreaterThan(100);+ expect(paths).toContain(STAMP_WRITER);+ expect(paths).toContain(STAMP_CONSTANT_HOME);+ });++ test("the key is referenced only by the closed set around the store", () => {+ // Any spelling - the store's identifier or the bare literal - outside+ // this set means a module composes or parses the stamp itself: a new+ // writer the citation probe would miss, named here before it can+ // silence a delete-by-source cleanup.+ const referencing = srcModulePaths().filter((path) => referencesStampKey(path));+ expect(referencing.toSorted()).toEqual(STAMP_KEY_FILES.toSorted());+ });++ test("the only key reference that writes a page is the ingest stamp site", () => {+ // This is the one-writer assumption the citation probe rests on,+ // stated as architecture: among the modules that reference the key,+ // exactly one binds a page-write primitive, and it takes the key from+ // the store's constant, never a second literal.+ const writers = srcModulePaths().filter((path) => {+ if (!referencesStampKey(path)) return false;+ const code = lexSource(readFileSync(join(SRC_ROOT, path), "utf8")).code;+ return PAGE_WRITE_PRIMITIVES.some((primitive) => code.includes(primitive));+ });+ expect(writers).toEqual([STAMP_WRITER]);+ const writerCode = lexSource(readFileSync(join(SRC_ROOT, STAMP_WRITER), "utf8")).code;+ expect(writerCode.includes(STAMP_KEY_IDENTIFIER)).toBe(true);+ });+});++describe("the sweep's relativization", () => {+ test("a drive-letter absolute entry relativizes to its POSIX walk path", () => {+ // The windows (2/10) CI failure, replayed through path.win32: a+ // walker under a drive-letter SRC_ROOT yields `D:\...` entries, and+ // the `posix.relative` spelling - pinned failing below - never+ // answers the plain walk for one. The platform flavor does, and the+ // separator re-join spells the answer POSIX.+ const root = win32.join("D:\\a\\open-second-brain", "src");+ const abs = win32.join(root, "cli", "advisory-rail.ts");+ expect(win32.isAbsolute(abs)).toBe(true);+ expect(posix.relative(root, abs)).not.toBe("cli/advisory-rail.ts");+ expect(relativize(root, abs, win32)).toBe("cli/advisory-rail.ts");+ });++ test("an absolute entry handed over by this platform's walker relativizes identically", () => {+ // The sweep is robust to a walker that yields absolute paths: the+ // same call relativizes one, to the spelling every consumer reads.+ const abs = join(SRC_ROOT, "core", "brain", "provenance", "source-archive.ts");+ expect(relativize(SRC_ROOT, abs)).toBe(+ posix.join("core", "brain", "provenance", "source-archive.ts"),+ );+ });+});diff --git a/tests/core/architecture/state-surface-census.test.ts b/tests/core/architecture/state-surface-census.test.tsindex e2863768..774060ac 100644--- a/tests/core/architecture/state-surface-census.test.ts+++ b/tests/core/architecture/state-surface-census.test.ts@@ -82,9 +82,9 @@ const STORE_DIR_IDENTIFIER = "DERIVED_STORE_DIR";const SWEPT_POPULATION_SIZE = 24;/** Declared surfaces today. Pinned for the same reason. */-// 49: the decisions-ledger row (Task 2) and the bootstrap receipt row-// (Task 14) both join the population.-const DECLARED_SURFACE_COUNT = 49;+// 50: the source-archives row (answer-trust Task C1) joins the population,+// the same join the decisions ledger and the bootstrap receipt made.+const DECLARED_SURFACE_COUNT = 50;/** An exclusion reason has to be an argument, not a label. */const MIN_REASON_LENGTH = 80;diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.tsindex 11dcea8a..7eddfc8a 100644--- a/tests/core/architecture/verdict-vocabulary-census.test.ts+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts@@ -500,6 +500,16 @@ import {MANIFEST_STATUS,MANIFEST_STATUSES,} from "../../../src/core/brain/architect/manifests.ts";+import {+ ANSWER_QUOTE_VERDICT,+ ANSWER_QUOTE_VERDICTS,+ isAnswerQuoteVerdict,+} from "../../../src/core/brain/answer-quotes/check.ts";+import {+ ARCHIVE_VERIFICATION,+ ARCHIVE_VERIFICATIONS,+ isArchiveVerification,+} from "../../../src/core/brain/provenance/source-archive.ts";interface VocabularyUnderCensus {/** Identifies the vocabulary in a failure message. */@@ -1552,6 +1562,30 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([members: REVIEW_LANES,guard: isReviewLane,},+ {+ // The verdict on one quoted span of a host answer (answer-trust wave,+ // Lane A). It rides the Stop hook's annotation and the enforce trail's+ // Brain-log event, and its degradation members are the point: a+ // truncated note can under-deliver evidence but never acquits a span+ // (`source-truncated`), and "we could not check" is a finding, not an+ // all-clear (`note-unavailable`).+ name: "ANSWER_QUOTE_VERDICT",+ values: ANSWER_QUOTE_VERDICT,+ members: ANSWER_QUOTE_VERDICTS,+ guard: isAnswerQuoteVerdict,+ },+ {+ // What comparing a stamped archive digest against the entry it names+ // concluded (answer-trust wave, Lane C). It rides the capture-scope+ // detector's finding evidence and the archive read op, and the pair it+ // separates is the unit: `missing` (the evidence is gone) and+ // `mismatched` (the evidence disagrees with the page) are different+ // repairs, and a boolean would collapse them.+ name: "ARCHIVE_VERIFICATION",+ values: ARCHIVE_VERIFICATION,+ members: ARCHIVE_VERIFICATIONS,+ guard: isArchiveVerification,+ },]);// ---------------------------------------------------------------------------@@ -1816,7 +1850,9 @@ const SCANNED = scanVocabularies(SOURCE_TREE);* How many four-piece vocabularies `src/` currently holds. Measured, and* kept as an equality rather than a floor - see the population test.*/-const VOCABULARY_POPULATION = 95;+// 97: Lane C's ARCHIVE_VERIFICATION (answer trust) joins the scanned+// population, the same append Lane A's ANSWER_QUOTE_VERDICT made.+const VOCABULARY_POPULATION = 97;const REGISTERED = new Map(CENSUS.map((entry) => [entry.name, entry] as const));describe("verdict vocabulary census", () => {diff --git a/tests/core/architecture/visibility-surface-census.test.ts b/tests/core/architecture/visibility-surface-census.test.tsindex 9441b158..dc0c6465 100644--- a/tests/core/architecture/visibility-surface-census.test.ts+++ b/tests/core/architecture/visibility-surface-census.test.ts@@ -596,8 +596,16 @@ function reasonProblems(entries: ReadonlyArray<VisibilitySurfaceEntry>): {* receipt envelope. The four new names are `brain_create_note`,* `brain_update_note`, `brain_append_note` and `brain_write_batch`, whose* near-duplicate hint named sibling pages the caller could not read.+ *+ * 80 before the ingest suite's cleanup began reading page frontmatter for+ * the archive-orphan decision (answer trust), which made+ * `ingest-tools.ts` itself a note-content importer and swept in every tool+ * it registers on the file-level rule. The four new names are+ * `brain_ingest_source`, `brain_search_by_source`, `brain_delete_by_source`+ * and `brain_ingest_batch_plan`; each was already asking a read root at its+ * read site, so all four classify as covered.*/-const MCP_TOOL_POPULATION_SIZE = 80;+const MCP_TOOL_POPULATION_SIZE = 84;/** Measured: MCP resources + templates. */const MCP_RESOURCE_POPULATION_SIZE = 8;/** Measured: hand-enumerated CLI verb mirrors. */@@ -668,6 +676,7 @@ describe("visibility surface census", () => {"brain_dead_ends","brain_decision","brain_deep_synthesis",+ "brain_delete_by_source","brain_derive_fact","brain_diarize","brain_doctor",@@ -680,6 +689,8 @@ describe("visibility surface census", () => {"brain_health","brain_hygiene","brain_idea_discovery",+ "brain_ingest_batch_plan",+ "brain_ingest_source","brain_intent_review","brain_intention","brain_labels",@@ -695,6 +706,7 @@ describe("visibility surface census", () => {"brain_review_candidates","brain_scaffold_stub","brain_search",+ "brain_search_by_source","brain_search_expand","brain_skill_proposals","brain_stale_scan",diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.tsindex 54df94de..12248147 100644--- a/tests/core/architecture/write-site-census.test.ts+++ b/tests/core/architecture/write-site-census.test.ts@@ -604,6 +604,16 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object"mechanism here; the surviving records' rewrites go through " +"`writeFrontmatterAtomic` in the same block.",},+ "src/core/brain/provenance/source-archive.ts": {+ categories: [C.retentionDelete],+ calls: ["rmSync"],+ reason:+ "discards one content-addressed archive entry when delete-by-source has established " ++ "its last citing page is in the same confirmed deletion - the store's write half (the " ++ "redacted put) routes through `atomicWriteFileSync`, and a removal is not a write any " ++ "shared writer has a form for. The path is derived from the entry's own sha-256 and " ++ "validated before the join, so the only file this call can address is the entry named.",+ },"src/core/brain/exact-state.ts": {categories: [C.retentionDelete],calls: ["rmSync"],@@ -1298,8 +1308,14 @@ const DIRECT_ROWS = ROWS.filter((row) => row.directCalls.length > 0);* page into the review queue - stage, then unlink the canonical copy. A* lifecycle move authors no content; the unlink is the site's only* direct call.+ *+ * 81 -> 82: the source archive (`src/core/brain/provenance/+ * source-archive.ts`) discards an entry whose last citing page a+ * confirmed delete-by-source removed - an evidence-store prune whose+ * only direct call is the rmSync; its write half routes through the+ * shared atomic writer.*/-const DIRECT_WRITE_ROWS = 81;+const DIRECT_WRITE_ROWS = 82;/*** Measured modules reaching a write through a shared helper. An equality.@@ -1390,8 +1406,15 @@ const DIRECT_WRITE_ROWS = 81;* hallways pass (`src/core/brain/link-graph/hallways.ts`) writes* `Brain/link-graph/hallways.json` and its dismissal keys through the* same helper class.+ *+ * 117 -> 119, from the answer-trust wave and nothing else: the source+ * archive (`src/core/brain/provenance/source-archive.ts`) persists its+ * redacted entries through `atomicWriteFileSync`, and `src/core/config.ts`+ * joins the population through its new `path-constants.ts` import (the+ * quote_check resolvers) carrying the config write it already made+ * through the same shared writer.*/-const SHARED_HELPER_ROWS = 117;+const SHARED_HELPER_ROWS = 119;// ----- Origin-channel coverage boundary (Unit C) ----------------------------@@ -1467,9 +1490,12 @@ const STAMPED_PATHS: ReadonlySet<string> = new Set(* 77 -> 78: the per-agent MCP token store's custody swap (hash-at-rest* state, not notes).* 78 -> 79: the intake's stage-disposition page move (a lifecycle move- * whose only direct call is the unlink; it stamps no channel).+ * whose only direct call is the unlink; it stamps no channel).+ * 79 -> 80: the source archive's entry discard (answer trust) - a+ * content-addressed evidence prune whose last citing page the same+ * confirmed delete-by-source removed; no origin stamp on archive cleanup.*/-const UNSTAMPED_DIRECT_ROWS = 80;+const UNSTAMPED_DIRECT_ROWS = 81;/*** Shared-helper write sites the stamp does not reach, measured the same@@ -1496,9 +1522,14 @@ const UNSTAMPED_DIRECT_ROWS = 80;* not notes). 112 -> 114: the recall-quality wave's derived artifacts - the* shared derived-artifact helper and the hallways artifact with its* dismissal keys - write machine JSON through the shared atomic writer- * (derived state, not notes; no origin stamp on either).+ * (derived state, not notes; no origin stamp on either). 114 -> 116: the+ * answer-trust wave - the source archive persists its redacted entries+ * through the shared atomic writer (evidence bytes; no origin stamp on an+ * archive put), and the config writer joins the population through its new+ * path-constants import carrying the config write it already made (module+ * state, not notes).*/-const UNSTAMPED_SHARED_ROWS = 114;+const UNSTAMPED_SHARED_ROWS = 116;describe("in-vault write-site census", () => {test("every direct-fs write site carries a written exclusion", () => {diff --git a/tests/core/brain.idea-lineage.test.ts b/tests/core/brain.idea-lineage.test.tsindex 6c2dd0ca..2f435970 100644--- a/tests/core/brain.idea-lineage.test.ts+++ b/tests/core/brain.idea-lineage.test.ts@@ -126,6 +126,59 @@ describe("traceIdeaLineage over the continuity source graph", () => {});});+describe("idea lineage no-session semantics (t_22d58fa7)", () => {+ test("two no-session records never merge through a fabricated scope key", () => {+ // Store order decides the global turn index, so the string-session+ // turn is appended first. The second turn carries a NUMERIC session+ // id - the value the turn index used to stringify into a "5" scope,+ // merging two unrelated records into one group.+ const stringTurn = appendContinuityRecord(vault, {+ kind: "session_turn",+ createdAt: "2026-06-14T09:00:00.000Z",+ payload: { session_id: "real", turn_id: "t1", role: "user", text: "string session" },+ });+ appendContinuityRecord(vault, {+ kind: "session_turn",+ createdAt: "2026-06-14T09:30:00.000Z",+ payload: { session_id: 5, turn_id: "t1", role: "user", text: "numeric session" },+ });+ const referrer = appendContinuityRecord(vault, {+ kind: "session_summary_node",+ createdAt: "2026-06-14T10:00:00.000Z",+ sourceRefs: [{ id: "t1", kind: "session_turn" }],+ payload: { session_id: 5, depth: 1, summary: "numeric referrer" },+ });++ // A number names no session, so the referrer resolves through the+ // global turn index (store order), never through a fabricated "5"+ // scope that would bind it to the other numeric record.+ const result = traceIdeaLineage(vault, { id: referrer.id });+ expect(+ result.edges.some((edge) => edge.from === referrer.id && edge.to === stringTurn.id),+ ).toBe(true);+ const numericTurn = result.nodes.find((node) => node.label.includes("numeric session"));+ expect(numericTurn).toBeUndefined();+ });++ test("a record with no session still resolves its sources through the global turn index", () => {+ const orphanTurn = appendContinuityRecord(vault, {+ kind: "session_turn",+ createdAt: "2026-06-14T09:00:00.000Z",+ payload: { turn_id: "t9", role: "user", text: "unattributed observation" },+ });+ const orphanDigest = appendContinuityRecord(vault, {+ kind: "session_summary_digest",+ createdAt: "2026-06-14T10:00:00.000Z",+ sourceRefs: [{ id: "t9", kind: "session_turn" }],+ payload: { decisions: ["unattributed conclusion"], content_hash: "0123456789abcdef" },+ });++ const result = traceIdeaLineage(vault, { id: orphanDigest.id });+ expect(result.edges.some((edge) => edge.to === orphanTurn.id)).toBe(true);+ expect(result.truncated).toBe(false);+ });+});+describe("traceIdeaLineage for a preference (belief evolution)", () => {test("traces creation then promotion of a preference", () => {writeDream("2026-05-01", { run_id: "r1", new_unconfirmed: ["[[pref-foo|First rule]]"] });diff --git a/tests/core/brain.session-summary.test.ts b/tests/core/brain.session-summary.test.tsindex 425d07a3..fcf46ccc 100644--- a/tests/core/brain.session-summary.test.ts+++ b/tests/core/brain.session-summary.test.ts@@ -21,6 +21,7 @@ import {listContinuityRecords,appendContinuityRecord,} from "../../src/core/brain/continuity/store.ts";+import type { ContinuityRecord } from "../../src/core/brain/continuity/types.ts";let vault: string;@@ -425,3 +426,69 @@ describe("project scope (Task 18)", () => {expect(() => listSessionSummaries(vault, { project: "***" })).toThrow(SessionSummaryError);});});++describe("explicit no-session semantics (t_22d58fa7)", () => {+ /**+ * Seed one digest record whose payload names no session, the way a+ * writer that stamps `session_id` conditionally leaves the key absent.+ * `sessionId` replaces the identity wholesale, so a test can also seed a+ * non-string value - the coercion the reads used to perform.+ */+ function seedDigest(sessionId: unknown): ContinuityRecord {+ return appendContinuityRecord(vault, {+ kind: "session_summary_digest",+ createdAt: "2026-06-14T10:00:00.000Z",+ sourceRefs: [{ id: "s-x", kind: "session" }],+ payload: {+ decisions: ["unattributed"],+ content_hash: "0123456789abcdef",+ ...(sessionId !== undefined ? { session_id: sessionId } : {}),+ },+ });+ }++ test("no-session records are skipped by the reads, never matched against the empty string", () => {+ seedDigest(undefined);+ seedDigest(undefined);++ // The reads used to coerce the missing key to "" and answer a report+ // that lumped every unrelated no-session digest into one phantom+ // session; "" asks for a session that no writer ever named.+ expect(getSessionSummaryReport(vault, "")).toBeNull();+ expect(listSessionSummaries(vault, { sessionId: "" })).toEqual([]);+ });++ test("a non-string session_id is excluded, not coerced into a scope match", () => {+ const numeric = seedDigest(7);++ // The read used to stringify 7 and match a scope asked for as "7".+ expect(listSessionSummaries(vault, { sessionId: "7" })).toEqual([]);++ // Unscoped reads still return the record.+ expect(listSessionSummaries(vault).map((digest) => digest.id)).toEqual([numeric.id]);+ });++ test("a no-session digest carries no sessionId key, and a session digest keeps its own", () => {+ const blank = seedDigest(undefined);+ const attributed = appendSessionSummary(vault, {+ sessionId: "s-present",+ decisions: ["attributed"],+ createdAt: "2026-06-14T11:00:00.000Z",+ });++ const digests = listSessionSummaries(vault);+ const blankDigest = digests.find((digest) => digest.id === blank.id)!;+ expect("sessionId" in blankDigest).toBe(false);+ expect(Object.keys(blankDigest).toSorted()).toEqual([+ "createdAt",+ "decisions",+ "id",+ "learnings",+ "nextSteps",+ "request",+ ]);++ const presentDigest = digests.find((digest) => digest.id === attributed.id)!;+ expect(presentDigest.sessionId).toBe("s-present");+ });+});diff --git a/tests/core/brain/answer-quotes/check.test.ts b/tests/core/brain/answer-quotes/check.test.tsnew file mode 100644index 00000000..3340edf2--- /dev/null+++ b/tests/core/brain/answer-quotes/check.test.ts@@ -0,0 +1,308 @@+/**+ * The answer-time quote check: every quoted span of a host answer is+ * compared with the evidence the turn actually had - the note the span+ * cites, or the notes the injection ledger says entered context. Pure;+ * no I/O.+ *+ * The false-positive bar is the distill lane's own suite+ * (`tests/core/brain/distill/quote-check.test.ts`): every span that suite+ * verifies must verify here under the same evidence, because both lanes+ * run the same distill helpers (`findQuoteSpans`, `normalizeForQuoteComparison`,+ * `quoteHaystack`, `spanOccursIn`) imported in place.+ */++import { describe, expect, test } from "bun:test";++import {+ ANSWER_QUOTE_VERDICT,+ ANSWER_QUOTE_VERDICTS,+ checkAnswerQuotes,+ isAnswerQuoteVerdict,+ mergeAnswerQuoteVerdicts,+ type AnswerQuoteEvidence,+ type AnswerQuoteVerdict,+} from "../../../../src/core/brain/answer-quotes/check.ts";+import { QUOTE_SPAN_PREVIEW_MAX_CHARS } from "../../../../src/core/brain/distill/quote-verdict.ts";+import { findQuoteSpans } from "../../../../src/core/brain/distill/quote-spans.ts";++/**+ * The distill suite's source, verbatim, so its verified spans are the+ * mirror cases below under identical evidence.+ */+const SOURCE = [+ "# Restaking",+ "",+ "Restaking reuses staked capital to secure additional services. ^abc",+ "",+ "It introduces correlated **slashing** risk across",+ "every service at once. ^risk",+ "",+ 'He said "stake it" twice. ^said',+ "",+ "The first step, then the second step, and the final step. ^steps",+ "",+ "Duplicate one. ^dup",+ "",+ "Duplicate two. ^dup",+ "",+ "Café prices rose.",+].join("\n");++const TEXT: AnswerQuoteEvidence = { kind: "text", text: SOURCE, truncated: false };++function verdictOf(answer: string, evidence: AnswerQuoteEvidence = TEXT): string {+ const spans = findQuoteSpans(answer).spans.map((span) => span.inner);+ expect(spans.length).toBe(1);+ return checkAnswerQuotes({ spans, evidence }).outcomes[0]!.verdict;+}++describe("ANSWER_QUOTE_VERDICT vocabulary", () => {+ test("carries exactly the five pinned verdicts, in order", () => {+ expect(ANSWER_QUOTE_VERDICT).toEqual({+ verified: "verified",+ notInNote: "not-in-note",+ sourceTruncated: "source-truncated",+ noteUnavailable: "note-unavailable",+ notText: "not-text",+ });+ expect(ANSWER_QUOTE_VERDICTS).toEqual([+ "verified",+ "not-in-note",+ "source-truncated",+ "note-unavailable",+ "not-text",+ ]);+ });++ test("the object is frozen and the guard accepts only its members", () => {+ expect(Object.isFrozen(ANSWER_QUOTE_VERDICT)).toBe(true);+ expect(Object.isFrozen(ANSWER_QUOTE_VERDICTS)).toBe(true);+ for (const member of ANSWER_QUOTE_VERDICTS) {+ expect(isAnswerQuoteVerdict(member)).toBe(true);+ }+ for (const outsider of ["", "verified ", "Verified", "unverified", null, undefined, 42, {}]) {+ expect(isAnswerQuoteVerdict(outsider)).toBe(false);+ }+ });+});++describe("checkAnswerQuotes - the verdict table", () => {+ test("a span in the note text is verified", () => {+ expect(verdictOf("The note says “reuses staked capital” plainly.")).toBe(+ ANSWER_QUOTE_VERDICT.verified,+ );+ });++ test("a span absent from the note text is not-in-note", () => {+ expect(verdictOf("The note says “reuses pooled capital” plainly.")).toBe(+ ANSWER_QUOTE_VERDICT.notInNote,+ );+ });++ test("truncated text evidence: a hit verifies, a miss is source-truncated", () => {+ // `text` IS the available prefix - the part of the note that reached+ // context. The tail the pack cut away holds "Café prices rose."+ const truncated: AnswerQuoteEvidence = {+ kind: "text",+ text: SOURCE.split("\n").slice(0, 8).join("\n"),+ truncated: true,+ };+ expect(verdictOf("The note says “reuses staked capital”.", truncated)).toBe(+ ANSWER_QUOTE_VERDICT.verified,+ );+ expect(verdictOf("The note says “Café prices rose.”", truncated)).toBe(+ ANSWER_QUOTE_VERDICT.sourceTruncated,+ );+ });++ test("unavailable evidence is note-unavailable, whatever the span says", () => {+ expect(verdictOf("“anything at all”", { kind: "unavailable" })).toBe(+ ANSWER_QUOTE_VERDICT.noteUnavailable,+ );+ expect(verdictOf("“reuses staked capital”", { kind: "unavailable" })).toBe(+ ANSWER_QUOTE_VERDICT.noteUnavailable,+ );+ });++ test("non-text evidence is not-text", () => {+ expect(verdictOf("“reuses staked capital”", { kind: "not-text" })).toBe(+ ANSWER_QUOTE_VERDICT.notText,+ );+ });+});++describe("checkAnswerQuotes - the report shape", () => {+ test("outcomes carry the input index, the preview-capped span and the verdict, in input order", () => {+ const long = "word ".repeat(60).trim();+ const res = checkAnswerQuotes({+ spans: ["reuses staked capital", long, "reuses pooled capital"],+ evidence: TEXT,+ });+ expect(res.verified).toBe(1);+ expect(res.unverified).toBe(2);+ expect(res.outcomes).toEqual([+ { index: 0, span: "reuses staked capital", verdict: "verified" },+ { index: 1, span: long.slice(0, QUOTE_SPAN_PREVIEW_MAX_CHARS), verdict: "not-in-note" },+ { index: 2, span: "reuses pooled capital", verdict: "not-in-note" },+ ]);+ });++ test("no spans: an empty report with zero counters", () => {+ expect(checkAnswerQuotes({ spans: [], evidence: TEXT })).toEqual({+ outcomes: [],+ verified: 0,+ unverified: 0,+ });+ });+});++describe("checkAnswerQuotes - the distill suite's verified spans verify here", () => {+ // Mirror cases from tests/core/brain/distill/quote-check.test.ts: each+ // span that suite verifies must verify under the same evidence.+ test("a verbatim span verifies", () => {+ expect(verdictOf("“reuses staked capital”", TEXT)).toBe(ANSWER_QUOTE_VERDICT.verified);+ });++ test("curly marks inside the span match straight marks in the source", () => {+ expect(verdictOf("«He said “stake it” twice.»", TEXT)).toBe(ANSWER_QUOTE_VERDICT.verified);+ });++ test("NFD in the answer matches NFC in the source", () => {+ const nfd = "Café prices rose".normalize("NFD");+ expect(verdictOf(`“${nfd}”`, TEXT)).toBe(ANSWER_QUOTE_VERDICT.verified);+ });++ test("emphasis in the source and collapsed whitespace both verify", () => {+ expect(verdictOf("“correlated slashing risk across every service”", TEXT)).toBe(+ ANSWER_QUOTE_VERDICT.verified,+ );+ });++ test("an ellipsis span verifies when its fragments appear in order", () => {+ expect(verdictOf("“The first step … the final step.”", TEXT)).toBe(+ ANSWER_QUOTE_VERDICT.verified,+ );+ });++ test("a CRLF source verifies a span that crosses its line break", () => {+ const crlf: AnswerQuoteEvidence = {+ kind: "text",+ text: SOURCE.replaceAll("\n", "\r\n"),+ truncated: false,+ };+ expect(verdictOf("“correlated slashing risk across every service”", crlf)).toBe(+ ANSWER_QUOTE_VERDICT.verified,+ );+ });++ test("a span inside a longer word of the source does not verify", () => {+ const unsafe: AnswerQuoteEvidence = {+ kind: "text",+ text: "The method is unsafe.",+ truncated: false,+ };+ expect(verdictOf("It is “safe” here.", unsafe)).toBe(ANSWER_QUOTE_VERDICT.notInNote);+ });++ test("a case difference does not verify", () => {+ expect(verdictOf("“Reuses staked capital”", TEXT)).toBe(ANSWER_QUOTE_VERDICT.notInNote);+ });++ test("a fabricated quote in CJK running text does not verify", () => {+ expect(verdictOf("他说「完全捏造」。", TEXT)).toBe(ANSWER_QUOTE_VERDICT.notInNote);+ });+});++describe("checkAnswerQuotes - the degradation matrix, table-style", () => {+ // The matrix end-to-end: each evidence state with a span that occurs+ // and one that does not. Degradation never upgrades a verdict - a+ // truncated source can under-deliver evidence but never acquits a+ // span, and "we could not check" is a finding, not an all-clear.+ const tail = SOURCE.split("\n").slice(0, 8).join("\n");+ const table: ReadonlyArray<+ readonly [+ string,+ AnswerQuoteEvidence,+ readonly [string, AnswerQuoteVerdict],+ readonly [string, AnswerQuoteVerdict],+ ]+ > = [+ [+ "complete text",+ { kind: "text", text: SOURCE, truncated: false },+ ["reuses staked capital", ANSWER_QUOTE_VERDICT.verified],+ ["reuses pooled capital", ANSWER_QUOTE_VERDICT.notInNote],+ ],+ [+ "truncated prefix",+ { kind: "text", text: tail, truncated: true },+ ["reuses staked capital", ANSWER_QUOTE_VERDICT.verified],+ ["Café prices", ANSWER_QUOTE_VERDICT.sourceTruncated],+ ],+ [+ "unavailable",+ { kind: "unavailable" },+ ["reuses staked capital", ANSWER_QUOTE_VERDICT.noteUnavailable],+ ["nothing of this", ANSWER_QUOTE_VERDICT.noteUnavailable],+ ],+ [+ "not-text",+ { kind: "not-text" },+ ["reuses staked capital", ANSWER_QUOTE_VERDICT.notText],+ ["nothing of this", ANSWER_QUOTE_VERDICT.notText],+ ],+ ];+ for (const [name, evidence, hit, miss] of table) {+ test(`${name}: a hit is ${hit[1]}, a miss is ${miss[1]}`, () => {+ const res = checkAnswerQuotes({ spans: [hit[0], miss[0]], evidence });+ expect(res.outcomes.map((o) => o.verdict)).toEqual([hit[1], miss[1]]);+ expect(res.verified).toBe(hit[1] === ANSWER_QUOTE_VERDICT.verified ? 1 : 0);+ expect(res.unverified).toBe(hit[1] === ANSWER_QUOTE_VERDICT.verified ? 1 : 2);+ });+ }+});++describe("mergeAnswerQuoteVerdicts - the no-citation candidate ladder", () => {+ test("a hit anywhere verifies", () => {+ expect(+ mergeAnswerQuoteVerdicts([+ ANSWER_QUOTE_VERDICT.notInNote,+ ANSWER_QUOTE_VERDICT.verified,+ ANSWER_QUOTE_VERDICT.sourceTruncated,+ ]),+ ).toBe(ANSWER_QUOTE_VERDICT.verified);+ });++ test("no candidates at all is note-unavailable - nothing to check is a finding, not an all-clear", () => {+ expect(mergeAnswerQuoteVerdicts([])).toBe(ANSWER_QUOTE_VERDICT.noteUnavailable);+ });++ test("any truncated miss outranks readable misses and unreachable evidence", () => {+ expect(+ mergeAnswerQuoteVerdicts([ANSWER_QUOTE_VERDICT.notInNote, ANSWER_QUOTE_VERDICT.notText]),+ ).toBe(ANSWER_QUOTE_VERDICT.notText);+ expect(+ mergeAnswerQuoteVerdicts([+ ANSWER_QUOTE_VERDICT.notInNote,+ ANSWER_QUOTE_VERDICT.noteUnavailable,+ ]),+ ).toBe(ANSWER_QUOTE_VERDICT.noteUnavailable);+ expect(+ mergeAnswerQuoteVerdicts([+ ANSWER_QUOTE_VERDICT.notInNote,+ ANSWER_QUOTE_VERDICT.noteUnavailable,+ ANSWER_QUOTE_VERDICT.notText,+ ANSWER_QUOTE_VERDICT.sourceTruncated,+ ]),+ ).toBe(ANSWER_QUOTE_VERDICT.sourceTruncated);+ });++ test("readable misses only are not-in-note", () => {+ expect(mergeAnswerQuoteVerdicts([ANSWER_QUOTE_VERDICT.notInNote])).toBe(+ ANSWER_QUOTE_VERDICT.notInNote,+ );+ expect(+ mergeAnswerQuoteVerdicts([ANSWER_QUOTE_VERDICT.notInNote, ANSWER_QUOTE_VERDICT.notInNote]),+ ).toBe(ANSWER_QUOTE_VERDICT.notInNote);+ });+});diff --git a/tests/core/brain/continuity/reader-census.test.ts b/tests/core/brain/continuity/reader-census.test.tsindex 243565a0..266b3560 100644--- a/tests/core/brain/continuity/reader-census.test.ts+++ b/tests/core/brain/continuity/reader-census.test.ts@@ -97,6 +97,10 @@ const DIRECT_STORE_READERS: Readonly<Record<string, string>> = Object.freeze({"src/core/brain/doctor/orphan-session-check.ts":"reads the WHOLE store to collect every known session id, so a " +"session_ref resolves against the same universe the writers stamp.",+ "src/core/brain/doctor/session-identity-check.ts":+ "reads the WHOLE store once to count the records per kind that name no " ++ "session; count-only, so a partial read would dress a store gap up as a " ++ "finding and an unreadable ledger costs an uncertainty instead.","src/core/brain/link-graph/repair-lane.ts":"reads the WHOLE store to harvest `sourceRefs` paths for link repair.","src/core/brain/link-graph/session-mining.ts":@@ -151,7 +155,10 @@ const DIRECT_STORE_READERS: Readonly<Record<string, string>> = Object.freeze({* nothing extra to keep true.*/const READ_MODEL_READER_COUNT = 4;-const DIRECT_STORE_READER_COUNT = 26;+// 26 -> 27: the answer-trust wave registers the blank-session-identity+// doctor check (`doctor/session-identity-check.ts`), which reads the whole+// store once to count records per kind that name no session.+const DIRECT_STORE_READER_COUNT = 27;/** A file the classifier must see, and that `grep` alone does not. */diff --git a/tests/core/brain/ingest/ingest-capture-scope.test.ts b/tests/core/brain/ingest/ingest-capture-scope.test.tsindex 376a092e..1b35b87d 100644--- a/tests/core/brain/ingest/ingest-capture-scope.test.ts+++ b/tests/core/brain/ingest/ingest-capture-scope.test.ts@@ -1,23 +1,42 @@/**- * Capture scope on ingest summary pages. The scope follows the lane the- * intake already decided for the cited source: a vault file the summary was- * built from is `full-local` and writes nothing new (the page stays- * byte-identical to the pre-scope output), a source with no local bytes is- * `url-only` and the page says so in `capture_scope`.+ * Capture scope and the durable archive stamp on ingest summary pages. The+ * scope follows the lane the intake already decided for the cited source: a+ * vault file the summary was built from is `full-local`, a source with no+ * local bytes is `url-only` and the page says so in `capture_scope`. The+ * trusted lane additionally archives the source's bytes - redacted,+ * content-addressed - and stamps the entry on the page on success only.*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";+import { createHash } from "node:crypto";import { bootstrapBrain } from "../../../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";import { ingestSource } from "../../../../src/core/brain/ingest/ingest.ts";+import {+ ARCHIVE_MAX_BYTES,+ ARCHIVE_VERIFICATION,+ SOURCE_ARCHIVE_BYTES_KEY,+ SOURCE_ARCHIVE_HASH_KEY,+ verifySourceArchive,+} from "../../../../src/core/brain/provenance/source-archive.ts";import {CAPTURE_SCOPE,CAPTURE_SCOPE_KEY,} from "../../../../src/core/brain/provenance/capture-scope.ts";+import { redactRawOutput } from "../../../../src/core/redactor.ts";import { parseFrontmatter } from "../../../../src/core/vault.ts";let vault: string;@@ -32,6 +51,12 @@ const URL_SOURCE = "https://example.test/articles/a";const BASE_LOCAL_PAGE ='---\nkind: brain-source\nsource_path: Articles/a.md\nsource_hash: f84f9777c1d1c4b660d50d094897c7b95dab0108683ad9343c481a99d277c20e\nprovenance: stated\ncreated_at: "2026-06-13T12:00:00Z"\nupdated_at: "2026-06-13T12:00:00Z"\ntags: [brain, brain/source]\n---\n\nA summary.\n\n## Sources\n\n- [[Articles/a.md]]\n\n## Entities\n\n- [[ent-concept-alpha]]\n';+const sha256Text = (text: string): string =>+ createHash("sha256").update(text, "utf8").digest("hex");++/** The archived digest an ingest of "bytes\n" must stamp: the redacted bytes'. */+const EXPECTED_LOCAL_STAMP = sha256Text(redactRawOutput("bytes\n"));+function input(sourcePath: string) {return {sourcePath,@@ -63,14 +88,24 @@ afterEach(() => {});describe("ingestSource capture scope", () => {- test("an in-vault source is full-local and the page is byte-identical to the base output", () => {+ test("an in-vault source is full-local and the page is the base output plus the archive stamp", () => {mkdirSync(join(vault, "Articles"), { recursive: true });writeFileSync(join(vault, LOCAL_SOURCE), "bytes\n", "utf8");const result = ingestSource(vault, input(LOCAL_SOURCE), { agent: "claude", now: NOW });expect(result.captureScope).toBe(CAPTURE_SCOPE.fullLocal);- expect(readFileSync(join(vault, result.summaryPath), "utf8")).toBe(BASE_LOCAL_PAGE);+ // The trusted-local page changed deliberately with the archive lane: it+ // is the base rendering with the two stamp lines inserted, and nothing+ // else. The stamp is computed here, not remembered, so a redaction+ // change shows up as a digest the archive entry itself disagrees with.+ const expected = BASE_LOCAL_PAGE.replace(+ "provenance: stated\n",+ `provenance: stated\n` ++ `source_archive_hash: ${EXPECTED_LOCAL_STAMP}\n` ++ `source_archive_bytes: ${Buffer.byteLength("bytes\n", "utf8")}\n`,+ );+ expect(readFileSync(join(vault, result.summaryPath), "utf8")).toBe(expected);});test("a URL source stamps capture_scope: url-only and reports it", () => {@@ -102,3 +137,117 @@ describe("ingestSource capture scope", () => {expect(meta[CAPTURE_SCOPE_KEY]).toBe(CAPTURE_SCOPE.urlOnly);});});++/**+ * The durable archive (answer trust, Task C3): the trusted-local branch+ * persists its source's bytes and stamps the entry on the page on success+ * only. An unstamped page means exactly "not captured", and a capture+ * failure never fails the ingest.+ */+const archivesDir = (vaultDir: string): string => join(vaultDir, "Brain", ".archives");++function seedSource(vaultDir: string, rel: string, contents: string): void {+ mkdirSync(join(vaultDir, rel, ".."), { recursive: true });+ writeFileSync(join(vaultDir, rel), contents, "utf8");+}++describe("ingestSource durable archive stamp", () => {+ test("the stamp names an entry that verifies, with the archived byte count", () => {+ seedSource(vault, LOCAL_SOURCE, "bytes\n");+ const result = ingestSource(vault, input(LOCAL_SOURCE), { agent: "claude", now: NOW });++ expect(result.sourceArchiveHash).toBe(EXPECTED_LOCAL_STAMP);+ expect(result.sourceArchiveBytes).toBe(Buffer.byteLength("bytes\n", "utf8"));+ expect(result.sourceArchiveRefusal).toBeUndefined();+ expect(verifySourceArchive(vault, EXPECTED_LOCAL_STAMP)).toEqual({+ state: ARCHIVE_VERIFICATION.verified,+ hash: EXPECTED_LOCAL_STAMP,+ });+ const [meta] = parseFrontmatter(join(vault, result.summaryPath));+ expect(meta[SOURCE_ARCHIVE_HASH_KEY]).toBe(EXPECTED_LOCAL_STAMP);+ // The byte count round-trips through frontmatter as its decimal spelling.+ expect(meta[SOURCE_ARCHIVE_BYTES_KEY]).toBe(String(Buffer.byteLength("bytes\n", "utf8")));+ });++ test("identical source bytes stamp one shared entry - the address is the dedup", () => {+ seedSource(vault, "Articles/a.md", "twin bytes\n");+ seedSource(vault, "Articles/b.md", "twin bytes\n");+ const a = ingestSource(vault, input("Articles/a.md"), { agent: "claude", now: NOW });+ const b = ingestSource(vault, input("Articles/b.md"), { agent: "claude", now: LATER });++ expect(b.sourceArchiveHash).toBe(a.sourceArchiveHash);+ expect(readdirSync(archivesDir(vault))).toEqual([`${a.sourceArchiveHash}.txt`]);+ });++ test("a credential-shaped source never lands unredacted in the archive", () => {+ const contents = "runbook\napi_key: c3VwZXItbm90LWEtbGVha18xMjM0\nend\n";+ seedSource(vault, LOCAL_SOURCE, contents);+ const result = ingestSource(vault, input(LOCAL_SOURCE), { agent: "claude", now: NOW });++ const entry = readFileSync(+ join(vault, "Brain", ".archives", `${result.sourceArchiveHash}.txt`),+ "utf8",+ );+ expect(entry).not.toContain("c3VwZXItbm90LWEtbGVha18xMjM0");+ });++ test("an oversized source skips capture with the named refusal and an unstamped page", () => {+ seedSource(vault, LOCAL_SOURCE, "x".repeat(ARCHIVE_MAX_BYTES + 1));+ const result = ingestSource(vault, input(LOCAL_SOURCE), { agent: "claude", now: NOW });++ // The ingest itself succeeded - only the capture was refused.+ expect(result.created).toBe(true);+ expect(result.sourceArchiveHash).toBeUndefined();+ expect(result.sourceArchiveRefusal).toContain(`${ARCHIVE_MAX_BYTES}-byte ceiling`);+ const [meta] = parseFrontmatter(join(vault, result.summaryPath));+ expect(meta[SOURCE_ARCHIVE_HASH_KEY]).toBeUndefined();+ expect(meta[SOURCE_ARCHIVE_BYTES_KEY]).toBeUndefined();+ expect(existsSync(archivesDir(vault))).toBe(false);+ });++ test("an unwritable archive store leaves the page unstamped and the ingest whole", () => {+ seedSource(vault, LOCAL_SOURCE, "bytes\n");+ // A regular file where the archives directory belongs: the capture's+ // mkdir fails for a reason that is not the source's fault (the same+ // seed pattern the session-identity check's unreadable-ledger case+ // uses). Task C3's write-failure arm.+ writeFileSync(archivesDir(vault), "not a directory\n");++ const result = ingestSource(vault, input(LOCAL_SOURCE), { agent: "claude", now: NOW });++ // The design contract: an archive failure never fails an ingest that+ // already committed its knowledge - the page lands, unstamped.+ expect(result.created).toBe(true);+ expect(result.sourceArchiveHash).toBeUndefined();+ expect(result.sourceArchiveBytes).toBeUndefined();+ // What the fs-error arm actually records: the host's errno line only -+ // identifiers, never the host path the raw fs message embeds (the+ // refusal crosses to the wire, so it cannot name the machine).+ expect(result.sourceArchiveRefusal).toContain("EEXIST");+ expect(result.sourceArchiveRefusal).not.toContain(vault);+ const [meta] = parseFrontmatter(join(vault, result.summaryPath));+ expect(meta[SOURCE_ARCHIVE_HASH_KEY]).toBeUndefined();+ expect(meta[SOURCE_ARCHIVE_BYTES_KEY]).toBeUndefined();+ });++ test("a source withheld from remote readers is never archived, though it stays full-local", () => {+ seedSource(vault, "Notes/private.md", "---\nvisibility: private\n---\nThe code is ZX8.\n");+ const result = ingestSource(vault, input("Notes/private.md"), { agent: "claude", now: NOW });++ expect(result.captureScope).toBe(CAPTURE_SCOPE.fullLocal);+ expect(result.sourceArchiveHash).toBeUndefined();+ // Not a refusal: the source was never capture-eligible, so the answer+ // is the byte-identical to today shape - no stamp, no reason, no bytes.+ expect(result.sourceArchiveRefusal).toBeUndefined();+ expect(existsSync(archivesDir(vault))).toBe(false);+ });++ test("a URL source is unarchived and carries no refusal", () => {+ const result = ingestSource(vault, input(URL_SOURCE), { agent: "claude", now: NOW });++ expect(result.captureScope).toBe(CAPTURE_SCOPE.urlOnly);+ expect(result.sourceArchiveHash).toBeUndefined();+ expect(result.sourceArchiveRefusal).toBeUndefined();+ expect(existsSync(archivesDir(vault))).toBe(false);+ });+});diff --git a/tests/core/brain/ingest/ingest-derived-section.test.ts b/tests/core/brain/ingest/ingest-derived-section.test.tsindex cf8805c6..24d890cc 100644--- a/tests/core/brain/ingest/ingest-derived-section.test.ts+++ b/tests/core/brain/ingest/ingest-derived-section.test.ts@@ -26,9 +26,15 @@ import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";import { hashBytes } from "../../../../src/core/brain/ingest/content-manifest.ts";import { ingestSource } from "../../../../src/core/brain/ingest/ingest.ts";import { INGEST_TOOLS } from "../../../../src/mcp/brain/ingest-tools.ts";+import { createHash } from "node:crypto";+import { IS_WINDOWS } from "../../../helpers/platform.ts";+import { redactRawOutput } from "../../../../src/core/redactor.ts";const NOW = new Date("2026-06-13T12:00:00Z");++const sha256Text = (text: string): string =>+ createHash("sha256").update(text, "utf8").digest("hex");const LATER = new Date("2026-06-14T09:00:00Z");const PAGE_HTML =@@ -286,6 +292,11 @@ describe("a text source", () => {"source_path: Notes/a.md","source_hash: 4764013adda2ade4813ac7dddb5f4deb453cff19f705e137c07e0beddb9ef7c2","provenance: stated",+ // The durable archive stamp (answer trust, Task C3): the digest of+ // the archived (redacted) source bytes and their count, computed+ // here rather than remembered.+ `source_archive_hash: ${sha256Text(redactRawOutput("# A\n\nBody.\n"))}`,+ `source_archive_bytes: ${Buffer.byteLength("# A\n\nBody.\n", "utf8")}`,'created_at: "2026-06-13T12:00:00Z"','updated_at: "2026-06-13T12:00:00Z"',"tags: [brain, brain/source]",diff --git a/tests/core/brain/intake/intake-trust.test.ts b/tests/core/brain/intake/intake-trust.test.tsindex dd855979..e8169917 100644--- a/tests/core/brain/intake/intake-trust.test.ts+++ b/tests/core/brain/intake/intake-trust.test.ts@@ -104,6 +104,12 @@ const GOLDEN_TRUSTED_SUMMARY_PAGE ="source_path: Articles/primer.md\n" +"source_hash: 51b0f811072b41378ce56e723de332a315cd3c2841915c355606b294f1304019\n" +"provenance: stated\n" ++ // The two lines the answer-trust wave adds to a trusted-local summary+ // page: the content-addressed archive entry the trusted branch persisted+ // (its address IS the digest of the redacted source bytes, so it equals+ // TRUSTED_SOURCE_HASH here) with its byte count beside it.+ `source_archive_hash: ${TRUSTED_SOURCE_HASH}\n` ++ "source_archive_bytes: 17\n" +'created_at: "2026-06-13T12:00:00Z"\n' +'updated_at: "2026-06-13T12:00:00Z"\n' +"tags: [brain, brain/source]\n" +@@ -258,7 +264,7 @@ describe("intakeExtraction - the untrusted path", () => {describe("ingestSource derives trust from the source identity", () => {const INPUT = { summary: "An overview.", extraction: EXTRACTION };- test("a vault-relative source writes the pre-change summary bytes", () => {+ test("a vault-relative source writes the summary bytes with the archive stamp", () => {seed(TRUSTED_SOURCE);const res = ingestSource(vault,diff --git a/tests/core/brain/provenance/source-archive.test.ts b/tests/core/brain/provenance/source-archive.test.tsnew file mode 100644index 00000000..8dec5af6--- /dev/null+++ b/tests/core/brain/provenance/source-archive.test.ts@@ -0,0 +1,264 @@+/**+ * The durable raw-source archive store (answer trust, Task C2).+ *+ * Four invariants are pinned here because each one is a way the store could+ * silently stop being evidence: the address names the bytes on disk (dedup+ * is that address applied twice); a credential in a captured source never+ * reaches a second file (redaction runs BEFORE persist, and the digest is+ * the redacted bytes'); a past-ceiling input is refused whole, never stored+ * half; and a verification distinguishes "gone" from "disagrees".+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ ARCHIVE_MAX_BYTES,+ ARCHIVE_VERIFICATION,+ SOURCE_ARCHIVE_BYTES_KEY,+ SOURCE_ARCHIVE_HASH_KEY,+ discardSourceArchive,+ isArchiveVerification,+ putSourceArchive,+ readSourceArchiveEntry,+ sourceArchiveCitingPages,+ sourceArchivePath,+ sourceArchiveStats,+ sourceArchivesDir,+ verifySourceArchive,+} from "../../../../src/core/brain/provenance/source-archive.ts";+import { admitToIndex } from "../../../../src/core/vault-scope/index-admission.ts";+import { REDACTION_PLACEHOLDER, redactRawOutput } from "../../../../src/core/redactor.ts";+import { createHash } from "node:crypto";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-source-archive-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++const sha256 = (text: string): string => createHash("sha256").update(text, "utf8").digest("hex");++describe("putSourceArchive", () => {+ test("persists the bytes at their digest under Brain/.archives/<sha256>.txt", () => {+ const put = putSourceArchive(vault, "the source bytes\n");++ expect(put.hash).toBe(sha256("the source bytes\n"));+ expect(put.bytes).toBe(Buffer.byteLength("the source bytes\n", "utf8"));+ const entry = join(vault, "Brain", ".archives", `${put.hash}.txt`);+ expect(existsSync(entry)).toBe(true);+ expect(readFileSync(entry, "utf8")).toBe("the source bytes\n");+ });++ test("identical bytes persist once - the content address is the dedup", () => {+ const first = putSourceArchive(vault, "same bytes");+ const second = putSourceArchive(vault, "same bytes");++ expect(second.hash).toBe(first.hash);+ const store = join(vault, "Brain", ".archives");+ expect(readdirSync(store)).toEqual([`${first.hash}.txt`]);+ });++ test("a re-ingest of an intact entry leaves it untouched - no mtime churn", () => {+ const first = putSourceArchive(vault, "stable bytes");+ const entry = join(vault, "Brain", ".archives", `${first.hash}.txt`);+ const before = statSync(entry).mtimeMs;++ putSourceArchive(vault, "stable bytes");++ expect(statSync(entry).mtimeMs).toBe(before);+ });++ test("a re-ingest repairs an entry corrupted on disk", () => {+ // The natural repair of the `mismatched` state the hygiene scan+ // reports: the same source lands the same address, re-verifies the+ // entry it finds there, and rewrites it when the bytes disagree.+ const first = putSourceArchive(vault, "original");+ const entry = join(vault, "Brain", ".archives", `${first.hash}.txt`);+ writeFileSync(entry, "tampered after the stamp", "utf8");+ expect(verifySourceArchive(vault, first.hash).state).toBe(ARCHIVE_VERIFICATION.mismatched);++ const second = putSourceArchive(vault, "original");++ expect(second.hash).toBe(first.hash);+ expect(verifySourceArchive(vault, first.hash).state).toBe(ARCHIVE_VERIFICATION.verified);+ expect(readFileSync(entry, "utf8")).toBe("original");+ });++ test("a credential-shaped input never lands on disk unredacted", () => {+ // The redaction must run BEFORE persist, and the entry's address must+ // be the digest of the REDACTED bytes - an address over the raw input+ // would name a file that does not exist and break re-verification.+ const input = "deploy notes\napi_key: ZXhwb3J0ZWQta2V5LTEyMzQ1\ntrailing prose\n";+ const put = putSourceArchive(vault, input);+ const stored = readFileSync(join(vault, "Brain", ".archives", `${put.hash}.txt`), "utf8");++ expect(stored).not.toContain("ZXhwb3J0ZWQta2V5LTEyMzQ1");+ expect(stored).toContain(REDACTION_PLACEHOLDER);+ expect(put.hash).toBe(sha256(redactRawOutput(input)));+ });++ test("a past-ceiling input raises the named error and never a truncated write", () => {+ const oversized = "a".repeat(ARCHIVE_MAX_BYTES + 1);++ let thrown: unknown;+ try {+ putSourceArchive(vault, oversized);+ } catch (err) {+ thrown = err;+ }+ expect((thrown as Error)?.name).toBe("SourceArchiveError");+ expect((thrown as Error).message).toContain(`${ARCHIVE_MAX_BYTES}-byte ceiling`);+ // Refuse-not-truncate: nothing was written at all, neither a truncated+ // entry nor a partial one.+ expect(existsSync(sourceArchivesDir(vault))).toBe(false);+ });++ test("an input exactly at the ceiling is archived whole", () => {+ const atCeiling = "b".repeat(ARCHIVE_MAX_BYTES);+ const put = putSourceArchive(vault, atCeiling);+ expect(put.bytes).toBe(ARCHIVE_MAX_BYTES);+ expect(verifySourceArchive(vault, put.hash).state).toBe(ARCHIVE_VERIFICATION.verified);+ });+});++describe("verifySourceArchive and readSourceArchiveEntry", () => {+ test("an intact entry verifies", () => {+ const put = putSourceArchive(vault, "intact");+ expect(verifySourceArchive(vault, put.hash)).toEqual({+ state: ARCHIVE_VERIFICATION.verified,+ hash: put.hash,+ });+ });++ test("a tampered entry re-hashes differently - mismatched, not missing", () => {+ const put = putSourceArchive(vault, "original");+ writeFileSync(join(vault, "Brain", ".archives", `${put.hash}.txt`), "tampered", "utf8");+ expect(verifySourceArchive(vault, put.hash).state).toBe(ARCHIVE_VERIFICATION.mismatched);+ });++ test("an absent entry is missing, and a malformed stamp is missing too", () => {+ putSourceArchive(vault, "present");+ expect(verifySourceArchive(vault, sha256("absent")).state).toBe(ARCHIVE_VERIFICATION.missing);+ // A stamp that is not a hash names no entry the store could hold.+ expect(verifySourceArchive(vault, "not-a-hash").state).toBe(ARCHIVE_VERIFICATION.missing);+ });++ test("reading an entry returns its text and byte count; absent is null", () => {+ const put = putSourceArchive(vault, "read me");+ expect(readSourceArchiveEntry(vault, put.hash)).toEqual({+ state: ARCHIVE_VERIFICATION.verified,+ hash: put.hash,+ bytes: Buffer.byteLength("read me", "utf8"),+ text: "read me",+ });+ expect(readSourceArchiveEntry(vault, sha256("nope"))).toBeNull();+ });++ test("a caller-supplied hash cannot traverse out of the store", () => {+ for (const hostile of ["../secrets.txt", "../../etc/passwd", "A".repeat(64), "ab".repeat(31)]) {+ let thrown: unknown;+ try {+ sourceArchivePath(vault, hostile);+ } catch (err) {+ thrown = err;+ }+ expect((thrown as Error)?.name).toBe("SourceArchiveError");+ }+ });+});++describe("sourceArchiveStats", () => {+ test("a vault that never captured reports an empty store, not an error", () => {+ expect(sourceArchiveStats(vault)).toEqual({ entries: 0, totalBytes: 0 });+ });++ test("counts entries and their combined bytes, and nothing it does not recognize", () => {+ const a = putSourceArchive(vault, "alpha");+ const b = putSourceArchive(vault, "beta");+ // A stray file is not an entry: the store counts what its grammar names.+ writeFileSync(join(vault, "Brain", ".archives", "notes.txt"), "stray", "utf8");++ const stats = sourceArchiveStats(vault);+ expect(stats.entries).toBe(2);+ expect(stats.totalBytes).toBe(a.bytes + b.bytes);+ });+});++describe("discardSourceArchive", () => {+ test("removes the entry and says so; an absent entry was not removed", () => {+ const put = putSourceArchive(vault, "ephemeral");+ expect(discardSourceArchive(vault, put.hash)).toBe(true);+ expect(verifySourceArchive(vault, put.hash).state).toBe(ARCHIVE_VERIFICATION.missing);+ expect(discardSourceArchive(vault, put.hash)).toBe(false);+ });+});++describe("sourceArchiveCitingPages", () => {+ test("lists exactly the summary pages stamping the digest, sorted", () => {+ const put = putSourceArchive(vault, "cited bytes");+ const sources = join(vault, "Brain", "sources");+ mkdirSync(sources, { recursive: true });+ const stamped = (name: string, hash: string | null): void => {+ const hashLines =+ hash === null+ ? []+ : [`${SOURCE_ARCHIVE_HASH_KEY}: ${hash}`, `${SOURCE_ARCHIVE_BYTES_KEY}: 11`];+ writeFileSync(+ join(sources, name),+ ["---", "kind: brain-source", ...hashLines, "---", "", "body", ""].join("\n"),+ "utf8",+ );+ };+ stamped("b-second.md", put.hash);+ stamped("a-first.md", put.hash);+ stamped("c-other.md", sha256("another source"));+ stamped("d-unstamped.md", null);++ expect(sourceArchiveCitingPages(vault, put.hash)).toEqual([+ "Brain/sources/a-first.md",+ "Brain/sources/b-second.md",+ ]);+ expect(sourceArchiveCitingPages(vault, sha256("nothing cites this"))).toEqual([]);+ });+});++describe("the archive store is refused to the search index", () => {+ test("an entry path is excluded by name, a sibling lane is not", () => {+ expect(admitToIndex(`Brain/.archives/${"a".repeat(64)}.txt`)).toEqual({+ admit: false,+ reason: "source-archive-store",+ });+ expect(admitToIndex("Brain/archives-notes.md").admit).toBe(true);+ });+});++describe("the verification vocabulary", () => {+ test("the guard accepts exactly the three members", () => {+ expect(Object.values(ARCHIVE_VERIFICATION).toSorted()).toEqual([+ "mismatched",+ "missing",+ "verified",+ ]);+ for (const member of Object.values(ARCHIVE_VERIFICATION)) {+ expect(isArchiveVerification(member)).toBe(true);+ }+ expect(isArchiveVerification("intact")).toBe(false);+ expect(isArchiveVerification(42)).toBe(false);+ });+});diff --git a/tests/core/brain/session-identity-check.test.ts b/tests/core/brain/session-identity-check.test.tsnew file mode 100644index 00000000..fedf09b4--- /dev/null+++ b/tests/core/brain/session-identity-check.test.ts@@ -0,0 +1,478 @@+/**+ * The blank-session-identity check (t_22d58fa7), and the census that+ * keeps its kind classification honest.+ *+ * Readers across the continuity surface used to coerce a missing or+ * non-string `session_id` to "" - a phantom identity no writer ever+ * stamped. The readers now treat absence as no-session explicitly, and+ * this check is the vault-level mirror of that decision: it COUNTS the+ * records that name no session, one issue per affected kind, and does+ * nothing else. No `fix` field (a session no writer stamped cannot be+ * restored from the record, and the ledger is append-only history), no+ * payload rewrite, and an unreadable ledger is an uncertainty rather+ * than a clean bill.+ *+ * The census half exists because most of the ledger is sessionless BY+ * DESIGN: the telemetry lanes (`gate-telemetry.ts`, `recall-telemetry.ts`,+ * `observed-use.ts`, `recent-turns.ts`, `token-impact.ts`,+ * `context-pack-evidence.ts`, `context-pack-outcome.ts`,+ * `context-receipts.ts`) stamp the key only when their lane has a session+ * in scope, `appendContinuitySourceInvalidation` writes only `{reason}`,+ * and the remaining kinds correlate their session outside the payload key+ * entirely. Counting those put a permanent warning on every used vault+ * and made `--strict` unexitable, so the check counts only the kinds+ * whose writer stamps `session_id` unconditionally from a required+ * input. The census pins that classification three ways: every kind in+ * the `ContinuityRecordKind` union is classified exactly once, the named+ * sessionless writers' files stay out of the count (a behavioural case+ * per kind), and each kind's pinned writer file still has the stamp+ * shape its classification claims.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join, relative, sep } from "node:path";++import { lexSource } from "../../helpers/source-lexer.ts";+import { emitGateTelemetry } from "../../../src/core/brain/gate-telemetry.ts";+import {+ appendContinuityRecord,+ appendContinuitySourceInvalidation,+} from "../../../src/core/brain/continuity/store.ts";+import type {+ AppendContinuityRecordInput,+ ContinuityRecordKind,+} from "../../../src/core/brain/continuity/types.ts";+import { runDoctor } from "../../../src/core/brain/doctor.ts";+import {+ SESSION_IDENTITY_CHECK_CODE,+ SESSION_IDENTITY_CHECKED_KINDS,+ sessionIdentityCheck,+} from "../../../src/core/brain/doctor/session-identity-check.ts";+import type { DoctorUncertainEntry } from "../../../src/core/brain/doctor/report.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import type { DoctorIssue } from "../../../src/core/brain/types.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-session-identity-"));+ vault = join(tmp, "vault");+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function seed(+ payload: Record<string, unknown>,+ kind: AppendContinuityRecordInput["kind"] = "session_turn",+): void {+ appendContinuityRecord(vault, {+ kind,+ createdAt: "2026-06-01T00:00:00.000Z",+ payload,+ });+}++function findings(): { issues: DoctorIssue[]; uncertain: DoctorUncertainEntry[] } {+ const issues: DoctorIssue[] = [];+ const uncertain: DoctorUncertainEntry[] = [];+ sessionIdentityCheck.run(+ {+ vault,+ now: new Date("2026-06-02T00:00:00.000Z"),+ logs: [],+ } as unknown as Parameters<typeof sessionIdentityCheck.run>[0],+ { issues, uncertain },+ );+ return { issues, uncertain };+}++describe("blank-session-identity counts, and only counts", () => {+ test("one issue per affected kind, carrying the count, with no fix field", () => {+ seed({ turn_id: "t1", text: "names no session" });+ seed({ turn_id: "t2", text: "names no session either" });+ seed({ depth: 1, summary: "node names no session" }, "session_summary_node");+ seed({ session_id: "sess-real", turn_id: "t3", text: "attributed" });++ const { issues, uncertain } = findings();+ expect(uncertain).toEqual([]);+ expect(issues.map((issue) => issue.message)).toEqual([+ expect.stringContaining("1 session_summary_node"),+ expect.stringContaining("2 session_turn"),+ ]);+ for (const issue of issues) {+ expect(issue.severity).toBe("warning");+ expect(issue.code).toBe(SESSION_IDENTITY_CHECK_CODE);+ expect("fix" in issue).toBe(false);+ }+ });++ test("an empty-string or non-string session_id counts as blank, never as an identity", () => {+ seed({ session_id: "", turn_id: "t1", text: "blank string" });+ seed({ session_id: 42, turn_id: "t2", text: "numeric" });++ const { issues } = findings();+ expect(issues.length).toBe(1);+ expect(issues[0]!.message).toContain("2 session_turn");+ });++ test("every kind whose writer stamps a session is counted when its id is blank", () => {+ // Regression: the census narrowed the count to the session-scoped+ // kinds; each of them must still count exactly as before, one issue+ // per kind, kinds in deterministic order.+ const checked: ReadonlyArray<AppendContinuityRecordInput["kind"]> = [+ "decision_model_extract_commit",+ "post_compact_audit",+ "pre_compact_extract",+ "session_summary_digest",+ "session_summary_node",+ "session_turn",+ ];+ for (const kind of checked) seed({}, kind);++ const { issues, uncertain } = findings();+ expect(uncertain).toEqual([]);+ expect(issues.length).toBe(checked.length);+ expect(issues.map((issue) => issue.message)).toEqual(+ [+ "1 decision_model_extract_commit",+ "1 post_compact_audit",+ "1 pre_compact_extract",+ "1 session_summary_digest",+ "1 session_summary_node",+ "1 session_turn",+ ].map((fragment) => expect.stringContaining(fragment)),+ );+ });++ test("a clean ledger is quiet", () => {+ seed({ session_id: "sess-a", turn_id: "t1", text: "attributed" });+ expect(findings().issues).toEqual([]);+ });++ test("an unreadable ledger is an uncertain stream outcome, never a throw or a finding", () => {+ // A regular file where the continuity directory belongs: the listing+ // fails for a reason that is not absence, which is precisely what the+ // uncertainty stream exists for.+ const continuity = join(vault, "Brain", "log", "continuity");+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });+ writeFileSync(continuity, "not a directory\n");++ const { issues, uncertain } = findings();+ expect(issues).toEqual([]);+ expect(uncertain.length).toBe(1);+ expect(uncertain[0]!.code).toBe("vault-walk-entry-skipped");+ });++ test("an absent ledger is the ordinary quiet case, not uncertainty", () => {+ rmSync(join(vault, "Brain", "log", "continuity"), { recursive: true, force: true });+ const { issues, uncertain } = findings();+ expect(issues).toEqual([]);+ expect(uncertain).toEqual([]);+ });+});++describe("blank-session-identity skips the sessionless-by-design kinds", () => {+ test("sessionless gate telemetry and a source invalidation leave the check silent and the vault clean", () => {+ // The review's reproduction: a vault whose ONLY continuity records+ // are one gate decision written with no session in scope (exactly+ // what `emitGateTelemetry` does under the recall-gate opt-in) and+ // one source invalidation (which writes only `{reason}`). Both are+ // sessionless by design, so this check counts nothing, `brain+ // doctor` reads clean, and `--strict` (which exits 2 exactly when+ // the pass has warnings) exits 0.+ emitGateTelemetry(vault, {+ host: "cli",+ prompt: "what changed",+ retrieve: false,+ reason: "no-index",+ });+ appendContinuitySourceInvalidation(vault, {+ createdAt: "2026-06-01T00:00:00.000Z",+ source: { id: "src-1" },+ reason: "source deleted",+ });++ const { issues, uncertain } = findings();+ expect(uncertain).toEqual([]);+ expect(issues).toEqual([]);++ const result = runDoctor(vault);+ expect(result.warnings).toEqual([]);+ });++ test("every sessionless-by-design kind produces no issue, taken one record at a time", () => {+ // The behavioural half of the census: each kind classified+ // sessionless below (minus `source_invalidation`, covered above+ // through its writer) is seeded as the sessionless record its+ // writer legitimately produces, and the check must stay silent on+ // every one of them.+ const { sessionlessKinds } = classification();+ expect(sessionlessKinds.length).toBeGreaterThan(10);+ for (const kind of sessionlessKinds) {+ if (kind === "source_invalidation") continue; // writer-level case above+ appendContinuityRecord(vault, {+ kind: kind as AppendContinuityRecordInput["kind"],+ createdAt: "2026-06-01T00:00:00.000Z",+ payload: {},+ });+ }++ const { issues } = findings();+ expect(issues).toEqual([]);+ });+});++describe("blank-session-identity runs in the pass", () => {+ test("runDoctor reports the count with zero config", () => {+ seed({ turn_id: "t1", text: "names no session" });+ const result = runDoctor(vault);+ const warning = result.warnings.find((issue) => issue.code === SESSION_IDENTITY_CHECK_CODE);+ expect(warning).toBeDefined();+ expect(warning!.message).toContain("1 session_turn");+ });++ test("a clean vault stays clean", () => {+ const result = runDoctor(vault);+ expect(result.warnings.some((issue) => issue.code === SESSION_IDENTITY_CHECK_CODE)).toBe(false);+ });+});++// ---------------------------------------------------------------------------+// The classification census.+//+// Mirrors the sibling censuses: a lexed view of each module+// (`tests/helpers/source-lexer.ts`), so a kind discussed in a docblock is+// not a writer and a stamp named in a string literal is not a site.+// ---------------------------------------------------------------------------++const SRC_ROOT = join(import.meta.dir, "..", "..", "..", "src");++/** The store's append primitives - binding one is what makes a module a writer. */+const APPEND_PRIMITIVES: ReadonlyArray<string> = Object.freeze([+ "appendContinuityRecord",+ "appendContinuityRecords",+ "appendContinuitySourceInvalidation",+]);++/**+ * A payload stamp written unconditionally, from a required binding.+ * `session_id: sessionId`, `session_id: input.sessionId`, ...+ * (`session_id?: string` in an interface is not a stamp; a read of+ * `payload["session_id"]` is not one either.)+ */+const UNCONDITIONAL_STAMP_RE = /session_id: [A-Za-z$_]/;++/**+ * The conditional-spread shape the sessionless lanes stamp with:+ * `...(input.sessionId !== undefined ? { session_id: ... } : {})`, under+ * either spelling of the key.+ */+const CONDITIONAL_STAMP_RE = /\? \{ (?:\[CONTINUITY_SESSION_ID_KEY\]|session_id\b)/;++/**+ * Every kind the census classifies, with the module(s) whose code shapes+ * that kind's payload. The writers of `source_invalidation` all funnel+ * through `appendContinuitySourceInvalidation`, whose `{reason}` payload+ * is fixed at the store and whose input type carries no session field.+ */+const KIND_WRITERS: ReadonlyArray<{+ readonly kind: ContinuityRecordKind;+ /** Session-scoped: the writer stamps `session_id` unconditionally. */+ readonly sessionScoped: boolean;+ readonly writers: ReadonlyArray<string>;+}> = Object.freeze([+ { kind: "context_receipt", sessionScoped: false, writers: ["core/brain/context-receipts.ts"] },+ { kind: "recall_telemetry", sessionScoped: false, writers: ["core/brain/recall-telemetry.ts"] },+ { kind: "gate_telemetry", sessionScoped: false, writers: ["core/brain/gate-telemetry.ts"] },+ {+ kind: "pre_compact_extract",+ sessionScoped: true,+ writers: ["core/brain/pre-compact-extract.ts"],+ },+ {+ kind: "post_compact_audit",+ sessionScoped: true,+ writers: ["core/brain/post-compact-audit.ts"],+ },+ {+ kind: "session_turn",+ sessionScoped: true,+ writers: ["core/brain/session-recall.ts"],+ },+ { kind: "recent_turn", sessionScoped: false, writers: ["core/brain/recent-turns.ts"] },+ {+ kind: "session_summary_node",+ sessionScoped: true,+ writers: ["core/brain/session-recall.ts"],+ },+ {+ kind: "session_summary_digest",+ sessionScoped: true,+ writers: ["core/brain/session-summary.ts"],+ },+ {+ kind: "generation_report",+ sessionScoped: false,+ writers: ["core/brain/generation-reports.ts"],+ },+ { kind: "ingest_dedup", sessionScoped: false, writers: ["core/brain/dedup-telemetry.ts"] },+ { kind: "mcp_route_latency", sessionScoped: false, writers: ["core/brain/mcp-route-metrics.ts"] },+ { kind: "token_impact", sessionScoped: false, writers: ["core/brain/token-impact.ts"] },+ {+ kind: "token_impact_outcome",+ sessionScoped: false,+ writers: ["core/brain/token-impact.ts"],+ },+ {+ kind: "context_pack_outcome",+ sessionScoped: false,+ writers: ["core/brain/context-pack-outcome.ts"],+ },+ {+ kind: "context_pack_evidence",+ sessionScoped: false,+ writers: ["core/brain/context-pack-evidence.ts"],+ },+ { kind: "host_memory_write", sessionScoped: false, writers: ["core/brain/host-memory-write.ts"] },+ { kind: "recall_observed_use", sessionScoped: false, writers: ["core/brain/observed-use.ts"] },+ { kind: "skill_invoked", sessionScoped: false, writers: ["core/brain/sessions/import.ts"] },+ {+ kind: "source_invalidation",+ sessionScoped: false,+ writers: [+ "core/brain/continuity/store.ts",+ "core/brain/source-cleanup.ts",+ "core/brain/portability/knowledge-pack.ts",+ ],+ },+ { kind: "negative_recall", sessionScoped: false, writers: ["core/brain/gate-telemetry.ts"] },+ { kind: "decision_model_call", sessionScoped: false, writers: ["core/decision-model/record.ts"] },+ {+ kind: "decision_model_extract_commit",+ sessionScoped: true,+ writers: ["core/brain/extract-signals-prefilter.ts"],+ },+ {+ kind: "session_entity_mention",+ sessionScoped: false,+ writers: ["core/brain/link-graph/session-mining.ts"],+ },+]);++/**+ * A benchmark fixture writes throwaway ledgers for timing runs, not a+ * vault a doctor pass will ever examine. Named here so the writer+ * population below accounts for it by name rather than by silence.+ */+const FIXTURE_WRITER = "core/bench/fixture.ts";++/** Every .ts file under src, as POSIX paths relative to it, sorted. */+function srcModulePaths(): ReadonlyArray<string> {+ const out: string[] = [];+ const walk = (dir: string): void => {+ for (const name of readdirSync(dir).toSorted()) {+ const abs = join(dir, name);+ if (statSync(abs).isDirectory()) {+ walk(abs);+ continue;+ }+ if (name.endsWith(".ts")) out.push(relative(SRC_ROOT, abs).split(sep).join("/"));+ }+ };+ walk(SRC_ROOT);+ return out;+}++/** The `ContinuityRecordKind` union, read out of `types.ts` at census time. */+function declaredKinds(): ReadonlyArray<string> {+ const view = lexSource(+ readFileSync(join(SRC_ROOT, "core", "brain", "continuity", "types.ts"), "utf8"),+ );+ const start = view.withoutComments.indexOf("export type ContinuityRecordKind");+ const end = view.withoutComments.indexOf(";", start);+ const union = view.withoutComments.slice(start, end);+ return [...union.matchAll(/"([a-z_]+)"/g)].map((match) => match[1]!);+}++/** The census tables, checked for internal consistency once per run. */+function classification(): {+ readonly checkedKinds: ReadonlyArray<ContinuityRecordKind>;+ readonly sessionlessKinds: ReadonlyArray<ContinuityRecordKind>;+} {+ const checked = KIND_WRITERS.filter((row) => row.sessionScoped).map((row) => row.kind);+ const sessionless = KIND_WRITERS.filter((row) => !row.sessionScoped).map((row) => row.kind);+ return { checkedKinds: checked, sessionlessKinds: sessionless };+}++describe("blank-session-identity classification census", () => {+ test("the sweep sees the vault-facing src tree", () => {+ // A census over an empty sweep is a claim about a census; pin the+ // population's scale and a load-bearing member's presence.+ const paths = srcModulePaths();+ expect(paths.length).toBeGreaterThan(100);+ expect(paths).toContain("core/brain/continuity/types.ts");+ });++ test("the check's allowlist is exactly the session-scoped classification", () => {+ const { checkedKinds } = classification();+ expect([...SESSION_IDENTITY_CHECKED_KINDS].toSorted()).toEqual(checkedKinds.toSorted());+ });++ test("every declared kind is classified exactly once, session-scoped or sessionless by design", () => {+ const declared = declaredKinds();+ const { checkedKinds, sessionlessKinds } = classification();+ // The union parse must have read the real population, not a fragment.+ expect(declared.length).toBeGreaterThanOrEqual(20);+ expect(declared.toSorted()).toEqual([...checkedKinds, ...sessionlessKinds].toSorted());+ expect(new Set([...checkedKinds].filter((k) => sessionlessKinds.includes(k))).size).toBe(0);+ });++ test("each kind's writer files exist and carry the stamp shape its classification claims", () => {+ for (const row of KIND_WRITERS) {+ for (const writer of row.writers) {+ const view = lexSource(readFileSync(join(SRC_ROOT, writer), "utf8"));+ const stamps = UNCONDITIONAL_STAMP_RE.test(view.withoutComments);+ const conditional = CONDITIONAL_STAMP_RE.test(view.withoutComments);+ if (row.sessionScoped) {+ // A session-scoped writer stamps unconditionally and never+ // behind the conditional spread - otherwise a sessionless+ // lane could belong on this side of the census.+ expect(stamps, `${writer} should stamp session_id unconditionally`).toBe(true);+ expect(conditional, `${writer} should not stamp session_id conditionally`).toBe(false);+ } else {+ // A sessionless writer either stamps only conditionally or+ // never touches the payload key at all (its session+ // correlation lives elsewhere).+ expect(conditional || !stamps, `${writer} should be sessionless by design`).toBe(true);+ }+ }+ }+ });++ test("the writer population is exactly the classified writers plus the named fixture", () => {+ // Any module that binds an append primitive writes SOME kind's+ // payload; if it is not classified above, its kinds are counted (or+ // spared) by a writer this census never read. Exempted: the bench+ // fixture, which writes throwaway ledgers for timing runs.+ const writers = new Set(KIND_WRITERS.flatMap((row) => row.writers));+ const population = srcModulePaths().filter((path) => {+ const code = lexSource(readFileSync(join(SRC_ROOT, path), "utf8")).code;+ return APPEND_PRIMITIVES.some((primitive) => code.includes(primitive));+ });+ expect(population.toSorted()).toEqual([...writers, FIXTURE_WRITER].toSorted());+ });+});diff --git a/tests/core/brain/session-recall.test.ts b/tests/core/brain/session-recall.test.tsindex 9cc77587..e95b6086 100644--- a/tests/core/brain/session-recall.test.ts+++ b/tests/core/brain/session-recall.test.ts@@ -9,6 +9,8 @@ import {importSessionRecall,searchSessionRecall,} from "../../../src/core/brain/session-recall.ts";+import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";+import type { ContinuityRecord } from "../../../src/core/brain/continuity/types.ts";import type { SessionTurn } from "../../../src/core/brain/sessions/types.ts";let vault: string;@@ -263,3 +265,84 @@ describe("session recall — since/before time bounds (S1 / t_347e8224)", () =>expect(turnIdsFor({}).toSorted(byString)).toEqual(["t1", "t2", "t3"]);});});++describe("session recall - explicit no-session semantics (t_22d58fa7)", () => {+ /**+ * Seed one raw turn whose payload names no session, the way the+ * conditional telemetry writers leave the key absent. `override`+ * replaces the identity wholesale, so a test can also seed a non-string+ * value - the coercion the read path used to perform.+ */+ function seedUnattributedTurn(sessionId: unknown): ContinuityRecord {+ return appendContinuityRecord(vault, {+ kind: "session_turn",+ createdAt: "2026-05-20T17:30:00.000Z",+ payload: {+ turn_id: "tno",+ role: "user",+ text: "unattributed needle",+ ...(sessionId !== undefined ? { session_id: sessionId } : {}),+ },+ });+ }++ function seedAttributedSession(): void {+ importSessionRecall(vault, {+ sessionId: "session-a",+ turns: [turn("t1", "user", "attributed needle")],+ summaryGroupSize: 2,+ createdAt: "2026-05-20T17:00:00.000Z",+ });+ }++ test("a record without session_id is excluded from scoped recall and kept by unscoped search", () => {+ seedAttributedSession();+ seedUnattributedTurn(undefined);++ const scoped = searchSessionRecall(vault, { query: "needle", sessionId: "session-a" });+ expect(scoped.hits.map((hit) => hit.turn_id)).toEqual(["t1"]);++ const unscoped = searchSessionRecall(vault, { query: "needle" });+ expect(unscoped.hits.map((hit) => hit.turn_id).toSorted()).toEqual(["t1", "tno"]);+ });++ test("a non-string session_id is excluded, not coerced into a scope match", () => {+ seedAttributedSession();+ const numeric = seedUnattributedTurn(42);+ const nulled = seedUnattributedTurn(null);++ // The read used to coerce 42 to "42" and match a scope asked for as+ // "42"; a number names no session and must never match one.+ const scoped = searchSessionRecall(vault, { query: "needle", sessionId: "42" });+ expect(scoped.hits).toHaveLength(0);++ const unscoped = searchSessionRecall(vault, { query: "needle" });+ const unscopedIds = unscoped.hits.map((hit) => hit.id);+ expect(unscopedIds).toContain(numeric.id);+ expect(unscopedIds).toContain(nulled.id);+ });++ test("the lineage ledger's blank-id omission is pinned: a blank record contributes no link", () => {+ seedAttributedSession();+ appendContinuityRecord(vault, {+ kind: "session_turn",+ createdAt: "2026-05-20T17:40:00.000Z",+ payload: {+ turn_id: "tblank",+ role: "user",+ text: "blank lineage needle",+ root_session_id: "root-blank",+ parent_session_id: "root-blank",+ },+ });++ // The blank record stamps a root but no session id, so it joins no+ // lineage map and cannot turn the flat session into a chain.+ const described = describeSessionRecall(vault, { sessionId: "session-a" });+ expect("lineage_root" in described).toBe(false);+ expect("segments" in described).toBe(false);++ const scoped = searchSessionRecall(vault, { query: "needle", sessionId: "session-a" });+ expect(scoped.hits.every((hit) => hit.turn_id !== "tblank")).toBe(true);+ });+});diff --git a/tests/core/brain/truth/claim-provenance-scans.test.ts b/tests/core/brain/truth/claim-provenance-scans.test.tsnew file mode 100644index 00000000..5e1028bf--- /dev/null+++ b/tests/core/brain/truth/claim-provenance-scans.test.ts@@ -0,0 +1,158 @@+/**+ * One-read-per-ledger provenance hydration (answer-trust repair M3).+ *+ * The events operation hydrates provenance for every sampled claim on+ * its page. Resolving each claim through its own ledger reads would+ * cost three full-ledger scans per claim - remotely triggerable at the+ * page cap - so the report builds one index per ledger and resolves+ * every claim from it. This suite pins the READ COUNT, not just the+ * answer shape: the three ledger readers are wrapped in forwarding+ * module mocks that count calls (the open-store precedent), and a full+ * page of sampled claims must answer from exactly ONE read of each+ * ledger. A page with no sampled claims reads none at all.+ */++import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { appendClaimEvent } from "../../../../src/core/brain/truth/store.ts";+import { TRANSPORT_REACH } from "../../../../src/core/graph/transport-reach.ts";+import { claimEventsReport } from "../../../../src/mcp/brain/knowledge-tools.ts";++// The counters live beside forwarding mocks installed over the three+// ledger-reader modules. Captured before the mock is installed, or the+// forward would recurse; inert (byte-transparent forwards) unless this+// file's test turns counting on, so the mocks never answer differently+// for any other test file sharing the process.+import * as receiptsModule from "../../../../src/core/brain/context-receipts.ts";+import * as outcomesModule from "../../../../src/core/brain/context-pack-outcome.ts";+import * as evidenceModule from "../../../../src/core/brain/context-pack-evidence.ts";++const realListContextReceipts = receiptsModule.listContextReceipts;+const realListContextPackOutcomes = outcomesModule.listContextPackOutcomes;+const realListContextPackEvidence = evidenceModule.listContextPackEvidence;++let receiptReads = 0;+let outcomeReads = 0;+let evidenceReads = 0;+let counting = false;++mock.module("../../../../src/core/brain/context-receipts.ts", () => ({+ ...receiptsModule,+ listContextReceipts: (+ ...args: Parameters<typeof realListContextReceipts>+ ): ReturnType<typeof realListContextReceipts> => {+ if (counting) receiptReads += 1;+ return realListContextReceipts(...args);+ },+}));++mock.module("../../../../src/core/brain/context-pack-outcome.ts", () => ({+ ...outcomesModule,+ listContextPackOutcomes: (+ ...args: Parameters<typeof realListContextPackOutcomes>+ ): ReturnType<typeof realListContextPackOutcomes> => {+ if (counting) outcomeReads += 1;+ return realListContextPackOutcomes(...args);+ },+}));++mock.module("../../../../src/core/brain/context-pack-evidence.ts", () => ({+ ...evidenceModule,+ listContextPackEvidence: (+ ...args: Parameters<typeof realListContextPackEvidence>+ ): ReturnType<typeof realListContextPackEvidence> => {+ if (counting) evidenceReads += 1;+ return realListContextPackEvidence(...args);+ },+}));++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "osb-claim-prov-scans-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ receiptReads = 0;+ outcomeReads = 0;+ evidenceReads = 0;+ counting = false;+});++afterEach(() => {+ counting = false;+ rmSync(tmp, { recursive: true, force: true });+});++/** One receipt plus one claim stated against it, times `count`. */+function seedSampledClaims(count: number): void {+ for (let i = 0; i < count; i += 1) {+ const stamp = `2026-06-0${(i % 8) + 1}T09:00:00.000Z`;+ const receipt = receiptsModule.emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: stamp },+ items: [{ id: `note-${i}`, path: `Brain/notes/note-${i}.md`, tokens: 40 }],+ finalText: `the final answer text ${i}`,+ });+ appendClaimEvent(vault, {+ ts: `2026-06-0${(i % 8) + 1}T10:00:00Z`,+ agent: "claude",+ entity: `Entity ${i}`,+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/note-0.md]]",+ sample_id: receipt.id,+ });+ }+}++describe("provenance hydration reads each ledger once per report", () => {+ test("a full page of sampled claims answers from one read per ledger", () => {+ seedSampledClaims(5);+ counting = true;+ const body = claimEventsReport(vault, undefined, TRANSPORT_REACH.local, {+ sinceMs: null,+ untilMs: null,+ limit: 200,+ });+ counting = false;+ // The hydration is real - every sampled row carries its receipt -+ // so the count pins below are about a working join, not a skipped+ // one.+ const events = body["events"] as ReadonlyArray<{+ provenance?: { receipt?: { id?: string } | null };+ }>;+ expect(events).toHaveLength(5);+ for (const event of events) {+ expect(event.provenance!.receipt!.id).toBeTruthy();+ }+ // One read per ledger for the WHOLE page - not three reads per+ // claim, which at the page cap is three thousand full-ledger scans+ // per call.+ expect(receiptReads).toBe(1);+ expect(outcomeReads).toBe(1);+ expect(evidenceReads).toBe(1);+ });++ test("a page with no sampled claims reads none of the ledgers", () => {+ appendClaimEvent(vault, {+ ts: "2026-06-01T10:00:00Z",+ agent: "claude",+ entity: "Entity 0",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/note-0.md]]",+ });+ counting = true;+ const body = claimEventsReport(vault, undefined, TRANSPORT_REACH.local, {+ sinceMs: null,+ untilMs: null,+ limit: 200,+ });+ counting = false;+ expect(body["total"]).toBe(1);+ expect(receiptReads + outcomeReads + evidenceReads).toBe(0);+ });+});diff --git a/tests/core/brain/truth/claim-provenance.test.ts b/tests/core/brain/truth/claim-provenance.test.tsnew file mode 100644index 00000000..94227fef--- /dev/null+++ b/tests/core/brain/truth/claim-provenance.test.ts@@ -0,0 +1,407 @@+/**+ * Read-only claim-to-provenance join (answer-trust, task B3): a claim's+ * optional `sample_id` resolves to the context receipt it names and the+ * outcome row posted against that sample. Omit-don't-invent governs+ * every half - a missing side is null, never fabricated - and a claim+ * timestamped before its claimed receipt carries an inversion flag+ * instead of being silently joined.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { emitContextPackOutcome } from "../../../../src/core/brain/context-pack-outcome.ts";+import {+ emitContextReceipt,+ listContextReceipts,+} from "../../../../src/core/brain/context-receipts.ts";+import {+ appendContinuityRecord,+ continuityLogPath,+} from "../../../../src/core/brain/continuity/store.ts";+import type { ContinuityRecord } from "../../../../src/core/brain/continuity/types.ts";+import {+ resolveClaimProvenanceFromIndex,+ resolveClaimProvenance,+ loadClaimProvenanceIndex,+} from "../../../../src/core/brain/truth/claim-provenance.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "osb-claim-prov-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const RECEIPT_CREATED = "2026-06-02T09:00:00.000Z";+const CLAIM_TS_AFTER = "2026-06-02T10:00:00Z";++function emitSampleReceipt(): ContinuityRecord {+ return emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: RECEIPT_CREATED },+ items: [+ { id: "note-alpha", path: "Brain/notes/alpha.md", tokens: 40, trimmed: false },+ { id: "note-beta", path: "Brain/notes/beta.md", tokens: 20, trimmed: true },+ ],+ finalText: "the final answer text",+ });+}++describe("resolveClaimProvenance", () => {+ test("resolves a receipt-backed sample id to receipt items and both verdicts", () => {+ const receipt = emitSampleReceipt();+ emitContextPackOutcome(+ vault,+ {+ createdAt: "2026-06-03T09:00:00.000Z",+ host: "mcp",+ sampleId: receipt.id,+ firstPassSuccess: true,+ evidenceClaim: { itemCount: 2 },+ },+ true,+ );+ const provenance = resolveClaimProvenance(vault, receipt.id, CLAIM_TS_AFTER);+ expect(provenance.sample_id).toBe(receipt.id);+ expect(provenance.receipt).not.toBeNull();+ expect(provenance.receipt!.id).toBe(receipt.id);+ expect(provenance.receipt!.created_at).toBe(RECEIPT_CREATED);+ expect(provenance.receipt!.trigger).toBe("context_pack");+ expect(provenance.receipt!.withheld).toBe(false);+ expect(provenance.receipt!.items).toEqual([+ { id: "note-alpha", path: "Brain/notes/alpha.md", trimmed: false },+ { id: "note-beta", path: "Brain/notes/beta.md", trimmed: true },+ ]);+ expect(provenance.outcome).not.toBeNull();+ expect(provenance.outcome!.first_pass_success).toBe(true);+ expect(provenance.outcome!.evidence_verdict).toBe("match");+ expect(provenance.timestamp_inverted).toBe(false);+ });++ test("a sample id with a receipt but no outcome row is receipt known, outcome unknown", () => {+ // Absent, never invented: the outcome half stays null and no verdict+ // is fabricated for the caller.+ const receipt = emitSampleReceipt();+ const provenance = resolveClaimProvenance(vault, receipt.id, CLAIM_TS_AFTER);+ expect(provenance.receipt).not.toBeNull();+ expect(provenance.outcome).toBeNull();+ expect(provenance.timestamp_inverted).toBe(false);+ });++ test("an outcome-only sample id (opaque request hash) resolves the outcome without a receipt", () => {+ emitContextPackOutcome(+ vault,+ {+ createdAt: "2026-06-03T09:00:00.000Z",+ sampleId: "req-hash:0123456789abcdef",+ firstPassSuccess: false,+ repairRequired: true,+ },+ true,+ );+ const provenance = resolveClaimProvenance(vault, "req-hash:0123456789abcdef", CLAIM_TS_AFTER);+ expect(provenance.receipt).toBeNull();+ expect(provenance.outcome).not.toBeNull();+ expect(provenance.outcome!.first_pass_success).toBe(false);+ expect(provenance.timestamp_inverted).toBe(false);+ });++ test("an unknown sample id resolves nothing on either side", () => {+ const provenance = resolveClaimProvenance(vault, "rcpt-absent", CLAIM_TS_AFTER);+ expect(provenance.sample_id).toBe("rcpt-absent");+ expect(provenance.receipt).toBeNull();+ expect(provenance.outcome).toBeNull();+ expect(provenance.timestamp_inverted).toBe(false);+ });++ test("a claim timestamped before its claimed receipt carries the inversion flag", () => {+ const receipt = emitSampleReceipt();+ const provenance = resolveClaimProvenance(vault, receipt.id, "2026-06-01T10:00:00Z");+ expect(provenance.receipt).not.toBeNull();+ expect(provenance.timestamp_inverted).toBe(true);+ });++ test("a claim at exactly the receipt's created_at is not inverted", () => {+ // "Predates" is strict: the receipt the claim names existed at the+ // claim's own second.+ const receipt = emitSampleReceipt();+ const provenance = resolveClaimProvenance(vault, receipt.id, RECEIPT_CREATED);+ expect(provenance.timestamp_inverted).toBe(false);+ });++ test("a sub-second claim stamp after its receipt's second is not inverted", () => {+ // The compare is between parsed instants, not strings. Lexically, a+ // millis claim stamp (`...:00.500Z`) sorts before a second-precision+ // receipt stamp (`...:00Z`) - "." < "Z" - so a string compare flags+ // a claim written half a second AFTER its receipt as an inversion.+ // The receipts the continuity boundary stamps at second precision+ // are exactly the shape that hits this.+ const receipt = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: "2026-06-02T09:00:00Z" },+ items: [{ id: "note-alpha", path: "Brain/notes/alpha.md", tokens: 40 }],+ finalText: "the final answer text",+ });+ const provenance = resolveClaimProvenance(vault, receipt.id, "2026-06-02T09:00:00.500Z");+ expect(provenance.receipt).not.toBeNull();+ expect(provenance.timestamp_inverted).toBe(false);+ });++ test("a sub-second claim stamp before its receipt's second is inverted", () => {+ // The parsed-instant form must not weaken the flag either direction:+ // a claim half a second BEFORE the receipt still predates it.+ const receipt = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: "2026-06-02T09:00:00Z" },+ items: [{ id: "note-alpha", path: "Brain/notes/alpha.md", tokens: 40 }],+ finalText: "the final answer text",+ });+ const provenance = resolveClaimProvenance(vault, receipt.id, "2026-06-02T08:59:59.500Z");+ expect(provenance.timestamp_inverted).toBe(true);+ });++ test("a private receipt is known but its items are never unfolded", () => {+ // The receipts-fold rule, applied at the join: redacted content must+ // not re-enter the vault through a claim's provenance.+ const record = appendContinuityRecord(vault, {+ kind: "context_receipt",+ createdAt: RECEIPT_CREATED,+ sourceRefs: [],+ private: true,+ payload: {+ host: "mcp",+ trigger: "context_pack",+ item_count: 1,+ items: [{ id: "note-secret", path: "Brain/notes/private.md" }],+ final_text_hash: "abc",+ },+ });+ const provenance = resolveClaimProvenance(vault, record.id, CLAIM_TS_AFTER);+ expect(provenance.receipt).not.toBeNull();+ expect(provenance.receipt!.withheld).toBe(true);+ expect(provenance.receipt!.items).toEqual([]);+ expect(JSON.stringify(provenance)).not.toContain("note-secret");+ });++ test("an excluded receipt renders as the unknown-id answer", () => {+ // The caller's receipt-visibility rule (the receipts list's exclude+ // hook, bound below local reach by the surfaces): a store without+ // the excluded receipt answers "no receipt names this id", so the+ // receipt half renders null - never a marker confirming it exists.+ const receipt = emitSampleReceipt();+ emitContextPackOutcome(+ vault,+ { createdAt: "2026-06-03T09:00:00.000Z", sampleId: receipt.id, firstPassSuccess: true },+ true,+ );+ const provenance = resolveClaimProvenance(vault, receipt.id, CLAIM_TS_AFTER, {+ exclude: (record) => record.id === receipt.id,+ });+ expect(provenance.receipt).toBeNull();+ // The outcome half is the caller's to keep: the exclusion is a+ // receipt-visibility rule, not an outcome one.+ expect(provenance.outcome).not.toBeNull();+ expect(provenance.timestamp_inverted).toBe(false);+ });++ test("items the caller may not see leave the unfolded items", () => {+ // The receipts fold's excludeItem hook shape: a surface binds its+ // reach's item rule and the join drops those items before the+ // answer is built, so provenance never discloses an item the caller+ // could not read directly.+ const receipt = emitSampleReceipt();+ const provenance = resolveClaimProvenance(vault, receipt.id, CLAIM_TS_AFTER, {+ excludeItem: (item) => (item as { id?: unknown })["id"] === "note-alpha",+ });+ expect(provenance.receipt!.items).toEqual([+ { id: "note-beta", path: "Brain/notes/beta.md", trimmed: true },+ ]);+ });++ test("an evidence row that never posted leaves the evidence verdict absent", () => {+ // The outcome row's first-pass verdict is the row's own field; the+ // evidence verdict exists only when its own row exists.+ const receipt = emitSampleReceipt();+ const outcome = emitContextPackOutcome(+ vault,+ { createdAt: "2026-06-03T09:00:00.000Z", sampleId: receipt.id, firstPassSuccess: true },+ true,+ );+ expect(outcome).not.toBeNull();+ const provenance = resolveClaimProvenance(vault, receipt.id, CLAIM_TS_AFTER);+ expect(provenance.outcome).not.toBeNull();+ expect(provenance.outcome!.evidence_verdict).toBe("unclaimed");+ });++ test("an outcome row without a first-pass verdict renders unknown, never false", () => {+ // L2.3 regression: the `=== true` coercion turned a MISSING verdict+ // into `false`, inventing a failed first pass for a row that carried+ // none. The outcome writer validates the boolean, but the reader+ // meets whatever the ledger holds, so unknown renders as null.+ const receipt = emitSampleReceipt();+ appendContinuityRecord(vault, {+ kind: "context_pack_outcome",+ createdAt: "2026-06-03T09:00:00.000Z",+ sourceRefs: [],+ payload: { sample_id: receipt.id },+ });+ const provenance = resolveClaimProvenance(vault, receipt.id, CLAIM_TS_AFTER);+ expect(provenance.outcome).not.toBeNull();+ expect(provenance.outcome!.first_pass_success).toBeNull();+ });++ test("a blank sample id refuses by name", () => {+ // Unreachable through the ledger (the store refuses blank ids at+ // write), refused here too so no caller can read silence as an+ // answer.+ expect(() => resolveClaimProvenance(vault, " ", CLAIM_TS_AFTER)).toThrow(/sample_id/);+ });++ test("a receipt record with a non-canonical createdAt reads as unknown, not a failed read", () => {+ // M4 regression: the continuity reader validates `createdAt` on+ // append only, so a shard synced from another device or edited by+ // hand can carry a stamp no append would accept. The join degrades+ // PER CLAIM - the claim naming the unreadable receipt answers+ // "receipt unknown", exactly as an absent id would - instead of+ // failing the whole events read for every unrelated claim.+ const receipt = emitSampleReceipt();+ const shard = continuityLogPath(vault, receipt.createdAt.slice(0, 7));+ const text = readFileSync(shard, "utf8");+ const unreadable = { ...receipt, createdAt: "2026-06-garbage" };+ writeFileSync(shard, text.replace(JSON.stringify(receipt), JSON.stringify(unreadable)));+ const provenance = resolveClaimProvenance(vault, receipt.id, CLAIM_TS_AFTER);+ expect(provenance.receipt).toBeNull();+ expect(provenance.outcome).toBeNull();+ expect(provenance.timestamp_inverted).toBe(false);+ // The indexed path (what the events report takes) degrades the same+ // way: the unreadable record never enters the index.+ const index = loadClaimProvenanceIndex(vault);+ expect(index.receiptsByReceiptId.has(receipt.id)).toBe(false);+ expect(resolveClaimProvenanceFromIndex(index, receipt.id, CLAIM_TS_AFTER).receipt).toBeNull();+ });+});++describe("listContextReceipts receiptId filter", () => {+ test("filters to exactly the named receipt", () => {+ emitSampleReceipt();+ const middle = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: "2026-06-03T09:00:00.000Z" },+ items: [{ id: "note-middle" }],+ finalText: "middle",+ });+ emitSampleReceipt();+ const matched = listContextReceipts(vault, { receiptId: middle.id });+ expect(matched).toHaveLength(1);+ expect(matched[0]!.id).toBe(middle.id);+ });++ test("the receiptId match is applied BEFORE the limit", () => {+ // Pinning the order: a receipt lookup with a page bound answers with+ // the NAMED receipt, never with whichever receipts happen to be+ // newest. The oldest receipt is findable at limit 1. The three+ // fixtures stamp DISTINCT createdAt values on DISTINCT payloads so+ // they derive distinct record ids - byte-identical fixtures would+ // collapse into one id and the pin would pass even for a filter+ // applied after the slice, which returns whichever receipt is+ // newest.+ const oldest = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: "2026-06-02T09:00:00.000Z" },+ items: [{ id: "note-oldest" }],+ finalText: "oldest",+ });+ emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: "2026-06-02T09:05:00.000Z" },+ items: [{ id: "note-middle" }],+ finalText: "middle",+ });+ emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: "2026-06-02T09:10:00.000Z" },+ items: [{ id: "note-newest" }],+ finalText: "newest",+ });+ const matched = listContextReceipts(vault, { receiptId: oldest.id, limit: 1 });+ expect(matched).toHaveLength(1);+ expect(matched[0]!.id).toBe(oldest.id);+ });++ test("an unknown receipt id answers empty", () => {+ emitSampleReceipt();+ expect(listContextReceipts(vault, { receiptId: "rcpt-absent" })).toHaveLength(0);+ });+});++describe("loadClaimProvenanceIndex + resolveClaimProvenanceFromIndex", () => {+ test("resolves every sample id exactly as the single-call join does", () => {+ const first = emitSampleReceipt();+ const second = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "pre_compress", createdAt: "2026-06-02T11:00:00.000Z" },+ items: [{ id: "note-gamma", path: "Brain/notes/gamma.md", trimmed: false }],+ finalText: "gamma text",+ });+ emitContextPackOutcome(+ vault,+ {+ createdAt: "2026-06-03T09:00:00.000Z",+ sampleId: first.id,+ firstPassSuccess: true,+ evidenceClaim: { itemCount: 2 },+ },+ true,+ );+ const index = loadClaimProvenanceIndex(vault);+ for (const id of [first.id, second.id, "rcpt-absent"]) {+ expect(resolveClaimProvenanceFromIndex(index, id, CLAIM_TS_AFTER)).toEqual(+ resolveClaimProvenance(vault, id, CLAIM_TS_AFTER),+ );+ }+ });++ test("keeps the newest record per sample id when a ledger holds duplicates", () => {+ // The filtered list functions answer newest-first, so the NEWEST+ // row under a key is the answer; an index that let an older row win+ // would resolve a different join than the single call.+ emitContextPackOutcome(+ vault,+ {+ createdAt: "2026-06-02T09:00:00.000Z",+ sampleId: "req-hash:duplicate",+ firstPassSuccess: true,+ },+ true,+ );+ emitContextPackOutcome(+ vault,+ {+ createdAt: "2026-06-03T09:00:00.000Z",+ sampleId: "req-hash:duplicate",+ firstPassSuccess: false,+ },+ true,+ );+ const index = loadClaimProvenanceIndex(vault);+ expect(+ resolveClaimProvenanceFromIndex(index, "req-hash:duplicate", CLAIM_TS_AFTER).outcome!+ .first_pass_success,+ ).toBe(false);+ expect(+ resolveClaimProvenance(vault, "req-hash:duplicate", CLAIM_TS_AFTER).outcome!+ .first_pass_success,+ ).toBe(false);+ });++ test("carries the caller's exclusion hooks to the indexed resolution", () => {+ const receipt = emitSampleReceipt();+ const index = loadClaimProvenanceIndex(vault);+ const provenance = resolveClaimProvenanceFromIndex(index, receipt.id, CLAIM_TS_AFTER, {+ exclude: (record) => record.id === receipt.id,+ excludeItem: (item) => (item as { id?: unknown })["id"] === "note-beta",+ });+ expect(provenance.receipt).toBeNull();+ });+});diff --git a/tests/core/brain/truth/stated-claims.test.ts b/tests/core/brain/truth/stated-claims.test.tsindex f7ae889f..d4067f7f 100644--- a/tests/core/brain/truth/stated-claims.test.ts+++ b/tests/core/brain/truth/stated-claims.test.ts@@ -15,7 +15,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdtempSync, rmSync } from "node:fs";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -270,3 +270,83 @@ describe("appendStatedClaims", () => {expect(readClaimEvents(vault).events).toHaveLength(0);});});++describe("payload sampleId (answer-trust, task B2)", () => {+ test("a present sampleId is trimmed and threads onto every committed event", () => {+ const outcome = withDeviceId("", () =>+ appendStatedClaims(vault, {+ ...PAYLOAD,+ sampleId: " rcpt-2026-0601-abcd ",+ claims: [claim()],+ }),+ );+ expect(outcome.committed).toHaveLength(1);+ expect(outcome.committed[0]!.event.sample_id).toBe("rcpt-2026-0601-abcd");+ const events = readClaimEvents(vault).events;+ expect(events[0]!.sample_id).toBe("rcpt-2026-0601-abcd");+ });++ test("a multi-claim payload threads the same sampleId onto each commit", () => {+ const outcome = withDeviceId("", () =>+ appendStatedClaims(vault, {+ ...PAYLOAD,+ sampleId: "rcpt-1",+ claims: [claim(), claim({ subject: "Bob Stone", object: "Meta" })],+ }),+ );+ // The text anchors Alice Mason and Meta but not Bob Stone, so the+ // second claim reports back and only the first commits.+ expect(outcome.committed).toHaveLength(1);+ expect(outcome.committed[0]!.event.sample_id).toBe("rcpt-1");+ });++ test("an empty or whitespace-only sampleId refuses the whole payload, before any write", () => {+ // Named refusal, never coerced: a blank id is not an absent one.+ expect(() =>+ withDeviceId("", () =>+ appendStatedClaims(vault, { ...PAYLOAD, sampleId: "", claims: [claim()] }),+ ),+ ).toThrow(StatedClaimsRefusal);+ expect(() =>+ withDeviceId("", () =>+ appendStatedClaims(vault, { ...PAYLOAD, sampleId: " ", claims: [claim()] }),+ ),+ ).toThrow(/sample_id/);+ expect(readClaimEvents(vault).events).toHaveLength(0);+ });++ test("a sampleId over the 256-character cap refuses the whole payload, naming the limit", () => {+ // L2.1 regression: the same shape check the store append applies,+ // fired HERE so an unacceptable id refuses before the first write+ // instead of surfacing mid-loop.+ expect(() =>+ withDeviceId("", () =>+ appendStatedClaims(vault, { ...PAYLOAD, sampleId: "r".repeat(300), claims: [claim()] }),+ ),+ ).toThrow(/sample_id must be a non-empty string of at most 256 characters/);+ // Exactly at the cap threads.+ const atCap = withDeviceId("", () =>+ appendStatedClaims(vault, { ...PAYLOAD, sampleId: "r".repeat(256), claims: [claim()] }),+ );+ expect(atCap.committed[0]!.event.sample_id).toHaveLength(256);+ });++ test("a sampleId carrying a control character refuses the whole payload", () => {+ expect(() =>+ withDeviceId("", () =>+ appendStatedClaims(vault, { ...PAYLOAD, sampleId: "rcpt\u0000-1", claims: [claim()] }),+ ),+ ).toThrow(/without control characters/);+ expect(readClaimEvents(vault).events).toHaveLength(0);+ });++ test("an absent sampleId leaves the committed events byte-identical to today", () => {+ const outcome = withDeviceId("", () =>+ appendStatedClaims(vault, { ...PAYLOAD, claims: [claim()] }),+ );+ expect(outcome.committed).toHaveLength(1);+ expect("sample_id" in outcome.committed[0]!.event).toBe(false);+ const line = readFileSync(join(vault, "Brain", "truth", "claims.jsonl"), "utf8");+ expect(line).not.toContain("sample_id");+ });+});diff --git a/tests/core/brain/truth/store.test.ts b/tests/core/brain/truth/store.test.tsindex 8f7381d8..b0172f2b 100644--- a/tests/core/brain/truth/store.test.ts+++ b/tests/core/brain/truth/store.test.ts@@ -437,3 +437,122 @@ describe("claim validity windows (presence-gated, schema v1)", () => {expect(warnings.map((w) => w.message)).toEqual(["invalid claim extractor: 42"]);});});++describe("claim sample_id (presence-gated, schema v1)", () => {+ // The same windowless line the validity block pins: a sample-less+ // append must serialize byte-identically to the pre-attribution+ // ledger, so the schema version never moves for this field.+ const PLAIN_LINE =+ JSON.stringify({+ v: 1,+ ts: "2026-06-01T10:00:00Z",+ agent: "claude-dev-agent",+ entity: "alice mason",+ aspect: "employer",+ value: "Google",+ valueKind: "text",+ source: "[[Brain/notes/standup.md]]",+ }) + "\n";++ test("a sample-less append writes a byte-identical line (no sample_id key)", () => {+ const written = append();+ expect(readFileSync(written.path, "utf8")).toBe(PLAIN_LINE);+ expect("sample_id" in written.event).toBe(false);+ });++ test("a present sample_id is stored verbatim and roundtrips through the reader", () => {+ const written = append({ sample_id: "rcpt-2026-0601-abcd" });+ const row = JSON.parse(readFileSync(written.path, "utf8")) as Record<string, unknown>;+ // Opaque caller-supplied id: stored verbatim, never normalized.+ expect(row["sample_id"]).toBe("rcpt-2026-0601-abcd");+ expect(row["v"]).toBe(1);+ expect(written.event.sample_id).toBe("rcpt-2026-0601-abcd");+ const { events, warnings } = readClaimEvents(vault);+ expect(warnings).toHaveLength(0);+ expect(events).toHaveLength(1);+ expect(events[0]!.sample_id).toBe("rcpt-2026-0601-abcd");+ });++ test("an empty or whitespace-only sample_id refuses the append, writing nothing", () => {+ // Named refusal, never coerced: a blank id means nothing and is not+ // upgraded to an absent one behind the caller's back.+ expect(() => append({ sample_id: "" })).toThrow(/sample_id/);+ expect(() => append({ sample_id: " " })).toThrow(/sample_id/);+ expect(readClaimEvents(vault).events).toHaveLength(0);+ });++ test("a sample_id over the 256-character cap refuses the append by name", () => {+ // L2.1 regression: the id is copied onto every claim stated against+ // the sample, so an unbounded one multiplied one call's payload+ // across the ledger. The refusal names the limit.+ expect(() => append({ sample_id: "r".repeat(300) })).toThrow(+ /sample_id must be a non-empty string of at most 256 characters/,+ );+ // Exactly at the cap is acceptable.+ expect(append({ sample_id: "r".repeat(256) }).event.sample_id).toHaveLength(256);+ expect(readClaimEvents(vault).events).toHaveLength(1);+ });++ test("a sample_id carrying a control character refuses the append by name", () => {+ // Non-whitespace control characters (NUL, bell, DEL) refuse by name;+ // whitespace controls are removed by the same trim both paths apply,+ // so they never reach this check.+ expect(() => append({ sample_id: "rcpt\u0000-1" })).toThrow(+ /sample_id must be a non-empty string of at most 256 characters without control characters/,+ );+ expect(() => append({ sample_id: "rcpt\u0007-1" })).toThrow(/without control characters/);+ expect(() => append({ sample_id: "rcpt-1\u007F" })).toThrow(/without control characters/);+ expect(readClaimEvents(vault).events).toHaveLength(0);+ });++ test("a whitespace-padded sample_id is stored trimmed, matching what the stated path threads", () => {+ // L2.2 regression: the store applies the SAME trim as the stated+ // boundary, so a padded id threads and stores identically on both+ // paths and the provenance join resolves what was threaded.+ const written = append({ sample_id: " rcpt-2026-0601-abcd " });+ expect(written.event.sample_id).toBe("rcpt-2026-0601-abcd");+ const row = JSON.parse(readFileSync(written.path, "utf8")) as Record<string, unknown>;+ expect(row["sample_id"]).toBe("rcpt-2026-0601-abcd");+ });++ test("the reader passes a stored sample_id through verbatim, whatever it spells", () => {+ // The id is opaque: the reader validates it is a non-empty string and+ // otherwise keeps the caller's exact bytes.+ mkdirSync(truthDir(vault), { recursive: true });+ const opaque = {+ v: 1,+ ts: "2026-06-01T09:00:00Z",+ agent: "a",+ entity: "alice mason",+ aspect: "employer",+ value: "Google",+ valueKind: "text",+ source: "[[x]]",+ sample_id: "req-hash:0123456789abcdef",+ };+ writeFileSync(join(truthDir(vault), "claims.jsonl"), JSON.stringify(opaque) + "\n");+ const { events, warnings } = readClaimEvents(vault);+ expect(warnings).toHaveLength(0);+ expect(events).toHaveLength(1);+ expect(events[0]!.sample_id).toBe("req-hash:0123456789abcdef");+ });++ test("a sample_id that is not a non-empty string drops the line with a warning", () => {+ mkdirSync(truthDir(vault), { recursive: true });+ const badId = {+ v: 1,+ ts: "2026-06-01T09:00:00Z",+ agent: "a",+ entity: "alice mason",+ aspect: "employer",+ value: "Google",+ valueKind: "text",+ source: "[[x]]",+ sample_id: 42,+ };+ writeFileSync(join(truthDir(vault), "claims.jsonl"), JSON.stringify(badId) + "\n");+ const { events, warnings } = readClaimEvents(vault);+ expect(events).toHaveLength(0);+ expect(warnings.map((w) => w.message)).toEqual(["invalid claim sample_id: 42"]);+ });+});diff --git a/tests/core/brain/vault-guard-census.test.ts b/tests/core/brain/vault-guard-census.test.tsindex ec38ded8..afb28868 100644--- a/tests/core/brain/vault-guard-census.test.ts+++ b/tests/core/brain/vault-guard-census.test.ts@@ -105,6 +105,12 @@ const UNGUARDED_WITH_REASON: Readonly<Record<string, string>> = Object.freeze({"src/core/brain/portability/recall-sources.ts":"machine-local recall-source registry under the config directory, not " +"vault content. Keyed by `configPath`; no vault is in scope.",+ "src/core/brain/provenance/source-archive.ts":+ "every path it writes or removes is derived inside this module from the " ++ "entry's own sha-256 and validated before the join, so the store cannot be " ++ "aimed anywhere but `Brain/.archives/`; its two vault-reaching callers (the " ++ "ingest trusted branch and the confirmed delete-by-source) assert vault " ++ "identity ahead of the first byte and ahead of the removal.","src/core/brain/secrets/crypto.ts":"takes a keyfile path, not a vault. The three public entry points in " +"`secrets/store.ts` that reach it are guarded ahead of their first byte.",diff --git a/tests/core/config-answer-quote-check.test.ts b/tests/core/config-answer-quote-check.test.tsnew file mode 100644index 00000000..a3924280--- /dev/null+++ b/tests/core/config-answer-quote-check.test.ts@@ -0,0 +1,218 @@+/**+ * The `quote_check.*` config resolvers (answer-trust wave, Lane A).+ *+ * Three keys in the `quote_check` block of `Brain/_brain.yaml`, one+ * resolver each, no second reader: default `shadow` per phase,+ * `off|shadow|enforce` accepted, any other value a field-named error+ * naming `quote_check.<phase>` (never silently `off`), unknown block keys+ * warned per the strict-block convention. The resolvers are pure: the+ * brain config path in, the mode out; no environment variable and no+ * other file participates.+ */++import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ ANSWER_QUOTE_CHECK_MODES,+ isAnswerQuoteCheckMode,+ resolveAnswerQuoteCheckActive,+ resolveAnswerQuoteCheckRecall,+ resolveAnswerQuoteCheckSubagent,+} from "../../src/core/config.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-quote-check-config-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** Write a `Brain/_brain.yaml` under `root` and return its path. */+function brainYaml(body: string, root: string = tmp): string {+ const brain = join(root, "Brain");+ mkdirSync(brain, { recursive: true });+ const path = join(brain, "_brain.yaml");+ writeFileSync(path, body);+ return path;+}++/** A path under the throwaway root where nothing was ever written. */+function absentPath(): string {+ return join(tmp, "Brain", "missing", "_brain.yaml");+}++describe("ANSWER_QUOTE_CHECK_MODES vocabulary", () => {+ test("carries exactly the three modes and the guard accepts only them", () => {+ expect(ANSWER_QUOTE_CHECK_MODES).toEqual(["off", "shadow", "enforce"]);+ expect(isAnswerQuoteCheckMode("shadow")).toBe(true);+ for (const outsider of ["", "off ", "ON", "enforced", null, undefined, 42, {}]) {+ expect(isAnswerQuoteCheckMode(outsider)).toBe(false);+ }+ });+});++describe("resolveAnswerQuoteCheck* defaults", () => {+ test("an absent config file resolves every phase to shadow", () => {+ const absent = absentPath();+ expect(resolveAnswerQuoteCheckRecall(absent)).toBe("shadow");+ expect(resolveAnswerQuoteCheckActive(absent)).toBe("shadow");+ expect(resolveAnswerQuoteCheckSubagent(absent)).toBe("shadow");+ });++ test("a config without the block resolves every phase to shadow", () => {+ const path = brainYaml("schema_version: 2\n");+ expect(resolveAnswerQuoteCheckRecall(path)).toBe("shadow");+ expect(resolveAnswerQuoteCheckActive(path)).toBe("shadow");+ expect(resolveAnswerQuoteCheckSubagent(path)).toBe("shadow");+ });++ test("a block without the phase key resolves that phase to shadow", () => {+ const path = brainYaml("quote_check:\n recall: enforce\n");+ expect(resolveAnswerQuoteCheckRecall(path)).toBe("enforce");+ expect(resolveAnswerQuoteCheckActive(path)).toBe("shadow");+ expect(resolveAnswerQuoteCheckSubagent(path)).toBe("shadow");+ });+});++describe("resolveAnswerQuoteCheck* accepted values", () => {+ for (const mode of ANSWER_QUOTE_CHECK_MODES) {+ test(`each resolver reads its own key: ${mode}`, () => {+ const path = brainYaml(+ `quote_check:\n recall: ${mode}\n active: ${mode}\n subagent: ${mode}\n`,+ );+ expect(resolveAnswerQuoteCheckRecall(path)).toBe(mode);+ expect(resolveAnswerQuoteCheckActive(path)).toBe(mode);+ expect(resolveAnswerQuoteCheckSubagent(path)).toBe(mode);+ });+ }++ test("quoted values read the same as bare words", () => {+ const path = brainYaml('quote_check:\n recall: "enforce"\n');+ expect(resolveAnswerQuoteCheckRecall(path)).toBe("enforce");+ });+});++describe("resolveAnswerQuoteCheck* refusals", () => {+ test("an unknown value is a field-named error, never a silent off", () => {+ const path = brainYaml("quote_check:\n recall: enforced\n");+ expect(() => resolveAnswerQuoteCheckRecall(path)).toThrow(+ /quote_check\.recall: unsupported value "enforced"; expected one of off, shadow, enforce/,+ );+ });++ test("a wrongly typed value is the same field-named error", () => {+ const numbered = brainYaml("quote_check:\n active: 3\n");+ expect(() => resolveAnswerQuoteCheckActive(numbered)).toThrow(/quote_check\.active:/);+ const flagged = brainYaml("quote_check:\n subagent: true\n");+ expect(() => resolveAnswerQuoteCheckSubagent(flagged)).toThrow(/quote_check\.subagent:/);+ const empty = brainYaml("quote_check:\n recall:\n");+ expect(() => resolveAnswerQuoteCheckRecall(empty)).toThrow(/quote_check\.recall:/);+ });++ test("a scalar block is a field-named error on the block", () => {+ const path = brainYaml("quote_check: enforce\n");+ expect(() => resolveAnswerQuoteCheckRecall(path)).toThrow(+ /quote_check: expected a block of per-phase modes/,+ );+ });++ test("a malformed YAML file is refused by name, with the parser's line detail", () => {+ const path = brainYaml("quote_check:\n deep:\n nested: 1\n");+ expect(() => resolveAnswerQuoteCheckRecall(path)).toThrow(+ /quote_check: failed to parse: line \d+/,+ );+ });+});++describe("unknown keys inside the quote_check block", () => {+ test("warn per the strict-block convention without disturbing the known keys", () => {+ const errWrite = spyOn(process.stderr, "write").mockReturnValue(true);+ try {+ const path = brainYaml("quote_check:\n recall: off\n bogus: enforce\n");+ expect(resolveAnswerQuoteCheckRecall(path)).toBe("off");+ const lines = errWrite.mock.calls+ .map((call) => String(call[0]))+ .filter((text) => text.includes("quote_check."));+ expect(lines).toEqual(["quote_check.bogus: unknown field ignored (forward-compat)\n"]);+ } finally {+ errWrite.mockRestore();+ }+ });++ test("warn once per key per process, not once per call", () => {+ const errWrite = spyOn(process.stderr, "write").mockReturnValue(true);+ try {+ const path = brainYaml("quote_check:\n subagent: off\n mistyped: shadow\n");+ resolveAnswerQuoteCheckSubagent(path);+ resolveAnswerQuoteCheckSubagent(path);+ const lines = errWrite.mock.calls+ .map((call) => String(call[0]))+ .filter((text) => text.includes("quote_check.mistyped"));+ expect(lines.length).toBe(1);+ } finally {+ errWrite.mockRestore();+ }+ });++ test("a block with only known keys warns nothing", () => {+ const errWrite = spyOn(process.stderr, "write").mockReturnValue(true);+ try {+ const path = brainYaml(+ "quote_check:\n recall: off\n active: enforce\n subagent: shadow\n",+ );+ expect(resolveAnswerQuoteCheckActive(path)).toBe("enforce");+ const lines = errWrite.mock.calls+ .map((call) => String(call[0]))+ .filter((text) => text.includes("quote_check."));+ expect(lines).toEqual([]);+ } finally {+ errWrite.mockRestore();+ }+ });+});++describe("the resolvers are pure", () => {+ test("no environment variable and no second file participates", () => {+ const path = brainYaml("quote_check:\n recall: enforce\n");+ const other = brainYaml("quote_check:\n recall: off\n", join(tmp, "other-vault"));+ expect(other).not.toBe(path);+ process.env["OPEN_SECOND_BRAIN_QUOTE_CHECK_RECALL"] = "off";+ process.env["QUOTE_CHECK_RECALL"] = "off";+ process.env["OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED"] = "false";+ try {+ expect(resolveAnswerQuoteCheckRecall(path)).toBe("enforce");+ expect(resolveAnswerQuoteCheckRecall(other)).toBe("off");+ } finally {+ delete process.env["OPEN_SECOND_BRAIN_QUOTE_CHECK_RECALL"];+ delete process.env["QUOTE_CHECK_RECALL"];+ delete process.env["OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED"];+ }+ });++ test("without a path, the standard vault's Brain/_brain.yaml is read", () => {+ const vault = tmp;+ brainYaml("quote_check:\n active: enforce\n", vault);+ process.env["VAULT_DIR"] = vault;+ try {+ expect(resolveAnswerQuoteCheckActive()).toBe("enforce");+ expect(resolveAnswerQuoteCheckRecall()).toBe("shadow");+ } finally {+ delete process.env["VAULT_DIR"];+ }+ });++ test("without a path and without a vault, the defaults apply", () => {+ process.env["VAULT_DIR"] = join(tmp, "no", "such", "vault");+ try {+ expect(resolveAnswerQuoteCheckSubagent()).toBe("shadow");+ } finally {+ delete process.env["VAULT_DIR"];+ }+ });+});diff --git a/tests/core/search/kind-attributes-pushdown.test.ts b/tests/core/search/kind-attributes-pushdown.test.tsindex 7a75f392..654d167d 100644--- a/tests/core/search/kind-attributes-pushdown.test.ts+++ b/tests/core/search/kind-attributes-pushdown.test.ts@@ -32,7 +32,7 @@*/import { Database } from "bun:sqlite";-import { writeFileSync } from "node:fs";+import { mkdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, test } from "bun:test";@@ -50,11 +50,13 @@ import {} from "../../../src/core/search/query-cache.ts";import { keywordTopK, keywordTopKSql } from "../../../src/core/search/store/keyword.ts";import { semanticTopK, semanticTopKSql } from "../../../src/core/search/store/vectors.ts";+import { Store, indexedSnapshotStale } from "../../../src/core/search/store.ts";import { resolvePoolFilters } from "../../../src/core/search/pipeline/pool-filters.ts";import {isSearchKind,resolveKindFilter,resolvePropertyPushdown,+ withoutAttributeNarrowing,} from "../../../src/core/search/property-pushdown.ts";import { SearchError } from "../../../src/core/search/search-error.ts";import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";@@ -864,6 +866,194 @@ describe("the unpromoted attribute narrowing (document_attributes)", () => {});});+/**+ * A fixed instant far from "now", so a forced mtime is deterministic.+ */+const EDITED_MTIME_MS = 1_700_000_000_000;++/**+ * The freshness gate's corpus: two draft pages whose snapshots start in+ * sync with their files.+ */+async function seedFlipVault(): Promise<void> {+ writeMd(vault, "notes/flip.md", note("Flip", "status: draft\n", "lattice delta flipgate"));+ writeMd(vault, "notes/hold.md", note("Hold", "status: draft\n", "lattice delta holdgate"));+ await indexVault(makeConfig({ vault, dbPath }));+}++/** Rewrite a note's frontmatter and force a stat the index contradicts. */+function editNote(relPath: string, frontmatter: string, body: string): void {+ const abs = writeMd(vault, relPath, note(relPath, frontmatter, body));+ const edited = new Date(EDITED_MTIME_MS);+ utimesSync(abs, edited, edited);+}++/**+ * The freshness gate on attribute narrowing (answer-trust repair, M1).+ *+ * The narrowing fragment excludes a document when the attributes side+ * table holds rows for a key and none of them is accepted - but those rows+ * are a SNAPSHOT taken at index time. A document indexed `status: draft`+ * and edited to `status: done` must not vanish from a `status=done` query:+ * the advertised contract is "narrow on the attribute snapshot, judged+ * live" (the brain_search `properties` schema), so a candidate whose+ * indexed snapshot may be stale falls through to the live post-rank+ * filter instead of being dropped in SQL.+ *+ * The gate rides the stat fingerprint the index already maintains+ * (`documents.mtime` + `documents.size`, the exact pair the indexer's+ * fastpath treats as "content unchanged"): a candidate the narrowing would+ * exclude gets one stat, and only a live stat that still matches the+ * indexed fingerprint proves the snapshot current. It never reads file+ * contents - that read is the live filter's own, paid for every surfaced+ * row exactly as before.+ */+describe("the freshness gate on attribute narrowing", () => {+ test("a document indexed draft and edited to done is returned under status=done", async () => {+ const cfg = makeConfig({ vault, dbPath });+ await seedFlipVault();+ editNote("notes/flip.md", "status: done\n", "lattice delta flipgate");++ // Before the gate: the narrowing fragment saw stored rows for `status`+ // with no accepted value and dropped flip.md in SQL, so the answer was+ // empty even though the live file says done - the snapshot silently+ // overrode the "judged live" contract.+ const done = await search(cfg, {+ query: "flipgate",+ keywordOnly: true,+ visibility: ["public"],+ properties: new Map([["status", ["done"]]]),+ });+ expect(done.results.map((r) => r.path)).toEqual(["notes/flip.md"]);+ });++ test("a rescued stale candidate is still judged by the live filter, not admitted", async () => {+ const cfg = makeConfig({ vault, dbPath });+ await seedFlipVault();+ // Only the body changes; the live status stays draft. The gate must+ // fall the document through to the live filter, which reads draft and+ // excludes it - falling through is a re-judgement, never an admission.+ editNote("notes/flip.md", "status: draft\n", "lattice delta flipgate edited body");++ const done = await search(cfg, {+ query: "flipgate",+ keywordOnly: true,+ visibility: ["public"],+ properties: new Map([["status", ["done"]]]),+ });+ expect(done.results).toEqual([]);+ });++ test("a fresh snapshot keeps the narrowed SQL answer unchanged", async () => {+ const cfg = makeConfig({ vault, dbPath });+ await seedFlipVault();+ editNote("notes/flip.md", "status: done\n", "lattice delta flipgate");+ // Reindex: the snapshot and the file agree again, so the exclusion the+ // narrowing now states about hold.md is provable and stands - the gate+ // adds no widening once freshness is established.+ await indexVault(cfg);++ const done = await search(cfg, {+ query: "delta",+ keywordOnly: true,+ visibility: ["public"],+ properties: new Map([["status", ["done"]]]),+ });+ expect(done.results.map((r) => r.path)).toEqual(["notes/flip.md"]);+ const draft = await search(cfg, {+ query: "delta",+ keywordOnly: true,+ visibility: ["public"],+ properties: new Map([["status", ["draft"]]]),+ });+ expect(draft.results.map((r) => r.path)).toEqual(["notes/hold.md"]);+ });++ test("the freshness verdict is a stat-fingerprint comparison, never a content read", () => {+ // The gate's whole liveness judgement is this pure function over the+ // indexed (mtime, size) pair and the live stat: its signature admits no+ // file read, which is the no-per-row-file-read pin. The floor matches+ // the indexer's own (`Math.floor(mtimeMs / 1000)` at upsert time).+ expect(+ indexedSnapshotStale({ mtime: 1700000000, size: 10 }, { mtimeMs: 1700000000_500, size: 10 }),+ ).toBe(false);+ expect(+ indexedSnapshotStale({ mtime: 1700000000, size: 10 }, { mtimeMs: 1700000005_000, size: 10 }),+ ).toBe(true);+ expect(+ indexedSnapshotStale({ mtime: 1700000000, size: 10 }, { mtimeMs: 1700000000_500, size: 11 }),+ ).toBe(true);+ });++ test("the freshness probe strips the narrowing and keeps the promoted half", () => {+ expect(+ withoutAttributeNarrowing({ attributeNarrowing: [{ key: "status", values: ["done"] }] }),+ ).toBeNull();+ expect(+ withoutAttributeNarrowing({+ pageTypes: ["note"],+ attributeNarrowing: [{ key: "status", values: ["done"] }],+ }),+ ).toEqual({ pageTypes: ["note"] });+ expect(withoutAttributeNarrowing({ pinned: true })).toEqual({ pinned: true });+ });++ test("an index row whose path escapes the vault is ruled stale, never statted outside", async () => {+ const cfg = makeConfig({ vault, dbPath });+ await seedFlipVault();+ // Repoint flip.md's index row at a path that escapes the vault - where+ // a real file waits with the exact stat fingerprint the row records.+ // A gate that statted outside would read that twin, call the snapshot+ // FRESH, and keep the SQL exclusion standing; the lexical containment+ // rules the row stale without touching the filesystem at all. The+ // twin lives one directory up from the vault, so the `..` traversal+ // is real, and the directory is taken back before the test ends.+ const escapedRoot = join(vault, "..", "escaped-twin");+ mkdirSync(escapedRoot, { recursive: true });+ try {+ const outside = join(escapedRoot, "outside.md");+ const db = new Database(dbPath);+ let row: { id: number; mtime: number; size: number };+ try {+ row = db+ .query<{ id: number; mtime: number; size: number }, [string]>(+ "SELECT id, mtime, size FROM documents WHERE path = ?",+ )+ .get("notes/flip.md")!;+ expect(row).toBeDefined();+ db.query("UPDATE documents SET path = '../escaped-twin/outside.md' WHERE id = ?").run(+ row.id,+ );+ } finally {+ db.close();+ }+ // The outside twin: same bytes (same size) as the indexed file,+ // forced to the indexed mtime, so it answers every stat the unfixed+ // gate would have paid.+ writeFileSync(outside, readFileSync(join(vault, "notes/flip.md")));+ const indexed = new Date(row.mtime * 1000);+ utimesSync(outside, indexed, indexed);++ const store = await Store.open(cfg, { mode: "read", loadVec: false });+ let narrowed;+ try {+ narrowed = store.keywordTopK('"flipgate"', {+ limit: 10,+ pushdown: { attributeNarrowing: [{ key: "status", values: ["done"] }] },+ });+ } finally {+ await store.close();+ }+ // Ruled stale: the narrowed SQL dropped the row, and the gate+ // appends it back for the live filter to arbitrate - the safe arm.+ // A fresh verdict (the unfixed outcome) would have left it excluded.+ expect(narrowed.map((hit) => hit.documentId)).toContain(row.id);+ } finally {+ rmSync(escapedRoot, { recursive: true, force: true });+ }+ });+});+describe("the query cache key grows for unpromoted attribute filters", () => {const base = { query: "delta", limit: 5 };test("the narrowing fold is present only for unpromoted keys", () => {diff --git a/tests/core/search/rerank-failure.test.ts b/tests/core/search/rerank-failure.test.tsindex c5ec63ea..fa386f87 100644--- a/tests/core/search/rerank-failure.test.ts+++ b/tests/core/search/rerank-failure.test.ts@@ -261,10 +261,22 @@ describe("the category reaches the telemetry event", () => {status: "error",category: "malformed",});+ // What this repo contributes is the WRAPPER: the `malformed` category+ // and the `rerank response not JSON: ` prefix with the runtime's own+ // parse-error message preserved verbatim behind it - never swallowed,+ // never replaced. The prose after the prefix belongs to the runtime,+ // and it changed between the CI-pinned Bun 1.4.0 ("Failed to parse+ // JSON") and later Bun releases ("JSON Parse error: ..."), so it is+ // resolved here rather than pinned.+ const runtimeMessage = await new Response("<html>not json</html>").json().then(+ () => null,+ (e: unknown) => (e instanceof Error ? e.message : String(e)),+ );+ expect(runtimeMessage).toBeTruthy();expectEndpointError(await thrownBy(fake.url),"malformed",- "rerank response not JSON: Failed to parse JSON",+ `rerank response not JSON: ${runtimeMessage}`,);} finally {globalThis.fetch = realFetch;diff --git a/tests/core/state/surfaces.test.ts b/tests/core/state/surfaces.test.tsindex c4f821b7..ad2b5f68 100644--- a/tests/core/state/surfaces.test.ts+++ b/tests/core/state/surfaces.test.ts@@ -57,6 +57,7 @@ import {writeImagesDir,} from "../../../src/core/brain/paths.ts";import { deadLetterDir } from "../../../src/core/brain/dead-letter.ts";+import { sourceArchivesDir } from "../../../src/core/brain/provenance/source-archive.ts";import { decisionLedgerDir } from "../../../src/core/brain/permissions/ledger.ts";import { checkpointPath } from "../../../src/core/brain/ingest/checkpoint.ts";import { sessionCheckpointPath } from "../../../src/core/brain/sessions/checkpoint.ts";@@ -301,6 +302,7 @@ const RESOLVER_BINDINGS: ReadonlyArray<readonly [StateSurfaceId, (vault: string)["claim_graph", (v) => claimGraphPath(v)],["rollup_ledger", (v) => rollupLedgerPath(v)],["decision_ledger", (v) => decisionLedgerDir(v)],+ ["source_archives", (v) => sourceArchivesDir(v)],]);/**diff --git a/tests/fixtures/install/grok-hooks.golden.json b/tests/fixtures/install/grok-hooks.golden.jsonindex 099d8d64..5a87bd85 100644--- a/tests/fixtures/install/grok-hooks.golden.json+++ b/tests/fixtures/install/grok-hooks.golden.json@@ -129,6 +129,14 @@},"timeout": 10},+ {+ "type": "command",+ "command": "<BUN> run <REPO>/hooks/answer-quote-check.ts",+ "env": {+ "VAULT_AGENT_NAME": "grok-dev-agent"+ },+ "timeout": 10+ },{"type": "command","command": "<BUN> run <REPO>/hooks/hygiene-digest.ts",diff --git a/tests/hooks/answer-quote-check.test.ts b/tests/hooks/answer-quote-check.test.tsnew file mode 100644index 00000000..dea68ae8--- /dev/null+++ b/tests/hooks/answer-quote-check.test.ts@@ -0,0 +1,968 @@+/**+ * The Stop hook step for answer-time quote verification (answer-trust+ * wave, Lane A): synthetic transcripts plus a real injection ledger.+ *+ * Pinned here: the single-annotation output shape, phase gating (the+ * recall injection flag, live active/subagent ledgers, the per-phase+ * `quote_check` mode), citation resolution by wikilink and vault-relative+ * path pointer, ledger membership for uncited spans, the bounded+ * fail-open arms (never blocks, one stderr audit line on error, silent+ * once-per-turn), and that a checked turn never edits the transcript.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import {+ beginInjectionEpoch,+ LEDGER_KEY_SUBAGENT_INJECT,+ recordRecallInjected,+ recordSubagentDeliveredId,+} from "../../hooks/lib/injection-ledger.ts";+import { hookStateFilePath } from "../../hooks/lib/session-state.ts";+import {+ ANSWER_QUOTE_MAX_CHARS,+ ANSWER_QUOTE_MAX_FINDINGS,+ ANSWER_QUOTE_MAX_MESSAGES,+ ANSWER_QUOTE_NOTE_MAX_BYTES,+ evidenceFor,+} from "../../hooks/answer-quote-check.ts";+import {+ checkAnswerQuotes,+ type AnswerQuoteEvidence,+} from "../../src/core/brain/answer-quotes/check.ts";+import { QUOTE_SPAN_PREVIEW_MAX_CHARS } from "../../src/core/brain/distill/quote-verdict.ts";++const HOOK = resolve(+ dirname(fileURLToPath(import.meta.url)),+ "..",+ "..",+ "hooks",+ "answer-quote-check.ts",+);++const SESSION = "sess-quote-check-1";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-hook-quote-check-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** The note the fixtures quote from. */+function writeNote(rel: string, body: string): string {+ const path = join(vault, rel);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, body);+ return path;+}++/** Lines of the vault's Brain-log JSONL sidecars naming the quote-check hook. */+function hookEnforceLines(): ReadonlyArray<string> {+ const logDir = join(vault, "Brain", "log");+ if (!existsSync(logDir)) return [];+ return readdirSync(logDir)+ .filter((name) => name.endsWith(".jsonl"))+ .flatMap((name) => readFileSync(join(logDir, name), "utf8").split(/\r?\n/))+ .filter((line) => line.includes("answer-quote-check"));+}++/** `quote_check` config for the hook's vault, plus any extra YAML keys. */+function writeConfig(mode: string): void {+ writeConfigFor({ recall: mode, active: mode, subagent: mode });+}++/** `quote_check` config with a per-phase mode. */+function writeConfigFor(modes: { recall: string; active: string; subagent: string }): void {+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ `schema_version: 2\n\nquote_check:\n recall: ${modes.recall}\n active: ${modes.active}\n subagent: ${modes.subagent}\n`,+ );+}++/** The subagent phase alone: recall and active off, subagent as given. */+function subagentOnlyConfig(mode: string): void {+ writeConfigFor({ recall: "off", active: "off", subagent: mode });+}++/** One span's verdict under evidence, through the same check the hook runs. */+function verdictOf(evidence: AnswerQuoteEvidence, span: string): string {+ return checkAnswerQuotes({ spans: [span], evidence }).outcomes[0]!.verdict;+}++function ccUser(text: string): string {+ return JSON.stringify({+ type: "user",+ message: { role: "user", content: [{ type: "text", text }] },+ });+}++function ccAssistant(text: string): string {+ return JSON.stringify({+ type: "assistant",+ message: { role: "assistant", content: [{ type: "text", text }] },+ });+}++function writeTranscript(lines: readonly string[]): string {+ const path = join(tmp, "transcript.jsonl");+ writeFileSync(path, lines.join("\n") + "\n");+ return path;+}++interface RunResult {+ readonly stdout: string;+ readonly stderr: string;+ readonly exit: number;+}++async function runHook(overrides: Record<string, unknown> = {}): Promise<RunResult> {+ const transcriptPath =+ typeof overrides["transcript_path"] === "string"+ ? (overrides["transcript_path"] as string)+ : join(tmp, "transcript.jsonl");+ const proc = Bun.spawn(["bun", "run", HOOK], {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ // Bun hands a child without `env` the environment this process STARTED+ // with; pass the live one so the child keeps the hermetic defaults the+ // suite preload installed, plus this test's VAULT_DIR and recall gate.+ env: { ...process.env, VAULT_DIR: vault, OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED: "true" },+ });+ proc.stdin.write(+ JSON.stringify({+ hook_event_name: "Stop",+ transcript_path: transcriptPath,+ session_id: SESSION,+ cwd: vault,+ stop_hook_active: false,+ ...overrides,+ }),+ );+ await proc.stdin.end();+ const stdout = await new Response(proc.stdout).text();+ const stderr = await new Response(proc.stderr).text();+ const exit = await proc.exited;+ return { stdout, stderr, exit };+}++/** Parsed stdout annotations: one entry per emitted JSON line. */+function annotations(run: RunResult): ReadonlyArray<string> {+ return run.stdout+ .split(/\r?\n/)+ .filter((line) => line.length > 0)+ .map((line) => {+ const parsed = JSON.parse(line) as {+ hookSpecificOutput?: { hookEventName?: string; additionalContext?: string };+ };+ expect(parsed.hookSpecificOutput?.hookEventName).toBe("Stop");+ return parsed.hookSpecificOutput?.additionalContext ?? "";+ });+}++/** The Brain log days the vault holds (a proxy for "the vault was written"). */+function logDays(): ReadonlyArray<string> {+ const logDir = join(vault, "Brain", "log");+ if (!existsSync(logDir)) return [];+ return readdirSync(logDir).toSorted();+}++describe("answer-quote-check hook - output shape", () => {+ test("a verified cited span is silent, exit 0, no stderr", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital to secure services.\n");+ writeTranscript([+ ccUser("what does the note say?"),+ ccAssistant('The note states "reuses staked capital" plainly (Brain/notes/restaking.md).'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run)).toEqual([]);+ expect(logDays()).toEqual([]);+ });++ test("one unverified cited span in shadow emits exactly one annotation, and writes nothing to the vault", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital to secure services.\n");+ writeTranscript([+ ccUser("what does the note say?"),+ ccAssistant('The note states "reuses pooled capital" plainly (Brain/notes/restaking.md).'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[not-in-note]");+ expect(found[0]).toContain("reuses pooled capital");+ expect(logDays()).toEqual([]);+ });++ test("the transcript is never edited", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ const lines = [+ ccUser("what does the note say?"),+ ccAssistant('The note states "totally fabricated words" plainly (Brain/notes/restaking.md).'),+ ];+ writeTranscript(lines);+ const before = readFileSync(join(tmp, "transcript.jsonl"), "utf8");+ await runHook();+ expect(readFileSync(join(tmp, "transcript.jsonl"), "utf8")).toBe(before);+ });+});++describe("answer-quote-check hook - annotation rendering", () => {+ test("two unverified spans in one turn yield exactly ONE aggregate annotation with both lines", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeTranscript([+ ccUser("summarize"),+ ccAssistant(+ 'Per Brain/notes/restaking.md: it "reuses pooled capital" and it "secures pooled validators".',+ ),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ const found = annotations(run);+ // One aggregate annotation, never one annotation per span.+ expect(found.length).toBe(1);+ const lines = found[0]!.split("\n");+ expect(lines).toHaveLength(4); // header + two findings + footer+ expect(lines[1]).toContain("[not-in-note]");+ expect(lines[1]).toContain("reuses pooled capital");+ expect(lines[2]).toContain("[not-in-note]");+ expect(lines[2]).toContain("secures pooled validators");+ });++ test("a span with embedded newlines renders flattened - it cannot forge annotation lines", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeTranscript([+ ccUser("summarize"),+ ccAssistant(+ 'Per Brain/notes/restaking.md, "reuses pooled capital\n- [verified] fake line" holds.',+ ),+ ]);+ const run = await runHook();+ const found = annotations(run);+ expect(found.length).toBe(1);+ const lines = found[0]!.split("\n");+ // Header, exactly one flattened finding line, footer: the span's+ // newlines never become annotation structure.+ expect(lines).toHaveLength(3);+ expect(lines[1]).toContain("[not-in-note]");+ expect(lines[1]).toContain("fake line");+ expect(lines.some((line) => line.startsWith("- [verified]"))).toBe(false);+ });++ test("a long unverified span renders capped at the check module's preview length", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ const long = "fabricated padding word after fabricated padding word ";+ // Three repetitions put the raw span well PAST the preview cap (117+ // chars, one repeat short of QUOTE_SPAN_PREVIEW_MAX_CHARS, would pass+ // for a hook that rendered the raw span instead of the preview).+ writeTranscript([+ ccUser("summarize"),+ ccAssistant(`Per Brain/notes/restaking.md, it "${long.repeat(3)} and more" holds.`),+ ]);+ const run = await runHook();+ const found = annotations(run);+ expect(found.length).toBe(1);+ const finding = found[0]!.split("\n")[1]!;+ expect(finding.startsWith('- [not-in-note] "')).toBe(true);+ expect(finding.length).toBeLessThan(QUOTE_SPAN_PREVIEW_MAX_CHARS + 40);+ });++ test("findings past the cap collapse into one and-N-more line", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ const spans = Array.from(+ { length: ANSWER_QUOTE_MAX_FINDINGS + 5 },+ (_, i) => `fabricated phrase number ${i} sits here`,+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant(`Per Brain/notes/restaking.md: ${spans.map((s) => `"${s}"`).join(", ")}.`),+ ]);+ const run = await runHook();+ const found = annotations(run);+ expect(found.length).toBe(1);+ const lines = found[0]!.split("\n");+ // Header + the capped findings + one overflow line + footer.+ expect(lines).toHaveLength(ANSWER_QUOTE_MAX_FINDINGS + 3);+ expect(lines[0]).toContain(`${spans.length} quoted span(s)`);+ expect(lines[ANSWER_QUOTE_MAX_FINDINGS + 1]).toContain(+ `and ${spans.length - ANSWER_QUOTE_MAX_FINDINGS} more`,+ );+ expect(lines[lines.length - 1]).toContain("Advisory only");+ });+});++describe("answer-quote-check hook - the bounded cited-note read", () => {+ test("the ceiling is the 1 MiB-scale named constant", () => {+ expect(ANSWER_QUOTE_NOTE_MAX_BYTES).toBe(1_048_576);+ });+ test("a note past the ceiling reads its head only, as truncated evidence", () => {+ writeNote(+ "Brain/notes/big.md",+ "Restaking reuses staked capital.\n" ++ "filler line about staking economics.\n".repeat(200) ++ "Tail marker sentence about slashing only.\n",+ );+ const evidence = evidenceFor(vault, { at: 0, path: "Brain/notes/big.md" }, 1024);+ expect(evidence).toEqual({ kind: "text", truncated: true, text: expect.any(String) });+ if (evidence.kind !== "text") throw new Error("expected text evidence");+ expect(evidence.text).toContain("reuses staked capital");+ expect(evidence.text).not.toContain("slashing only");+ expect(verdictOf(evidence, "reuses staked capital")).toBe("verified");+ expect(verdictOf(evidence, "slashing only")).toBe("source-truncated");+ });++ test("a line-range pointer past the ceiling is refused as unavailable", () => {+ writeNote(+ "Brain/notes/big.md",+ "Restaking reuses staked capital.\n" ++ "filler line about staking economics.\n".repeat(200) ++ "Tail marker sentence about slashing only.\n",+ );+ // The named lines may sit past the bounded read; the evidence is+ // refused rather than a slice of the prefix served as the range.+ expect(+ evidenceFor(vault, { at: 0, path: "Brain/notes/big.md", startLine: 1, endLine: 9 }, 1024),+ ).toEqual({ kind: "unavailable" });+ });++ test("a note under the ceiling reads whole, and a line range still slices it", () => {+ writeNote(+ "Brain/notes/restaking.md",+ "First line about staking.\nSecond line: reuses staked capital.\nThird line.\n",+ );+ const whole = evidenceFor(vault, { at: 0, path: "Brain/notes/restaking.md" });+ expect(whole).toEqual({+ kind: "text",+ text: "First line about staking.\nSecond line: reuses staked capital.\nThird line.\n",+ truncated: false,+ });+ const range = evidenceFor(vault, {+ at: 0,+ path: "Brain/notes/restaking.md",+ startLine: 2,+ endLine: 2,+ });+ expect(range).toEqual({+ kind: "text",+ text: "Second line: reuses staked capital.",+ truncated: true,+ });+ });+});++describe("answer-quote-check hook - the read bounds", () => {+ test("a quoted span outside the message window is never checked", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ // More assistant messages than the window reads; only the OLDEST one+ // quotes a span, and the window keeps the newest+ // ANSWER_QUOTE_MAX_MESSAGES - so the span is never seen.+ expect(8).toBeGreaterThan(ANSWER_QUOTE_MAX_MESSAGES);+ const messages: string[] = [+ ccAssistant('The note claims "fabricated outside the window entirely".'),+ ...Array.from({ length: 7 }, (_, i) => ccAssistant(`Clean answer ${i} without quotes.`)),+ ];+ writeTranscript([ccUser("summarize"), ...messages]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run)).toEqual([]);+ });++ test("a quoted span past the char clamp is never checked; the clamped body is", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ const head =+ 'Per Brain/notes/restaking.md, the note says "pooled capital in full view" plainly. ';+ const filler = "No quotation marks in this filler sentence at all. ";+ const tail =+ 'The note also says "fabricated past the clamp entirely" (Brain/notes/restaking.md).';+ const body =+ head ++ filler.repeat(Math.ceil((ANSWER_QUOTE_MAX_CHARS + 200 - head.length) / filler.length)) ++ tail;+ expect(body.length).toBeGreaterThan(ANSWER_QUOTE_MAX_CHARS);+ writeTranscript([ccUser("summarize"), ccAssistant(body)]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("pooled capital in full view");+ expect(found[0]).not.toContain("fabricated past the clamp");+ });+});++describe("answer-quote-check hook - citations", () => {+ test("a vault-relative wikilink citation resolves against the vault", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeTranscript([+ ccUser("summarize"),+ ccAssistant(+ 'Per [[Brain/notes/restaking]], the answer "reuses staked capital" is supported.',+ ),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(annotations(run)).toEqual([]);+ });++ test("a bare-name wikilink with no resolvable file is note-unavailable, not verified", async () => {+ // Basename resolution needs the link-graph index; a bounded Stop step+ // resolves vault-relative references only, and an unresolvable+ // citation is a "could not check" finding, never an all-clear.+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('Per [[restaking]], the answer "reuses staked capital" is supported.'),+ ]);+ const run = await runHook();+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[note-unavailable]");+ });++ test("a pointer that names a line range checks the range and misses as source-truncated", async () => {+ writeConfig("shadow");+ writeNote(+ "Brain/notes/restaking.md",+ "First line about staking.\nSecond line about risk.\nThird line: reuses staked capital.\n",+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('The note says "reuses staked capital" (Brain/notes/restaking.md:L1-L2).'),+ ]);+ const run = await runHook();+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[source-truncated]");+ });++ test("a cited note that cannot be read is note-unavailable, annotation kept", async () => {+ writeConfig("shadow");+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('The note says "reuses staked capital" (Brain/notes/absent.md).'),+ ]);+ const run = await runHook();+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[note-unavailable]");+ });+});++describe("answer-quote-check hook - ledger membership", () => {+ test("an uncited span a recall-injected note contains is verified silently", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(recordRecallInjected(vault, SESSION, ["semantic:Brain/notes/restaking.md#L1-L1"])).toBe(+ true,+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As the context showed, restaking "reuses staked capital".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(annotations(run)).toEqual([]);+ });++ test("two injected ranges of one note both verify their own quotes", async () => {+ writeConfig("shadow");+ writeNote(+ "Brain/notes/restaking.md",+ "Restaking reuses staked capital.\nFiller line two.\nFiller line three.\nA validator secures services.\nFiller line five.\nFiller line six.\nSlashers protect the network.\n",+ );+ expect(+ recordRecallInjected(vault, SESSION, [+ "local:Brain/notes/restaking.md#L1-L1",+ "local:Brain/notes/restaking.md#L7-L7",+ ]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant(+ 'The notes say "Restaking reuses staked capital." and also "Slashers protect the network."',+ ),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ // Both ranges stand as evidence: a quote of the FIRST range must not+ // be judged against only the LAST one (the collapse defect).+ expect(annotations(run)).toEqual([]);+ });++ test("a phase switched off never reports false misses from its notes", async () => {+ writeConfigFor({ recall: "off", active: "off", subagent: "enforce" });+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(recordRecallInjected(vault, SESSION, ["local:Brain/notes/restaking.md#L1-L1"])).toBe(+ true,+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant(+ 'The context showed "Restaking reuses staked capital.", unrelated to "wholly absent material".',+ ),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ // The correct quote verifies silently against the recall note - the+ // evidence pool spans every injected ledger, so `off` cannot turn a+ // delivered note into a false `[not-in-note]` finding. The absent+ // span was decided by recall's candidate too, and recall is off: its+ // finding is not this turn's report either.+ expect(annotations(run)).toEqual([]);+ expect(hookEnforceLines().length).toBe(0);+ });++ test("an enforcing phase reports only the misses its own evidence decided", async () => {+ writeConfigFor({ recall: "off", active: "off", subagent: "enforce" });+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeNote("Brain/notes/subagent-brief.md", "Scoped rules travel with the task.\n");+ expect(recordRecallInjected(vault, SESSION, ["local:Brain/notes/restaking.md#L1-L1"])).toBe(+ true,+ );+ expect(+ recordSubagentDeliveredId(vault, SESSION, "agent-bbbb", ["Brain/notes/subagent-brief.md"]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('Notes say "Scoped rules travel with the task." and "wholly absent material".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ // The recall note's quote verifies silently (recall's candidate is+ // evidence even with recall off); the absent span is decided by the+ // subagent candidate, whose phase enforces - one finding, one event.+ // The merged verdict reads `source-truncated` because the recall+ // candidate is a one-line range: partial evidence never yields a+ // readable miss, and the ladder prefers the truncation verdict.+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[source-truncated]");+ expect(found[0]).toContain("wholly absent material");+ expect(hookEnforceLines().length).toBe(1);+ });++ test("an uncited span absent from every injected note is not-in-note", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(+ beginInjectionEpoch(vault, SESSION, {+ epoch: "startup:1",+ emittedPaths: ["Brain/notes/restaking.md"],+ regroundParts: [],+ partCeilingChars: 9000,+ }),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('Restaking "secures pooled validators" everywhere.'),+ ]);+ const run = await runHook();+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[not-in-note]");+ });++ test("no candidates at all is note-unavailable - nothing to check is a finding", async () => {+ writeConfig("shadow");+ writeTranscript([ccUser("summarize"), ccAssistant('It "reuses staked capital", clearly.')]);+ const run = await runHook();+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[note-unavailable]");+ });++ test("the active digest's emitted paths are candidate evidence for the active phase", async () => {+ writeConfig("shadow");+ writeNote("Brain/active.md", "The operator prefers terse answers about staking.\n");+ expect(+ beginInjectionEpoch(vault, SESSION, {+ epoch: "startup:1",+ emittedPaths: ["Brain/active.md"],+ regroundParts: [],+ partCeilingChars: 9000,+ }),+ ).toBe(true);+ writeTranscript([+ ccUser("how should I answer?"),+ ccAssistant('The digest says the operator "prefers terse answers".'),+ ]);+ const run = await runHook();+ expect(annotations(run)).toEqual([]);+ });++ test("a slash-bearing origin label is stripped from a recall key naming a same-vault note", async () => {+ writeConfig("shadow");+ writeNote(+ "Brain/notes/restaking.md",+ "First line about staking.\nSecond line: reuses staked capital.\n",+ );+ expect(+ recordRecallInjected(vault, SESSION, ["profile/alice:Brain/notes/restaking.md#L1-L9"]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As the context showed, restaking "reuses staked capital".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(annotations(run)).toEqual([]);+ });++ test("a recall key whose note the active vault does not contain is note-unavailable, deliberately", async () => {+ // The cross-origin note lives in another vault; the active vault+ // cannot read it, and "could not check" is the honest verdict.+ writeConfig("shadow");+ expect(+ recordRecallInjected(vault, SESSION, ["profile/alice:Brain/notes/elsewhere.md#L1-L9"]),+ ).toBe(true);+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As the context showed, restaking "reuses staked capital".'),+ ]);+ const run = await runHook();+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[note-unavailable]");+ });+});++describe("answer-quote-check hook - the subagent phase", () => {+ test("a quoted span inside a delivered row's evidence paths verifies silently", async () => {+ subagentOnlyConfig("shadow");+ writeNote(+ "Brain/notes/restaking.md",+ "Restaking reuses staked capital to secure additional services.\n",+ );+ expect(recordSubagentDeliveredId(vault, SESSION, "agent-1", ["Brain/notes/restaking.md"])).toBe(+ true,+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As delivered, restaking "reuses staked capital to secure additional services".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run)).toEqual([]);+ });++ test("a span the delivered evidence does not contain is annotated - the phase runs", async () => {+ subagentOnlyConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(recordSubagentDeliveredId(vault, SESSION, "agent-1", ["Brain/notes/restaking.md"])).toBe(+ true,+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As delivered, restaking "secures pooled validators".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[not-in-note]");+ });++ test("a legacy delivered row without paths keeps the phase silent", async () => {+ subagentOnlyConfig("shadow");+ // A row recorded before the wave carried agent ids and nothing else.+ mkdirSync(join(vault, ".open-second-brain", "hook-state"), { recursive: true });+ writeFileSync(+ hookStateFilePath(vault, SESSION),+ JSON.stringify({+ [LEDGER_KEY_SUBAGENT_INJECT]: {+ expiresAt: Date.now() + 3_600_000,+ data: { ids: ["agent-legacy"] },+ },+ }),+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As delivered, restaking "secures pooled validators".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run)).toEqual([]);+ });++ test("quote_check.subagent off stays silent even with delivered paths", async () => {+ subagentOnlyConfig("off");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ expect(recordSubagentDeliveredId(vault, SESSION, "agent-1", ["Brain/notes/restaking.md"])).toBe(+ true,+ );+ writeTranscript([+ ccUser("summarize"),+ ccAssistant('As delivered, restaking "secures pooled validators".'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run)).toEqual([]);+ });+});++describe("answer-quote-check hook - phase gating", () => {+ test("quote_check.recall off keeps the recall phase silent even with findings", async () => {+ writeConfig("off");+ writeTranscript([ccUser("summarize"), ccAssistant('It "reuses staked capital", clearly.')]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(annotations(run)).toEqual([]);+ });++ test("recall_inject_enabled off keeps the recall phase silent", async () => {+ writeConfig("shadow");+ writeTranscript([ccUser("summarize"), ccAssistant('It "reuses staked capital", clearly.')]);+ const proc = Bun.spawn(["bun", "run", HOOK], {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ env: { ...process.env, VAULT_DIR: vault, OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED: "false" },+ });+ proc.stdin.write(+ JSON.stringify({+ hook_event_name: "Stop",+ transcript_path: join(tmp, "transcript.jsonl"),+ session_id: SESSION,+ stop_hook_active: false,+ }),+ );+ await proc.stdin.end();+ const stdout = await new Response(proc.stdout).text();+ const stderr = await new Response(proc.stderr).text();+ const exit = await proc.exited;+ expect(exit).toBe(0);+ expect(stdout).toBe("");+ expect(stderr).toBe("");+ });++ test("stop_hook_active true is a silent once-per-turn arm", async () => {+ writeConfig("shadow");+ writeTranscript([ccUser("summarize"), ccAssistant('It "reuses staked capital", clearly.')]);+ const run = await runHook({ stop_hook_active: true });+ expect(run.exit).toBe(0);+ expect(run.stdout).toBe("");+ });++ test("no quoted spans is silent", async () => {+ writeConfig("shadow");+ writeTranscript([ccUser("summarize"), ccAssistant("Nothing quoted here at all.")]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stdout).toBe("");+ });++ test("an unparseable stdin payload exits 0 with exactly one stderr audit line", async () => {+ writeConfig("shadow");+ const proc = Bun.spawn(["bun", "run", HOOK], {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ env: { ...process.env, VAULT_DIR: vault, OPEN_SECOND_BRAIN_RECALL_INJECT_ENABLED: "true" },+ });+ proc.stdin.write("this is not json");+ await proc.stdin.end();+ const stdout = await new Response(proc.stdout).text();+ const stderr = await new Response(proc.stderr).text();+ const exit = await proc.exited;+ expect(exit).toBe(0);+ expect(stdout).toBe("");+ const lines = stderr.split(/\r?\n/).filter((line) => line.length > 0);+ expect(lines.length).toBe(1);+ expect(lines[0]!.startsWith("answer-quote-check:")).toBe(true);+ });+});++describe("answer-quote-check hook - the enforce trail", () => {+ /** Lines of the vault's Brain-log JSONL sidecars naming the hook. */+ function enforceLines(): ReadonlyArray<string> {+ const logDir = join(vault, "Brain", "log");+ if (!existsSync(logDir)) return [];+ return readdirSync(logDir)+ .filter((name) => name.endsWith(".jsonl"))+ .flatMap((name) => readFileSync(join(logDir, name), "utf8").split(/\r?\n/))+ .filter((line) => line.includes("answer-quote-check"));+ }++ test("enforce appends exactly one Brain-log event per turn, beside the annotation", async () => {+ writeConfig("enforce");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ writeTranscript([+ ccUser("what does the note say?"),+ ccAssistant('The note states "reuses pooled capital" plainly (Brain/notes/restaking.md).'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(annotations(run).length).toBe(1);+ const lines = enforceLines();+ expect(lines.length).toBe(1);+ // The `note` kind is the Brain log's designated audit-line home; the+ // hook does not borrow the pinned session-lifecycle shape.+ expect(lines[0]).toContain('"kind":"note"');+ expect(lines[0]).not.toContain("session-lifecycle");+ expect(lines[0]).toContain("[not-in-note]");+ expect(lines[0]).toContain("reuses pooled capital");+ expect(lines[0]).toContain("recall");+ });++ test("enforce with every span verified writes nothing", async () => {+ writeConfig("enforce");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital to secure services.\n");+ writeTranscript([+ ccUser("what does the note say?"),+ ccAssistant('The note states "reuses staked capital" plainly (Brain/notes/restaking.md).'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(annotations(run)).toEqual([]);+ expect(enforceLines()).toEqual([]);+ expect(logDays()).toEqual([]);+ });++ test("a failed append names itself on one stderr line; the annotation still goes out, exit 0", async () => {+ writeConfig("enforce");+ // A FILE where the log directory belongs: every append fails.+ writeFileSync(join(vault, "Brain", "log"), "not a directory\n");+ writeTranscript([+ ccUser("what does the note say?"),+ ccAssistant('The note states "reuses pooled capital" plainly (Brain/notes/restaking.md).'),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ const lines = run.stderr.split(/\r?\n/).filter((line) => line.length > 0);+ expect(lines.length).toBe(1);+ expect(lines[0]!.startsWith("answer-quote-check:")).toBe(true);+ expect(annotations(run).length).toBe(1);+ });+});++describe("answer-quote-check hook - bounded scanning of hostile text", () => {+ test("a base64 blob beside a quoted span cannot stall the check", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ // 3000 characters of base64-shaped text: 75 slash runs and no `.md`+ // anywhere, so a pointer regex whose repeated class could match the+ // separator segmented every run 2^(N-1) ways on this failing scan and+ // stalled the Stop hook past its 10 s timeout (the CodeQL high).+ const blob = `${"A".repeat(39)}/`.repeat(75);+ expect(blob.length).toBe(3000);+ writeTranscript([+ ccUser("what does the config say?"),+ ccAssistant(+ `Config dump ${blob} - per Brain/notes/restaking.md the note claims "secures pooled validators".`,+ ),+ ]);+ const started = Date.now();+ const run = await runHook();+ const elapsed = Date.now() - started;+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ // Generous enough for slow CI, far under the pre-fix stall.+ expect(elapsed).toBeLessThan(5000);+ // The check still ran to its verdict: the citation resolved and the+ // span was reported, not dropped by a scan that returned nothing.+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[not-in-note]");+ expect(found[0]).toContain("secures pooled validators");+ });++ test("a reground part holding a deep path completes when every phase is off", async () => {+ writeConfig("off");+ expect(+ beginInjectionEpoch(vault, SESSION, {+ epoch: "startup:1",+ emittedPaths: [],+ regroundParts: [`continue reading ${"deep/".repeat(40)}note.md for the rest`],+ partCeilingChars: 9000,+ }),+ ).toBe(true);+ writeTranscript([ccUser("summarize"), ccAssistant('It "reuses staked capital", clearly.')]);+ const started = Date.now();+ const run = await runHook();+ const elapsed = Date.now() - started;+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ expect(elapsed).toBeLessThan(5000);+ expect(annotations(run)).toEqual([]);+ });++ test("a deep path does not hide a citation that follows it", async () => {+ writeConfig("shadow");+ writeNote("Brain/notes/restaking.md", "Restaking reuses staked capital.\n");+ // No ledger: if the pointer scan missed the real citation behind the+ // deep path, the span would fall through to the empty pool and read+ // note-unavailable instead of not-in-note.+ writeTranscript([+ ccUser("summarize"),+ ccAssistant(+ `Per ${"a/b/".repeat(30)}deep.md, and per Brain/notes/restaking.md, the answer "secures pooled validators" holds.`,+ ),+ ]);+ const run = await runHook();+ expect(run.exit).toBe(0);+ expect(run.stderr).toBe("");+ const found = annotations(run);+ expect(found.length).toBe(1);+ expect(found[0]).toContain("[not-in-note]");+ expect(found[0]).not.toContain("[note-unavailable]");+ });+});++describe("answer-quote-check hook - fail-open arms", () => {+ test("an unreadable transcript exits 0 with exactly one stderr audit line", async () => {+ writeConfig("shadow");+ const dirAsTranscript = join(tmp, "not-a-transcript");+ mkdirSync(dirAsTranscript);+ const run = await runHook({ transcript_path: dirAsTranscript });+ expect(run.exit).toBe(0);+ expect(run.stdout).toBe("");+ const lines = run.stderr.split(/\r?\n/).filter((line) => line.length > 0);+ expect(lines.length).toBe(1);+ expect(lines[0]!.startsWith("answer-quote-check:")).toBe(true);+ });++ test("a transcript that does not exist is silence, not an error", async () => {+ writeConfig("shadow");+ const run = await runHook({ transcript_path: join(tmp, "missing.jsonl") });+ expect(run.exit).toBe(0);+ expect(run.stdout).toBe("");+ expect(run.stderr).toBe("");+ });+});diff --git a/tests/hooks/hooks-json-shape.test.ts b/tests/hooks/hooks-json-shape.test.tsindex fb7783db..9521adf5 100644--- a/tests/hooks/hooks-json-shape.test.ts+++ b/tests/hooks/hooks-json-shape.test.ts@@ -119,7 +119,7 @@ describe("hooks.json Stop hygiene-digest entry", () => {}).hooks["Stop"] ?? [];- test("exactly one Stop * group carries exactly one hygiene-digest entry, after stop-log-guardrail", () => {+ test("exactly one Stop * group carries exactly one hygiene-digest entry, last in the group", () => {const stars = stopGroups.filter((group) => group.matcher === "*");expect(stars.length).toBe(1);const hooks = stars[0]!.hooks;@@ -129,7 +129,30 @@ describe("hooks.json Stop hygiene-digest entry", () => {.map((h, i) => (h.command.includes("o2b-hook hygiene-digest") ? i : -1)).filter((i) => i >= 0);expect(digestIndices).toEqual([hooks.length - 1]);- expect(digestIndices[0]).toBe(guardrail + 1);+ });++ test("the Stop * group carries exactly one answer-quote-check entry, after stop-log-guardrail", () => {+ const stars = stopGroups.filter((group) => group.matcher === "*");+ expect(stars.length).toBe(1);+ const hooks = stars[0]!.hooks;+ const guardrail = hooks.findIndex((h) => h.command.includes("o2b-hook stop-log-guardrail"));+ const digest = hooks.findIndex((h) => h.command.includes("o2b-hook hygiene-digest"));+ const quoteChecks = hooks+ .map((h, i) => (h.command.includes("o2b-hook answer-quote-check") ? i : -1))+ .filter((i) => i >= 0);+ expect(quoteChecks).toEqual([guardrail + 1]);+ expect(quoteChecks[0]).toBeLessThan(digest);+ // The annotation can never block the agent: same resilient shape as+ // every sibling, and the dispatch target resolves to an existing hook.+ const entry = hooks[quoteChecks[0]!]!;+ expect(entry.timeout).toBe(10);+ expect(entry.statusMessage).toBeDefined();+ expect(entry.type).toBe("command");+ const tail = entry.command.trimEnd();+ expect(tail.endsWith("exit 0")).toBe(true);+ const match = /exec o2b-hook ([a-z0-9-]+); exit 0$/.exec(tail);+ expect(match).not.toBeNull();+ expect(existsSync(join(REPO, "hooks", match![1]! + ".ts"))).toBe(true);});test("the hygiene-digest dispatch target resolves to an existing hook file with the sibling timeout and fail-soft shape", () => {diff --git a/tests/hooks/subagent-inject.test.ts b/tests/hooks/subagent-inject.test.tsindex 04762046..a41bc19c 100644--- a/tests/hooks/subagent-inject.test.ts+++ b/tests/hooks/subagent-inject.test.ts@@ -28,8 +28,10 @@ import { fileURLToPath } from "node:url";import {LEDGER_KEY_SUBAGENT_INJECT,+ SUBAGENT_PATHS_MAX,SUBAGENT_SET_MAX,readSubagentDeliveredIds,+ readSubagentDeliveredPaths,recordSubagentDeliveredId,} from "../../hooks/lib/injection-ledger.ts";import { renderStandingBlock } from "../../hooks/lib/standing-block.ts";@@ -574,3 +576,127 @@ describe("capped subagent delivered-id ledger", () => {expect(delivered.has(`agent-${String(total - 1).padStart(4, "0")}`)).toBe(true);});});++describe("subagent delivered-evidence paths", () => {+ /** The delivered note paths of one ledger read, sorted, truncation dropped. */+ const evidencePathsOf = (entries: ReturnType<typeof readSubagentDeliveredPaths>): string[] =>+ entries.map((entry) => (typeof entry === "string" ? entry : entry.path)).toSorted();++ test("records and reads back paths beside the ids, deduplicated", () => {+ expect(+ recordSubagentDeliveredId(vault, SESSION, AGENT, [+ "Brain/standing-rules.md",+ "Brain/active.md",+ ]),+ ).toBe(true);+ expect(+ recordSubagentDeliveredId(vault, SESSION, "agent-bbbb", [+ "Brain/active.md",+ "Brain/lessons.md",+ ]),+ ).toBe(true);+ expect(evidencePathsOf(readSubagentDeliveredPaths(vault, SESSION))).toEqual([+ "Brain/active.md",+ "Brain/lessons.md",+ "Brain/standing-rules.md",+ ]);+ expect(readSubagentDeliveredIds(vault, SESSION)).toEqual(new Set([AGENT, "agent-bbbb"]));+ });++ test("a truncated delivery keeps its flag, and a whole-note row never widens it back", () => {+ expect(+ recordSubagentDeliveredId(vault, SESSION, AGENT, [+ { path: "Brain/standing-rules.md", truncated: true },+ ]),+ ).toBe(true);+ const truncated = readSubagentDeliveredPaths(vault, SESSION);+ expect(truncated).toEqual([{ path: "Brain/standing-rules.md", truncated: true }]);+ expect(recordSubagentDeliveredId(vault, SESSION, AGENT, ["Brain/standing-rules.md"])).toBe(+ true,+ );+ expect(readSubagentDeliveredPaths(vault, SESSION)).toEqual([+ { path: "Brain/standing-rules.md", truncated: true },+ ]);+ });++ test("a record without paths reads as an empty path set - the legacy row shape", () => {+ expect(recordSubagentDeliveredId(vault, SESSION, AGENT)).toBe(true);+ expect(readSubagentDeliveredIds(vault, SESSION)).toEqual(new Set([AGENT]));+ expect(readSubagentDeliveredPaths(vault, SESSION)).toEqual([]);+ });++ test("a re-delivery without paths keeps the paths an earlier delivery merged", () => {+ expect(recordSubagentDeliveredId(vault, SESSION, AGENT, ["Brain/active.md"])).toBe(true);+ expect(recordSubagentDeliveredId(vault, SESSION, AGENT)).toBe(true);+ expect(evidencePathsOf(readSubagentDeliveredPaths(vault, SESSION))).toEqual([+ "Brain/active.md",+ ]);+ });++ test("keeps only the most recent paths past the cap", () => {+ const total = SUBAGENT_PATHS_MAX + 5;+ const all = Array.from(+ { length: total },+ (_, i) => `Brain/notes/n${String(i).padStart(4, "0")}.md`,+ );+ expect(recordSubagentDeliveredId(vault, SESSION, AGENT, all)).toBe(true);+ const paths = readSubagentDeliveredPaths(vault, SESSION);+ expect(paths.length).toBe(SUBAGENT_PATHS_MAX);+ expect(evidencePathsOf(paths)).not.toContain("Brain/notes/n0000.md");+ expect(evidencePathsOf(paths)).toContain(+ `Brain/notes/n${String(total - 1).padStart(4, "0")}.md`,+ );+ });++ test("the carrier records the note paths its payload was built from", async () => {+ writeRules("Always run the test suite before committing.");+ writeActive(ACTIVE_BODY);+ writeLessons(LESSONS_BODY);+ const delivering = await runHook(subagentStartPayload({ agentId: AGENT }));+ expect(delivering.exit).toBe(0);+ expect(deliveredContext(delivering.stdout).additionalContext).not.toBe("");+ expect(evidencePathsOf(readSubagentDeliveredPaths(vault, SESSION))).toEqual([+ "Brain/active.md",+ "Brain/lessons.md",+ "Brain/standing-rules.md",+ ]);+ });++ test.skipIf(CHMOD_CANNOT_DENY)(+ "a delivery whose rules read failed records no standing-rules path",+ async () => {+ // The failure block names the path; the payload never carried the+ // file's content, so the path is not delivered evidence.+ const path = writeRules("rules that exist but cannot be read");+ writeActive(ACTIVE_BODY);+ chmodSync(path, 0o000);+ try {+ const delivering = await runHook(subagentStartPayload({ agentId: AGENT }));+ expect(delivering.exit).toBe(0);+ expect(deliveredContext(delivering.stdout).additionalContext).toContain("UNAVAILABLE:");+ } finally {+ chmodSync(path, 0o644);+ }+ expect(evidencePathsOf(readSubagentDeliveredPaths(vault, SESSION))).toEqual([+ "Brain/active.md",+ ]);+ },+ );++ test("an absent memory body records only the lanes that rendered", async () => {+ writeRules("Always run the test suite before committing.");+ const delivering = await runHook(subagentStartPayload({ agentId: AGENT }));+ expect(delivering.exit).toBe(0);+ expect(evidencePathsOf(readSubagentDeliveredPaths(vault, SESSION))).toEqual([+ "Brain/standing-rules.md",+ ]);+ });++ test("a standing body over its cap records the path truncated", async () => {+ writeRules(`${"Always run the test suite before committing. ".repeat(400)}`);+ const delivering = await runHook(subagentStartPayload({ agentId: AGENT }));+ expect(delivering.exit).toBe(0);+ const entries = readSubagentDeliveredPaths(vault, SESSION);+ expect(entries).toEqual([{ path: "Brain/standing-rules.md", truncated: true }]);+ });+});diff --git a/tests/mcp/brain-truth.test.ts b/tests/mcp/brain-truth.test.tsindex 4421bea3..73a8755d 100644--- a/tests/mcp/brain-truth.test.ts+++ b/tests/mcp/brain-truth.test.ts@@ -5,7 +5,7 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -13,8 +13,11 @@ import { bootstrapBrain } from "../../src/core/brain/init.ts";import { readClaimEvents, appendClaimEvent } from "../../src/core/brain/truth/store.ts";import { computeTruthStateWithConflicts } from "../../src/core/brain/truth/conflicts.ts";import { upsertEntity } from "../../src/core/brain/entities/registry.ts";+import { emitContextPackOutcome } from "../../src/core/brain/context-pack-outcome.ts";+import { emitContextReceipt } from "../../src/core/brain/context-receipts.ts";+import { continuityLogPath } from "../../src/core/brain/continuity/store.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";-import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";@@ -814,3 +817,455 @@ test("ingest refuses a malformed validity bound as invalid params, not an intern}expect(readClaimEvents(vault).events).toHaveLength(0);});++// ----- state sample_id + provenance-hydrated reads (answer-trust, B4) -----++interface ClaimProvenanceRow {+ readonly sample_id: string;+ readonly receipt: {+ readonly id: string;+ readonly created_at: string;+ readonly trigger: string | null;+ readonly items: ReadonlyArray<{ readonly id: string; readonly path?: string }>;+ readonly withheld: boolean;+ } | null;+ readonly outcome: {+ readonly id: string;+ readonly first_pass_success: boolean | null;+ readonly evidence_verdict?: string;+ } | null;+ readonly timestamp_inverted: boolean;+}++test("state accepts a sample_id and echoes it on each committed claim", async () => {+ seedRegistry();+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const body = (await call(server, {+ operation: "state",+ claims: [{ subject: "Alice Mason", relation: "extends", object: "Project Atlas" }],+ text: "Alice Mason said the Atlas extension plan refines Project Atlas scope.",+ source: "[[Brain/notes/session.md]]",+ sample_id: "rcpt-2026-0601-abcd",+ })) as unknown as StateResponse;+ expect(body.ok).toBe(true);+ expect(body.committed).toHaveLength(1);+ expect((body.committed[0] as unknown as { sample_id?: string }).sample_id).toBe(+ "rcpt-2026-0601-abcd",+ );+ const [stored] = readClaimEvents(vault).events;+ expect(stored!.sample_id).toBe("rcpt-2026-0601-abcd");+});++test("state refuses a non-string sample_id as invalid params", async () => {+ seedRegistry();+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const raw = await callRaw(server, {+ operation: "state",+ claims: [{ subject: "Alice Mason", relation: "extends", object: "Project Atlas" }],+ text: "Alice Mason said the Atlas extension plan refines Project Atlas scope.",+ source: "[[Brain/notes/session.md]]",+ sample_id: 42,+ });+ expect(raw.error).toBeDefined();+ expect(raw.error!.code).toBe(-32602);+ expect(raw.error!.message).toMatch(/sample_id/);+ expect(readClaimEvents(vault).events).toHaveLength(0);+});++test("state refuses a blank sample_id through the named refusal, before any write", async () => {+ seedRegistry();+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ // A blank id is a named refusal, never coerced to absent.+ const raw = await callRaw(server, {+ operation: "state",+ claims: [{ subject: "Alice Mason", relation: "extends", object: "Project Atlas" }],+ text: "Alice Mason said the Atlas extension plan refines Project Atlas scope.",+ source: "[[Brain/notes/session.md]]",+ sample_id: " ",+ });+ expect(raw.error).toBeDefined();+ expect(raw.error!.code).toBe(-32602);+ expect(raw.error!.message).toMatch(/sample_id/);+ expect(readClaimEvents(vault).events).toHaveLength(0);+});++test("state refuses an over-long or control-character sample_id, naming the limit", async () => {+ // L2.1 regression: the same shape check the core boundaries apply -+ // at most 256 characters, no control characters - mapped to the same+ // invalid-params failure class as the blank-id refusal.+ seedRegistry();+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ for (const bad of ["r".repeat(300), "rcpt\u0000-1", "rcpt\u0007-1"]) {+ const raw = await callRaw(server, {+ operation: "state",+ claims: [{ subject: "Alice Mason", relation: "extends", object: "Project Atlas" }],+ text: "Alice Mason said the Atlas extension plan refines Project Atlas scope.",+ source: "[[Brain/notes/session.md]]",+ sample_id: bad,+ });+ expect(raw.error).toBeDefined();+ expect(raw.error!.code).toBe(-32602);+ expect(raw.error!.message).toMatch(+ /sample_id must be a non-empty string of at most 256 characters without control characters/,+ );+ }+ expect(readClaimEvents(vault).events).toHaveLength(0);+});++test("events hydrate provenance for claims carrying a sample_id", async () => {+ seedRegistry();+ writeSourcePage("session.md");+ // The receipt item's path is filtered at the caller's reach, and a+ // path naming no page fails closed like any unreadable one - back the+ // item with a real page so the join may unfold it.+ writeSourcePage("alpha.md");+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ // An explicit past stamp: a defaulted `now` receipt can land up to a+ // second AFTER the claim's floored assertion stamp, which is a genuine+ // timestamp inversion the join must flag - the fixture keeps the+ // receipt unambiguously before the claim.+ const receipt = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: "2026-06-02T09:00:00.000Z" },+ items: [{ id: "note-alpha", path: "Brain/notes/alpha.md", tokens: 40 }],+ finalText: "the final answer text",+ });+ await call(server, {+ operation: "state",+ claims: [{ subject: "Alice Mason", relation: "extends", object: "Project Atlas" }],+ text: "Alice Mason said the Atlas extension plan refines Project Atlas scope.",+ source: "[[Brain/notes/session.md]]",+ sample_id: receipt.id,+ });+ const body = (await call(server, { operation: "events" })) as unknown as {+ events: ReadonlyArray<ClaimEventRow & { sample_id?: string; provenance?: ClaimProvenanceRow }>;+ };+ expect(body.events).toHaveLength(1);+ const row = body.events[0]!;+ expect(row.sample_id).toBe(receipt.id);+ expect(row.provenance).toBeDefined();+ expect(row.provenance!.sample_id).toBe(receipt.id);+ // Receipt known.+ expect(row.provenance!.receipt).not.toBeNull();+ expect(row.provenance!.receipt!.id).toBe(receipt.id);+ expect(row.provenance!.receipt!.items).toEqual([+ { id: "note-alpha", path: "Brain/notes/alpha.md" },+ ]);+ // Outcome unknown - absent, never invented.+ expect(row.provenance!.outcome).toBeNull();+ expect(row.provenance!.timestamp_inverted).toBe(false);+});++test("events leave claims without a sample_id exactly as today", async () => {+ seedRegistry();+ writeSourcePage("session.md");+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ await call(server, {+ operation: "state",+ claims: [{ subject: "Alice Mason", relation: "extends", object: "Project Atlas" }],+ text: "Alice Mason said the Atlas extension plan refines Project Atlas scope.",+ source: "[[Brain/notes/session.md]]",+ });+ const body = (await call(server, { operation: "events" })) as unknown as {+ events: ReadonlyArray<Record<string, unknown>>;+ };+ expect(body.events).toHaveLength(1);+ expect("provenance" in body.events[0]!).toBe(false);+ expect("sample_id" in body.events[0]!).toBe(false);+});++test("events hydrate a posted outcome row with its first-pass and evidence verdicts", async () => {+ seedRegistry();+ writeSourcePage("session.md");+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const receipt = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack" },+ items: [{ id: "note-alpha", path: "Brain/notes/alpha.md", tokens: 40 }],+ finalText: "the final answer text",+ });+ const posted = emitContextPackOutcome(+ vault,+ { sampleId: receipt.id, firstPassSuccess: false, repairRequired: true },+ true,+ );+ expect(posted).not.toBeNull();+ await call(server, {+ operation: "state",+ claims: [{ subject: "Alice Mason", relation: "extends", object: "Project Atlas" }],+ text: "Alice Mason said the Atlas extension plan refines Project Atlas scope.",+ source: "[[Brain/notes/session.md]]",+ sample_id: receipt.id,+ });+ const body = (await call(server, { operation: "events" })) as unknown as {+ events: ReadonlyArray<{ provenance?: ClaimProvenanceRow }>;+ };+ const provenance = body.events[0]!.provenance!;+ expect(provenance.outcome).not.toBeNull();+ expect(provenance.outcome!.first_pass_success).toBe(false);+ expect(provenance.outcome!.evidence_verdict).toBe("unclaimed");+});++test("two claims sharing a sample_id carry per-event inversion flags", async () => {+ // H2 regression: the inversion flag compares EACH claim's own ts+ // against the claimed receipt's created_at. Resolving per sample_id+ // instead of per event let one page row's verdict overwrite the+ // other's in the per-id map, so with one claim stated before its+ // receipt and one after, both rows rendered the same flag - the+ // earlier claim's inversion disappeared. Resolution is per event now,+ // attached by page position; the page itself still renders in the+ // ledger's ts-ascending order, so the flag must follow each row's ts+ // whichever way the ledger was appended.+ const receiptAt = "2026-06-02T09:00:00.000Z";++ const pageInversionFlags = async (+ server: MCPServer,+ ): Promise<ReadonlyArray<{ ts: string; inverted: boolean }>> => {+ const body = (await call(server, { operation: "events" })) as unknown as {+ events: ReadonlyArray<{ ts: string; provenance?: ClaimProvenanceRow }>;+ };+ expect(body.events).toHaveLength(2);+ return body.events.map((event) => ({+ ts: event.ts,+ inverted: event.provenance?.timestamp_inverted === true,+ }));+ };++ // Order 1: the inverted claim appended first.+ writeSourcePage("a.md");+ const receipt = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: receiptAt },+ items: [{ id: "note-a", path: "Brain/notes/a.md", tokens: 40 }],+ finalText: "the final answer text",+ });+ appendClaimEvent(vault, {+ ts: "2026-06-02T08:00:00Z",+ agent: "claude",+ entity: "Entity Early",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/a.md]]",+ sample_id: receipt.id,+ });+ appendClaimEvent(vault, {+ ts: "2026-06-02T10:00:00Z",+ agent: "claude",+ entity: "Entity Late",+ aspect: "employer",+ value: "Meta",+ source: "[[Brain/notes/a.md]]",+ sample_id: receipt.id,+ });+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ expect(await pageInversionFlags(server)).toEqual([+ { ts: "2026-06-02T08:00:00Z", inverted: true },+ { ts: "2026-06-02T10:00:00Z", inverted: false },+ ]);++ // Order 2: the inverted claim appended last, in a fresh ledger.+ const b = secondVault();+ try {+ mkdirSync(join(b.vault, "Brain", "notes"), { recursive: true });+ writeFileSync(join(b.vault, "Brain", "notes", "a.md"), "---\nkind: note\n---\n\na page\n");+ const receiptB = emitContextReceipt(b.vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: receiptAt },+ items: [{ id: "note-a", path: "Brain/notes/a.md", tokens: 40 }],+ finalText: "the final answer text",+ });+ appendClaimEvent(b.vault, {+ ts: "2026-06-02T10:00:00Z",+ agent: "claude",+ entity: "Entity Late",+ aspect: "employer",+ value: "Meta",+ source: "[[Brain/notes/a.md]]",+ sample_id: receiptB.id,+ });+ appendClaimEvent(b.vault, {+ ts: "2026-06-02T08:00:00Z",+ agent: "claude",+ entity: "Entity Early",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/a.md]]",+ sample_id: receiptB.id,+ });+ const serverB = new MCPServer({ vault: b.vault, configPath: b.configPath });+ await initialize(serverB);+ expect(await pageInversionFlags(serverB)).toEqual([+ { ts: "2026-06-02T08:00:00Z", inverted: true },+ { ts: "2026-06-02T10:00:00Z", inverted: false },+ ]);+ } finally {+ rmSync(b.configHome, { recursive: true, force: true });+ }+});++test("one receipt with an unparseable createdAt degrades per claim, not per page", async () => {+ // M4 regression: the continuity reader validates createdAt on append+ // only, so a hand-edited shard can carry a stamp no append would+ // accept. The events op must still answer ok with every row - the+ // sampled claim names an unreadable receipt and renders it unknown,+ // the unsampled claim renders byte-identically - instead of throwing+ // a plain internal error for the whole page.+ writeSourcePage("session.md");+ const receipt = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: "2026-06-02T09:00:00.000Z" },+ items: [{ id: "note-alpha", path: "Brain/notes/alpha.md", tokens: 40 }],+ finalText: "the final answer text",+ });+ const shard = continuityLogPath(vault, receipt.createdAt.slice(0, 7));+ const text = readFileSync(shard, "utf8");+ writeFileSync(+ shard,+ text.replace(+ JSON.stringify(receipt),+ JSON.stringify({ ...receipt, createdAt: "2026-06-garbage" }),+ ),+ );+ appendClaimEvent(vault, {+ ts: "2026-06-02T10:00:00Z",+ agent: "claude",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/session.md]]",+ sample_id: receipt.id,+ });+ appendClaimEvent(vault, {+ ts: "2026-06-03T10:00:00Z",+ agent: "claude",+ entity: "Bob Doe",+ aspect: "employer",+ value: "Meta",+ source: "[[Brain/notes/session.md]]",+ });+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const body = (await call(server, { operation: "events" })) as unknown as {+ ok: boolean;+ events: ReadonlyArray<{+ entity: string;+ provenance?: ClaimProvenanceRow | null;+ }>;+ };+ expect(body.ok).toBe(true);+ expect(body.events).toHaveLength(2);+ const sampled = body.events.find((event) => event.entity === "alice mason")!;+ expect(sampled.provenance).toBeDefined();+ // Receipt unreadable: it renders unknown, never a failed read.+ expect(sampled.provenance!.receipt).toBeNull();+ const unsampled = body.events.find((event) => event.entity === "bob doe")!;+ expect("provenance" in unsampled).toBe(false);+});++// ----- provenance at the caller's reach (answer-trust repair M2/F3) -----++const RULE_RECEIPT_STAMP = "2026-06-02T09:00:00.000Z";++function emitClaimOnReceipt(receiptId: string): void {+ appendClaimEvent(vault, {+ ts: "2026-06-02T10:00:00Z",+ agent: "claude",+ entity: "Alice Mason",+ aspect: "employer",+ value: "Google",+ source: "[[Brain/notes/session.md]]",+ sample_id: receiptId,+ });+}++async function eventsProvenanceAt(+ reach: TransportReach,+): Promise<ReadonlyArray<ClaimProvenanceRow | undefined>> {+ const server = new MCPServer({ vault, configPath }, { reach });+ await initialize(server);+ const body = (await call(server, { operation: "events" })) as unknown as {+ events: ReadonlyArray<{ provenance?: ClaimProvenanceRow }>;+ };+ expect(body.events).toHaveLength(1);+ return body.events.map((event) => event.provenance);+}++test("a rule-only injection receipt answers provenance as an unknown id below local reach", async () => {+ writeSourcePage("session.md");+ const receipt = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "session_inject", createdAt: RULE_RECEIPT_STAMP },+ items: [{ id: "standing-rules" }, { id: "scoped-rules" }],+ finalText: "constitution and scoped rules",+ });+ emitClaimOnReceipt(receipt.id);+ const [remoteProvenance] = await eventsProvenanceAt(TRANSPORT_REACH.remote);+ // The unknown-id answer: `brain_context_receipts show` refuses this+ // receipt below local reach and `list` leaves it out, so a claim's+ // provenance must not answer for it either - even a withheld-shaped+ // row would confirm the operator's rules were injected.+ expect(remoteProvenance!.receipt).toBeNull();+ expect(JSON.stringify(remoteProvenance)).not.toContain("standing-rules");+ const [localProvenance] = await eventsProvenanceAt(TRANSPORT_REACH.local);+ expect(localProvenance!.receipt).not.toBeNull();+ expect(localProvenance!.receipt!.items).toEqual([+ { id: "standing-rules" },+ { id: "scoped-rules" },+ ]);+});++test("a mixed receipt keeps its non-rule items and drops the rule items below local reach", async () => {+ writeSourcePage("session.md");+ writeSourcePage("alpha.md");+ const receipt = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "session_inject", createdAt: RULE_RECEIPT_STAMP },+ items: [+ { id: "standing-rules" },+ { id: "note-alpha", path: "Brain/notes/alpha.md", tokens: 40 },+ ],+ finalText: "rules plus a note",+ });+ emitClaimOnReceipt(receipt.id);+ const [remoteProvenance] = await eventsProvenanceAt(TRANSPORT_REACH.remote);+ // Not rule-only, so the receipt stays known - shaped as the receipts+ // surface shapes it, with the rule items and nothing else removed.+ expect(remoteProvenance!.receipt).not.toBeNull();+ expect(remoteProvenance!.receipt!.items).toEqual([+ { id: "note-alpha", path: "Brain/notes/alpha.md" },+ ]);+ const [localProvenance] = await eventsProvenanceAt(TRANSPORT_REACH.local);+ expect(localProvenance!.receipt!.items).toEqual([+ { id: "standing-rules" },+ { id: "note-alpha", path: "Brain/notes/alpha.md" },+ ]);+});++test("a receipt item whose path is withheld at the caller's reach leaves the provenance", async () => {+ writeSourcePage("session.md");+ writeSourcePage("alpha.md");+ writeSourcePage("secret.md", `\nvisibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`);+ const receipt = emitContextReceipt(vault, {+ options: { host: "mcp", trigger: "context_pack", createdAt: RULE_RECEIPT_STAMP },+ items: [+ { id: "note-secret", path: "Brain/notes/secret.md" },+ { id: "note-alpha", path: "Brain/notes/alpha.md" },+ ],+ finalText: "two notes",+ });+ emitClaimOnReceipt(receipt.id);+ const [remoteProvenance] = await eventsProvenanceAt(TRANSPORT_REACH.remote);+ // The same visibility rule the event rows of this report are gated+ // by, applied to the items the join unfolds: a path the caller may+ // not read drops exactly like a row naming it would.+ expect(remoteProvenance!.receipt!.items).toEqual([+ { id: "note-alpha", path: "Brain/notes/alpha.md" },+ ]);+ expect(JSON.stringify(remoteProvenance)).not.toContain("secret");+ const [localProvenance] = await eventsProvenanceAt(TRANSPORT_REACH.local);+ expect(localProvenance!.receipt!.items).toEqual([+ { id: "note-secret", path: "Brain/notes/secret.md" },+ { id: "note-alpha", path: "Brain/notes/alpha.md" },+ ]);+});diff --git a/tests/mcp/hygiene-capture-scope-reach.test.ts b/tests/mcp/hygiene-capture-scope-reach.test.tsindex 8aa6572f..adb3fdd2 100644--- a/tests/mcp/hygiene-capture-scope-reach.test.ts+++ b/tests/mcp/hygiene-capture-scope-reach.test.ts@@ -8,17 +8,28 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";+import { brainConfigPath } from "../../src/core/brain/paths.ts";import { bootstrapBrain } from "../../src/core/brain/init.ts";import { CAPTURE_SCOPE_DETECTOR_ID } from "../../src/core/brain/hygiene/detectors/capture-scope.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";import { HEALTH_TOOLS } from "../../src/mcp/brain/health-tools.ts";+import { INGEST_TOOLS } from "../../src/mcp/brain/ingest-tools.ts";import { HYGIENE_TOOLS } from "../../src/mcp/brain/hygiene-tools.ts";import { RESEARCH_TOOLS } from "../../src/mcp/brain/research-tools.ts";+import { MCPError } from "../../src/mcp/protocol.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";@@ -106,3 +117,210 @@ describe("brain_hygiene capture-scope at the caller's reach", () => {},);});++/**+ * The archive arm (answer trust, Task C5): a summary page stamped with an+ * archive digest claims durable evidence, and a stamp whose entry is absent+ * or re-hashes differently is a named finding - one per page, review+ * proposed action. An intact entry is not a finding, and a page with no+ * stamp means exactly "not captured", never a finding either. The+ * verification is a fact about the store, so the finding reaches every+ * caller who may read the page, at either reach.+ */+describe("brain_hygiene capture-scope archive findings", () => {+ const ingest = INGEST_TOOLS[0]!.handler;+ const SOURCE = "Articles/archived.md";+ let summaryPath: string;+ let archiveFile: string;++ /** The capture-scope findings at this reach, with their evidence. */+ const findingsAt = async (reach: TransportReach) => {+ const res = (await hygiene(+ { ...ctx, reach },+ { mode: "scan", detectors: [CAPTURE_SCOPE_DETECTOR_ID] },+ )) as {+ findings: ReadonlyArray<{+ targets: ReadonlyArray<string>;+ proposed_action: string;+ title: string;+ evidence: Record<string, unknown>;+ }>;+ };+ return res.findings.filter((f) => f.targets.includes(summaryPath));+ };++ beforeEach(async () => {+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, SOURCE), "archived bytes\n", "utf8");+ const res = (await ingest(ctx, {+ source_path: SOURCE,+ summary: "Durable.",+ entities: [{ category: "concept", name: "Durable" }],+ })) as { summary_path: string; source_archive_hash: string };+ summaryPath = res.summary_path;+ archiveFile = join(vault, "Brain", ".archives", `${res.source_archive_hash}.txt`);+ expect(existsSync(archiveFile)).toBe(true);+ });++ test("an intact entry is not a finding, at either reach", async () => {+ expect(await findingsAt(TRANSPORT_REACH.local)).toEqual([]);+ expect(await findingsAt(TRANSPORT_REACH.remote)).toEqual([]);+ });++ test("a deleted entry is a missing-archive finding naming the page", async () => {+ rmSync(archiveFile);+ const findings = await findingsAt(TRANSPORT_REACH.local);+ expect(findings).toHaveLength(1);+ expect(findings[0]!.proposed_action).toBe("review");+ expect(findings[0]!.evidence["archive"]).toBe("missing");+ // The same fact reaches a remote caller who may read the page.+ expect(await findingsAt(TRANSPORT_REACH.remote)).toEqual(findings);+ });++ test("a tampered entry is a mismatched-archive finding, not a missing one", async () => {+ writeFileSync(archiveFile, "rewritten after the stamp", "utf8");+ const findings = await findingsAt(TRANSPORT_REACH.local);+ expect(findings).toHaveLength(1);+ expect(findings[0]!.evidence["archive"]).toBe("mismatched");+ });++ test("a page with no stamp is never an archive finding", async () => {+ const url = (await ingest(ctx, {+ source_path: "https://example.test/unarchived",+ summary: "Remote.",+ entities: [{ category: "concept", name: "Unarchived" }],+ })) as { summary_path: string; source_archive_hash: string | null };+ expect(url.source_archive_hash).toBeNull();+ const res = (await hygiene(ctx, {+ mode: "scan",+ detectors: [CAPTURE_SCOPE_DETECTOR_ID],+ })) as { findings: ReadonlyArray<{ targets: ReadonlyArray<string> }> };+ expect(res.findings.some((f) => f.targets.includes(url.summary_path))).toBe(false);+ });+});++/**+ * The `archive_get` read on the existing tool (answer trust, Task C6),+ * with `brain_artifact_get`'s bounded-fetch posture and the wave's+ * visibility rule: LOCAL reach only. A remote caller gets the answer an+ * absent entry gives - the named miss, no bytes - whether or not an entry+ * is there, so the response is never an existence oracle and never carries+ * archived source bytes off the host.+ */+describe("brain_hygiene archive_get", () => {+ const ingest = INGEST_TOOLS[0]!.handler;+ const SOURCE = "Articles/fetchable.md";+ let hash: string;+ let entryPath: string;+ let summaryPath: string;++ const archiveGet = (reachCtx: ServerContext, args: Record<string, unknown>) =>+ hygiene(reachCtx, { mode: "archive_get", ...args }) as Promise<Record<string, unknown>>;++ /** The delivery gate the owner-scope view reads: `fail` enforces the scope. */+ const setOwnerGate = (mode: string): void => {+ atomicWriteFileSync(+ brainConfigPath(vault),+ `schema_version: 1\nintegrity:\n owner_scope_delivery: ${mode}\n`,+ );+ };++ /** Restamp the citing summary page under another owner. */+ const restampUnder = (owner: string): void => {+ const path = join(vault, summaryPath);+ writeFileSync(+ path,+ readFileSync(path, "utf8").replace(/^---\n/, `---\nowner: ${owner}\n`),+ "utf8",+ );+ };++ beforeEach(async () => {+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, SOURCE), "fetchable bytes\n", "utf8");+ const res = (await ingest(ctx, {+ source_path: SOURCE,+ summary: "Fetchable.",+ entities: [{ category: "concept", name: "Fetchable" }],+ })) as { source_archive_hash: string; summary_path: string };+ hash = res.source_archive_hash;+ entryPath = join(vault, "Brain", ".archives", `${hash}.txt`);+ summaryPath = res.summary_path;+ });++ test("at local reach a known hash resolves the archived bytes", async () => {+ const res = await archiveGet({ ...ctx, reach: TRANSPORT_REACH.local }, { hash });+ expect(res).toEqual({+ hash,+ archive: "verified",+ bytes: Buffer.byteLength("fetchable bytes\n", "utf8"),+ content: "fetchable bytes\n",+ });+ });++ test("an unknown hash is a named miss, not an error", async () => {+ const res = await archiveGet(+ { ...ctx, reach: TRANSPORT_REACH.local },+ { hash: "b".repeat(64) },+ );+ expect(res).toEqual({ hash: "b".repeat(64), archive: "missing" });+ });++ test("a mismatched entry says so and returns the bytes it actually holds", async () => {+ writeFileSync(entryPath, "rewritten after the stamp", "utf8");+ const res = await archiveGet({ ...ctx, reach: TRANSPORT_REACH.local }, { hash });+ expect(res["archive"]).toBe("mismatched");+ expect(res["content"]).toBe("rewritten after the stamp");+ });++ test("a malformed hash is the caller's named refusal", async () => {+ await expect(+ archiveGet({ ...ctx, reach: TRANSPORT_REACH.local }, { hash: "../../etc/passwd" }),+ ).rejects.toThrow(MCPError);+ });++ test("a remote caller gets the absent entry's answer, never the bytes", async () => {+ // The entry EXISTS; the response must be identical to its absence.+ const res = await archiveGet(ctx, { hash });+ expect(res).toEqual({ hash, archive: "missing" });+ expect(res).not.toHaveProperty("content");+ expect(res).not.toHaveProperty("bytes");+ });++ test("an owner-scoped caller cannot confirm an entry whose citing page is another owner's", async () => {+ // The scan withholds another owner's citing page through the gated+ // view; answering this entry's state or bytes would stand beside that+ // as a confirm-a-guess oracle. Under an enforced scope the entry whose+ // every citing page is withheld reads exactly as absent.+ setOwnerGate("fail");+ restampUnder("other-agent");+ const res = await archiveGet(+ { ...ctx, reach: TRANSPORT_REACH.local, agentName: "me-agent" },+ { hash },+ );+ expect(res).toEqual({ hash, archive: "missing" });+ });++ test("the entry's own owner still reads the bytes at local reach", async () => {+ setOwnerGate("fail");+ restampUnder("other-agent");+ const res = await archiveGet(+ { ...ctx, reach: TRANSPORT_REACH.local, agentName: "other-agent" },+ { hash },+ );+ expect(res["archive"]).toBe("verified");+ expect(res["content"]).toBe("fetchable bytes\n");+ });++ test("an enforced scope still answers a shared citing page with the bytes", async () => {+ // The gate narrows only what the page itself withholds: an ownerless+ // summary page is shared, so the same scoped caller keeps the fetch.+ setOwnerGate("fail");+ const res = await archiveGet(+ { ...ctx, reach: TRANSPORT_REACH.local, agentName: "me-agent" },+ { hash },+ );+ expect(res["archive"]).toBe("verified");+ expect(res["content"]).toBe("fetchable bytes\n");+ });+});diff --git a/tests/mcp/ingest-parts-reach.test.ts b/tests/mcp/ingest-parts-reach.test.tsindex e4a0f36a..bf63cc66 100644--- a/tests/mcp/ingest-parts-reach.test.ts+++ b/tests/mcp/ingest-parts-reach.test.ts@@ -100,7 +100,11 @@ describe("brain_ingest_source on an HTML source", () => {const result = await ingest(f, HTML_PATH);expect(result["parts"]).toEqual({ extracted: true, count: 2 });const keys = Object.keys(result);- expect(keys.indexOf("parts")).toBe(keys.indexOf("capture_scope") + 1);+ // The archive stamp (answer trust) follows capture_scope's field+ // pattern: the hash is always present, the byte count rides only with+ // a hash, and the ingest-specific block keeps its place after them.+ expect(keys.indexOf("source_archive_hash")).toBe(keys.indexOf("capture_scope") + 1);+ expect(keys.indexOf("parts")).toBe(keys.indexOf("source_archive_bytes") + 1);expect("table" in result).toBe(false);const page = pageOf(f, result);diff --git a/tests/mcp/ingest-tool-table.test.ts b/tests/mcp/ingest-tool-table.test.tsindex c1fd8959..38bd4728 100644--- a/tests/mcp/ingest-tool-table.test.ts+++ b/tests/mcp/ingest-tool-table.test.ts@@ -113,7 +113,11 @@ describe("brain_ingest_source on a table source", () => {redacted_cells: 0,});const keys = Object.keys(result);- expect(keys.indexOf("table")).toBe(keys.indexOf("capture_scope") + 1);+ // The archive stamp (answer trust) follows capture_scope's field+ // pattern: the hash is always present, the byte count rides only with+ // a hash, and the ingest-specific block keeps its place after them.+ expect(keys.indexOf("source_archive_hash")).toBe(keys.indexOf("capture_scope") + 1);+ expect(keys.indexOf("table")).toBe(keys.indexOf("source_archive_bytes") + 1);const page = pageOf(f, result);const fm = frontmatterKeys(page);diff --git a/tests/mcp/ingest-tool.test.ts b/tests/mcp/ingest-tool.test.tsindex 37db5d11..470f26b4 100644--- a/tests/mcp/ingest-tool.test.ts+++ b/tests/mcp/ingest-tool.test.ts@@ -304,6 +304,149 @@ describe("brain_ingest_source - capture_scope", () => {});});+/**+ * The durable-archive result fields (answer trust, Task C4), following the+ * capture_scope pattern: `source_archive_hash` is always present, null when+ * the source was not archived, and the named refusal rides only when an+ * ELIGIBLE source could not be.+ */+describe("brain_ingest_source - source_archive_hash", () => {+ interface ArchiveResult {+ readonly source_archive_hash: string | null;+ readonly source_archive_bytes?: number;+ readonly source_archive_refusal?: string;+ }+ const ingest = (sourcePath: string, extra: Record<string, unknown> = {}) =>+ handler(ctx, {+ source_path: sourcePath,+ summary: "Archived?",+ entities: [{ category: "concept", name: "Archived" }],+ ...extra,+ }) as Promise<ArchiveResult>;++ test("a trusted source reports the entry digest and byte count", async () => {+ seed("Articles/held.md");+ const res = await ingest("Articles/held.md");+ expect(res.source_archive_hash).toMatch(/^[0-9a-f]{64}$/);+ expect(res.source_archive_bytes).toBe(Buffer.byteLength("bytes of Articles/held.md\n", "utf8"));+ expect(res.source_archive_refusal).toBeUndefined();+ });++ test("a url source reports a null hash, never a missing key", async () => {+ const res = await ingest("https://example.test/post");+ expect(res.source_archive_hash).toBeNull();+ expect(res.source_archive_bytes).toBeUndefined();+ expect(res.source_archive_refusal).toBeUndefined();+ });++ test("an oversized trusted source reports a null hash and the named refusal", async () => {+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, "Articles", "big.md"), "y".repeat(1_048_577), "utf8");+ const res = await ingest("Articles/big.md");+ expect(res.source_archive_hash).toBeNull();+ expect(res.source_archive_bytes).toBeUndefined();+ expect(res.source_archive_refusal).toContain("1048576-byte ceiling");+ });++ test("a source withheld at the caller's reach reports a null hash and no refusal", async () => {+ mkdirSync(join(vault, "Notes"), { recursive: true });+ writeFileSync(+ join(vault, "Notes", "quiet.md"),+ "---\nvisibility: private\n---\nThe code is ZX8.\n",+ "utf8",+ );+ const res = await ingest("Notes/quiet.md");+ // The caller's reach makes it untrusted: not capture-eligible, so no+ // stamp, no refusal, and nothing on disk.+ expect(res.source_archive_hash).toBeNull();+ expect(res.source_archive_refusal).toBeUndefined();+ expect(existsSync(join(vault, "Brain", ".archives"))).toBe(false);+ });+});++/**+ * Delete-by-source takes the source's archive entry with it once the last+ * citing page goes (answer trust, Task C4), reported as its own kind. Two+ * sources with identical bytes share one content-addressed entry, so the+ * first deletion must leave it standing.+ */+describe("brain_delete_by_source - archive entry cleanup", () => {+ const deleteTool = INGEST_TOOLS.find((t) => t.name === "brain_delete_by_source")!.handler;+ const TWIN_A = "Articles/twin-a.md";+ const TWIN_B = "Articles/twin-b.md";++ interface CleanupResult {+ readonly archive_entries?: ReadonlyArray<{ hash: string; path: string }>;+ readonly deleted: ReadonlyArray<string>;+ }+ const cleanup = (source: string, confirm: boolean) =>+ deleteTool(ctx, { source_file: source, confirm }) as Promise<CleanupResult>;++ beforeEach(async () => {+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, TWIN_A), "twin bytes\n", "utf8");+ writeFileSync(join(vault, TWIN_B), "twin bytes\n", "utf8");+ const a = (await handler(ctx, {+ source_path: TWIN_A,+ summary: "Twin A.",+ entities: [{ category: "concept", name: "TwinA" }],+ })) as { source_archive_hash: string };+ const b = (await handler(ctx, {+ source_path: TWIN_B,+ summary: "Twin B.",+ entities: [{ category: "concept", name: "TwinB" }],+ })) as { source_archive_hash: string };+ expect(b.source_archive_hash).toBe(a.source_archive_hash);+ });++ test("a dry run over one of two citing sources names no archive entry", async () => {+ const res = await cleanup(TWIN_A, false);+ expect(res.archive_entries).toBeUndefined();+ });++ test("removing the first citing source leaves the shared entry on disk", async () => {+ const res = await cleanup(TWIN_A, true);+ expect(res.archive_entries).toBeUndefined();+ expect(readdirSync(join(vault, "Brain", ".archives"))).toHaveLength(1);+ });++ test("removing the LAST citing source removes the entry, reported as its own kind", async () => {+ await cleanup(TWIN_A, true);+ const dry = await cleanup(TWIN_B, false);+ // readdirSync names the file WITH its extension; the entry hash is the stem.+ const file = readdirSync(join(vault, "Brain", ".archives"))[0]!;+ const hash = file.replace(/\.txt$/, "");+ expect(dry.archive_entries).toEqual([{ hash, path: `Brain/.archives/${file}` }]);++ const res = await cleanup(TWIN_B, true);+ expect(res.archive_entries).toEqual([{ hash, path: `Brain/.archives/${file}` }]);+ // The entry file is gone; the (now empty) store directory may remain.+ expect(existsSync(join(vault, "Brain", ".archives", file))).toBe(false);+ expect(readdirSync(join(vault, "Brain", ".archives"))).toEqual([]);+ });++ test("an undeletable entry is omitted from archive_entries and the confirmed deletion still succeeds", async () => {+ // Down to one citing page, so the confirmed deletion below orphans the+ // shared entry - then the entry itself is replaced by a non-empty+ // DIRECTORY of the same name: a deterministic, root-proof stand-in for+ // an undeletable entry (rmSync raises ERR_FS_EISDIR on it).+ await cleanup(TWIN_A, true);+ const file = readdirSync(join(vault, "Brain", ".archives"))[0]!;+ const entryPath = join(vault, "Brain", ".archives", file);+ rmSync(entryPath);+ mkdirSync(join(entryPath, "junk"), { recursive: true });++ const res = await cleanup(TWIN_B, true);+ // The tool succeeds: the page deletion completed, the failed cleanup+ // neither fails it nor leaks the host path, and the entry is simply+ // omitted from the reported kinds (the doctor's uncited count names+ // the leftover).+ expect(res.archive_entries).toBeUndefined();+ expect(res.deleted.length).toBeGreaterThan(0);+ expect(existsSync(entryPath)).toBe(true);+ });+});+/*** A page the caller cannot read at its reach is ingested exactly like an* absent one: untrusted lane, `url-only`, and no digest on any page.diff --git a/tests/mcp/session-summary-tool.test.ts b/tests/mcp/session-summary-tool.test.tsindex 3e30369b..5f6af866 100644--- a/tests/mcp/session-summary-tool.test.ts+++ b/tests/mcp/session-summary-tool.test.ts@@ -6,6 +6,7 @@ import { join } from "node:path";import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";import { buildToolTable } from "../../src/mcp/tools.ts";import { appendSessionSummary } from "../../src/core/brain/session-summary.ts";+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";let vault: string;@@ -246,4 +247,21 @@ describe("brain_session_summary project scope (Task 18)", () => {const properties = (tool!.inputSchema as { properties: Record<string, unknown> }).properties;expect(properties["project_scope"]).toBeDefined();});++ test("list renders a no-session digest without a fabricated session_id", async () => {+ // Seeded directly, the way a writer that stamps `session_id`+ // conditionally leaves the key absent.+ appendContinuityRecord(vault, {+ kind: "session_summary_digest",+ createdAt: "2026-06-14T10:00:00.000Z",+ sourceRefs: [{ id: "s-none", kind: "session" }],+ payload: { decisions: ["unattributed"], content_hash: "0123456789abcdef" },+ });++ const listed = payload(await call({ operation: "list" }));+ expect(listed["count"]).toBe(1);+ const digest = (listed["digests"] as Array<Record<string, unknown>>)[0]!;+ expect("session_id" in digest).toBe(false);+ expect(digest["decisions"]).toEqual(["unattributed"]);+ });});diff --git a/uv.lock b/uv.lockindex 28d475fb..574cfbc1 100644--- a/uv.lock+++ b/uv.lock@@ -4,5 +4,5 @@ requires-python = ">=3.11"[[package]]name = "open-second-brain"-version = "1.80.0"+version = "1.81.0"source = { editable = "." }