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: a label is not a boundary (v1.49.0) (#166)
Sol Aitkenb49af81ebe20
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 78537db4..1aaddd3c 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.48.0",+ "version": "1.49.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 e4c539ef..ecc89f9c 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.48.0",+ "version": "1.49.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 79bd756f..76416ed0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,69 @@ 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.49.0] - 2026-08-16++Ten tracker items, picked by priority off the board and read against the real source before anything was designed, turned out to describe one defect seen from ten sides: the product declares a boundary and puts nothing behind it. An owner-isolation filter whose field no writer ever emitted. A gate that enforced whichever scope the caller asked for. A confidence floor compared against a number that could not vary with match quality. An egress registry built to stop an unguarded export, with an unguarded export outside it. A census whose docblock claimed to have closed the mis-parse class that was live inside it.++Reconnaissance corrected most of the ten task bodies before a line was written. Six corrections changed what the unit is rather than how it is worded, two findings turned out to be the opposite of what was filed, and two described a live defect rather than an improvement: a credential leaving verbatim through a shipped export path, and an authorisation check that read back whatever the caller claimed. Each unit then takes one declared boundary and does exactly one of three things, chosen by evidence: ENFORCE it and put a census behind the check, RE-MEASURE it against the signal that actually varies with what the label claims, or RETRACT it and say so.++Then two reviewers were given the finished branch with no knowledge of how it was built, and told that a comment is a claim rather than evidence and that a test which cannot fail proves nothing. They turned the release's own thesis on it and it did not survive contact. The isolation probe this release is proudest of — one two-owner fixture driving every classified tool — was itself a label with nothing behind it: flipping it to run with the gate OPEN and demanding the marker appear gave 15 pass and 81 fail. Eighty-one of the ninety-six entries were driven against arguments naming artifacts the fixture never created, so they could not have failed under any setting. Three more surfaces were leaking behind that green: `brain_hygiene mode=apply` retired another owner's preference and named both hidden ids, `brain_analytics` filtered one view of four, and `brain_health` returned a verdict folded over findings it had just withheld. The MCP resources surface had no ownership filtering at all. The central measurement the four rethreaded thresholds rest on was wrong by 0.05 in seven places. Everything named below is what shipped after that.++### Added++- **Ownership is written, or it is not a boundary.** With `integrity.owner_scope_delivery` on, every production preference writer stamps the server-resolved agent identity onto a new record. A rewrite never re-owns, so a page created before the gate stays shared rather than being retro-owned by whoever rewrote it first. With the gate off nothing is stamped and a vault that never opted in is byte-identical, measured with a whole-tree digest. "Every writer" is enforced by a census derived from source rather than a hand-written list: a module that builds a preference path and writes bytes must reach the stamp or carry a declared exemption. The hand-written list is what let `import-claude-memory` write an unstamped preference through its own renderer.+- **A caller-supplied owner scope is checked.** Under the gate, an `agent_scope` naming an owner other than the resolved identity is refused by name, never silently narrowed — a narrowing would leave the caller believing it had read what it asked for. An unconfigured install cannot become an owner either: the placeholder identity `agent` is refused by the same predicate on the write side that already refused it on the read side, so the two halves cannot disagree.+- **The scope matrix asserts correctness, and asserts that it asserts anything.** Ninety-six classified tools carry 220 call recipes, one per mode, view or operation, because one executed view is not an executed classification. Every recipe runs twice against the same two-owner fixture — once with the gate closed, once open — and the classification decides what the open run must show. The 31 recipes claiming to reach owner-taggable content must surface the marker with the gate off, which is what stops the closed run from passing vacuously; the other 189 carry a claim of unreachability, executed directly where nothing is hidden. All three numbers are pinned as equalities.+- **The MCP resources surface honours the gate.** `osb://preference/{id}`, `osb://topic/{slug}`, `osb://backlinks/{id}` and `osb://log/{date}` returned another owner's file verbatim, including its `owner:` line, while the delivery path correctly withheld it. A withheld resource now answers with the same not-found message an absent one produces. The topic scope reaches the selection rather than filtering after it, so a shared record is not hidden merely because another owner's sorted first.+- **The delegation boundary the host already delivers.** `SubagentStop` is registered, and a session turn carries the delegated `agentId` and `isSidechain` — the only things separating a sub-agent's turns from its parent's, since a sub-agent transcript reuses the parent's session id. Both are emitted only where the transcript records them, so a flat transcript keeps its pre-delegation shape byte for byte. The Grok installer registered six of eight hook events and captured nothing from a delegated sub-agent; a parity test now derives the expectation from `hooks/hooks.json` itself.+- **An unreachable search origin is reported rather than dropped**, with a four-piece vocabulary distinguishing reachable, unreachable and unknown, each carrying its own reason where it has one — "it is not there" and "I could not look" have different repairs, and neither may read as a zero contribution.+- **The `vault_path` contract has an enumeration behind it.** Forty-four sites emit the field and three honoured the contract stated in prose above them. A census lexes every emission out of the tool surface and requires it to come from the one producer. The producer moved to its own leaf module, because importing it back from the tool aggregator would have closed an import cycle the architecture ratchet gates — and that move is also what let the OpenClaw plugin, a second runtime with three emissions of its own, reach it.++### Changed++- **Four thresholds stop reading a number that cannot vary with match quality.** Whenever the keyword lane is non-empty, the top row of any recall scores at or above the configured `search_keyword_weight` — shipped at 0.6, identical to `recall_adequacy_sufficient` — and 0.65 measured end to end on a freshly written keyword-only vault, where the ranker adds the freshness prior on top of the min-max normalised lane. Nothing about how well the row matched can move it below that floor. So every keyword recall graded `sufficient / proceed`, a gap task auto-closed on a hit of any quality, and the cross-vault chain stop meant opposite things under the two fusion modes. All four now read IDF-weighted coverage. No threshold value changed; what they measure did.+- **Match quality can say it does not know.** `idfWeightedCoverage` is `number | null`, and `null` exactly when there is no IDF mass to weigh. It used to return 1.0 — maximum confidence — for any query it could not weigh, which included every one- or two-character CJK query, because "significant term" carried a three-character floor that was an English-shaped stopword rule in structural disguise. That floor is gone; a token qualifies if it carries a word character, and nothing branches on script. The same floor sat one layer up in the demand log, where it made a CJK query unable to form a bucket at all, so its recall gaps were invisible to the gap-promotion loop. `null` is nullable rather than a flag so the compiler forces every consumer to choose: the targeted retry does not fire, completeness gains an `unmeasurable` verdict rather than folding into `sparse`, the chain stop does not stop, the gap loop does not close, and recall-inject abstains with a named reason.+- **What match quality is, stated narrowly enough to be true.** It is absolute as against a score — no rank position, no lane magnitude, no fusion mode — so two retrievals for one query are comparable. It is NOT independent of which rows were delivered: it is computed over the returned window, so the same query at `limit: 1` and `limit: 20` differs, and that is pinned by a test. The first version of this release claimed pool-independence in five docblocks.+- **The `tier:` frontmatter knob reaches the ranker.** It shipped with a weight table, a breakdown line and no producer, so a page stamped `tier: peripheral` scored identically to an untagged one. An untagged vault emits no tier map at all and its ranking is unchanged, pinned by an ordered `(path, score)` window over the committed benchmark corpus.+- **`brain_recall_gate` and `brain_context_pack` take `match_quality` beside their scores**, all-or-nothing: the level is decided by the quality alone, and deriving one from the scores is the substitution this release removes. The tool description advertised the call the handler now refuses; it names the pairing, the schema states it as `dependentRequired`, and the verdict returns `match_quality` so the quantity that decided the level travels with it.+- **A scoped call on an unreadable config is refused rather than delivered.** An unreadable config resolves to the strict integrity fallback precisely so it cannot loosen a gate, only close one. That rationale is about READERS, and this release first wired a writer to it — one bad token in the YAML silently began stamping ownership onto every new preference, permanently. The writer now refuses and names the parse failure: it cannot infer an operator's intent to enable ownership from a file it could not read.+- **One lexer for every census that reads this repository's own source.** Four census files had grown their own copy; one read a backtick inside a regex literal as a template opener, blanked 9,706 bytes of a shipped module and hid what its census could not otherwise see. Its own offset invariant was then broken by an astral character — both views were built by code point while the scanner indexed code units — so four instruments were reading one shipped module one character out of step. Six further single-file assertions that stripped comments by naive regex now route through it too.+- **Census counts become equalities where a floor hid a drifted reality.** The direct continuity-store reader floor sat at twenty against a real twenty-one, and the observability doc had inherited the wrong number from it. The `vault_path` and write-site censuses carried the same shape and are pinned too.++### Fixed++- **`brain_hygiene mode=apply` wrote across the owner boundary.** The owner view was constructed inside the `scan` branch, so a caller whose scan correctly returned nothing could hand `apply` a finding id and retire another owner's preference — and the response named both hidden artifacts. Finding ids are a digest of their targets, derivable rather than secret, so withholding them was never the boundary. The plan is built from the filtered report, which also closes the existence oracle: a hidden id now answers exactly as an id nobody issued. `brain_doctor repair` had the same shape and rewrote another owner's frontmatter.+- **Three surfaces disclosed what they had just withheld.** `brain_analytics` filtered `timeline` and left `concept_synthesis`, `belief_evolution` and `dedup` open — the first returned another owner's preference id and a verbatim line of its body. `brain_health` returned a verdict folded over the unfiltered findings while the arrays beside it were empty, telling the caller a hidden artifact had tripped a detector. `brain_sources` was reclassified rather than filtered: it groups signals by author, and signals carry no owner in this product, so the reason was wrong and not the payload. The widened probe found five more — `brain_clusters`, `brain_dream`, `brain_trigger`, `brain_doctor repair` and `brain_agent_diff` — all closed, none moved to the unscoped bucket.+- **An unredacted vault export.** `o2b brain explorer --export` wrote vault content to an operator-named file without the redactor every other export path uses. The egress census missed it because its population rule keyed on a hardcoded list of destination flags — the same defect class the census exists to catch, one level up. Its two synthetic positive controls could not have caught the fix either: both appended a fabricated path string to an already-derived population, and blinding the derivation to an empty list left them green. All three now run the real derivation over the intruder's real source.+- **The egress registry could not express the largest egress in the product.** A second population rule finds modules POSTing vault-derived bytes to an operator-configured URL. Five such sites exist, not one: two embedding providers, the cross-encoder reranker — which POSTs the query and the candidate documents — the Telegram capture reply, and the research transport. Each is declared with the reason redaction would corrupt rather than protect the result, and an operator-facing table in the CLI reference names what leaves and when. A default install reaches none of them.+- **An export that could not parse a preference reported success**, silently omitting records. It now collects every failure in one run and refuses by name with a non-zero exit, and the message is vault-relative rather than carrying the host path. The bare `catch { return [] }` on the directory listing above it, which reported a permission fault as an empty Brain, raises with the reason.+- **`o2b brain bank-import` no longer aborts on a malformed rule in the destination.** The refusal's justification — no caller for whom a shorter list is the right answer — is true of an export and false of a prior-topic map, where a destination-side defect has nothing to do with the bundle being imported. The scan runs on the readable rules and reports each file it could not read, because a collision list over a partial map is a partial answer and not an empty one.+- **The redactor ate signal ids**, so an exported preference lost the link it points through. The carve-out keys on the shape rather than the prefix. It also surfaced that the CLI `--json` redactor has no high-entropy pass at all, so the two surfaces answered differently about the same string — only one of them ever ate it, and the tests now pin both.+- **`log.md` was empty on every default install.** The OKF export's date pattern matched only the legacy un-sharded log name while the writer has produced per-device shards since sharding landed. It reads the recogniser in the module that owns the layout, and shards of one day fold into one section.+- **A backlink index reported a confident zero** on a legacy-frontmatter preference, swallowed by a `catch { continue }`. The failures ride on the returned index, so its call sites are unaffected, and the CLI verb — the surface an operator debugging a legacy vault reaches first — renders them instead of printing the unmeasured zero.+- **The gap loop measured coverage over rows its own gate rejects.** The path exclusion that stops a gap-task note closing itself applied to only half the condition, so the note the loop is trying not to count still inflated the number the floor read. The membership rule now travels with the query. The hook that drives it was then passing a retriever of the old shape — which TypeScript accepts, since a function taking fewer parameters is assignable to one taking more — so the hook threw and its outer catch swallowed it, doing nothing silently. It reports a distinct failed action rather than a zeroed healthy one.+- **`schema_inspect view=lint` and `view=orphans` died on the artifact they exist to report**, with an absolute host path in the message. Both report it instead, through one shared rewrite the export refusal now uses too, and the orphan review carries those rows because "nothing uses this token" is a claim over every artifact.+- **An absent argument was answered with a sentence about its shape.** `brain_labels` and `brain_tiers` answered a missing `path` with "path must be a vault-relative string", so a caller who sent the wrong argument name read it as a malformed value.+- **The owner-scope view failed open on a reference it could not resolve**, against its own stated convention, for two reasons: three directories holding owner-taggable id-addressable pages were missing from its list, and a bracketed wikilink matched neither branch.++### Notes++Some of what was asked for is not here, and each absence is a decision with a measurement behind it.++There is no git-visibility ladder: there is no git transport, every `git` invocation under `src/` is read-only, and the egress registry states in prose that there deliberately never will be one. A fail-closed check needs something to guard. There is no staging copy and no history purge: there is no history to purge, and the export bundle already is the staging copy. There is no `off` identity mode: the bottom of the identity chain is already the literal `agent`, itself a placeholder. The `passthrough` / `managed` mode names are not adopted — passthrough is the shipped, ungated default across every tool that accepts a caller-supplied agent, and the owner-scope refusal is what makes it gateable. There is no per-agent instruction block: neither transport can reach one, since both resolve identity from process environment and config rather than from the request, and the config reader has no block-scalar form. The `shared` observation-scope member stays retracted: a positive scope no reader requests narrows visibility rather than widening it.++`private: true` in frontmatter is retracted as a privacy claim rather than enforced. Nothing under `portability/` reads the key, the export composers are content composers rather than visibility filters, and the `<private>` region marker is the only content-derived privacy primitive. A test asserts that such a page exports in full, so the label cannot be re-read as a boundary.++The keyword lane is not de-normalised: every score in the product would move and four thresholds would flip at once.++Three things this release does NOT achieve, stated because the obvious reading of the bullets above is wider than the truth.++On a default keyword-only install, match quality is effectively binary. The keyword lane matches with implicit AND, so every returned row contains every query term and coverage is 1 whenever anything comes back and 0 when nothing does. The measurement is honest — that material really does cover the query — but `weak` remains unreachable on that configuration, for a different reason than before. Partial values need the semantic lane or the broadened second pass. A consequence worth naming rather than burying: the cross-vault chain stop has inverted. It never fired in `linear` mode and now fires on the first origin that returns anything. It is opt-in and off by default.++Computing match quality on every search is a new cost, not a recovered saving. An earlier draft of these notes claimed the number was already being computed and thrown away; it was reachable only in evidence-pack mode, which is off by default. Measured on the committed benchmark corpus it adds about 0.15 ms to a 5.9 ms query — roughly 2.5%, inside run-to-run noise at that size — and it scales with the query's term count rather than with the corpus.++`warn` is inert on the surfaces that now filter by the server-resolved identity. Reporting how many rows `fail` would withhold is itself the disclosure, so `warn`'s observability there is the `owner:` stamp appearing on new files, not a count in any response. The docblock that promised otherwise says so now.+## [1.48.0] - 2026-08-15Nine units picked by priority off the tracker, and reconnaissance against the real source before any of them was designed. That pass corrected six of the nine task bodies rather than following them, because they describe a different system: one with a resident daemon, a chat-model client of its own, and an ingest that locks too often. This one has none of those. What it does have is long, resource-hungry work that reports nothing while it runs, and surfaces that print claims nobody checked.@@ -7123,6 +7186,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.49.0]: https://github.com/itechmeat/open-second-brain/compare/v1.48.0...v1.49.0[1.48.0]: https://github.com/itechmeat/open-second-brain/compare/v1.47.0...v1.48.0[1.47.0]: https://github.com/itechmeat/open-second-brain/compare/v1.46.0...v1.47.0[1.46.0]: https://github.com/itechmeat/open-second-brain/compare/v1.45.1...v1.46.0diff --git a/docs/architecture.md b/docs/architecture.mdindex 69dddadc..3574f5bc 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -284,3 +284,72 @@ and is declared in `src/core/egress/registry.ts`, withsource so a new export path cannot ship undeclared. A payload the redactorcould only partially scan refuses the write rather than producing a file thatclaims to be clean.++The census derives that population under TWO rules, because a registry whose+membership check is narrower than what it claims to enforce is a label with+nothing behind it. The first rule finds FILE destinations - a destination+parameter plus a raw file write - and it is how `o2b brain explorer --export`+went undeclared: its destination flag was not in the list the rule keys on, so+the site wrote an unredacted vault export past a registry built to prevent+exactly that. The second rule finds NETWORK destinations - a module POSTing+vault-derived bytes to an operator-configured URL - which the first rule+cannot express at all. Under it the embedding endpoint+(`src/core/search/embeddings/openai-compat.ts`) is declared with a reason+stating plainly that chunk bodies leave unscanned. Both rules are proved by+synthetic modules, so each fails the build until the site it finds is+declared.++Five paths send vault-derived bytes to a network destination without passing+the shared redactor - the two embedding providers, the cross-encoder reranker+(which POSTs the query PLUS the candidate documents), the Telegram capture+reply, and the research transport. Each is declared in+`src/core/egress/registry.ts` as `unscanned_network_payload` with the reason+redaction would corrupt rather than protect the result, and+`docs/cli-reference.md` carries the operator-facing table; the census fails if+a sixth appears undeclared or an existing one falls out of that table. A+default install reaches none of them.++Ownership is a boundary only where something writes it. With+`integrity.owner_scope_delivery` on, every production preference writer stamps+the server-resolved agent identity onto a NEW record; a rewrite never re-owns,+so a page created before the gate stays shared rather than being retro-owned+by whoever rewrote it first. With the gate off nothing is stamped and a vault+that never opted in is byte-identical. On the read side a caller-supplied+`agent_scope` naming another owner is REFUSED by name under the gate, never+silently narrowed to the caller's own - a narrowing would leave the caller+believing it had read what it asked for.++The surfaces that take no `agent_scope` argument honour the same gate through+the server-resolved identity. They aggregated their own rows and asked nothing,+so under `fail` they returned another owner's artifact ids, paths, titles and+body prose. Each now filters through `ownerScopeView`, an adapter over the one+ownership rule rather than a second one, and the set spans the tool surface,+the MCP resources surface and one CLI verb. A withheld row is dropped and+nothing counts it: `brain_hygiene`'s per-detector counts, `brain_claims`'+`count` and the timeline's `total` are recomputed over the visible rows, so a+filtered report is indistinguishable from a report over a vault that never held+them. Two surfaces also bound a WRITE rather than only a payload -+`brain_hygiene mode=apply` and `brain_doctor repair` planned against the+unfiltered report, so a caller whose scan correctly returned nothing could+still act on a row it had never been shown. With the gate off every one of+these is byte-identical, because the view short-circuits before it reads a+file.++`warn` is inert on this set, deliberately and now stated where it is+implemented: reporting how many rows `fail` would withhold is itself the+disclosure, so `warn`'s observability here is the `owner:` stamp appearing on+new files, not a count in any response.++The enforcement lives in `tests/mcp/agent-scope-matrix.test.ts`, and its shape+is the point rather than its size. Ninety-six classified tools carry 220 call+recipes - one per mode, view or operation, because one executed view is not an+executed classification. Every recipe runs TWICE against the same two-owner+fixture, once with the gate closed and once with it open, and the classification+decides what the open run must show: the 31 recipes classified as reaching+owner-taggable content must surface the marker with the gate off, which is what+stops the closed run from passing vacuously. The other 189 carry a claim of+unreachability, and that claim is executed directly - the marker must be absent+even where nothing is hidden. The first version of this probe asserted only the+closed half, and 81 of its entries were driven against arguments that named+artifacts the fixture never created; they could not have failed. Those three+numbers are pinned as equalities in the same file.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/cli-output/claude.md b/docs/brainstorm/a-label-is-not-a-boundary/cli-output/claude.mdnew file mode 100644index 00000000..e5cc583b--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/cli-output/claude.md@@ -0,0 +1,44 @@+### Variant 1: Repair the instruments, let the red builds define the scope++- **Approach**: Treat the release as a measurement failure before a product failure. Five of the ten findings are broken auditors — the scope matrix that asserts partition instead of correctness, the egress census whose destination-name lists miss `export`, the hand-rolled lexer that blanks 31% of a module, the ranker that reports pool-relative score where an absolute one already exists and is discarded, and the adequacy threshold pinned to the keyword weight. Fix those instruments first, in dependency order, and ship whatever product fixes the newly-red builds then demand; the ten findings are the entry points, not the deliverable.+- **Trade-offs**:+ - Pro: matches the v1.48.0 thesis lineage directly — that release already discovered a census reading no source, so this is the same move applied at scale, and the argument writes itself.+ - Pro: strongest durability story per unit of work. A repaired census does not just fix finding 7, it fixes every future instance of finding 7, and the positive-control synthetic module from finding 8 is already built.+ - Pro: the discarded `idfWeightedCoverage` and the existing three-value egress verdict mean most instrument repairs are wiring, not invention — squarely on the v1.47.0 precedent.+ - Con: scope is not knowable before the work starts. Turning the scope matrix into a content assertion over 110 tools, or unblanking 9,706 bytes, will surface findings nobody has budgeted, and this must land in one branch.+ - Con: serialises badly. The four lexer copies collapse into one shared module that four test files import; one agent owns that file and three wait on it, which is the opposite of the parallelism requirement.+ - Con: findings 5, 6, 9 and 10 have no instrument to repair and fall outside the organising principle, so they either ride along unexplained or get cut.+- **Complexity**: large+- **Risk**: high++### Variant 2: A boundary census — one new mechanism that holds all ten++- **Approach**: Build an eleventh census in the established idiom: every label-bearing declaration in `src/` — a scope field, a config gate under `integrity.*`, a bucket in a classification, a registry member, a frozen vocabulary — must name the site that enforces it, and the census derives that population structurally from source and fails the build when a declared boundary has no reader, no writer, or no check. All ten findings become rows in one table; each fix is "make this row green". The release ships one artifact and ten entries.+- **Trade-offs**:+ - Pro: a single spine that makes the thesis mechanical rather than editorial, and a genuine guard against the eleventh instance of this defect class, which none of the existing ten censuses covers.+ - Pro: parallelises cleanly once the census exists — ten agents, ten rows, ten separate files, one shared read-only contract.+ - Pro: forces honest dispositions on findings 5 and 10, since "this label has no subject" becomes a recorded verdict rather than silence.+ - Con: the population is not structurally derivable the way write sites or progress emitters are. "A declared boundary" is a semantic category; deriving it from source needs a declaration surface, and a mandatory reason field is a new vocabulary shape beside the existing four-piece idiom — direct tension with "no second registry where one exists, no new vocabulary shape".+ - Con: the census must be designed before any of the ten fixes can start, so the whole branch has a single serialised critical path at its head.+ - Con: high risk of the mechanism itself becoming the next finding — a registry whose membership check is weaker than what it claims to enforce is precisely the defect under review.+- **Complexity**: large+- **Risk**: high++### Variant 3: Disposition triage — enforce, retract, or re-measure; no new mechanism++- **Approach**: Assign every finding exactly one of three verdicts and route it to the census that already owns its class. ENFORCE (1, 2, 4, 7, 9): make the check real — condition the `owner:` emission at the writer, make `coerceAgentScope` resolve rather than echo, put the shared namespace into `listSearchOrigins` and report the dead origin into the `warnings` array instead of dropping it at `:63`, register `--export` and the embedding POST as egress sites, subscribe `SubagentStop`. RETRACT (3's tier multiplier, 5's `off` mode, 10 entirely, and `origin_vault` if no reader is wanted): delete the label, because a mechanism that cannot change an outcome is the defect. RE-MEASURE (3, 6, 8): swap the wrong measure for the right one — `idfWeightedCoverage` in place of the normalised keyword score, the agent name kept on the writer and catalog scopes, one shared lexer with the newline guard restored. Nothing new is registered; each fix extends the existing egress registry, origins enumerator, vocabulary census, or progress contract.+- **Trade-offs**:+ - Pro: satisfies "maximally native integration" by construction — every landing site is an existing registry, and no eleventh census is invented.+ - Pro: best parallelism of the three. The ten units touch largely disjoint files, each is test-first against a specific `file:line`, and only the lexer dedupe has a shared owner.+ - Pro: RETRACT is a first-class outcome, which is the only honest disposition for finding 10 (no git transport exists and the registry's prose says one never will) and for the tier multiplier with no producer.+ - Pro: bounded scope. Every unit's definition of done is a named assertion, not a discovery loop.+ - Con: no single new mechanism guards the eleventh instance; durability is the sum of ten census extensions rather than one guarantee, which is weaker than the v1.46.0/v1.48.0 pattern.+ - Con: the thesis lives in the CHANGELOG and the test names, so the release reads as ten fixes unless the framing is written carefully.+ - Con: volume. Ten units, four hardcoded lists tripped by any tool change, an exact tool count of 110, and byte-identity of the committed bundle all have to stay green in one branch.+ - Con: RETRACT decisions are product calls the operator may want to review individually, which introduces a checkpoint the other variants avoid.+- **Complexity**: medium+- **Risk**: medium++### Recommended: Variant 3++**Rationale**: It is the only variant whose critical path is empty — ten agents can start test-first on separate files immediately, which the one-branch parallel-implementation constraint requires, whereas Variants 1 and 2 both serialise behind a shared artifact (the merged lexer, the new census) before any product fix can begin. It also honours "no second registry where one exists" literally, where Variant 2 must invent a declaration surface and a mandatory reason field beside the existing four-piece idiom, and it keeps scope knowable, where Variant 1 explicitly defers scope to whatever the repaired instruments turn red. The instrument repairs Variant 1 is built around survive here as individual RE-MEASURE units — the shared lexer, `idfWeightedCoverage`, the census destination derivation — without buying the unbounded discovery loop that came with them.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/cli-output/prompt.md b/docs/brainstorm/a-label-is-not-a-boundary/cli-output/prompt.mdnew file mode 100644index 00000000..ccba28ea--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/cli-output/prompt.md@@ -0,0 +1,78 @@+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++Ship one release for Open Second Brain that carries ten tracker items. Reconnaissance against the real source has already been done and it CORRECTED most of the tracker bodies; what follows is the corrected framing, not the original wording. Every claim below carries a file:line anchor that was opened and read, and several were reproduced by execution.++The ten items share one shape: **a boundary that is declared but not enforced**. In each case the product carries a label - a bucket name, a vocabulary member, a config gate, a scope field, a registry - and behind the label there is either no check, no reader, no writer, or a check that measures something other than what the label claims.++## The ten findings, as measured++1. **The owner-isolation layer is unconditioned.** `writePreference` emits an `owner:` field only when the caller supplies one (`src/core/brain/preference.ts:446,553`), and no production caller supplies it - not the MCP feedback tools (`src/mcp/brain/feedback-tools.ts:231-251`), not the CLI (`src/cli/brain/verbs/feedback.ts:139`), not derived-fact, merge, or the preference transaction. On any vault written through shipped surfaces every page is ownerless, `isOwnerVisible` returns true universally, and the whole filter passes everything. Separately, the MCP scope matrix (`tests/mcp/agent-scope-matrix.test.ts:301-303`) partitions 110 tools into three buckets and asserts only that each tool is classified exactly once - never that a classification is correct. Ten tools in the unasserted bucket return other agents' document identity on a bare `{}` call; one of them returns whole source lines of body text, and another returns full preference principle text plus a path.++2. **A gate that enforces self-declaration.** With `integrity.owner_scope_delivery` set to fail, `coerceAgentScope` (`src/mcp/coerce.ts:120-121`) returns the caller-supplied `agent_scope` unconditionally and `resolveOwnerScopeDelivery` (`src/core/brain/preferences-collect.ts:182`) enforces the *requested* scope, so any caller reads any owner's private preferences by naming that owner. The gate implies a check that is never performed.++3. **Four absolute thresholds compared against a pinned number.** `rankResults` min-max-normalises the keyword lane, so on a keyword-only vault (the default install, no embeddings) the top result is a constant 0.6000 to 0.6500 regardless of match quality. The recall confidence floor is 0.35, so it never rejects a weak match - but it DOES fire at 0.0000 when a `visibility:` filter removes the pool's BM25 maximum, and at 0.3000 with supersede fade on, i.e. it fires for reasons unrelated to match quality. `assessRecallAdequacy.sufficient` is 0.6 (`src/core/brain/recall-adequacy.ts:46`), exactly equal to the keyword weight, so every keyword hit grades `sufficient` and the `weak` and `insufficient` verdicts are unreachable; two shipped MCP tools sit on that. A gap-loop auto-close floor of 0.5 is always cleared, so gap tasks close on hits of arbitrary quality. A tier multiplier is wired into the ranker but `tierByDoc` has no producer anywhere in `src/`, so notes stamped `tier: peripheral` measure a multiplier of exactly 1. An absolute, pool-independent match-quality signal is already computed and then discarded (`idfWeightedCoverage`, `src/core/brain/coverage.ts:162-187`), and the vector lane's cosine is absolute and works correctly - the default install just has no vector lane.++4. **A write-only sink.** `src/core/brain/shared-namespace.ts` mirrors explicit remember-writes into a shared vault with contributor attribution carried twice (`agent` and `origin_vault`). `origin_vault` has zero readers repo-wide. `listSearchOrigins` (`src/core/brain/portability/origins.ts:34-73`) is the single place that enumerates which vaults participate in a read, and the shared namespace is not among them. Worse, that function silently drops an unreachable origin at `:63` before the search layer can see it, so a search across N origins with one dead origin returns as though the dead one honestly contributed nothing - and the `warnings` array that exists to report this (`src/core/search/cross-vault.ts:110`) cannot be populated because the information was already destroyed one layer up. A sibling module one layer down gets it right and documents the rule as "reported, never dropped".++5. **A mode switch whose modes already exist, unlabelled.** The tracker asked for `managed` / `passthrough` / `off` identity modes. Passthrough is the shipped, ungated default: 21 MCP tools accept a caller-supplied `agent` and stamp it verbatim, filtered only by a 22-string placeholder blocklist. Managed exists in exactly one tool. `off` has no subject, because the bottom of the resolution chain is the literal string `"agent"`, itself a placeholder.++6. **A per-agent selector that the transport cannot carry.** The instruction block returned at MCP `initialize` resolves the agent name from process env and config, never from the request; both transports share one server instance. "Per agent" therefore collapses to "per process", which the installer already provides. The sharper finding underneath: on the writer and catalog scopes the agent name is dropped before it is read (`src/mcp/instructions.ts:110-111`), so the always-loaded surface carrying the five identity-bearing writers never states which name to log under, while the full surface insists on it.++7. **An eighth egress site outside a registry built to prevent exactly that.** The repository has a mature egress boundary: `redactForEgress` (`src/core/egress/guard.ts:147`) with a three-value fail-closed verdict, a registry of seven declared sites each carrying a mandatory reason, and a census that derives the population structurally from source. `o2b brain explorer --export <path>` makes zero guard calls and is not in the registry; the census misses it because the flag name `export` is in neither of its two destination-name lists. Reproduced: an exported HTML file contained `OPENAI_API_KEY=sk-proj-...` verbatim where every other export path emits a redaction. Also reproduced: a page marked `private: true` in frontmatter with `tags: [private, confidential]` exports in full - only the inline region marker is honoured. Meanwhile the largest continuous egress in the product, raw vault chunk bodies POSTed to an operator-configured embedding endpoint, is outside the registry entirely and scanned by nothing.++8. **A census with a hole of the class its own docblock claims to have closed.** Four tests hand-roll a source lexer that blanks comments and literal contents while preserving byte offsets. One of them excludes the newline guard for backticks, so a backtick inside a regex literal opens a phantom template: measured, 9,706 of 31,608 bytes (31%) of one shipped module are blanked, and the only frozen binding in the entire tree that the vocabulary census cannot see is inside the blanked region. A positive control was built: a synthetic module containing a complete, correct four-piece vocabulary scans to empty today and is found under the shared lexer. Two of the four lexers are byte-identical copies of one another, differing only in a return type.++9. **A hook the host delivers and the repository does not register.** No delegation-boundary capture exists. `SubagentStop` is in the host's official event list and nothing subscribes. Also reproduced: sub-agent transcript lines carry the parent's session id and the adapter reads neither the agent id nor the sidechain flag, so a sub-agent transcript parses as 85 ordinary parent turns; and the tool-boundary "(task, result) pair" the tracker assumed does not exist, because the launch returns a receipt and the result arrives later out of band.++10. **A fail-closed ladder with nothing to guard.** The tracker asked for repo-visibility verification before data leaves the machine. There is no git transport in the product and the egress registry's own prose states there deliberately never will be; every `git` call in `src/` is read-only. Similarly, the tracker asked for a personal-to-team sanitisation pipeline with a history purge; there is no history to purge and the export bundle IS the staging copy. Two bidirectional bundle formats already exist, with importers on both sides.++# Project context++Open Second Brain: TypeScript on Bun, about 2,100 source files and 1,100 test files, roughly 10,300 tests. A hand-rolled JSON-RPC 2.0 MCP server with no SDK and exactly one runtime dependency. Also a Python plugin and a committed JavaScript bundle that CI byte-diffs.++Recent releases and their theses:++- v1.45.0 "silence is not an answer" - an empty result must say why it is empty.+- v1.46.0 "evidence at the boundary" - a claim crossing a surface carries what backs it.+- v1.47.0 "wiring what exists" - connect the mechanisms already built rather than adding new ones.+- v1.48.0 "nothing runs unwatched" - long operations report progress; a documented deadline that four call paths lacked; and the discovery that the census the previous release's argument rested on read no source at all.++Conventions this repository enforces mechanically, each by a test that fails the build:++- **The four-piece closed-vocabulary idiom**: a frozen object, a derived union type, a members array, and a type guard whose parameter is `unknown`, all in one module and registered in a census that scans `src/`. A guard typed `string` instead of `unknown` silently drops the vocabulary out of the audited population.+- **Census-as-durability**: a fix is considered durable only when a test enumerates the population structurally from source, so the next instance of the defect fails the build rather than relying on a reviewer noticing. Existing censuses cover write sites, destructive sites, doctor exit codes, vocabularies, progress emitters, egress sites, help-surface parity, import cycles, and layering.+- **Progress contract**: any options type accepting a deadline must also accept a progress sink, and every progress emitter must appear in a census with a drivable entry point.+- A new MCP tool trips four hardcoded lists including an exact tool count of 110.+- A new CLI verb that merely returns success fails a terminal-state census by name.+- Byte-identity of generated output is measured against the whole tree, never asserted per-file.++Constraints, from the operator, non-negotiable:++- No fallback that quietly does nothing. If there is an error, show the error explicitly.+- No stubs, no placeholders, no half-wired features. A mechanism that cannot change an outcome is the defect under review, not an acceptable outcome.+- Maximally native integration: no parallel idiom beside an existing one, no second registry where one exists, no new vocabulary shape.+- SOLID, KISS, DRY. Anything extractable becomes a named constant or variable.+- No hardcoded natural-language word lists in any language; language-dependent behaviour must be expressed structurally.+- Everything user-facing in English.+- The release must be implementable test-first, unit by unit, in one branch, by several agents working in parallel on separate files.++# Required output format++Produce exactly 3 distinct architectural variants for how to organise this release. The variants should differ in what the ORGANISING PRINCIPLE is - what unifies ten findings into one release, what mechanism (if any) is built to hold them together, and what is deliberately left out - not merely in which files get touched.++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/a-label-is-not-a-boundary/design.md b/docs/brainstorm/a-label-is-not-a-boundary/design.mdnew file mode 100644index 00000000..ebb40126--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/design.md@@ -0,0 +1,253 @@+# A label is not a boundary - put a check behind every declared boundary, or retract the declaration++**Status:** draft+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Ten tracker items, selected by priority off the board and read against the real+source before anything was designed, turn out to describe one defect seen from+ten sides: the product declares a boundary and puts nothing behind it. An+owner-isolation filter whose field no writer ever emits. A gate that enforces+the scope the caller asked for. A confidence floor compared against a number+that cannot vary with match quality. A shared namespace written twice over with+attribution nobody reads. An egress registry built to stop an unguarded export,+with an unguarded export outside it. A census whose docblock claims to have+closed the mis-parse class that is live inside it.++Reconnaissance corrected most of the ten task bodies. Six of the corrections+changed what the unit is, not merely how it is worded; two findings turned out+to be the opposite of what was filed; one is a live credential leak on a shipped+path and one is a live authorisation defect. The corrected findings, with their+anchors and the measurements that produced them, are in `recon/`.++## Scope++Ten units. Each takes one declared boundary and does exactly one of three+things, chosen by evidence rather than by preference:++- **ENFORCE** - the label names a real boundary and nothing checks it; put the+ check where the data is aggregated, and put a census behind the check so the+ next instance fails the build.+- **RE-MEASURE** - the check exists and measures the wrong quantity; swap in the+ signal that varies with what the label claims, where such a signal is already+ computed and discarded.+- **RETRACT** - the label has no subject in this product; delete it and say so.+ A mechanism that cannot change an outcome is the defect under review, so+ keeping it "for later" is not available.++| # | Unit | Verdict | Tracker |+| --- | --- | --- | --- |+| U1 | Ownership is written, or it is not a boundary | ENFORCE | t_b18551b1 |+| U2 | Identity is resolved, never echoed | ENFORCE | t_b18551b1, t_3ebb6e0e |+| U3 | The scope matrix asserts correctness | ENFORCE | t_b18551b1 |+| U4 | Four thresholds against a pinned number | RE-MEASURE + RETRACT | t_eb94ac35 |+| U5 | The write-only sink gets a reader | ENFORCE | t_a160764a, t_77efc212 |+| U6 | The writer surface states its own name | ENFORCE | t_f2ede668 |+| U7 | The delegation boundary the host already delivers | ENFORCE | t_0c6f31ee |+| U8 | The eighth egress site | ENFORCE | t_09a3752a, t_08f6ffca |+| U9 | One lexer, and the hole in the live one | RE-MEASURE | t_1d4f932f |+| U10 | Retractions, stated with their evidence | RETRACT | t_09a3752a, t_08f6ffca, t_3ebb6e0e, t_77efc212, t_f2ede668 |+| U11 | The contract honoured at three sites of forty-one | ENFORCE | found in recon |+| U12 | The small ones, each with its own failing test | ENFORCE | found in recon |++Two units carry no tracker item. They are here because reconnaissance found+them, the operator's standing rule is that problems seen along the way are+fixed rather than deferred, and U11 in particular is this release's own thesis+on the same surface: a contract stated at one site and honoured at three of+forty-one.++## Out of scope++Deliberately, each with the evidence that decided it:++- **A git-visibility ladder** (asked for by t_09a3752a). There is no git+ transport in the product; every `git` invocation under `src/` is read-only,+ and `src/core/egress/registry.ts:6-8` states in prose that the vault "has no+ git transport and deliberately never will". A fail-closed check needs+ something to guard. U10 records this; U8 retargets the fail-closed shape at+ the destinations that do exist.+- **A staging copy and a history purge** (asked for by t_08f6ffca). There is no+ history to purge, and the export bundle already is the staging copy. Two+ bidirectional bundle formats exist with importers on both sides.+- **An `off` identity mode** (asked for by t_3ebb6e0e). The bottom of the+ identity chain is already the literal string `"agent"`, itself a placeholder;+ `off` has no subject distinct from it.+- **De-normalising the keyword lane.** Measured blast radius: every score in the+ product moves and four thresholds flip at once. U4 gates the floor on a signal+ that is already absolute instead.+- **A per-agent instruction block.** Not reachable over either transport: both+ resolve identity from process env and config, never from the request, so "per+ agent" collapses to "per process", which the installer already provides. There+ is also nowhere to declare a multi-line block - the config reader rejects+ nesting past two levels and has no block-scalar form.+- **An eleventh census over "declared boundaries" in general.** The population is+ semantic, not structural; deriving it would need a declaration surface and a+ mandatory-reason field beside the four-piece vocabulary idiom, which is the+ parallel-idiom this repository forbids. Each unit lands its assertion inside+ the census that already owns its class.+- **A fleet view with three metrics.** Open task count has no referent in this+ product; there is no `open_tasks` anywhere in `src/`. U5 ships the two metrics+ that are computable and says the third does not exist.++## Chosen approach++Variant 3 of three, with one correction and one graft.++### Agreement with the recommendation++The consultant recommended disposition triage on the strength of its empty+critical path, and that holds against the source: the ten units touch largely+disjoint files, each has a definition of done anchored at a specific+`file:line`, and only the lexer extraction has a shared owner. Variant 1 defers+scope to whatever the repaired instruments turn red, which is not a scope at all+for a single branch. Variant 2's eleventh census is the parallel idiom the+operator's constraints forbid, and its own trade-offs predict the failure: "a+registry whose membership check is weaker than what it claims to enforce is+precisely the defect under review".++### The correction++Variant 3 lists "no single new mechanism guards the eleventh instance" as an+accepted cost, and this repository's own doctrine says a fix without a census is+not durable. The cost is not accepted here. Finding 1 already names the missing+mechanism precisely: `tests/mcp/agent-scope-matrix.test.ts` asserts that every+one of 110 tools is classified exactly once and never that a classification is+correct. Turning `NON_CONTENT: string[]` into `{name, args, reason}[]` and+driving every entry against a two-owner fixture is a structurally-derived+enforcement census - and it is an extension of the test that already owns the+class, not an eleventh registry. That is U3, and it is what makes U1 durable.++### The graft++Variant 2's principle survives inside U3 and U8: a bucket without a per-surface+assertion is another label with nothing under it, so every ENFORCE unit ships+its assertion in the same commit as its check. U8 additionally widens the+existing egress census's destination derivation, because the census missed the+eighth site through a hardcoded name list - which is the same defect class the+census exists to catch, one level up.++### Why RETRACT is a first-class outcome here++The operator's constraint is that a fallback which quietly does nothing is+forbidden and an error must be shown explicitly. A knob that cannot change an+outcome is the silent-fallback defect in configuration form: an operator sets+it, reads no error, and believes a boundary exists. Deleting it is the honest+disposition, and U10 records each deletion with the measurement that justified+it rather than performing it quietly.++One exception is written into the tracker and is honoured: t_eb94ac35 states+that `below_floor` must not be closed by deleting the vocabulary member, because+the member describes a state the system should be able to reach. U4 therefore+re-measures rather than retracts - after the change the floor fires when the+match is genuinely weak, which is what the member always claimed.++## Design decisions++- **Owner is the writing agent identity, resolved server-side.**+ `src/core/graph/agent-scope.ts:23-24` already rules that owner tokens are+ agent names. The alternative - a human owner distinct from the agent - has no+ representation anywhere in the vault and would be an invention.+- **Emission of `owner:` is conditioned on the gate, not unconditional.** A+ vault that has not enabled owner-scope delivery must stay byte-identical, so+ the writer stamps ownership only where the boundary is switched on. Measured+ with the vault-digest helper over the whole tree, not asserted per file.+- **A conflicting caller-supplied identity is an error, not a silent+ narrowing.** With the gate on, a caller naming an owner other than the+ resolved identity receives a typed refusal that names the conflict. Silently+ substituting the correct scope would leave the caller believing it read what+ it asked for.+- **The recall floor is gated on IDF-weighted coverage**, which is absolute,+ pool-independent, in `[0,1]`, and already computed today in evidence-pack mode+ before being discarded. No score moves; the floor starts measuring match+ quality instead of pool position.+- **An unreachable origin is reported, never dropped.** The sibling module one+ layer down already documents this rule; `origins.ts` undoes it. The verdict is+ a four-piece closed vocabulary registered in the vocabulary census.+- **The shared namespace becomes enumerable as a read origin**, which produces+ the reader that a named shared scope has now failed twice for lack of, and+ gives `origin_vault` its first consumer.+- **One lexer under `tests/helpers/`, taken verbatim from the more general of+ the two identical copies**, with the backtick newline-guard hole closed. The+ helper gets its own tests, which no helper in that directory has today; the+ populations each census enumerates are run and compared before and after, not+ read from a comment, because no census asserts an exact count.+- **The embedding endpoint is declared as an egress site.** It is the largest+ continuous egress in the product and is currently outside the registry+ entirely. Declaring it with its mandatory reason is what the registry is for;+ whether it is scanned is a separate, stated decision.+- **`SubagentStop` is registered and the session turn carries both ids.** The+ additive-field path is the one `docs/observability.md:73` already commits to.++## File changes++New:++- `tests/helpers/source-lexer.ts`, `tests/helpers/source-lexer.test.ts`+- a reachability vocabulary module beside `src/core/brain/portability/origins.ts`+- an owner-conflict refusal vocabulary beside the scope coercion it guards+- recon notes and this design set under `docs/brainstorm/a-label-is-not-a-boundary/`++Modified, by unit (paths verified against the tree at `f02c1fd3`, after a spec+review corrected nine of them): `src/core/brain/preference.ts` and the five+writers that omit `owner`; `src/mcp/coerce.ts`,+`src/core/brain/preferences-collect.ts`; `tests/mcp/agent-scope-matrix.test.ts`,+`src/core/search/store/links.ts`, `src/core/brain/backlinks.ts`,+`src/core/brain/notes/scaffold-stub.ts`,+`src/core/brain/link-graph/moc-audit.ts`,+`src/core/brain/link-graph/unlinked-mentions.ts`;+`src/core/brain/recall-inject.ts`, `src/core/brain/recall-adequacy.ts`,+`src/core/search/coverage.ts`, `src/core/brain/gaps/gap-loop.ts`,+`src/core/bench/failure-modes.ts`, `src/core/search/ranker.ts`,+`src/core/search/pipeline/assemble.ts`, `src/core/brain/page-meta/tier.ts`;+`src/core/brain/portability/origins.ts`, `src/core/search/cross-vault.ts`,+`src/core/brain/shared-namespace.ts`, `src/core/brain/agent-source/*`;+`src/mcp/instructions.ts`, `src/mcp/tool-contract.ts`, `src/mcp/http.ts`;+`hooks/hooks.json`, `src/core/brain/session-lifecycle.ts`,+`src/core/brain/sessions/*`; `src/cli/brain/verbs/explorer.ts`,+`src/core/brain/explorer.ts`, `src/core/egress/registry.ts`,+`tests/core/architecture/egress-census.test.ts`,+`src/core/brain/portability/okf.ts`, `src/core/brain/export.ts`,+`src/core/redactor.ts`, `src/core/search/embeddings/openai-compat.ts`;+`src/mcp/tools.ts` and the ten tool modules emitting `vault_path`; the four+census tests that hand-roll a lexer, plus the layering and reader censuses.++Docs: `docs/observability.md`, `docs/architecture.md`, `docs/mcp.md`,+`docs/cli-reference.md`, `docs/how-it-works.md`, `README.md`, `CHANGELOG.md`.++## Risks and open questions++Three of the five risks this document first listed were open questions with two+possible answers. A spec review against the source closed them; they are+recorded here as decisions, because an implementing agent must not have to ask.++- **The scope matrix probe is the highest-variance unit, and stays open.**+ Driving the classified tools against a two-owner fixture may surface leaks+ beyond the ten already named. The unit's budget must absorb that. All ten+ named leaks must close; an additional one is either fixed or moved to the+ unscoped bucket with a reason of the specificity the existing entries carry.+- **The digest cannot reach another branch.** `tests/helpers/vault-digest.ts`+ hashes a tree in the current process, so "byte-identical to `main`" is not+ writable. The measurement is between two vaults written by one fixture script+ under a pinned clock and vault id, with owner stamping on and off, compared by+ `digestVaultTree` and `changedPaths`.+- **The tier multiplier is wired, not retracted.** `src/core/brain/page-meta/tier.ts:38-45`+ documents `tier` as a multiplicative ranker weight and `:8-9` justifies the+ default value by ranker bit-identity, so the label has a subject in shipped+ source and the missing half is the producer. The untagged fixture corpus+ cannot move, because the default multiplier is 1.0.+- **`private: true` in frontmatter is retracted, not enforced.** The+ `<private>` region marker is the product's only content-derived privacy+ primitive; nothing under `portability/` reads the frontmatter key, and the+ export composers are content composers rather than visibility filters. A test+ asserts the page exports in full, so the label cannot be re-read as a+ boundary, and the registry reason strings say which primitive is the real one.+- **The lexer migration can produce a false clean.** Routing an import-specifier+ read through the wrong view drops a census from 64 rows to zero with an empty+ failure list. A test that pins the specifier-preserving view is mandatory.+- **The egress census cannot express a network destination.** Its population is+ derived from a file-destination parameter plus a raw file write, so declaring+ the embedding endpoint under the existing rule fails the+ declaration-outlives-module assertion. U8 adds a second population rule and+ proves it with a synthetic network-destination module.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/plan.md b/docs/brainstorm/a-label-is-not-a-boundary/plan.mdnew file mode 100644index 00000000..963ec1a8--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/plan.md@@ -0,0 +1,454 @@+# A label is not a boundary - implementation plan++Twelve units carrying ten tracker items. Each unit is one atomic commit or a+short sequence of them, test-first. Units marked **independent** may run in+parallel; the rest name what they depend on. Every acceptance line is a test+that fails before the change and passes after; a claim without a failing test+first is not accepted.++This plan was revised after a spec review that verified every number and path+against the source at `f02c1fd3`. Seven acceptance lines were unachievable as+first written and are corrected here; nine file paths were wrong and are+corrected here. Where a line says "fails today", the review confirmed it.++## Standing rules for every unit++From the operator and from this repository:++- No fallback that quietly does nothing. An error is shown explicitly, with the+ information that diagnoses it. A bare `catch { continue }` or+ `catch { return "failed" }` destroys the diagnosis and is forbidden.+- No stubs, no placeholders, no half-wired features.+- Maximally native: extend the registry, census or vocabulary that already owns+ the class. No parallel idiom, no second registry.+- A new closed vocabulary ships all four pieces in one module - frozen object,+ derived union type, members array, type guard whose parameter is `unknown` -+ and is registered in `CENSUS` in+ `tests/core/architecture/verdict-vocabulary-census.test.ts`. There is no+ exemption list.+- Any options type accepting a `Safeguard` also accepts `onProgress?:+ ProgressSink`; every `progressCounter(` site is registered in the emitter+ census with a drivable entry point.+- Anything extractable becomes a named constant. No natural-language word lists+ in any language.+- Defects noticed in passing are fixed in the same unit, not deferred.+- Format and lint are green before every commit. Commit with the pathspec form+ `git commit --only <paths>` so another agent's staged work is never swept in.+ Never `git commit --amend` - another agent may own the tip.++### Shared files, and how to not lose another agent's work++Several units edit the same three test files. Every unit works in ONE shared+working tree, so there is no merge conflict to resolve - there is only the+hazard of a stale overwrite. Rules:++- Never `Write` a file another unit also edits. Re-read it immediately before+ each change and use `Edit` against a unique anchor.+- `tests/core/architecture/verdict-vocabulary-census.test.ts` - U2, U5, U6, U9+ all append to `CENSUS` or edit the masker. Append at the end of the array,+ one entry per unit.+- `tests/mcp/agent-scope-matrix.test.ts` - U2 changes behaviour the fixture+ asserts, U3 rewrites the bucket shape. U3 depends on U2 for this reason.+- `src/core/brain/portability/okf.ts`, `src/core/redactor.ts` - U8 only.++## Tasks++### U1: Ownership is written, or it is not a boundary+- **Tracker**: t_b18551b1+- **Verdict**: ENFORCE+- **Files**: `src/core/brain/preference.ts`; `src/mcp/brain/feedback-tools.ts`;+ `src/cli/brain/verbs/feedback.ts`; `src/core/brain/derived-fact.ts`;+ `src/core/brain/merge.ts`; `src/core/brain/preference-txn.ts`;+ `src/core/graph/agent-scope.ts`+- **Acceptance**:+ - With `integrity.owner_scope_delivery` enabled, a preference written through+ each of the five production writers carries `owner:` equal to the+ server-resolved agent identity. A test drives all five and fails today on+ all five, because `writePreference` emits the field only when a caller+ supplies it (`preference.ts:446,553`) and no production caller does.+ - No new config key. Owner stamping is conditioned on the existing+ `integrity.owner_scope_delivery` gate, which is already templated and+ already commented (`config-template.ts:410`); a test pins that+ `brainConfigKnownKeys()` gained no entry.+ - With the gate off, a vault written by a fixture script under a pinned clock+ and pinned vault id has `digestVaultTree` equal to a second vault written by+ the same script with owner stamping forced off, and `changedPaths` between+ them is empty. Additionally, no file under `Brain/preferences/` contains an+ `owner:` line. (`vault-digest.ts` hashes trees in one process and cannot+ reach another branch, so the comparison is between two vaults here, not+ against `main`.)+ - `isOwnerVisible` returning false is ALREADY exercised at+ `tests/mcp/agent-scope-matrix.test.ts:228-234,367-374` using a hand-supplied+ `owner`. The new assertion is that the same withholding occurs on a vault+ written entirely through production surfaces, with no test-only owner+ argument anywhere in the fixture.+- **Depends on**: none (**independent**)++### U2: Identity is resolved, never echoed+- **Tracker**: t_b18551b1, t_3ebb6e0e+- **Verdict**: ENFORCE+- **Files**: `src/mcp/coerce.ts`; `src/core/brain/preferences-collect.ts`;+ `src/core/agent-identity.ts`; a new refusal vocabulary module;+ `tests/core/architecture/verdict-vocabulary-census.test.ts` registration;+ `tests/mcp/agent-scope-matrix.test.ts`+- **Acceptance**:+ - With `integrity.owner_scope_delivery` set to fail, a caller supplying an+ `agent_scope` naming an owner other than the server-resolved identity+ receives a typed refusal naming the conflict. The test proves the old+ behaviour first: today `coerceAgentScope` (`coerce.ts:120-121`) returns the+ argument unconditionally and `resolveOwnerScopeDelivery`+ (`preferences-collect.ts:182`) enforces the requested scope, so the caller+ receives that owner's private preferences.+ - A caller supplying no scope, and a caller supplying its own identity, are+ unaffected; both asserted.+ - With the gate off, behaviour is unchanged; a test pins that.+ - The refusal vocabulary passes the four-piece census with its guard typed+ `unknown`, registered in `CENSUS`.+ - The tools that stamp a caller-supplied `agent` verbatim are enumerated+ STRUCTURALLY from `buildToolTable`, never hand-written - a hand-written list+ is the exact defect this release is about. The test asserts the count and+ fails when a tool joins or leaves the set.+ - `agent-scope-matrix.test.ts:447-456` drives `brain_retrieval_plan` with a+ foreign `agent_scope` under a failing gate; that call now refuses, and the+ fixture is updated with the reason written in.+- **Depends on**: none (**independent**)++### U3: The scope matrix asserts correctness, not partition+- **Tracker**: t_b18551b1+- **Verdict**: ENFORCE+- **Files**: `tests/mcp/agent-scope-matrix.test.ts`;+ `src/core/search/store/links.ts`; `src/core/brain/backlinks.ts`;+ `src/core/brain/notes/scaffold-stub.ts`;+ `src/core/brain/link-graph/moc-audit.ts`;+ `src/core/brain/link-graph/unlinked-mentions.ts`;+ `src/mcp/brain/hygiene-tools.ts`+- **Acceptance**:+ - The unasserted bucket becomes `{name, args, reason}[]`: every entry carries+ the arguments that drive it and a written reason for its classification. The+ classification test at `:299-311`, which spreads the buckets as strings, is+ updated with it.+ - One two-owner fixture drives every entry and asserts no cross-owner marker+ appears in the response. The test fails today naming the ten tools listed in+ `recon/owner-scope-isolation.md` section C6. After the change all ten return+ no cross-owner marker; any ADDITIONAL leak the probe surfaces is either+ fixed or moved to `UNSCOPED_CONTENT` with a reason of the length and+ specificity the existing entries carry.+ - `listDanglingTargets` takes an optional owner scope and drops whole targets,+ not only sources; `buildBacklinkIndex` takes an optional second parameter+ and its nine call sites still compile untouched.+ - Adding a tool to the matrix without arguments fails the build; a test proves+ it, so the bucket cannot regrow as a bare name list.+ - `buildBacklinkIndex`'s `catch { continue; }` (`backlinks.ts:193-195`), which+ returns a confident `count: 0` on legacy frontmatter, reports the failure+ instead. A test drives a legacy-frontmatter preference and asserts the+ report.+ - The probe needs the `{ force: true }` index precondition+ (`notes/scaffold-stub.ts:172-180`) and pins `HOME` per file; nothing pins it+ globally.+- **Depends on**: U1 (needs a vault where ownership exists), U2 (same fixture+ file, and U2 changes what a gated call returns)++### U4: Four thresholds against a pinned number+- **Tracker**: t_eb94ac35+- **Verdict**: RE-MEASURE+- **Files**: `src/core/brain/recall-inject.ts`; `src/core/search/coverage.ts`;+ `src/core/brain/recall-adequacy.ts`; `src/core/brain/gaps/gap-loop.ts`;+ `src/core/bench/failure-modes.ts`; `src/core/search/ranker.ts`;+ `src/core/search/pipeline/assemble.ts`;+ `src/core/brain/page-meta/tier.ts`; `src/core/search/cross-vault.ts`+- **Acceptance**:+ - The recall floor is evaluated against IDF-weighted coverage+ (`src/core/search/coverage.ts:162-187`), which is absolute and+ pool-independent. A test drives a deliberately weak match through the+ shipped retriever and gets `below_floor`; a strong match does not. Both fail+ today.+ - No search score moves: the ranker's ordered `(path, score)` list over the+ committed fixture corpus is unchanged, pinned as a literal expectation and+ compared before and after within the same commit.+ - Through `brain_recall_gate` and `brain_context_pack` on a default+ keyword-only vault, a deliberately weak match yields `weak` and a no-match+ yields `insufficient`. Today both yield `sufficient`, because+ `DEFAULT_RECALL_ADEQUACY_THRESHOLDS.sufficient` (0.6) equals the shipped+ `keywordWeight` (0.6) and `normalizeBm25` pins the top row at 1. The+ end-to-end test is the failing one; the pure function is already covered at+ `tests/core/brain/recall-adequacy.test.ts` and must stay green.+ - The gap-loop auto-close floor rejects a low-quality hit; a test drives it.+ - The `0.65` at `src/core/bench/failure-modes.ts:40` is corrected to the real+ `keywordWeight` (`src/core/search/index.ts:154`), and a test ties the stated+ number to the constant so it cannot drift again.+ - The tier producer is wired, not retracted: `page-meta/tier.ts:38-45`+ documents `tier` as a multiplicative ranker weight and `:8-9` justifies the+ default by ranker bit-identity, so the label has a subject and the plumbing+ is the missing half. `collectCandidateSignals` gains a tier collector and+ `rankCandidates` (`pipeline/assemble.ts:390-441`) passes `tierByDoc`. Blast+ radius is measured as the score delta on a tier-tagged fixture; the untagged+ fixture corpus cannot move because `supporting` is 1.0.+ - `search_chain_stop_score` (`cross-vault.ts:200`) means opposite things under+ the two fusion modes - unreachable in one, always met in the other. It is+ resolved in this unit, and the commit message states which way and why.+ - If `idfWeightedCoverage` is surfaced on the search outcome, every MCP tool+ with a declared `outputSchema` is validated at request time+ (`server.ts:466`); the new field must satisfy those contracts.+ `recall_adequacy_sufficient` and siblings (`src/core/config.ts:850-868`) are+ operator-facing and change meaning, so `docs/cli-reference.md` is updated.+- **Depends on**: none (**independent**)++### U5: The write-only sink gets a reader+- **Tracker**: t_a160764a, t_77efc212+- **Verdict**: ENFORCE+- **Files**: `src/core/brain/portability/origins.ts`;+ `src/core/search/cross-vault.ts`; `src/core/brain/shared-namespace.ts`;+ `src/core/brain/agent-source/types.ts`, `query.ts`; `src/core/config.ts`;+ a new reachability vocabulary module; census registration+- **Acceptance**:+ - An unreachable origin is reported rather than dropped at+ `origins.ts:63`: a search across three origins with one unreachable returns+ a warning naming it. The `warnings` array at `cross-vault.ts:110` cannot be+ populated at all today because the information is destroyed one layer up.+ - The reachability verdict is a four-piece vocabulary distinguishing+ reachable, unreachable and unknown; a test proves unreachable and unknown+ are different values and neither reads as a zero contribution.+ - The shared namespace is enumerable as a read origin, and a test reads back a+ record written through the mirror carrying its `origin_vault` - the field's+ first reader anywhere in the repository.+ - `mirrorSignal` and `mirrorNote` (`shared-namespace.ts:52-54,80-83`) no+ longer discard the failure reason; a test drives a write failure and asserts+ the reason reaches the caller. `MirrorOutcome` stops conflating operator+ misconfiguration with I/O failure under one token, and becomes a four-piece+ vocabulary registered in `CENSUS` rather than a two-piece type alias outside+ the audited population.+ - `resolveAgentName`'s fallback to the literal `"agent"` (`config.ts:379`)+ merges every unconfigured install into one roster row that reads as a very+ busy agent. The fallback is made explicit: the roster reports an+ unconfigured identity as unconfigured rather than as a name.+ - The per-agent roster gains `last_activity`. The summary type declares+ exactly `contribution_count` and `last_activity`; a test asserts the+ returned key set equals that pair, so a third metric cannot be added without+ changing the assertion, and the docblock records that no open/closed unit of+ work exists in this product.+ - The tracker asked for a fleet surface. The surface already exists -+ `brain_agent_query` and `brain_agent_diff` - so no new tool is added; what+ was missing was the metrics and the honesty about the third. The unit+ records that reasoning in the test, and `AgentSourceSummary` gaining a field+ must satisfy `brain_agent_query`'s output contract.+- **Depends on**: none (**independent**)++### U6: The writer surface states its own name+- **Tracker**: t_f2ede668+- **Verdict**: ENFORCE+- **Files**: `src/mcp/instructions.ts`; `src/mcp/tool-contract.ts`;+ `src/mcp/tools.ts`; `src/cli/main.ts`; `src/core/identity-reminder.ts`;+ `src/mcp/http.ts`; `scripts/measure-token-surface.ts`; `tests/mcp/mcp.test.ts`+- **Acceptance**:+ - The writer and catalog instruction branches carry the identity line; a test+ asserts the resolved agent name appears on all three scopes and fails today+ on two, because `instructions.ts:110-111` returns before `agent` is read.+ - The declared-but-never-read `vault` option (`:26-27`) and the dead+ string-argument branch (`:105-107`) are removed; `tests/mcp/mcp.test.ts:792-793`+ and `scripts/measure-token-surface.ts:62-63` are updated with them, and the+ always-loaded token surface the script measures is re-measured and recorded.+ - `ToolScope`'s members, hand-copied into four places with nothing asserting+ agreement (`tool-contract.ts:19`, `tools.ts:378`, `cli/main.ts:629`,+ `cli/main.ts:762`), are promoted to the four-piece idiom and registered in+ `CENSUS`; the four sites derive from it.+ - `isRuntimeTarget` (`identity-reminder.ts:45`) takes `unknown`, as the idiom+ requires, not `string | undefined`.+ - `src/mcp/http.ts:166` stops advertising an `mcp-session-id` nothing reads:+ either it is read or it is not minted, and a test pins the choice.+- **Depends on**: none (**independent**)++### U7: The delegation boundary the host already delivers+- **Tracker**: t_0c6f31ee+- **Verdict**: ENFORCE+- **Files**: `hooks/hooks.json`; `hooks/README.md`;+ `hooks/lib/context-events.ts`; `src/core/brain/session-lifecycle.ts`;+ `src/core/brain/sessions/claude.ts`, `import.ts`, `registry.ts`;+ the session turn type; `docs/observability.md`+- **Acceptance**:+ - `SubagentStop` is registered - it is in the host's official event list and+ `hooks/hooks.json` registers seven events without it - and its payload is+ normalised. A test drives the hook with the captured payload shape.+ - `SessionTurn` carries the agent id and the sidechain flag. A committed+ fixture under `tests/fixtures/sessions/` holds a parent transcript plus a+ sidechain file with `isSidechain: true` and a distinct `agentId` under the+ same `sessionId`; the test asserts the parent turn count excludes the+ sidechain turns and that the flag is set. The count is whatever the+ committed fixture holds, pinned in the test.+ - `tool_response`, declared in the hook payload and dropped by+ `normalizePayload` (`session-lifecycle.ts:563-568`), is either carried or+ removed from the declaration; a test pins the choice, and if it is carried,+ the payload-safety rules in `docs/observability.md` are updated with it.+ - `--agent` on `o2b brain import-session` is honoured rather than validated+ and discarded (`import.ts:601-604`); the intentional-precedence docblock at+ `:597-600` changes with the behaviour, and `agentLabelForTurn`'s unused+ `turn` parameter becomes the seam that carries the sub-agent label.+ - Three of five session adapters stamp `claude`, `codex` and `hermes`, which+ `normalizeAgentArgument` rejects as non-identities everywhere else. The+ contradiction is resolved in this unit and a test asserts the two surfaces+ agree.+- **Depends on**: none (**independent**)++### U8: The eighth egress site+- **Tracker**: t_09a3752a, t_08f6ffca+- **Verdict**: ENFORCE+- **Files**: `src/cli/brain/verbs/explorer.ts`; `src/core/brain/explorer.ts`;+ `src/core/egress/registry.ts`; `src/core/egress/guard.ts`;+ `tests/core/architecture/egress-census.test.ts`; `src/core/redactor.ts`;+ `src/core/brain/export.ts`; `src/core/brain/portability/okf.ts`;+ `src/core/search/embeddings/openai-compat.ts`+- **Acceptance**:+ - `o2b brain explorer --export` calls `redactForEgress`. A test exports a+ vault containing a credential and asserts the redaction marker; today the+ credential appears verbatim while every other export path redacts it.+ - The egress census's file-destination derivation is widened so the flag that+ hid the eighth site cannot hide a ninth: `export` joins `DESTINATION_FLAGS`+ (`egress-census.test.ts:96-118`), and a synthetic destination flag proves+ the census fails until the site is declared.+ - The census gains a SECOND population rule for network destinations - a+ module POSTing vault-derived bytes to an operator-configured URL - because+ the existing derivation (`:164-171`) requires a file-destination parameter+ and a raw file write, so a network site cannot be declared under it without+ failing `:196-201`. `src/core/search/embeddings/openai-compat.ts` is+ declared under the new rule with a reason stating that chunk bodies leave+ unscanned. A synthetic network-destination module proves the rule fires.+ - Every new `EGRESS_SITES` entry satisfies `:204` (declared-as-redacting+ implies a `redactForEgress` call), `:217` (guard calls at least equal+ destination count) and `:241` (no entry understates its module).+ - `private: true` frontmatter is retracted as a privacy claim: the+ `<private>` region marker in `continuity/redaction.ts` is the product's only+ content-derived privacy primitive, nothing under `portability/` reads the+ frontmatter key, and the export composers are content composers rather than+ visibility filters. The registry reason strings state that the region marker+ is the only primitive, and a test asserts a `private: true` page exports in+ full, so the label cannot be re-read as a boundary.+ - The redactor no longer eats signal ids: a round trip exports and imports a+ preference whose `_evidenced_by` link survives, which fails today because+ `HIGH_ENTROPY_TOKEN_RE` (`src/core/redactor.ts:337-338`) consumes+ `sig-<date>-<slug>`. The carve-out follows the existing `CONTENT_ADDRESS_RE`+ precedent and its effect on `redactSecrets` in the CLI `--json` path+ (`json-helpers.ts:75-86`) is asserted by+ `tests/cli/cli-json-contract.test.ts`.+ - `export.ts:106-107,118-119` and `explorer.ts:105-108` no longer silently+ continue past a parse failure; a test drives a malformed preference and+ asserts a non-zero exit and a message naming the file. The new exit code+ lands in the terminal-state census, and `CliError` exits 1 under+ `o2b brain` (`src/cli/brain.ts:462-467`), not 2.+ - `okf.ts:334`'s date pattern matches only the legacy un-sharded log name+ while `log.ts:113-114` writes `<date>.<deviceId>.md`, so `log.md` is empty+ on every default install. A test exports a vault with one log day and+ asserts it is present.+- **Depends on**: none (**independent**)++### U9: One lexer, and the hole in the live one+- **Tracker**: t_1d4f932f+- **Verdict**: RE-MEASURE+- **Files**: `tests/helpers/source-lexer.ts` (new);+ `tests/helpers/source-lexer.test.ts` (new);+ `tests/core/architecture/destructive-site-census.test.ts`;+ `tests/core/architecture/progress-census.test.ts`;+ `tests/core/architecture/verdict-vocabulary-census.test.ts`;+ `tests/cli/progress-emitter-census.test.ts`;+ `tests/core/architecture/write-site-census.test.ts`;+ `tests/core/layering.test.ts`;+ `tests/core/brain/continuity/reader-census.test.ts`+- **Acceptance**:+ - One helper exports the two views, taken verbatim from the more general of+ the two byte-identical copies. Its own tests cover the regex literal+ containing a quote, the regex literal containing a backtick, the brace in a+ string, the brace in a comment, division mistaken for a regex opener, an+ escaped backslash before a quote, and a nested template interpolation. No+ helper in `tests/helpers/` has its own test today, so this establishes the+ convention.+ - The backtick newline-guard hole at+ `verdict-vocabulary-census.test.ts:1085` is closed. The positive control - a+ synthetic module carrying a complete four-piece vocabulary inside a region+ the live masker blanks - is found after the change and not before.+ - Populations are run before and after and compared: 10 safeguard-bearing+ options types, 57 `CENSUS` entries, 461 modules with 31 destructive sites,+ 129 write-site rows with 64 direct, **8** emitter sites. No census loses a+ rule. (The task body says nine emitters; the census asserts set equality+ against eight, and the ninth is the declaration site itself.)+ - A test pins that the comment-stripped view preserves import specifiers.+ Routing that read through the other view drops the write-site census from 64+ rows to zero with an empty failure list, which is the false-clean signature+ these censuses exist to prevent.+ - Count floors become equalities where a floor hides a drifted reality:+ `verdict`'s `toBeGreaterThan(50)` against 57, and+ `MIN_DIRECT_STORE_READERS = 20` against 21.+ - `tests/core/layering.test.ts:39-42` decides "is a comment" from a line+ prefix, which both over- and under-matches; it routes through the helper,+ and its population is compared before and after like the others.+- **Depends on**: none (**independent**)++### U10: Retractions, stated with their evidence+- **Tracker**: t_09a3752a, t_08f6ffca, t_3ebb6e0e, t_77efc212, t_f2ede668+- **Verdict**: RETRACT+- **Files**: `docs/architecture.md`, `docs/observability.md`, `docs/mcp.md`,+ `CHANGELOG.md`, and the dead declarations U4, U6 and U8 identify+- **Acceptance**: each of the following is recorded with the measurement that+ justified it, and no retraction leaves a dangling reference (the link ratchet+ has zero headroom at 22/22 on `templates/brain-starter`):+ - The git-visibility ladder: no git transport exists and+ `src/core/egress/registry.ts:6-8` states there deliberately never will be;+ every `git` call under `src/` is read-only.+ - The staging copy and history purge: no history to purge, and the export+ bundle already is the staging copy.+ - The `off` identity mode: the bottom of the chain is already the literal+ `"agent"`, which is itself a placeholder, so `off` has no distinct subject.+ - The `passthrough` and `managed` mode vocabulary: passthrough is the shipped,+ ungated default across the tools that accept a caller-supplied `agent`, and+ U2 is what makes it gateable. The mode names are not adopted, and the reason+ is recorded rather than left implicit.+ - The per-agent instruction block: not reachable over either transport, and+ the config reader has no block-scalar form to declare one in.+ - The `shared` observation-scope member: a positive scope that no reader+ requests narrows visibility rather than widening it. U5 builds the first+ reader of a foreign origin, and the disposition records that a shared scope+ is reconsidered only once a reader requests one by name.+ - Whatever U8 resolves for `private:` frontmatter, and whatever U4 resolves+ for `search_chain_stop_score`.+- **Depends on**: U4, U6, U8++### U11: The contract honoured at three sites of forty-one+- **Tracker**: none - found during reconnaissance for t_b18551b1+- **Verdict**: ENFORCE+- **Files**: `src/mcp/tools.ts`; the ten `src/mcp/brain/*-tools.ts` modules that+ emit `vault_path`; a new census assertion+- **Acceptance**:+ - `src/mcp/tools.ts:94-119` states the contract for what a `vault_path` may+ contain; 41 sites emit the raw absolute host path and 3 honour it. A test+ enumerates the emitting sites structurally from source and asserts each+ honours the contract; it fails today naming 38.+ - The substitution is mechanical and changes no tool's schema.+ - This is the same shape as U3 - a rule with no enumeration behind it - on the+ same tool surface, which is why it ships here rather than as a follow-up.+- **Depends on**: none (**independent**)++### U12: The small ones, each with its own failing test+- **Tracker**: none - found during reconnaissance+- **Verdict**: ENFORCE+- **Files**: `src/mcp/brain/admin-tools.ts`; the `schema_inspect` handler;+ `src/core/brain/secrets/store.ts`; `src/core/time.ts`+- **Acceptance**:+ - `schema_inspect view=lint` and `view=orphans` currently die on the malformed+ artifact they exist to report, and the message carries an absolute host+ path. They report the artifact instead; a test drives a malformed artifact.+ - `brain_labels {operation:"show", id}` errors with "path must be a+ vault-relative string" for an argument named `id`; the mismatch is resolved+ and a test drives the documented call.+ - `secrets/store.ts:309-311` duplicates `time.ts`'s `isoSecond`; the duplicate+ is removed.+- **Depends on**: none (**independent**)++## Release-phase tasks++- Docs pass: `docs/observability.md` (session turn fields, and the three sites+ that still say twenty readers against a 21-entry reality),+ `docs/architecture.md` (owner scope, the egress registry and its second+ population rule), `docs/mcp.md` (the refusal and the instruction surface),+ `docs/cli-reference.md` (recall adequacy thresholds changing meaning, any new+ flag or exit code), `docs/how-it-works.md`, `README.md`.+- `CHANGELOG.md` entry under a new version heading plus its compare link.+- `package.json` version bump to 1.49.0 followed by+ `bun run scripts/sync-version.ts`, verified with `--check`.+- OpenClaw bundle rebuild if any bundled source changed; CI byte-diffs it.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/recon/census-lexer.md b/docs/brainstorm/a-label-is-not-a-boundary/recon/census-lexer.mdnew file mode 100644index 00000000..3d27dfba--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/recon/census-lexer.md@@ -0,0 +1,352 @@+# Recon: two censuses built the same lexer (t_1d4f932f)++Read-only reconnaissance on `feat/a-label-is-not-a-boundary`. Every claim below+carries a `file:line` anchor that was read, and every number was produced by+running the code, not by reading a comment.++Test command that worked (clean `HOME`, per the suite convention in+`bunfig.toml:1-3` preloading `tests/setup.ts`):++```+mkdir -p /tmp/emptyhome+env HOME=/tmp/emptyhome bun test tests/core/architecture/progress-census.test.ts \+ tests/core/architecture/verdict-vocabulary-census.test.ts \+ tests/core/architecture/destructive-site-census.test.ts \+ tests/core/architecture/write-site-census.test.ts+# 162 pass, 0 fail, 278 expect() calls, 4 files, 6.99s+```++## 1. What exists: every test that reads source text structurally++`tests/` holds seventeen tests that read `.ts` source and decide something from+its shape. Only the technique column matters for this task.++| Test | Anchor | Technique | Owns a lexer? |+|---|---|---|---|+| progress census | `tests/core/architecture/progress-census.test.ts:181-285` | full lexer, two-view collapsed to one (`code`) | YES — `lex` |+| destructive-site census | `tests/core/architecture/destructive-site-census.test.ts:232-339` | full lexer, two views (`withoutComments`, `code`) | YES — `lex` |+| verdict-vocabulary census | `tests/core/architecture/verdict-vocabulary-census.test.ts:1047-1102` | partial masker: comments + quoted strings + whole templates; **no regex rule** | YES — `maskSource` |+| progress-emitter census | `tests/cli/progress-emitter-census.test.ts:97-132` | partial masker: comments blanked, strings *skipped* (contents kept); **no regex rule** | YES — `blankComments` |+| write-site census | `tests/core/architecture/write-site-census.test.ts:745`, `:805-806` | regex over RAW text | no |+| egress census | `tests/core/architecture/egress-census.test.ts:149-174` | regex over raw text | no |+| import cycles | `tests/core/architecture/import-cycles.test.ts:51-57`, `:81-85` | line-anchored regex over raw text (`^[ \t]*import`) | no |+| core layering | `tests/core/layering.test.ts:39-42`, `:48-57` | per-line, `isCommentLine` prefix test | no |+| doctor-exit census | `tests/core/brain/doctor-exit-census.test.ts:91`, `:127-136` | regex over raw text | no |+| terminal-state census | `tests/cli/terminal-state-census.test.ts:239`, `:303`, `:361`, `:387-394` | regex + `indexOf` slicing over raw text | no |+| entity-read census | `tests/core/brain/entities/entity-read-census.test.ts:69-115` | regex over raw text | no |+| vault-guard census | `tests/core/brain/vault-guard-census.test.ts:29-57`, `:119-122` | regex over raw text | no |+| continuity reader census | `tests/core/brain/continuity/reader-census.test.ts:44-46`, `:167-168` | regex over raw text | no |+| manifest completeness | `tests/cli/manifest-completeness.test.ts:76-95`, `:111` | `indexOf` slicing over raw text | no |+| help-surface parity | `tests/cli/help-surface-parity.test.ts:31-33` | parses CLI *output*, not source | n/a |+| chunk-window census | `tests/core/search/chunk-window-census.test.ts` | imports values; reads no source | n/a |+| config-template ratchet | `tests/core/brain/config-template-ratchet.test.ts:114` | reads YAML lines, not TS | n/a |++### Correction to the premise++The task says "three censuses now read source syntactically". **Four do.**+`tests/cli/progress-emitter-census.test.ts:97-132` carries a fourth+hand-written blanker, written for the same reason and stated in the same+words ("A census that matched raw text would count `progressCounter(` inside a+docblock as an emitter", `:92-95`). The task also says "a fourth will be+written eventually" — it already was.++The task also implies the destructive census's lexer was the origin the+progress census borrowed from. That is what `progress-census.test.ts:179` says+("This is the same lexer the destructive-site census runs, for the same+reason"), and it is exactly true: the two bodies are character-identical apart+from the second view (see §2).++## 2. Comparison of the four implementations++| Aspect | `destructive.lex` (`:232-339`) | `progress.lex` (`:181-285`) | `verdict.maskSource` (`:1047-1102`) | `emitter.blankComments` (`:97-132`) |+|---|---|---|---|---|+| Return | `SourceViews { withoutComments, code }` (`:178-181`) | `string` (the `code` view only) | `string` | `string` |+| Offsets preserved | yes (`:236-240`) | yes (`:184-188`) | yes (`:1049-1051`) | yes (`:98`) |+| Newlines preserved | yes | yes | yes | yes |+| Line comments | blanked in both views (`:274-281`) | blanked (`:222-228`) | blanked (`:1056-1062`) | blanked (`:103-106`) |+| Block comments | blanked in both views (`:282-289`) | blanked (`:229-235`) | blanked (`:1063-1069`) | blanked (`:107-119`) |+| String contents | blanked in `code`, KEPT in `withoutComments` (`:290-297`) | blanked (`:236-243`) | blanked (`:1070-1098`) | **kept** — the scanner only skips past them (`:120-128`) |+| Unterminated-quote rule | none — regex rule covers it | none — regex rule covers it | "a `"`/`'` with no partner before the newline is not an opener" (`:1078-1088`) | none |+| Template literals | mode stack; text blanked, `${…}` re-entered as CODE (`:250-272`, `:298-302`) | identical (`:198-220`, `:244-248`) | blanked WHOLE, no `${…}` re-entry (`:1070`, `:1085`) | skipped whole, contents kept (`:120-128`) |+| Nested `${}` braces | own brace counter per interpolation (`:244-245`, `:323-334`) | identical (`:192-193`, `:269-280`) | n/a (blanked whole) | n/a |+| Regex literals | recognised, contents blanked, char-class aware (`:303-322`) | identical (`:249-267`) | **NOT recognised** | **NOT recognised** |+| Regex-vs-division | `REGEX_PRECEDING` set + keyword lookbehind (`:184-230`) | identical (`:124-170`) | n/a | n/a |+| Escapes | `\` consumes two chars in strings, templates, regexes | identical | `\` consumes two chars in strings only (`:1073-1076`) | `\` consumes two chars in strings (`:123`) |++`diff` of `progress-census.test.ts:181-285` against+`destructive-site-census.test.ts:232-339` is nine hunks, every one of them the+mechanical consequence of the second view (`blank(from,to)` becoming+`blank(arr,from,to)`; two extra `blank(withoutComments, …)` calls in the two+comment branches; the return type). The preceding constant blocks+(`progress:124-170` vs `destructive:184-230`) differ only by the+`ReadonlySet<string>` annotation on two `new Set([…])`. **The two are one+implementation typed twice.**++### The one thing `withoutComments` buys++`destructive-site-census.test.ts:172-174` states it: an import specifier IS a+string, so the binding detector must read it. `fsImports(withoutComments)`+at `:425` reads specifiers; `removalSites(code, …)` at `:469` and+`gateSpans(code)` at `:503` read calls. Any extraction must expose both views,+and §5 shows a migration that forgets this silently zeroes a census.++## 3. Measured populations, today++| Census | Measurement | Value |+|---|---|---|+| progress | modules scanned (`SRC_ROOT`, `:974`) | 951 |+| progress | `safeguardedShapes(SOURCES)` (`:979`) | **10** options types |+| progress | of those, with a sink | 9 (the 10th is the declared exemption `EmbeddingPhaseOptions`, `:107-111`) |+| progress | `filesDeclaringSafeguard` cross-check (`:994`) | 9 files |+| verdict | files scanned (`:1326`) | 951 |+| verdict | `scanVocabularies` population (`:1327`) | **57** vocabularies |+| verdict | `CENSUS` registry (`:1328`) | 57 entries — exact agreement |+| destructive | modules under `src/core/brain/` (`:565`) | 461 |+| destructive | files with removal sites (`ROWS`, `:566`) | 32 |+| destructive | ungated rows (`:568`) | 31 |+| destructive | `DESTRUCTIVE_SITES` registry | 31 — exact agreement |+| write-site | modules scanned | 951 |+| write-site | rows in population (`:821`) | 129 |+| write-site | direct-fs rows (`:822`) | 64 (registry `DIRECT_WRITE_EXCLUSIONS` also 64) |+| write-site | shared-writer rows | 94 |+| emitter | `progressCounter(` sites in `src/` | 9 |++The 10 and the 57 the task quotes are confirmed. Note that no census asserts an+exact count — `progress-census.test.ts:985` is `toBeGreaterThan(0)` and+`verdict-vocabulary-census.test.ts:1451-1452` is `toBeGreaterThan(50)` /+`toBeGreaterThan(500)`. A before/after equality check on the extraction has to+be run, not read off an assertion.++## 4. Measured mis-parses++Adversarial inputs were run against all four implementations from+`/tmp/.../scratchpad/` by importing each census under a `bun:test` stub.++Neither of the two full lexers mis-parsed any of the 24 inputs tried, including+every case the task named: regex containing a quote; template with nested+braces and an interpolated string; comment containing a quote; division after+an identifier, a `)`, a `]`, a `>` and a `++`; escaped backslash before a+closing quote; regex containing `{`, `//`, an escaped `/` in a character class,+and an escaped `[`; nested template inside an interpolation; a comment inside an+interpolation. Length and newline positions were preserved in every case.++### Defect 1 — `verdict.maskSource` is wrong on live source, today++The rule at `verdict-vocabulary-census.test.ts:1085` is+`if (char !== "\`" && text[k] === "\n")`. The unterminated-quote guard —+the one the docblock at `:86-91` credits with keeping `/["]/` from blanking+the rest of a module — is **excluded for backticks**. A backtick inside a+regex literal is therefore read as a template opener and blanks real code to+the next backtick anywhere in the file.++Two shapes that exist in `src/` today reproduce it:++```+src/core/vault.ts:88 const CODE_BLOCK_RE = /```[\s\S]*?```|`[^`]+`/g;+src/core/install/adapters/generic.ts:70 if (/[:#[\]{},&*!|>'"%@`]/.test(s) || …)+```++Measured over the real tree: `maskSource` blanks **9,706 of the 31,608 bytes**+of `src/core/vault.ts` (31 %) that the shared lexer keeps. Consequence today:+the frozen binding `DOUBLE_QUOTED_ESCAPES` at `src/core/vault.ts:748` is+**invisible** to the census — it is the one frozen binding in the whole tree+that `maskSource` cannot see and the shared lexer can.++Positive control (a synthetic module carrying `src/core/vault.ts:88` verbatim+followed by a complete four-piece vocabulary):++```+current maskSource scanVocabularies -> [] <- the vocabulary vanishes+same file, regex line deleted -> ["ZZ"]+shared lexer scanVocabularies -> ["ZZ"]+```++This is the mis-parse class the file's own docblock says is "worse than a+miss" (`:1081-1084`), still live, one line away from hiding a real vocabulary.++### Defect 2 — `emitter.blankComments` has the original bug, latent++`tests/cli/progress-emitter-census.test.ts:120-128` treats `"`, `'` and+`` ` `` as string openers with no regex rule and no newline guard. Input:++```+const RE = /["]/;+/** Mentions progressCounter( in prose. */+const tail = "x";+```++Result: the docblock is **not blanked** and `progressCounter(` in prose counts+as an emitter — precisely the failure `:92-95` says the function exists to+prevent. Measured over `src/` today the count is unchanged (9 sites either+way), so this one is latent, not live.++### Not defects, but asymmetries to decide++- `destructive.withoutComments` leaks string and template CONTENTS by design+ (`:172-176`). Any shared type must keep that documented at the helper.+- `verdict.maskSource` blanks templates whole, so code inside `${…}` is+ invisible; the shared lexer reads it as code. This is a *widening* on+ migration and the docblock text at `:86-91` must change with it.++## 5. Would the extraction break layering or import cycles?++No, and neither guard can even see it.++- `tests/core/architecture/import-cycles.test.ts:43` sets `SRC = resolve(ROOT, "src")`+ and `moduleFiles()` at `:82` globs `**/*.ts` under that root only. A module+ under `tests/helpers/` is not a node in the graph.+- `tests/core/layering.test.ts:18` sets `CORE_ROOT = src/core` and walks only+ that. The banned calls (`process.exit`, `process.stdout.write`, `console.log`)+ are irrelevant to a pure string function anyway.+- The helper would import nothing — not even from `src/` — so it adds no edge+ in either direction.++## 6. What `tests/helpers/` looks like today++Ten modules, no subdirectories: `cli-timeout.ts`, `epipe-stream-harness.ts`,+`fake-http.ts`, `fixtures.ts`, `mock-embedding.ts`, `progress-records.ts`,+`run-cli.ts`, `search-fixtures.ts`, `sqlite-vec.ts`, `vault-digest.ts`.++Conventions, from `tests/helpers/progress-records.ts:1-24` and+`tests/helpers/vault-digest.ts:1-20`:++- kebab-case filename naming the thing, not the verb;+- a docblock that argues WHY the helper exists before it says what it does,+ and `{@link}` references to the exported names;+- named `export`s only, no default export;+- explicit `ReadonlyArray` / `Readonly` on returned structures;+- imports use an explicit `.ts` extension and a relative specifier+ (`tests/cli/progress-emitter-census.test.ts:79-80`);+- helpers may import from `src/` (`progress-records.ts:11`) but need not.++**No helper has its own test file** — `tests/helpers/*.test.ts` does not exist,+and the three helpers whose behaviour is load-bearing (`vault-digest`,+`progress-records`, `run-cli`) are exercised only indirectly through the 298+tests that import from `tests/helpers/`. The acceptance criterion "its own+tests" therefore establishes a new convention rather than following one. Bun+discovers `*.test.ts` anywhere, and `bunfig.toml` preloads `tests/setup.ts`+globally, so `tests/helpers/source-lexer.test.ts` needs no configuration.++## 7. Each census's "what this cannot see", quoted++**progress census**, `progress-census.test.ts:67-86`, "## What it still does not+see, stated rather than implied": a heritage clause this tree cannot resolve+(`extends`/`&` followed only into this tree; an imported base or `Omit<…>`+resolves to the whole base); a sink whose asynchrony is more than one alias+deep; a counter it cannot recognise as one; whether a declared `onProgress` is+ever READ. **None of these four belongs to the lexer.** The lexer's own limits+are stated positively instead, at `:51-65`.++**verdict-vocabulary census**, `verdict-vocabulary-census.test.ts:63-96`,+"## What the scan cannot see, stated rather than implied": a vocabulary SPLIT+ACROSS MODULES; a vocabulary with no membership list or no guard; values that+are not literals in the object; a guard whose parameter is typed `string`;+trees other than `src/`; and — the lexer one — "Code inside a `${…}`+interpolation: a template literal is blanked whole, so a vocabulary piece+written inside one is not read. A template can also legally span lines, which+is why the masker's 'a quote with no partner on this line is not a string' rule+— the rule that keeps a regex literal such as `/["]/` from blanking the rest of+a module — applies to `"` and `'` only." That last sentence is the one the+measurement in §4 falsifies as a *safety* claim: it is true as written and the+gap it leaves is a live mis-parse.++**destructive-site census**, `destructive-site-census.test.ts:100-114`, "## What+this file deliberately does NOT do": it does not check that a declared recovery+story is TRUE; it does not reach outside `src/core/brain/`. Its lexer claim is+separate, at `:51-54`: "a removal named in a comment is not a site and a site is+not hidden by a quote inside a regular expression."++**write-site census**, `write-site-census.test.ts:54-58`: "a write issued through+a `node:fs/promises` FileHandle method, or through a binding re-exported by an+intermediate module." It states no lexical limit because it does no lexing.++Union of lexer-owned limits, to state once at the helper: interpolated `${…}`+code is read as code but is not attributed to the template; a regex whose+opening `/` sits in a position the heuristic reads as division is read as+division; angle brackets are not counted as brackets; `withoutComments` carries+literal contents on purpose. Intersection of the *non*-lexer limits: empty —+every census's remaining blind spots are about its own rule and stay with it.++## 8. Recommended extraction++**Module:** `tests/helpers/source-lexer.ts`++**Exported surface:**++```ts+/** Two views of one module, both the same LENGTH as the source. */+export interface LexedSource {+ /** Comments blanked; string, template and regex CONTENTS kept. */+ readonly withoutComments: string;+ /** Comments and all literal CONTENTS blanked; `${…}` code kept. */+ readonly code: string;+}++export function lexSource(text: string): LexedSource;++/** `lexSource(text).code`, for the callers that need one view. */+export function lexCode(text: string): string;+```++Take the body verbatim from `destructive-site-census.test.ts:184-339` — it is+the strictly more general of the two identical copies. Move the docblock+prose from `progress-census.test.ts:36-65` and `:172-179` (the argument for+lexing) and from `destructive-site-census.test.ts:168-181` (the argument for+two views) into the helper's header, and state the union from §7 there.++**Tests:** `tests/helpers/source-lexer.test.ts`, minimum cases:++1. regex literal containing a quote (`/["']/`) — code after it survives;+2. regex literal containing a backtick, using `src/core/vault.ts:88` verbatim —+ this is the Defect-1 regression test;+3. brace inside a string — bracket matching unaffected;+4. brace inside a comment — same;+5. template with nested `${}` and an interpolated string;+6. division that looks like a regex opener, after an identifier, `)`, `]`, `>`+ and `++`;+7. escaped backslash before a closing quote;+8. `withoutComments` keeps an import specifier while `code` blanks it —+ the invariant the write-site migration depends on;+9. length and newline-offset preservation on every input above.++**Migration, per census:**++| Census | Change | Measured effect |+|---|---|---|+| destructive-site | delete `:184-339`, import `lexSource`; `lexed()` at `:534` and `classify()` at `:539` call it | none — identical implementation |+| progress | delete `:124-285`, import `lexCode`; `analyze()` at `:622` becomes `lexCode(file.text)` | none — identical implementation. `constants(file.text, code)` at `:629` keeps working because offsets are preserved |+| verdict-vocabulary | delete `maskSource` `:1047-1102`; `scanVocabularies` at `:1288` becomes `lexSource(file.text).code` | **57 → 57**, names identical. Fixes Defect 1. Requires rewriting the docblock bullet at `:86-91`, because interpolated code becomes visible |+| progress-emitter | delete `blankComments` `:97-132`; `:158` becomes `lexCode(readFileSync(…))` | **9 → 9** call sites. Fixes Defect 2 |+| write-site | *optional, recommended*: `classify` at `:803-806` becomes `directWriteCalls(V.code, fsImports(V.withoutComments))` and `V.code.matchAll(SHARED_WRITE_RE)` | **129 rows / 64 direct / 94 shared → identical**, no registry drift. Removes its raw-text reading |++**Every census can migrate.** There is no census that must keep its own copy.+The one migration that is *not* mechanical is `verdict-vocabulary`, and only+because its prose asserts a limit that stops being true.++**The trap:** routing `fsImports` through `code` instead of `withoutComments`+blanks the `"node:fs"` specifier and silently drops the write-site census from+64 direct rows to **0**, with an empty failure list — measured. That is the+same false-clean signature the censuses exist to prevent, so criterion 8 in the+test list above is not optional.++## 9. Other defects noticed++- `tests/core/layering.test.ts:39-42` decides "is a comment" from a line prefix,+ so `const s = "// process.exit";` is not skipped (false positive) and+ `foo(); // ok` on a code line is scanned (harmless), while a banned call+ inside a block-comment line that does not start with `*` is skipped. With the+ helper available this becomes `lexCode(text).split("\n")` and the+ `isCommentLine` heuristic disappears.+- `tests/core/architecture/import-cycles.test.ts:51-57` anchors on `^[ \t]*`,+ which is why a specifier inside a docblock does not match — but a specifier+ inside a template literal at column zero would. Low risk; worth one line in+ the helper's "who could use this next" note.+- None of the three lexer-owning censuses has a test that exercises the+ regex-literal case its own docblock argues about+ (`progress:1088-1117` covers brace-in-generic, brace-in-string and+ commented-out-sink; `destructive:808` covers string-and-comment;+ `verdict` covers none of the three). The bug in §4 survived exactly there.+- `verdict-vocabulary-census.test.ts:1451` floors the population at+ `toBeGreaterThan(50)` against an actual 57. The extraction is the moment to+ make that an equality against `CENSUS.length`, which is already asserted+ to match at `:1407-1426`.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/recon/conventions-and-release-machinery.md b/docs/brainstorm/a-label-is-not-a-boundary/recon/conventions-and-release-machinery.mdnew file mode 100644index 00000000..c6a66b7b--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/recon/conventions-and-release-machinery.md@@ -0,0 +1,1867 @@+# Conventions and release machinery++Reconnaissance for the `a-label-is-not-a-boundary` release, on branch+`feat/a-label-is-not-a-boundary` at `package.json` version **1.48.0**.++This note is the shared contract for the nine feature units. Read it+instead of rediscovering the same rules nine times. Every claim below+carries a `file:line` anchor that was read; every command output is real.++Status of the tree as measured (see "Verified command output" for the+transcripts): `bun run lint` 0 errors / 123 warnings, `bun run fmt:check`+clean, `bun run typecheck` clean, `bun run scripts/sync-version.ts+--check` clean at 1.48.0, `git status --porcelain` empty.++---++## 1. Vocabulary idiom++The repository has one mandated shape for a closed set of string values,+and a census that reads `src/` and enrols every construct carrying it.+Writing three of the four pieces leaves the construct out of the+population; writing all four and not registering it fails the census.++### 1.1 The four pieces, all four in ONE module++Stated in the census docblock at+`tests/core/architecture/verdict-vocabulary-census.test.ts:38-47`:++1. `const NAME = Object.freeze({ … })` whose every entry is+ `key: "string literal"`;+2. a union derived from it — `(typeof NAME)[keyof typeof NAME]`;+3. a membership list built from it — a const initialised from+ `Object.values(NAME)` or from an array of `NAME.member`;+4. a guard: a function or arrow taking a parameter typed `unknown` that+ reads the membership list or the object.++They must be in the SAME file. Detection is per-file+(`verdict-vocabulary-census.test.ts:70-72`), so a vocabulary split across+modules is out of population entirely — which means the audit never runs+on it, and that is a silent hole, not a pass.++### 1.2 Canonical example from src++`src/core/doctor-readiness.ts:128-153`:++```ts+export const READINESS_STATUS = Object.freeze({+ /** The probe ran and the surface answered correctly. */+ pass: "pass",+ /** The probe ran and the surface is broken; the detail names how. */+ fail: "fail",+ /** Nothing to measure: the surface is deliberately not configured. */+ skipped: "skipped",+ /** The probe could not measure; the detail says what stopped it. */+ unknown: "unknown",+} as const);++/** Closed union over {@link READINESS_STATUS}. */+export type ReadinessStatus = (typeof READINESS_STATUS)[keyof typeof READINESS_STATUS];++/** Membership list, in reporting order from best-known to least-known. */+export const READINESS_STATUSES: ReadonlyArray<ReadinessStatus> = Object.freeze([+ READINESS_STATUS.pass,+ READINESS_STATUS.fail,+ READINESS_STATUS.skipped,+ READINESS_STATUS.unknown,+]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isReadinessStatus(value: unknown): value is ReadinessStatus {+ return typeof value === "string" && (READINESS_STATUSES as ReadonlyArray<string>).includes(value);+}+```++`src/core/brain/safeguard.ts:52-80` (`OPERATION` / `Operation` /+`OPERATIONS` / `isOperation`) and `src/core/brain/progress.ts:66-92`+(`PROGRESS_KIND`) are the same shape.++### 1.3 Casing and naming++- Object constant: `SCREAMING_SNAKE`, singular+ (`READINESS_STATUS`, `PROGRESS_KIND`, `OPERATION`).+- Keys: `lowerCamelCase` identifiers — `timedOut`, `transportSingleResponse`+ (`src/core/brain/progress.ts:104,111`).+- Values: lowercase kebab wire strings — `"timed-out"`,+ `"transport-single-response"` (same lines). Key and value need not+ match; the value is what crosses the wire.+- Derived type: `PascalCase` singular (`ReadinessStatus`, `ProgressKind`).+- Membership list: `SCREAMING_SNAKE` plural, typed+ `ReadonlyArray<TheType>`, itself `Object.freeze`d+ (`src/core/doctor-readiness.ts:143`). Plural spelling is free —+ `GRAPH_HEALTH_CODE_LIST` and `MATERIALIZE_FRESHNESS_STATES` both pass;+ the census matches on the object name, not the list name+ (`verdict-vocabulary-census.test.ts:1302-1308`).+- Guard: `isPascalCase`, parameter typed **`unknown`**, returns+ `value is TheType`.++### 1.4 What the audit asserts (7 checks)++`auditVocabulary` at `verdict-vocabulary-census.test.ts:374-404`:++1. `Object.isFrozen(values)` (line 378).+2. No duplicate value in the object (lines 380-383).+3. No duplicate entry in the membership list (lines 385-388).+4. Every declared value is a member (line 392).+5. The guard accepts every declared value (line 393).+6. No member that no value declares (line 396).+7. The guard rejects every one of `NON_MEMBERS` — `""`, `" "`,+ `"unknown-vocabulary-member"`, `null`, `undefined`, `42`, `{}`+ (`verdict-vocabulary-census.test.ts:363-371`, checked at 398-402).++Values need NOT be unique across vocabularies+(`verdict-vocabulary-census.test.ts:23-25`): two `absent` members in two+different vocabularies are fine.++### 1.5 Registration, and how discovery works after v1.48.0++`CENSUS` at `verdict-vocabulary-census.test.ts:411-1004` is a frozen array+of `{ name, values, members, guard }` (interface at lines 347-356).+`name` must be the **source identifier of the frozen object**, spelled+exactly (`verdict-vocabulary-census.test.ts:1427-1445`).++v1.48.0 made the census read the tree. `scanVocabularies`+(`verdict-vocabulary-census.test.ts:1285-1324`) walks+`SCANNED_ROOTS = ["src"]` (line 1013), lexes each `.ts` file with+`maskSource` (line 1047 — comments and string CONTENTS blanked, offsets+preserved), and enrols a construct only when all four pieces resolve.+Four assertions then bind the scan to the registry+(`verdict-vocabulary-census.test.ts:1406-1466`):++- every four-piece vocabulary in `src/` is registered, **named** in the+ failure (line 1407);+- no registration outlives its vocabulary (line 1418);+- each registration's values equal the values the source declares+ (line 1427);+- the scan is not vacuous: `SCANNED.length > 50` and+ `SOURCE_TREE.length > 500` (lines 1451-1452).++There is **no exemption list** (`verdict-vocabulary-census.test.ts:59-61`).++### 1.6 The concrete recipe for a new vocabulary++To pass, in one module under `src/`:++1. `export const NEW_THING = Object.freeze({ key: "value", … } as const);`+ with every entry a plain `key: "literal"`. A spread, a nested object,+ a computed key, or a value built by a call drops it out of population+ (`verdict-vocabulary-census.test.ts:1204-1219`).+2. `export type NewThing = (typeof NEW_THING)[keyof typeof NEW_THING];`+ — this exact text is what the scan matches+ (`verdict-vocabulary-census.test.ts:1295-1298`).+3. `export const NEW_THINGS: ReadonlyArray<NewThing> = Object.freeze([NEW_THING.a, …]);`+ or `Object.freeze(Object.values(NEW_THING))` — the multi-line+ `Object.values` form is explicitly supported and pinned by name+ (`verdict-vocabulary-census.test.ts:1455-1465`).+4. `export function isNewThing(value: unknown): value is NewThing { … }`+ reading the list. An arrow form works too+ (`verdict-vocabulary-census.test.ts:1510-1516`). A parameter typed+ `string` puts you **out** of population — a documented and deliberate+ hole (`verdict-vocabulary-census.test.ts:80-82`, negative fixture at+ 1588-1595).+5. Add the import and the `{ name, values, members, guard }` entry to+ `CENSUS` in `tests/core/architecture/verdict-vocabulary-census.test.ts`,+ with a comment saying why the vocabulary exists (every existing entry+ carries one; not asserted, but universal).++Shapes deliberately kept OUT, so do not expect them to be enrolled:+a frozen object with no derived union; a curated ORDERING with no guard+(`DREAM_STEP_RUNNABLE`, `DREAM_GATE_NAMES` —+`verdict-vocabulary-census.test.ts:52-58`); a frozen lookup whose values+are not literals; a `string`-parameter guard+(`verdict-vocabulary-census.test.ts:1568-1596`).++Blind spots stated in the docblock rather than hidden+(`verdict-vocabulary-census.test.ts:63-96`): a split trio, a missing list+or guard, non-literal values, a `string` guard, trees other than `src/`+(`hooks/`, `scripts/`, `plugins/` are unscanned), and code inside a+`${…}` interpolation.++---++## 2. Censuses and their obligations++Thirteen enforced gates. Each one is a test that reads the source tree+and fails by NAME, not by count.++| Census | Path | Population | Registry lives in |+|---|---|---|---|+| verdict vocabulary | `tests/core/architecture/verdict-vocabulary-census.test.ts` | four-piece vocabularies in `src/` | the test (`CENSUS`, :411) |+| write-site | `tests/core/architecture/write-site-census.test.ts` | direct `node:fs` content writes that can address the vault | the test (`DIRECT_WRITE_EXCLUSIONS`, :243) |+| destructive-site | `tests/core/architecture/destructive-site-census.test.ts` | removal/displacement calls under `src/core/brain/` | **src** (`src/core/brain/destructive-sites.ts:125`) |+| egress | `tests/core/architecture/egress-census.test.ts` | modules declaring an out-of-vault destination | **src** (`src/core/egress/registry.ts:85`) |+| progress (source) | `tests/core/architecture/progress-census.test.ts` | options types accepting a `Safeguard` | the test (`DECLARED_EXEMPTIONS`, :106) |+| progress (execution) | `tests/cli/progress-emitter-census.test.ts` | every `progressCounter(` call site in `src/` | the test (`EMITTERS`, :201) |+| import cycles | `tests/core/architecture/import-cycles.test.ts` | the `src/` module graph | none |+| layering | `tests/core/layering.test.ts` | `src/core/` | none |+| doctor exit codes | `tests/core/brain/doctor-exit-census.test.ts` | doctor checks | see §7 |+| config template ratchet | `tests/core/brain/config-template-ratchet.test.ts` | `_brain.yaml` schema vs template | see §6 |+| help-surface parity | `tests/cli/help-surface-parity.test.ts` | the CLI command manifest | see §5.7 |+| manifest completeness | `tests/cli/manifest-completeness.test.ts` | the four CLI dispatchers | the test (four empty unlisted tables, `:50-62`) |+| terminal-state | `tests/cli/terminal-state-census.test.ts` | every CLI terminal state | the test (`CLASSIFIED_BY_MODULE_WALK`, `:33-37`) |++Note the asymmetry, because it will trip someone: the write-site+exclusions and the progress exemptions live **in the test file**, while+the destructive-site and egress registries live **in `src/`** and are+imported by their tests. When you add a declaration, put it where that+census keeps it.++### 2.1 Write-site census++`tests/core/architecture/write-site-census.test.ts`.++Population (docblock :20-29): a module is in population when it lives+under `src/core/brain/`, `src/core/search/`, `src/cli/brain/`, `src/mcp/`+(`:77-82`), or is `src/core/vault.ts` / `src/core/fs-atomic.ts`+(`:85-88`), or imports `paths.ts` from anywhere (`:91`).++A WRITE is a content write bound from `node:fs` / `node:fs/promises`:+the closed call list is at `:97-120` and includes `writeFileSync`,+`appendFileSync`, `renameSync`, `rmSync`, `unlinkSync`, `cpSync`,+`createWriteStream`, `chmodSync`, `symlinkSync` and the promise twins.+`mkdirSync` is deliberately NOT a write (`:31-41`). `Bun.write` is matched+on the receiver (`:51-52`).++Assertions (`:824-871`):+- every direct-fs write site carries an entry in `DIRECT_WRITE_EXCLUSIONS`+ (`:825`);+- no exclusion outlives its site (`:833`);+- the entry's `calls` array equals exactly the calls found, sorted+ (`:839-853`) — a NEW KIND of write in an already-excused file is a new+ decision;+- every entry has a non-empty `reason` and at least one category+ (`:855`).++**Obligation on a new feature:** route vault writes through the shared+writers (`src/core/fs-atomic.ts`, `src/core/vault.ts`). If you cannot,+add a `DIRECT_WRITE_EXCLUSIONS` entry at+`tests/core/architecture/write-site-census.test.ts:243` with+`categories` drawn from the closed `WRITE_CATEGORY` vocabulary (`:201-218`+— `shared-writer-itself`, `append-only-ledger`, `lifecycle-move`,+`retention-delete`, `machine-artifact`, `lock-primitive`,+`archive-transfer`, `metadata-only`), the exact sorted `calls`, and a+non-empty `reason`.++### 2.2 Destructive-site census++`tests/core/architecture/destructive-site-census.test.ts`, registry at+`src/core/brain/destructive-sites.ts:125`.++Rule (docblock `:11-15`): a removal site under `src/core/brain/` is either+routed through the destructive gate, or it carries a+`DESTRUCTIVE_SITES` entry — **never both, never neither**. Gating is per+SITE, not per file (`:57-60`): a `withDestructiveSnapshot(` in a comment+gates nothing (`:848`), and a function handed to the gate by name is not+lexically gated (`:858`).++`DestructiveSiteDeclaration` at `src/core/brain/destructive-sites.ts:87-94`:+`calls: ReadonlyArray<string>`, `recovery: RecoverabilityFacts`,+`reason: string`.++Assertions (`:570-678`):+- every ungated removal site is declared (`:571`);+- a fully gated site must NOT also carry a declaration (`:579`);+- no declaration outlives its site (`:589`);+- the declaration's `calls` equal exactly the ungated calls found (`:595`);+- every reason is at least `DESTRUCTIVE_SITE_MIN_REASON_LENGTH` = **60**+ characters (`src/core/brain/destructive-sites.ts:84`, asserted at+ `:614-620`);+- **no two sites share a reason** (`:622-635`) — pasting one sentence+ across entries is the cheapest fake and is detected;+- every declaration classifies to a verdict from `RECOVERABILITY_STATE` /+ `RECOVERY_COVERAGE` / `RECOVERABILITY_BLOCKER`, frozen (`:637-651`);+- a site with `recoveryPoint: false` may not reach `covered` or `partial`+ (`:653-667`);+- vacuity floors: tree > 250 files, rows > 28, declarations > 25+ (`:669-678`).++**Obligation:** any new `unlinkSync` / `rmSync` / `renameSync` under+`src/core/brain/` must go through `withDestructiveSnapshot(` or gain a+declaration with a ≥60-character reason nobody else has written.++### 2.3 Egress census++`tests/core/architecture/egress-census.test.ts`, registry at+`src/core/egress/registry.ts:85` (`EGRESS_SITES`), entry interface at+`src/core/egress/registry.ts:64-74` (`id`, `verb`, `module`, `redaction`,+`reason`).++Population, two rules (`:23-48`): (1) a module declaring a string+parameter named `out` / `outdir` / `dest` / … is in population by the+declaration alone; (2) an ambiguous name (`file`, `path`, `to`, `report`)+counts when the same module also writes bytes. Rule 2 is the route that+reaches the MCP surface, because an MCP tool declares its destination as+an `inputSchema` property with the same `name: { type: "string" }` shape+(`:43-45`).++Assertions (`:190-280`): every module in population is declared (`:191`);+no declaration outlives its module (`:197`); an entry declared as+redacting actually calls the shared guard (`:204`); every declared+destination in a redacting module is matched by a guard call (`:217`);+no entry understates what its module does (`:241`); every entry has an+`id`, a `verb` and a non-empty `reason` (`:262`); ids and module paths+are unique (`:270`).++**Obligation:** any new verb or MCP tool that writes vault-derived bytes+to an operator-named path must call the shared redactor and add an+`EGRESS_SITES` entry.++### 2.4 Progress source census++See §3.4.++### 2.5 Progress emitter (execution) census++See §3.5.++### 2.6 Import cycles++`tests/core/architecture/import-cycles.test.ts`. `src/` carries no import+cycle (`:220`). `import type … from` **IS** an edge (`:24-28`, asserted at+`:240`); a deferred `await import("…")` is **NOT** (`:30-35`, asserted at+`:250`) and is the sanctioned cure. Non-vacuity assertion at `:224`.++**Obligation:** a new module that closes a loop fails here. The fix is a+leaf module that imports nothing from the layer above it, or a deferred+`await import(…)`.++### 2.7 Layering++`tests/core/layering.test.ts:20-24`. `src/core/**` may never contain+`process.exit`, `process.stdout.write`, or `console.log(` on a+non-comment line. `process.stderr.write` and `console.error` remain+allowed and are the house fail-soft pattern (`:6-7`) — `progress.ts:283`+uses exactly that.++**Obligation:** core emits, the CLI prints and exits. A new core module+that wants to say something says it through a callback or on stderr.++---++## 3. The progress contract (v1.48.0)++`src/core/brain/progress.ts`.++### 3.1 Vocabularies++- `PROGRESS_SCHEMA = "o2b.progress.v1"` (`:56`) — the envelope+ discriminator, present on every event.+- `PROGRESS_KIND` (`:66-92`): `started`, `advanced`, `refused`,+ `stopped`, `finished`.+- `PROGRESS_REASON` (`:100-147`): `aborted`, `timed-out`,+ `transport-single-response`, `stream-buffered`, `failed`.+- `OPERATION` (`src/core/brain/safeguard.ts:52-59`): `dream`, `reindex`,+ `bridges`, `clusters`, `maintenance`, `architect`. This is the+ repository's own statement of what is long, and it is shared by the+ timeout ladder and the progress spine so the two cannot disagree+ (`verdict-vocabulary-census.test.ts:822-832`).++`ProgressEvent` (`src/core/brain/progress.ts:153-172`): `schema`,+`operation`, `kind`, `stage`, `completed`, optional `total`, optional+`reason` (present only on `stopped` and `refused`).++`ProgressSink = (event: ProgressEvent) => void` (`:175`) — **synchronous+by construction**, and the census asserts the declaration itself never+mentions `Promise<` (`progress-census.test.ts:1029-1041`).++### 3.2 The counter++`progressCounter(operation, sink, opts)` (`src/core/brain/progress.ts:235`)+returns `{ start, advance, finish, stop }` (`:185-194`). It keeps the+per-stage counter so no call site does. Enforced invariants:++- `total` must be a non-negative integer or absent — otherwise+ `RangeError` (`:228-233`);+- `advance(by)` must be a positive integer — otherwise `RangeError`+ (`:300-305`);+- `advance` before any `start`, or naming a different stage than the+ current one, throws (`:306-311`);+- any call after `finish`/`stop` throws: a run ends **once**+ (`:246-256`, 291, 299, 316, 321);+- absence of a sink means nobody asked; it is not a swallowed event+ (`:16-17`, and `emit` returns early at `:259`).++### 3.3 The sink-error policy++`emit` wraps `sink(event)` in try/catch (`src/core/brain/progress.ts:269-286`).+On a throw: the sink is **detached for the rest of the run**+(`live = false`, `:272`), the error is reported **once**, and the run+continues. If `opts.onSinkError` is supplied it receives the error;+otherwise the default writes one line to **stderr**:++```+progress: <operation> stream detached after the sink threw: <message>+```++The default is deliberately the safe one (`:210-217`): a rule every+caller must remember is a rule five of six callers will forget. Do not+re-implement this policy at a call site.++### 3.4 `withProgress` — the termination rule++`withProgress(counter, body)` (`:343-352`) and `withProgressAsync`+(`:355-367`) run `body`, call `counter.finish()` on success, and on a+throw call `counter.stop(progressReasonForError(error) ?? PROGRESS_REASON.failed)`+and rethrow. `progressReasonForError` (`:379-383`) maps+`SafeguardAbortError → aborted` and `SafeguardTimeoutError → timed-out`,+`null` otherwise.++The rule: **a stream that simply stops arriving is the shape of a+completed run, a crashed run and a hung run at once** (`:331-334`). Every+emitter must terminate exactly once. Use `withProgress`; do not hand-roll+the try/catch.++### 3.5 The rule the progress census enforces++`tests/core/architecture/progress-census.test.ts`, docblock `:12-17`:++> **a type that takes a safeguard takes a progress sink, or carries a+> written reason why it cannot.**++Assertions (`:977-1042`):+- every options type accepting a `Safeguard` accepts a progress sink,+ unless it is in `DECLARED_EXEMPTIONS` (`:978-987`; population must be+ non-empty);+- the parser sees every module that declares a safeguard, cross-checked+ against a naive search (`:989-996`);+- every exemption names a type that still exists (`:998`);+- every exemption's reason is **≥ 80 characters** and contains no+ `TODO` / `for now` / `later` (`:1004-1012`);+- **no stage is prose**, wherever the emitter keeps it (`:1014-1019`).+ The identifier shape is `/^[a-z0-9]+([-_][a-z0-9]+)*$/`+ (`progress-census.test.ts:114`). Inline literals, bare `const`s, frozen+ objects and `stage:` fields on hand-built events are all read, and an+ argument that resolves to none of those is REPORTED, not skipped+ (`:26-28`);+- the sink is synchronous everywhere it is declared (`:1021-1027`);+- `ProgressSink` itself promises nothing (`:1029-1041`).++There is exactly one exemption today: `EmbeddingPhaseOptions`+(`progress-census.test.ts:106-111`).++The execution census `tests/cli/progress-emitter-census.test.ts`+enumerates every `progressCounter(` call site in `src/` by+`<path under src/>#<enclosing top-level function>` (`:152-181`) and+requires each to appear in `EMITTERS` (`:201-242`) with an `entryPoint`,+an `operation`, and a discriminating `stage` witness. It then **drives+each entry point for real** with `--progress` and asserts records arrived,+that there is exactly one terminator, and that it is last (`:367-412`).++### 3.6 What a NEW long operation in this release must do++1. Add the operation to `OPERATION` / `OPERATIONS` in+ `src/core/brain/safeguard.ts:52-71` if it is genuinely a new long+ operation, and register the vocabulary change is already covered+ (`OPERATION` is registered at+ `verdict-vocabulary-census.test.ts:828-831`).+2. Put `readonly onProgress?: ProgressSink;` on the SAME options+ interface that carries `safeguard`, optional and readonly, invoked+ with `?.` — the house idiom (`src/core/brain/progress.ts:13-17`).+ Anything else fails `progress-census.test.ts:978`.+3. Build the counter with `progressCounter(OPERATION.x, opts.onProgress)`.+ Do **not** pass `onSinkError` unless you have somewhere better than+ stderr; the default is already safe.+4. Wrap the body in `withProgress` / `withProgressAsync` so the stream+ terminates exactly once.+5. Name every stage as a lowercase kebab/underscore identifier. No+ sentences, no spaces, no capitals.+6. Give the operation a CLI entry point that accepts `--progress`, then+ add the call site to `EMITTERS` in+ `tests/cli/progress-emitter-census.test.ts:201` and a driver to+ `ENTRY_POINTS` (`:265`), with a `(entryPoint, operation, stage)`+ witness that is unique across all emitters (`:363-364`).+7. If the emitter's fixture needs a vault, extend the `beforeAll` at+ `tests/cli/progress-emitter-census.test.ts:284-326`.++---++## 4. MCP surface++### 4.1 Registration++One assembly point: `buildToolTable(scope)` at `src/mcp/tools.ts:438`, whose+array literal begins at `src/mcp/tools.ts:439`. It composes five inline+entries (`second_brain_capabilities` `:440-451`, `second_brain_status`+`:452-468`, `second_brain_query` `:469-491`, `vault_health` `:497-511`,+`brain_artifact_get` `:512-529`) plus five spread slices: `...BRAIN_TOOLS`+(`:495`), `...SEARCH_TOOLS` (`:496`), `...SCHEMA_TOOLS` (`:530`),+`...WATCHDOG_TOOLS` (`:531`), `...SKILL_TOOLS` (`:532`). `tool_hydrate` is+pushed last for non-writer scopes over a late-bound getter (`:538`).++Slice arrays — this is where you actually add an entry:++- `BRAIN_TOOLS` = 31 per-domain arrays concatenated at+ `src/mcp/brain-tools.ts:48-80`, imports at `:13-43`. Per-domain exports+ such as `LANDSCAPE_TOOLS` at `src/mcp/brain/landscape-tools.ts:27`,+ `NOTES_TOOLS` at `src/mcp/brain/notes-tools.ts:391`.+- `SEARCH_TOOLS` `src/mcp/search-tools.ts:1730`; `SCHEMA_TOOLS`+ `src/mcp/schema-tools.ts:56`; `WATCHDOG_TOOLS`+ `src/mcp/watchdog-tools.ts:5`; `SKILL_TOOLS` `src/mcp/skill-tools.ts:123`.++Canonical smallest complete entry:+`src/mcp/brain/landscape-tools.ts:27-59` (handler signature at `:12`).++Scope filtering happens AFTER assembly (`src/mcp/tools.ts:534-544`):+`writer` filters to `WRITER_TOOL_NAMES` (`:421-427`, five names) and never+gets `tool_hydrate`; `catalog` shallow-clones everything outside+`CATALOG_ADVERTISED_NAMES` (`:432-436`) with `hidden: true` — still+callable, not listed. Dispatch is `findTool` (`:547-560`); an unknown name+in `REMOVED_TOOLS` throws `INVALID_PARAMS` naming the replacement+(`:552-555`), otherwise `METHOD_NOT_FOUND` (`:557`).++Server wiring: `MCPServer` calls `evaluateToolCapabilities(buildToolTable(...))`+at `src/mcp/server.ts:123-129`; `tools/list` filters `hidden !== true`+(`:320-333`); `tools/call` is `:352-386`; every handler passes through the+single seam `invokeToolHandler` (`:199-226`), which runs+`assertKnownArguments(tool, args)` FIRST (`:204`).++Result envelope: `buildMcpToolResult` (`server.ts:461-474`) validates the+output contract (`:466`), stringifies with a key-sorting replacer+(`:467,483-489`), applies the preview budget (`:468`). Errors go through+`toolError` (`:476-481`) — `isError: true`, message in `content[0].text`,+**no** `structuredContent`. An `MCPError` is re-thrown as a JSON-RPC error+instead (`:379`).++### 4.2 The tool contract++`interface ToolDefinition` at `src/mcp/tool-contract.ts:64-106`:++| Field | Line | Required | Meaning |+|---|---|---|---|+| `name: string` | `:65` | yes | registry key |+| `description: string` | `:66` | yes | advertised; ≤ 300 chars; line 1 becomes the catalog line |+| `inputSchema: Record<string, unknown>` | `:67` | yes | object-rooted, `properties`, `additionalProperties: false` |+| `outputSchema?: OutputSchema` | `:68` | no | validated on every response at request time |+| `previewBudget?: number` | `:69-77` | no | over-budget results are parked in the artifact store; no budget = never truncated |+| `hidden?: boolean` | `:78-83` | no | callable, omitted from `tools/list` |+| `handler(ctx, args, onProgress?)` | `:85-105` | yes | third parameter is per-REQUEST; a two-parameter handler still satisfies the type |++`ToolScope = "full" \| "writer" \| "catalog"` at `:19`. `ServerContext` at+`:35-62` — note `agentName` (`:46-61`) is a **getter** on the live server+(`server.ts:167-169`) that re-resolves per access and throws+`ConfigReadError` on an unreadable config; touch it only if the tool+genuinely needs identity.++Reuse the coercion helpers in `src/mcp/coerce.ts` (`coerceStr:11`,+`coerceInt:36`, `coerceBool:53`, `AGENT_SCOPE_SCHEMA:98-102`,+`coerceAgentScope:115`, `coerceIsoDate:125`).++### 4.3 Schema-completeness rules++`src/mcp/registry-guard.ts` — test-time only (`:44-46`); the request-path+counterpart `src/mcp/argument-guard.ts` READS the+`additionalProperties: false` this audit guarantees (`:14-17,70`).++Caps: `TOOL_DESCRIPTION_MAX = 300` (`:51`),+`PROPERTY_DESCRIPTION_MAX = 160` (`:52`),+`EXEMPTION_REASON_MIN = 10` (`:59`). There is deliberately NO exemption+table for descriptions (`:39-42`).++`SCHEMA_NODE_KIND` (`:66-75`): `root`, `property`, `items`, `values`.+`SCHEMA_COMPLETENESS_RULE` (`:188-203`), each enforced in `auditNode`+(`:263-313`):++| Rule | Value | Enforced | Rule |+|---|---|---|---|+| `nonObjectRoot` | `non-object-root` | `:284-286` | root must be exactly `type: "object"` |+| `missingProperties` | `missing-properties` | `:287` | root must carry a `properties` object (may be `{}`) |+| `openRoot` | `open-root` | `:288-290` | root must declare `additionalProperties: false` |+| `missingDescription` | `missing-description` | `:293-298` | every `property`-kind node needs a non-blank string `description` (only property nodes — not root, items, or values) |+| `missingType` | `missing-type` | `:300-302` | EVERY node must declare `type` or `enum` |+| `undeclaredRequired` | `undeclared-required` | `:304-312` | every `required` entry must name a property that node declares |+| `unsupportedComposition` | `unsupported-composition` | `:269-278` | `oneOf`, `anyOf`, `allOf`, `$ref` and tuple-form `items: [...]` are all rejected |++Scope is INPUT schemas only (`auditSchemaCompleteness` `:251-261`;+rationale `:238-250`).++Preview budgets: `PREVIEW_BUDGET_EXEMPT` name→reason map at `:327-401`;+`auditPreviewBudgets` (`:423-438`) reports unbudgeted-and-unexempted,+stale exemptions, and exemptions naming dead tools. Default constant+`MCP_PREVIEW_BUDGET = 2000` at `src/mcp/preview-budget.ts:23`.++### 4.4 How the catalog documents itself++Three surfaces, no per-tool metadata beyond name and description.++1. `second_brain_capabilities` — `evaluateToolCapabilities`+ (`src/mcp/capabilities.ts:27-69`) walks the table and emits+ `{scope, server_name, static_tool_count, available_tool_count,+ available[], withheld[]}`. Always available, never counted against+ `maxTools` (`:40-47`). A new tool appears automatically.+2. `tool_hydrate` — `src/mcp/hydrate-tool.ts:23`, built over a late-bound+ getter (`:32-81`). No args → `{count, catalog:[{name, description,+ group}]}` (`:50-61`); `names: [...]` → full schemas plus a per-name+ `unknown` list (`:62-78`).+3. `toolDescriptors` — `src/core/surface/descriptor.ts:67-81`. Two+ derivations to design around:+ - `description` = `firstLine(t.description)` (`:74`, `firstLine` at+ `:40-46`). **Put the summary sentence first; the catalog shows only+ line 1.**+ - `group` = `surfaceGroup(name)` (`:56-60`): `second_brain_*` → `core`;+ first `_`-segment in `GROUP_PREFIXES = ["brain","schema"]` (`:48`) →+ that prefix; everything else → `core`. **The name prefix is the only+ grouping mechanism.** `tags` is always `[]` for tools (`:76`).++To be always-loaded on the writer server: add to `WRITER_TOOL_NAMES`+(`src/mcp/tools.ts:421-427`) AND to `WRITER_SET` in+`src/mcp/profiles.ts:30-36` — the profile copy is separate and+hand-maintained. Profiles are `TOOL_SURFACE_PROFILES` at+`profiles.ts:38-77`; `recall` (`:59-66`) and `minimal` (`:74`) carry+hardcoded allow-lists, so a new tool is withheld from those hosts unless+added. Unknown profiles fail OPEN to full (`:121-145`).++**There is no tool-annotation surface.** No `readOnlyHint`,+`destructiveHint`, `idempotentHint`, `openWorldHint` or `annotations`+anywhere in `src/`, `tests/` or `docs/`. Read-only-ness is conveyed as+prose in the description, e.g. `landscape-tools.ts:31` ends "Read-only.".++### 4.5 `_meta.progressToken` after v1.48.0++`readProgressToken(params)` at `src/mcp/progress.ts:97-114`. `_meta`+absent → `undefined` (`:99`); `_meta` non-object → `INVALID_PARAMS`+(`:100-105`); `_meta` without a token → `undefined`, not an error+(`:106-107`); the token is a string or an INTEGER number only (`:108-109`),+anything else → `INVALID_PARAMS` naming what arrived (`:110-113`).+`type ProgressToken = string | number` (`:61`).++Server plumbing in `handleToolsCall` (`src/mcp/server.ts:352`):++1. `readProgressToken(params)` at `:366`, deliberately BEFORE the handler+ runs (`:363-365`);+2. `progressSink(token, this.sendNotification)` at `:367`+ (`progress.ts:149-155` returns `undefined` when there is no token or no+ writer);+3. when the transport cannot carry it,+ `progressRefusal(token, PROGRESS_REASON.transportSingleResponse)` at+ `:371-374` (shape at `progress.ts:158-165`);+4. the sink is handed to the handler through the single seam at `:376`,+ forwarded to `tool.handler(this.context, args, onProgress)` at+ `:205,209`;+5. the refusal is attached to BOTH success and error envelopes+ (`:377,384`); `withProgressRefusal` (`progress.ts:173-179`) returns the+ result untouched when there is no refusal, so a call that asked for+ nothing is byte-identical to v1.47.++Wire format: `PROGRESS_NOTIFICATION_METHOD = "notifications/progress"`+(`progress.ts:46`); namespaced meta key+`PROGRESS_META_KEY = "open-second-brain/progress"` (`:53`); frame builder+`progressNotification` (`:125-139`) emits the spec fields `progressToken`,+`progress` (= `event.completed`), optional `total`, plus the typed event+under `_meta[PROGRESS_META_KEY]`.++`sendNotification` is an optional runtime option (`server.ts:67-81`):+stdio supplies it, HTTP does not — which is exactly what turns an HTTP+token into a NAMED refusal rather than a silent drop (`progress.ts:11-21`).++A long-running new tool must:++1. declare `onProgress?: ProgressSink` as the third handler parameter+ (pattern: `src/mcp/brain/feedback-tools.ts:346-350`,+ `src/mcp/brain/admin-tools.ts:253`);+2. forward it conditionally into the core options object:+ `...(onProgress ? { onProgress } : {})` (`feedback-tools.ts:429,522`,+ `admin-tools.ts:307`);+3. if it is a `view` dispatcher, use+ `dispatchByView(table, ctx, args, onProgress)`+ (`src/mcp/brain/shared.ts:207-231`; the docblock at `:196-206` names+ dropping the sink as the exact defect to avoid);+4. bound the call with a safeguard from+ `safeguard_timeout_<operation>_seconds`+ (`feedback-tools.ts:427` uses `toolSafeguard(ctx, OPERATION.dream)`).++### 4.6 Every test a NEW MCP tool must satisfy++- `tests/mcp/registry-guard.test.ts` — description caps (`:43-49`),+ `previewBudget` or an exemption (`:53-56`), no stale exemptions+ (`:58-62`), reason length (`:64-68`), **zero completeness violations+ across the whole table** (`:126-128`).+- `tests/mcp/agent-scope-matrix.test.ts` — the strictest gate.+ `:301-309` requires `SCOPED_SURFACES` (`:66-81`) ∪ `UNSCOPED_CONTENT`+ (`:88-114`) ∪ `NON_CONTENT` (`:117-206`) to equal the full tool table in+ BOTH directions. `:313-315` is+ **`expect(TOOLS.length).toBe(110)`** — the only hardcoded tool count in+ the suite. `:317-330` requires argument-scoped surfaces to declare+ `agent_scope`.+- `tests/mcp/brain-tools-parity.test.ts` — `FROZEN_BRAIN_TOOL_NAMES` at+ `:61-154` (93 names) must equal `BRAIN_TOOLS` exactly (`:157-160`);+ no duplicates (`:162-165`); every tool has a function handler and a+ defined `inputSchema` (`:167-172`).+- `tests/mcp/mcp.test.ts:170-353` — `tools/list` names must EQUAL an+ exhaustive inline array of all 110 names; `:351-353` every advertised+ `inputSchema.type === "object"`. `:569-593` pins the error shape:+ `isError: true`, no `structuredContent`, `content[0].text` containing+ `"<tool> output contract failed"`.+- `tests/mcp/catalog-scope.test.ts` — advertised set (`:28-32`), catalog+ length equals full length (`:34-40`), and `:62-63` every description's+ first line is non-empty and single-line.+- `tests/mcp/scope-filter.test.ts:27-40` — writer-scope entries must be+ the SAME object instances as full scope, so never clone in a filter.+- `tests/mcp/profiles.test.ts:56-73` — `minimal` equals exactly 7 names.+- `tests/mcp/argument-guard.test.ts`, `tests/mcp/output-contract.test.ts`,+ `tests/mcp/consolidated-tools.test.ts:239-270`,+ `tests/mcp/removed-tools.test.ts`,+ `tests/mcp/runtime-capabilities.test.ts`,+ `tests/mcp/brain.test.ts:816-1026`,+ `tests/cli/mcp-writer-probe.test.ts:35-42`,+ `tests/openclaw/bundle.test.ts:37-48`.+- `tests/mcp/long-running-tools.test.ts` and+ `tests/mcp/progress-token.test.ts` for anything that takes a token.+- `src/mcp/` is a declared vault-write root+ (`write-site-census.test.ts:81`), so a direct `node:fs` write in a new+ tool module needs an exclusion entry.+- Import types from `./tool-contract.ts`, never from `./tools.ts` — that+ is the whole reason the contract module exists+ (`src/mcp/tool-contract.ts:1-13`), and `import-cycles.test.ts` is what+ catches the mistake.++### 4.7 Hardcoded lists to update, loudest first++1. `tests/mcp/agent-scope-matrix.test.ts:314` — the `110` count.+2. `tests/mcp/agent-scope-matrix.test.ts` — classify the name into+ exactly one of the three tables.+3. `tests/mcp/brain-tools-parity.test.ts:61-154` — add alphabetically,+ extend the header rationale at `:1-55`.+4. `tests/mcp/mcp.test.ts:180-346` — the exhaustive `tools/list` array.+5. `src/mcp/registry-guard.ts:327-401` — set `previewBudget` or add an+ exemption with a > 10-char reason.+6. Only if writer/catalog/profile-scoped: `src/mcp/tools.ts:421-427`,+ `:432-436`, `src/mcp/profiles.ts:30-36`, `:59-66`, `:74` — and then+ also `tests/mcp/scope-filter.test.ts:18-24`,+ `tests/mcp/catalog-scope.test.ts:18-26`,+ `tests/mcp/profiles.test.ts:64-72`,+ `tests/mcp/brain.test.ts:1013-1025`,+ `tests/cli/mcp-writer-probe.test.ts:36-42`.+7. `docs/mcp.md:145+` Tool Highlights table (documentation only, not+ test-enforced) and `CHANGELOG.md`.++There is no `.snap` file and no generated tool manifest.++---++## 5. CLI surface++### 5.1 Registration — three switch dispatchers plus a parallel manifest++There is no registry object. "The dispatcher is a small `switch`+statement, not a registry" (`src/cli/main.ts:7-8`). Four enumerable+levels, all four named as the authoritative population by+`tests/cli/manifest-completeness.test.ts:140-167`:++| Level | Dispatcher |+|---|---|+| `o2b <cmd>` | `src/cli/main.ts:964-1028` |+| `o2b brain <verb>` | `src/cli/brain.ts:174-461` (~140 verbs; ratchet floor > 130 at `manifest-completeness.test.ts:216`) |+| `o2b search <verb>` | `src/cli/search.ts:31-48` (`KNOWN_VERBS`) and `:61-97` (switch) |+| `o2b partner codegraph <verb>` | `src/cli/partner.ts` (frozen `CODEGRAPH_VERBS`) |++The machine-readable half is `src/cli/command-manifest.ts`. Types at+`:1-12`; one entry's shape at `:42-46`; constructors `command(...)`+`:717-729` and `flag(name, type)` `:731-733`; `--json` is injected onto+every node by `addInheritedFlags` (`:734-754`), exposed through+`manifestForJson()` (`:653-655`).++**A new top-level verb must supply:**++1. a `case` before `default:` in `src/cli/main.ts:964-1013` (the census+ parser bounds on `default:` —+ `manifest-completeness.test.ts:74-81`);+2. a handler taking `argv: string[]`, parsing via `parseFlags(argv,+ schema)` (`src/cli/argparse.ts:38`);+3. a `command(...)` node with a **non-empty** summary+ (`manifest-completeness.test.ts:298-302`) declaring EVERY flag it+ parses with the matching type;+4. a `--json` ownership decision (§5.2);+5. a terminal-state class (§5.7).++**A new brain verb additionally must:**++1. live in `src/cli/brain/verbs/<new>.ts`;+2. be re-exported from the barrel `src/cli/brain/verbs/index.ts`;+3. have a `case` in `src/cli/brain.ts:174-456`;+4. have a `command(...)` node under the `brain` node;+5. have a line in `BRAIN_HELP` **and** an entry in `VERB_HELP`+ (`src/cli/brain/help-text.ts:31+` and `:176`). An unmatched+ `VERB_HELP[verb]` dumps the whole `BRAIN_HELP` and returns **2**, so+ `o2b brain <new> --help` is a usage error until you add it+ (`src/cli/brain.ts:163-171`);+6. import helpers ONLY through `src/cli/brain/helpers.ts` — "never+ directly from `../argparse.ts`, `../output.ts`, `../coerce.ts`, or+ `../helpers.ts`" (`:4-11`).++A new search verb must be added to **both** `KNOWN_VERBS`+(`src/cli/search.ts:31-48`) and the switch (`:61-97`) — asserted equal at+`manifest-completeness.test.ts:221-228` — plus the `COVERED` table in+`tests/cli/search-query-flag-manifest.test.ts:32-45`.++### 5.2 `--json`++Acceptance is structural: `parseFlags` injects a boolean `json` into any+schema that omits it (`src/cli/argparse.ts:39-40`), so no verb can reject+`--json` as unknown. That backs the banner claim at+`src/cli/help-render.ts:60-62`.++Two families, one fact table. `ownsInternalJson(command, rest)`+(`src/cli/json-helpers.ts:68-73`) is "the single fact table behind two+questions" (`:60-67`): which invocations `main` must wrap, and which+stdout streams advisory chrome would corrupt. The set of 12+internal-JSON commands is at `:45-58` (`status, install, update,+tool-call, secrets, brain, search, vault, discipline, partner, doctor,+onboarding`), plus two argv-resolved extras: `mcp` only with `--probe`,+and `help` always (`:70-73`).++Everything else is wrapped: `src/cli/main.ts:957-961`.+`withJsonFallback` patches BOTH `process.stdout.write` and+`process.stderr.write` into accumulators for the whole run+(`json-helpers.ts:94-114`), restores in `finally`, then emits+`{ ok, command, code, stdout, stderr }` with `redactSecrets` applied+(`:116-120`, redaction at `:75-86,123-125`). Asserted at+`tests/cli/cli-json-contract.test.ts:35-47` and `:75-86`.++Semantic payloads use either `okJson(payload)` →+`{ ok: true, ...payload }` (`src/cli/output.ts:15-17`, the brain-verb+house style) or `JSON.stringify(payload, sortedReplacer, 2)`+(`src/cli/main.ts:102,216,403`).++`wantsJsonFlag(argv)` (`src/cli/main.ts:32-38`) is the raw-argv scan used+only at the two pre-parse call sites. **Never feed it to the rails**; they+require the verb's PARSED flag (`src/cli/advisory-rail.ts:22-25`).++**There is no per-verb `--json` census.** `cli-json-contract.test.ts`+samples four cases; `advisory-rail.test.ts:185-195` loops over+`COMMANDS_WITH_INTERNAL_JSON`. Known gaps: `o2b secrets --json` exits 2+because `cmdSecrets` dispatches on `argv[0]` before parsing+(`src/cli/main.ts:483-498`); search verbs have no per-verb `--help`.++If the verb has a registered diagnostic code, spread+`nextCommandField(code)` into the payload so `--json` carries the exit+under `next_command` (`src/core/brain/next-step.ts:80-99`; example+`src/cli/main.ts:101`; obligation stated at+`tests/cli/json-next-command.test.ts:1-20`).++### 5.3 The advisory rail++`src/cli/advisory-rail.ts` is the single emission point for every+forward-pointer line, "and through nothing else" (`:1-8`).++- Label `NEXT_STEP_LABEL = "next:"` (`:37`); line is+ `` `${NEXT_STEP_LABEL} ${step.nextCommand}` `` (`:91-93`).+- Stream is **stdout**, via `info()` (`:122`; `src/cli/output.ts:26-28`).+- **There is no parameter for prose.** The caller passes a diagnostic+ CODE, resolved through `resolveNextStep` (`:31,104`). A sentence passed+ where a code belongs resolves to nothing+ (`tests/cli/advisory-rail.test.ts:116-128`).+- `ADVISORY_OUTCOME` (`:53-60`): `emitted`,+ `suppressed-machine-stream`, `unregistered-code`. `AdvisoryEmission`+ (`:65-78`) is frozen and echoes the `code` back.+- `advisoryIsLegal(stream)` (`:85-88`): legal unless `jsonRequested` and+ the command owns internal JSON.+- `emitNextStep` (`:103-124`) never throws, and **suppression is not a+ drop** (`:26-28`) — the resolved step is still attached.+- `emitNextSteps` (`:142-161`) de-duplicates on the resolved COMMAND, not+ the code (`:126-140`).++Opt in with `emitNextStep("<registered-code>", { command, argv,+jsonRequested: Boolean(flags["json"]) })` — canonical+`src/cli/main.ts:120-126`, also `src/cli/brain/verbs/bridges.ts:145`.++Gating tests: `tests/cli/advisory-rail.test.ts` (365 lines) and+`tests/cli/advisory-claim-truth.test.ts` — **a registered terminal state+fires only where its claim holds** (`:1-15`). The trap for a new verb is+the audit at `:198-246`: a hardcoded `GUARDED` table of+`[file, code, guard]` triples (`:204-223`) asserting that EVERY+occurrence of a code string in that file is textually preceded by its+guard expression (`:232-234`). A new rail call site in an already-listed+file must add its guard text.++### 5.4 The progress rail++`src/cli/progress-rail.ts`.++- Stream is **stderr**, never stdout (`:14-16`, default writer+ `:158-160,203-205`). Format is **NDJSON**, one `JSON.stringify(event)`+ per line (`:123-125`), because a partial line is self-evidently partial+ (`:116-121`).+- `PROGRESS_OUTCOME` has exactly two members (`:55-81`): `emitted`+ (`:57`) and `suppressedBufferedStream` (`:80`). The comment at+ `:58-79` is load-bearing: **no shipped command reaches the second one+ today**, and the branch is kept because deleting it removes the check.+- The buffered-stream rule (`:109-112`) is the **exact inverse** of the+ advisory rule, deliberately (`:96-108`):++```ts+export function progressIsLegal(stream: ProgressStream): boolean {+ if (!stream.jsonRequested) return true;+ return ownsInternalJson(stream.command, stream.argv);+}+```++ Rationale: `withJsonFallback` accumulates stdout AND stderr, which makes+ an advisory line harmless but a progress line worthless — "not degraded,+ it is invisible until the run finishes and then dumped at once - which+ reads as though it had worked" (`:19-22`). The dependency is asserted,+ not trusted (`tests/cli/progress-rail.test.ts:92-113`).+- **There is no TTY detection in the progress rail.** No `isTTY`+ reference exists in the file. TTY sniffing lives only in the+ confirmation path (`src/cli/brain/verbs/lint.ts:25`, `page-dedup.ts:24`,+ `rollback.ts:162`, `upgrade.ts:72`, `merge.ts:68`,+ `import-claude-memory.ts:87`). Do not add it to a progress path.+- `attachProgress(stream, write = process.stderr.write)` (`:156-180`)+ returns a frozen attachment: refused →+ `{ outcome: suppressedBufferedStream, sink: undefined, reason:+ PROGRESS_REASON.streamBuffered }`; legal → `{ outcome: emitted, sink }`+ where the sink throws `TypeError` on an unknown `event.kind` (`:169-178`).+ `sink: undefined` on refusal is the house idiom for "nobody asked"+ (`:131-136`).+- `reportProgressRefusal(attachment | null)` (`:201-209`) writes+ `progress: not emitted (<reason>)` and must be called **before** the+ operation starts (`:190-195`).++Standard verb wiring, copy this shape+(`src/cli/brain/verbs/bridges.ts:151-176`):++```ts+const observation =+ flags["progress"] === true+ ? attachProgress({ command: "brain", argv: ["bridges"], jsonRequested: asJson })+ : null;+reportProgressRefusal(observation);+// …+...(observation?.sink !== undefined ? { onProgress: observation.sink } : {}),+```++Progress is opt-in because attaching by default would change the stderr+of every existing invocation (`:152-155`). Shared search helper:+`observeIndexRun` at `src/cli/search/verbs/indexing.ts:98-107`. Declare+`flag("progress", "boolean")` in the manifest+(`src/cli/command-manifest.ts:538,548,592`).++### 5.5 Exit codes++There is **no single central registry**; codes are declared per surface+as frozen tables with a written cross-surface pinning discipline.++Dispatcher-wide (`src/cli/main.ts`): 0 success; **1 = "a machine that+cannot answer the question"** (`NoVaultConfiguredError`,+`ConfigReadError` — `:1019-1025,1030-1041`); **2 = "a mistake in the+argv"** (`CliError` — `:1014-1018,1033-1035`; unknown command+`:1009-1012`). Stated verbatim at `:1033-1035`.++| Table | Anchor | Members |+|---|---|---|+| `DOCTOR_EXIT` | `src/cli/main.ts:298-302` | `ok:0, failed:1, probeIncomplete:6`; precedence `:314-321` |+| `SEARCH_CHECK_EXIT` | `src/cli/search/verbs/check.ts:107-113` | `ok:0, fatal:1, providerUnreachable:5, probeIncomplete:6`; precedence `:129-144` |+| `MAINTENANCE_EXIT` | `src/cli/brain/verbs/maintenance.ts:81-86` | `ok:0, failed:1, usage:2, refused:7` (7 not 6, argued at `:55-80`) |+| `INSTALL_EXIT` | `src/cli/install/install.ts:58-65` | `ok:0, runtimeError:1, usage:2, drift:3, userModifiedBlock:4, mcpUnreachable:5` |+| signals | `src/cli/interrupt.ts:84-102` | `EXIT_INTERRUPTED=130`, `EXIT_TERMINATED=143` |++**Sub-dispatcher divergence, worth knowing:** `src/cli/brain.ts:462-467`+maps `CliError → 1`, while `src/cli/main.ts:1014-1018` maps+`CliError → 2` and `src/cli/search.ts:98-117` maps `CliError → 2`,+`SafeguardTimeoutError → 1`, `SearchError → 2 | 1`.++Rule for a new code (`main.ts:284-297`, `check.ts:100-106`,+`maintenance.ts:55-80`, enforced at `tests/cli/doctor-exit.test.ts:78-85`):++1. name it once in a frozen table with a+ `type X = (typeof X)[keyof typeof X]` alias;+2. **reuse the number if the meaning already exists** — one number means+ one thing across this CLI;+3. write the agreement assertion plus a uniqueness check;+4. follow `exitCodeForCheck` precedence — the proved fault keeps the+ generic code, the specific code never masks it;+5. never take 2 for anything but an argv error, nor 130/143.++### 5.6 The confirmation ladder and `--expect N` / `--strict`++The ladder, stated canonically at+`src/core/brain/notes/lifecycle.ts:19-22`, in execution order:++1. **Dry run is the default**; `--apply` / `--confirm` is required to+ mutate (`src/cli/brain/verbs/note-lifecycle.ts:14-17`,+ `forget-source.ts:5-11`).+2. **Preview, then guard, then mutate**: run the operation with+ `confirm: false` to compute the blast radius, assert the guard against+ it, and only then re-run with `confirm: true`+ (`src/cli/brain/verbs/forget-source.ts:51-71`).+3. **A second confirmation for the irreversible arm** — a named refusal,+ not a bare throw+ (`src/core/brain/notes/lifecycle.ts:775-781`, code in the closed+ vocabulary at `:313-314`).+4. **Non-interactive guard**: `--yes` is mandatory under `--json` or a+ non-TTY stdin (`src/cli/brain/verbs/lint.ts:25-27`, same shape in five+ other verbs).+5. **Recovery point**: `withDestructiveSnapshot(vault, reason, op, opts)`+ takes the archive BEFORE `op` runs+ (`src/core/brain/snapshot-gate.ts:360-377`); a throw in `takeSnapshot`+ aborts before any destructive work (`:366-369`).+6. **Report the verdict**: surface `recoverability.state` and `blockers`+ on both output shapes (`forget-source.ts:113-125`,+ `note-lifecycle.ts:43-47`).++`src/core/brain/count-guard.ts`:++- `CountGuardError` carries `code = "COUNT_GUARD"`, `matched`,+ `expected`, `matchList` (`:12-25`).+- `assertExpectedCount(opts)` (`:48-72`): `expected !== matched` →+ `--expect N but the operation matched M; aborting without writing.`+ (`:52-60`); `strict && expected === null && willMutate` →+ `--strict refuses a guardless mutation: pass --expect M …` (`:62-71`).+- The matched list is inlined, capped at `MATCH_LIST_PREVIEW = 20`+ (`:41,74-82`).+- Both guards default off, so a verb passing neither is byte-identical to+ before (`:8-9`).++CLI-side pattern: `expect: { type: "string" }`,+`strict: { type: "boolean" }`, then `Number(...)` with+`!Number.isInteger(n) || n < 0` → usage error+(`note-lifecycle.ts:106-107,123-127`, `forget-source.ts:23-24,35-43`).+Then `assertExpectedCount({ matched: preview.blastRadius, expect, strict,+willMutate: confirm, matchList: [...] })` (`forget-source.ts:58-68`) —+note `willMutate` is the confirm flag, not `true`.++**A new destructive verb must** take dry-run-by-default plus `expect` and+`strict`; compute the blast radius with a non-mutating probe; call+`assertExpectedCount` before any write; catch `CountGuardError` and+report it parseably under `--json`; put the removal lexically inside+`withDestructiveSnapshot(` if it lives under `src/core/brain/`, or accept+a `DESTRUCTIVE_SITES` entry (§2.2); and surface the recoverability+verdict.++Two gating subtleties from the destructive census: a removal extracted+into a named helper handed to the gate is **not** lexically gated and+must declare (`destructive-site-census.test.ts:65-73`, pinned `:858-868`);+a gate named only in a comment gates nothing (`:848-856`). The census+reaches only `src/core/brain/` (`:110-114`) — CLI verbs and the MCP+surface are a separate population, held by the write-site census instead.++### 5.7 Help-surface parity, and the terminal-state census++`tests/cli/help-surface-parity.test.ts`. The files that must agree are+exactly **two, both derived from one source**: the human `o2b help`+rendered by `src/cli/help-render.ts:110-118`, and `o2b help --json`+serialising `manifestForJson()` (`src/cli/main.ts:893-894`). Both derive+from `CLI_COMMAND_MANIFEST` (`src/cli/command-manifest.ts:26`).+**README.md, `skills/*`, `docs/cli-reference.md` and the plugin manifests+are NOT in this test.**++Assertions: path sets equal in both directions (`:87-95`); every summary+verbatim (`:97-108`); every declared flag list verbatim and in order+(`:110-124`); anti-vacuity `human.size > 180` and > 10 flagged entries+(`:126-131`); `o2b help --json` deep-equals `manifestForJson()`+(`:133-137`). Plus spot checks at `:140-172` and, at `:174-185`, an+unknown command's stderr must list EVERY top-level manifest command and+mention `o2b help`.++The parse contract: `ENTRY_RE` two-space indent and ≥ 2-space gutter+(`:31`), `FLAGS_RE` six-space indent (`:33`), matched by+`help-render.ts:51-55,84-88`. Inherited `--json` is excluded on both+sides (`:68-72`, `help-render.ts:69-73`).++**Do not hand-edit `help-render.ts`** — the human surface is derived, and+hand-editing it is the exact defect the derivation removed+(`help-render.ts:1-19`).++`tests/cli/terminal-state-census.test.ts` (573 lines) enumerates from the+same three dispatchers and requires each terminal state to hold exactly+one of three classes (`:1-21,75-79`): `names-an-exit` (detected by+`/emitNextSteps?\(/`, `:66`), `names-a-refusal` (detected by+`/\bfail\(|\bfailWith\(|usageError\(|CliError|throw new |process\.stderr\.write\(/`,+`:69-71`), or `deliberately-silent` — which currently has **zero+members** (`:531`). The import walk follows one hop into sibling modules+(`:24-38`), and anything classified only via that hop needs a+`CLASSIFIED_BY_MODULE_WALK` entry with a reason (`:33-37`, gated+`:456-481`). Floors: > 160 rows, > 8 exits, > 120 refusals (`:485-487`).++**Practical consequence: a new verb that can only `return 0` silently+fails this census by name** until it gains an exit, a refusal, or a+written exclusion.++`tests/cli/manifest-completeness.test.ts` closes the loop+dispatcher↔manifest in both directions (`:170-193`). The four+unlisted-exclusion tables (`:50-62`) are all currently **empty**, so any+exclusion is a new precedent and needs a reason of at least+`MIN_REASON_LENGTH = 10` chars (`:196-209`).++## 6. Config — adding a `Brain/_brain.yaml` key++### 6.1 Where the pieces live++- Typed shape: `BrainConfig` at `src/core/brain/types.ts:1577`; per-block+ optional members (e.g. `health?: BrainHealthConfig` at `:1669`), block+ types near `:1925` and `:1955`.+- Re-export surface: `src/core/brain/policy.ts:36-127` (pure re-exports;+ the implementation is split under `src/core/brain/policy/`, explained+ at `policy.ts:21-33`).+- Validator: `src/core/brain/policy/validate.ts:75`+ (`validateBrainConfigDetailed`); ordered block calls at `:98-122`;+ assembled literal at `:126-153`; mandatory `schema_version` seeded at+ `:91`; unknown top-level keys are a WARNING, never an error+ (`validate.ts:191`, `warnUnknownTopLevelKeys`).+- Key vocabulary, by construction:+ `src/core/brain/policy/key-index.ts:21` (`BrainConfigKeyIndex`),+ `:100` (`warnUnknownKeys`). Enumeration entry point used by the+ ratchet: `brainConfigKnownKeys()` at+ `src/core/brain/policy/validate.ts:220` — a two-pass probe (`:208-233`).++**Two homes for a default, and the distinction is load-bearing**:++1. Write-side (what `brain init` writes, and the merge base):+ `DEFAULT_BRAIN_CONFIG` at `src/core/brain/policy/defaults.ts:40`.+ Only the grandfathered live blocks are here.+2. Read-side (block absent → this table decides): beside the block+ parser in `src/core/brain/policy/blocks/*.ts`, e.g.+ `BRAIN_HEALTH_DEFAULTS` at+ `src/core/brain/policy/blocks/health.ts:54`, resolver `:68`, parser+ `:92`, sub-key registration `:124-129`.++`defaults.ts:5-8` states the rule: a read-side-only default must NOT go+in `defaults.ts`.++### 6.2 The template is generated TypeScript, not a file under `templates/`++There is no YAML config template on disk. `templates/` holds only+`brain-starter/`, `brain-explorer.html`, `identity-reminder.*` and+`install/`. The `_brain.yaml` template is generated by+`src/core/brain/config-template.ts`, terminating at+`src/core/brain/config-template.ts:676`+(`export const DEFAULT_BRAIN_CONFIG_YAML = renderBrainConfigTemplate();`).+Rationale for the location — a module-init cycle if it lived in the+config layer — at `src/core/brain/policy/defaults.ts:67-71`.++Structure:++- Emission vocabulary at `config-template.ts:83`:+ `"live" | "commented-default" | "commented-example"`, each meaning+ documented at `:72-82`.+- `BrainTemplateKey` at `:87`, `BrainTemplateBlock` at `:100`,+ `BrainTemplateOmission` at `:110`.+- Constructors: `live()` `:125`, `def()` `:134` (commented AT the+ resolver default), `example()` `:142` (no default exists; the value is+ an illustration).+- `BRAIN_CONFIG_TEMPLATE` at `:155` — the whole file, block by block.+ **Values are read from the default tables, never re-literalled**+ (e.g. `:180` reads `DEFAULT_BRAIN_CONFIG.dream.candidate_threshold`).+- The live/commented boundary is a literal comment line at `:275-276`.+ Above it: the seven grandfathered live blocks (`schema_version`,+ `primary_agent`, `dream`, `retire`, `confidence`, `snapshots`,+ `vault`). Below it: everything is commented.+- `BRAIN_CONFIG_TEMPLATE_OMISSIONS` at `:574` — one entry today,+ `hygiene.dedup_threshold` (`:576-581`).+- `renderBrainConfigTemplate({ allDefaultsLive? })` at `:642`.+- Rationale for commented-not-live (a live default pins today's value+ into every new vault and defeats a future default change) at `:16-41`.++### 6.3 The four ratchet assertions++`tests/core/brain/config-template-ratchet.test.ts`,+`describe("config template ratchet — coverage")`, `:192-240`:++1. `:197` every top-level key the resolver understands is templated or+ justified by an omission.+2. `:204` every sub-key the resolver understands is templated or+ justified (an omission may be keyed `block.sub` or the whole `block`,+ `:212`).+3. `:219` the template names no key the resolver does not understand —+ the reverse direction, top level and sub-key.+4. `:234` every omission carries a non-empty reason and is not also+ templated.++### 6.4 The commented-vs-live rule++`config-template-ratchet.test.ts:255-264`, test+`"newly exposed keys are emitted commented, never live"`: for every+template key whose `emit !== "live"`, no line of+`DEFAULT_BRAIN_CONFIG_YAML` may match `^\s*<key>\s*:`.++**A newly added key may only be `commented-default` or+`commented-example`.** Adding a `live()` key fails this test AND the+live-surface byte-identity test at `:251`, which compares+`liveSurface(DEFAULT_BRAIN_CONFIG_YAML)` against the v1.38.0 template+text inlined on purpose at `:68-112`.++Three further pinned properties in the same file: the generated YAML+round-trips with zero warnings (`:243`); resolved-behaviour identity+between `renderBrainConfigTemplate({ allDefaultsLive: true })` and a bare+`schema_version: 1` (`:268`, compared through the **hand-maintained**+`resolvedView` at `:132-190`); and a pre-generation config resolves+identically (`:274`).++### 6.5 Exact steps for a new sub-key `foo` on an existing block `X`++1. `src/core/brain/types.ts` — add the optional field to `BrainXConfig`+ (and to the resolved twin if the block has one).+2. `src/core/brain/policy/blocks/X.ts` — add the default to+ `BRAIN_X_DEFAULTS`, read it in `resolveX`, validate it in+ `parseXBlock`, and **add the key name to the `warnUnknownKeys(...)`+ known-list**. That call is what registers the sub-key in the key+ index; skip it and the validator accepts the key while+ `brainConfigKnownKeys()` never reports it, so ratchet assertion 3+ fires on the template entry.+3. Only if `brain init` must WRITE the key into a live block, also add it+ to `DEFAULT_BRAIN_CONFIG` (`policy/defaults.ts:40`). For a commented+ key, do not.+4. `src/core/brain/config-template.ts` — add+ `def("foo", <DEFAULT_FROM_THE_TABLE>, [...doc])` (or `example(...)`)+ to block `X`'s `keys` array in `BRAIN_CONFIG_TEMPLATE` (`:155`).+ **Never `live(...)`.** Import the default constant; do not repeat the+ literal. The alternative is a `BRAIN_CONFIG_TEMPLATE_OMISSIONS` entry+ (`:574`) with a substantive reason.+5. If the key participates in resolution, extend `resolvedView` in+ `tests/core/brain/config-template-ratchet.test.ts:132` (and its+ imports at `:33-59`), or the all-defaults-live identity test silently+ stops covering it.+6. For a NEW top-level block, additionally: write+ `policy/blocks/<block>.ts`, call its parser from+ `validate.ts:98-122`, spread it into the literal at `:126-153`,+ re-export from `policy.ts:36-127`, and add a whole+ `BrainTemplateBlock` with `emit: "commented-default"` or+ `"commented-example"`.+7. Run `bun test tests/core/brain/config-template-ratchet.test.ts+ tests/core/brain.policy.test.ts tests/core/brain/upgrade.test.ts`.++`upgrade.ts:357` (`mergeBrainYaml`) is purely additive (`:355`): missing+keys are appended or spliced; nothing is deleted, reordered, or+rewritten.++**Docs are not gated.** `README.md:31,125`,+`skills/open-second-brain/SKILL.md:15`, `docs/how-it-works.md`,+`docs/architecture.md`, `docs/updating.md` mention config keys in prose,+and no test asserts them against the schema. The generator plus the+ratchet is the only mechanized key inventory; prose is updated by+judgement.++---++## 7. Doctor — adding a check++### 7.1 Registry and check shape++`src/core/brain/doctor.ts` is the registry only (`:9-14`); the 20 check+modules live under `src/core/brain/doctor/`.++- `DOCTOR_CHECKS` at `src/core/brain/doctor.ts:134-170`, 30 entries.+ **Order is contract** (`:127-133`): findings report in discovery+ order, and `duplicateIdCheck` (`:141`) must follow the record checks+ that fill `ctx.idIndex`. Imports at `:49-92`.+- Run loop `:268-281`: a `failSoft: false` check propagates a throw out+ of `runDoctor`; `failSoft: true` is wrapped in try/catch.+- Two pre-registry early returns: unreadable Brain root `:209-227`,+ absent Brain root `:228-260` (`BRAIN_ROOT_ABSENT_CODE` at `:175`).+- `checkSemanticHealth` sits outside the registry at `:283-295`.++Contract at `src/core/brain/doctor/check.ts`: `DoctorCheckContext` `:23`+(note `now` at `:26` — read time from `ctx.now`, never `new Date()`, so+age lints are pinnable), `DoctorFindings` `:59` (two streams: `issues`+and `uncertain`), `DoctorCheck` `:64` (exactly `failSoft: boolean` and+`run(ctx, out): void`; the `failSoft` semantics are documented at+`:65-73`). `check.ts:8-9`: "A new check joins the pass by being added to+the registry array in `doctor.ts`."++Canonical simple check: `src/core/brain/doctor/config-checks.ts:27`.+Canonical recent check with hoisted code constants:+`src/core/brain/doctor/embedding-sunset-check.ts:78-84`.++### 7.2 `DOCTOR_REGISTERED_CODES`++Defined at `tests/core/brain/doctor-exit-census.test.ts:177-202` — a+24-entry frozen list living in the TEST, not in `src/`. Why, at+`:163-176`: `DIAGNOSTIC_SIGNALS` holds far more than doctor codes, so+nothing derivable from it says which entries the doctor still spells.++Asserted at `:252-260` as a set equality against `doctorCodes()`, which+is a syntactic scan (`:225`) over `DOCTOR_SOURCE_PATHS` (`:119-122` —+`doctor.ts` plus a recursive walk of `doctor/` plus every module reached+through a `*_CODE` import) matching `code: "<literal>"` (`:127`) and+`const <NAME>_CODE = "<literal>";` (`:130`).++### 7.3 The doctor exit census++`tests/core/brain/doctor-exit-census.test.ts`. "Exit" here means the+`next:` command an operator runs, not a process exit code.++| Line | Assertion |+|---|---|+| `:237` | no code is in neither `DIAGNOSTIC_SIGNALS` nor `DOCTOR_EXIT_EXCLUSIONS` |+| `:245` | no code is in both |+| `:252` | the registered subset equals `DOCTOR_REGISTERED_CODES` exactly |+| `:262` | no exclusion outlives the code it explains |+| `:268` | every exclusion reason is ≥ 80 chars (`MIN_REASON_LENGTH`, `:205`) |+| `:276` | **no exclusion reason may contain an `o2b <verb>` invocation** (`INVOCATION_RE`, `:208`) — if a command fits, it is a registration, not an excuse |+| `:283` | non-vacuity floors: source paths > 10, codes > 35, constant codes > 3, registered > 14, excluded > 20 |+| `:298` | every `code:` value is a string literal, a `*_CODE` identifier, or a declared `NON_LITERAL_CODE_SITES` entry (`:145`) |+| `:307` | every `*_CODE` identifier used as a value was read by the constant scan |+| `:320` | every `NON_LITERAL_CODE_SITES` entry still exists and carries a ≥ 80-char reason |+| `:330` | shape-guard non-vacuity: > 30 literal sites, > 2 identifier sites |++**Obligation:** every code a new check spells must be classified in+exactly ONE table, in the SAME commit.++- With a command → add a `DiagnosticSignal` to+ `src/core/brain/diagnostics.ts:125` (interface at `:77`) AND add the+ literal to `DOCTOR_REGISTERED_CODES`.+- Without one → add `{ code, reason }` to `EXCLUSIONS` at+ `src/core/brain/doctor-exits.ts:54`; ≥ 80 chars, no `o2b` invocation,+ and it must fall into one of the two admitted shapes documented at+ `doctor-exits.ts:19-32` (a JUDGEMENT over content, or an EDIT whose+ target shape is not derivable from the finding).++Published surface: `DOCTOR_EXIT_EXCLUSIONS` `doctor-exits.ts:291`+(duplicate code throws at import, `:279`), `doctorExitReason` `:306`,+`NO_EXIT_KEY = "no_exit"` `:316`, `noExitReasons` `:329`. Rendered by+`src/cli/brain/verbs/doctor.ts:70` (human) and `:174,186` (`--json`).+CLI behaviour pinned by `tests/cli/brain-doctor-next-step.test.ts:106-221`,+including byte-identity of a clean vault's output at `:212-221`.++**Do not confuse this with process exit codes.**+`tests/cli/doctor-exit.test.ts` covers `o2b doctor --readiness` (the+top-level verb): `DOCTOR_EXIT` / `doctorExitCode` from+`src/cli/main.ts` (`:22`), 0 = clean, 1 = proved failure, 6 = probe+incomplete (`:58-73`), failure outranks unmeasured (`:74-79`), and 6/0+are byte-equal to `SEARCH_CHECK_EXIT.probeIncomplete` / `.ok` (`:81-87`).+A new `brain doctor` check does not touch that table.++### 7.4 The `nextCommand` structural assertion++Field at `src/core/brain/diagnostics.ts:83` ("a structural CLI string,+never prose"). Serialized key `NEXT_COMMAND_KEY = "next_command"` at+`src/core/brain/next-step.ts:80`; `nextCommandField(code)` `:95`;+`resolveNextStep` `:36` (returns `null`, never a fabricated command);+`requireNextStep` `:68` throws `UnregisteredNextStepError` (`:47`).++Enforced at `tests/core/brain/next-step.test.ts:59-69` over EVERY entry+of `DIAGNOSTIC_SIGNALS`. All five must hold:++1. `command === command.trim()`;+2. no `\n`;+3. no double space;+4. no sentence punctuation — `SENTENCE_PUNCTUATION_RE = /[.!?;,:]/`+ (`:33`);+5. matches `STRUCTURAL_COMMAND_RE` (`:29-30`):++```+/^o2b(?: [a-z][a-z0-9-]*){1,3}(?: (?:--[a-z][a-z0-9-]*(?:=\S+)?|<[a-z][a-z0-9-]*>))*$/+```++Literal `o2b`, one to three bare lowercase verb words, then only long+flags and `<placeholder>` arguments. No bare word may follow a flag.+Conforming examples: `diagnostics.ts:132`+(`o2b brain doctor --repair --apply`), `:188`+(`o2b brain merge <keep> <drop>`), `:233`, `:489`. Counter-example+battery at `next-step.test.ts:71-85`.++### 7.5 Exact steps for a new doctor check++1. Write `src/core/brain/doctor/<name>.ts` exporting a `DoctorCheck`.+ Choose `failSoft` deliberately per `check.ts:65-73`. Read time from+ `ctx.now`.+2. Spell each code readably: `code: "<literal>"` at the push site, or+ `export const <NAME>_CODE = "<literal>";` at module scope. Avoid a+ computed code (it needs a `NON_LITERAL_CODE_SITES` entry).+3. Import in `src/core/brain/doctor.ts:49-92` and append to+ `DOCTOR_CHECKS` (`:134-170`), respecting the ordering contract.+4. Classify every code exactly once (§7.3).+5. If any applier acts on the code, add an entry to `APPLIER_CAPABILITY`+ (`src/core/brain/applier-capability.ts:147`, published at `:299`)+ declaring it `mechanical` (naming the fixer) or `refused` (naming the+ reason); otherwise `requireRepairCapability` throws+ `UnclassifiedRepairCodeError` (`:115`). Bound both ways by+ `tests/core/brain/applier-capability.test.ts:104-155`. This answers a+ different question from `doctor-exits.ts` (`doctor-exits.ts:35-42`);+ a code may legitimately be in both.+6. If the check needs a config knob, do all of §6 first. Worked+ precedent: `policy/blocks/embeddings.ts` ++ `config-template.ts:370-389` (`commented-example`) ++ `doctor/embedding-sunset-check.ts`.+7. Add `tests/core/brain/doctor/<name>.test.ts`, then run+ `bun test tests/core/brain/doctor-exit-census.test.ts+ tests/core/brain/next-step.test.ts+ tests/cli/brain-doctor-next-step.test.ts+ tests/core/brain/applier-capability.test.ts+ tests/core/brain.doctor.test.ts`.++---++## 8. Release machinery++### 8.1 The version is `package.json`, and nothing else++`CLAUDE.md:7-11` names `package.json` `version` as the single source of+truth, mirrored into six manifests plus `pyproject.toml`. Never+hand-edit a mirror (`CLAUDE.md:13-14`).++`scripts/sync-version.ts` writes exactly **seven** targets — the brief's+"seven manifests plus pyproject" is off by one; there are six manifests+plus `pyproject.toml`:++| # | Target | Declared at | Path in file |+|---|---|---|---|+| 1 | `plugin.yaml` | `scripts/sync-version.ts:26` | top-level `version:` (`plugin.yaml:2`) |+| 2 | `plugins/hermes/plugin.yaml` | `scripts/sync-version.ts:26` | top-level `version:` (`plugins/hermes/plugin.yaml:2`) |+| 3 | `.claude-plugin/plugin.json` | `scripts/sync-version.ts:28` | `$.version` (`:3`) |+| 4 | `.codex-plugin/plugin.json` | `scripts/sync-version.ts:29` | `$.version` (`:3`) |+| 5 | `plugins/codex/.codex-plugin/plugin.json` | `scripts/sync-version.ts:30` | `$.version` (`:3`) |+| 6 | `openclaw.plugin.json` | `scripts/sync-version.ts:31` | `$.version` (`:5`) |+| 7 | `pyproject.toml` | `scripts/sync-version.ts:33` | `[project] version = "…"` (`:13`) |++Deliberately NOT touched (`scripts/sync-version.ts:9-13`): `CHANGELOG.md`,+`install.md`, `docs/architecture.md`, `tests/`.++`--check` (`scripts/sync-version.ts:77-107`) writes nothing, prints+`ok:` / `DRIFT:` / `WARN no version line in …` per target, and exits **1**+when anything drifted or was unmatched (`:99-105`), else 0. Asymmetry+worth knowing: an unmatched target is fatal only under `--check`; the+write form warns and returns 0.++Scripts: `bun run sync-version` and `bun run sync-version:check`+(`package.json:47-48`).++### 8.2 When to bump — inside the feature PR++`CLAUDE.md:25-50` overrides the generic `feature-release-playbook`. The+bump rides in with the feature, before the first push, because `main` is+protected and the bump cannot be a post-merge step. Concretely:++1. Insert `## [X.Y.Z] - YYYY-MM-DD` into `CHANGELOG.md` immediately after+ line 6 (there is no `## [Unreleased]` section; the top version heading+ follows the Keep a Changelog boilerplate directly — current top+ heading is `CHANGELOG.md:8`).+2. Insert `[X.Y.Z]: https://github.com/itechmeat/open-second-brain/compare/v1.48.0...vX.Y.Z`+ as the new first line of the compare-link block, which begins at+ `CHANGELOG.md:7126`.+3. Edit `version` in `package.json:3` only.+4. `bun run scripts/sync-version.ts`, then confirm with+ `bun run scripts/sync-version.ts --check`.+5. Commit both, push, open the PR.+6. `gh release create vX.Y.Z` only AFTER the PR merges; it tags the+ already-bumped commit and never changes the version (`CLAUDE.md:48-50`).++### 8.3 `openclaw/index.js` is a committed build artifact++CI byte-diffs it: `.github/workflows/ci.yml:46-59`, step "OpenClaw bundle+is in sync with sources", rebuilds to `/tmp/openclaw-rebuild.js` and runs+`diff -q`. On drift it prints `openclaw/index.js is out of date; run: bun+run build:openclaw` and exits 1. Duplicated in+`.github/workflows/release.yml:76-87`.++Exact rebuild command (`package.json:38`):++```+bun run build:openclaw+# = bun build src/openclaw/index.ts --outfile openclaw/index.js --target=node --format=esm --external openclaw/plugin-sdk/plugin-entry+```++The flag list is copy-pasted in three places (`package.json:38`,+`ci.yml:54-57`, `release.yml:82-85`) with no shared source. The bundle is+excluded from formatting (`package.json:42-43`) so `oxfmt` cannot break+the byte-diff. `tests/openclaw/bundle.test.ts:28-73` additionally asserts+every tool registration is present and retired tools are absent — a new+MCP tool exposed through OpenClaw must be added there.++**If you touch anything under `src/openclaw/`, rebuild and commit the+bundle in the same commit.**++### 8.4 Other committed artifacts CI checks++- `link-ratchet.json` — dangling-link ceiling. Gate:+ `.github/workflows/ci.yml:61-62` (`bun run link-ratchet:check`), also+ `release.yml:50-51`. Scripts at `package.json:49-50`. Exit 1 on a rise,+ on an unmeasurable subject, or when the ceiling file is not comparable+ (`scripts/link-ratchet.ts:21-27,110-117`). **`templates/brain-starter`+ sits exactly at its ceiling of 22 with zero headroom** — one new+ dangling wikilink in that template reddens CI.+- `check:paths` — `.github/workflows/ci.yml:64-65`, report-only: it always+ exits 0 (`scripts/check-hardcoded-paths.ts:51` — `--strict` is not+ passed in CI). The enforcing gate is `hardcoded-paths.test.ts` under+ `bun test`.+- `schemas/` — four committed JSON Schemas with no dedicated CI step;+ covered only by `bun test`.++### 8.5 CI — `.github/workflows/ci.yml`++Triggers: `pull_request` on all branches, `push` to `main` (`:7-11`).+Permissions `contents: read` (`:13-14`). Concurrency+`ci-${{ github.ref }}`, cancel-in-progress (`:16-18`).++**One job, `validate`** (`:21-23`), strictly sequential; any failing step+aborts the rest. There are no `needs:` edges because there is only one job.++| # | Step | Command | Gates |+|---|---|---|---|+| 1 | Check out repository (`:25-28`) | `actions/checkout@v4` | — |+| 2 | Set up Bun (`:30-33`) | `oven-sh/setup-bun@v2`, `latest` | unpinned; a Bun release can redden CI with no repo change |+| 3 | Set up Python (`:35-38`) | `actions/setup-python@v5`, 3.11 | — |+| 4 | Install JS dependencies (`:40-41`) | `bun install --frozen-lockfile` | lockfile drift |+| 5 | **Verify manifest version sync** (`:43-44`) | `bun run sync-version:check` | version drift; **first substantive gate, blocks everything below** |+| 6 | OpenClaw bundle is in sync (`:46-59`) | inline `bun build` + `diff -q` | stale committed bundle |+| 7 | Broken-link ratchet (`:61-62`) | `bun run link-ratchet:check` | dangling links above ceiling |+| 8 | Hardcoded path hygiene (`:64-65`) | `bun run check:paths` | **nothing** — report-only |+| 9 | Formatting check (`:67-68`) | `bun run fmt:check` | oxfmt 0.47.0 |+| 10 | Lint (`:70-71`) | `bun run lint` | oxlint 1.62.0, errors only |+| 11 | Typecheck (`:73-74`) | `bun run typecheck` | `tsc --noEmit` |+| 12 | TypeScript test suite (`:76-77`) | `bun test` (raw, not `bun run test`) | the whole TS suite |+| 13 | Python plugin tests (`:79-80`) | `python -m unittest discover -s tests/python -v` | Hermes plugin |+| 14 | Python package compiles (`:82-83`) | `python -m compileall -q plugins/hermes` | Python syntax |++`.github/workflows/release.yml` has two jobs: `verify` (`:27-96`) and+`release` (`:98-174`, `needs: verify`). `verify` re-runs sync-version+check, link ratchet, typecheck, `bun test`, Python tests, manifest+validation, the OpenClaw byte-diff and an OpenClaw packaging check, plus+`./scripts/o2b doctor --vault . --repo .` (`:62-74`). It does **not** run+`fmt:check`, `lint`, or `check:paths` — the release gate is weaker than+the PR gate on formatting and lint, and stronger on doctor and packaging.++Local hooks (bypassable, not CI): `.githooks/pre-commit` runs `fmt:check`+then `lint`; `.githooks/pre-push:17` runs `typecheck` only.++## 9. Test conventions++### 9.1 Isolation — correcting the "clean HOME" premise++The brief (and a widely-repeated note) says `scripts/test` gives you a+clean HOME. **It does not.** `scripts/test` is 13 lines: it sources+`scripts/_bun-precheck.sh` (`:8`), sources `scripts/_macos-sqlite.sh`+(`:11`), and `exec bun test "$@"` (`:13`). It sets **no** env var.++- `scripts/_bun-precheck.sh:17-53` verifies `bun` is on PATH and+ ≥ 1.1.0, exiting 127 / 1 otherwise. No exports.+- `scripts/_macos-sqlite.sh:71` exports the wrapper's ONLY env var,+ `DYLD_LIBRARY_PATH`, and only on Darwin (`:43`), only when the var is+ unset (`:53`), and only when a Homebrew sqlite lib prefix exists+ (`:63-66`). Reason at `:3-13`: Apple's system libsqlite3 is built with+ `SQLITE_OMIT_LOAD_EXTENSION`, so `db.loadExtension()` for `sqlite-vec`+ fails.++**The real global isolation is `OPEN_SECOND_BRAIN_CONFIG`, and it lives+in a bun preload, not the script.** `bunfig.toml:1-3` sets+`[test] preload = ["./tests/setup.ts"]`. `tests/setup.ts:31-38`: if+`OPEN_SECOND_BRAIN_CONFIG` is unset, mkdtemp an `osb-test-default-*`+root, create `<root>/vault/Brain`, write `<root>/config.yaml` with+`vault: <vault>`, and point the env var there. Rationale at `:9-15`: on a+bare runner ~136 tests threw "plugin config not found"; on a configured+machine those same tests read — and could write — the operator's real+vault. `tests/setup.ts:27-29` also pins `O2B_DEVICE_ID` to `""`.++**HOME is pinned per test file, never globally.** No helper in+`tests/helpers/` touches HOME. Call sites that do it themselves:+`tests/cli/cli.test.ts:212-224` (`readinessEnv()` returns+`{OPEN_SECOND_BRAIN_CONFIG:"", XDG_CONFIG_HOME:"", VAULT_DIR:"",+OPEN_SECOND_BRAIN_SEARCH_SEMANTIC:"false", HOME: tmp}` — the+installed-runtimes probe reads real runtime configs out of HOME, so a+developer's own install would otherwise decide the exit code),+`tests/cli/doctor-exit.test.ts:89-100`,+`tests/cli/install-json-shape.test.ts:59-67`,+`tests/cli/install-ownership-close.test.ts:49`,+`tests/core/config-read-failure.test.ts:386`. The phrase "this suite+mandates a clean HOME" appears only as prose in three MCP test comments+(`tests/mcp/mcp.test.ts:28-35`, `config-read-failure-tools.test.ts:54`,+`config-read-failure-server.test.ts:57`). Nothing enforces it.++**Run `bun run test` locally** (`package.json:39` → `bash scripts/test`).+Bare `bun test` still gets full config isolation via the preload and+works on Linux — CI itself runs bare `bun test`+(`.github/workflows/ci.yml:76-77`). What you lose without the wrapper is+the Bun-version precheck and, on macOS only, `DYLD_LIBRARY_PATH` —+without which `sqlite-vec` cannot load and every vec-dependent test+silently **no-ops** rather than failing+(`tests/helpers/sqlite-vec.ts:5-22` returns `false`, and call sites do+`if (!sqliteVecLoadable()) return;`, e.g.+`tests/core/search/store.vec.test.ts:111,154,199,225,253,279`).++**If you write a test that reads the operator's home — an install probe,+a runtime detector — pin `HOME` yourself. Nothing does it for you.**++### 9.2 `runCli`++`tests/helpers/run-cli.ts:261-271`:++```ts+export async function runCli(args: ReadonlyArray<string>, opts: RunCliOptions = {}): Promise<RunResult>+```++`RunResult` (`:18-22`) is `{ stdout: string; stderr: string; returncode: number }`+— the field is **`returncode`**, not `exitCode`. `RunCliOptions`+(`:59-72`): `env?`, `stdin?`, `cwd?`, `subprocess?`.++Two modes (`:267-270`). The default is **in-process**: it imports `main`+from `src/cli/main.ts` (`:15`) and calls `await main(args)` (`:239`),+swapping `process.env`, `process.chdir` and both write streams and+restoring them in a `finally` (`:245-258`). A child `bun run+src/cli/main.ts …` is spawned only when `subprocess: true` or `stdin` is+passed (`:140-146`).++**Concurrency is refused, not tolerated** (`:183-202`): a second+overlapping in-process run throws `ConcurrentInProcessRunError` (`:186`),+pinned by `tests/cli/run-cli-helper.test.ts:21-25`. Concurrent runs must+pass `{ subprocess: true }` (`:44-52` of that test; live example+`tests/cli/brain-feedback-race.test.ts:67`).++`RUNTIME_OVERRIDABLE_ENV` (`:37-57`) is DELETED from the child env unless+the caller passes the key (`:83-85`): `VAULT_DIR`, `VAULT_AGENT_NAME`,+`VAULT_TIMEZONE`, `OPEN_SECOND_BRAIN_CONFIG`,+`OPEN_SECOND_BRAIN_SEARCH_SEMANTIC`, `OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER`,+`PARTNER_CODEGRAPH_DISABLED_ENV` and six more. Then two defaults are+injected: the codegraph switch is forced on (`:97`, §9.4) and, absent a+caller value, a throwaway `mkdtemp("o2b-test-")/isolated-config.yaml`+(`:99-103,158,256`). It does **not** manage `HOME`.++**There is no JSON assertion helper.** Tests do+`JSON.parse(r.stdout) as SomeInterface` against a locally declared+interface (`tests/cli/brain-lint.test.ts:34,113-136`,+`tests/cli/brain-hygiene.test.ts:32-53`). A good diagnostic idiom for the+exit assertion is at `tests/cli/install-json-shape.test.ts:73`: compare+`"<args> exit <code>\n<stderr>"` against `"<args> exit 0\n"` so a failure+prints stderr. For stderr progress streams use `progressRecords()`+(`tests/helpers/progress-records.ts:23-42`), which selects lines by the+`schema === PROGRESS_SCHEMA` discriminator rather than by position.++### 9.3 The vault digest — measured over the whole tree++`tests/helpers/vault-digest.ts` exports three functions:++- `digestVaultFiles(root): Map<string,string>` (`:20-37`) — sha256 per+ file, keys POSIX-normalised vault-relative (`:30`), directories walked+ in `localeCompare` order (`:23-25`);+- `digestVaultTree(root): string` (`:43-51`) — one sha256 over+ `` `${path}\0${digest}\n` `` for every entry, so **a created or deleted+ file changes the value as surely as an edited one** (`:39-42`);+- `changedPaths(before, after): string[]` (`:58-66`) — sorted symmetric+ difference, including appeared and vanished files.++The documented rule (`vault-digest.ts:5-13`) is: *"the dry run wrote+nothing" is only worth asserting if it covers the whole tree* —+spot-checking the two files a preview named cannot catch an audit record,+a leftover lock, or a rebuilt projection. The "measured, not+spot-checked" wording lives in the consumers+(`tests/cli/brain-lint.test.ts:10-15`,+`tests/cli/brain-hygiene.test.ts:12-13`). The strongest form is at+`brain-lint.test.ts:126-136`:++```ts+expect(changedPaths(before, digestVaultFiles(vault))).toEqual(reported);+```++— an apply changes EXACTLY the set the dry run reported; the set is+compared, not merely its size.++Other consumers worth copying:+`tests/core/brain/architect-progress.test.ts:130-142` —+`expect(digestVaultTree(watched)).toBe(digestVaultTree(silent))`, i.e.+attaching a progress observer changes not one byte;+`tests/core/brain/dream-progress.test.ts:117-155` — compares against a+`cpSync` copy of the seeded vault (a fresh bootstrap carries its own+vault id) and excludes two prefixes with stated reasons,+`Brain/.snapshots/` (tar carries mtimes) and `Brain/log/dream-runs/`+(journal stamps real wall-clock even under an injected clock),+`:141-152`.++### 9.4 The v1.48.0 partner-binary switch++`OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED` — `src/core/config.ts:1038`,+exported as `PARTNER_CODEGRAPH_DISABLED_ENV`. Config-key twin+`partner_codegraph_disabled` at `:1039`; resolver+`resolvePartnerCodegraphDisabled()` at `:1060-1066`; default OFF in+production (`:1042-1043`). It gates **only** `doctor()`'s automatic+consultation of the third-party `codegraph` CLI; `o2b partner codegraph+report` is never suppressed (`:1054-1058`). The doctor quotes both+spellings in the row it prints for a check it did not run+(`src/core/partner/codegraph.ts:503-504`). Measured effect:+`tests/cli/cli.test.ts` went 96.03 s → 1.09 s (`CHANGELOG.md:67`).++`runCli` sets it to `"true"` for you unless you pass the key+(`tests/helpers/run-cli.ts:86-97`). **Any test that invokes `doctor()` or+`vault_health` WITHOUT going through `runCli` must set it itself** in+`beforeEach` and restore in `afterEach` — `tests/mcp/mcp.test.ts:34-36,41-44`,+`tests/mcp/config-read-failure-tools.test.ts:59-60`,+`tests/mcp/config-read-failure-server.test.ts:30`. The exception is a test+asserting about the switch, which deletes it first+(`tests/core/doctor-codegraph-switch.test.ts:73-82`, using a fake+`codegraph` on PATH that records invocations, `:47-60`).++### 9.5 General conventions++**Temp vaults, three tiers.** Lightweight, no Brain bootstrap:+`createSandboxVault(root, name?)` at `tests/helpers/fixtures.ts:11-25`+(companion `createPluginRepo` at `:27-89`). Real vault:+`bootstrapBrain(vault, { configPath })` from `src/core/brain/init.ts`+after writing a config with `atomicWriteFileSync`+(`tests/cli/brain-hygiene.test.ts:55-62`) — pair it with+`resetVaultIdentityPins()` in **both** `beforeEach` and `afterEach`+(`:56` and `:65`) or vault-identity pins leak across files. Universal+wrapper: `mkdtempSync(join(tmpdir(), "<prefix>-"))` in `beforeEach`,+`rmSync(tmp, {recursive:true, force:true})` in `afterEach`+(`tests/cli/cli.test.ts:25-31`). Search fixtures:+`tests/helpers/search-fixtures.ts`.++**Location mirrors `src/`**: `tests/cli/` (176 files, drives the CLI+through `runCli`), `tests/core/` (758, calls core directly),+`tests/mcp/` (124, drives `MCPServer.handleRequest` with raw JSON-RPC+envelopes — `tests/mcp/mcp.test.ts:47-60`), `tests/hooks/`,+`tests/discipline/`, `tests/scripts/`, `tests/docs/`, `tests/openclaw/`,+`tests/plugins/`, `tests/e2e/` (suffix `*.integration.test.ts`), and+Python separately in `tests/python/`.++**Every file opens with a docblock stating what defect it exists to+catch.** This is the strongest stylistic convention in the tree+(`tests/cli/run-cli-helper.test.ts:1-9`,+`tests/helpers/cli-timeout.ts:1-44`,+`tests/core/doctor-codegraph-switch.test.ts:1-19`).++**Filesystem yes, under `os.tmpdir()` only. Network loopback only.**+Embedding providers are replaced by `MockEmbeddingProvider`+(`tests/helpers/mock-embedding.ts:14-32`, sha256-derived unit vectors) or+an ephemeral `Bun.serve({port:0})` on `127.0.0.1`+(`tests/helpers/fake-http.ts:52-90`). Rationale at+`tests/helpers/run-cli.ts:47-53`.++**Timeouts.** bun's default is 5 s. Any file that drives the real CLI+must put `setDefaultTimeout(CLI_SPAWN_BUDGET_MS)` at module top level,+importing from `tests/helpers/cli-timeout.ts`+(`CLI_SPAWN_BUDGET_MS = 60_000` at `:45`). The docblock (`:1-44`) records+the experiment: `bunfig.toml [test] timeout` is parsed and **ignored**;+`setDefaultTimeout()` from a preload applies only to whichever file bun+runs first; `bun test --timeout` works but CI runs bare `bun test`. Only+the per-file form behaves identically under `bun test`,+`bun test <file>` and `bun run test`. Current adopters:+`tests/cli/cli.test.ts:21`, `cli-json-contract.test.ts:9`,+`doctor-exit.test.ts:29`, `install-verb.test.ts:29`,+`config-read-failure-surfaces.test.ts:37`, `run-cli-helper.test.ts:19`.+For one slow test, use the third `test()` argument instead.++### 9.6 Invocation++- CI: `.github/workflows/ci.yml:76-77`, bare `bun test`, no wrapper, no+ flags. Python at `:79-80`.+- Local: `bun run test` → `package.json:39` → `bash scripts/test`. Full+ gate: `bun run validate` = `typecheck && lint && test`+ (`package.json:45`). Single file: `bun test tests/cli/cli.test.ts`.+- Git hooks deliberately do NOT run the suite: `.githooks/pre-commit`+ runs `fmt:check` + `lint`; `.githooks/pre-push:2-4` states the full+ suite is intentionally skipped because CI's required `validate` check+ runs it on the PR.++**Do not run the full suite casually — it takes minutes.** Run the+targeted census files named in each section above.++---++## 10. Verified command output++All run on branch `feat/a-label-is-not-a-boundary`, working tree clean.++```+$ bun run lint+… (truncated: 123 warning bodies) …+Found 123 warnings and 0 errors.+Finished in 817ms on 2103 files with 110 rules using 4 threads.+EXIT=0+```++Warnings do not fail CI — `oxlint` exits 0. Only errors gate+(`.github/workflows/ci.yml:70-71`).++```+$ bun run fmt:check+$ oxfmt --check '**/*.{ts,js,json}' '.oxfmtrc.json' '!**/openclaw/index.js' '!.claude/**' --no-error-on-unmatched-pattern+Checking formatting...++All matched files use the correct format.+Finished in 1770ms on 2110 files using 4 threads.+EXIT=0+```++```+$ bun run typecheck+$ tsc --noEmit+EXIT=0+```++```+$ bun run scripts/sync-version.ts --check+canonical version: 1.48.0+ ok: plugin.yaml+ ok: plugins/hermes/plugin.yaml+ ok: .claude-plugin/plugin.json+ ok: .codex-plugin/plugin.json+ ok: plugins/codex/.codex-plugin/plugin.json+ ok: openclaw.plugin.json+ ok: pyproject.toml+EXIT=0+```++Seven `ok:` lines — six manifests plus `pyproject.toml`.++```+$ bun run link-ratchet:check+$ bun run scripts/link-ratchet.ts --check+canonical definition: ladder:links-unresolved-after-read-resolution@2+ ok: templates/brain-starter (dangling 22 of 55 link row(s), ceiling 22)+EXIT=0+```++**Zero headroom.** One new dangling wikilink in `templates/brain-starter`+reddens CI.++```+$ bun run check:paths+$ bun run scripts/check-hardcoded-paths.ts+check-hardcoded-paths: clean — no hardcoded home paths in shipped surfaces+EXIT=0+```++```+$ git status --porcelain+(no output — clean)+```++**Version:** `package.json` `version` = `1.48.0` (`package.json:3`).+**Top CHANGELOG heading:** `## [1.48.0] - 2026-08-15`+(`CHANGELOG.md:8`).++The full test suite is invoked as `bun run test` locally+(`package.json:39` → `bash scripts/test`) and bare `bun test` in CI+(`.github/workflows/ci.yml:77`). It was NOT run for this reconnaissance —+it takes minutes.++---++## 11. Where two conventions conflict++Six places where the obvious reading is wrong. Each has cost somebody a+red build.++1. **"Clean HOME" is folklore for the wrapper, real for individual+ tests.** `scripts/test` sets no env var at all (§9.1). Global config+ isolation comes from `bunfig.toml:1-3` + `tests/setup.ts:31-38`. HOME+ pinning is per-file. Do not assume a helper is doing it for you.++2. **The two rails have exactly inverted legality rules.** Advisory is+ legal unless the command owns internal JSON+ (`src/cli/advisory-rail.ts:85-88`); progress is legal only IF the+ command owns internal JSON (`src/cli/progress-rail.ts:109-112`). The+ inversion is deliberate and argued at `progress-rail.ts:96-108`.++3. **Census registries live in two different places.** Write-site+ exclusions and progress exemptions live in the TEST file+ (`write-site-census.test.ts:243`, `progress-census.test.ts:106`);+ destructive-site and egress registries live in `src/`+ (`src/core/brain/destructive-sites.ts:125`,+ `src/core/egress/registry.ts:85`). `DOCTOR_REGISTERED_CODES` lives in+ the test (`doctor-exit-census.test.ts:177`) while+ `DOCTOR_EXIT_EXCLUSIONS` lives in `src`+ (`src/core/brain/doctor-exits.ts:54`).++4. **`CliError` maps to a different exit code depending on the+ dispatcher**: 2 in `src/cli/main.ts:1014-1018` and+ `src/cli/search.ts:98-117`, but **1** in `src/cli/brain.ts:462-467`.+ A brain verb that throws `CliError` for an argv mistake exits 1, not 2.++5. **CI and the release workflow gate different things.**+ `ci.yml` runs `fmt:check`, `lint` and `check:paths`;+ `release.yml` does not, but adds `o2b doctor` and an OpenClaw+ packaging check. A branch green on CI is not proof the release job is+ green, and vice versa.++6. **`CLAUDE.md` overrides `feature-release-playbook` on when to bump.**+ The playbook says bump in a release phase; this repo bumps inside the+ feature PR before the first push (`CLAUDE.md:45-48`). Follow+ `CLAUDE.md`.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/recon/egress-boundary.md b/docs/brainstorm/a-label-is-not-a-boundary/recon/egress-boundary.mdnew file mode 100644index 00000000..8a480b15--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/recon/egress-boundary.md@@ -0,0 +1,374 @@+# Egress boundary recon — what actually leaves this machine today++Branch `feat/a-label-is-not-a-boundary`. Read-only reconnaissance against+`main`-descended source at `280469d2`. Every claim below carries a+`file:line` anchor that was read, or a command that was run against a+scratch vault under the session scratchpad.++Scope: verify two kanban task bodies (`t_08f6ffca` "sanitize a personal+brain into a shareable team brain", `t_09a3752a` "portable repo-visibility+verification before sensitive data leaves the machine") against this+codebase, and establish what egress actually exists.++---++## 1. What exists — the boundary is already built, and it is named++Both task bodies were written as if this repository had no egress+boundary. It has one, and it is a mature one.++- `src/core/egress/guard.ts:147` — `redactForEgress(site, payload)`. The+ one call every export path makes before its bytes leave the vault.+- `src/core/egress/guard.ts:72-83` — a three-value verdict:+ `released`, `refused_scan_truncated`, `refused_secret_identifier`.+ Both refusals are fail-closed: the export "either scanned its payload+ or it did not go" (`guard.ts:26`).+- `src/core/egress/registry.ts:85-167` — Registry R2, seven declared+ egress sites, each with a `reason` string that is required to be+ non-empty.+- `tests/core/architecture/egress-census.test.ts` — derives the+ POPULATION of egress modules structurally from source and asserts the+ registry accounts for all of it, then checks each declaration against+ the module's own text (`:204-215`, `:241-260`).++The registry answers task (B) directly and explicitly:++> "The vault has no git transport and deliberately never will, so there+> is no commit or push boundary to gate."+> — `src/core/egress/registry.ts:6-8`++Verified independently: every `git` invocation in `src/` is read-only.+`src/core/brain/git/reader.ts:104` runs `git -C <repo> <args>` where the+args are log/show reads; `:394` runs `remote get-url origin`.+`src/core/discipline/activity-git.ts:25-37` runs `git log --numstat`.+There is no `push`, `commit`, `clone`, `add`, or `remote add` anywhere+under `src/`, `scripts/`, or `hooks/`.++### The redaction policy, precisely++`src/core/egress/guard.ts:125-128` sets exactly two flags:++```+redactTokens: true+redactUrlCredentials: true+```++`redactInfra` is OFF, deliberately and with a stated reason+(`guard.ts:43-49`): a `host:port` or a public IP in an authored note is a+reference a portable bundle has to keep.++What the shared redactor catches (`src/core/redactor.ts`):+key=value / `key: value` / JSON / `Authorization: Bearer` assignment+shapes (`:1-17`); vendor-prefixed tokens `sk-`, `ghp_`, `xox?-`, `AKIA`,+`AIza`, `glpat-` (`:317-329`); bare mixed-class runs of ≥24 characters+(`:337-338`); base64 credentials 32-64 chars (`:385-394`);+`<private>…</private>` region stripping (`:492`, applied from `:621`).++---++## 2. Egress inventory — complete, and wider than the registry++The registry covers **file destinations only**. Four further categories+cross a trust boundary and are not in it. This is the honest inventory.++### A. Declared file exports — guarded (7 sites)++| Site | Verb | Module | Status |+|---|---|---|---|+| `brain-bank-export` | `o2b brain bank-export` | `src/cli/brain/verbs/bank-export.ts:28` | guarded |+| `brain-graph-export` | `o2b brain graph-export` | `src/cli/brain/verbs/graph-export.ts` | guarded |+| `brain-okf-export` | `o2b brain okf-export` | `src/cli/brain/verbs/okf-export.ts:48` | guarded |+| `brain-preference-export` | `o2b brain export` | `src/cli/brain/verbs/export.ts` | guarded |+| `config-export` | `o2b export-config` | `src/cli/main.ts` | guarded |+| `brain-continuity-export` | `o2b brain continuity export` | `src/cli/brain/verbs/continuity.ts` | guarded |+| `install-adapter-out` | `o2b install --out` | `src/cli/install/install.ts` | `no_vault_content` |++### B. UNDECLARED file export — unguarded (defect D1, below)++`o2b brain explorer --export <path>` —+`src/cli/brain/verbs/explorer.ts:15,28`. Writes a self-contained HTML+file carrying the full preference graph as embedded JSON. Zero calls to+`redactForEgress` in either `src/cli/brain/verbs/explorer.ts` or+`src/core/brain/explorer.ts`; not present in `EGRESS_SITES`. The census+cannot see it because its flag is named `export`, which is in neither+`DESTINATION_FLAGS` nor `AMBIGUOUS_DESTINATION_NAMES`+(`tests/core/architecture/egress-census.test.ts:96-118`).++### C. Network egress — real, continuous, and outside the registry entirely++1. **Embedding provider** — `src/core/search/embeddings/openai-compat.ts:440-451`+ POSTs `{model, input: texts}` to the configured endpoint with a bearer+ key. `texts` is `batch.map((p) => p.content)`+ (`src/core/search/indexer.ts:966-967`) — raw vault chunk bodies. No+ `redactForEgress`, no `stripPrivateRegions`; grep for `private|redact`+ over `src/core/search/chunker.ts` and `src/core/search/indexer.ts`+ returns nothing. **This is the largest and most continuous egress in+ the product and nothing scans it.** Same shape at+ `src/core/search/embeddings/zeroentropy.ts:200` and+ `src/core/search/rerank/cross-encoder.ts:85`.+ Also reached from `src/core/brain/hygiene/detectors/dedup.ts:145`+ (preference principles) and `src/core/brain/entities/semantic-dedup.ts:331`+ (entity names).+2. **Telegram capture** — `src/core/brain/capture/telegram-capture.ts:433`+ POSTs `/catchup` reply text to the Bot API. Transport is built only by+ the CLI runner verb (`:411-413`).+3. **External research fetch** — `src/core/brain/research/external-fetch.ts:231`.+ Agent-composed search queries to Brave/Tavily. Key-gated; a `null` key+ makes every call a typed `disabled` error (`:6-8`).+4. **MCP over HTTP** — `src/mcp/http.ts:40-49`. Loopback by default, and+ **already fail-closed**: a non-loopback bind without `--api-key` is+ refused with "refusing to expose an unauthenticated endpoint on the+ network". This is the closest existing analogue to task (B)'s ladder.+5. **Explorer live server** — `src/core/brain/explorer.ts:322-337`.+ `127.0.0.1` hard-coded and non-optional; serves the same unredacted+ graph JSON at `/data.json`.++No telemetry, analytics, or phone-home exists. Every `telemetry` module+under `src/core/brain/` writes into the vault's own continuity log.++### D. Second-vault mirrors and cross-vault reads++- `src/core/brain/shared-namespace.ts:42-84` — opt-in `shared_namespace`+ config key mirrors feedback signals and notes into a SECOND vault root,+ stamped with `origin_vault`. Fail-soft by contract (`:12-15`). No+ redaction of any kind on the mirror path.+- `src/core/search/cross-vault.ts` and+ `src/core/brain/portability/recall-sources.ts:1-14` — other vaults+ attached as READ-ONLY recall origins. Ingress, not egress.+- `src/core/brain/portability/profiles.ts` — named multi-vault profiles;+ local pointer file, no egress.++### E. Hermes plugin / openclaw++Neither adds network egress. `plugins/hermes/bridge.py:299` spawns+`o2b mcp` as a local subprocess over pipes. `src/openclaw/index.ts:15`+imports `redactConfigMapping` for its status tool.++---++## 3. Corrections to each premise++### Task (A) — "sanitize a personal brain into a shareable team brain"++| Premise | Verdict |+|---|---|+| "Open Second Brain has no personal-to-team export path" | **Wrong.** Two bidirectional bundle formats exist with CLI verbs on both sides: `bank-export`/`bank-import` (`src/cli/brain.ts:297`) and `okf-export`/`okf-import` (`src/cli/brain.ts:375`). |+| "only `sanitize-principle.ts` (narrow single-principle text sanitization)" | **Wrong.** That file (`src/core/brain/text/sanitize-principle.ts`, 68 lines) has nothing to do with privacy — it strips leaked tool-call XML fragments and backslash-escape amplification from corrupted frontmatter (`:5-17`). The privacy machinery is `src/core/redactor.ts` + `src/core/egress/guard.ts`. |+| "no staging-copy / strip-keep / history-purge module found" | **Correct, and correctly absent.** There is no git history to purge (`registry.ts:6-8`). The export IS the staging copy — it is a fresh tree composed read-only from the vault. |+| Validator: "value depends on an unproven team-sharing use case" | **Half right.** The export bundle is the only multi-recipient artefact, and it is already consumed by a second party's `bank-import`. The unproven part is not the artefact, it is who reads it. |++Corrected framing for (A): the export path exists, is guarded, and+already refuses two classes of unsafe payload. The gap is not a missing+sanitizer — it is that **a `private` label is not a boundary**.++Proven by running it. A page with `private: true` in frontmatter AND+`tags: [private, confidential]` exported **in full** through+`okf-export`; only the inline `<private>…</private>` REGION marker was+honoured:++```+--- vault/page-one.md (input) --- --- okf/concepts/page-one.md (output) ---+Authorization: Bearer ghp_ABC… Authorization: Bearer ***REDACTED***+<private> ***PRIVATE***+Salary discussion…+</private>++--- vault/page-three.md (input) --- --- okf2/concepts/page-three.md (output) ---+private: true private: true <- label ignored+tags: [private, confidential] tags: [private, confidential]+postgres://admin:[email protected] postgres://***REDACTED***@10.4.4.9+internal-jump.corp.example:2222 internal-jump.corp.example:2222 <- kept+IP 203.0.113.44 IP 203.0.113.44 <- kept+operator [email protected] operator [email protected] <- kept+```++Grepping `src/core/brain/portability/` and `src/core/brain/regions.ts`+for any honouring of a `private` frontmatter key or tag returns nothing.+The only content-derived `private` signal in the product is the region+marker, at `src/core/brain/continuity/redaction.ts:9` — and it governs+the continuity log, not pages.++### Task (B) — "portable repo-visibility verification, fail closed both ways"++| Premise | Verdict |+|---|---|+| "OSB scans content for leaks but does not verify a destination remote is private before pushing" | **Correct in the second half, and there is nothing to fix.** There is no push. |+| Validator: "NO INTEGRATION SUBSTRATE: no git-push path in src (verified by grep this run)" | **Confirmed, and it is a design commitment, not an omission** — `src/core/egress/registry.ts:6-8` states it in prose. |+| "where the visibility check hooks in is an open decision" | **Closed by this recon.** Nowhere. A repo-visibility ladder guarding an operation this product does not perform is a fail-closed check with nothing to guard. |++The transferable idea from upstream is the *shape*, not the subject:+verify the destination before the bytes go, and refuse when the answer is+unprovable. That shape already exists twice here —+`guard.ts:147-176` (refuse an unscannable payload) and+`src/mcp/http.ts:45-49` (refuse an unauthenticated non-loopback bind).+The place it is missing is the destinations that actually exist.++---++## 4. Smallest native unit per task++### (A) → Make `--export` an egress site, and make the census able to see it++Four edits, all inside existing structures:++1. `tests/core/architecture/egress-census.test.ts:96-104` — add `export`+ to `DESTINATION_FLAGS`. It is unambiguous: nothing reads from an+ `--export`. Grep confirms `explorer.ts:15` is the ONLY flag in `src/`+ matching `(export|save|write|archive|snapshot|bundle): { type: "string" }`,+ so this widens the population by exactly one module — the tripwire+ firing on a real hole, which is the behaviour the census documents at+ `:361-369`.+2. `src/core/egress/registry.ts` — add a `brain-explorer-export` entry+ with `redaction: sharedRedactor` and a reason naming what the HTML+ carries (every preference principle verbatim, plus the vault path via+ `src/core/brain/explorer.ts:286-288`).+3. `src/cli/brain/verbs/explorer.ts:22-32` — route the graph through+ `redactForEgress("brain-explorer-export", graph)` before+ `renderExportedHtml`, honouring both refusal arms and emitting+ `EGRESS_REDACTION_NOTICE` on stderr, exactly as `bank-export.ts:44`+ does.+4. A regression test that the exported HTML does not contain a+ vendor-prefixed key present in the vault.++This is native because it adds no concept: it fills the seventh slot in a+registry whose docstring already says its purpose is "what stops a+seventh appearing unredacted" (`registry.ts:10-11`).++**Optional second half, if the label question is in scope**: decide+whether `private: true` frontmatter is a boundary. Today it is not, and+nothing in the code claims it is — so either honour it in the export+composers (`okf.ts`, `graph.ts`, `page-contract.ts`) or state in+`registry.ts`'s reason strings that the region marker is the only+privacy primitive. Stating it is cheaper and is the repo's own idiom+("that gap is stated here rather than left to be discovered",+`guard.ts:48-49`).++### (B) → Retarget to the destination that exists, or close the task++There is no push to guard. The honest native units, in order of value:++1. **Close (B) as not-applicable**, citing `registry.ts:6-8`. The task+ body's own validator already found the missing substrate; this recon+ confirms the absence is a commitment.+2. If the fail-closed *shape* is wanted, the destination that actually+ exists and is unverified is the **shared-namespace mirror**+ (`src/core/brain/shared-namespace.ts:42-84`): it writes signals into a+ second vault root the operator names, with no redaction and no+ verification that the target is a vault the operator owns. A+ `verifyMirrorTarget` that refuses an unresolvable or non-vault target+ would be the same ladder against a destination that is real here. Note+ it already refuses one case — a self-mirror (`:92-94`).+3. The **embedding endpoint** is the other real unverified destination:+ raw vault content to an operator-configured URL with no scan. A+ fail-closed check there (refuse to embed a chunk whose text carries a+ vendor-prefixed credential, rather than shipping it) would be the+ highest-value application of (B)'s principle in this codebase.++---++## 5. Defects noticed++### D1 — `explorer --export` writes unredacted credentials (HIGH)++Observed in the bytes. Scratch vault, one preference created through the+real writer (`o2b brain feedback --force-confirmed`), then:++```+$ o2b brain explorer --vault $V --export $SP/explorer.html+exported 1 nodes to …/explorer.html++$ grep -o '"nodes":\[[^]]*\]' explorer.html+"nodes":[{"id":"pref-secret-leak","kind":"preference","topic":"secret-leak",+"principle":"Always deploy with OPENAI_API_KEY=sk-proj-AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHH1234+ set from <operator-home>/private-client-work", …}]+```++The identical principle through `bank-export` comes out as+`OPENAI_API_KEY=***REDACTED***`. Anchors: `src/cli/brain/verbs/explorer.ts:15,28`+(flag and write), zero `redactForEgress` in that file or in+`src/core/brain/explorer.ts`, zero `explorer` in+`src/core/egress/registry.ts`. The census gap is+`tests/core/architecture/egress-census.test.ts:96-118`.++### D2 — OKF `log.md` is silently empty on every default install (MEDIUM)++`src/core/brain/portability/okf.ts:334`:++```ts+const dateRe = /^(\d{4}-\d{2}-\d{2})\.md$/;+```++matches only the LEGACY un-sharded log filename. The current default+writes a per-device shard `<date>.<deviceId>.md`+(`src/core/brain/log.ts:113-114`, `:256-258`). Observed: `Brain/log/`+contained `2026-08-16.bb4363ed.md`, and the export reported+`0 log day(s)` with an empty `log.md`. The bundle presents "this vault+has no change log" as a fact rather than reporting that it could not read+one — the misleading success this repo forbids.++### D3 — Signal-provenance wikilinks are destroyed by the egress guard, and the damage survives import (MEDIUM)++`sig-2026-08-16-secret-leak` is 26 characters of `[A-Za-z0-9_-]` mixing+letters and digits, and is not pure hex, so it matches+`HIGH_ENTROPY_TOKEN_RE` (`src/core/redactor.ts:337-338`) and is replaced.+Every OSB signal id has the shape `sig-YYYY-MM-DD-<slug>` and crosses the+24-character gate as soon as the slug reaches 9 characters — i.e.+routinely. Round trip observed end to end:++```+on disk: _evidenced_by: ["[[sig-2026-08-16-secret-leak]]"]+exported: "evidenced_by": ["[[***REDACTED***]]"]+imported: _evidenced_by: ["[[***REDACTED***]]"] <- restored 1 of 1, failed 0+```++`bundle.ts:35-41` anticipates exactly this hazard ("a placeholder is a+constant — two records that lost a name land on one") and guards the+NAMING fields via `redacted_identifier` refusals. It does not guard+`evidenced_by`, so the import reports full success while writing a+dangling wikilink that every preference with a redacted signal id shares.+`CONTENT_ADDRESS_RE` (`redactor.ts:356`) already carves out hex ids for+this reason; a `sig-<date>-<slug>` carve-out is the same fix.++### D4 — `collectExportRows` silently drops unparseable preferences (MEDIUM)++`src/core/brain/export.ts:106-107` and `:118-119` both `continue` on a+caught exception. Observed during this recon: a preference file with+legacy un-prefixed Group C frontmatter keys produced+`"preferences": []` in the bundle with exit code 0 and nothing on stderr,+while the file sat on disk. This is a path that writes data outward while+swallowing the error that says the data is incomplete — an export that+omits a rule reads identically to a vault that never had it.+`src/core/brain/explorer.ts:105-108` has the same shape with an explicit+comment.++### D5 — Shared-namespace mirror swallows the reason (LOW)++`src/core/brain/shared-namespace.ts:52-54` and `:80-83` catch and return+`"failed"` with no diagnostic. Fail-soft is the stated contract+(`:12-15`) and is right, but discarding the message means an operator+whose mirror has been silently failing for a month has no way to learn+whether the cause is a permission error, a missing directory, or a+corrupt target vault.++### D6 — Duplicated `isoSecond` (TRIVIAL)++`src/core/brain/secrets/store.ts:309-311` reimplements the helper that+`src/core/brain/time.ts` already exports and that `shared-namespace.ts`+imports.++---++## 6. Answer to "is there a team brain here"++Yes, but exactly one artefact, and it is not a vault.++The only multi-recipient artefacts are the **export bundles**:+`bank-export` → `bank-import` and `okf-export` → `okf-import`. Both have+importers a second person runs. Everything else that looks multi-party is+not: cross-vault recall sources are read-only ingress+(`recall-sources.ts:1-14`), profiles are one operator's own vaults+(`profiles.ts:1-13`), and the shared namespace is a one-way mirror+between agents, not people (`shared-namespace.ts:15-17`).++So the honest scope for (A) is: **guard the export that does exist.**+That is D1.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/recon/fleet-and-shared-scope.md b/docs/brainstorm/a-label-is-not-a-boundary/recon/fleet-and-shared-scope.mdnew file mode 100644index 00000000..17b05069--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/recon/fleet-and-shared-scope.md@@ -0,0 +1,505 @@+# Recon: fleet view (t_a160764a) and named shared observation scope (t_77efc212)++Read-only reconnaissance against `feat/a-label-is-not-a-boundary` at+`package.json` v1.48.0. Every claim below carries a `file:line` anchor that was+actually read.++---++## What exists++### 1. `src/core/brain/shared-namespace.ts` — the whole surface++104 lines, three exported functions, one config key.++**What turns it on.** `resolveSharedNamespace` reads the `shared_namespace` key+off the device config and returns the trimmed value or `null`+(`src/core/brain/shared-namespace.ts:31-35`). Absent or blank is off. The key is+device-level, alongside `vault:` itself+(`docs/brainstorm/agent-write-contract-suite/design.md:42`).++**What it mirrors, and when.** Exactly two record families, both mirrored AFTER+the primary write has already landed:++- feedback signals — `mirrorSignal` calls `writeSignal(sharedVault, …)`+ (`src/core/brain/shared-namespace.ts:42-55`); called from+ `src/mcp/brain/feedback-tools.ts:184-187` and+ `src/cli/brain/verbs/feedback.ts:98-101`.+- narrative notes — `mirrorNote` appends one `note` log event+ (`src/core/brain/shared-namespace.ts:64-84`); called from+ `src/core/brain/note.ts:75-83`.++Nothing else mirrors. `brain_apply_evidence` does not; preferences do not;+continuity records do not; graph pages do not. The MCP dedupe path deliberately+skips the mirror on a retry (`src/mcp/brain/feedback-tools.ts:166-180`).++**Attribution.** Carried twice as claimed: the pre-existing `agent` field plus+`origin_vault`, set to `basename(originVault)`+(`src/core/brain/shared-namespace.ts:50` and `:77`). On the signal path+`origin_vault` is persisted into the signal's frontmatter metadata+(`src/core/brain/signal.ts:403-404`), declared optional on the input type at+`src/core/brain/signal.ts:102`. On the note path it goes into the log event body+(`src/core/brain/shared-namespace.ts:74-78`).++**How failure is handled — "fail-soft", concretely.** Both mirror functions wrap+their write in `try { … } catch { return "failed"; }`+(`src/core/brain/shared-namespace.ts:49-54`, `:70-83`). The caught error object+is **discarded entirely** — no message, no cause, no stderr line, no continuity+record. The single bit `"failed"` is the whole diagnosis.++That bit is not swallowed at the boundary: it is surfaced. `MirrorOutcome`+(`src/core/brain/shared-namespace.ts:28`) reaches+`AppendBrainNoteResult.mirror` (`src/core/brain/note.ts:48`, emitted at `:89`),+the MCP feedback result (`src/mcp/brain/feedback-tools.ts:273`), and the CLI,+which both puts it in the JSON payload and prints `mirror: <outcome>`+(`src/cli/brain/verbs/feedback.ts:187`, `:199-200`). Unconfigured setups emit+nothing at all — the field is conditional on `mirror !== undefined`.++So the repository's "no silently swallowed error" rule is honoured at the+*envelope* level and violated at the *diagnosis* level: the caller is told that+something failed, and is given no way whatsoever to learn what. Contrast the+sibling append in the same call, which at least writes the message to stderr+(`src/mcp/brain/feedback-tools.ts:200-202`,+`src/cli/brain/verbs/feedback.ts:187-188` region).++**What a reader of the shared vault can see.** A mirrored signal is an ordinary+`sig-*.md` in the shared vault's inbox, indistinguishable from a locally written+one except for the extra `origin_vault` metadata key. A mirrored note is an+ordinary `note` log event. The module docblock states the intent explicitly:+"the shared vault's own dream pass treats mirrored records as ordinary+first-class signals" (`src/core/brain/shared-namespace.ts:15-16`). There is no+marker that says "this came from elsewhere" other than `origin_vault`, and see+§2 for who reads that.++**Self-mirror guard.** A `shared_namespace` pointing at the origin vault is+detected by realpath comparison and reported as `"failed"`+(`src/core/brain/shared-namespace.ts:92-103`), asserted at+`tests/core/brain/shared-namespace.test.ts:78-79`.++### 2. Readers of the shared vault — the decisive enumeration++**Readers of `origin_vault`: zero.** A repository-wide grep over `src/`, `docs/`+and `skills/` returns only the three write sites and their docblocks+(`src/core/brain/signal.ts:102`, `:403-404`;+`src/core/brain/shared-namespace.ts:10`, `:39`, `:50`, `:77`). No search filter,+no digest, no dream phase, no MCP tool, no CLI verb reads the field back. It is+write-only attribution.++**Readers of the shared vault as a vault: zero, by construction.** The one place+that enumerates which vaults participate in a read is+`listSearchOrigins` (`src/core/brain/portability/origins.ts:34-73`). It unions+three kinds — the active vault (`:39-46`), registered profiles (`:47-59`), and+read-only recall sources (`:60-71`) — and `shared_namespace` is **none of them**.+Its sole consumer is the cross-vault search fan-out+(`src/core/search/cross-vault.ts:106`).++The consequence, stated plainly: **the shared namespace is a write-only sink.**+Configuring it causes records to leave, and causes nothing to arrive. An+operator who wants to read a shared vault must separately register it under a+*different* registry (`recall-sources.json`,+`src/core/brain/portability/recall-sources.ts:37-39`) via+`addRecallSource` (`:101-135`), and nothing connects the two keys or warns that+one is set without the other.++This single fact governs both tasks and is the most important output of this+recon.++### 3. Agent discoverability — the three metrics, answered separately++**What identifies an agent.** `resolveAgentName` (`src/core/config.ts:373-380`):+`VAULT_AGENT_NAME` env var, then the `agent_name` / `agentName` config key, then+the literal fallback `"agent"`. An opaque string. There is no agent id, no+registration step, and the fallback means an unconfigured install writes under+the same name as every other unconfigured install.++**Is there a registry?** Yes — a *derived* one, and it already exists.+`listAgentSources(vault)` (`src/core/brain/agent-source/registry.ts:25-27`)+folds every contribution in a vault into a per-agent roster+(`summarizeAgentSources`, `:39-82`), where contributions are harvested from+signals, preferences/retired records, and Brain-log events+(`src/core/brain/agent-source/vault-provider.ts:25-49`). An agent exists+because it wrote something. `computeAgentSummary`+(`src/core/brain/digest-agent-summary.ts:37-122`) does the same over the log+alone, per window.++Both are exposed today: `brain_agent_query`+(`src/mcp/brain/query-tools.ts:598-637`) and `brain_agent_diff` (`:641+`) are+already read-only cross-agent surfaces. They are **within one vault**, over+agents that share it.++Now the three upstream metrics:++- **Memory count — COMPUTABLE, already computed.**+ `AgentSourceSummary.contribution_count`+ (`src/core/brain/agent-source/types.ts:27`) is exactly this, split by kind at+ `:28`. `computeAgentSummary` gives the finer per-event-type breakdown+ (`src/core/brain/digest-agent-summary.ts:20-26`).++- **Last activity — COMPUTABLE, not currently surfaced.** Every contribution+ carries a `timestamp` (`src/core/brain/agent-source/types.ts:8`) and the+ collection is sorted by it (`registry.ts:84-90`), so the max per agent is a+ fold away. `AgentSourceSummary` does not carry it today — that is a genuine+ small gap, not a missing data source.++- **Open tasks — NO SOURCE IN THIS PRODUCT.** This is the correct output and it+ is worth stating flatly. Greps for `open_tasks` / `openTasks` over `src/`+ return nothing. Every `kanban` hit in `src/` is a docblock reference to the+ *external* Hermes board that tracked the unit+ (`src/core/brain/freshness.ts:3`,+ `src/core/brain/hygiene/types.ts:3`, `src/core/brain/path-constants.ts:49`,+ and similar) — provenance comments, not a data structure. The two nearby+ candidates are not tasks: `src/core/brain/commitment.ts:1-16` is an epistemic+ *stance* ladder on a belief (`exploring → leaning → decided → locked`), and+ `src/core/brain/agenda.ts:1-11` is a pure function over calendar events the+ *runtime* passes in, with "no vault writes, no clock, no model". Nothing in+ this product persists a unit of work with an open/closed state.++ **Any fleet view here that reports an "open task count" would have to invent+ the number.** That is a stub with a plausible face, which this release+ forbids.++### 4. Agent scope and the `owner_scoping` equivalent++**The filter.** `src/core/graph/agent-scope.ts` defines the whole rule in three+functions: `ownerToken` / `pageOwner` resolve a page's `owner:` frontmatter+(`:69-85`), `normalizeAgentScope` normalizes a caller's request (`:91-95`), and+`isOwnerVisible` decides (`:104-108`). Semantics: no requested scope means no+filtering at all (`:105`); an ownerless page is shared and always reachable+(`:106`); an owned page reaches only its own owner (`:107`). A present-but-+unparseable `owner:` resolves to the unreachable sentinel `OWNER_UNRESOLVED`+(`:53`, produced at `:72` and `:74`), so an unreadable ownership claim fails+closed rather than publishing to everyone.++**What turns it on — this is the `owner_scoping` analogue.** The gate is the+`integrity.owner_scope_delivery` config key, read by `resolveOwnerScopeDelivery`+(`src/core/brain/preferences-collect.ts:171-185`). It ships `off`+(`:19`), under which it returns `{ enforcedScope: null }` unconditionally+(`:176-178`); only `GATE_MODE.fail` grants narrowing (`:182`). Its consumers are+the five delivery surfaces: `active.ts:266`, `digest.ts:724`,+`pre-compress-pack.ts:202`, plus context-pack and morning-brief+(`preferences-collect.ts:5-7`).++Crucially, the surrounding contract is stated at+`src/core/brain/preferences-collect.ts:111-113`: "A bare scope string is+deliberately NOT accepted: passing the gate's verdict is the only way to filter,+so no delivery surface can narrow a vault without the operator having asked for+it."++`brain_agent_query` takes `agent_scope` as a *plain argument* rather than+through the gate (`src/mcp/brain/query-tools.ts:632-637`,+`src/core/brain/agent-source/query.ts:22`), which is legal — it narrows on+request rather than by policy — but it means the two scoping paths in this repo+are not the same mechanism.++**What "REFUSED when owner_scoping is on" maps onto here.** It maps onto+`resolveOwnerScopeDelivery(vault, …).mode === GATE_MODE.fail`. But see+Corrections §B: the mapping is available and the *rationale* does not transfer.++### 5. The continuity read-model and its readers — exact numbers++- `src/core/brain/continuity/read-model.ts` applies three things and only three:+ schema-version dispatch (`:87-88`), the `private` drop (`:117`), and fail-soft+ normalization (`:66-72`). Its filter type carries `kind`, `sessionId`,+ `since`, `until`, `keepPrivate` (`:56-63`).+- `tests/core/brain/continuity/reader-census.test.ts` holds two exact+ inventories: `READ_MODEL_READERS` with **4** entries (`:65-74`) and+ `DIRECT_STORE_READERS` with **21** entries (`:82-116`). Counted mechanically:+ 4 and 21. Total **25** readers.+- What it asserts today: both inventories match the tree exactly, via `toEqual`+ against a byte-classifier over `src/**/*.ts` (`:186-191`); the store door is+ the majority (`:197-199`); floors of `MIN_READ_MODEL_READERS = 4` and+ `MIN_DIRECT_STORE_READERS = 20` (`:133-134`, checked at `:200-201`); the+ classifier survives a NUL-carrying file (`:204-234`); the two excluded layer+ modules still exist (`:236-239`); and the census is demonstrably able to fail+ against injected rogue readers (`:241-265`).++### 6. The typed-refusal idiom — the enforced shape++`tests/core/architecture/verdict-vocabulary-census.test.ts` enforces a+**four-piece** shape, all four in one module+(`:38-47`):++1. `const NAME = Object.freeze({ … })` with every entry a string literal;+2. a union `(typeof NAME)[keyof typeof NAME]`;+3. a membership list from `Object.values(NAME)` or an array of `NAME.member`;+4. a guard taking a parameter typed `unknown` (not `string` — `:80-82`) that+ reads the list or the object.++`auditVocabulary` (`:374-405`) runs seven checks: values frozen; no duplicate+value in the object; no duplicate in the list; every declared value is a member;+the guard accepts every declared value; no member is "a member of nothing"; and+the guard rejects each of the seven near-miss `NON_MEMBERS` — `""`, `" "`,+`"unknown-vocabulary-member"`, `null`, `undefined`, `42`, `{}` (`:361-370`).++The population is **scanned, not remembered**: `scanVocabularies` walks `src/`+for the four-piece shape and `CENSUS` must account for every hit (`:27-36`).+There is **no exemption list, by policy** (`:59-61`). 57 vocabularies are+registered today (`:417-999`), including `GATE_MODE`+(`:422`), which is the gate mode used by `owner_scope_delivery`.++**Any new refusal must register here or the census fails it by name.**++### 7. Truncation and unknown-vs-zero — both have precedent++**Truncation declaration:**+- `AgentSourceQueryResult` carries `total_matched` next to `returned`+ (`src/core/brain/agent-source/query.ts:39-40`) — the exact idiom a capped+ fleet scan needs, on the exact surface a fleet view would extend.+- `context-receipts.ts:414` sets `truncated: matched.length > folded.length`,+ with the reason spelled out at `:192-196`: report the fact "rather than+ silently returning a prefix as if it were" the whole answer.+- `redactor.ts:583-593` — "`truncated` is a fact about" the scan, with a marker+ appended at `:618-619`.+- `pinned.ts:74` refuses with `budget_exceeded` "instead of being silently+ truncated to look like a" success.++**Unknown-vs-zero / unknown-vs-absent:**+- `NEGATIVE_RECALL_STATE` separates `not_found` (searched, nothing there) from+ `unknown` (no claim possible), with a companion+ `NEGATIVE_RECALL_UNKNOWN_REASON` naming *why*+ (`src/core/brain/negative-recall.ts:114-124`, `:149-161`). Both are in the+ vocabulary census (`verdict-vocabulary-census.test.ts:449`, `:455`).+- `doctor-readiness.ts:21-24` is the canonical statement: a probe that could not+ run "has found out nothing at all, which is what `unknown` " means, and+ `:174` — "an unmeasured surface is not a broken one".+- `CollectedPage.unreadable` (`src/core/brain/preferences-collect.ts:196-203`)+ keeps "could not read the file" apart from "the file declares no owner", so a+ caller can fail closed instead of leaking.+- `RecallSourceStatus.broken` (`src/core/brain/portability/recall-sources.ts:27-30`),+ documented at `:149-153` as "reported, never dropped — the operator decides".+- `AgentSourceQueryResult.unknown_agents`+ (`src/core/brain/agent-source/query.ts:38`) — a requested agent that does not+ exist is *named*, not returned with a count of zero. This is the single+ closest precedent to the upstream boundary in task (A).++---++## What does not exist++- No fleet / sibling / multi-agent *operator* surface. The validator hint is+ correct on this point.+- No reader of `origin_vault` anywhere (§2).+- No path by which a `shared_namespace` vault is read back (§2). It is+ write-only.+- No env-flag gate anywhere near this area. Gating in this repo is by config+ key — `shared_namespace` (`shared-namespace.ts:33`),+ `integrity.owner_scope_delivery` (`preferences-collect.ts:175`),+ `mcp_route_metrics_enabled` (`src/mcp/server.ts:130`). An env-flag-gated+ surface would be a new idiom here; only `VAULT_AGENT_NAME`+ (`src/core/config.ts:374`) uses the environment at all.+- No open/closed unit of work in the product (§3). No task store, no todo, no+ issue, no assignment.+- No `last_activity` field on `AgentSourceSummary`+ (`src/core/brain/agent-source/types.ts:24-30`) — computable, not present.+- No declared-scope field on the continuity read-model. `ContinuityReadModelFilter`+ (`src/core/brain/continuity/read-model.ts:56-63`) has no `scope` member; the+ v1.43.0 verdict's account of the removal is accurate against the code.+- No link between the `shared_namespace` key and the `recall-sources.json`+ registry, and no warning when one is configured without the other.++---++## Corrections to each premise++### (A) t_a160764a — fleet view++**A1. "open task count" has no referent in this product.** The single largest+correction. §3 establishes there is no persisted unit of work. Two of the three+upstream metrics port; the third cannot be computed from anything, and shipping+it would mean inventing a number. The task as written cannot be done honestly.++**A2. "sibling agents" is ambiguous in this codebase, and the two readings are+not the same feature.** Upstream (a database with namespaces) has one meaning.+Here there are two:+ - *agents sharing one vault*, distinguished by the `agent` field on their+ writes. This is already discoverable+ (`src/core/brain/agent-source/registry.ts:25-27`) and already has a+ read-only surface (`brain_agent_query`,+ `src/mcp/brain/query-tools.ts:598-637`). A fleet view over these is a fold+ away and reaches no other vault.+ - *other vaults*, i.e. profiles, recall sources, and the shared namespace.+ Reaching these means filesystem access to another vault root, which is+ where "unreachable" and "truncation" actually bite.++ The task body does not say which, and the two produce different units. The+ second is the one that makes the upstream boundaries meaningful.++**A3. "never crosses workspaces" has no analogue and should be dropped.** There+is no workspace concept in this codebase — the nearest boundary is the vault+root, enforced by `ensureInsideVault`+(`src/core/brain/payload-registry.ts:96-101`,+`src/core/brain/ingest/sources-registry.ts:69-79`). Cross-vault reads are not+forbidden here; they are a shipped feature with its own registry+(`recall-sources.ts:101-135`) and its own refusals — self-link (`:114-116`),+duplicate path (`:122-126`), direct circular link (`:127-132`). The upstream+boundary would be re-stating something the recall-source registry already+enforces better.++**A4. "REFUSED when owner_scoping is on" maps mechanically but not in+substance.** The mapping exists (§4: `owner_scope_delivery === fail`). The+*reason* does not: upstream refuses because "namespaces are people, not agents".+Here, `owner:` tokens are explicitly "an agent name" —+`src/core/graph/agent-scope.ts:23-24` says so directly. Owner scoping in this+repo is agent isolation, so a fleet view under it should **narrow**, not refuse+— and `queryAgentSources` already demonstrates exactly that correct behaviour,+folding the roster from what survived the filter precisely so the withheld+contributions are not counted or named+(`src/core/brain/agent-source/query.ts:50-56`,+`src/core/brain/agent-source/registry.ts:29-38`). Importing the upstream refusal+would be a regression against a leak this repo has already closed.++**A5. The premise is right that no operator surface exists, and wrong that+nothing exists.** The validator hint stops at `agent-scope.ts` and misses+`src/core/brain/agent-source/` entirely — six modules, a provider abstraction+(`types.ts:32-36`), a per-agent roster, two shipped MCP tools, and the+`unknown_agents` / `total_matched` idioms the upstream boundaries call for. Any+work here should extend that, not start beside it.++### (B) t_77efc212 — named shared observation scope++**B1. The v1.43.0 verdict is accurate and still binding.** Verified against the+code, not taken on trust: `ContinuityReadModelFilter` carries no scope member+(`read-model.ts:56-63`), and `private` is computed from the record rather than+declared by a caller (`read-model.ts:94`, `private: record["private"] === true`).+The verdict's demand stands.++**B2. The verdict's demand is now ANSWERABLE, and the answer is no.** It asked:+name the reader that would request a shared scope. §2 settles it — the shared+namespace has *zero* readers of any kind. A `shared` vocabulary member would be+declared by writers and consumed by nobody, and by the read-model's own drop+semantics a declared scope no reader names makes a record less visible, not more.+The 21 direct store readers (`reader-census.test.ts:82-116`) would not see it+either, since they bypass the read-model wholesale.++ **The premise of (B) does not hold, for the second time, for a reason that is+ now provable rather than argued.** The right move is not a third attempt at+ the field. It is to build the reader first — and the fleet view in (A) is a+ candidate reader, which is why these two tasks are correctly filed together.++**B3. The counts in the task body are stale by one.** The verdict says "four of+twenty-four readers". The census today lists 4 read-model readers and **21**+direct store readers — 25 total, not 24. See Defects §D1.++**B4. "a `shared` keyword added to an observation-scope taxonomy" would not be a+free-standing vocabulary here.** Any such member must satisfy the four-piece+shape and register in `verdict-vocabulary-census.test.ts` (§6), which has no+exemption list (`:59-61`). A one-member vocabulary also cannot satisfy the+duplicate/non-member checks meaningfully — the census's own reasoning about+`unknown` being "the member the trio was missing" (seed entry comment+at `:415-419`) shows the shape expects a real alternative, not a lone value.+This is the mechanical restatement of why the previous attempt's single member+was wrong.++---++## Smallest native unit per task++### (A) — the smallest unit that is true against this codebase++Not a fleet view. **Give `listSearchOrigins` an honest reachability verdict, and+give the shared namespace a place in it.**++Concretely, one unit:++1. A four-piece `ORIGIN_REACH` vocabulary (`reachable` / `unreachable` /+ `unknown` with an `ORIGIN_UNREACHABLE_REASON` companion), registered in+ `tests/core/architecture/verdict-vocabulary-census.test.ts` per §6, modelled+ on `NEGATIVE_RECALL_STATE` + `NEGATIVE_RECALL_UNKNOWN_REASON`+ (`src/core/brain/negative-recall.ts:114-124`, `:149-161`).+2. `listSearchOrigins` stops dropping broken sources silently+ (`src/core/brain/portability/origins.ts:63`) and instead returns every+ registered origin carrying its verdict, so `cross-vault.ts` can put an+ unreachable origin in the `warnings` array it already maintains+ (`src/core/search/cross-vault.ts:110`) rather than being handed a+ pre-filtered list it cannot describe.+3. `shared_namespace` becomes an enumerable origin, so the write-only sink+ becomes readable and the mirror stops being a one-way write into nothing.++This is native (it fixes a live defect, D2 below, in exactly the class this+release attacks), it is small, it invents no data, and it produces the reader+that (B) has now failed twice for lack of.++If a per-agent roster is genuinely wanted, the honest version is a **second,+smaller unit**: add `last_activity` (max contribution timestamp) to+`AgentSourceSummary` (`src/core/brain/agent-source/types.ts:24-30`) and surface+the existing `contribution_count` / `unknown_agents` / `total_matched` through a+roster mode. Two metrics, both real. **Do not ship an open-task count.**++### (B) — plain statement that the premise does not hold++The premise does not hold. A caller-declared `shared` scope requires a reader+that requests it; §2 proves there is not one, and §5 proves that even if there+were, 21 of 25 continuity readers would ignore it. The v1.43.0 verdict's+precondition is not merely unmet — it is now *measurably* unmet, and this recon+is the measurement. (B) should be blocked on (A)'s unit landing a reader, or+closed as premise-invalid. It should not be attempted a third time as written.++---++## Defects noticed++**D1. Reader-census prose has drifted from the census's own assertion, and the+floor hides it.** `DIRECT_STORE_READERS` holds 21 entries+(`tests/core/brain/continuity/reader-census.test.ts:82-116`), but three places+still say twenty: the census docblock (`:9-11`, "twenty call+`listContinuityRecords` straight off the store"), the read-model docblock+(`src/core/brain/continuity/read-model.ts:20`, "twenty call+`listContinuityRecords` directly"), and the shipped documentation+(`docs/observability.md:85`, "Twenty other modules call `listContinuityRecords`+on the store directly"). No test fails, because `MIN_DIRECT_STORE_READERS = 20`+(`reader-census.test.ts:134`) is a floor, not an equality. The census was built+to stop exactly this drift and does not cover its own prose.++**D2. `listSearchOrigins` silently drops unreachable origins — the exact defect+class this release attacks.** `src/core/brain/portability/origins.ts:63`:+`if (seen.has(vault) || source.broken) continue;`. A registered recall source+whose directory has gone away is removed from the fan-out *before*+`cross-vault.ts` ever sees it, so a cross-vault search over N origins where one+is unreachable returns as though that origin honestly contributed zero hits.+`cross-vault.ts` maintains a `warnings` array (`:110`) and cannot populate it,+because the information was destroyed upstream. The module docblock+(`origins.ts:12-14`) is candid that broken sources "never reach the search+fan-out" — it treats this as a design note rather than as the unknown-vs-zero+confusion it is. `recall-sources.ts:149-153` gets it right one layer down+("reported, never dropped"); `origins.ts` undoes that.++**D3. `mirrorSignal` / `mirrorNote` destroy the error object.**+`src/core/brain/shared-namespace.ts:52-54` and `:81-83` are bare+`catch { return "failed"; }`. A permissions problem, a missing shared vault, a+full disk and a schema violation are all one indistinguishable bit. The outcome+does reach the caller (`note.ts:89`, `feedback-tools.ts:273`,+`feedback.ts:199-200`), so this is not a swallowed *failure* — but it is a+swallowed *diagnosis*, and the mirror is precisely the path an operator cannot+observe by other means, since nothing reads the shared vault back (§2). The+sibling log append in the same functions at least writes the message to stderr+(`src/mcp/brain/feedback-tools.ts:200-202`). Minimum fix: carry a reason, using+the `*_UNKNOWN_REASON` idiom already in the census.++**D4. `MirrorOutcome` overloads `"failed"` across two unrelated conditions.** A+self-mirror is an *operator misconfiguration* detected before any I/O+(`src/core/brain/shared-namespace.ts:48`, `:69`, and the guard at `:92-94`), and+its own docblock calls it "always an operator misconfiguration" (`:88-89`) — yet+it returns the same token as a genuine write failure. The test asserts both as+`"failed"` (`tests/core/brain/shared-namespace.test.ts:73-74` vs `:78-79`),+which locks the conflation in. A vault where `shared_namespace` points at itself+reports identically to one where the shared disk is unmounted, and the fix for+each is completely different. `MirrorOutcome` is a three-member closed+vocabulary that does not follow the four-piece idiom (`:28` is a bare type alias+— no frozen object, no member list, no guard), so the census never audited it.++**D5. `MirrorOutcome` is not in the vocabulary census.** Following from D4:+`src/core/brain/shared-namespace.ts:28` is `export type MirrorOutcome = "ok" |+"failed" | "off";`. It is persisted-adjacent (it is emitted in MCP tool results+and CLI JSON at `feedback-tools.ts:273` and `feedback.ts:187`), which is the+condition the census exists for, but two-piece constructs are outside the scanned+population by design (`verdict-vocabulary-census.test.ts:73-76`). This is a+named blind spot being used, not a bug in the census — but it is the cheapest+way out of the population, and this vocabulary took it.++**D6. `resolveAgentName` falls back to the literal `"agent"`.**+`src/core/config.ts:379`. Every unconfigured install writes under one shared+identity, so a per-agent roster (§3) silently merges all of them into a single+row that looks like one very busy agent. Any fleet view must either distinguish+the default from a chosen name or refuse to report on it — reporting it as one+agent is a misleading non-empty, which is the same defect class as a misleading+empty.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/recon/identity-and-attribution.md b/docs/brainstorm/a-label-is-not-a-boundary/recon/identity-and-attribution.mdnew file mode 100644index 00000000..afd0d9c4--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/recon/identity-and-attribution.md@@ -0,0 +1,414 @@+# Recon: identity and attribution — who a write says it is, and who may read it++Read-only reconnaissance against `feat/a-label-is-not-a-boundary` @ `280469d2`+(v1.48.0). Covers kanban `t_3ebb6e0e` (agent identity modes) and `t_0c6f31ee`+(`on_delegation` episodic capture). Every claim below carries a `file:line`+anchor that was opened; three findings were reproduced by execution and say so.++Both task bodies are wrong in the same direction. They assume the missing thing+is a way to CARRY identity across a boundary. What is missing is a boundary at+all: identity is already carried, freely, by whoever asks.++## What exists++### The identity path, end to end++**Resolution.** One function: `resolveAgentName(configPath?)`+(`src/core/config.ts:373-380`). Order is `VAULT_AGENT_NAME` env → config+`agent_name` / `agentName` → the literal string `"agent"`. Nothing else resolves+an identity. `openclaw/index.js:1683` is a vendored duplicate in the bundled+plugin, not a second source.++Two derivations sit on top:++- `normalizeAgentArgument(value)` (`src/core/agent-identity.ts:44-55`) strips a+ leading `@`, trims, canonicalises `_`→`-`, and returns `null` for anything in+ `PLACEHOLDER_AGENT_VALUES` (`:19-42`) so a model that guessed `claude` or+ `assistant` falls through to the server value.+- `deriveRuntimeAgentName(runtimeId, operatorName)`+ (`src/core/agent-identity.ts:84-93`) rewrites `claude-vps-agent` into+ `openclaw-vps-agent` for a non-primary runtime. Callers:+ `src/openclaw/index.ts:58`, `src/core/install/identity.ts:29,51`.++**Where it is stamped.** Every writer takes the same shape — an optional caller+argument, then the resolved server value:++| Surface | Anchor |+|---|---|+| MCP feedback / evidence | `src/mcp/brain/feedback-tools.ts:114,368,600` |+| MCP admin | `src/mcp/brain/admin-tools.ts:81,234,290` |+| MCP knowledge | `src/mcp/brain/knowledge-tools.ts:527,600` |+| MCP write-batch | `src/mcp/brain/write-batch-tools.ts:167` |+| MCP synthesis (`brain_session_checkpoint`) | `src/mcp/brain/synthesis-tools.ts:224` |+| MCP context (`brain_write_session`) | `src/mcp/brain/context-tools.ts:80` |+| Core note | `src/core/brain/note.ts:64-65` |+| Core decisions | `src/core/brain/decisions/record.ts:397-398,476-477,528-529` |+| Core tombstone / temporal-replace | `src/core/brain/lifecycle/tombstone.ts:236-237`, `lifecycle/temporal-replace.ts:218-219` |+| Core tensions | `src/core/brain/tensions.ts:375` |+| Core diagnostics | `src/core/brain/diagnostics.ts:1166` |+| Entity registry (`source_agent`) | `src/core/brain/entities/registry.ts:504,542` |+| Claude-memory import | `src/core/brain/import-claude-memory.ts:250` |+| Session lifecycle hook | `hooks/session-capture.ts:51` |+| Shared-namespace mirror | `src/core/brain/shared-namespace.ts:50,77` |+| CLI verbs | `apply-evidence.ts:29`, `dream.ts:200`, `handoff.ts:32`, `import-session.ts:51`, `maintenance.ts:166`, `session-hook.ts:23` |++**Where it is read back.**++- `src/core/brain/agent-source/vault-provider.ts:28,117,142-149,169-175` — the+ only reader that turns a stored `agent` string into a queryable roster+ (signals' `agent`, log entries' `agent`).+- `src/core/brain/agent-source/registry.ts:39-80` folds that into+ `AgentSourceSummary`; `query.ts:46-70` filters it; `diff.ts:38-63` is the+ per-agent view `brain_agent_diff` serves — `per_agent` counts, `shared_topics`,+ `unique_topics`, `topic_map`.+- `src/core/graph/agent-scope.ts:104` `isOwnerVisible(owner, scope)` — the read+ side, comparing a page's `owner:` frontmatter against a requested scope.+- `src/mcp/server.ts:167-169` — `ServerContext.agentName`, a getter so a config+ edit takes effect without a restart, and so `ConfigReadError` reaches only the+ handlers that actually need an identity.+- `src/mcp/server.ts:295-316,433-435` — the `initialize` handshake renders the+ identity into the instructions, or renders the reason there is none.+- `templates/identity-reminder.txt:1`, `.hermes.txt:1`, `.openclaw.txt:1` via+ `buildReminder(agent, target)` (`src/core/identity-reminder.ts:134-141`).++**Per-turn injection.** Hermes `prefetch` (`plugins/hermes/provider.py:503-505`)+and OpenClaw `before_prompt_build` (`src/openclaw/index.ts:47-59`). Claude Code+and Codex get no identity reminder at all — their nudge is+`hooks/lib/messages.ts:postWriteReminder`, which carries no `@agent`+(`src/core/identity-reminder.ts:12-14`, `hooks/README.md` "What the hooks do").++### Hook events: what this repo registers, what the host delivers++`hooks/hooks.json` registers seven event names: `PostToolUse` (two matchers:+`brain_feedback`, `Write|Edit|MultiEdit|apply_patch`), `SessionStart`,+`UserPromptSubmit`, `PreToolUse`, `Stop`, `SessionEnd`, `PostCompact`. Nine entry+scripts back them (`hooks/active-inject.ts`, `gap-agenda.ts`, `gap-promote.ts`,+`nav-inject.ts`, `post-write-reminder.ts`, `pretool-orient.ts`,+`recall-inject.ts`, `session-capture.ts`, `stop-log-guardrail.ts`).++The host's full event list is+`~/.claude/plugins/marketplaces/claude-plugins-official/plugins/plugin-dev/README.md:63`:+`PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd,+UserPromptSubmit, PreCompact, Notification`.++Cross the two lists:++- **`SubagentStop` is delivered and not registered.** It is the delegation+ boundary event, and it exists today. `~/.claude/cache/changelog.md:1315,1672`+ confirms it is live and carries the same input shape as `Stop`.+- `PreCompact` and `Notification` are likewise delivered and not registered.+- `PostCompact` is registered and is **not** in the host's list —+ `hooks/README.md` and `hooks/lib/context-events.ts:12-19` already say so+ ("current Claude Code has no PostCompact hook event"), keeping the+ registration as a deliberate no-op.++### What a sub-agent leaves behind today (reproduced)++Against a real transcript tree in+`~/.claude/projects/-srv-projects-open-second-brain/c67b3203-ea88-4049-9972-12d0a00c0448/`:++1. Sub-agent turns are written to a **separate file**,+ `<parent-session-id>/subagents/agent-<id>.jsonl`. The parent transcript+ contains none of them.+2. Every line in that file carries `sessionId` **equal to the parent's session+ id**, plus its own `agentId` and `isSidechain: true`.+3. `claudeAdapter.detect()` returns `true` on it and+ `claudeAdapter.iterate()` yields 85 turns and 25 tool calls (executed).+ `turnFromLine` (`src/core/brain/sessions/claude.ts:32-82`) reads only+ `type`, `uuid`, `timestamp`, `message` — it reads neither `agentId` nor+ `isSidechain`. A sub-agent transcript imports as an ordinary session of the+ parent.+4. `importSessionPath` (`src/core/brain/sessions/import.ts:637-676`) walks a+ directory recursively for `*.jsonl`, so pointing it at a project directory+ ingests parent and sub-agent transcripts into one flat stream.+5. In this harness the delegation tool is named `Agent` (21 calls in that+ transcript), and it is **asynchronous**: the `tool_result` at the call site is+ `"Async agent launched successfully… agentId: …"` (1112 bytes of launch+ metadata), not the sub-agent's answer. The answer arrives later as a synthetic+ user turn `<task-notification>` carrying `<task-id>`, `<tool-use-id>`,+ `<output-file>` (a path under `/tmp/claude-…/tasks/`), `<status>` and+ `<summary>`.++So the parent transcript alone already holds both halves of the pair, joinable on+`tool-use-id`: the task (the `Agent` tool_use `input.prompt`) and the completion+record (the `<task-notification>` turn). The full result body lives in a `/tmp`+file that is not part of the transcript.++### Continuity records and the `agent` field++`docs/observability.md:73` (the task body cites `:66`; the line is **73**) says:+"Multi-agent vaults attribute writers via per-agent identity+(`brain_agent_query`); continuity records do not yet thread parent/child agent+ids". **Still true, and understated.**++- `session_turn` payload (`src/core/brain/session-recall.ts:350-364`) and+ `session_summary_node` payload (`:400-410`) carry `session_id`, `turn_id`,+ `timestamp`, `role`, `text`, hashes, lineage — and **no agent field at all**.+ Not "no parent id": no id.+- `CONTINUITY_AGENT_ID_KEY = "agent_id"` exists+ (`src/core/brain/continuity/types.ts:15`) and is clip-protected (`:38-42`), but+ the only writer is `brain_context_pack_outcome`, from a caller **argument**+ (`src/mcp/brain/recall-tools.ts:760`).+- The envelope is pinned at eight fields+ (`docs/observability.md:32`, `tests/core/brain/continuity/record-envelope.test.ts`),+ so an agent id can only ride inside `payload` as an additive field — which is+ exactly what `docs/observability.md:73` already promises.+- Session lineage (`src/core/brain/lineage/resolve.ts:1-19`) threads+ `parent_session_id` / `root_session_id` / `compression_depth`+ (`hooks/lib/stdin.ts:28-30`), but the docblock is explicit that this answers+ "which conversation does this session id belong to" for **compression chains**.+ It cannot separate a sub-agent anyway: finding 2 above shows the sub-agent+ reuses the parent's `sessionId`.++### Shared-namespace attribution++`src/core/brain/shared-namespace.ts` mirrors explicit remember-writes into a+second vault named by the `shared_namespace` config key (`:31-35`). Attribution+is carried twice: the existing `agent` field and `origin_vault`, the basename of+the primary vault (`:50`, `:77`). Writers: `src/cli/brain/verbs/feedback.ts:97-101`+and `src/mcp/brain/feedback-tools.ts:59` for signals, `src/core/brain/note.ts:75-79`+for notes. Self-mirror is refused as `"failed"` rather than silently duplicated+(`:92-94`).++## What does not exist++- **No `on_delegation` hook, in any spelling.** A repository-wide search for+ `delegation`, `on_delegation`, `subagent`, `sub-agent`, `SubagentStop` (all+ file types, excluding `node_modules` and `docs/brainstorm/`) returns only+ docblocks about *dispatching* work outward — `ingest/batch-plan.ts:10-11`,+ `ingest/checkpoint.ts:172`, `sync-lockfile.ts:232`, `health/reconcile.ts:7` —+ and generic "delegates to" prose. Nothing captures a returning sub-agent.+- **No identity mode switch.** No config key, env var, tool argument, or CLI flag+ selects between identity behaviours. `resolveAgentName` has one code path.+- **No `off`.** There is no way to suppress identity. The bottom of the chain is+ the literal string `"agent"` (`src/core/config.ts:379`), which is itself in+ `PLACEHOLDER_AGENT_VALUES` (`src/core/agent-identity.ts:20`) — so the "no+ identity configured" state is a value that every argument-normalising surface+ rejects, and `src/openclaw/index.ts:53` special-cases by comparing to it.+- **No `tool_response` consumer in capture.** `hooks/lib/stdin.ts:41` declares+ the field and `:57` maps grok's `toolResponse` onto it, but+ `normalizePayload` (`src/core/brain/session-lifecycle.ts:528-570`) lifts+ `tool_name` and `tool_input` and **not** `tool_response`. The only reader+ anywhere is `hooks/post-write-reminder.ts:100`, and it only asks whether the+ call errored.+- **No reader for `origin_vault`.** Grep across `src/`, `tests/`, `docs/`: it is+ written at `shared-namespace.ts:50,77`, persisted into signal frontmatter at+ `src/core/brain/signal.ts:403-404`, asserted present by+ `tests/core/brain/shared-namespace.test.ts:67,94`, and read by nothing. No+ query filter, no display field, no roster dimension. `brain_agent_diff` cannot+ tell a mirrored contribution from a native one.+- **No credential.** `src/core/write-binding/index.ts:12-22` states the position+ in the source: there is no credential in this system to key a fence to, and a+ caller who can call the tool can name itself anything. `initialize` discards+ `clientInfo`; `handleToolsCall` performs no JSON-schema validation, so+ `required` and `additionalProperties: false` are advisory to the model.++## Correction to premise (A) — `managed` / `passthrough` / `off`++**`passthrough` is not missing. It is the default, it is unconditional, and it is+the defect.**++Enumerated by loading the shipped schemas (executed against+`src/mcp/brain-tools.ts`, 92 tools, plus `search-tools`/`skill-tools`/+`schema-tools`/`watchdog-tools`, 12 tools):++- **21 tools accept a caller-supplied `agent`** and stamp it verbatim onto the+ record: `brain_apply_evidence`, `brain_dead_ends`, `brain_decision`,+ `brain_delete_by_source`, `brain_derive_fact`, `brain_distill_source`,+ `brain_dream`, `brain_feedback`, `brain_generation_reports`,+ `brain_ingest_source`, `brain_intake_entities`, `brain_labels`,+ `brain_lifecycle`, `brain_maintenance`, `brain_note`, `brain_research_report`,+ `brain_secrets`, `brain_session_checkpoint`, `brain_tension`, `brain_truth`,+ `brain_write_session`.+- **12 tools accept a caller-supplied `agent_scope`**: `brain_agent_query`,+ `brain_anticipatory_context`, `brain_brief`, `brain_context_pack`,+ `brain_deep_synthesis`, `brain_file_context`, `brain_pre_compress_pack`,+ `brain_query`, `brain_retrieval_plan`, `brain_search`, `brain_search_expand`,+ `brain_search_by_source`.++The only filter on a supplied `agent` is `normalizeAgentArgument`+(`src/core/agent-identity.ts:44-55`), which rejects 22 well-known placeholder+strings and accepts every other string on sight. A sub-agent can already write+under the orchestrator's identity today by passing `agent: "<parent-name>"`. That+is `passthrough`, shipped, with no switch and no verification. The project has+written the reason down itself: `src/mcp/brain/recall-tools.ts:738-750` argues+that "the identity a client asserts is exactly as self-asserted as the one the+config holds".++**`managed` does not exist except in one place.** `brain_context` is the single+surface with no `agent` argument, so `ServerContext.agentName` is its only source+of identity (`src/mcp/server.ts:151-169`, `src/mcp/brain/context-tools.ts:388-397`).+Everywhere else, the config value is a default, not an owner.++**The read side has the same hole, and it is worse because it is sold as+isolation.** `coerceAgentScope(ctx, args, fallbackToServerIdentity)`+(`src/mcp/coerce.ts:115-123`) returns an explicit argument **unconditionally**;+the server identity is consulted only when the argument is absent. Six gated+call sites pass `true` (`recall-tools.ts:379`, `pack-tools.ts:151,567,656`,+`brief-tools.ts:74,150`). `resolveOwnerScopeDelivery`+(`src/core/brain/preferences-collect.ts:171-185`) then sets+`enforcedScope = requestedScope` under `owner_scope_delivery: fail` — the scope+enforced is the one the caller asked for, never checked against the caller. So+with the isolation gate ON, any caller reads any owner's owner-private+preferences by naming that owner in `agent_scope`. The label is the boundary.++**`off` has no subject.** There is no identity behaviour to disable — no+per-record cost, no per-turn injection on Claude Code / Codex at all. Suppressing+"identity noise in a single-agent vault" would mean not rendering+`templates/identity-reminder.txt` on Hermes/OpenClaw, which is one string in one+prompt, and the operator already gets that by leaving `agent_name` unset+(`src/openclaw/index.ts:53` returns `undefined` and injects nothing).++## Correction to premise (B) — `on_delegation`++The validator's finding is confirmed — no hook, no capture — but the framing is+wrong on three counts.++1. **"The capture point sits on the HOST runtime's delegation boundary, not+ inside Open Second Brain."** Half right. The host exposes exactly the boundary+ this repo needs and this repo does not register it: `SubagentStop`. It carries+ `session_id` and `transcript_path` like `Stop` does, and the sub-agent+ transcript it names is a real file on disk that `claudeAdapter` already parses+ (reproduced above: 85 turns, 25 tool calls).++2. **"Captures each delegated sub-agent's (task, result) pair."** At the+ delegation tool boundary in this harness there is no result to capture. The+ `Agent` tool is async; its `tool_result` is a 1112-byte launch receipt. A hook+ built on `PostToolUse`/`Agent` would persist a task and a receipt — a capture+ that captures nothing, which is precisely the do-nothing fallback this+ repository forbids. The result is recoverable only from (a) the+ `<task-notification>` turn later in the parent transcript, or (b) the+ sub-agent's own transcript file, or (c) the `/tmp` output file, which is+ ephemeral.++3. **"Scoped to the PARENT agent's namespace."** There is no namespace to scope+ to. `sessionId` is identical for parent and sub-agent (finding 2), and the+ `agent` label is a per-adapter constant (see the defect below), so both halves+ of the intended key are already collapsed before any hook runs.++**Does an orchestrator's later turn recall what a dispatched worker found?+No — and the mechanism that would carry it erases the distinction rather than+losing it.** Today the only route is `o2b brain import-session` over the+transcript tree, which flattens sub-agent turns into the parent session id under+the label `"claude"`. `brain_session_checkpoint`+(`src/mcp/brain/synthesis-tools.ts:213-230`) and `brain_write_session`+(`src/mcp/brain/context-tools.ts:60-160`) are voluntary: the agent must decide to+call them, and a sub-agent that finishes without calling one leaves nothing.+`brain_pre_compact_extract` (`src/mcp/brain/pack-tools.ts:604-620`) requires+`session_id`, `turn_start`, `turn_end` and `text` from the caller — it is a+kernel for text the caller already holds, not a capture.++## Smallest native unit per task++### For `t_3ebb6e0e` — the honest unit is a REFUSAL, not a mode++The three-mode vocabulary does not map. `passthrough` ships as the ungated+default; `off` has no subject. The one mode that does not exist is `managed`, and+naming it "a mode" hides that today's behaviour is the unsafe one.++Smallest native unit: **a config key that makes the server-resolved identity+authoritative, and refuses a conflicting caller-supplied one.**++- One key, default off so existing vaults are byte-identical. When on,+ `normalizeAgentArgument(args.agent)` that resolves to something other than the+ server identity becomes an `INVALID_PARAMS` error naming both values, rather+ than being silently accepted (21 write tools) or silently honoured (12 read+ tools).+- The read side is the load-bearing half: under `owner_scope_delivery: fail`,+ `coerceAgentScope` (`src/mcp/coerce.ts:120-121`) must stop letting an explicit+ argument outrank `ctx.agentName`. Today the isolation gate isolates by+ self-declaration, which is not isolation. This is a real behaviour change and+ belongs in the release notes as one.+- It changes something observable in both directions, so it is not a mode that+ changes nothing.++What it does not buy, stated honestly: nothing here authenticates a caller. A+process that can reach the MCP socket can edit `agent_name` or set+`VAULT_AGENT_NAME`. The value is that a *cooperating* multi-agent setup stops+being able to cross the line by accident, and a crossing becomes an error with a+name instead of a record.++### For `t_0c6f31ee` — register the boundary the host already fires++The premise "an `on_delegation` hook … writes a (task, result) pair" does not+hold as written: the delegation call site has no result. What does hold:++Smallest native unit: **a `SubagentStop` registration in `hooks/hooks.json`+routing to `session-capture`, plus the two fields that make a sub-agent+distinguishable.**++1. Register `SubagentStop` in `hooks/hooks.json` alongside `Stop`, same+ launcher shape, same fail-soft contract. The event is delivered today and this+ repo ignores it.+2. Lift the sub-agent discriminators the transcript already carries into+ `SessionTurn`: `agentId` and `isSidechain` in+ `src/core/brain/sessions/claude.ts:32-82`, and a corresponding optional field+ in `sessions/types.ts`. Without this, step 1 records a second session under+ the parent's id and the boundary is still erased.+3. Persist the sub-agent's turns as `session_turn` continuity records under a+ payload that names both ids — the additive-field path+ `docs/observability.md:73` already commits to, no schema bump. The parent+ recalls the worker through `searchSessionRecall`+ (`src/core/brain/session-recall.ts:190-200`), which is the read surface that+ already exists.++Bounded and fail-soft come free: `armProcessCeiling`+(`hooks/session-capture.ts:20-37`) and the capture boundary+(`src/core/brain/session-lifecycle.ts:186-190`) already govern every lifecycle+event.++If `SubagentStop` cannot be relied on across the host matrix, the fallback that+is still honest is the `<task-notification>` turn in the parent transcript — it+is ordinary transcript text, already parsed into a `SessionTurn`, and joinable to+the `Agent` tool_use on `tool-use-id`. That records the summary and the status,+never the full result, and should say so.++## Defects noticed++1. **`--agent` on `o2b brain import-session` is accepted, validated, and+ discarded.** `agentLabelForTurn`+ (`src/core/brain/sessions/import.ts:601-604`) is+ `getAdapter(adapter).defaultAgent.trim() || fallback`. Every shipped+ `defaultAgent` is a non-empty constant, so `fallback` — the `opts.agent` that+ `src/cli/brain/verbs/import-session.ts:47-51` computed from `--agent` or+ `resolveAgentName(config)` — is unreachable. Executed: with+ `--agent claude-vps-agent` on a claude transcript the emitted label is+ `"claude"`. Four call sites are affected (`import.ts:427,458,490,520`). The+ docblock at `:597-600` documents the precedence as intentional; the CLI flag+ contradicts it, and one of the two is wrong.++2. **Three of five session adapters stamp a label that every other surface+ treats as "no identity".** Executed against+ `src/core/brain/sessions/registry.ts:36-42`:+ `normalizeAgentArgument("claude") → null`, `"codex" → null`,+ `"hermes" → null`; `"opencode"` and `"grok"` survive. So session-imported+ signals are attributed to a string that `normalizeAgentArgument` rejects+ everywhere else, and `brain_agent_query` rosters an agent named `claude` that+ no writer could ever have named itself.++3. **`origin_vault` is write-only.** Written at+ `src/core/brain/shared-namespace.ts:50,77`, persisted at+ `src/core/brain/signal.ts:403-404`, read by nothing in `src/`. The module+ docblock (`:9-10`) advertises it as one of two attribution carriers. A+ contributor field no reader consults is attribution in name only.++4. **`tool_response` is declared and dropped.** `hooks/lib/stdin.ts:41` and+ `:57` carry it to `captureSessionLifecycleEvent`, and+ `normalizePayload` (`src/core/brain/session-lifecycle.ts:563-568`) lifts+ `tool_name` and `tool_input` past it. Any capture of what a tool *returned* —+ including the delegation unit above — starts by fixing this line.++5. **`agentLabelForTurn` takes a `turn` it discards.**+ `src/core/brain/sessions/import.ts:602` is `void turn; // reserved for future+ per-turn role-aware fallback`. It is the exact seam where a sub-agent turn+ would need to be labelled differently, and it is currently a parameter that+ exists to be ignored.++6. **`resolveOwnerScopeDelivery` enforces the requested scope, not the caller's.**+ `src/core/brain/preferences-collect.ts:182`:+ `enforcedScope: mode === GATE_MODE.fail ? requestedScope : null`. Combined+ with `src/mcp/coerce.ts:120-121`, turning the isolation gate on gives a caller+ the ability to select which owner's private memory it receives. This is the+ sharpest instance of the release's thesis and the one place where the current+ behaviour is worse than having no gate, because the gate's presence implies a+ check that is not performed.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/recon/mcp-instruction-surface.md b/docs/brainstorm/a-label-is-not-a-boundary/recon/mcp-instruction-surface.mdnew file mode 100644index 00000000..0531738a--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/recon/mcp-instruction-surface.md@@ -0,0 +1,445 @@+# Recon — the MCP instruction surface, and whether `agent` can select on it++Task under verification: kanban `t_f2ede668` (priority 2), "Per-agent extraction+instruction set selectable by agent scope, with split-by-attribution".++Every claim below carries a `file:line` anchor that was read. Anchors are from+the working tree on `feat/a-label-is-not-a-boundary`.++---++## What exists++### 1. The instruction surface, end to end++`src/mcp/instructions.ts` is the whole surface. It exports one function and+holds three bodies of text.++| Piece | Anchor | Varies by |+| --- | --- | --- |+| `BuildInstructionsOpts` | `src/mcp/instructions.ts:13` | — |+| `WRITER_INSTRUCTIONS` (constant) | `src/mcp/instructions.ts:32` | nothing |+| `CATALOG_INSTRUCTIONS` (constant) | `src/mcp/instructions.ts:61` | nothing |+| `identityLine(agent)` | `src/mcp/instructions.ts:89` | `agent` only |+| `buildInstructions` full branch | `src/mcp/instructions.ts:116-138` | `agent` (one sentence) |++Assembly is a three-way branch in `buildInstructions`+(`src/mcp/instructions.ts:105`):++- `scope === "writer"` → return `WRITER_INSTRUCTIONS` verbatim+ (`src/mcp/instructions.ts:110`).+- `scope === "catalog"` → return `CATALOG_INSTRUCTIONS` verbatim+ (`src/mcp/instructions.ts:111`).+- otherwise → `identityLine(agent)` concatenated with four fixed paragraphs+ (memory contract, consolidated read views, preview budget)+ (`src/mcp/instructions.ts:116-138`).++**What varies today: exactly one sentence, and only on one of three scopes.**+`identityLine` renders either `You are @<agent> on this Open Second Brain+vault.` (`src/mcp/instructions.ts:91-94`) or a refusal naming the unreadable+config (`src/mcp/instructions.ts:96-102`). Everything else is a literal.++**`agent` is discarded on two of three scopes.** The writer and catalog+branches return before `agent` is ever read (`src/mcp/instructions.ts:110-111`).+The writer scope is the always-loaded surface an agent carries in every+session — so on the surface where agent identity matters most, the current+code does not use `agent` at all.++**`vault` is declared and never read.** `BuildInstructionsOpts.vault`+(`src/mcp/instructions.ts:26-27`) is documented as "reserved for future+per-vault customisation" and does not appear anywhere in the function body+(`src/mcp/instructions.ts:105-139`). A test passes it anyway+(`tests/mcp/mcp.test.ts:793`).++Callers of `buildInstructions`, complete:++- `src/mcp/server.ts:313` — the only production caller.+- `src/mcp/index.ts:25` — re-export.+- `scripts/measure-token-surface.ts:62-63` — token-budget report.+- `tests/mcp/mcp.test.ts:792` — writer-branch assertion.++### 2. How the block reaches a client++`initialize` is the only carrier. `MCPServer.handleInitialize`+(`src/mcp/server.ts:295`) returns `instructions: buildInstructions({ agent,+scope })` at `src/mcp/server.ts:313`. No other JSON-RPC method emits it; the+`tools/list`, `resources/list`, and `tools/call` handlers+(`src/mcp/server.ts:320`, `:335`, `:352`) never touch it.++It is **re-computed on every `initialize` request** — `resolveIdentityOrReason`+(`src/mcp/server.ts:305`, defined `src/mcp/server.ts:433`) reads the config+each time rather than caching at construction. But every input is+process-global:++- `resolveAgentName` order is `VAULT_AGENT_NAME` env → `agent_name`/`agentName`+ in the plugin config → the literal `"agent"` (`src/core/config.ts:373-380`).+- `this.scope` is fixed at construction (`src/mcp/server.ts:122`).++**`handleInitialize` reads only `params["protocolVersion"]`**+(`src/mcp/server.ts:296`). `clientInfo` is never read anywhere under `src/`+(grep for `clientInfo`: zero hits). So the request carries no identity the+server consults.++Transport confirms the same:++- **stdio** — one process per client (`src/mcp/stdio.ts:46`); the process's+ env/config *is* the agent.+- **HTTP** — a single `MCPServer` instance is shared by every request+ (`src/mcp/http.ts:52`). An `mcp-session-id` is minted on `initialize`+ (`src/mcp/http.ts:166`) and **never read back** — grep shows exactly one+ occurrence. There is no per-session or per-client state of any kind.++**Consequence:** a client cannot receive a different block per agent over+either transport. "One block per agent" is already expressible today, and only+today, as "one server process per agent" — which is precisely how identity is+configured now.++### 3. Where a per-agent block would be declared — nowhere, today++Two config files exist; neither can hold the value.++**Plugin config** (`~/.config/open-second-brain/config.yaml`, located by+`resolveDefaultConfigPath`, `src/core/config.ts:120`) is parsed by+`parseSimpleYaml` (`src/core/config.ts:~148`), which is a flat `key: value`+reader: "Lines that aren't `key: value` (comments, blanks, complex YAML) are+skipped." No nesting, therefore no map of agent → block.++**Vault config** (`<vault>/Brain/_brain.yaml`, `src/core/brain/policy/load.ts`)+is parsed by `parseBrainYaml` (`src/core/brain/yaml-parse.ts:39`). Its grammar+is stated at `src/core/brain/yaml-parse.ts:9-24`: top-level scalars, one+indented block level, and lists inside a block — "This intentionally rejects+nested mappings deeper than two levels". Scalars have no escape sequences and+there is no block-scalar (`|`) form, so a multi-line instruction body is not+expressible. Every block is additionally validated against a closed+`KNOWN_KEYS` list (pattern at `src/core/brain/policy/blocks/discipline-report.ts:19`),+so an arbitrary agent-name key would be rejected as unknown.++The only agent-keyed configuration that exists:++- `primary_agent` — a single scalar (`src/core/brain/policy/primary-agent.ts:15,45`).+- `discipline_report.known_agents` — a list of strings+ (`src/core/brain/policy/blocks/discipline-report.ts:19,52`).++Neither is a map from agent to anything.++**Operator text already has two homes, both global:**++- `Brain/standing-rules.md` — `src/core/brain/standing-rules.ts:1-2`, path+ constant `src/core/brain/path-constants.ts:173`, capped at 4000 chars+ (`src/core/brain/standing-rules.ts:67`), injected first and exempt from the+ adaptive budget (`src/core/brain/standing-rules.ts:5-11`).+- `<vault>/VAULT.md`, name configurable via `link_graph.vault_instruction_file`+ — `src/core/brain/vault-instruction-file.ts:31-33`, resolved at+ `src/core/brain/vault-instruction-file.ts:100-108`, line ceiling from+ `guardrails.instruction_file_max_lines` (`src/core/brain/config-template.ts:339`,+ checked `src/core/brain/doctor.ts:305-308`).++Both are delivered by `brain_context`, a `tools/call` surface+(`src/mcp/brain/context-tools.ts:338` reads standing rules, `:408` prepends+them; the vault instruction file is read in the enrichment just below), not by+`initialize`. Neither has a per-agent axis.++### 4. `scope` — what it selects, and orthogonality++**The task's anchor is wrong.** `src/mcp/server.ts:79` is inside the+`sendNotification` doc comment. The real anchors are:++- `ToolScope = "full" | "writer" | "catalog"` — `src/mcp/tool-contract.ts:19`.+- `MCPServerRuntimeOptions.scope` — `src/mcp/server.ts:59`.+- Stored per server — `src/mcp/server.ts:104`, defaulted `src/mcp/server.ts:122`.++`scope` selects two things: which tools `buildToolTable` emits+(`src/mcp/tools.ts:438`, catalog branch `src/mcp/tools.ts:540`), and which+instruction constant is returned (`src/mcp/instructions.ts:110-111`). It is a+process-level flag, set by `--scope` / `--writer-only` / `--tool-profile`+(`src/cli/main.ts:602,614-634,667`) through `resolveToolSurface`+(`src/mcp/profiles.ts:121-145`).++**Orthogonal in principle, entangled in fact.** `scope` and agent identity are+independent inputs, but `scope` currently decides *whether the agent axis is+consulted at all*: writer and catalog discard `agent`+(`src/mcp/instructions.ts:110-111`). A per-agent block would therefore have to+be defined over `(agent × scope)`, or the two constant branches would need an+identity line they deliberately do not have today.++### 5. The intake path, and every reader of `source_agent`++Types and stamp:++- `ExtractionIntake` — `src/core/brain/intake/extract-intake.ts:61`.+- `IntakeOptions` — `src/core/brain/intake/extract-intake.ts:66`; `agent` at+ `:68`, documented as "Agent identity stamped as the entity `source_agent`".+ There is **no instruction field** on it.+- `intakeExtraction` — `src/core/brain/intake/extract-intake.ts:194`; passes+ `agent: opts.agent` into `upsertEntity` at `:219`.++Writes:++- `src/core/brain/entities/registry.ts:504` — update arm, `source_agent: input.agent`.+- `src/core/brain/entities/registry.ts:542` — create arm, `source_agent: input.agent`.+- `src/core/brain/entities/registry.ts:319` — the field's slot in+ `ENTITY_FIELD_ORDER`.+- `src/core/brain/entities/registry.ts:620` — carried forward unchanged on relate.+- `src/core/brain/entities/registry.ts:705` — carried forward unchanged on status change.++Readers, complete (grep `source_agent|sourceAgent` over `src/`):++- `src/core/brain/entities/types.ts:57` — `readonly source_agent?: string` on+ the index entry.+- `src/core/brain/entities/index-builder.ts:112,120` — parsed off frontmatter+ into that index entry.+- `src/cli/brain/verbs/entity.ts:39` — rendered in CLI output.+- `src/mcp/brain/entity-tools.ts:36` — rendered in the MCP response.+- `src/core/brain/frontmatter-tiers.ts:119` — classified as tier `"system"`+ under `brain-entity`.++**Nothing filters, gates, routes, or selects on `source_agent`.** It is written,+indexed, displayed, and tier-classified. The validator hint is correct.++Where the intake `agent` comes from at the MCP boundary:++- `src/mcp/brain/ner-tools.ts:34-36` — optional per-call `agent` argument, else+ `resolveAgentName(ctx.configPath)`.+- `src/mcp/brain/ingest-tools.ts:54-56` — the same pattern.+- Parsed at `src/mcp/brain/intake-args.ts:164`.++So intake's `agent` **is** a per-call value. The instruction surface's `agent`+is not. Same word, two axes.++### 6. The four-piece closed-vocabulary idiom++Enforced by `tests/core/architecture/verdict-vocabulary-census.test.ts`. The+four pieces, all four required and all four **in one module**+(doc block `:40-48`):++1. `const NAME = Object.freeze({ … })` whose every entry is+ `key: "string literal"`;+2. a derived union — `(typeof NAME)[keyof typeof NAME]`;+3. a membership list built from it — `Object.values(NAME)` or an array of+ `NAME.member`;+4. a guard: a function or arrow whose parameter is typed **`unknown`** and+ which reads the membership list or the object.++`auditVocabulary` (`:374-404`) enforces seven checks:++1. the values object is frozen (`:378`);+2. no duplicate value in the object (`:382`);+3. no duplicate in the membership list (`:387`);+4. every declared value is a member (`:392`);+5. the guard accepts every declared value (`:393`);+6. every member is declared (`:396`);+7. the guard rejects every `NON_MEMBERS` outsider (`:398-401`) — the outsiders+ are `""`, `" "`, `"unknown-vocabulary-member"`, `null`, `undefined`, `42`,+ `{}` (`:363-371`).++Registration is not optional: `scanVocabularies` walks `src/`+(`:1285`, invoked `:1327`) and `CENSUS` (`:411`) must account for every+vocabulary found; an entry in `CENSUS` that the scan cannot find is reported as+orphaned (`:1423`). There is **no exemption list** — the doc block states why+(`:59-63`).++Known blind spots the doc names (`:66-97`): a vocabulary split across modules,+a two-piece vocabulary, non-literal values, a guard typed `string`, trees other+than `src/`, and code inside a template interpolation.++**`ToolScope` is not in this population.** `src/mcp/tool-contract.ts:19` is a+bare union — no frozen object, no members array, no guard. So the existing+scope axis does *not* follow the idiom, and a new selector built to the idiom+would sit beside a sibling that is not.++`KNOWN_RUNTIME_TARGETS` (`src/core/identity-reminder.ts:41`) is also out of+population: array plus derived type plus guard, but no frozen object, and+`isRuntimeTarget` takes `string | undefined` (`src/core/identity-reminder.ts:45`)+rather than `unknown`. It is the nearest existing "selector" and it must not be+copied as a template.++### 7. Existing "operator supplies text the server returns" mechanisms++Three exist. **All three select on runtime or host — none on agent.**++1. **Per-runtime template files.** `templates/identity-reminder.txt` plus+ `templates/identity-reminder.<target>.txt` for `hermes` and `openclaw`+ (`src/core/identity-reminder.ts:41`). Read at+ `src/core/identity-reminder.ts:57` (common) and `:92` (per-target);+ `{agent}` is substituted at `:138,:140`; target comes from an explicit+ parameter or `O2B_TARGET` (`:108-119`); a missing per-target file silently+ falls back (`:136-140`). These files ship in the repo — they are install+ artifacts, not operator-authored vault content, and the module states that+ adding a target "is a PR-change … not a runtime decision"+ (`src/core/identity-reminder.ts:34-39`).++2. **Per-runtime hook reminder.** `postWriteReminder`+ (`hooks/lib/messages.ts:57`) with `postWriteCadenceLine`+ (`hooks/lib/messages.ts:30-55`) branching over `HookRuntime`+ (`claudecode | codex | grok | unknown`).++3. **Operator-authored vault text.** `Brain/standing-rules.md`+ (`src/core/brain/standing-rules.ts`) and `<vault>/VAULT.md`+ (`src/core/brain/vault-instruction-file.ts`), both delivered through+ `brain_context` (`src/mcp/brain/context-tools.ts:338,408`).++Mechanism 3 is the one that already answers "an operator writes text and the+server returns it". Building a per-agent instruction block on the `initialize`+path would be a fourth mechanism with a fifth text home.++---++## What does not exist++- **No per-agent configuration store, in the vault or in the device config.**+ Neither YAML grammar can represent a map from agent name to a text block+ (§3). Nothing under `src/core/brain/policy/blocks/` is keyed by agent.+- **No per-agent selection anywhere in the instruction path.**+ `BuildInstructionsOpts` (`src/mcp/instructions.ts:13`) exposes+ `agent`/`vault?`/`scope?`; only `agent` and `scope` are read, and `agent`+ reaches one sentence on one branch.+- **No per-request or per-session identity.** `clientInfo` is unread; the HTTP+ session id is minted and discarded (`src/mcp/http.ts:166`).+- **No instruction field on `IntakeOptions`** (`src/core/brain/intake/extract-intake.ts:66-80`).+- **No behavioural reader of `source_agent`** — it is a display/index field+ only (§5).+- **No server-side extraction prompt to instruct.** Extraction is agent-side;+ the module header states the boundary explicitly:+ "the model that produced the extraction lives on the agent side of the+ MCP/CLI boundary. This primitive never calls a model"+ (`src/core/brain/intake/extract-intake.ts:10-12`), echoed at+ `src/mcp/brain/ner-tools.ts:5`.++---++## Corrections to the premise++1. **`src/mcp/server.ts:79` does not define `scope`.** That line is inside the+ `sendNotification` doc comment. `ToolScope` is `src/mcp/tool-contract.ts:19`;+ the runtime option is `src/mcp/server.ts:59`; the stored field is+ `src/mcp/server.ts:104`.++2. **`recall-tools.ts:720` has nothing to do with `agent` stamping.** That line+ is inside `brain_context_pack_outcome`'s `post` branch+ (`src/mcp/brain/recall-tools.ts:700-735`), returning `evidence` on a+ context-pack outcome. No `agent`, no `source_agent`.++3. **"`agent` is only a LABEL" is right for intake and wrong for instructions.**+ In `IntakeOptions` it is a pure stamp (§5). In `BuildInstructionsOpts` it is+ not a label at all — it is rendered into a directive sentence+ (`src/mcp/instructions.ts:91-94`) or replaced by a refusal+ (`src/mcp/instructions.ts:96-102`). And on the writer and catalog scopes it+ is **dropped entirely** (`src/mcp/instructions.ts:110-111`), which is a+ sharper finding than "it is only a label": the always-loaded surface has no+ identity line whatsoever.++4. **These are two different `agent` axes, not one.** Intake's `agent` is a+ per-call tool argument with a server-resolved default+ (`src/mcp/brain/ner-tools.ts:34-36`, `src/mcp/brain/ingest-tools.ts:54-56`).+ The instruction surface's `agent` is a process-level config value read at+ handshake (`src/core/config.ts:373-380`, `src/mcp/server.ts:305`). Turning+ the first into a selector says nothing about the second, and vice versa.+ The task treats them as the same field.++5. **"Selectable by agent" is not reachable over the transport as designed.**+ Both transports resolve identity from process env/config, never from the+ request (§2). Per-agent selection today collapses to per-process selection,+ which the install already provides by giving each agent its own+ `VAULT_AGENT_NAME` or config file. There is no new capability in "select by+ agent" unless a new identity channel is introduced — and introducing one+ (trusting a client-declared name) would put the identity an agent writes+ under into the agent's own hands, which+ `src/mcp/instructions.ts:17-23` argues against by name.++6. **"Give the block a home" is the real precondition, and it is not free.**+ The task's own hedge is correct but understated: no operator can write a+ per-agent block anywhere today, and neither YAML grammar can be extended to+ hold one without either a third-level map (`src/core/brain/yaml-parse.ts:23`+ rejects it by design) or a new file-per-agent convention that would be a+ fourth operator-text mechanism alongside `standing-rules.md`, `VAULT.md`,+ and the `templates/identity-reminder.*.txt` set (§7).++---++## Smallest native unit that is true against this codebase++**None of the shapes in the task body is a native unit as stated.** The honest+finding is that "select a per-agent instruction block" has no supplier, no+home, and no transport channel. Stating that is the correct output.++Ranked by how native they are:++**A. The true zero-invention unit — the writer scope has no identity line.**+`src/mcp/instructions.ts:110` returns `WRITER_INSTRUCTIONS` before `agent` is+read, so the always-loaded surface — the one an agent carries into every+session — never says which name to log under, while the full surface insists on+it (`src/mcp/instructions.ts:91-94`). The writer tools are exactly the+identity-bearing writers. This is a real gap in the existing design, needs no+new config, no new vocabulary, and no new file: prepend `identityLine(agent)`+to the writer (and catalog) branches. It also removes the entanglement noted in+§4. This is the smallest thing that is both true and worth doing here.++**B. If a per-agent block is genuinely wanted, the home comes first and it is+the whole unit.** The only native home is the one that already exists: an+operator-authored file delivered through `brain_context`, alongside+`standing-rules.md` and `VAULT.md` (§7, `src/mcp/brain/context-tools.ts:338,408`).+Not `initialize.instructions` — that path is process-global, capped by a token+budget the repo actively measures (`scripts/measure-token-surface.ts:83-84`),+and has no per-agent axis to hang anything on. Framing it as "extend the+existing operator-text lane with an agent-scoped variant" keeps one mechanism;+framing it as "per-agent block in `initialize`" invents a parallel one, which+this repo forbids.++**C. What must NOT be built.** A `ToolScope`-style selector union for+instruction sets, with no operator able to supply a second set, is a+do-nothing fallback with a type attached. Under the census rules (§6) it would+also have to ship the full four pieces plus a `CENSUS` registration for a+vocabulary whose only member is `"default"`.++**Recommendation:** ship A, and reframe the kanban task from "select a block"+to "the writer surface states no identity" plus a separate, later question+about whether operator text needs an agent-scoped variant at all.++---++## Defects noticed++1. **Dead option field.** `BuildInstructionsOpts.vault`+ (`src/mcp/instructions.ts:26-27`) is declared, documented as reserved, and+ never read in `buildInstructions` (`src/mcp/instructions.ts:105-139`). A+ test supplies it (`tests/mcp/mcp.test.ts:793`), which makes it look load-+ bearing. Delete it, or the next unit will "extend" it.++2. **Dead legacy-compat branch.** `buildInstructions` accepts+ `BuildInstructionsOpts | string` with a documented legacy string path+ (`src/mcp/instructions.ts:105-108`). All three call sites pass an object+ (`src/mcp/server.ts:313`, `scripts/measure-token-surface.ts:62-63`,+ `tests/mcp/mcp.test.ts:792`); grep finds no string-argument call anywhere+ outside `.claude/worktrees/`. The union widens the signature for nothing and+ forces two `typeof opts === "string"` reads per call.++3. **`ToolScope` members are copied by hand into four places, with nothing+ asserting they agree.** The type at `src/mcp/tool-contract.ts:19`; a literal+ `enum: ["full", "writer", "catalog"]` in the capabilities output schema at+ `src/mcp/tools.ts:378`; a re-declared inline union at `src/cli/main.ts:762`;+ and a hand-written list in the CLI error message at `src/cli/main.ts:629`.+ This is verbatim the drift class the census doc calls out — "a status list+ copied as a literal into a tool schema with nothing asserting the two agree"+ (`tests/core/architecture/verdict-vocabulary-census.test.ts:16-18`) — and+ `ToolScope` is out of the census population because it has neither a frozen+ object nor a guard. Promoting `ToolScope` to the four-piece idiom and+ registering it in `CENSUS` is a small, self-contained fix that any work on+ this axis would benefit from.++4. **HTTP mints a session id it never reads.** `src/mcp/http.ts:166` sets+ `mcp-session-id` on the `initialize` response; grep finds exactly one+ occurrence in the file. The header advertises per-session state that does+ not exist — which is also why per-agent instructions cannot ride the HTTP+ transport without real work.++5. **`isRuntimeTarget` guard takes `string | undefined`, not `unknown`**+ (`src/core/identity-reminder.ts:45`). It is out of the census population+ (no frozen object), so nothing fails — but it is the nearest thing to an+ existing selector and it diverges from the idiom the repo enforces+ elsewhere.++Not a defect, corrected for the record: codegraph reports `buildInstructions`+as having "no covering tests". That is a false negative — the catalog branch is+covered at `tests/mcp/catalog-scope.test.ts:104-113` and the unresolved-identity+branch at `tests/mcp/config-read-failure-server.test.ts:134-143`, both through+`handleInitialize` rather than by calling the function directly.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/recon/owner-scope-isolation.md b/docs/brainstorm/a-label-is-not-a-boundary/recon/owner-scope-isolation.mdnew file mode 100644index 00000000..1d5bb937--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/recon/owner-scope-isolation.md@@ -0,0 +1,615 @@+# Recon: owner-scope isolation and the `NON_CONTENT` bucket++Task under verification: kanban `t_b18551b1`, "Decide whether a document path+counts as content for owner-scope isolation." Branch+`feat/a-label-is-not-a-boundary`, repo at `package.json` version `1.48.0`.++Every claim below carries a `file:line` anchor that was opened and read.+Behavioural claims marked EMPIRICAL were reproduced against throwaway vaults+under `/tmp/.../scratchpad` with two owners (`agent-a`, `agent-b`) and+`integrity.owner_scope_delivery: fail`.++---++## What exists++### 1. The ownership rule, end to end++The rule is a single pure module, `src/core/graph/agent-scope.ts`:++- `pageOwner(meta)` (`agent-scope.ts:83`) reads one frontmatter field,+ `meta["owner"]`, through `ownerToken` (`agent-scope.ts:69`).+- `normalizeAgentScope(value)` (`agent-scope.ts:91`) NFC-trims-lowercases a+ requested scope; blank becomes `null` meaning "no filtering".+- `isOwnerVisible(owner, scope)` (`agent-scope.ts:104`) is the whole+ decision: `scope === null` → visible; `owner === null` → visible; else+ `owner === scope`.+- `OWNER_UNRESOLVED` (`agent-scope.ts:53`) is the fail-closed token for an+ ownership claim the parser cannot reduce to one string.++There is no owner column anywhere in the search database. `documents` is+declared at `src/core/search/schema.ts:103-113` with `id, path, title,+content_hash, mtime, size, created_at, updated_at, indexed_at` and nothing+else; `links` at `schema.ts:165-174` likewise. Ownership is therefore a+**filesystem-frontmatter** read at result time, never a SQL predicate.++The one place the rule meets the filesystem is+`isPathOwnerVisible(vault, path, scope, frontmatterCache)` at+`src/core/search/result-filters.ts:309-318`. It fails closed on an unreadable+file (`result-filters.ts:316`), which the comment at `result-filters.ts:302-307`+contrasts deliberately with visibility scoping's fail-open default.+`applyAgentScope` (`result-filters.ts:320-327`) is the ranked-search wrapper.++The parallel Brain-side walk is+`collectPreferencePages` at `src/core/brain/preferences-collect.ts:264-289`,+whose gate at `preferences-collect.ts:274-285` applies the same+`!unreadable && isOwnerVisible(pageOwner(meta), gate.scope)` test and counts+`hiddenByOwnerScope`.++Production consumers of `isOwnerVisible` are exactly four:+`src/core/brain/agent-source/query.ts:60`,+`src/core/brain/owner-scoped-facts.ts:42`,+`src/core/brain/preferences-collect.ts:280`,+`src/core/search/result-filters.ts:317`, plus the inline listing filter at+`src/mcp/tools.ts:263`.++### 2. The config key and its two regimes++`integrity.owner_scope_delivery` (`off | warn | fail`, default `off`) is+declared at `src/core/brain/policy/blocks/integrity.ts:28,67,113` and read by+`resolveOwnerScopeDelivery` at `src/core/brain/preferences-collect.ts:171-185`.+Only `fail` populates `enforcedScope`; `warn` populates `requestedScope` only.++The gate covers the **preference/delivery** surfaces+(`active.ts:266`, `context-pack.ts:427`, `pre-compress-pack.ts:202`,+`digest.ts:724`, `morning-brief.ts:81`, `anticipatory-cache.ts:197`,+`mcp/brain/context-tools.ts:397`). The **search-backed** surfaces are ungated+and honour only an explicit per-call `agent_scope` argument — the reasoning is+written into the matrix test at+`tests/mcp/agent-scope-matrix.test.ts:54-63`.++How a tool learns the scope: `coerceAgentScope(ctx, args,+fallbackToServerIdentity)` at `src/mcp/coerce.ts:115-123`. Gated surfaces pass+`true` and fall back to `ServerContext.agentName`; ungated ones pass `false`.+`ServerContext.agentName` is a **getter** resolved per access at+`src/mcp/server.ts:167-169`.++Exactly 13 of 110 tools declare `agent_scope` in their input schema+(EMPIRICAL, enumerated from `buildToolTable("full")`): `second_brain_query`,+`brain_context_pack`, `brain_pre_compress_pack`, `brain_anticipatory_context`,+`brain_query`, `brain_agent_query`, `brain_brief`, `brain_deep_synthesis`,+`brain_retrieval_plan`, `brain_search_by_source`, `brain_search`,+`brain_search_expand`, `brain_file_context`. `brain_context` is the 14th+scoped surface and takes no arguments at all.++### 3. The codebase's own stated doctrine on existence leaks++`src/core/brain/preferences-collect.ts:298-303` states it plainly: under+`fail` the surface says nothing at all, because+"a count would tell one agent that another agent's private memories exist -+the existence leak the search side avoids by making a hidden chunk+indistinguishable from an absent one."++The matrix test enforces the same doctrine for `brain_agent_query`'s roster at+`tests/mcp/agent-scope-matrix.test.ts:556-594`, and `second_brain_query`'s+`total_pages` at `agent-scope-matrix.test.ts:485-486` ("a count that still+included the hidden pages would leak their number").++**This settles question (1) on the codebase's own terms.** A bare count is+already ruled a leak here. A document path, or a Brain artifact id, is+strictly more information than a count. "A path is metadata" is not a position+this repository actually holds anywhere else; it is only a position the+`NON_CONTENT` label implies by omission.++### 4. The matrix test's exact structure++`tests/mcp/agent-scope-matrix.test.ts`, three buckets:++- `SCOPED_SURFACES` (`:66-81`), 14 entries, each `{name, source, gated}`.+- `UNSCOPED_CONTENT` (`:88-114`), 8 entries, each `{name, reason}`.+- `NON_CONTENT` (`:117-206`), 88 bare strings, header comment+ "Everything else: metadata, analytics, maintenance, writers, catalog."++Assertions, and only these:++```+test("the matrix classifies every tool exactly once", () => {+ const classified = [+ ...SCOPED_SURFACES.map((s) => s.name),+ ...UNSCOPED_CONTENT.map((s) => s.name),+ ...NON_CONTENT,+ ];+ expect(new Set(classified).size).toBe(classified.length);+ const actual = TOOLS.map((t) => t.name).toSorted();+ expect(classified.toSorted()).toEqual(actual);+}); // :299-311+```++```+test("the tool count is unchanged: an argument was added, never a tool", () => {+ expect(TOOLS.length).toBe(110);+}); // :313-315+```++```+test("every argument-scoped surface declares agent_scope in its input schema", () => {+ for (const surface of SCOPED_SURFACES) { ... }+}); // :317-329+```++`grep -n` over the file confirms the bucket identifiers appear at exactly+these lines: `SCOPED_SURFACES` at `:66, :301, :318`; `UNSCOPED_CONTENT` at+`:88, :302`; `NON_CONTENT` at `:117, :303`.++So:++- `SCOPED_SURFACES` carries a schema assertion (`:317-329`) plus fifteen+ behavioural tests (`:362-379` gated loop, `:447-615` ungated cases).+- `UNSCOPED_CONTENT` carries **only** the partition, plus a prose `reason`+ string that nothing reads.+- `NON_CONTENT` carries **only** the partition. Nothing checks the claim.++**What the test would catch:** a tool added to `buildToolTable` and not+classified; a tool removed and not de-classified; a name listed twice; a+change in tool count; an argument-scoped surface that stops declaring+`agent_scope`.++**What it would not catch:** any `NON_CONTENT` or `UNSCOPED_CONTENT` tool+returning owner-private data. The classification is an assertion about the+world made by a human in a string literal, and nothing in the file executes+it. The premise's characterisation of the enforcement gap is exactly right.++### 5. `listDangling` — signature, callers, reachability++`src/core/search/store/links.ts:170-192`:++```ts+export function listDangling(db: Database, limit: number): ReadonlyArray<DanglingLinkTarget>+```++`DanglingLinkTarget` (`links.ts:148-153`) is `{ target: string; sources:+ReadonlyArray<string> }` where `sources` are **vault-relative document+paths**. The query at `links.ts:173-176` is+`SELECT DISTINCT l.target_path AS target, d.path AS source FROM links l JOIN+documents d ON d.id = l.source_document_id WHERE l.target_path IS NOT NULL AND+<ladder> IS NULL ORDER BY target, source` — the premise's description is+accurate, and there is no owner predicate.++Caller chain, complete:++1. `Store.listDangling(limit)` — `src/core/search/store.ts:541-543`+2. `listDanglingTargets(vault, opts)` — `src/core/brain/notes/scaffold-stub.ts:142-192`,+ calls it at `:183`+3. Two production callers of that:+ - `src/cli/brain/verbs/scaffold-stub.ts:105`+ - `src/mcp/brain/lifecycle-file-tools.ts:265` (tool `brain_scaffold_stub`,+ `action: "list"`; response shape at `lifecycle-file-tools.ts:266-272`)+4. One test caller: `tests/core/search/dangling-links.test.ts:49`++An owner predicate is threadable through `ListDanglingOptions`+(`scaffold-stub.ts:128-131`) as an optional field without touching either+existing caller's call site. It cannot be SQL — `documents` has no owner+column — so the shape is a post-query filter over+`isPathOwnerVisible` (`result-filters.ts:309`) applied to `t.sources`, with+the target dropped when every source is filtered away (otherwise the surviving+`target` string is itself an existence oracle for the hidden note's outbound+links).++### 6. `buildBacklinkIndex` — signature, callers, reachability++`src/core/brain/backlinks.ts:98`:++```ts+export function buildBacklinkIndex(vault: string): BacklinkIndex+```++Nine production callers:++- `src/core/brain/digest.ts:517`+- `src/core/brain/explorer.ts:88`+- `src/core/brain/link-graph/concept-cluster.ts:68`+- `src/core/brain/link-graph/moc-audit.ts:106`+- `src/core/brain/doctor/link-checks.ts:77`+- `src/core/brain/stale-dependency.ts:476`+- `src/cli/brain/verbs/backlinks.ts:15`+- `src/mcp/resources.ts:369`+- `src/mcp/brain/query-tools.ts:314` (tool `brain_backlinks`)++An optional second parameter (`ownerScope?: string | null`) leaves all nine+call sites compiling unchanged; only the ones that must enforce would pass it.++---++## What does not exist++### A. Nothing writes `owner:`++This is the finding that decides whether a predicate is enforceable or a+fiction, and it goes against the task's implicit assumption.++`owner` reaches disk through exactly one path:+`writePreference` copies `input.owner?.trim()` at+`src/core/brain/preference.ts:446` and emits the frontmatter key at+`src/core/brain/preference.ts:553` — **only when the caller supplies it**.+`parsePreference` / `parseRetired` read it back at+`preference.ts:829` and `preference.ts:1018`.++Every non-test caller of `writePreference` was checked:++- `src/mcp/brain/feedback-tools.ts:231-251` (`brain_feedback`, force-confirmed+ path) passes `slug, topic, principle, created_at, unconfirmed_until, status,+ evidenced_by, confirmed_at, confidence_value, scope` — **no `owner`**.+- `src/cli/brain/verbs/feedback.ts:139` — same shape, no `owner`.+- `src/core/brain/derived-fact.ts:135`, `src/core/brain/merge.ts:211`,+ `src/core/brain/preference-txn.ts:237` — no `owner`.++`src/core/brain/signal.ts` contains no occurrence of `owner` at all; a signal+records `agent:`, which is provenance ("who reported this"), not ownership+("who may read this"). Nothing maps `agent` → `owner`.++A grep of `src/` for owner assignment yields nine hits, all of them reads or+type declarations (`src/core/scope-key.ts:57,74`;+`src/core/brain/preference.ts:446,829,1018`;+`src/core/brain/agent-source/vault-provider.ts:104,153`;+two argument descriptions in `src/mcp/brain/query-tools.ts:633` and+`src/mcp/brain/ingest-tools.ts:384`).++**Consequence.** On a vault written entirely through the shipped MCP and CLI+surfaces by two agents, every page is ownerless, `pageOwner` returns `null`+everywhere, `isOwnerVisible` returns `true` for every (page, scope) pair, and+the isolation boundary filters nothing. The boundary is operator-authored+today: it exists only if a human hand-writes `owner:` into frontmatter, or an+external tool calls `writePreference` with an `owner` field. Files that+predate the field, and files that carry none, are shared — by design+(`agent-scope.ts:9-11`), and that design is currently the only case that ever+occurs in practice.++### B. No test asserts anything about a `NON_CONTENT` tool's payload++Established in §4 above. There is no per-surface assertion behind the label.++### C. No enumeration of the `vault_path` redaction contract++`vaultPathField(ctx)` at `src/mcp/tools.ts:109-119` is the declared way to+emit `vault_path`, rendering `vault://<hex>` unless `expose_host_paths` is+set, "since MCP responses land in model context" (`tools.ts:94-99`). It has+**three** call sites: `tools.ts:208`, `tools.ts:277`, `tools.ts:319`.++`grep -rn "vault_path: ctx.vault" src/mcp/` returns **41** sites across ten+files (`landscape-tools.ts`, `pack-tools.ts`, `recall-tools.ts`,+`generation-tools.ts`, `context-tools.ts`, `analytics-tools.ts`,+`query-tools.ts`, `review-tools.ts`, `brief-tools.ts`, `knowledge-tools.ts`).+Each emits the raw absolute host path. Confirmed EMPIRICAL: the+`brain_unlinked_mentions` response begins+`{"vault_path":"/tmp/sweep2-vault-cZQz8h",...}` and `brain_moc_audit` and+`brain_stale_scan` do the same.++No test enumerates the surfaces that must use the helper —+`tests/core/config.test.ts:519-533` and+`tests/core/config.installation-secret.test.ts:97-110` test the helper in+isolation only. This is the identical failure shape the matrix test was+written to fix (`agent-scope-matrix.test.ts:5-15`: "nothing enumerated the+surfaces, so each new one silently opted out"), reproduced in a second+dimension and currently at 41 opt-outs against 3 compliances.++---++## Corrections to the premise++### C1. `buildBacklinkIndex` is not "a full scan of `Brain/`", and `refs[].source` is not a document path++`buildBacklinkIndex` walks five specific directories —+`dirs.preferences`, `dirs.retired`, `dirs.inbox`, `dirs.processed`,+`dirs.log` (`backlinks.ts:143-147`) — not `Brain/` at large. `notes/`, the+whole user-note lane, is invisible to it.++`BacklinkRef.source` (`backlinks.ts:46-47`) is documented as "Source id+(basename without `.md`, e.g. `pref-foo`, `ret-bar`,+`sig-2026-05-14-baz`)" and is produced by `name.slice(0, -".md".length)` at+`backlinks.ts:177` and `:246`. `brain_backlinks` returns exactly that field+(`src/mcp/brain/query-tools.ts:320`).++The correction sharpens rather than weakens the concern: preferences and+retired artifacts are *precisely* the objects that can carry `owner:`+(`preference.ts:553`, `preference.ts:1018`), so a Brain artifact id is a+tighter binding to an owner than an arbitrary vault path is.++EMPIRICAL: with `pref-secret-of-a` (owner `agent-a`) and `ret-secret-b`+(owner `agent-a`) both referencing the shared `pref-shared-pref`,+`brain_backlinks {id: "pref-shared-pref"}` called as `agent-b` returned:++```+{"id":"pref-shared-pref","count":3,"refs":[+ {"source":"pref-secret-of-a","source_kind":"preference","field":"supersedes"},+ {"source":"ret-secret-b","source_kind":"retired","field":"body"},+ {"source":"sig-2026-05-01-secret-sig","source_kind":"signal","field":"source"}]}+```++### C2. `brain_hygiene` does not reach `listDangling`, and its leak is a different one++`brain_hygiene`'s `link_integrity` block comes from `measureFromIndex`+(`src/mcp/brain/hygiene-tools.ts:111-144`, importing from+`src/core/search/link-ratchet.ts`), which returns **counts only**+(`dangling`, `links`, `documents`). EMPIRICAL: `{"link_integrity":+{"definition":"ladder:links-unresolved-after-read-resolution@2","measured":true,+"dangling":4,"links":5,"documents":4}}`. No paths.++The real `brain_hygiene` leak is `findings[].targets`, rendered by+`findingView` at `hygiene-tools.ts:79-91`. EMPIRICAL, as `agent-b`:++```+"findings":[{"id":"usefulness:3256a37e2407","detector":"usefulness",+ "title":"Preference pref-secret-of-a has no recall or applied evidence since creation",+ "targets":["pref-secret-of-a"], ...}]+```++That is an artifact id plus a prose title naming it, not a path from+`listDangling`.++### C3. `brain_unlinked_mentions` returns bodies, not just identity — it belongs in the content bucket, not a new identity bucket++`MentionRef.contextSnippet` (`src/core/brain/link-graph/unlinked-mentions.ts:35-36`)+is "Line content with the match in situ (single line, untrimmed)", pushed+verbatim at `unlinked-mentions.ts:194`, and surfaced as `context` by the tool+at `src/mcp/brain/query-tools.ts:425`.++EMPIRICAL, as `agent-b`:++```+"mentions":[+ {"source":"pref-secret-of-a","line":1,"term":"Shared Pref",+ "context":"See [[pref-shared-pref]]. Also Shared Pref secretmarkerzz here."},+ {"source":"ret-secret-b","line":1,"term":"Shared Pref",+ "context":"See [[pref-shared-pref]] and Shared Pref secretmarkerzz."}]+```++`secretmarkerzz` appears only inside `agent-a`-owned artifacts. This is body+prose crossing the boundary. Any three-way split that files this tool under+"returns document identity but no bodies" would file it wrong.++### C4. `brain_moc_audit`'s leak is an existence oracle, not an enumeration++`auditMoc` (`src/core/brain/link-graph/moc-audit.ts:106-157`) only inspects+targets the caller-named hub already links to (`moc-audit.ts:80-84`), so it+cannot enumerate anything the hub's body does not already name. What it adds+is a verdict on each: `locateArtifact` succeeding puts the id in+`wellCovered`/`fragile` with a `bodyChars` measurement+(`moc-audit.ts:113-128`); failing puts it in `candidateMissing`+(`moc-audit.ts:115`).++EMPIRICAL, hub `pref-hub` linking to two `agent-a`-owned members, three+ownerless members and one absent target, called as `agent-b`:++```+"fragile":[{"id":"pref-secret-a1","backlinkCount":0,"bodyChars":38},+ {"id":"pref-secret-a2","backlinkCount":0,"bodyChars":38}, ...]+"candidate_missing":[{"id":"pref-missing-secretmarkerzz","referenceCount":1}]+```++Exists-vs-absent is decided, and `bodyChars` sizes the private body. That is+the same class of leak the codebase already refuses at+`preferences-collect.ts:298-303` and `agent-scope-matrix.test.ts:556-594`.++### C5. `brain_scaffold_stub` is the only one of the five that leaks a real vault document path — and the premise's fix location for it is wrong++EMPIRICAL, as `agent-b`, against a forced full index:++```+{"action":"list","state":"measured","targets":[+ {"target":"Secretmarkerzz Page","sources":["notes/shared.md"]},+ {"target":"missing-target-of-a","sources":["notes/secret-a.md"]},+ {"target":"missing-target-shared","sources":["notes/shared.md"]},+ {"target":"pref-missing-x","sources":["Brain/preferences/pref-shared-pref.md"]}]}+```++`notes/secret-a.md` carries `owner: agent-a`. Its path crosses. Note also that+`target: "Secretmarkerzz Page"` leaks the private page's **title** through a+link written from a shared note — a second channel a `sources` filter alone+would not close.++The premise says the predicate "belongs in both `listDangling` and+`buildBacklinkIndex` in the same change". `listDangling` is a SQL function+over a schema with no owner column (`schema.ts:103-113`); a predicate cannot+go there. It belongs one layer up, in `listDanglingTargets`+(`scaffold-stub.ts:142`), where the vault root is in hand and+`isPathOwnerVisible` can be called.++Precondition worth noting: `brain_scaffold_stub action=list` refuses unless+the index records a completed full pass (`scaffold-stub.ts:172-180`). On an+incrementally-indexed vault it returns `state: "partial_resolution"` and no+targets at all — EMPIRICAL, reproduced before adding `{ force: true }`.++### C6. The bucket contains **nine** identity-leaking tools, not five — and four of the nine leak with a bare no-argument call++A sweep invoked every `NON_CONTENT` tool with `{}` as `agent-b` against a+two-owner vault under `owner_scope_delivery: fail`, then re-ran the+argument-requiring ones with plausible arguments. Markers were strings present+only inside `agent-a`-owned artifacts.++Leaks confirmed EMPIRICAL, with what crosses:++| Tool | Call | What crosses |+|---|---|---|+| `brain_backlinks` | `{id: <shared id>}` | `refs[].source` — private artifact ids |+| `brain_unlinked_mentions` | `{id: <shared id>}` | `mentions[].source` **and** `mentions[].context` (body prose) |+| `brain_moc_audit` | `{id: <shared hub>}` | `fragile[].id`, `bodyChars`, exists-vs-missing verdict |+| `brain_hygiene` | `{mode: "scan"}` | `findings[].targets` ids + titles naming them |+| `brain_scaffold_stub` | `{action: "list"}` | `targets[].sources` vault paths + private page titles |+| `brain_doctor` | `{}` | `errors[].path` — `Brain/preferences/pref-secret-of-a.md`, `Brain/retired/ret-secret-b.md`, `Brain/inbox/sig-…-secret-sig.md` |+| `brain_claims` | `{}` | `claims[].path`, `.topic`, **and `.principle` — the full rule text** |+| `brain_idea_discovery` | `{}` | `source_artifacts[]` paths plus a `reason` sentence naming the path |+| `brain_stale_scan` | `{}` | `stale_preferences[].{prefId,topic,path}`, `stale_signals[].path` |+| `brain_event_trace` | `{}` | `events[].body.path` from log payloads |++That is **ten** surfaces (the five named plus `brain_doctor`, `brain_claims`,+`brain_idea_discovery`, `brain_stale_scan`, `brain_event_trace`). Two of the+ten — `brain_unlinked_mentions` and `brain_claims` — return bodies, so the+"identity but no bodies" framing does not partition this set either.++`brain_claims {}` is the sharpest counter-example to the whole "metadata"+label:++```+"claims":[{"id":"pref-secret-of-a","path":"Brain/preferences/pref-secret-of-a.md",+ "topic":"secret-of-a","principle":"secretmarkerzz principle", ...}]+```++Verified clean under the same sweep (no marker in the payload):+`second_brain_status`, `brain_dream`, `brain_intent_review`, `brain_retention`,+`brain_review_candidates`, `brain_pinned_context`, `brain_agent_diff`,+`brain_sources`, `brain_health`, `brain_status`, `brain_codegraph_report`,+`brain_foresight`, `brain_knowledge_gaps`, `brain_mcp_landscape`,+`vault_health`, `brain_watchdog`, `list_skills`, `tool_hydrate`,+`brain_audit`, `brain_analytics` (`timeline`, `attention_flows`, `dedup`),+`brain_bridges`, `brain_clusters`, `brain_truth`, `brain_dead_ends`,+`brain_tiers`, `brain_entity`, `schema_inspect view=graph`,+`brain_context_receipts`, `brain_decision`, `brain_tension`,+`brain_generation_reports`, `brain_procedural_memory`, `brain_skill_proposals`,+`brain_recurrence`, `brain_intention`, `brain_obligation`, `brain_trigger`.++"Clean" here means "clean on this fixture". `brain_stale_scan` read clean in+the first sweep and leaked in the second — the only difference was adding+`tags: []` so the preference parsed. Several of the clean results are clean+because the fixture produced no rows, not because the surface is structurally+safe. A per-surface assertion is the only thing that can distinguish the two,+which is the same point question (2) makes.++### C7. The premise's framing of question (1) is the wrong question first++"Does 'a path is metadata' survive a vault with more than one writing agent?"+presumes such a vault can exist. §A establishes it cannot arise through the+shipped writers: no write path sets `owner:`, so a two-agent vault is a vault+of ownerless, shared pages and every tool above is correctly labelled today.++The honest statement is: the label is not wrong, it is **unconditioned**. It+is true on the only vaults the product produces and false on the vaults the+`owner:` field was designed for. Both halves need saying, and a fix that+filters paths without also making ownership assignable ships a boundary that+still nothing ever crosses.++---++## Where a fix belongs++Smallest native placements, in dependency order. Nothing here is a new+subsystem; each is an existing seam.++1. **`isPathOwnerVisible` / `isOwnerVisible` stay the only rule.**+ `src/core/search/result-filters.ts:309` and+ `src/core/graph/agent-scope.ts:104`. Any new filter calls one of these. A+ second ownership comparison written inline would be the parallel idiom the+ repo forbids.++2. **Ownership must become assignable before it can be enforced.**+ The native seam is `WritePreferenceInput.owner`+ (`src/core/brain/preference.ts:142`), already plumbed to disk at+ `preference.ts:553`. What is missing is a caller. `brain_feedback`+ (`src/mcp/brain/feedback-tools.ts:231`) already resolves an agent identity+ for the signal's `agent:` field; whether `owner` should default from it, be+ an explicit argument, or be operator-gated is a design decision this recon+ does not make — but it is one decision in one file, and without it items 3+ and 4 are unreachable code.++3. **Path-returning surfaces: filter at the aggregator, not in SQL.**+ - `listDanglingTargets` (`src/core/brain/notes/scaffold-stub.ts:142`) —+ add an optional owner scope to `ListDanglingOptions`+ (`scaffold-stub.ts:128`), filter `t.sources` through+ `isPathOwnerVisible`, and **drop the whole target** when no source+ survives, so `target` cannot act as an oracle for a hidden note's links.+ `listDangling` itself (`links.ts:170`) stays untouched.+ - `buildBacklinkIndex` (`src/core/brain/backlinks.ts:98`) — optional second+ parameter; resolve each collected `source` id back to its file (the+ collectors already hold `full` at `backlinks.ts:176` and `:244`) and test+ `pageOwner` there. All nine call sites keep compiling.++4. **The enforcement mechanism, which is the actual deliverable.**+ `tests/mcp/agent-scope-matrix.test.ts` currently has one mechanism (the+ exactly-once partition) and it protects nothing in two of three buckets.+ The native fix is not a fourth bucket label — that repeats the defect the+ file's own header describes — but a **generic per-surface probe**: build+ one two-owner fixture vault, call every tool in the non-scoped buckets, and+ assert the payload contains no marker unique to the other owner's+ artifacts. The sweep script that produced §C6 is a working prototype of+ exactly that; each entry then needs a call recipe (arguments) rather than a+ bare name, which turns `NON_CONTENT: string[]` into+ `NON_CONTENT: {name, args, reason}[]` and makes an unclassifiable tool fail+ loudly.++ A bucket without a probe behind it is a label, and the task title is right+ about what that is worth.++5. **Errors stay explicit.** `listDanglingTargets` already models this well:+ `refusal(state, detail)` at `scaffold-stub.ts:119-126` returns a named+ state and a `nextCommand` rather than an empty list. A filtered-away result+ must not become an indistinguishable empty list where the surface already+ has a channel to say why — but note the counter-pressure from+ `preferences-collect.ts:298-303`: under `fail`, saying *how many* were+ withheld is itself the leak. The resolution the codebase already uses is+ "identical to absent", and a new filter should match it rather than invent+ a third convention.++---++## Defects noticed++**D1. 41 MCP responses emit the raw absolute host path as `vault_path`,+against a contract stated in the codebase.**+Contract at `src/mcp/tools.ts:94-119`; honoured at `tools.ts:208, 277, 319`;+violated at 41 sites across `src/mcp/brain/{landscape,pack,recall,generation,+context,analytics,query,review,brief,knowledge}-tools.ts`. Confirmed EMPIRICAL+in `brain_unlinked_mentions` (`query-tools.ts:419`), `brain_moc_audit`+(`knowledge-tools.ts:324`) and `brain_stale_scan`. No test enumerates the+surfaces. This is in scope for a release that fixes what it finds, and it is+mechanically the same defect as the one this task is about: a rule with no+enumeration behind it.++**D2. `brain_scaffold_stub action=list` leaks a private page's *title*, not+only its path.** `targets[].target` carries the link spelling verbatim+(`links.ts:150`, `scaffold-stub.ts` response at+`lifecycle-file-tools.ts:269`). A shared note writing `[[Secretmarkerzz Page]]`+against an owner-private target publishes that target's title to every caller.+Filtering `sources` alone does not close it.++**D3. `brain_moc_audit` counts backlinks from artifacts the caller may not+see.** `inboundFromOthers` at `moc-audit.ts:123` folds every ref in the+unfiltered index. Even with member ids filtered, the count would remain a+population estimate of the private set — the exact failure the+`brain_agent_query` roster test at `agent-scope-matrix.test.ts:556-594` was+written to prevent, in a surface that has no such test.++**D4. `buildBacklinkIndex` silently drops any preference whose frontmatter+uses the un-prefixed Group C shape.** `normalizeDerivedKeys`+(`preference.ts:725-741`) throws on a bare `status:`, and the collector's+`catch { continue; }` at `backlinks.ts:193-195` swallows it. Reproduced+accidentally during this recon: a fixture with `status: confirmed` produced an+index missing every preference-sourced ref, with no diagnostic. The module+header at `backlinks.ts:24-25` declares this deliberate ("`brain_doctor` is the+surface that flags malformed artifacts"), so it is defensible — but the+consequence is that `brain_backlinks` returns a confidently wrong `count: 0`+on a legacy vault, and the caller has no way to tell that from a genuine zero.+The same shape `listDanglingTargets` refuses to ship+(`scaffold-stub.ts:119-126`) is shipped here.++**D5. `brain_labels {operation: "show", id: ...}` rejects `id` with+"path must be a vault-relative string".** EMPIRICAL. Either the argument name+in the error is wrong or the schema advertises an argument the handler does+not accept; worth one look at `src/mcp/brain/admin-tools.ts:402`.++**D6. `schema_inspect view=lint|orphans` raises a hard parse error carrying an+absolute host path.** EMPIRICAL: `preference missing field: retired_at+(/tmp/sweep2-vault-cZQz8h/Brain/retired/ret-secret-b.md)`. A *lint* view that+cannot report on a malformed artifact without dying on it inverts its own+purpose, and the message leaks the host path D1 is about.++---++## Reproduction++Scripts under+`/tmp/claude-1001/-srv-projects-open-second-brain/f6f02ff9-6785-4ac9-8e4c-95f95be29cb5/scratchpad/`:+`probe.ts` (five named tools), `probe2.ts` (backlinks / mentions / hygiene at+the core-function level), `sweep.ts` (all `NON_CONTENT` tools, no arguments),+`sweep2.ts` (argument-requiring tools), `moc.ts` (MOC threshold fixture). Run+with `env HOME=<empty-dir> bun <script>` per the clean-HOME convention. The+index must be built with `indexVault(config, { force: true })` or+`brain_scaffold_stub` refuses (`scaffold-stub.ts:174-180`).diff --git a/docs/brainstorm/a-label-is-not-a-boundary/recon/retrieval-confidence-floor.md b/docs/brainstorm/a-label-is-not-a-boundary/recon/retrieval-confidence-floor.mdnew file mode 100644index 00000000..e8323501--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/recon/retrieval-confidence-floor.md@@ -0,0 +1,374 @@+# Recon: the recall-inject confidence floor (t_eb94ac35)++Read-only reconnaissance against `feat/a-label-is-not-a-boundary` @ `280469d2`+(v1.48.0). Every anchor below was read; paths are repo-relative. Every number+below was produced by running the shipped `indexVault` + `search` ++`decideRecallInject` over disposable vaults, or by calling `rankResults`+directly — the probe scripts are throwaway and live outside the repo.++Headline, in one line: **the premise is right about the outcome and wrong+about three of its four mechanisms, and the floor is not the only knob the+pinned top score neutralises — it is the least consequential of four.**++---++## What exists++### 1. The scoring path, exactly++`rankResults` (`src/core/search/ranker.ts:392`) computes one composite per+candidate at `:623-633`:++```+score = clamp01(+ weighted * tierMul * trendMul+ + linkBoost + recency + entityBoost + activationBoost+ + coAccessBoost + reuseBoost + (temporalBoost ?? 0) + sessionFocus+)+```++**The relevance term (`weighted`, `:564-568`).** Two mutually exclusive modes:++- `linear` (the default, `src/core/search/index.ts:171`):+ `keywordWeight * kwMul * kwNorm + semanticWeight * semMul * cos`.+- `rrf`: `weighted = rrf` — the fused value **replaces** the term, and the+ configured lane weights are deliberately not applied (`:558-563`,+ `src/core/search/fusion.ts:10-27`).++**The keyword lane is min-max normalised within the candidate set**+(`normalizeBm25`, `:203-219`). The best BM25 hit gets exactly `1`, the worst+exactly `0`. When every hit ties — **including the single-hit case** — every+hit gets `1` (`:211-213`). The raw `bm25` value never leaves this function.++**The semantic lane is NOT normalised.** `semanticFromDistance`+(`:222-225`) maps L2-on-unit-vectors to `1 - d²/2`, clamped — an **absolute**+cosine similarity, pool-independent. This asymmetry is the whole story of+this task (see §5, §6).++**The RRF lane is also min-max normalised** to `[0,1]`+(`src/core/search/fusion.ts:125-138`), so `rrf` mode pins the top at `1.0`,+not at a weight.++**Constants and where they live:**++| Layer | Cap / value | Anchor |+| --- | --- | --- |+| `keywordWeight` | **0.6** (default) | `src/core/search/index.ts:154` |+| `semanticWeight` | 0.4 (default) | `src/core/search/index.ts:155` |+| `kw + sem <= 1` invariant | validated | `src/core/search/index.ts:324-328` |+| link + tag boost | 0.05 (0.03 + 0.02) | `ranker.ts:118-122` |+| entity boost | 0.04 | `ranker.ts:124` |+| activation boost | 0.04 | `ranker.ts:126` |+| co-access boost | 0.03 | `ranker.ts:128` |+| observed-reuse boost | 0.06 | `ranker.ts:130` |+| temporal-intent boost | 0.06 | `ranker.ts:138` |+| recency amplitude | 0.05 | `src/core/search/recency.ts:39-43` |+| tier multiplier | core 1.4 / supporting 1.0 / peripheral 0.6 | `src/core/brain/page-meta/tier.ts:45-49` |+| trend multiplier | strengthening 1.05 / weakening 0.93 / stale 0.85 | `ranker.ts:141-145` |+| supersede fade | 0.5 | `ranker.ts:156` |+| intent `keywordMul` | 0.9 … 1.3 | `src/core/search/query-plan.ts:52-67` |+| learned weight bounds | 0.8 … 1.2 | `src/core/search/feedback.ts:29-31` |++Post-ranker stages that still move a score: `applyRankAdjusters`+(`src/core/search/rank-adjust.ts:90`) multiplies and re-clamps (`:135`),+driven by `supersedeFadeAdjuster` (`src/core/search/result-filters.ts:219`)+and `trustGateAdjuster` — both off by default+(`src/core/search/index.ts:755-769`). Traversal, temporal bridge, MMR,+relevance rerank and the cross-encoder re-order or add rows+(`src/core/search/pipeline/assemble.ts:274-310`,+`pipeline/post-rank.ts:58-113`).++### 2. The hand-off: the number thresholded IS the number the ranker produced++`decideRecallInject` (`src/core/brain/recall-inject.ts:155`) sorts the+retriever's candidates and compares `ranked[0].score` to+`RECALL_INJECT_CONFIDENCE_FLOOR = 0.35` (`:43`, `:189-192`).++The chain, unmodified end to end:++- `defaultRecallRetriever` (`:361-381`) maps `result.score` straight onto+ `RecallCandidate.score` — no rescaling.+- `searchAcrossVaults` (`src/core/search/cross-vault.ts:170`) only appends an+ `origin:` reason; the score is copied (`:46-52`). The module states the+ merge is score-as-is at `:20-22`.+- `search` (`src/core/search/search.ts:285-295`) slices and decorates.++So the floor is applied to the ranker's `clamp01` output. Confirmed by+measurement: every `topScore` reported by the decision equals the `score` on+`outcome.results[0]` to the digit.++---++## Measurements++Method: `indexVault` + `search` over disposable vaults with the shipped+defaults (`tests/helpers/search-fixtures.ts:129-184` reproduces+`resolveSearchConfig`'s defaults exactly, including `keywordWeight: 0.6`),+`limit: 4`, then `decideRecallInject` with a retriever wrapping the same+`search`. File mtimes were pushed 400 days back to zero the recency layer+unless stated.++### The default path: the top score is a constant++| Case | Top score | Decision |+| --- | --- | --- |+| Single weak keyword hit ("kubernetes" mentioned once in a gardening note) | **0.6000** | `inject` |+| 12 notes, wide BM25 spread, worst match still top of pool | **0.6000** | `inject` |+| Every note tagged `tier: peripheral` | **0.6000** | `inject` |+| `tier: peripheral` + `freshness_trend: stale` | **0.6000** | `inject` |+| `freshness_trend: stale` (note not under `Brain/preferences/`) | **0.6000** | `inject` |+| `fusionMode: rrf` | **1.0000** | `inject` |+| Fresh (today) file, keyword hit | **0.6500** | `inject` |+| No lexical match at all | — | `abstain / no_matches` |++The observable band of the *top* score in a default, keyword-only vault is+**[0.60, 0.65]** — `keywordWeight` plus the recency amplitude. The floor at+0.35 sits entirely below it. Every additive boost only pushes it further up.++### The floor CAN fire. Four exact configurations++| # | Configuration | Top score | Decision |+| --- | --- | --- | --- |+| H | `search_supersede_fade_enabled: true`, every matching candidate carries `superseded_by` | **0.3000** | `abstain / below_floor` |+| K | Strongest match carries `visibility: private`, dropped by the default visibility scope; the surviving candidate is the pool's BM25 minimum | **0.0000** | `abstain / below_floor` |+| J | `search_keyword_weight` set to **0.34** or below (0.35 is exactly at the boundary and still injects) | 0.3400 | `abstain / below_floor` |+| M/N | Semantic-only candidate (no keyword hit): distance 1.414 → **0.0000**; distance 0.8 → **0.2720** | 0.0000 / 0.2720 | below floor |++Case **K needs no non-default flag**. It is the general mechanism, and it is+worse than the premise's framing: because `normalizeBm25` pins the pool+*minimum* at 0, any downstream stage that removes the pool maximum+(visibility scope, owner scope, status filter, exact-state barrier,+structured exclusion, duplicate merge) leaves a survivor whose score is a+statement about *which rows were filtered*, not about how well anything+matched. Verified directly on the pure ranker: a two-hit pool scores+`0.6000 / 0.0000` regardless of how good the loser's BM25 actually was+(`bm25 = -0.0001` vs `-10` produced the same `0.0000`).++### Absolute ceilings, for calibration++- Keyword-only vault (embeddings off — the common default): relevance term+ maxes at `0.6`. The 0.4 `semanticWeight` is simply unspent.+- Embeddings on: a hybrid hit can reach `0.6 + 0.4 = 1.0` before boosts.+- `rrf` mode: relevance term is `1.0` at the top by construction.++The same `0.35` therefore means three different things depending on+configuration, and in none of them does it mean "the match was weak".++---++## Corrections to the premise++1. **The keyword weight is 0.6, not 0.65.** `src/core/search/index.ts:154`.+ The 0.65 figure appears in the task body *and in shipped source* —+ `src/core/bench/failure-modes.ts:38-44` states "0.65 by default" in a+ doc comment that the conformance suite's caveat rests on. That comment is+ wrong on the number and should be corrected whatever else is decided.++2. **`below_floor` is NOT unreachable.** It fires today, under default+ config, whenever a scope/visibility filter removes the pool maximum+ (case K, measured at `0.0000`), and under two documented opt-in knobs+ (supersede fade, keyword weight ≤ 0.34). "Unreachable" is the wrong+ diagnosis; **"fires for reasons unrelated to match quality"** is the+ right one. The `false_fire` term in the conformance suite is therefore+ not merely inert — when it does bite, it is measuring the filter stack.++3. **The tier multiplier claim is right, but for a different reason than+ stated.** `tierMul` *does* reach the score arithmetically+ (`ranker.ts:572-573`, `:624`). It never fires because+ **`tierByDoc` has no producer anywhere in `src/`** — `rankCandidates`+ (`src/core/search/pipeline/assemble.ts:390-441`) does not pass it, and+ grep finds the field only in `ranker.ts:50`, `ranker.ts:572` and+ `tests/core/search/ranker-tier.test.ts`. Every shipped search reports+ `breakdown.tier === 1`; my probe confirmed `tier=1` on notes explicitly+ stamped `tier: peripheral`. This is a separate defect (see §Defects).++4. **The supersede claim is wrong.** "Only affects rank 2+" — no. The fade+ is a multiply in kernel 1 applied per candidate+ (`result-filters.ts:219-229`), and when the *only* matching candidates+ are superseded, the top score is `0.6 * 0.5 = 0.3000` and `below_floor`+ fires. Measured.++5. **`freshness_trend` is narrower than it looks.** The multiplier only+ applies to paths under `Brain/preferences/`+ (`src/core/search/pipeline/candidate-signals.ts:25`, `:223`). A+ `stale`-stamped preference page tops out at `0.6 * 0.85 = 0.5100`,+ measured — still above the floor.++6. **`rrf` mode makes the top score *higher*, not lower** (1.0), because RRF+ is min-max normalised too and bypasses the lane weights entirely. Any+ design that reasons about "the top score" must account for two different+ ceilings.++---++## The floor is the smallest of four knobs the pinned score neutralises++This is the part the task body does not cover, and it is what makes the+decision release-wide rather than local. Complete list of everything that+compares a normalised result score to a constant:++| Consumer | Constant | Anchor | Effect of the pinned 0.60 |+| --- | --- | --- | --- |+| `decideRecallInject` confidence floor | 0.35 | `src/core/brain/recall-inject.ts:43,190` | Never fires on a clean pool; fires only when a filter removed the pool max |+| **`assessRecallAdequacy`** `sufficient` | **0.6** | `src/core/brain/recall-adequacy.ts:45-49,124` | `0.6 >= 0.6` is **exactly true**: every keyword hit is graded `sufficient / proceed`. `weak` (0.3) and `insufficient` are unreachable on the default path. Knife-edge: lowering `search_keyword_weight` to 0.59 flips *every* recall to `re_recall` |+| — its callers | | `src/mcp/search-tools.ts:1156` (`brain_recall_gate`), `src/mcp/brain/pack-tools.ts:102` (`brain_context_pack`) | Both surfaces inherit the collapse |+| — its config keys | | `src/core/config.ts:850-868` | `recall_adequacy_sufficient` / `_weak` / `_min_results` are operator-facing and equally affected |+| **Gap-loop auto-close floor** | **0.5** | `src/core/brain/gaps/gap-loop.ts:47,402,415` | Always cleared by any keyword match — a gap task auto-closes on a hit of arbitrary quality |+| Cross-vault chain stop | 0.8 | `src/core/search/cross-vault.ts:200`; default `index.ts:175`, off by default `index.ts:801-805` | Unreachable in `linear` mode (band is [0.60,0.65]); **always** triggers in `rrf` mode (1.0). The knob means opposite things per fusion mode |+| Caller relevance floor (`opts.threshold`) | caller-supplied | `src/core/search/pipeline/assemble.ts:216,296-300` | Any value in (0, 0.6] is a no-op on the top row; a value above 0.65 empties the window |+| Cross-encoder `minScore` | 0 default | `src/core/search/rerank/index.ts:83-84`; `index.ts:180` | Compares *cross-encoder* scores, not fused ones — unaffected |+| Supersede fade multiplier | 0.5 | `ranker.ts:156`, `result-filters.ts:226` | The one knob that moves the top score in a measurable way today |+| Relative-only readers (no constant) | — | `mmr.ts:90`, `traversal.ts:127`, `temporal-bridge.ts:99`, `enrich.ts:159-161`, `deep-synthesis.ts:377-380`, `recall-hint.ts:60`, `rerank-fit-check.ts:178`, `mcp/search-tools.ts:998,1030,1574` | Unaffected — they only order or display |++Blast-radius reading of that table: **changing the normalisation changes four+absolute thresholds at once**, two of which (`recall_adequacy_*`, the gap-loop+floor) currently sit on the *wrong side* of the pinned value and would flip+behaviour, not merely become live. A scoring change is release-wide.++---++## What a score would have to be, and what already exists++For an absolute floor to be meaningful the number must vary with *match+quality* and not with *pool composition*. Two such signals are computed in+this tree today.++1. **`idfWeightedCoverage`** — `src/core/search/coverage.ts:162-187`. Share+ of the query's significant terms, IDF-weighted, that the retrieved+ material actually covers; `[0,1]`, pool-independent, language-agnostic by+ construction (`:24-32`), with a rare-term classification alongside+ (`:71-76`). **It is computed only in evidence-pack mode**+ (`src/core/search/evidence-verification.ts:59,83`,+ `src/core/search/evidence-pack.ts:159`) and is discarded on every ordinary+ search. This is the strongest candidate for an honest floor.++2. **The raw `bm25` value** — `src/core/search/store/keyword.ts:12-24`,+ `bm25(chunk_fts, 1.0, 0.3)`. Carried on `KeywordHit` into `rankResults`,+ consumed by `normalizeBm25` (`ranker.ts:208`) and by the RRF sort+ (`ranker.ts:423`), then **discarded** — it reaches no+ `BrainSearchResult` field, no `ScoreBreakdown`, no reason string. It is a+ corpus-relative magnitude, so it is not directly a `[0,1]` quality, but it+ is the only raw lexical-fit number the pipeline has and it is currently+ thrown away.++3. **Cosine similarity** — already absolute (`ranker.ts:222-225`), already on+ `BrainSearchResult.semanticScore`. Nothing to recover.++---++## The vector lane behaves differently, and the default has no vector lane++- **Keyword lane:** min-max normalised → top pinned at `1`, bottom pinned at+ `0`, both independent of match quality (`ranker.ts:203-219`).+- **Vector lane:** absolute cosine, no normalisation (`ranker.ts:409-414`).+ A genuinely poor semantic neighbour scores near zero — measured `0.0000`+ at distance √2 and `0.2720` at distance 0.8. **The floor already works+ correctly against this lane.**+- **Embeddings absent (the shipped default,+ `tests/helpers/search-fixtures.ts:104-116` mirrors+ `resolveSearchConfig`):** `semanticEnabled` is false+ (`search.ts:258`, `ranker.ts:394`), `semanticScore` is forced to 0+ (`ranker.ts:659`), the semantic lane never runs+ (`pipeline/semantic-lane.ts:47`), and the relevance term reduces to the+ keyword weight alone. So the floor's only *working* input is the one the+ default install does not have.++That is the cleanest statement of the defect: **the confidence floor is+correct for the lane that is usually absent and meaningless for the lane that+is always present.**++---++## Candidate fixes, with measured blast radius++### A. Express the floor against IDF-weighted coverage++Compute `buildCoverageReport` on the ordinary search path (it already runs in+evidence-pack mode) and expose `idfWeightedCoverage` on the outcome; have+`decideRecallInject` gate on it instead of on `score`.++- Blast radius: **local to the floor**, plus one new field on `SearchOutcome`.+ No score moves, so none of the four thresholds in the table above changes,+ and no ranking changes anywhere.+- Cost: one extra document-frequency read per query on a path that does not+ do one today (`evidence-verification.ts:59` shows the inputs required).+- Answers the "member describes a state the system SHOULD reach" constraint+ without touching ranking.++### B. Stop min-max-normalising the keyword lane++Replace `normalizeBm25` with a monotone absolute squash of raw BM25.++- Blast radius: **release-wide and measured**. Every result score in the+ product moves. Four absolute thresholds change meaning simultaneously+ (recall-inject 0.35, adequacy 0.6/0.3, gap-loop 0.5, chain-stop 0.8), and+ two of them currently sit exactly on the value the change would move+ (`assessRecallAdequacy.sufficient === 0.6 === keywordWeight`). Every+ ranking snapshot test over a fixture vault would need re-baselining.+- Not defensible inside this task alone.++### C. Fix the four thresholds instead of the score++Leave normalisation alone; make each consumer state that it reads a *ranking*+position, and delete the ones that cannot be honest — the adequacy+`sufficient` threshold and the gap-loop auto-close floor in particular.++- Blast radius: touches `recall-adequacy.ts`, its two MCP callers, three+ config keys (`src/core/config.ts:850-868`) and `gap-loop.ts`. No score+ moves. But it removes capability rather than adding it, and it does not+ give `below_floor` an honest firing condition.++### D. "Keep and document" — only in one form++The repo forbids settings that cannot change an outcome, and `below_floor`+*can* change one — just for the wrong reason. If nothing else is done, the+documentation must state the actual condition: *"the floor fires when a+downstream filter removes the pool's best row, or when supersede fade+applies, or when `search_keyword_weight` is below the floor — never because a+match was weak."* The comment at+`src/core/bench/failure-modes.ts:38-44` must be corrected regardless: it is+both numerically wrong (0.65) and behaviourally wrong ("unreachable").++Recommendation: **A**, plus the `failure-modes.ts` comment correction, plus+raising the tier-plumbing defect below as its own task.++---++## Defects noticed++1. **`tierByDoc` has no producer.** `ranker.ts:50,572-573` implement a+ documented, user-editable frontmatter knob (`tier:`,+ `src/core/brain/page-meta/tier.ts:1-10,28-37`) that the search pipeline+ never populates: `rankCandidates`+ (`src/core/search/pipeline/assemble.ts:390-441`) passes eleven signal maps+ and not this one. `collectCandidateSignals` has no tier collector+ (`src/core/search/pipeline/candidate-signals.ts`). Measured: notes stamped+ `tier: peripheral` report `breakdown.tier === 1` and score identically to+ untagged notes. `readTier` *is* consumed elsewhere+ (`src/core/brain/context-pack.ts:336`), so the frontmatter key is not+ dead — only its ranking half is. Note that+ `candidate-signals.ts:208` explicitly says "like the tier signal, the+ stamp is read from frontmatter at query time", describing a collector that+ does not exist.++2. **`src/core/bench/failure-modes.ts:38-44` states the wrong default+ (0.65 vs the actual 0.6) and the wrong conclusion ("unreachable").** The+ v1.48.0 conformance suite's caveat is anchored on both.++3. **`assessRecallAdequacy`'s `sufficient` threshold is exactly equal to the+ shipped `keywordWeight`** (`recall-adequacy.ts:46` vs+ `src/core/search/index.ts:154`). `>=` makes every keyword hit+ `sufficient`; a one-hundredth change to either constant inverts the+ verdict for every query in the product. Whatever is decided about the+ recall-inject floor, this coincidence should not survive as a coincidence.++4. **`search_chain_stop_score` means opposite things in the two fusion+ modes** — unreachable at 0.8 in `linear` (band [0.60, 0.65]), always met+ in `rrf` (top pinned at 1.0 by `fusion.ts:125-138`). The knob is+ documented as a normalised-confidence threshold+ (`cross-vault.ts:136-143`), which it is not across modes.++5. **`normalizeBm25` returns `1` for every hit when the pool ties**+ (`ranker.ts:211-213`), including the single-hit case. Defensible as+ ranking, indefensible as an input to an absolute threshold — a sole hit of+ any quality is scored identically to a perfect one.diff --git a/docs/brainstorm/a-label-is-not-a-boundary/variants.md b/docs/brainstorm/a-label-is-not-a-boundary/variants.mdnew file mode 100644index 00000000..7a241ae1--- /dev/null+++ b/docs/brainstorm/a-label-is-not-a-boundary/variants.md@@ -0,0 +1,98 @@+# Variants - audit trail++The consultant was Claude Code, run once with the prompt at+`cli-output/prompt.md` and captured verbatim at `cli-output/claude.md`. It+returned three parseable variants and a recommendation, so the fallback+consultant was not run.++The prompt carried the **corrected** framing rather than the tracker's original+wording. Eight reconnaissance passes against the real source had already+established that most of the ten task bodies describe a different system: one+where the ask is a git-visibility ladder for a product with no git transport, a+per-agent instruction block over a transport that cannot carry an agent, a fleet+view over a metric with no referent, and a symmetric shared scope for a private+flag that is content-derived rather than caller-declared. Variants generated+from those premises would have been variants for another codebase. The+corrections are in `recon/`, each anchored and several reproduced by execution.++## The three variants, verbatim++See `cli-output/claude.md`. In summary:++1. **Repair the instruments, let the red builds define the scope** - treat the+ release as a measurement failure first: fix the broken auditors in dependency+ order and ship whatever product fixes the newly-red builds demand. Complexity+ large, risk high.+2. **A boundary census** - build an eleventh census in the established idiom+ where every label-bearing declaration must name the site that enforces it,+ and make all ten findings rows in one table. Complexity large, risk high.+3. **Disposition triage: enforce, retract, or re-measure; no new mechanism** -+ assign every finding exactly one of three verdicts and route it to the census+ that already owns its class. Complexity medium, risk medium. Recommended by+ the consultant.++## Decision++**Variant 3, with one correction and one graft.**++### Agreement with the recommendation++The consultant's decisive argument is the empty critical path, and it holds+against the source: the ten units touch largely disjoint files, each has a+definition of done anchored at a specific `file:line`, and only the lexer+extraction has a shared owner. Variant 1 states outright that its scope is+whatever the repaired instruments turn red, which is not a scope for a single+branch that must also keep an exact tool count, four hardcoded lists and a+byte-diffed bundle green. Variant 2 is the parallel idiom the operator's+constraints forbid, and its own trade-offs predict the failure mode precisely:+"a registry whose membership check is weaker than what it claims to enforce is+precisely the defect under review."++### The correction++Variant 3 accepts "no single new mechanism guards the eleventh instance" as a+cost. That cost is not accepted. This repository's durability doctrine is that a+fix without a census is a fix a reviewer has to remember, and the previous+release proved the point in the sharpest possible way - the census its whole+argument rested on read no source at all.++The mechanism does not have to be new. Finding 1 already names it: the scope+matrix asserts that each of 110 tools is classified exactly once and never that+a classification is correct, which is the same shape as every other finding in+this release. Turning the unasserted bucket from a bare name list into entries+that each carry drivable arguments and a written reason, and running them+against a two-owner fixture, is a structurally-derived enforcement census inside+the test that already owns the class. That is U3, and it is what makes U1+durable rather than a fix that holds until the next tool is added.++### The graft++Variant 2's organising principle survives inside the ENFORCE units: a bucket+without a per-surface assertion is another label with nothing under it, so every+ENFORCE unit ships its assertion in the same commit as its check. U8 carries the+same idea one level up - the egress census missed the eighth site because its+destination derivation is a hardcoded name list, so the derivation is widened+and a synthetic destination is used to prove the widening works. The census that+catches unguarded exports had the defect it exists to catch.++Variant 1's best material is kept as individual RE-MEASURE units - the shared+lexer, the discarded IDF-weighted coverage, the egress destination derivation -+without buying the unbounded discovery loop that came with them. The one place+its logic is honoured in full is U3's risk note: driving ten tools against a+two-owner fixture may surface more leaks than the unit expects, and the budget+must absorb that rather than stopping at the ten already named.++### Why RETRACT is first-class, and its one exception++Two of the ten items ask for mechanisms with no subject in this product. The+operator's standing constraint is that a fallback which quietly does nothing is+forbidden and an error must be shown explicitly; a knob that cannot change an+outcome is that same defect in configuration form, because the operator sets it,+sees no error, and believes a boundary exists. So retraction is a shipped+outcome with its evidence recorded, not a deferral.++The exception is written into the tracker and is honoured: t_eb94ac35 states+that `below_floor` must not be closed by deleting the vocabulary member, because+the member describes a state the system should be able to reach. U4 re-measures+instead, and after it the floor fires when the match is genuinely weak - which is+what the member always claimed and what it has never done.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 7196b710..36877018 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -133,8 +133,10 @@ o2b brain snapshot log (CLI-only) Newest-first listing of every recoveryo2b brain snapshot diff (CLI-only) Read-only diff between two snapshots, or snapshot vs live Brain/o2b brain rollback (CLI-only) Restore Brain/ from a snapshot (--dry-run previews; drift abort vs --force-rollback); --list, the prompt and --json name the snapshot reason ('unknown' when the sidecar records none)o2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yes-o2b brain export Read-only dump of active preferences (--format json|llms-txt [--out <path>] [--force])-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).+o2b brain export Read-only dump of active preferences (--format json|llms-txt [--out <path>] [--force]). Since v1.49.0 the bytes pass the shared egress redactor (stderr carries a notice when anything was removed), and a `pref-*.md` the parser cannot read is REFUSED, not skipped: exit 1 naming every unreadable file in one run rather than exit 0 over a shorter list. `o2b brain doctor` reports the same files+o2b 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). 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 valueo2b 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-stampso2b 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)@@ -1086,7 +1088,7 @@ Recall and ranking quality (v0.20.0), each tunable and bounded:| `search_cache_enabled` | `OPEN_SECOND_BRAIN_SEARCH_CACHE_ENABLED` | `false` | Opt-in persistent query cache, gated by corpus generation || `search_cache_ttl_seconds` | `OPEN_SECOND_BRAIN_SEARCH_CACHE_TTL` | `300` | Cache row time-to-live in seconds || `search_chain_stop_enabled`| `OPEN_SECOND_BRAIN_SEARCH_CHAIN_STOP` | `false` | Opt-in cross-vault early termination once an origin answers confidently |-| `search_chain_stop_score` | `OPEN_SECOND_BRAIN_SEARCH_CHAIN_STOP_SCORE` | `0.8` | Normalized `[0,1]` top-score threshold that triggers the chain-stop |+| `search_chain_stop_score` | `OPEN_SECOND_BRAIN_SEARCH_CHAIN_STOP_SCORE` | `0.8` | Match-quality `[0,1]` threshold that triggers the chain-stop: the share of the query's IDF mass an origin covered, not its top result score |`brain_context_pack` also accepts `max_chars_per_memory` and`max_total_chars` (code-point caps). Pass `--lanes` to keep the legacy flat@@ -1102,6 +1104,34 @@ Entity-boosted retrieval and header-anchored chunking populate on thenext reindex and need no configuration. Every result carries a`why_retrieved` list naming the scoring layers that ranked it.+## What leaves the machine unscanned (network egress)++Every export that writes a FILE - `brain export`, `brain explorer --export`,+`brain bank-export`, `brain graph-export`, `brain okf-export`,+`export-config`, `install --out` - runs the shared redactor over its bytes+before they land, and prints a notice on stderr when it removed something.++Five paths send vault-derived bytes to a NETWORK destination and are+**not** scanned. That is a stated exposure, not an oversight: redacting an+embedding input produces a vector for the placeholder rather than for the+text, so the chunk comes back unfindable while the index reports success.+The full decision record for each is `src/core/egress/registry.ts`, keyed+by the id below.++| id | verb | what leaves | when it can happen |+| --- | --- | --- | --- |+| `search-embedding-openai-compat` | `o2b search index` / any reindex | every indexed chunk BODY, verbatim | only once `search_embedding_endpoint` + an API key are configured; the endpoint is whichever host you name, including a local one |+| `search-embedding-zeroentropy` | `o2b search index` (zeroentropy profile) | the same chunk bodies, to a second vendor's embed endpoint | same gate, when that provider profile is selected |+| `search-rerank-cross-encoder` | `o2b search --rerank` | the QUERY plus the top-of-pool candidate DOCUMENTS - vault text the embedding path may never have seen, chosen by relevance to what you just asked | only with a reranker endpoint configured |+| `brain-telegram-capture` | `o2b brain telegram-run` | reply text POSTed to the Telegram Bot API; the `/catchup` reply is composed from vault content | only while the runner verb is running; an install that never starts it never reaches this path |+| `research-external-fetch` | `o2b brain research` | an agent-composed search query (not a page body) to the configured research provider | key-gated: with no key set every call is a typed `disabled` error |++Semantic search, reranking, Telegram capture and research are all off+until you configure an endpoint, so a default install has no network+egress at all. `tests/core/architecture/egress-census.test.ts` fails if a+sixth such path is added without a declaration, and fails if a declared+one is missing from this table.+## Helpers```textdiff --git a/docs/mcp.md b/docs/mcp.mdindex 0c9570b2..765cd2aa 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -171,7 +171,7 @@ flags for a narrower per-process full server.| `brain_analytics` | Read-only Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis \| dedup`. `view=dedup` summarises the persisted exact-hash ingest dedup records into a trend plus a per-source re-ingest ranking; every count is an exact sha-256 drop, never a semantic figure (the semantic detectors nominate merge candidates and never drop). | `view` || `brain_search` | Read-only vault search with optional structured query lanes, explicit focus hints, time ranges, evidence-pack diagnostics, and a selectable recall `profile` (`fast \| balanced \| thorough`). | `query` || `brain_recall_feedback` | Record explicit up/down recall feedback for one search result; feeds the deterministic learned-weight fold. | `query`, `result_path`, `verdict` |-| `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. When the caller passes `scores`, also attaches an adequacy verdict (`sufficient` \| `weak` \| `insufficient`), a recommended action (`proceed` \| `re_recall` \| `abstain`), and an optional `escalate` flag over the gate-telemetry relevance scores plus the epistemic mix; thresholds via `recall_adequacy_sufficient` / `recall_adequacy_weak` / `recall_adequacy_min_results`. | `prompt` |+| `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. When the caller passes `scores` AND `match_quality` (the `idf_weighted_coverage` a search outcome reports - the two stand or fall together, and an incomplete pair is refused), also attaches an adequacy verdict (`sufficient` \| `weak` \| `insufficient`), a recommended action (`proceed` \| `re_recall` \| `abstain`), and an optional `escalate` flag. The LEVEL is decided by `match_quality` alone; the scores decide only the usable-result count. Thresholds via `recall_adequacy_sufficient` / `recall_adequacy_weak` / `recall_adequacy_min_results`. | `prompt` || `brain_context_pack` | Budgeted context slice; pass `lanes: true` to return directives, constraints, and consider lanes. Filtered items include `safety.reasons`. Each item carries a structural `epistemic` status (`observed` \| `derived` \| `hypothesis` \| `plan` \| `unknown`) plus `evidence_refs` derived from existing graph metadata; fields are absent when the status is `unknown`. | `max_tokens` || `brain_context_receipts` | List or show opt-in prompt context receipt continuity records with budgets, hashes, source refs, safety/redaction metadata, and item IDs. | `operation` || `brain_recall_telemetry` | List or summarise opt-in recall telemetry records for search, context-pack, and pre-compress calls. | `operation` |@@ -781,7 +781,14 @@ log line is machine-composed rather than authored.stable opaque store reference (`vault://<hash>`) instead of the absolutehost path, because tool responses land in model context. Set`expose_host_paths: true` (or `OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS=true`)- to restore the raw path.+ to restore the raw path. Until v1.49.0 only three sites honoured that+ rule and every other `vault_path` returned the raw host path; the field+ now comes from one function (`src/mcp/vault-path-field.ts`) at every+ emitting site, and `tests/core/architecture/vault-path-census.test.ts`+ enumerates those sites from the source so a new one cannot opt out. On+ a device config that cannot be read the field carries+ `{ "error": "..." }` naming the file, rather than falling back to the+ path it exists to redact.- Since v1.32.0 `brain_feedback` responses include a conflict advisory whenthe incoming principle closely resembles a confirmed same-scope preference(the write still proceeds); the advisory names the preference id and the@@ -870,6 +877,28 @@ log line is machine-composed rather than authored.`operator`, `today`) reject an explicit `agent_scope` with`INVALID_PARAMS` naming the view rather than accepting and ignoring it.The tool count is unchanged at 108 and no output schema changed.+- Since v1.49.0 the no-argument surfaces that reach owner-taggable artifacts+ apply the ownership rule using the server-resolved agent identity, and only+ under `integrity.owner_scope_delivery: fail`. They are `brain_backlinks`,+ `brain_unlinked_mentions`, `brain_moc_audit`, `brain_hygiene` (both `scan`+ and `apply`), `brain_scaffold_stub`, `brain_doctor` (including `repair`),+ `brain_claims`, `brain_idea_discovery`, `brain_stale_scan`,+ `brain_event_trace`, `brain_agent_diff`, `brain_analytics` (every view that+ names an artifact: `timeline`, `concept_synthesis`, `belief_evolution`,+ `dedup`), `brain_health`, `brain_retention`, `brain_review_candidates`,+ `brain_clusters`, `brain_trigger` and `brain_dream` - plus the `preference`,+ `topic`, `backlinks` and `log` MCP RESOURCE templates, which had no+ ownership filtering at all and returned another owner's file verbatim. A+ withheld row is dropped and no count reports it, so a filtered report reads+ exactly like a report over a vault that never held the rows; a withheld+ resource answers with the same not-found message an absent one produces.+ `brain_hygiene apply` and `brain_doctor repair` bound the PLAN, so the write+ is bounded and not only the payload. With the gate `off` or `warn` all of+ them are byte-identical - `warn` observes nothing here by construction,+ because reporting what `fail` would withhold is itself the disclosure. `brain_backlinks` additionally gains an `unparsed` key,+ present only when the walk skipped an artifact it could not parse: a `count`+ of 0 beside a non-empty `unparsed` is not a measurement, which is the+ distinction a legacy-frontmatter vault previously could not make.- Since v1.39.0 `brain_context_receipts` accepts a third `summary`operation, plus `since`, `until`, and `max_receipts`. The summary foldsexisting receipt records for one session into counts, distinct items,diff --git a/docs/observability.md b/docs/observability.mdindex 429222fd..43f5a107 100644--- a/docs/observability.md+++ b/docs/observability.md@@ -69,8 +69,9 @@ Since v0.39.0 every new continuity record is stamped `schema: "o2b.continuity.v1| `session_id`, `turn_id` | payloads of session-scoped kinds; lifted by the read-model | yes - the cross-surface session join || `handoffKind`, `handoffRef` | `generation_report` payload `handoff`; lifted by the read-model | yes - joins a generation report to the write-session / context-receipt / dream run it traced || `timestamp` + `agent` | Brain log events | per-event attribution |+| `agentId`, `isSidechain` | `SessionTurn`, from a transcript that records delegation | yes - the only thing separating a delegated sub-agent's turns from its parent's, because a sub-agent transcript reuses the PARENT's session id |-Multi-agent vaults attribute writers via per-agent identity (`brain_agent_query`); continuity records do not yet thread parent/child agent ids - if delegated-subagent correlation becomes needed, it lands as an additive payload field (no version bump).+Multi-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.## Payload safety@@ -82,7 +83,8 @@ Every continuity payload passes `safeContinuityPayload()` (`src/core/brain/conti- `gate_telemetry` never stores the raw prompt by construction - only a SHA-256 prefix (`prompt_hash`) and the length (`prompt_chars`). The test suite asserts this against the persisted files, not just returned values. `negative_recall` shares that construction (same module, same hash helper) and adds one rule of its own: the coverage receipt it carries drops `index_path`, so no host filesystem path replicates with the vault.- `generation_report` follows the same rule: the handoff prompt is hashed and counted but never persisted - only `prompt_hash` (full SHA-256 hex) and `prompt_chars` land on disk, plus token counts. The kernel never calls an LLM; the report is the agent's INBOUND record after it performed a generation for a brain handoff, so the local token estimate (`local_estimate.input_tokens`) is always present while the agent-reported `usage` block is present only when supplied - absent is reported as absent, never fabricated. A grep-guarded regression test pins that no `fetch`/provider HTTP call exists under `src/core` for this feature, and a persisted-file assertion confirms no raw prompt survives.- `mcp_route_latency` records the route (tool name), MCP scope, status, duration, and the sorted set of argument KEY NAMES only - the tool's own JSON-Schema property names, never operator-supplied argument values - so no prompt, note body, or preference id can land on disk. A persisted-file test asserts key names survive while values never do.-- The masking policy lives in the read-model (`src/core/brain/continuity/read-model.ts`) and governs only the readers that go through it: records flagged `private` are dropped by default and kept only on explicit request; masked text is never un-masked. That is FOUR modules - the `o2b brain continuity` verbs (trajectory export and listing), the bench harness, `brain_event_trace`, and skill-usage aggregation. Twenty other modules call `listContinuityRecords` on the store directly and see raw records: no `private` drop and no schema-version dispatch. The policy is read-model-wide, NOT store-wide. Both lists are asserted in `tests/core/brain/continuity/reader-census.test.ts`, which fails when a module joins or leaves either set; auditing the direct readers is tracked separately.+- The masking policy lives in the read-model (`src/core/brain/continuity/read-model.ts`) and governs only the readers that go through it: records flagged `private` are dropped by default and kept only on explicit request; masked text is never un-masked. That is FOUR modules - the `o2b brain continuity` verbs (trajectory export and listing), the bench harness, `brain_event_trace`, and skill-usage aggregation. Twenty-one other modules call `listContinuityRecords` on the store directly and see raw records: no `private` drop and no schema-version dispatch. The policy is read-model-wide, NOT store-wide. Both lists are asserted by name in `tests/core/brain/continuity/reader-census.test.ts`, which fails when a module joins or leaves either set, and both COUNTS are pinned there as equalities rather than floors - the direct floor used to sit at twenty against a reality of twenty-one, which is how the number in this sentence came to be wrong. Auditing the direct readers is tracked separately.+- A hook's `tool_response` is READ and never written. Lifecycle capture consults it to decide whether the call it is reacting to actually succeeded - a failed `brain_feedback` must not be replayed, because replaying it mints the record the tool declined to create - and the decline is counted rather than swallowed. The response body itself is arbitrary tool output and never reaches a payload, so declaring it in the hook contract costs nothing on disk.- `private` is the ONLY visibility signal a record carries, and it is inferred from a `<private>` region in the payload rather than declared. A caller-declared `scope` field was built for this envelope and removed before release: nothing in the codebase could supply one - no tool argument, no command-line flag, no config key and no library entry point - and its single vocabulary member would have narrowed a record's visibility rather than widened it, since a declared scope is dropped by every reader that does not name it. Adding a declaration to the envelope is a schema change; `tests/core/brain/continuity/record-envelope.test.ts` pins the eight fields and their order so the next attempt has to be argued for.## Fail-open rulesdiff --git a/docs/updating.md b/docs/updating.mdindex 3af03a3d..97805858 100644--- a/docs/updating.md+++ b/docs/updating.md@@ -47,6 +47,109 @@ instruction files such as `CLAUDE.md`/`AGENTS.md`, installed`.claude/skills/`) and warns with the exact replacement for any stalereference it finds (`removed-tool-reference`).+## Upgrading to 1.49.0++1.49.0 is a MINOR release that nevertheless changes behaviour for input+and vaults that 1.48.0 accepted. [`docs/stability.md`](stability.md) lists+"tightening validation so previously accepted input is rejected" as a+breaking change, so each one is written here rather than left to be+discovered at the terminal. Nothing below needs a migration step; they all+need a reader.++**A recall-gate call that passed `scores` alone is now refused.**+`brain_recall_gate` and `brain_context_pack` decide the adequacy level+from `match_quality` (a search outcome's `idf_weighted_coverage`) and no+longer derive one from the scores, because the keyword lane is min-max+normalised inside its own candidate set and its top row is pinned at the+configured weight however well it matched. The two arguments now stand or+fall together: `scores` without `match_quality`, or `match_quality`+without `scores`, answers `INVALID_PARAMS` naming both. The tool schema+states the pairing as `dependentRequired`, and the verdict now echoes+`match_quality` back so the quantity that decided the level travels with+it. **Fix:** send both, taking `match_quality` from the search outcome's+`idf_weighted_coverage`. Omit both to get the structural gate alone, which+is unchanged.++**An unreadable preference file now fails the verb instead of being+skipped.** `collectExportRows` used to `continue` past a `pref-*.md` it+could not parse, so an export silently omitted rules - and an export that+omits a rule reads exactly like a vault that never had it. It now collects+every failure in the directory (one run names them all) and refuses. Three+verbs that exited 0 on such a vault now exit **1** with+`N preference file(s) could not be parsed …`:++- `o2b brain export` (both `--format` values, with or without `--out`)+- `o2b brain bank-export`+- `o2b brain explorer --export <path>` - and nothing is written++`o2b brain doctor` reports the same files. **Fix:** repair or remove the+named files, then re-run. A vault with no malformed preference is+unaffected.++**`o2b brain bank-import` is deliberately NOT in that list.** It calls the+same collector against the DESTINATION vault, to learn which topics its+existing rules already claim. A pre-existing malformed rule there has+nothing to do with the bundle being carried, so the import proceeds on the+rules it could read and prints `topic-key check incomplete: <path> …` for+each one it could not - the topic-key collision list beside it is a+partial answer, not an empty one. The rows still restore, and the exit+code is still governed by the bundle's own failed rows.++**`o2b brain explorer` (live mode) refuses to start on an unparseable+Brain file.** The live server re-reads the vault on every request, so the+refusal is applied once at boot: a browser showing a silently smaller+graph is the same lie as a written file. Previously the server started and+served the incomplete graph. **Fix:** the refusal names every file;+repair or remove them.++**`o2b brain explorer --export` output content changes.** The exported+HTML now passes the shared egress redactor before the template+substitution, so a preference whose text contains a credential-shaped+value exports with a placeholder in place of it, and stderr carries a+one-line notice when anything was removed. Byte-for-byte comparisons of+exports across this boundary will differ on vaults that contain such+values; a vault that contains none produces the same document.++**`o2b brain feedback --json` mirror fields.** When a shared namespace is+configured, the payload carried a single `mirror` string. It now carries+`mirror` plus an optional `mirror_reason`, and the vocabulary changed:++| 1.48.0 | 1.49.0 |+| --- | --- |+| `mirror: "ok"` | unchanged |+| `mirror: "failed"` for an I/O failure | unchanged, plus `mirror_reason` |+| `mirror: "failed"` for a self-mirror | `mirror: "misconfigured"` plus `mirror_reason` |+| `mirror: "off"` | the key is absent entirely |++A self-mirror - `shared_namespace` resolving to the origin vault - is+decided before any I/O and is repaired by editing one config key, while+`failed` is a write that was attempted and raised; reporting them+identically sent the operator after the wrong fault. `off` was never+producible: no caller ever emitted it, and the absence of a mirror is+expressed by the key not being there. **Fix:** a consumer switching on+`mirror` must handle `misconfigured` and must not expect `off`.++**Four thresholds now measure something different for an unchanged+config.** No threshold VALUE changed; what each compares against did. The+recall-inject floor (`RECALL_INJECT_CONFIDENCE_FLOOR`), the recall-adequacy+verdict (`recall_adequacy_sufficient` / `recall_adequacy_weak`), the+gap-loop auto-close floor (`GAP_LOOP_AUTO_CLOSE_FLOOR`) and the cross-vault+chain stop (`search_chain_stop_score`) all compared their constant against+a result SCORE. The keyword lane is min-max normalised within its+candidate set, so the top row of any non-empty recall scored exactly+`search_keyword_weight` - shipped at 0.6, identical to+`recall_adequacy_sufficient`. Every keyword recall graded+`sufficient / proceed`, `weak` and `insufficient` were unreachable, a gap+task auto-closed on a hit of any quality, and the chain stop meant+opposite things under the two fusion modes (unreachable in `linear`,+always met in `rrf`). All four now read IDF-weighted coverage, which is+absolute and pool-independent. **Expect different outcomes from the same+numbers**: recall-inject abstains more often on weak matches, adequacy+verdicts span all three levels, gap tasks stay open on a poor hit, and a+configured chain stop starts firing (or stops firing) where it did not.+If you tuned any of these against the old behaviour, re-tune them against+`idf_weighted_coverage`, which `o2b search --evidence-pack` reports.+## For operatorsNormal updates need no manual steps:diff --git a/hooks/README.md b/hooks/README.mdindex ed70117c..f392fcaf 100644--- a/hooks/README.md+++ b/hooks/README.md@@ -26,6 +26,7 @@ hook payload shape, not on the runtime.| `PostToolUse` | `Write\|Edit\|MultiEdit\|apply_patch` | Emits `additionalContext` pointing at the three Brain writer tools. The full reminder is shown once per Claude Code session; later writes get a one-line nudge (Codex one-shot runs always get the full text). || `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, returns `decision: "block"` once, then lets the second Stop pass. |+| `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. |The Stop guardrail respects the runtime-provided `stop_hook_active`diff --git a/hooks/gap-promote.ts b/hooks/gap-promote.tsindex 51865382..2e5cb1c9 100644--- a/hooks/gap-promote.ts+++ b/hooks/gap-promote.ts@@ -15,8 +15,10 @@* Gap-task notes are plain durable files; they never touch the Hermes* kanban board. Flag off writes nothing (byte-identical no-op). Fail-open:* the hook arms the shared process ceiling and exits 0 on every path; a- * best-effort audit line records the run's counts. SessionEnd cannot carry- * additionalContext, so this hook never writes stdout.+ * best-effort audit line records the run's counts, and a run that threw+ * records a `gap_loop_failed` line plus a stderr notice instead of+ * vanishing. SessionEnd cannot carry additionalContext, so this hook never+ * writes stdout.*/import {@@ -27,11 +29,20 @@ import {} from "../src/core/config.ts";import { appendAuditRecord } from "../src/core/reliability/audit.ts";import { hookAuditDir } from "../src/core/brain/paths.ts";-import { defaultRecallRetriever } from "../src/core/brain/recall-inject.ts";+import { gapScopedRecallRetriever } from "../src/core/brain/gaps/gap-recall.ts";import { autoCloseRecalledGaps, promoteGapsToTasks } from "../src/core/brain/gaps/gap-loop.ts";import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";import { asHookPayload, readHookInput } from "./lib/stdin.ts";+/**+ * The vault this run resolved, remembered for the failure path.+ *+ * A failure is only auditable once the vault is known, and the vault is+ * resolved inside the run - so the failure reporter reads it from here+ * rather than re-resolving (which could itself be the thing that threw).+ */+let auditedVault: string | null = null;+function auditRun(vault: string, details: Record<string, unknown>): void {try {appendAuditRecord(hookAuditDir(vault), {@@ -47,6 +58,45 @@ function auditRun(vault: string, details: Record<string, unknown>): void {}}+/**+ * Report a run that threw, on both channels, and never rethrow.+ *+ * Fail-open is about the SESSION, not about the fault: swallowing the+ * throw silently is what let a retriever that ignored its membership rule+ * leave this hook doing nothing at all, run after run, with no trace+ * anywhere - a fallback that quietly does nothing, which this repository+ * does not allow. So the failure lands as its OWN audit action (`ok:+ * false`), never as a `gap_loop_run` row: a run that threw produced no+ * counts, and a counts row with zeros would read as a quiet, healthy+ * no-op - exactly the report this fault already got away with. Stderr+ * carries it too, for the operator who is not reading the audit log.+ *+ * Every step is individually guarded, because this is the last frame+ * before the process exits and there is nothing left to catch it.+ */+function reportRunFailure(exc: unknown): void {+ const kind = exc instanceof Error ? exc.name : typeof exc;+ const message = exc instanceof Error ? exc.message : "";+ try {+ process.stderr.write(`gap-promote: gap loop failed [${kind}] ${message}\n`);+ } catch {+ // a closed stderr must not become the crash the fail-open forbids+ }+ if (auditedVault === null) return;+ try {+ appendAuditRecord(hookAuditDir(auditedVault), {+ timestamp: new Date().toISOString(),+ actor: "gap-promote",+ action: "gap_loop_failed",+ target: "SessionEnd",+ ok: false,+ details: { error: kind, message },+ });+ } catch {+ // best-effort: auditing must never disturb the fail-open contract+ }+}+async function main(): Promise<void> {// Fast opt-out FIRST: default OFF means an immediate no-op, no writes.if (!resolveGapLoopEnabled()) return;@@ -61,6 +111,7 @@ async function main(): Promise<void> {const vault = resolveVault();if (vault === null) return;+ auditedVault = vault;const configPath = defaultConfigPath();const now = new Date();const threshold = resolveGapLoopThreshold(configPath);@@ -69,9 +120,15 @@ async function main(): Promise<void> {now,...(threshold !== undefined ? { threshold } : {}),});- const closure = await autoCloseRecalledGaps(vault, defaultRecallRetriever(configPath, vault), {- now,- });+ const closure = await autoCloseRecalledGaps(+ vault,+ // NOT `defaultRecallRetriever`: that one takes only the query, and a+ // one-parameter function is structurally assignable here, so it+ // compiled while silently ignoring the membership rule - returning+ // the gap-task note itself and making the gate throw on every run.+ gapScopedRecallRetriever(configPath, vault),+ { now },+ );auditRun(vault, {promoted: promotion.created.length,skipped: promotion.skipped.length,@@ -88,6 +145,8 @@ async function main(): Promise<void> {}}-main().catch(() => {- // Never crash the runtime; the session end must proceed regardless.+main().catch((exc: unknown) => {+ // Never crash the runtime; the session end must proceed regardless -+ // but never fail invisibly either. See `reportRunFailure`.+ reportRunFailure(exc);});diff --git a/hooks/hooks.json b/hooks/hooks.jsonindex 683e26e6..c7d29a2a 100644--- a/hooks/hooks.json+++ b/hooks/hooks.json@@ -106,6 +106,19 @@]}],+ "SubagentStop": [+ {+ "matcher": "*",+ "hooks": [+ {+ "type": "command",+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" session-capture; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook session-capture; exit 0",+ "timeout": 10,+ "statusMessage": "OSB: capturing delegated sub-agent stop"+ }+ ]+ }+ ],"SessionEnd": [{"matcher": "*",diff --git a/hooks/lib/context-events.ts b/hooks/lib/context-events.tsindex be148c4f..c0f4cf27 100644--- a/hooks/lib/context-events.ts+++ b/hooks/lib/context-events.ts@@ -14,6 +14,13 @@* https://code.claude.com/docs/en/hooks, 2026-06-02). Post-compaction* re-injection is served by the `SessionStart` hook with the* `compact` matcher instead - see `hooks/hooks.json`.+ *+ * `SubagentStop` is deliberately absent for the opposite reason: the host+ * DOES accept `additionalContext` there, and `hooks/hooks.json` registers+ * the event, but only for capture - no hook in this tree injects context+ * when a delegated sub-agent stops. Listing it would be a permission with+ * no producer behind it, and this list is a statement about what is+ * emitted, not about what would be accepted.*/export const CONTEXT_EVENT_NAMES = Object.freeze(["SessionStart", "UserPromptSubmit"] as const);diff --git a/hooks/lib/stdin.ts b/hooks/lib/stdin.tsindex 3d00c030..165b9c4d 100644--- a/hooks/lib/stdin.ts+++ b/hooks/lib/stdin.ts@@ -38,7 +38,20 @@ export interface HookPayloadBase {readonly stop_hook_active?: boolean;readonly tool_name?: string;readonly tool_input?: unknown;+ /**+ * What the host reported the tool call returned. Read through+ * `isToolResponseError` by both the post-write reminder and lifecycle+ * capture; the body itself is never persisted.+ */readonly tool_response?: unknown;+ /**+ * `SubagentStop`: the host-assigned id of the delegated sub-agent that+ * just finished. The event's sibling field `agent_transcript_path` is+ * deliberately not declared here - it is a machine-local host path and+ * nothing in this tree may persist one into a vault that syncs between+ * devices.+ */+ readonly agent_id?: string;}/**diff --git a/hooks/post-write-reminder.ts b/hooks/post-write-reminder.tsindex 1fde0a26..622a59d4 100755--- a/hooks/post-write-reminder.ts+++ b/hooks/post-write-reminder.ts@@ -28,6 +28,7 @@ import { existsSync, mkdirSync, readdirSync, statSync, unlinkSync, writeFileSyncimport { tmpdir } from "node:os";import { join } from "node:path";+import { isToolResponseError } from "../src/core/brain/tool-outcome.ts";import { asHookPayload, readHookInput } from "./lib/stdin.ts";import { detectHookRuntime, isArtifactToolName } from "./lib/detect.ts";import { postWriteNudge, postWriteReminder } from "./lib/messages.ts";@@ -125,12 +126,6 @@ async function main(): Promise<void> {process.stdout.write(JSON.stringify(out) + "\n");}-function isToolResponseError(response: unknown): boolean {- if (response === null || typeof response !== "object") return false;- const r = response as Record<string, unknown>;- return r.is_error === true || r.success === false;-}-function extractFilePath(input: unknown): string | null {if (input === null || typeof input !== "object") return null;const o = input as Record<string, unknown>;diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 6bea96ec..bb242be0 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.48.0",+ "version": "1.49.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex ebd0cb8e..6af831d3 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -1556,10 +1556,84 @@ var require_proper_lockfile = __commonJS((exports, module) => {import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";// src/core/config.ts-import { mkdirSync, readFileSync, statSync as statSync2 } from "node:fs";var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);+import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";+import { createHmac, randomBytes } from "node:crypto";import { homedir } from "node:os";-import { dirname, isAbsolute, join, resolve } from "node:path";+import { dirname as dirname2, isAbsolute, join as join2, resolve } from "node:path";++// src/core/fs-atomic.ts+import {+ closeSync,+ existsSync,+ fsyncSync,+ linkSync,+ mkdirSync,+ openSync,+ readFileSync,+ renameSync,+ unlinkSync,+ writeSync+} from "node:fs";+import { basename, dirname, join } from "node:path";+function atomicWriteFileSync(target, contents, opts = {}) {+ if (opts.skipIfUnchanged && isUnchanged(target, contents))+ return false;+ withTempFile(target, contents, (tmpPath) => {+ renameSync(tmpPath, target);+ });+ return true;+}+function isUnchanged(target, contents) {+ if (!existsSync(target))+ return false;+ try {+ return readFileSync(target, "utf8") === contents;+ } catch {+ return false;+ }+}+function withTempFile(target, contents, commit, mode = 420) {+ const dir = dirname(target);+ mkdirSync(dir, { recursive: true });+ const tmpName = `.${basename(target)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`;+ const tmpPath = join(dir, tmpName);+ let fd = null;+ let committed = false;+ try {+ fd = openSync(tmpPath, "wx", mode);+ const buf = Buffer.from(contents, "utf8");+ let written = 0;+ while (written < buf.byteLength) {+ written += writeSync(fd, buf, written, buf.byteLength - written);+ }+ fsyncSync(fd);+ closeSync(fd);+ fd = null;+ commit(tmpPath);+ committed = true;+ try {+ const dfd = openSync(dir, "r");+ try {+ fsyncSync(dfd);+ } finally {+ closeSync(dfd);+ }+ } catch {}+ } catch (err) {+ if (fd !== null) {+ try {+ closeSync(fd);+ } catch {}+ }+ if (!committed) {+ try {+ unlinkSync(tmpPath);+ } catch {}+ }+ throw err;+ }+}// src/core/brain/portability/profiles.tsvar import_proper_lockfile = __toESM(require_proper_lockfile(), 1);@@ -1590,6 +1664,8 @@ var WIKI_LINK_FORMATS = Object.freeze([var SUFFIX_INDEX_MEMO = new WeakMap;// src/core/config.ts+var CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", `+`, "\r"];var UNSUPPORTED_CONFIG_PLATFORMS = Object.freeze(["win32"]);class UnsupportedPlatformError extends Error {@@ -1615,11 +1691,11 @@ function resolveDefaultConfigPath(source) {return expandTilde(override);const xdg = source.env["XDG_CONFIG_HOME"];if (xdg)- return join(expandTilde(xdg), "open-second-brain", "config.yaml");+ return join2(expandTilde(xdg), "open-second-brain", "config.yaml");if (UNSUPPORTED_CONFIG_PLATFORMS.includes(source.platform)) {throw new UnsupportedPlatformError(source.platform);}- return join(source.home, ".config", "open-second-brain", "config.yaml");+ return join2(source.home, ".config", "open-second-brain", "config.yaml");}function defaultConfigPath() {return resolveDefaultConfigPath({@@ -1669,7 +1745,7 @@ function statConfigPath(resolved) {function readConfigText(resolved) {let bytes;try {- bytes = readFileSync(resolved);+ bytes = readFileSync2(resolved);} catch (err) {throw new ConfigReadError(resolved, err.message ?? String(err));}@@ -1679,6 +1755,25 @@ function readConfigText(resolved) {throw new ConfigReadError(resolved, `not valid UTF-8: ${err.message ?? String(err)}`);}}+function setConfigValue(key, value, path) {+ if (typeof value !== "string") {+ throw new TypeError(`config value for ${JSON.stringify(key)} must be a string`);+ }+ for (const bad of CONFIG_VALUE_REJECTED_CHARS) {+ if (value.includes(bad)) {+ throw new Error(`config value for ${JSON.stringify(key)} contains a disallowed character ` + `(${JSON.stringify(bad)}); reject rather than silently corrupting on read-back`);+ }+ }+ const resolved = path ?? defaultConfigPath();+ const discovery = discoverConfig(resolved);+ const data = { ...discovery.data, [key]: value };+ const body = Object.entries(data).map(([k, v]) => `${k}: "${v}"`).join(`+`) + `+`;+ atomicWriteFileSync(resolved, body);+ return resolved;+}+var UNCONFIGURED_AGENT_NAME = "agent";function resolveAgentName(configPath) {const env = process.env["VAULT_AGENT_NAME"];if (env)@@ -1687,7 +1782,59 @@ function resolveAgentName(configPath) {const value = data["agent_name"] ?? data["agentName"];if (value)return value;- return "agent";+ return UNCONFIGURED_AGENT_NAME;+}+function resolveExposeHostPaths(configPath) {+ return resolveConfigFlag("OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS", "expose_host_paths", configPath);+}+var INSTALLATION_SECRET_CONFIG_KEY = "installation_secret";+var INSTALLATION_SECRET_ENV_KEY = "O2B_INSTALLATION_SECRET";+var INSTALLATION_SECRET_RE = /^[0-9a-f]{32}$/;+function isValidInstallationSecret(value) {+ return INSTALLATION_SECRET_RE.test(value);+}+function resolveInstallationSecret(configPath) {+ const env = process.env[INSTALLATION_SECRET_ENV_KEY];+ if (env !== undefined && isValidInstallationSecret(env))+ return env;+ const resolved = configPath ?? defaultConfigPath();+ const read = () => {+ const value = discoverConfig(resolved).data[INSTALLATION_SECRET_CONFIG_KEY];+ return value && isValidInstallationSecret(value) ? value : null;+ };+ const existing = read();+ if (existing !== null)+ return existing;+ const dir = dirname2(resolved);+ mkdirSync2(dir, { recursive: true });+ let release;+ try {+ for (let attempt = 0;attempt < 10; attempt++) {+ try {+ release = import_proper_lockfile2.default.lockSync(dir, { stale: 1e4, realpath: false });+ break;+ } catch (err) {+ if (err.code !== "ELOCKED")+ break;+ Bun.sleepSync(50);+ }+ }+ const won = read();+ if (won !== null)+ return won;+ const generated = randomBytes(16).toString("hex");+ setConfigValue(INSTALLATION_SECRET_CONFIG_KEY, generated, resolved);+ return generated;+ } finally {+ release?.();+ }+}+var VAULT_STORE_REF_PREFIX = "vault://";+var VAULT_STORE_REF_HEX_LEN = 32;+function vaultStoreReference(vaultPath, configPath) {+ const key = resolveInstallationSecret(configPath);+ const digest = createHmac("sha256", key).update(resolve(vaultPath)).digest("hex").slice(0, VAULT_STORE_REF_HEX_LEN);+ return `${VAULT_STORE_REF_PREFIX}${digest}`;}function resolveConfigFlag(envKey, configKey, configPath) {const env = process.env[envKey]?.trim();@@ -1703,7 +1850,7 @@ function expandTilde(p) {if (p === "~")return homedir();if (p.startsWith("~/"))- return join(homedir(), p.slice(2));+ return join2(homedir(), p.slice(2));return p;}@@ -1798,9 +1945,16 @@ var CONTENT_ADDRESS_RE = /^[0-9a-fA-F]+(?:-[0-9a-fA-F]+)*$/;function isContentAddress(run) {return CONTENT_ADDRESS_RE.test(run);}+var SIGNAL_ID_RE = /^sig-\d{4}-\d{2}-\d{2}-[a-z0-9]+(?:-[a-z0-9]+)*$/;+function isSignalId(run) {+ return SIGNAL_ID_RE.test(run);+}+function isPreservedIdentifier(run) {+ return isContentAddress(run) || isSignalId(run);+}var BASE64_SECRET_RE = new RegExp("(?<![A-Za-z0-9+/=])" + "(?=[A-Za-z0-9+/=]{32,64}(?![A-Za-z0-9+/=]))" + "(?=[A-Za-z0-9+/=]{0,63}[a-z])" + "(?=[A-Za-z0-9+/=]{0,63}[A-Z])" + "(?=[A-Za-z0-9+/=]{0,63}\\d)" + "(?=[A-Za-z0-9+/=]{0,63}[+/=])" + "[A-Za-z0-9+=][A-Za-z0-9+/=]{30,62}[A-Za-z0-9+=]", "g");function redactBareTokens(text) {- return text.replace(VENDOR_TOKEN_RE, PLACEHOLDER).replace(BASE64_SECRET_RE, PLACEHOLDER).replace(HIGH_ENTROPY_TOKEN_RE, (run) => isContentAddress(run) ? run : PLACEHOLDER);+ return text.replace(VENDOR_TOKEN_RE, PLACEHOLDER).replace(BASE64_SECRET_RE, PLACEHOLDER).replace(HIGH_ENTROPY_TOKEN_RE, (run) => isPreservedIdentifier(run) ? run : PLACEHOLDER);}function redactUrlCredentials(text) {return text.replace(BASIC_AUTH_URL_RE, (_m, scheme) => `${scheme}${PLACEHOLDER}@`);@@ -1931,7 +2085,7 @@ function keyNameCarriesSecret(name) {if (identifierCarriesSecret(name))return true;for (const match of name.matchAll(HIGH_ENTROPY_TOKEN_RE)) {- if (!isContentAddress(match[0]))+ if (!isPreservedIdentifier(match[0]))return true;}return false;@@ -2002,11 +2156,13 @@ function redactStructured(input, opts = {}) {// src/core/egress/registry.tsvar EGRESS_REDACTION = Object.freeze({sharedRedactor: "shared_redactor",- noVaultContent: "no_vault_content"+ noVaultContent: "no_vault_content",+ unscannedNetworkPayload: "unscanned_network_payload"});var EGRESS_REDACTION_STATUSES = Object.freeze([EGRESS_REDACTION.sharedRedactor,- EGRESS_REDACTION.noVaultContent+ EGRESS_REDACTION.noVaultContent,+ EGRESS_REDACTION.unscannedNetworkPayload]);var R = EGRESS_REDACTION;var EGRESS_SITES = Object.freeze({@@ -2029,7 +2185,7 @@ var EGRESS_SITES = Object.freeze({verb: "o2b brain okf-export",module: "src/cli/brain/verbs/okf-export.ts",redaction: R.sharedRedactor,- reason: "the only export that carries page bodies VERBATIM, which is its interchange " + "contract and also why it is the widest leak by volume. The manifest is redacted " + "as a tree and `okf.json` re-serialised from it; the markdown files are redacted " + "as text. A bundle whose secrets were removed is no longer a lossless round-trip " + "of the vault, and the verb says so rather than implying otherwise."+ reason: "the only export that carries page bodies VERBATIM, which is its interchange " + "contract and also why it is the widest leak by volume. The manifest is redacted " + "as a tree and `okf.json` re-serialised from it; the markdown files are redacted " + "as text. A bundle whose secrets were removed is no longer a lossless round-trip " + "of the vault, and the verb says so rather than implying otherwise. What it does NOT " + "do is filter by label: a page carrying `private: true` in its frontmatter exports in " + "full, because the `<private>` region marker is this product's only content-derived " + "privacy primitive and these composers are content composers, not visibility filters."},"brain-preference-export": {id: "brain-preference-export",@@ -2052,6 +2208,48 @@ var EGRESS_SITES = Object.freeze({redaction: R.sharedRedactor,reason: "was declared as covered by its read model, which was wrong in both directions. " + "The upstream call redacts at WRITE time with the redactor's DEFAULT options, so " + "`redactTokens` and `redactUrlCredentials` were both off and a vendor key, a bare " + "high-entropy token and a `user:pass@host` URL all left through here verbatim - " + "the two flags the export boundary exists to turn on. Write-time coverage also " + "says nothing about a record already on disk or appended by another writer, since " + "the read model never re-scans. The verb now scans what it READ, which answers " + "both, and gains the truncation refusal the other five already had."},+ "brain-explorer-export": {+ id: "brain-explorer-export",+ verb: "o2b brain explorer --export",+ module: "src/cli/brain/verbs/explorer.ts",+ redaction: R.sharedRedactor,+ reason: "a self-contained HTML file with the whole rule graph embedded as JSON: every " + "preference and retired principle verbatim, plus each one's topic, scope and " + "provenance counts. It is the export most likely to be handed to a person rather " + "than a program - it opens in a browser - and it was the one export that never " + "scanned anything. Redaction runs over the graph TREE before the template " + "substitution, so a principle whose text contains a quote cannot disturb the " + "document. The label rule holds here too: a preference is not withheld for carrying " + "a `private` tag, because the `<private>` region marker is the only content-derived " + "privacy primitive in this product."+ },+ "search-embedding-openai-compat": {+ id: "search-embedding-openai-compat",+ verb: "o2b search index (embedding provider)",+ module: "src/core/search/embeddings/openai-compat.ts",+ redaction: R.unscannedNetworkPayload,+ reason: "the largest and most continuous egress in this product: every indexed chunk BODY " + "is POSTed verbatim to whichever endpoint the operator configured, for every " + "reindex, and nothing scans it. It is declared unscanned rather than wired to the " + "guard because redaction here would corrupt the thing being built - a vector " + "computed over a placeholder is a vector for the placeholder, so the chunk would " + "come back unfindable while the index reported success, which is a silent failure " + "where this one is at least a stated exposure. The controls that do exist are " + "the operator's: semantic search is off until an endpoint and a key are configured, " + "and the endpoint is whichever host they name, including a local one."+ },+ "search-embedding-zeroentropy": {+ id: "search-embedding-zeroentropy",+ verb: "o2b search index (zeroentropy provider)",+ module: "src/core/search/embeddings/zeroentropy.ts",+ redaction: R.unscannedNetworkPayload,+ reason: "the same chunk bodies as the OpenAI-compatible provider, to a second vendor's " + "embed endpoint under the same operator-configured base URL. Listed separately " + "rather than folded into one 'embedding' entry because the census keys on the " + "module, and a provider that stops being reachable from the resolver would " + "otherwise leave a declaration covering a path nobody can find."+ },+ "search-rerank-cross-encoder": {+ id: "search-rerank-cross-encoder",+ verb: "o2b search query --rerank",+ module: "src/core/search/rerank/cross-encoder.ts",+ redaction: R.unscannedNetworkPayload,+ reason: "sends the QUERY plus the candidate documents to a rerank endpoint, so it carries " + "vault text the embedding path may never have seen - the top-of-pool bodies of the " + "current result set, chosen by relevance to what the operator just asked. Unscanned " + "for the same reason as the embedding path: a reranker scoring placeholders returns " + "an order computed over text nobody wrote."+ },+ "brain-telegram-capture": {+ id: "brain-telegram-capture",+ verb: "o2b brain telegram-run",+ module: "src/core/brain/capture/telegram-capture.ts",+ redaction: R.unscannedNetworkPayload,+ reason: "POSTs reply text to the Telegram Bot API, and the `/catchup` reply is composed " + "from vault content. The transport is built only by the CLI runner verb, so an " + "install that never starts the runner never reaches this path at all - which is " + "why it is a declared narrow exposure rather than a guard call: the bytes are a " + "chat message the operator asked to be sent, and refusing to send one because it " + "quotes a credential-shaped string would break the surface without protecting a " + "destination the operator did not already choose."+ },+ "research-external-fetch": {+ id: "research-external-fetch",+ verb: "o2b brain research",+ module: "src/core/brain/research/external-fetch.ts",+ redaction: R.unscannedNetworkPayload,+ reason: "the one transport every research provider's POST goes through, which is why it is " + "declared here rather than at the provider modules that name the endpoints and " + "never call the network themselves. What leaves is an agent-composed search query, " + "not a page body, and the path is key-gated: with no key configured every call is " + "a typed `disabled` error, so an install that never sets one has no egress here."+ },"install-adapter-out": {id: "install-adapter-out",verb: "o2b install --out",@@ -2098,19 +2296,19 @@ function probeVaultDirectory(vault) {// src/core/doctor.tsimport {- existsSync as existsSync2,- mkdirSync as mkdirSync2,- openSync,- readFileSync as readFileSync2,+ existsSync as existsSync3,+ mkdirSync as mkdirSync3,+ openSync as openSync2,+ readFileSync as readFileSync3,rmSync,- writeSync,- closeSync+ writeSync as writeSync2,+ closeSync as closeSync2} from "node:fs";-import { dirname as dirname3, join as join3 } from "node:path";+import { dirname as dirname4, join as join4 } from "node:path";// src/core/partner/codegraph.ts-import { existsSync, readdirSync, realpathSync } from "node:fs";-import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";+import { existsSync as existsSync2, readdirSync, realpathSync } from "node:fs";+import { dirname as dirname3, join as join3, resolve as resolve2 } from "node:path";// src/core/partner/codegraph-health.tsvar GRAPH_HEALTH_CODES = Object.freeze({@@ -2193,11 +2391,11 @@ function codegraphInitCommand(projectPath) {}function isCodeProject(dir) {try {- if (!existsSync(dir))+ if (!existsSync2(dir))return false;- if (!isDir(join2(dir, ".git")))+ if (!isDir(join3(dir, ".git")))return false;- return CODE_MANIFESTS.some((m) => existsSync(join2(dir, m)));+ return CODE_MANIFESTS.some((m) => existsSync2(join3(dir, m)));} catch {return false;}@@ -2221,7 +2419,7 @@ function findCodeProjects(opts) {found.push(path);};consider(opts.cwd);- const vaultParent = dirname2(resolve2(opts.vault));+ const vaultParent = dirname3(resolve2(opts.vault));if (isDir(vaultParent)) {let entries = [];try {@@ -2233,7 +2431,7 @@ function findCodeProjects(opts) {for (const name of entries) {if (scanned >= limit)break;- consider(join2(vaultParent, name));+ consider(join3(vaultParent, name));}}for (const extra of opts.scanExtraPaths ?? []) {@@ -2375,7 +2573,7 @@ function codegraphDisabledResult() {};}function evaluateProjectStatus(project, deps) {- const indexDir = join2(project, ".codegraph");+ const indexDir = join3(project, ".codegraph");let indexed;try {indexed = statOrAbsent(indexDir)?.isDirectory() === true;@@ -2454,7 +2652,7 @@ function resolveRealpath(value) {// src/core/doctor.tsvar MANIFEST_FIX = "o2b update";function checkVaultWriteable(vault) {- if (!existsSync2(vault)) {+ if (!existsSync3(vault)) {return {name: "vault_writeable",ok: false,@@ -2462,10 +2660,10 @@ function checkVaultWriteable(vault) {fix: `mkdir -p "${vault}"`};}- const probe = join3(vault, ".open-second-brain-doctor-test");+ const probe = join4(vault, ".open-second-brain-doctor-test");try {- const fd = openSync(probe, "w");- closeSync(fd);+ const fd = openSync2(probe, "w");+ closeSync2(fd);rmSync(probe);} catch (exc) {return {@@ -2480,12 +2678,12 @@ function checkVaultWriteable(vault) {function checkConfigWriteable(config) {let createdForCheck = false;try {- mkdirSync2(dirname3(config), { recursive: true });- if (!existsSync2(config))+ mkdirSync3(dirname4(config), { recursive: true });+ if (!existsSync3(config))createdForCheck = true;- const fd = openSync(config, "a");- writeSync(fd, "");- closeSync(fd);+ const fd = openSync2(config, "a");+ writeSync2(fd, "");+ closeSync2(fd);if (createdForCheck)rmSync(config);} catch (exc) {@@ -2493,7 +2691,7 @@ function checkConfigWriteable(config) {name: "config_writeable",ok: false,message: `cannot write config ${config}: ${exc.message ?? exc}`,- fix: `mkdir -p "${dirname3(config)}" && chmod u+rwx "${dirname3(config)}"`+ fix: `mkdir -p "${dirname4(config)}" && chmod u+rwx "${dirname4(config)}"`};}return { name: "config_writeable", ok: true, message: `config writable: ${config}` };@@ -2523,7 +2721,7 @@ function loadJsonManifest(path, name) {}let data;try {- data = JSON.parse(readFileSync2(path, "utf8"));+ data = JSON.parse(readFileSync3(path, "utf8"));} catch (exc) {return {result: {@@ -2649,7 +2847,7 @@ function checkHermesManifest(path) {}let text;try {- text = readFileSync2(path, "utf8");+ text = readFileSync3(path, "utf8");} catch (exc) {return {name: "hermes_manifest",@@ -2698,7 +2896,7 @@ function checkOpenclawManifest(path) {}function checkOpenclawInstallability(repoRoot) {const results = [];- const pkgPath = join3(repoRoot, "package.json");+ const pkgPath = join4(repoRoot, "package.json");const { result, data } = loadJsonManifest(pkgPath, "openclaw_package_json");results.push(result);if (!data)@@ -2729,7 +2927,7 @@ function checkOpenclawInstallability(repoRoot) {});continue;}- const entryPath = join3(repoRoot, entry);+ const entryPath = join4(repoRoot, entry);const problem = manifestFileProblem(entryPath);if (problem === null) {results.push({@@ -2765,10 +2963,10 @@ function doctor(opts) {results.push(checkConfigWriteable(opts.config));if (opts.repoRoot) {const root = opts.repoRoot;- results.push(checkClaudeManifest(join3(root, ".claude-plugin", "plugin.json")));- results.push(checkCodexManifest(join3(root, ".codex-plugin", "plugin.json")));- results.push(checkHermesManifest(join3(root, "plugins", "hermes", "plugin.yaml")));- results.push(checkOpenclawManifest(join3(root, "openclaw.plugin.json")));+ results.push(checkClaudeManifest(join4(root, ".claude-plugin", "plugin.json")));+ results.push(checkCodexManifest(join4(root, ".codex-plugin", "plugin.json")));+ results.push(checkHermesManifest(join4(root, "plugins", "hermes", "plugin.yaml")));+ results.push(checkOpenclawManifest(join4(root, "openclaw.plugin.json")));results.push(...checkOpenclawInstallability(root));}const cg = checkCodegraph({@@ -2783,11 +2981,18 @@ function doctor(opts) {}// src/core/identity-reminder.ts-import { readFileSync as readFileSync3 } from "node:fs";-import { dirname as dirname4, resolve as resolve3 } from "node:path";+import { readFileSync as readFileSync4 } from "node:fs";+import { dirname as dirname5, resolve as resolve3 } from "node:path";import { fileURLToPath } from "node:url";-var TEMPLATE_PATH = resolve3(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");-var KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"];+var TEMPLATE_PATH = resolve3(dirname5(fileURLToPath(import.meta.url)), "..", "..", "templates", "identity-reminder.txt");+var RUNTIME_TARGET = Object.freeze({+ hermes: "hermes",+ openclaw: "openclaw"+});+var KNOWN_RUNTIME_TARGETS = Object.freeze([+ RUNTIME_TARGET.hermes,+ RUNTIME_TARGET.openclaw+]);function isRuntimeTarget(value) {return typeof value === "string" && KNOWN_RUNTIME_TARGETS.includes(value);}@@ -2796,7 +3001,7 @@ function loadReminderTemplate() {if (commonTemplateCache !== undefined)return commonTemplateCache;try {- commonTemplateCache = readFileSync3(TEMPLATE_PATH, "utf8").trimEnd();+ commonTemplateCache = readFileSync4(TEMPLATE_PATH, "utf8").trimEnd();return commonTemplateCache;} catch (err) {const message = err instanceof Error ? err.message : String(err);@@ -2805,7 +3010,7 @@ function loadReminderTemplate() {});}}-var TEMPLATES_DIR = resolve3(dirname4(fileURLToPath(import.meta.url)), "..", "..", "templates");+var TEMPLATES_DIR = resolve3(dirname5(fileURLToPath(import.meta.url)), "..", "..", "templates");var PER_TARGET_PATHS = Object.freeze(Object.fromEntries(KNOWN_RUNTIME_TARGETS.map((t) => [t, resolve3(TEMPLATES_DIR, `identity-reminder.${t}.txt`)])));var TEMPLATE_CACHE = new Map;function tryReadTargetTemplate(target) {@@ -2814,7 +3019,7 @@ function tryReadTargetTemplate(target) {return cached;let body;try {- body = readFileSync3(PER_TARGET_PATHS[target], "utf8").trimEnd();+ body = readFileSync4(PER_TARGET_PATHS[target], "utf8").trimEnd();} catch (err) {if (err.code !== "ENOENT")throw err;@@ -2848,8 +3053,8 @@ function buildReminder(agent, target) {}// src/core/vault.ts-import { mkdirSync as mkdirSync3, readFileSync as readFileSync4, readdirSync as readdirSync2, writeFileSync } from "node:fs";-import { dirname as dirname6, join as join4, relative as relative2 } from "node:path";+import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync as readdirSync2, writeFileSync } from "node:fs";+import { dirname as dirname7, join as join5, relative as relative2 } from "node:path";// src/core/integrity/degradation.tsvar DEGRADATION_CODE = Object.freeze({@@ -2895,7 +3100,7 @@ function emitDegradationNotice(sink, input) {}// src/core/path-safety.ts-import { dirname as dirname5, posix, relative, resolve as resolve4, sep } from "node:path";+import { dirname as dirname6, posix, relative, resolve as resolve4, sep } from "node:path";function vaultRelative(target, vault) {const rel = relative(resolve4(vault), resolve4(target));return rel.split(/[\\/]/).filter((p) => p.length > 0).join(posix.sep);@@ -2939,7 +3144,7 @@ function parseFrontmatterWithNotices(path, opts = {}) {const site = opts.site ?? FRONTMATTER_SITE;let text;try {- text = readFileSync4(path, "utf8");+ text = readFileSync5(path, "utf8");} catch (err) {const notices = [];emitDegradationNotice(notices, {@@ -3049,7 +3254,7 @@ function walk(root, dir, skipDirs, skipFiles, out, notices) {return;}for (const entry of entries) {- const full = join4(dir, entry.name);+ const full = join5(dir, entry.name);if (entry.isDirectory()) {if (skipDirs.has(entry.name))continue;@@ -3210,6 +3415,22 @@ function deriveRuntimeAgentName(runtimeId, operatorName) {return `${runtimeId}-${base}`;}+// src/mcp/vault-path-field.ts+function unresolvedField(err) {+ return { error: err.message };+}+var VAULT_PATH_OUTPUT_SCHEMA = Object.freeze({});+function vaultPathField(ctx) {+ const configPath = ctx.configPath ?? undefined;+ try {+ return resolveExposeHostPaths(configPath) ? ctx.vault : vaultStoreReference(ctx.vault, configPath);+ } catch (err) {+ if (err instanceof ConfigReadError)+ return unresolvedField(err);+ throw err;+ }+}+// src/openclaw/index.tsfunction resolveVaultPath(api) {const cfg = api.pluginConfig ?? {};@@ -3242,7 +3463,7 @@ var openclaw_default = definePluginEntry({config_exists: discovery.exists,config_keys: Object.keys(discovery.data).toSorted(),config: redactConfigMapping(discovery.data),- vault_path: vault,+ vault_path: vaultPathField({ vault }),vault_exists: presence.unexaminable ?? presence.present};return {@@ -3288,7 +3509,7 @@ var openclaw_default = definePluginEntry({metadata: p.metadata}));const result = {- vault_path: vault,+ vault_path: vaultPathField({ vault }),total_pages: pages.length,returned: matched.length,limit,@@ -3318,7 +3539,7 @@ var openclaw_default = definePluginEntry({const repoRoot = params["repo"] ?? null;const results = doctor({ vault, repoRoot });const result = {- vault_path: vault,+ vault_path: vaultPathField({ vault }),ok: results.every((r) => r.ok),checks: results.map((r) => ({name: r.name,diff --git a/package.json b/package.jsonindex 4e434954..3329d482 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.48.0",+ "version": "1.49.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 37cc8309..111c0ed0 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.48.0"+version: "1.49.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 8ff4a40a..46683e3a 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.48.0",+ "version": "1.49.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/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 37cc8309..111c0ed0 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.48.0"+version: "1.49.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 23cc2236..bcd1c702 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.48.0"+version = "1.49.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/scripts/measure-token-surface.ts b/scripts/measure-token-surface.tsindex 1901c69a..5644a0ab 100644--- a/scripts/measure-token-surface.ts+++ b/scripts/measure-token-surface.ts@@ -20,7 +20,12 @@ import { parseFrontmatterText } from "../src/core/vault.ts";import { estimateTokens } from "../src/core/brain/text/tokenizer.ts";import { buildInstructions } from "../src/mcp/instructions.ts";import { buildToolTable } from "../src/mcp/tools.ts";-import type { ToolDefinition } from "../src/mcp/tool-contract.ts";+import {+ TOOL_SCOPE,+ TOOL_SCOPES,+ type ToolDefinition,+ type ToolScope,+} from "../src/mcp/tool-contract.ts";interface ToolRow {readonly name: string;@@ -47,7 +52,7 @@ function sum(rows: ReadonlyArray<ToolRow>): { chars: number; tokens: number } {const json = process.argv.includes("--json");-const rows: ToolRow[] = buildToolTable("full").map((t) => {+const rows: ToolRow[] = buildToolTable(TOOL_SCOPE.full).map((t) => {const chars = wireSize(t);return {name: t.name,@@ -59,8 +64,10 @@ const rows: ToolRow[] = buildToolTable("full").map((t) => {const listed = rows.filter((r) => !r.hidden);const hidden = rows.filter((r) => r.hidden);-const fullInstructions = buildInstructions({ agent: "agent", scope: "full" });-const writerInstructions = buildInstructions({ agent: "agent", scope: "writer" });+// Every scope opens with the identity line, so every scope is measured.+const instructionChars = Object.fromEntries(+ TOOL_SCOPES.map((scope) => [scope, buildInstructions({ agent: "agent", scope }).length]),+) as Record<ToolScope, number>;const vault = resolveVault();let active: { raw: number; budgeted: number } | null = null;@@ -79,8 +86,9 @@ const report = {advertised_chars: sum(listed).chars,advertised_tokens_estimate: sum(listed).tokens,hidden_alias_chars: sum(hidden).chars,- instructions_full_chars: fullInstructions.length,- instructions_writer_chars: writerInstructions.length,+ instructions_full_chars: instructionChars[TOOL_SCOPE.full],+ instructions_writer_chars: instructionChars[TOOL_SCOPE.writer],+ instructions_catalog_chars: instructionChars[TOOL_SCOPE.catalog],active_md: active,top_tools: listed.toSorted((a, b) => b.chars - a.chars)@@ -95,8 +103,9 @@ if (json) {[`advertised tools ${report.advertised_tools} (${report.advertised_chars} chars, ~${report.advertised_tokens_estimate} tokens)`,`hidden aliases ${report.hidden_aliases} (${report.hidden_alias_chars} chars, callable but unlisted)`,- `instructions (full) ${report.instructions_full_chars} chars`,- `instructions (writer) ${report.instructions_writer_chars} chars`,+ `instructions (full) ${report.instructions_full_chars} chars`,+ `instructions (writer) ${report.instructions_writer_chars} chars`,+ `instructions (catalog) ${report.instructions_catalog_chars} chars`,active? `active.md ${active.raw} chars raw -> ${active.budgeted} chars injected (budget ${INJECT_BUDGET_CHARS_DEFAULT})`: "active.md (no vault resolved)",diff --git a/src/cli/brain/verbs/backlinks.ts b/src/cli/brain/verbs/backlinks.tsindex 1d53754c..8e980d83 100644--- a/src/cli/brain/verbs/backlinks.ts+++ b/src/cli/brain/verbs/backlinks.ts@@ -1,30 +1,71 @@import { buildBacklinkIndex } from "../../../core/brain/backlinks.ts";+import { gatedOwnerScopeView } from "../../../core/brain/owner-scope-view.ts";import { normaliseWikilinkTarget } from "../../../core/brain/wikilink.ts";-import { brainVerbContext, fail, parse } from "../helpers.ts";+import { brainVerbContext, fail, parse, resolveBrainAgent } from "../helpers.ts";++/**+ * The one sentence that turns a count into a measurement.+ *+ * `buildBacklinkIndex` reports the artifacts whose references it could not+ * read, and this verb printed the count alone - so an operator debugging a+ * legacy vault, on the surface they reach FIRST, read `Backlinks to+ * pref-x: 0` for a preference that is referenced by three files the walk+ * could not parse. The MCP tool says it; the CLI now says the same thing+ * in the same vocabulary.+ */+const INCOMPLETE_WALK_NOTE =+ "the count above is incomplete: the walk could not read these artifacts";export async function cmdBrainBacklinks(argv: string[]): Promise<number> {const { positional, flags } = parse(argv, {vault: { type: "string" },json: { type: "boolean" },});- const { vault } = brainVerbContext(flags);+ const { config, vault } = brainVerbContext(flags);const id = positional[0];if (!id) return fail("brain backlinks requires a target id (e.g. pref-foo, ret-bar, sig-...)");const target = normaliseWikilinkTarget(id);- const index = buildBacklinkIndex(vault);+ // The refs name the artifacts that WROTE them, so an unscoped index+ // publishes another owner's preference and retired ids - the leak+ // `brain_backlinks` closed on the MCP side while this verb, reading the+ // same index, kept publishing them. The scope is the gated one: under+ // `owner_scope_delivery: off` the view hides nothing and the output is+ // byte-identical.+ const index = buildBacklinkIndex(+ vault,+ gatedOwnerScopeView(vault, resolveBrainAgent(flags, config)).scope,+ );const refs = index.get(target) ?? [];if (flags["json"]) {- process.stdout.write(JSON.stringify({ id: target, count: refs.length, refs }, null, 2) + "\n");+ process.stdout.write(+ JSON.stringify(+ {+ id: target,+ count: refs.length,+ refs,+ // Omitted entirely on a clean walk, so a healthy vault's payload+ // is unchanged and matches `brain_backlinks` key for key.+ ...(index.unparsed.length > 0 ? { unparsed: index.unparsed } : {}),+ },+ null,+ 2,+ ) + "\n",+ );return 0;}process.stdout.write(`Backlinks to ${target}: ${refs.length}\n`);- if (refs.length === 0) return 0;for (const r of refs) {const ts = r.timestamp ? ` @ ${r.timestamp}` : "";process.stdout.write(` ${r.source} (${r.sourceKind}, field: ${r.field})${ts}\n`);}+ if (index.unparsed.length > 0) {+ process.stderr.write(`${INCOMPLETE_WALK_NOTE}:\n`);+ for (const u of index.unparsed) {+ process.stderr.write(` ${u.source} (${u.sourceKind}): ${u.reason}\n`);+ }+ }return 0;}diff --git a/src/cli/brain/verbs/bank-import.ts b/src/cli/brain/verbs/bank-import.tsindex 75d29974..460044c8 100644--- a/src/cli/brain/verbs/bank-import.ts+++ b/src/cli/brain/verbs/bank-import.ts@@ -96,6 +96,18 @@ export async function cmdBrainBankImport(argv: string[]): Promise<number> {`(${collision.prefIds.join(", ")}); consolidation plans nothing until one owner remains`,);}+ // The collision list above is a claim over every rule already in the+ // DESTINATION. A rule the scan could not parse makes it a partial+ // claim, and an empty list read as "no collisions" would be the+ // confident zero. The import itself is unaffected - those files are+ // not what the bundle carried - so it proceeds and says this instead+ // of refusing wholesale.+ for (const unreadable of p.topicScanUnreadable) {+ lines.push(+ ` topic-key check incomplete: ${unreadable.path} could not be parsed ` ++ `(${unreadable.reason}); an existing rule may already claim a restored topic key`,+ );+ }process.stdout.write(lines.join("\n") + "\n");}// A refused preference is a partial import, not a clean one: the callerdiff --git a/src/cli/brain/verbs/explorer.ts b/src/cli/brain/verbs/explorer.tsindex 8fc8fff0..b9d320e0 100644--- a/src/cli/brain/verbs/explorer.ts+++ b/src/cli/brain/verbs/explorer.ts@@ -4,10 +4,53 @@ import {buildLiveServer,collectExplorerData,renderExportedHtml,+ type ExplorerGraph,+ type ExplorerParseFailure,type LiveServerHandle,} from "../../../core/brain/explorer.ts";+import {+ EGRESS_OUTCOME,+ EGRESS_REDACTION_NOTICE,+ redactForEgress,+} from "../../../core/egress/guard.ts";import { brainVerbContext, fail, info, ok, parse } from "../helpers.ts";+/** How many unreadable files the refusal names before it stops listing. */+const MAX_NAMED_PARSE_FAILURES = 10;++/**+ * One sentence naming what could not be read. The graph is the whole+ * point of both modes, so an unreadable rule is reported rather than+ * skipped: a graph missing a node reads exactly like a vault that never+ * had one, and the reader is the person least able to tell the difference.+ */+function parseFailureDetail(failures: ReadonlyArray<ExplorerParseFailure>): string {+ const named = failures+ .slice(0, MAX_NAMED_PARSE_FAILURES)+ .map((f) => `${f.path} (${f.reason})`)+ .join("; ");+ const rest =+ failures.length > MAX_NAMED_PARSE_FAILURES+ ? ` and ${failures.length - MAX_NAMED_PARSE_FAILURES} more`+ : "";+ return (+ `${failures.length} file(s) under Brain/ could not be parsed, so the graph would be ` ++ `incomplete and nothing was written: ${named}${rest}. Repair or remove them, then ` ++ "re-run; `o2b brain doctor` reports the same files."+ );+}++/**+ * Collect the graph, refusing on anything unreadable. Returns the graph or+ * the exit code the caller should return, so both modes answer a corrupt+ * vault the same way.+ */+function collectOrRefuse(vault: string): ExplorerGraph | number {+ const graph = collectExplorerData(vault);+ if (graph.parse_failures.length > 0) return fail(parseFailureDetail(graph.parse_failures));+ return graph;+}+export async function cmdBrainExplorer(argv: string[]): Promise<number> {const { flags } = parse(argv, {vault: { type: "string" },@@ -22,17 +65,30 @@ export async function cmdBrainExplorer(argv: string[]): Promise<number> {if (exportPath !== undefined) {if (existsSync(exportPath) && !force)return fail(`${exportPath} exists; pass --force to overwrite`);- const graph = collectExplorerData(vault);- const html = renderExportedHtml(graph);+ const collected = collectOrRefuse(vault);+ if (typeof collected === "number") return collected;+ // Registry entry `brain-explorer-export`. The scan runs over the graph+ // TREE and the template substitution happens afterwards, so redaction+ // can never disturb the document's own quoting.+ const verdict = redactForEgress("brain-explorer-export", collected);+ if (verdict.outcome !== EGRESS_OUTCOME.released) return fail(verdict.detail);+ const html = renderExportedHtml(verdict.payload);try {atomicWriteFileSync(exportPath, html);} catch (err) {return fail(`failed to write ${exportPath}: ${(err as Error).message ?? err}`);}- ok(`exported ${graph.nodes.length} nodes to ${exportPath}`);+ ok(`exported ${verdict.payload.nodes.length} nodes to ${exportPath}`);+ if (verdict.redacted) process.stderr.write(EGRESS_REDACTION_NOTICE);return 0;}+ // The live server re-reads the vault on every request, so the same+ // refusal is applied once at boot rather than per request: a browser+ // showing a silently smaller graph is the same lie as a written file.+ const preflight = collectOrRefuse(vault);+ if (typeof preflight === "number") return preflight;+const portRaw = (flags["port"] as string | undefined) ?? "7777";const port = Number.parseInt(portRaw, 10);if (!/^\d+$/.test(portRaw) || !Number.isFinite(port) || port < 1 || port > 65535)diff --git a/src/cli/brain/verbs/feedback.ts b/src/cli/brain/verbs/feedback.tsindex 33e61651..9eaea0cd 100644--- a/src/cli/brain/verbs/feedback.ts+++ b/src/cli/brain/verbs/feedback.ts@@ -1,5 +1,9 @@import { readFileSync } from "node:fs";-import { mirrorSignal, resolveSharedNamespace } from "../../../core/brain/shared-namespace.ts";+import {+ mirrorReportFields,+ mirrorSignal,+ resolveSharedNamespace,+} from "../../../core/brain/shared-namespace.ts";import { resolveEffectiveScope, writeSignal } from "../../../core/brain/signal.ts";import {adviseIncomingFeedback,@@ -159,7 +163,10 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {confidence_value: 0,...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),},- { overwrite: false },+ // Ownership is resolved by the writer from the CLI's own config,+ // never echoed from `--agent`: the flag is caller-supplied, and a+ // caller must not be able to name whose memory this becomes.+ { overwrite: false, configPath: config },);} catch (exc) {return fail(`failed to force-confirm preference: ${(exc as Error).message ?? exc}`);@@ -184,7 +191,7 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {okJson({signal_path: sigResult.path,signal_id: sigResult.id,- ...(mirror !== undefined ? { mirror } : {}),+ ...mirrorReportFields(mirror),...(advisory !== null ? { advisory } : {}),// The machine stream carries the exit as a field, which is where a// forward pointer belongs on a payload the caller parses. The key@@ -197,7 +204,10 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {ok(`signal: ${sigResult.path}`);ok(`id: ${sigResult.id}`);if (mirror !== undefined) {- ok(`mirror: ${mirror}`);+ ok(`mirror: ${mirror.outcome}`);+ // A fail-soft outcome without its reason is a bit nobody can act on,+ // and the mirror is the one path an operator cannot inspect otherwise.+ if (mirror.reason !== undefined) ok(`mirror-reason: ${mirror.reason}`);}if (advisory !== null) {const where = advisory.scope ?? "(unscoped)";diff --git a/src/cli/brain/verbs/schema.ts b/src/cli/brain/verbs/schema.tsindex ac8ab379..a570894f 100644--- a/src/cli/brain/verbs/schema.ts+++ b/src/cli/brain/verbs/schema.ts@@ -189,16 +189,31 @@ function renderSchemaReportText(report: BrainSchemaReport, integrity: SchemaPackreturn lines.join("\n") + "\n";}+/**+ * One finding as a line, exhaustively over the union.+ *+ * The `switch` with a `never` default is deliberate: this used to be two+ * `if`s and a trailing `return` that rendered EVERY other kind as+ * `[unused-declaration]`, so a new member of the union would have been+ * printed under the wrong label with no compile error to say so.+ */function renderFinding(finding: SchemaReportFinding): string {- if (finding.kind === "unknown-token") {- return `[unknown-token] ${finding.category} ${finding.token} (${finding.path})`;- }- if (finding.kind === "link-constraint-violation") {- return (- `[link-constraint-violation] ${finding.relation} ` +- `${finding.source_type ?? "?"}->${finding.target_type ?? "?"} ` +- `(${finding.source} -> ${finding.target})`- );+ switch (finding.kind) {+ case "unknown-token":+ return `[unknown-token] ${finding.category} ${finding.token} (${finding.path})`;+ case "link-constraint-violation":+ return (+ `[link-constraint-violation] ${finding.relation} ` ++ `${finding.source_type ?? "?"}->${finding.target_type ?? "?"} ` ++ `(${finding.source} -> ${finding.target})`+ );+ case "unreadable-artifact":+ return `[unreadable-artifact] ${finding.category} ${finding.path}: ${finding.detail}`;+ case "unused-declaration":+ return `[unused-declaration] ${finding.category} ${finding.token}`;+ default: {+ const unreachable: never = finding;+ return unreachable;+ }}- return `[unused-declaration] ${finding.category} ${finding.token}`;}diff --git a/src/cli/main.ts b/src/cli/main.tsindex 6b1b5061..6eca0228 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -70,6 +70,7 @@ import { SERVER_VERSION } from "../mcp/protocol.ts";import { buildToolTable } from "../mcp/tools.ts";import { evaluateToolCapabilities, type RuntimeCapabilityWindow } from "../mcp/capabilities.ts";import { resolveToolSurface, toolSurfaceProfileNames } from "../mcp/profiles.ts";+import { TOOL_SCOPE, TOOL_SCOPES, isToolScope, type ToolScope } from "../mcp/tool-contract.ts";// ── Subcommands ─────────────────────────────────────────────────────────────@@ -618,19 +619,14 @@ async function cmdMcp(argv: string[]): Promise<number> {// rejected to avoid silent surprises.const writerOnly = Boolean(flags["writer-only"]);const explicitScope =- (flags["scope"] as string | undefined) ?? (writerOnly ? "writer" : undefined);- if (- explicitScope !== undefined &&- explicitScope !== "full" &&- explicitScope !== "writer" &&- explicitScope !== "catalog"- ) {+ (flags["scope"] as string | undefined) ?? (writerOnly ? TOOL_SCOPE.writer : undefined);+ if (explicitScope !== undefined && !isToolScope(explicitScope)) {process.stderr.write(- `o2b mcp: invalid --scope value: ${explicitScope}; expected one of: full, writer, catalog\n`,+ `o2b mcp: invalid --scope value: ${explicitScope}; expected one of: ${TOOL_SCOPES.join(", ")}\n`,);return 2;}- if (writerOnly && explicitScope !== "writer") {+ if (writerOnly && explicitScope !== TOOL_SCOPE.writer) {process.stderr.write(`o2b mcp: --writer-only conflicts with --scope ${explicitScope}\n`);return 2;}@@ -759,7 +755,7 @@ function parseCapabilityWindow(async function runMcpProbe(args: {vault: string | undefined;config: string;- scope: "full" | "writer" | "catalog";+ scope: ToolScope;serverName: string;json: boolean;capabilityWindow: RuntimeCapabilityWindow | undefined;diff --git a/src/core/agent-identity.ts b/src/core/agent-identity.tsindex 20fc307f..29047328 100644--- a/src/core/agent-identity.ts+++ b/src/core/agent-identity.ts@@ -14,8 +14,13 @@* filter against `PLACEHOLDER_AGENT_VALUES` (case-insensitive).* Returns `null` for empty / placeholder inputs so the caller can* fall back to the server-resolved default.+ * - `delegatedAgentName`: the identity a dispatched sub-agent writes+ * under, derived from its delegator's name and the id the host+ * assigned it.*/+import { createHash } from "node:crypto";+export const PLACEHOLDER_AGENT_VALUES: ReadonlySet<string> = new Set(["agent","assistant",@@ -54,6 +59,59 @@ export function normalizeAgentArgument(value: string | null | undefined): stringreturn cleaned;}+/**+ * Marker segment joining a delegating identity to the sub-agent it+ * dispatched. Kept as one token rather than a separator string so an+ * absent delegator degrades to `sub-<id>` instead of a leading hyphen.+ */+const DELEGATED_NAME_MARKER = "sub";++/** Characters of the host-supplied sub-agent id kept in a delegated name. */+const DELEGATED_ID_SEGMENT_CHARS = 8;++/** Runs of anything outside the canonical name alphabet, collapsed to one `-`. */+const NON_CANONICAL_NAME_RUN_RE = /[^a-z0-9]+/g;++/** Separator characters left at either end of a canonicalised segment. */+const EDGE_SEPARATOR_RE = /^-+|-+$/g;++/**+ * Derive the Brain identity of a sub-agent from the identity that+ * dispatched it and the id the host assigned it.+ *+ * A delegated turn was written by a different agent than the one that+ * opened the session, and the host says so - Claude Code stamps `agentId`+ * and `isSidechain: true` on every sidechain turn, under the PARENT's+ * session id. Collapsing the two onto one name erases the only record of+ * the boundary, which is why the roster could not tell a dispatched+ * worker's contribution from its orchestrator's.+ *+ * The result is a real identity, not a placeholder: it carries the+ * delegator's own name, so `normalizeAgentArgument` accepts it wherever a+ * caller-supplied identity is accepted. The id is canonicalised to the+ * name alphabet and truncated, because a host id is an opaque UUID and the+ * whole of it in a frontmatter field is noise; an id that canonicalises to+ * nothing falls back to a digest of the raw value rather than silently+ * dropping the segment and reading as the delegator itself.+ */+export function delegatedAgentName(delegator: string, subAgentId: string): string {+ const canonical = subAgentId+ .toLowerCase()+ .replace(NON_CANONICAL_NAME_RUN_RE, "-")+ .replace(EDGE_SEPARATOR_RE, "")+ .slice(0, DELEGATED_ID_SEGMENT_CHARS)+ .replace(EDGE_SEPARATOR_RE, "");+ const segment = canonical.length > 0 ? canonical : digestSegment(subAgentId);+ return [delegator.trim(), DELEGATED_NAME_MARKER, segment]+ .filter((part) => part.length > 0)+ .join("-");+}++/** Stable short digest for an id with no character in the name alphabet. */+function digestSegment(subAgentId: string): string {+ return createHash("sha256").update(subAgentId).digest("hex").slice(0, DELEGATED_ID_SEGMENT_CHARS);+}+/*** The operator identity template every device follows: `<vendor>-<host>-agent`* (e.g. `claude-vps-agent`, `hermes-mac-agent`). Capture group 1 is the hostdiff --git a/src/core/bench/failure-modes.ts b/src/core/bench/failure-modes.tsindex 0f4e8a5d..0d998c6c 100644--- a/src/core/bench/failure-modes.ts+++ b/src/core/bench/failure-modes.ts@@ -35,13 +35,29 @@* heavily as a silent miss, which is what makes a strategy that always* injects score strictly worse than one that abstains correctly.*- * A measured caveat that belongs with the number: through the shipped- * keyword lane the top-ranked result's score is pinned at the configured- * keyword weight (0.65 by default), because `rankResults` min-max- * normalizes the lane. `below_floor` is therefore unreachable via the- * default retriever today, and the abstain that actually fires on an- * off-topic prompt is `no_matches`. The floor is still the term under- * pressure - it is simply not, today, the term that fires.+ * A measured caveat that used to belong with the number, kept because it+ * is what the floor's current shape is a response to: through the shipped+ * keyword lane the top-ranked result's SCORE sits at or above the+ * configured keyword weight (`DEFAULT_KEYWORD_WEIGHT`,+ * `src/core/search/index.ts`) whenever that lane is non-empty, because+ * `rankResults` min-max normalizes it and then adds nine non-negative+ * layers on top - measured at `FRESH_KEYWORD_ONLY_TOP_SCORE` (0.65) on a+ * freshly written keyword-only vault, and higher still where a link or+ * entity boost fires. While the floor was compared against that score,+ * `below_floor` was unreachable via the default retriever and the abstain+ * that actually fired on an off-topic prompt was `no_matches` - the term+ * under pressure was not the term that fired. The floor now reads+ * `idfWeightedCoverage`, which grades the match rather than the pool's+ * shape, so a weak match reaches `below_floor` and this bench grades the+ * bound it says it grades.+ *+ * Both figures are named rather than written out here, and+ * `tests/core/search/keyword-lane-top-score.test.ts` drives the shipped+ * pipeline and asserts what it measures against those two bindings - that+ * test, not this sentence, is what keeps the stated number from drifting+ * from the shipped one. It drifted once: this paragraph read 0.65 before+ * the branch that rewrote it, the rewrite substituted 0.6, and 0.6 is the+ * floor rather than the measurement.** ## 2. Write-back fidelity*@@ -134,6 +150,7 @@ export function benchRecallRetriever(),),total: outcome.total,+ idfWeightedCoverage: outcome.idfWeightedCoverage,});};}diff --git a/src/core/brain/agent-backend/types.ts b/src/core/brain/agent-backend/types.tsindex b5ae7df5..15c735b5 100644--- a/src/core/brain/agent-backend/types.ts+++ b/src/core/brain/agent-backend/types.ts@@ -39,6 +39,18 @@ export interface MemoryRenderInput {readonly memoryPath: string;readonly importedAt: string;readonly bodySha256: string;+ /**+ * Owner token the rendered frontmatter must carry, or `undefined` for+ * an ownerless (shared) page.+ *+ * Resolved by the importer through `resolvedOwnerFor` - the same+ * decision `writePreference` makes - because a backend that renders+ * its own frontmatter is a preference writer, and a preference writer+ * that omits `owner:` under `integrity.owner_scope_delivery` hands+ * every imported memory to every agent (a-label-is-not-a-boundary,+ * U3).+ */+ readonly owner?: string | undefined;}/** One runtime's memory-format adapter. */diff --git a/src/core/brain/agent-source/registry.ts b/src/core/brain/agent-source/registry.tsindex 89588909..6e78d091 100644--- a/src/core/brain/agent-source/registry.ts+++ b/src/core/brain/agent-source/registry.ts@@ -1,3 +1,4 @@+import { isConfiguredAgentName } from "../../config.ts";import { vaultAgentSourceProvider } from "./vault-provider.ts";import type {AgentSourceContribution,@@ -46,6 +47,7 @@ export function summarizeAgentSources(kinds: Set<AgentSourceContributionKind>;topics: Set<string>;contributionCount: number;+ lastActivity: string;}>();@@ -56,11 +58,18 @@ export function summarizeAgentSources(kinds: new Set<AgentSourceContributionKind>(),topics: new Set<string>(),contributionCount: 0,+ lastActivity: contribution.timestamp,};current.providerIds.add(contribution.provider_id);current.kinds.add(contribution.kind);if (contribution.topic !== undefined) current.topics.add(contribution.topic);current.contributionCount++;+ // Folded rather than read off the last element: the caller may hand+ // in a filtered set, and an owner-scoped filter can remove exactly+ // the newest contribution.+ if (contribution.timestamp.localeCompare(current.lastActivity) > 0) {+ current.lastActivity = contribution.timestamp;+ }byAgent.set(agent, current);}}@@ -72,6 +81,8 @@ export function summarizeAgentSources(id,provider_ids: Object.freeze([...summary.providerIds].toSorted()),contribution_count: summary.contributionCount,+ last_activity: summary.lastActivity,+ identity_configured: isConfiguredAgentName(id),kinds: Object.freeze([...summary.kinds].toSorted()),topics: Object.freeze([...summary.topics].toSorted()),}),diff --git a/src/core/brain/agent-source/types.ts b/src/core/brain/agent-source/types.tsindex ed4f0bbc..632f059e 100644--- a/src/core/brain/agent-source/types.ts+++ b/src/core/brain/agent-source/types.ts@@ -18,13 +18,46 @@ export interface AgentSourceContribution {* at all (a log event), which is not owner-taggable by construction.*/readonly owner?: string;+ /**+ * Vault this contribution was mirrored from, when the record carries the+ * shared-namespace mirror's `origin_vault` attribution+ * (a-label-is-not-a-boundary, U5). Absent on locally written records,+ * which is every record on a vault with no shared namespace pointing at+ * it. This is the field's first reader anywhere in the repository: it was+ * written twice over and read nowhere.+ */+ readonly origin_vault?: string;readonly data: Readonly<Record<string, unknown>>;}+/**+ * One agent's row in the per-vault roster.+ *+ * The roster carries exactly TWO metrics, `contribution_count` and+ * `last_activity`, and the count of open units of work is deliberately not+ * a third: nothing in this product persists a unit of work with an+ * open/closed state - no task store, no todo, no assignment - so the number+ * could only be invented. A test asserts this type's key set rather than+ * the two metric names, so a third metric cannot appear without the+ * assertion changing with it.+ */export interface AgentSourceSummary {readonly id: string;readonly provider_ids: ReadonlyArray<string>;readonly contribution_count: number;+ /**+ * ISO timestamp of this agent's most recent contribution. Always present:+ * a row exists because something was written, so there is always a most+ * recent one.+ */+ readonly last_activity: string;+ /**+ * Whether `id` is a chosen identity or the placeholder every unconfigured+ * install writes under. Without it the roster folds every unconfigured+ * install into one row that reads as a single very busy agent, which is a+ * misleading non-empty - the same defect class as a misleading empty.+ */+ readonly identity_configured: boolean;readonly kinds: ReadonlyArray<AgentSourceContributionKind>;readonly topics: ReadonlyArray<string>;}diff --git a/src/core/brain/agent-source/vault-provider.ts b/src/core/brain/agent-source/vault-provider.tsindex 9d3f3c98..46b301a3 100644--- a/src/core/brain/agent-source/vault-provider.ts+++ b/src/core/brain/agent-source/vault-provider.ts@@ -118,6 +118,10 @@ function signalContribution(signal: BrainSignal): AgentSourceContribution {timestamp: signal.created_at,topic: signal.topic,...(signal.scope !== undefined ? { scope: signal.scope } : {}),+ // Attribution written by the shared-namespace mirror, surfaced here so+ // a shared vault's roster can say which vault a contribution came from+ // (a-label-is-not-a-boundary, U5).+ ...(signal.origin_vault !== undefined ? { origin_vault: signal.origin_vault } : {}),title: signal.topic,text: [signal.topic, signal.signal, signal.principle, signal.raw ?? ""].join("\n").trim(),data: {diff --git a/src/core/brain/backlinks.ts b/src/core/brain/backlinks.tsindex e9b0db31..0ec0be82 100644--- a/src/core/brain/backlinks.ts+++ b/src/core/brain/backlinks.ts@@ -21,14 +21,19 @@* fraction of `dream`'s cost; a smarter cache can land later if a* profile shows it pays.*- * Pure read. Skips files that fail to parse — `brain_doctor` is the- * surface that flags malformed artifacts, not this aggregator.+ * Pure read. `brain_doctor` is the surface that flags malformed+ * artifacts, not this aggregator — but an artifact this collector could+ * not parse is REPORTED here rather than skipped in silence, because a+ * dropped source produces a confidently wrong `count: 0` and the caller+ * has no way to tell that from a genuine zero+ * (a-label-is-not-a-boundary, U3; recon defect D4).*/import { existsSync, readdirSync } from "node:fs";import { join } from "node:path";import { parseFrontmatter } from "../vault.ts";+import { ownerScopeView } from "./owner-scope-view.ts";import { relationFromFrontmatterField } from "../graph/relation-vocab.ts";import { normalizeRelationTarget } from "../graph/frontmatter-relations.ts";import { buildAliasIndex } from "./link-graph/alias-index.ts";@@ -83,8 +88,56 @@ export interface BacklinkRef {readonly relation?: string;}-/** Frozen target → refs map. Keys are normalised wikilink targets. */-export type BacklinkIndex = ReadonlyMap<string, ReadonlyArray<BacklinkRef>>;+/**+ * One artifact whose references could not be collected, and why.+ *+ * `source` is the artifact id, never a host path: this record crosses the+ * MCP boundary through `brain_backlinks` and the contract at+ * `src/mcp/tools.ts:94-119` keeps absolute paths out of model context.+ */+export interface BacklinkParseFailure {+ /** Source id (basename without `.md`), as {@link BacklinkRef.source} spells it. */+ readonly source: string;+ /**+ * Which collector was reading it, in the SAME vocabulary+ * {@link BacklinkRef.sourceKind} uses - a failure and a ref describe+ * the same artifact, so a second spelling of "which lane" would be a+ * parallel vocabulary over one population. A log shard that cannot be+ * read has no event type to name, so it reports {@link LOG_READ_KIND}.+ */+ readonly sourceKind: BacklinkSourceKind;+ /** The failure's own message, with no host path in it. */+ readonly reason: string;+}++/**+ * `sourceKind` for a log shard whose entries could not be read at all.+ *+ * The per-ref form is `log-<eventType>`, and an unreadable shard has no+ * events to take a type from; this names the read itself instead, inside+ * the same `log-` namespace so no consumer needs a second branch.+ */+const LOG_READ_KIND = "log-read" as const;++/**+ * Frozen target → refs map, plus the artifacts the walk could not read.+ *+ * The failures ride on the index rather than in a second return value so+ * that the nine existing call sites keep compiling unchanged; the ones+ * that must report them read {@link BacklinkIndex.unparsed} and the rest+ * carry on using the map.+ */+export interface BacklinkIndex extends ReadonlyMap<string, ReadonlyArray<BacklinkRef>> {+ /**+ * Artifacts skipped because they could not be parsed.+ *+ * A `count: 0` beside a NON-EMPTY list here is not a measurement, and+ * a surface reporting the count must say so — the same distinction+ * `listDanglingTargets` draws between "measured zero" and "could not+ * measure". Empty on a healthy vault, so a clean payload is unchanged.+ */+ readonly unparsed: ReadonlyArray<BacklinkParseFailure>;+}// ----- Public API ----------------------------------------------------------@@ -94,10 +147,18 @@ export type BacklinkIndex = ReadonlyMap<string, ReadonlyArray<BacklinkRef>>;* The returned map is frozen and each entry's array is frozen too —* callers cannot mutate the shared index. Recompute by calling this* function again; there is no incremental update path on purpose.+ *+ * `ownerScope` (optional, second) drops every ref whose SOURCE artifact+ * the scope may not see, and drops it from `unparsed` too — an artifact+ * whose owner is unknowable is somebody else's, so naming it in a failure+ * report would leak exactly what the filter withheld. Absent (every+ * existing call site) means no ownership filtering at all.*/-export function buildBacklinkIndex(vault: string): BacklinkIndex {+export function buildBacklinkIndex(vault: string, ownerScope?: string | null): BacklinkIndex {const dirs = brainDirs(vault);+ const view = ownerScopeView(vault, ownerScope ?? null);const aliasIndex = buildAliasIndex(vault);+ const unparsed: BacklinkParseFailure[] = [];const map = new Map<string, BacklinkRef[]>();// Dedup key: `<source>\x00<canonical>\x00<anchor>\x00<block>`.// Anchor + block are part of the dedup key so two refs to@@ -106,6 +167,9 @@ export function buildBacklinkIndex(vault: string): BacklinkIndex {const seen = new Set<string>();const push = (target: string, ref: BacklinkRef): void => {+ // The SOURCE decides visibility: a ref names the artifact that wrote+ // it, so publishing one publishes that artifact's id.+ if (!view.visible(ref.source)) return;const parsed = parseWikilinkRich(target);const bare = parsed.target;if (!bare) return;@@ -140,17 +204,28 @@ export function buildBacklinkIndex(vault: string): BacklinkIndex {else map.set(canonicalId, [enriched]);};- collectPreferences(dirs.preferences, "preference", push);- collectPreferences(dirs.retired, "retired", push);- collectSignals(dirs.inbox, push);- collectSignals(dirs.processed, push);- collectLog(vault, dirs.log, push);+ const fail = (row: BacklinkParseFailure): void => {+ if (!view.visible(row.source)) return;+ unparsed.push(Object.freeze(row));+ };++ collectPreferences(dirs.preferences, "preference", push, fail);+ collectPreferences(dirs.retired, "retired", push, fail);+ collectSignals(dirs.inbox, push, fail);+ collectSignals(dirs.processed, push, fail);+ collectLog(vault, dirs.log, push, fail);// Freeze each entry's array so downstream callers can't mutate the// shared index.const frozen = new Map<string, ReadonlyArray<BacklinkRef>>();for (const [k, v] of map) frozen.set(k, Object.freeze(v));- return frozen;+ return Object.assign(frozen, { unparsed: Object.freeze(unparsed) });+}++/** The failure's own message, never the host path it happened at. */+function failureReason(err: unknown, path: string): string {+ const raw = err instanceof Error ? err.message : String(err);+ return raw.split(path).join("").replaceAll(" ()", "").trim();}/**@@ -169,6 +244,7 @@ function collectPreferences(dir: string,kind: "preference" | "retired",push: (target: string, ref: BacklinkRef) => void,+ fail: (row: BacklinkParseFailure) => void,): void {if (!existsSync(dir)) return;for (const name of readdirSync(dir)) {@@ -190,7 +266,13 @@ function collectPreferences(// building.meta = normalizeDerivedKeys(rawMeta);body = rawBody;- } catch {+ } catch (err) {+ // The row still aborts - the fields cannot be read - but it aborts+ // LOUDLY. `normalizeDerivedKeys` throws on the un-prefixed Group C+ // shape a legacy vault is full of, and the silent `continue` this+ // replaced produced an index missing every preference-sourced ref+ // with no diagnostic anywhere.+ fail({ source, sourceKind: kind, reason: failureReason(err, full) });continue;}@@ -237,7 +319,11 @@ function collectPreferences(}}-function collectSignals(dir: string, push: (target: string, ref: BacklinkRef) => void): void {+function collectSignals(+ dir: string,+ push: (target: string, ref: BacklinkRef) => void,+ fail: (row: BacklinkParseFailure) => void,+): void {if (!existsSync(dir)) return;for (const name of readdirSync(dir)) {if (!name.endsWith(".md")) continue;@@ -252,7 +338,8 @@ function collectSignals(dir: string, push: (target: string, ref: BacklinkRef) =>for (const body0 of extractWikilinkRichBodies(body)) {push(body0, { source, sourceKind: "signal", field: "body" });}- } catch {+ } catch (err) {+ fail({ source, sourceKind: "signal", reason: failureReason(err, full) });continue;}}@@ -262,6 +349,7 @@ function collectLog(vault: string,dir: string,push: (target: string, ref: BacklinkRef) => void,+ fail: (row: BacklinkParseFailure) => void,): void {if (!existsSync(dir)) return;// Shard-aware (Memory Integrity Suite): merged per-day reads. List the@@ -275,7 +363,8 @@ function collectLog(let entries;try {entries = readLogDay(vault, date, shards).entries;- } catch {+ } catch (err) {+ fail({ source, sourceKind: LOG_READ_KIND, reason: failureReason(err, dir) });continue;}for (const e of entries) {diff --git a/src/core/brain/claude-memory-render.ts b/src/core/brain/claude-memory-render.tsindex cacb6bf0..b2a5ef9a 100644--- a/src/core/brain/claude-memory-render.ts+++ b/src/core/brain/claude-memory-render.ts@@ -5,6 +5,8 @@ export interface RenderMemoryInput {readonly memoryPath: string;readonly importedAt: string; // ISO Zreadonly bodySha256: string;+ /** Owner token for the rendered page; omitted renders no `owner:`. */+ readonly owner?: string | undefined;}/**@@ -73,6 +75,10 @@ export function renderPreferenceFromMemory(input: RenderMemoryInput): string {"_confidence: high","pinned: false",`scope: ${scope}`,+ // Ownership, on the same terms every other preference writer uses.+ // Absent when the gate is off, so a vault that never opted in keeps+ // byte-identical imports.+ ...(input.owner === undefined ? [] : [`owner: ${input.owner}`]),"_force_confirmed_via: claude-memory",`_imported_from: ${JSON.stringify(input.memoryPath)}`,`_imported_sha256: ${input.bodySha256}`,diff --git a/src/core/brain/derived-fact.ts b/src/core/brain/derived-fact.tsindex dda017b7..042e0cfa 100644--- a/src/core/brain/derived-fact.ts+++ b/src/core/brain/derived-fact.ts@@ -35,6 +35,13 @@ export interface DeriveFactInput {export interface DeriveFactOptions {readonly now: Date;+ /**+ * Plugin config the writing agent's identity is resolved from when the+ * ownership gate stamps the new preference. Absent falls back to the+ * default config discovery; a surface running against a non-default+ * config passes its own.+ */+ readonly configPath?: string;}export interface DeriveFactResult {@@ -132,16 +139,20 @@ export function deriveFact(}const now = opts.now;- writePreference(vault, {- slug: input.slug,- topic: input.topic,- principle: input.principle,- created_at: isoSecond(now),- unconfirmed_until: isoSecond(addDays(now, unconfirmedWindowDays(vault))),- status: "unconfirmed",- evidenced_by: evidencedBy,- provenance: level,- });+ writePreference(+ vault,+ {+ slug: input.slug,+ topic: input.topic,+ principle: input.principle,+ created_at: isoSecond(now),+ unconfirmed_until: isoSecond(addDays(now, unconfirmedWindowDays(vault))),+ status: "unconfirmed",+ evidenced_by: evidencedBy,+ provenance: level,+ },+ opts.configPath !== undefined ? { configPath: opts.configPath } : {},+ );return { id: `pref-${input.slug.trim()}` };}diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.tsindex 85b410ea..6e34a174 100644--- a/src/core/brain/diagnostics.ts+++ b/src/core/brain/diagnostics.ts@@ -59,8 +59,10 @@ import {ENTITY_QUOTE_VARIANT_COLLISION_COMMAND,} from "./entities/canonical.ts";import { scanDanglingWorkruns, WORKRUN_PHASE } from "./dream-workrun.ts";+import { extractWikilinkRichBodies, parseWikilinkRich } from "./link-graph/parse-wikilink.ts";import { LINT_CONSOLIDATE_KIND } from "./lint-consolidate.ts";import { appendLogEvent } from "./log.ts";+import { ownerScopeView } from "./owner-scope-view.ts";import { acquireLockSync } from "./sync-lockfile.ts";import { isoSecond } from "./time.ts";import { BRAIN_LOG_EVENT_KIND, type DoctorIssue } from "./types.ts";@@ -1134,6 +1136,33 @@ export interface ApplyRepairOptions {readonly agent?: string;/** Config path for the agent-name resolver. */readonly configPath?: string;+ /**+ * Owner scope the repair is bounded by (a-label-is-not-a-boundary,+ * U3). Absent / `null` repairs everything, which is what the CLI and+ * every pre-gate caller get.+ *+ * Bounds the PLAN, not the report. `toolBrainDoctor` filters the+ * diagnostic streams it returns, and the repair branch returned before+ * reaching that filter - so a caller scoped to one owner both read and+ * REWROTE another owner's preferences, pruning their frontmatter and+ * logging a `doctor-repair` event for each. Filtering the outcome+ * afterwards would have hidden the second half while still doing it.+ */+ readonly ownerScope?: string | null;+}++/**+ * Every artifact one planned fix would name.+ *+ * `target` is a stable identifier whose first `::` segment is the+ * vault-relative page ({@link RepairItem.target}); `detail` spells the+ * same page and the reference being pruned in prose, as wikilinks. Both+ * are asked, because a fix that survives on one and discloses on the+ * other is not filtered.+ */+function repairRefs(item: RepairItem): ReadonlyArray<string> {+ const page = item.target.split("::", 1)[0]!;+ return [page, ...extractWikilinkRichBodies(item.detail).map((b) => parseWikilinkRich(b).target)];}/**@@ -1150,8 +1179,10 @@ export function applyRepair(vault: string, opts: ApplyRepairOptions): RepairOutc// section of `applier-capability.ts`.if (opts.dryRun !== true) assertVaultIdentityForWrite(vault);const plan = planRepair(vault);- const needsReview = plan.fixes.filter((f) => !f.applicable);- const applicable = plan.fixes.filter((f) => f.applicable);+ const view = ownerScopeView(vault, opts.ownerScope ?? null);+ const fixes = view.keep(plan.fixes, repairRefs);+ const needsReview = fixes.filter((f) => !f.applicable);+ const applicable = fixes.filter((f) => f.applicable);if (opts.dryRun) {const applied = applicable.map((f) => ({ code: f.code, target: f.target, detail: f.detail }));diff --git a/src/core/brain/event-trace.ts b/src/core/brain/event-trace.tsindex 5a7a78bd..fbbbf190 100644--- a/src/core/brain/event-trace.ts+++ b/src/core/brain/event-trace.ts@@ -34,6 +34,7 @@*/import { readLogDay } from "./log-jsonl.ts";+import { ownerScopeView } from "./owner-scope-view.ts";import type { BrainLogEntry, BrainLogEntryPayload } from "./log.ts";import { loadNormalizedContinuityRecords } from "./continuity/read-model.ts";import type { NormalizedContinuityRecord } from "./continuity/read-model.ts";@@ -84,6 +85,18 @@ export interface EventTraceSelector {readonly limit?: number;/** Keep continuity records flagged `private` (default: drop them). */readonly keepPrivate?: boolean;+ /**+ * Owner scope the trace is filtered against+ * (a-label-is-not-a-boundary, U3). Absent / `null` filters nothing.+ *+ * An event's `body` is echoed VERBATIM, so no allowlist of payload keys+ * can bound what it discloses - `path` alone is outside+ * {@link ARTIFACT_BODY_KEYS} and carried a preference path in the sweep+ * that found this. Every string in the body is therefore asked about,+ * and one hidden reference drops the whole event: a log line about an+ * artifact this caller may not see is a log line about that artifact.+ */+ readonly ownerScope?: string | null;}/** One continuity record attached to a log event, with the join provenance. */@@ -197,6 +210,7 @@ export function resolveLogEventTraces(}const { entries } = readLogDay(vault, date);+ const view = ownerScopeView(vault, selector.ownerScope ?? null);const records = loadNormalizedContinuityRecords(vault,selector.keepPrivate === true ? { keepPrivate: true } : {},@@ -213,6 +227,7 @@ export function resolveLogEventTraces(if (wantStamp !== undefined && entry.timestamp !== wantStamp) continue;const correlation = extractEventCorrelation(entry);if (selector.sessionId !== undefined && correlation.sessionId !== selector.sessionId) continue;+ if (!view.row(...correlation.artifacts, ...bodyStrings(entry.body))) continue;if (cap !== undefined && results.length >= cap) break;const traces = attachTracesToEvent(records, correlation);results.push({@@ -234,6 +249,23 @@ export function resolveLogEventTraces(// ----- internals ------------------------------------------------------------+/**+ * Every string an event body would print, scalars and array items alike.+ *+ * Deliberately not keyed on {@link ARTIFACT_BODY_KEYS}: that list bounds+ * which keys the CORRELATION reads, while the body is echoed whole, so a+ * key nobody thought to add to the list still reaches the caller.+ */+function bodyStrings(body: BrainLogEntryPayload): ReadonlyArray<string> {+ const out: string[] = [];+ for (const value of Object.values(body)) {+ for (const item of Array.isArray(value) ? value : [value]) {+ if (typeof item === "string" && item.length > 0) out.push(item);+ }+ }+ return out;+}+function joinReasons(record: NormalizedContinuityRecord,correlation: EventCorrelation,diff --git a/src/core/brain/explorer.ts b/src/core/brain/explorer.tsindex 2ffb8463..6eb25ea0 100644--- a/src/core/brain/explorer.ts+++ b/src/core/brain/explorer.ts@@ -16,10 +16,15 @@* `(source, target, kind)`. The collector emits a frozen object so* the live HTTP handler and the static export branch cannot* accidentally mutate it.+ *+ * A file that cannot be parsed is REPORTED on the graph+ * ({@link ExplorerParseFailure}), never dropped. This surface both+ * displays the graph and exports it, and a graph silently missing a rule+ * is indistinguishable from a vault that never had one.*/import { existsSync, readFileSync, readdirSync } from "node:fs";-import { basename, dirname, join, resolve } from "node:path";+import { basename, dirname, join, relative, resolve } from "node:path";import { fileURLToPath } from "node:url";import { buildBacklinkIndex, type BacklinkIndex } from "./backlinks.ts";@@ -64,12 +69,33 @@ export interface ExplorerEdge {readonly relation?: string;}+/**+ * A file under `Brain/preferences/` or `Brain/retired/` that could not be+ * parsed into a node.+ *+ * The collector used to skip these silently, on the reasoning that the+ * doctor reports parse-level corruption. That reasoning holds for a VIEW+ * and fails for an EXPORT: a graph missing a rule reads exactly like a+ * vault that never had it, and the file that carries the answer is the one+ * the reader no longer has. So the collector carries the failure out and+ * the caller decides - which for every path that writes bytes outward is+ * to refuse and name the file.+ */+export interface ExplorerParseFailure {+ /** Vault-relative path, so the message names a file the operator can open. */+ readonly path: string;+ /** The parser's own message. Never flattened to "failed". */+ readonly reason: string;+}+export interface ExplorerGraph {readonly generated_at: string;readonly schema_version: typeof EXPLORER_SCHEMA_VERSION;readonly vault_basename: string;readonly nodes: ReadonlyArray<ExplorerNode>;readonly edges: ReadonlyArray<ExplorerEdge>;+ /** Empty on a healthy vault; never absent, so a reader cannot miss it. */+ readonly parse_failures: ReadonlyArray<ExplorerParseFailure>;}export interface CollectExplorerDataOptions {@@ -90,6 +116,13 @@ export function collectExplorerData(const nodes: ExplorerNode[] = [];const knownIds = new Set<string>();+ const parseFailures: ExplorerParseFailure[] = [];+ const recordFailure = (path: string, err: unknown): void => {+ parseFailures.push({+ path: relative(vault, path),+ reason: err instanceof Error ? err.message : String(err),+ });+ };if (existsSync(dirs.preferences)) {for (const entry of readdirSync(dirs.preferences, {@@ -102,9 +135,8 @@ export function collectExplorerData(const pref = parsePreference(path);nodes.push(nodeFromPreference(pref, countFor(pref.id)));knownIds.add(pref.id);- } catch {- // Doctor reports parse-level corruption; the explorer skips- // silently so one bad file does not blank the whole graph.+ } catch (err) {+ recordFailure(path, err);}}}@@ -118,11 +150,12 @@ export function collectExplorerData(const ret = parseRetired(path);nodes.push(nodeFromRetired(ret, countFor(ret.id)));knownIds.add(ret.id);- } catch {- // ditto+ } catch (err) {+ recordFailure(path, err);}}}+ parseFailures.sort((a, b) => a.path.localeCompare(b.path));// Edges derived from the backlink index. The index maps// `target → ref[]` where each ref carries `source` + `field`.@@ -152,6 +185,7 @@ export function collectExplorerData(vault_basename: basename(vault),nodes: Object.freeze(nodes),edges: Object.freeze(edges),+ parse_failures: Object.freeze(parseFailures),});}diff --git a/src/core/brain/export.ts b/src/core/brain/export.tsindex 4fbb0b1b..5a5da437 100644--- a/src/core/brain/export.ts+++ b/src/core/brain/export.ts@@ -17,8 +17,9 @@*/import { existsSync, readdirSync } from "node:fs";-import { join } from "node:path";+import { join, relative } from "node:path";+import { hostPathFreeReason } from "./host-path-free.ts";import { parsePreference } from "./preference.ts";import { brainDirs } from "./paths.ts";import { vaultDisplayName } from "./templates.ts";@@ -28,6 +29,57 @@ import { parseFrontmatter } from "../vault.ts";export const BRAIN_EXPORT_SCHEMA_VERSION = 1 as const;+/** How many unreadable files the error names before it stops listing. */+const MAX_NAMED_PARSE_FAILURES = 10;++/**+ * One preference file the collector could not turn into a row, named the+ * way the operator sees it - relative to the vault, so the message is the+ * path they can open. Same shape as `ExplorerParseFailure`, because the+ * two surfaces report the same event over the same directory.+ */+export interface PreferenceParseFailure {+ readonly path: string;+ readonly reason: string;+}++/**+ * A preference file that could not be read into a row.+ *+ * Raised rather than skipped. The collector used to `continue` past a+ * caught parse error, which produced `"preferences": []` on a vault that+ * held rules, under exit code 0 and an empty stderr - an export that omits+ * a rule reads exactly like a vault that never had it, and the file that+ * would say otherwise is the one the recipient does not have. Every caller+ * of {@link collectExportRows} is composing something for a reader+ * (a bundle, a context pack, the topic map an import merges against), so+ * there is no caller for whom a shorter list is the right answer.+ */+export class PreferenceParseError extends Error {+ /** Vault-relative paths that failed, with the parser's own message. */+ readonly failures: ReadonlyArray<PreferenceParseFailure>;+ constructor(failures: ReadonlyArray<PreferenceParseFailure>) {+ const named = failures+ .slice(0, MAX_NAMED_PARSE_FAILURES)+ .map((f) => `${f.path} (${f.reason})`)+ .join("; ");+ const rest =+ failures.length > MAX_NAMED_PARSE_FAILURES+ ? ` and ${failures.length - MAX_NAMED_PARSE_FAILURES} more`+ : "";+ super(+ // Not "this export": the same collector backs the import's+ // topic map, and an import told its EXPORT is incomplete sends+ // the operator to the wrong end of the round trip.+ `${failures.length} preference file(s) could not be parsed, so Brain/preferences/ ` ++ `cannot be read completely: ${named}${rest}. Repair or remove them, then re-run; ` ++ "`o2b brain doctor` reports the same files.",+ );+ this.name = "PreferenceParseError";+ this.failures = failures;+ }+}+export type ExportFormat = "json" | "llms-txt";export interface ExportedPreferenceRow {@@ -80,48 +132,113 @@ export interface ExportedPreferencesJson {readonly preferences: ReadonlyArray<ExportedPreferenceRow>;}+/**+ * Every row the walk produced, and every file it could not read.+ *+ * The pair, never one of them: a caller holding this has been told both+ * how much it got and how much it missed, which is the property+ * {@link collectExportRows}' refusal enforces for callers that cannot use+ * a partial answer.+ */+export interface PreferenceCollection {+ readonly rows: ReadonlyArray<ExportedPreferenceRow>;+ readonly failures: ReadonlyArray<PreferenceParseFailure>;+}+/*** Walk `Brain/preferences/`, parse every `pref-*.md`, and project to* the export row shape sorted by `id` for deterministic output.- * Files that fail to parse are silently skipped — the doctor surface- * is the canonical place for surfacing those, not the read-only- * exporter.+ *+ * A file that cannot be read raises {@link PreferenceParseError} rather+ * than being skipped. Every failure in the directory is collected first,+ * so one run names all of them instead of making the operator repair one+ * file per re-run.+ *+ * @throws PreferenceParseError when any `pref-*.md` in the directory+ * cannot be parsed into a row.*/export function collectExportRows(vault: string): ReadonlyArray<ExportedPreferenceRow> {+ const { rows, failures } = collectPreferenceRows(vault);+ if (failures.length > 0) throw new PreferenceParseError(failures);+ return rows;+}++/**+ * The same walk, reporting its failures instead of raising them.+ *+ * Reserved for a caller that has a use for a partial answer AND reports+ * the gap. There is exactly one - the bank import's prior-topic map, which+ * reads the DESTINATION vault to learn which topics existing rules already+ * claim. `collectExportRows`' refusal is right for an export and wrong+ * there: one malformed rule already sitting in the destination would abort+ * an entire import, wholesale, on a condition unrelated to the bundle+ * being carried.+ *+ * Taking the failures without rendering them is the silent-drop defect+ * this module's refusal exists to prevent, so+ * {@link PreferenceRestoreResult.topicScanUnreadable} carries them all the+ * way to the operator's terminal.+ *+ * The directory LISTING failure still raises: it is a permission or+ * filesystem fault over the whole directory, not a per-file parse, and no+ * partial answer exists to give.+ */+export function collectPreferenceRows(vault: string): PreferenceCollection {const dir = brainDirs(vault).preferences;- if (!existsSync(dir)) return [];+ if (!existsSync(dir)) return { rows: [], failures: [] };const rows: ExportedPreferenceRow[] = [];+ const failures: PreferenceParseFailure[] = [];let entries: ReadonlyArray<string>;try {entries = readdirSync(dir);- } catch {- return [];+ } catch (err) {+ // The directory exists - `existsSync` just said so - so a listing+ // failure is a permission or filesystem fault, not an empty Brain.+ // Returning `[]` here reported the second while the first was true.+ // Named vault-relative for the same reason the per-file failures are:+ // this collector is reachable from an MCP error path.+ const rel = relative(vault, dir);+ throw new Error(`cannot list ${rel}: ${hostPathFreeReason(err, vault, dir, rel)}`, {+ cause: err,+ });}for (const name of entries) {if (!name.startsWith("pref-") || !name.endsWith(".md")) continue;const abs = join(dir, name);+ const record = (err: unknown): void => {+ const rel = relative(vault, abs);+ // The parser's own message carries the absolute host path+ // (`BrainParseError` composes `<detail> (<path>)`, and a raw `node:fs`+ // failure embeds it too), and this refusal is reachable from an MCP+ // error path, where `src/mcp/tools.ts` forbids one. The `path` field+ // beside it is already vault-relative; the reason now matches.+ failures.push({ path: rel, reason: hostPathFreeReason(err, vault, abs, rel) });+ };let pref: BrainPreference;try {pref = parsePreference(abs);- } catch {+ } catch (err) {+ record(err);continue;}// `parsePreference` deliberately drops the body. We re-parse the// file here to capture the markdown sections the agent wrote// (`## Principle`, `## Origin`, …) — those are the bytes a// consumer wants when sharing or system-prompt-injecting the- // rule. A read failure here drops the row entirely.+ // rule. A read failure here is the same defect as a frontmatter+ // one: the row would go out missing what the agent wrote.let body = "";try {const [, parsedBody] = parseFrontmatter(abs);body = parsedBody;- } catch {+ } catch (err) {+ record(err);continue;}rows.push(toRow(pref, body));}rows.sort((a, b) => a.id.localeCompare(b.id));- return rows;+ return { rows, failures };}function toRow(p: BrainPreference, body: string): ExportedPreferenceRow {diff --git a/src/core/brain/gaps/gap-loop.ts b/src/core/brain/gaps/gap-loop.tsindex ef48acd1..42f74030 100644--- a/src/core/brain/gaps/gap-loop.ts+++ b/src/core/brain/gaps/gap-loop.ts@@ -35,7 +35,7 @@ import { assertVaultIdentityForWrite } from "../vault-identity.ts";import { aggregateUnmetRecall } from "../query-demand.ts";import { summarizeRecallTelemetry } from "../recall-telemetry.ts";import { renderActivityTimeline, type ActivityItem } from "../render/activity-line.ts";-import type { RecallRetriever } from "../recall-inject.ts";+import type { RecallResultSet, RecallRetriever } from "../recall-inject.ts";import { isFileAlreadyExists } from "../../fs-atomic.ts";import { parseFrontmatterText, writeFrontmatterAtomic } from "../../vault.ts";import type { FrontmatterMap } from "../../types.ts";@@ -43,7 +43,20 @@ import type { FrontmatterMap } from "../../types.ts";/** Default recurrence threshold: a gap must recur this often to promote. */export const GAP_LOOP_RECURRENCE_THRESHOLD = 3;-/** Default normalized-score floor a recall must clear to auto-close a task. */+/**+ * Default match-quality floor a recall must clear to auto-close a task.+ *+ * Compared against {@link RecallResultSet.idfWeightedCoverage} - the share+ * of the topic's IDF mass the vault now covers - and not against a result+ * score. Against a score this floor could never refuse anything: the+ * keyword lane min-max normalises within the candidate set, so the top+ * row of ANY recall with a non-empty keyword lane scores at or above the+ * configured `keywordWeight` (`DEFAULT_KEYWORD_WEIGHT`, 0.6 by default,+ * measured at 0.65 on a freshly written keyword-only vault once the+ * freshness prior is added on top), which clears 0.5 whatever the hit was+ * worth. A gap task therefore auto-closed on the first keyword match of+ * any quality, which is the outcome this floor exists to prevent.+ */export const GAP_LOOP_AUTO_CLOSE_FLOOR = 0.5;/**@@ -376,6 +389,46 @@ export function renderGapAgenda(vault: string, now: Date): string {return `# Open recall-gap tasks\n${renderActivityTimeline(items, now)}`;}+/**+ * Retrieval for the auto-close gate: the topic, and the membership rule+ * the answer will be judged by.+ *+ * The predicate is an ARGUMENT rather than a post-filter the loop applies+ * afterwards, and that is the whole point. A gap-task note carries its own+ * topic verbatim, so it matches its own recall better than anything else+ * in the vault. Filtering it out of the returned rows afterwards - which+ * is what this gate used to do - removes it from the membership test and+ * leaves it inside the number: `idfWeightedCoverage` is computed over the+ * rows the retrieval returned, so the note the loop is trying not to count+ * was still supplying the IDF mass the floor read. Every task then cleared+ * the floor on its own text.+ *+ * So the rule travels WITH the query, and the two answers - "is there+ * anything" and "how much of the topic does it cover" - are measured over+ * one row set. A retriever that returns a row the predicate rejects has+ * measured something else, and {@link autoCloseRecalledGaps} refuses its+ * answer by name rather than reading the number anyway.+ *+ * A plain {@link RecallRetriever} is still assignable (it ignores the+ * second argument) and is still correct for a retrieval that cannot+ * surface a rejected path at all - which is what the vault-identity+ * guard's fixture is.+ */+export type GapRecallRetriever = (+ topic: string,+ admits: (path: string) => boolean,+) => Promise<RecallResultSet>;++/** Thrown when a {@link GapRecallRetriever} answers outside its membership rule. */+export class GapRecallScopeError extends Error {+ constructor(topic: string, paths: ReadonlyArray<string>) {+ super(+ `gap auto-close: retriever for "${topic}" returned ${paths.length} row(s) the membership rule excludes (${paths.join(", ")}); its match quality measures rows the gate rejected`,+ );+ this.name = "GapRecallScopeError";+ }+}+export interface GapAutoCloseResult {/** Keys of gap tasks closed by this run. */readonly closed: ReadonlyArray<string>;@@ -384,15 +437,29 @@ export interface GapAutoCloseResult {}/**- * Auto-close every open gap task whose topic now recalls at or above the- * confidence floor, flipping its frontmatter status to closed and stamping- * `closed_at` / `closed_reason` (mirroring the dream freshness auto-resolve- * precedent). A recall that fails or stays below the floor keeps the task+ * Auto-close every open gap task whose topic the vault now covers at or+ * above the match-quality floor, flipping its frontmatter status to closed+ * and stamping `closed_at` / `closed_reason` (mirroring the dream freshness+ * auto-resolve precedent). A recall that fails, returns nothing outside the+ * gap-task directory, or covers the topic below the floor keeps the task* open - fail-safe, never a silent close.+ *+ * Two conditions, deliberately separate. The gap-task notes themselves are+ * excluded by PATH, because a task note carries its own topic verbatim and+ * would otherwise close itself; that is a membership rule, and expressing+ * it as "its score must clear a floor" is what let the floor pretend to be+ * a quality test while only ever testing presence. The floor then judges+ * the quality of the retrieval, which it reads from the retrieval itself.+ *+ * Both conditions are measured over ONE row set - see+ * {@link GapRecallRetriever} for why the membership rule is handed to the+ * retriever instead of applied to its answer. An unmeasurable match+ * quality never closes a task: "the vault covers this" is a claim, and a+ * retrieval that could not weigh the topic has not made it.*/export async function autoCloseRecalledGaps(vault: string,- retriever: RecallRetriever,+ retriever: GapRecallRetriever,opts: { confidenceFloor?: number; now: Date },): Promise<GapAutoCloseResult> {// Vault-identity write guard (context-integrity-gates, Unit J), like@@ -403,21 +470,29 @@ export async function autoCloseRecalledGaps(const closed: string[] = [];const kept: string[] = [];for (const task of listGapTasks(vault, { status: GAP_TASK_STATUS_OPEN })) {- let topScore = 0;+ let coveredElsewhere = false;+ let matchQuality: number | null = null;+ let result: RecallResultSet | null = null;try {// eslint-disable-next-line no-await-in-loop -- one recall per open task, sequential by design- const set = await retriever(task.topic);- // Exclude the gap-task notes themselves: a task note carries its own- // topic verbatim, so counting it would self-close every gap. Only- // genuine vault coverage elsewhere may close a task.- topScore = set.candidates- .filter((candidate) => !isGapTaskPath(candidate.path))- .reduce((max, candidate) => Math.max(max, candidate.score), 0);+ result = await retriever(task.topic, admitsGapCoverageRow);} catch {kept.push(task.key);continue;}- if (topScore >= floor) {+ // Outside the catch: a retriever that answered outside its membership+ // rule is a broken caller, not a failed recall, and folding it into+ // "keep the task open" would hide it behind the fail-safe path.+ const rejected = result.candidates+ .map((candidate) => candidate.path)+ .filter((path) => !admitsGapCoverageRow(path));+ if (rejected.length > 0) throw new GapRecallScopeError(task.topic, rejected);+ // Only genuine vault coverage elsewhere may close a task - and the+ // quality now describes the same rows, because the retriever was told+ // which rows count before it measured them.+ coveredElsewhere = result.candidates.length > 0;+ matchQuality = result.idfWeightedCoverage;+ if (coveredElsewhere && matchQuality !== null && matchQuality >= floor) {closeGapTask(task, opts.now);closed.push(task.key);} else {@@ -446,3 +521,12 @@ function stringField(value: unknown): string {function isGapTaskPath(path: string): boolean {return path.includes(BRAIN_GAP_TASKS_REL);}++/**+ * The membership rule the auto-close gate judges by, as the predicate a+ * {@link GapRecallRetriever} receives. One definition, used both to shape+ * the retrieval and to verify what came back, so the two cannot disagree.+ */+function admitsGapCoverageRow(path: string): boolean {+ return !isGapTaskPath(path);+}diff --git a/src/core/brain/gaps/gap-recall.ts b/src/core/brain/gaps/gap-recall.tsnew file mode 100644index 00000000..71d290b3--- /dev/null+++ b/src/core/brain/gaps/gap-recall.ts@@ -0,0 +1,149 @@+/**+ * Gap-scoped recall: the {@link GapRecallRetriever} the auto-close gate+ * runs against a real vault (theme A, t_67d38036).+ *+ * The gate hands the retriever the membership rule the answer will be+ * judged by, and refuses by name any answer that contains a row the rule+ * excludes. A plain {@link defaultRecallRetriever} is structurally+ * assignable to that type - TypeScript accepts a one-parameter function+ * where a two-parameter one is wanted - but it ignores the predicate, so+ * it returns the gap-task note itself and the gate throws. This module is+ * the retriever that actually honours the rule.+ *+ * ## Why the coverage is recomputed rather than reused+ *+ * `SearchOutcome.idfWeightedCoverage` is measured over the rows the search+ * returned. Drop a row and reuse that number and the gate reads a match+ * quality that includes the very row the membership rule exists to+ * exclude - a gap-task note carries its own topic verbatim, so it is+ * usually the strongest row in the set, and the floor would clear on the+ * task's own text. So the number is rebuilt over exactly the rows this+ * retriever returns, through {@link coverageOverResults}, on ONE path: the+ * quantity always describes the returned rows, whether or not anything was+ * dropped, so the two cases cannot drift apart.+ *+ * ## Why not shape the retrieval instead+ *+ * The tempting alternative is to make the excluded rows unreachable by the+ * query, so the search's own coverage is already over admitted rows only,+ * and `resolveSearchConfig` does accept `scopeRules`. It was rejected on+ * the facts: `ResolvedSearchConfig.scopeRules` is read in exactly one+ * place, `walkVaultScope` in `src/core/search/walker.ts`, which is the+ * INDEXER's walk. Query time never consults it. Passing exclusion rules+ * here would therefore (a) change nothing for the normal case of an index+ * that already exists, and (b) when a self-heal did rebuild, write a+ * shared index with the gap tasks missing from it - breaking every other+ * search of the vault to serve this gate. `SearchOptions` has a positive+ * `pathPrefix` but no exclusion, so there is no query-time way to shape+ * the row set. Recomputation is the only honest option available.+ *+ * The third option - reporting `null` coverage whenever a row was dropped+ * - is not implemented anywhere here on purpose: a gap task matches its+ * own topic almost every time, so "unmeasurable whenever something was+ * dropped" would be "unmeasurable always", and auto-close would be a+ * feature that never fires while looking like one that works.+ */++import { resolve } from "node:path";++import { searchAcrossVaults } from "../../search/cross-vault.ts";+import { coverageOverResults } from "../../search/evidence-verification.ts";+import { resolveSearchConfig } from "../../search/index.ts";+import { Store } from "../../search/store.ts";+import type { BrainSearchResult, ResolvedSearchConfig } from "../../search/types.ts";+import type { RecallCandidate } from "../recall-inject.ts";+import type { GapRecallRetriever } from "./gap-loop.ts";++/** Admitted rows one gap recall reports; the gate only needs a handful. */+export const GAP_RECALL_MAX_ROWS = 4;++/**+ * How many rows are fetched per admitted row wanted.+ *+ * The exclusion happens after ranking (see above: there is no query-time+ * way to shape it), so every excluded row occupies a slot the admitted+ * rows needed. Without over-fetch a vault holding several gap tasks whose+ * topics overlap could fill the whole window with notes the gate rejects+ * and report "nothing covers this" over a vault that covers it well.+ */+export const GAP_RECALL_OVERFETCH = 4;++/**+ * A retriever for {@link autoCloseRecalledGaps} that answers strictly+ * inside the membership rule it is handed: the rows it returns are+ * admitted rows, and its `idfWeightedCoverage` measures those same rows.+ *+ * Coverage is weighed against the ACTIVE vault's corpus statistics, which+ * is the corpus the gap task itself belongs to. The union may surface rows+ * from read-only recall sources; `searchAcrossVaults` already folds+ * per-origin coverages measured on per-origin corpora, so one IDF scale+ * for the merged window is if anything the more coherent number.+ *+ * A coverage that cannot be measured at all - the index will not open, or+ * the topic carries no IDF mass - is reported as `null`, which keeps the+ * task open. That is the fail-safe the gate documents, and it is reached+ * only by an unmeasurable retrieval, never by the ordinary act of dropping+ * a row.+ */+export function gapScopedRecallRetriever(+ configPath: string,+ vault: string,+ limit: number = GAP_RECALL_MAX_ROWS,+): GapRecallRetriever {+ const activeVault = resolve(vault);+ return async (topic, admits) => {+ const config = resolveSearchConfig({ vault: activeVault, configPath });+ const outcome = await searchAcrossVaults(+ configPath,+ activeVault,+ { query: topic, limit: Math.max(1, limit) * GAP_RECALL_OVERFETCH },+ config,+ );+ const admitted = outcome.results+ .filter((result) => admits(result.path))+ .slice(0, Math.max(1, limit));+ return Object.freeze({+ candidates: Object.freeze(admitted.map(toRecallCandidate)),+ total: outcome.total,+ idfWeightedCoverage: await coverageOverAdmitted(config, topic, admitted),+ });+ };+}++function toRecallCandidate(result: BrainSearchResult): RecallCandidate {+ return Object.freeze({+ path: result.path,+ title: result.title,+ score: result.score,+ searchType: result.searchType,+ startLine: result.startLine,+ endLine: result.endLine,+ ...(result.origin !== undefined ? { origin: result.origin } : {}),+ });+}++/**+ * IDF-weighted coverage of `query` over exactly `results`, or `null` when+ * the corpus cannot be read. The store is opened read-only (and without+ * the vector extension, which coverage does not use) for the length of one+ * document-frequency read, mirroring every other read-side store user.+ */+async function coverageOverAdmitted(+ config: ResolvedSearchConfig,+ query: string,+ results: ReadonlyArray<BrainSearchResult>,+): Promise<number | null> {+ let store: Store;+ try {+ store = await Store.open(config, { mode: "read", loadVec: false });+ } catch {+ return null;+ }+ try {+ return coverageOverResults(store, query, results).idfWeightedCoverage;+ } catch {+ return null;+ } finally {+ await store.close();+ }+}diff --git a/src/core/brain/health/reconcile.ts b/src/core/brain/health/reconcile.tsindex 249dfef2..d30072e6 100644--- a/src/core/brain/health/reconcile.ts+++ b/src/core/brain/health/reconcile.ts@@ -96,6 +96,49 @@ export interface SemanticHealthReport {readonly suppressed?: SemanticHealthSuppression;}+/** The four surfaced finding families a verdict is folded from. */+export interface SemanticHealthFindings {+ readonly contradictions: ReadonlyArray<unknown>;+ readonly conceptGaps: ReadonlyArray<unknown>;+ readonly staleClaims: ReadonlyArray<unknown>;+ readonly batchInflation: ReadonlyArray<unknown>;+}++/**+ * Fold four finding families into one verdict.+ *+ * A contradiction between two confirmed preferences is the most serious+ * finding - two active rules disagree, so an agent will apply a+ * coin-flip. Gaps, stale claims, and batch-inflation bursts are quality+ * nudges, not active conflicts, so they only raise a watch.+ *+ * Exported because the verdict must be recomputed wherever the arrays it+ * summarises are NARROWED after detection, and there are two such+ * narrowings. The acknowledge-before watermark is one: a fully+ * acknowledged burst must not pin `watch`. An owner-scope filter is the+ * other (a-label-is-not-a-boundary, U3): `brain_health` withholds the+ * findings a caller may not see, and shipping the unfiltered verdict+ * beside those emptied arrays told the caller a hidden artifact had+ * tripped a detector - the existence leak with the evidence removed.+ * `toolBrainDoctor` already recomputes its `ok` for the same reason; the+ * arithmetic is here so the two cannot drift.+ *+ * Deliberately over `ReadonlyArray<unknown>`: only the lengths decide,+ * and a signature naming the four finding types would force every caller+ * that filtered them to reconstruct those types to say "none left".+ */+export function foldSemanticHealthVerdict(findings: SemanticHealthFindings): SemanticHealthVerdict {+ if (findings.contradictions.length > 0) return "investigate";+ if (+ findings.conceptGaps.length > 0 ||+ findings.staleClaims.length > 0 ||+ findings.batchInflation.length > 0+ ) {+ return "watch";+ }+ return "clean";+}+export function reconcileSemanticHealth(input: SemanticHealthInput,config: SemanticHealthConfig,@@ -129,16 +172,12 @@ export function reconcileSemanticHealth(config.silenceBefore,);- // A contradiction between two confirmed preferences is the most- // serious finding - two active rules disagree, so an agent will apply- // a coin-flip. Gaps, stale claims, and batch-inflation bursts are- // quality nudges, not active conflicts, so they only raise a watch.- // The verdict folds the SURFACED findings, so a fully-acknowledged- // burst no longer pins `watch`.- let verdict: SemanticHealthVerdict = "clean";- if (contradictions.length > 0) verdict = "investigate";- else if (conceptGaps.length > 0 || staleClaims.length > 0 || batchInflation.length > 0)- verdict = "watch";+ const verdict = foldSemanticHealthVerdict({+ contradictions,+ conceptGaps,+ staleClaims,+ batchInflation,+ });return {contradictions,diff --git a/src/core/brain/host-path-free.ts b/src/core/brain/host-path-free.tsnew file mode 100644index 00000000..b1f91c73--- /dev/null+++ b/src/core/brain/host-path-free.ts@@ -0,0 +1,46 @@+/**+ * One failure message with no host location in it.+ *+ * Three surfaces already needed this and each had grown its own copy:+ * `schema-report`'s `locationFreeDetail`, `backlinks`' `failureReason` and+ * `scaffold-stub`'s `hostPathFree`. The reason is always the same one - a+ * {@link BrainParseError} separates prose from location, but the same+ * scans meet plain `node:fs` and YAML errors that carry the absolute path+ * INSIDE the message (`ENOENT: … open '/home/…/Brain/log/x.md'`), and+ * every one of these surfaces states its locations as a vault-relative+ * `path` field beside the reason.+ *+ * It matters beyond tidiness: `collectExportRows` is reachable from an MCP+ * error path, and the contract at `src/mcp/tools.ts` keeps absolute host+ * paths out of model context. A message composed on one surface and+ * cleaned on another is how a path gets out.+ */++import { sep } from "node:path";++import { BrainParseError } from "./parse-error.ts";++/**+ * The failure text with the host location rewritten out.+ *+ * @param err the thrown value, of any shape.+ * @param vault absolute vault root; any in-vault path mentioned in the+ * message loses this prefix.+ * @param absolutePath the artifact's own absolute path, if the caller has+ * one; it becomes {@link rel} rather than merely losing the vault root.+ * @param rel the artifact's vault-relative path - what {@link absolutePath}+ * is replaced by, and what the caller reports in its own `path` field.+ */+export function hostPathFreeReason(+ err: unknown,+ vault: string,+ absolutePath: string | null,+ rel: string,+): string {+ const raw =+ err instanceof BrainParseError ? err.detail : err instanceof Error ? err.message : String(err);+ const named = absolutePath === null ? raw : raw.split(absolutePath).join(rel);+ // Trailing separator included, so `<vault>/Brain/x.md` becomes+ // `Brain/x.md` rather than `/Brain/x.md`.+ return named.split(`${vault}${sep}`).join("").split(vault).join("");+}diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.tsindex 1a783aa5..b6d0bb16 100644--- a/src/core/brain/import-claude-memory.ts+++ b/src/core/brain/import-claude-memory.ts@@ -13,6 +13,7 @@ import { assertSafeMemoryPath } from "./claude-memory-paths.ts";import { claudeMemoryBackend } from "./agent-backend/claude.ts";import type { MemorySourceBackend } from "./agent-backend/types.ts";import { BRAIN_PREFERENCES_REL, preferencePath } from "./paths.ts";+import { resolvedOwnerFor } from "./preference.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";export interface ImportClaudeMemoryOpts {@@ -157,6 +158,15 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe});plans.push(plan);if (plan.action === "CREATE" || plan.action === "RECREATE" || plan.action === "UPDATE") {+ // This module renders its own frontmatter and writes it with+ // `atomicWriteFileSync`, so it never reaches `writePreference`+ // and never got the ownership stamp every other preference+ // writer applies (a-label-is-not-a-boundary, U3). Asking the+ // shared resolver is the fix; rendering a second copy of the+ // rule here is how the next writer would get it wrong again.+ // `prefFile` is passed so an UPDATE carries the existing owner+ // forward instead of re-owning the page, exactly as a rewrite+ // through `writePreference` does.const body = backend.renderPreference({name: parsed.name,description: parsed.description,@@ -164,6 +174,7 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMememoryPath: join(baseDir, name),importedAt,bodySha256: parsed.bodySha256,+ owner: resolvedOwnerFor(opts.vault, prefFile, undefined, undefined),});filesToWrite.push({ plan, body, sha256: parsed.bodySha256, slug });}diff --git a/src/core/brain/link-graph/concept-cluster.ts b/src/core/brain/link-graph/concept-cluster.tsindex 6875ad03..d75ffaf7 100644--- a/src/core/brain/link-graph/concept-cluster.ts+++ b/src/core/brain/link-graph/concept-cluster.ts@@ -48,6 +48,17 @@ export interface BuildConceptClusterOptions {readonly includeUnlinked?: boolean;/** Cap on unlinked-mention rows when included. Default `100`. */readonly unlinkedLimit?: number;+ /**+ * Owner scope both producers are asked under+ * (a-label-is-not-a-boundary, U3). `null` / absent hides nothing.+ *+ * Both of them, because a cluster is exactly the two: `linkers`+ * carries the id of every artifact that points AT the target, and+ * `unlinkedMentions` carries a verbatim line of body prose out of the+ * page that mentioned it. Threading the scope into one and not the+ * other would leave the more disclosive half open.+ */+ readonly ownerScope?: string | null;}/**@@ -63,9 +74,10 @@ export function buildConceptCluster(opts: BuildConceptClusterOptions = {},): ConceptClusterEnvelope {const normalised = normaliseWikilinkTarget(targetId);+ const scope = opts.ownerScope ?? null;const targetTitle = resolveTitle(vault, normalised);- const index = buildBacklinkIndex(vault);+ const index = buildBacklinkIndex(vault, scope);const refs = index.get(normalised) ?? [];const linkers: ConceptLinker[] = refs.map((r) =>@@ -86,11 +98,10 @@ export function buildConceptCluster(});const unlinkedMentions = opts.includeUnlinked- ? findUnlinkedMentions(- vault,- normalised,- opts.unlinkedLimit !== undefined ? { limit: opts.unlinkedLimit } : {},- )+ ? findUnlinkedMentions(vault, normalised, {+ ...(opts.unlinkedLimit !== undefined ? { limit: opts.unlinkedLimit } : {}),+ ownerScope: scope,+ }): Object.freeze([] as MentionRef[]);return Object.freeze({diff --git a/src/core/brain/link-graph/moc-audit.ts b/src/core/brain/link-graph/moc-audit.tsindex 6b1b121c..b9e71e1b 100644--- a/src/core/brain/link-graph/moc-audit.ts+++ b/src/core/brain/link-graph/moc-audit.ts@@ -21,6 +21,7 @@ import { existsSync, readFileSync } from "node:fs";import { join } from "node:path";import { buildBacklinkIndex } from "../backlinks.ts";+import { ownerScopeView } from "../owner-scope-view.ts";import { brainDirs } from "../paths.ts";import { loadBrainConfig, resolveLinkGraph } from "../policy.ts";import { normaliseWikilinkTarget } from "../wikilink.ts";@@ -66,12 +67,29 @@ export interface AuditMocOptions {readonly minOutboundLinks?: number;/** When set, skip the `link_graph` config lookup and use this. */readonly minLinkRatio?: number;+ /**+ * Owner scope the cluster is filtered against+ * (a-label-is-not-a-boundary, U3). Absent / `null` filters nothing.+ *+ * A hidden member is dropped from EVERY bucket, not moved into+ * `candidateMissing`: reporting it as missing would answer the+ * exists-vs-absent question this audit exists to answer, in the+ * direction that says "no such artifact" about one that exists. It+ * simply does not appear, which is what "identical to absent" means+ * everywhere else in this vault. `bodyChars` sizes a private body and+ * `backlinkCount` counts references from artifacts the caller may not+ * see, so both follow the member out.+ */+ readonly ownerScope?: string | null;}export function auditMoc(vault: string, hubId: string, opts: AuditMocOptions = {}): MocAuditReport {const hubCanonical = normaliseWikilinkTarget(hubId);+ const view = ownerScopeView(vault, opts.ownerScope ?? null);const hubPath = locateArtifact(vault, hubCanonical);- if (!hubPath) {+ // A hub the caller may not see reads as a hub that is not there: the+ // same sentence an absent hub produces, so the two are indistinguishable.+ if (!hubPath || !view.visible(hubCanonical)) {throw new MocAuditError(`hub note not found: ${hubCanonical}`);}@@ -103,7 +121,7 @@ export function auditMoc(vault: string, hubId: string, opts: AuditMocOptions = {}// Backlink index + cluster member metadata.- const index = buildBacklinkIndex(vault);+ const index = buildBacklinkIndex(vault, view.scope);const wellCovered: MocClusterMember[] = [];const fragile: MocClusterMember[] = [];const candidateMissing: { id: string; referenceCount: number }[] = [];@@ -111,6 +129,9 @@ export function auditMoc(vault: string, hubId: string, opts: AuditMocOptions = {for (const target of outboundTargets) {const memberPath = locateArtifact(vault, target);+ // A member this caller may not see leaves no trace in any bucket -+ // not even the missing one, which would decide exists-vs-absent for it.+ if (memberPath && !view.visible(target)) continue;if (!memberPath) {missingCounts.set(target, (missingCounts.get(target) ?? 0) + 1);continue;@@ -145,7 +166,7 @@ export function auditMoc(vault: string, hubId: string, opts: AuditMocOptions = {if (!missingCounts.has(target)) continue;for (const member of outboundTargets) {const path = locateArtifact(vault, member);- if (!path) continue;+ if (!path || !view.visible(member)) continue;const body = stripFrontmatter(readFileSync(path, "utf8"));for (const bracketBody of extractWikilinkRichBodies(body)) {const t = parseWikilinkRich(bracketBody).target;diff --git a/src/core/brain/link-graph/unlinked-mentions.ts b/src/core/brain/link-graph/unlinked-mentions.tsindex 421a810c..568546b2 100644--- a/src/core/brain/link-graph/unlinked-mentions.ts+++ b/src/core/brain/link-graph/unlinked-mentions.ts@@ -22,6 +22,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";import { join } from "node:path";import { parseFrontmatter } from "../../vault.ts";+import { ownerScopeView, type OwnerScopeView } from "../owner-scope-view.ts";import { brainDirs } from "../paths.ts";/** One unlinked-mention occurrence. */@@ -42,6 +43,15 @@ export interface FindUnlinkedMentionsOptions {* not exposed; callers needing more should call with a larger cap.*/readonly limit?: number;+ /**+ * Owner scope the mentions are filtered against+ * (a-label-is-not-a-boundary, U3). A mention carries its source+ * artifact's id AND the line of prose the term sits in, so an+ * unfiltered scan published an owner-private body verbatim. Absent /+ * `null` means no ownership filtering, which is what every existing+ * caller gets.+ */+ readonly ownerScope?: string | null;}const DEFAULT_LIMIT = 100;@@ -73,10 +83,11 @@ export function findUnlinkedMentions(const terms = resolveSearchTerms(vault, targetId);if (terms.length === 0) return Object.freeze([]) as ReadonlyArray<MentionRef>;+ const view = ownerScopeView(vault, opts.ownerScope ?? null);const collected: MentionRef[] = [];- scanDir(dirs.preferences, targetId, terms, collected, limit);+ scanDir(dirs.preferences, targetId, terms, collected, limit, view);if (collected.length < limit) {- scanDir(dirs.retired, targetId, terms, collected, limit);+ scanDir(dirs.retired, targetId, terms, collected, limit, view);}return Object.freeze(collected) as ReadonlyArray<MentionRef>;@@ -132,6 +143,7 @@ function scanDir(terms: ReadonlyArray<string>,out: MentionRef[],limit: number,+ view: OwnerScopeView,): void {if (!existsSync(dir)) return;for (const name of readdirSync(dir)) {@@ -139,6 +151,9 @@ function scanDir(if (!name.endsWith(".md")) continue;const source = name.slice(0, -".md".length);if (source === targetId) continue;+ // A mention discloses its source artifact's id and one line of its+ // body, so the source decides visibility before the file is read.+ if (!view.visible(source)) continue;let text: string;try {text = readFileSync(join(dir, name), "utf8");diff --git a/src/core/brain/note.ts b/src/core/brain/note.tsindex 7776e2fe..809b90e1 100644--- a/src/core/brain/note.ts+++ b/src/core/brain/note.ts@@ -14,7 +14,12 @@ import { vaultRelative } from "../path-safety.ts";import { sanitiseTextField } from "../redactor.ts";import { appendLogEvent } from "./log.ts";-import { mirrorNote, resolveSharedNamespace, type MirrorOutcome } from "./shared-namespace.ts";+import {+ mirrorNote,+ mirrorReportFields,+ resolveSharedNamespace,+ type MirrorOutcome,+} from "./shared-namespace.ts";import { isoSecond } from "./time.ts";import { BRAIN_LOG_EVENT_KIND } from "./types.ts";@@ -46,6 +51,12 @@ export interface AppendBrainNoteResult {* keep the previous result shape.*/readonly mirror?: MirrorOutcome;+ /**+ * Why the mirror did not succeed. Present exactly when `mirror` is+ * present and is not `ok`: a fail-soft outcome that carries no diagnosis+ * is a bit the operator cannot act on.+ */+ readonly mirror_reason?: string;}/**@@ -86,6 +97,6 @@ export function appendBrainNote(input: AppendBrainNoteInput): AppendBrainNoteReslog_path: vaultRelative(res.logPath, input.vault),absolute_log_path: resolve(res.logPath),agent,- ...(mirror !== undefined ? { mirror } : {}),+ ...mirrorReportFields(mirror),};}diff --git a/src/core/brain/notes/scaffold-stub.ts b/src/core/brain/notes/scaffold-stub.tsindex f8ad54e5..a6d31f69 100644--- a/src/core/brain/notes/scaffold-stub.ts+++ b/src/core/brain/notes/scaffold-stub.ts@@ -116,6 +116,16 @@ const REINDEX_COMMAND = requireNextStep(SEARCH_INDEX_MISSING_CODE).nextCommand;/** Default cap on targets returned by one scan. */export const DANGLING_SCAN_DEFAULT_LIMIT = 100;+/**+ * The `limit` handed to `Store.listDangling` so it groups every+ * unresolved row rather than the first page of them.+ *+ * `listDangling` takes a required cap; there is no "all" spelling. The+ * caller's own limit cannot be that cap, because it has to be applied+ * after the ownership filter - see the call site.+ */+const UNBOUNDED_TARGETS = Number.MAX_SAFE_INTEGER;+function refusal(state: DanglingScan, detail: string): DanglingScanResult {return Object.freeze({state,@@ -128,6 +138,21 @@ function refusal(state: DanglingScan, detail: string): DanglingScanResult {export interface ListDanglingOptions {/** Maximum targets returned. Defaults to {@link DANGLING_SCAN_DEFAULT_LIMIT}. */readonly limit?: number;+ /**+ * Owner scope the listing is filtered against+ * (a-label-is-not-a-boundary, U3). Absent / `null` filters nothing,+ * which is what both existing callers get.+ *+ * The predicate cannot be SQL - `documents` has no owner column+ * (`src/core/search/schema.ts:103-113`) - so it lands here, one layer+ * above `listDangling`, where the vault root is in hand and+ * `isPathOwnerVisible` can be asked. A target whose sources are ALL+ * filtered away is dropped WHOLE: the surviving `target` string is the+ * link spelling a hidden note wrote, so publishing it would name a+ * private page's title and confirm the existence of the note that+ * pointed at it.+ */+ readonly ownerScope?: string | null;}/**@@ -178,9 +203,19 @@ export async function listDanglingTargets("a dangling list is only reproducible after a forced full pass",);}+ // The limit caps what the CALLER receives, so it is applied AFTER+ // the ownership filter, never before it. Asking the store for+ // `limit` targets and then hiding some of them silently returns+ // fewer rows than the caller asked for and than the vault holds -+ // and the shortfall is proportional to how much the other owner+ // wrote, which is the existence leak read off a row count. Ordering+ // it this way costs nothing: `listDangling` reads every unresolved+ // row out of sqlite regardless and applies `limit` while grouping.+ const scope = opts.ownerScope ?? null;+ const visible = await visibleTargets(vault, store.listDangling(UNBOUNDED_TARGETS), scope);return Object.freeze({state: DANGLING_SCAN.measured,- targets: store.listDangling(limit),+ targets: Object.freeze(visible.slice(0, limit)),detail: null,nextCommand: REINDEX_COMMAND,});@@ -191,6 +226,43 @@ export async function listDanglingTargets(}}+/**+ * Drop the sources the scope may not see, and drop the WHOLE target when+ * none of them survives.+ *+ * Filtering `sources` alone would not close this: `target` is the link+ * text a hidden note wrote, so a target reachable only from hidden+ * sources publishes that note's private outbound link - and, when the+ * link was written by title, the private page's title with it. A target+ * that still has a visible source stays, because that source's own text+ * already names it to this caller.+ *+ * The owner-scope view is reached through a DEFERRED import for the same+ * reason the store is: it imports the search-side frontmatter cache, and+ * a static edge from a Brain note writer into the search tree is the+ * shape the acyclic-import ratchet exists to keep out.+ */+async function visibleTargets(+ vault: string,+ targets: ReadonlyArray<DanglingLinkTarget>,+ scope: string | null,+): Promise<ReadonlyArray<DanglingLinkTarget>> {+ if (scope === null) return targets;+ const { ownerScopeView } = await import("../owner-scope-view.ts");+ const view = ownerScopeView(vault, scope);+ const kept: DanglingLinkTarget[] = [];+ for (const target of targets) {+ const sources = target.sources.filter((source) => view.visible(source));+ if (sources.length === 0) continue;+ kept.push(+ sources.length === target.sources.length+ ? target+ : Object.freeze({ target: target.target, sources: Object.freeze(sources) }),+ );+ }+ return Object.freeze(kept);+}+/*** `err`'s own message with this install's absolute host paths removed.*diff --git a/src/core/brain/owner-scope-view.ts b/src/core/brain/owner-scope-view.tsnew file mode 100644index 00000000..7b5f4098--- /dev/null+++ b/src/core/brain/owner-scope-view.ts@@ -0,0 +1,225 @@+/**+ * What one caller may see, asked once per response+ * (a-label-is-not-a-boundary, U3).+ *+ * `isOwnerVisible` (`src/core/graph/agent-scope.ts`) is the vault's only+ * ownership rule and `isPathOwnerVisible`+ * (`src/core/search/result-filters.ts`) is the only place that rule meets+ * the filesystem. Neither is a second registry and nothing here becomes+ * one: this module is the ADAPTER the report-shaped surfaces needed, and+ * it exists because those surfaces hold an artifact id or a+ * vault-relative path rather than a ranked search result.+ *+ * The defect it closes is enumerated in+ * `docs/brainstorm/a-label-is-not-a-boundary/recon/owner-scope-isolation.md`+ * section C6: fourteen tools classified as metadata returned another+ * owner's artifact ids, paths, titles and body prose under+ * `integrity.owner_scope_delivery: fail`, because each one aggregated its+ * rows itself and none of them asked the rule.+ *+ * ## Two conventions this module inherits rather than invents+ *+ * FAIL CLOSED. A page whose file cannot be read has an unknowable owner+ * and is hidden, exactly as `isPathOwnerVisible` decides it — an+ * ownership claim that cannot be read is not an absence of one.+ *+ * IDENTICAL TO ABSENT. A withheld row is dropped, and nothing counts it.+ * `preferences-collect.ts` states the reason: under `fail` a count would+ * tell one agent that another agent's private memories exist, which is+ * the existence leak the search side already avoids. So no surface using+ * this view reports how many rows it withheld, and a caller cannot tell a+ * filtered report from a report over a vault that never held the rows.+ *+ * ## Cost when nobody opted in+ *+ * `scope === null` — the only state a vault with the gate off can reach —+ * short-circuits every predicate to `true` before any file is touched.+ * A vault that never enabled owner-scope delivery pays one comparison per+ * call and reads nothing.+ *+ * ## `warn` is INERT on every surface that uses this view+ *+ * Said plainly because the write side says the opposite about itself and+ * the two were being read as one promise. `resolveOwnerScopeDelivery`+ * returns `enforcedScope: null` under `warn`, so+ * {@link gatedOwnerScopeView} hands back the no-op view and nothing is+ * withheld — and the IDENTICAL TO ABSENT convention above forbids+ * reporting a withheld count, so nothing is reported either. Under+ * `warn` these surfaces are therefore byte-identical to `off`: they+ * neither withhold nor observe.+ *+ * Where `warn` IS observable is the WRITE side. `warn` stamps `owner:`+ * exactly as `fail` does (`preference.ts`), so an operator who sets it+ * can read the ownership that has accumulated straight off the+ * preference files and see the population `fail` would start+ * withholding, BEFORE turning `fail` on. That is the whole of what+ * `warn` does today. A per-response "this is what `fail` would have+ * withheld" field on these fifteen surfaces would be the other half, and+ * it is deliberately not claimed here until it exists.+ */++import { join } from "node:path";+import { existsSync } from "node:fs";++import { isPathOwnerVisible, type FrontmatterCache } from "../search/result-filters.ts";+import { BRAIN_SOURCES_REL, brainDirs } from "./paths.ts";+import { resolveOwnerScopeDelivery } from "./preferences-collect.ts";+import { ANCHORED_WIKILINK_RE } from "./wikilink.ts";++/** The `.md` extension every Brain artifact id resolves through. */+const MARKDOWN_EXT = ".md";++/**+ * A reference a report row carries: either a vault-relative path+ * (`Brain/preferences/pref-x.md`, `notes/y.md`) or a bare Brain artifact+ * id (`pref-x`, `ret-y`, `sig-2026-05-01-z`), optionally spelled as a+ * wikilink (`[[pref-x]]`, `[[notes/y.md]]`).+ *+ * `null` / `undefined` / empty are accepted and read as "this row names+ * nothing here", which is visible: a row with no subject cannot disclose+ * one.+ */+export type OwnerScopeRef = string | null | undefined;++/**+ * Strip the wikilink brackets a report row may have kept around its+ * reference, leaving the target verbatim.+ *+ * The brackets are SYNTAX, not part of the reference: a retirement's+ * `retired_by`, a dream transition's `link` and an evidence row's+ * `artifact` all carry `[[…]]` straight out of frontmatter or a log+ * body, and `[[Brain/preferences/pref-x.md]]` names exactly the page+ * `Brain/preferences/pref-x.md`. Before this, such a reference matched+ * neither branch below and the row failed OPEN.+ *+ * Deliberately NOT {@link parseWikilinkRich}: that normaliser collapses+ * folder segments and drops `.md`, which turns a path-shaped link into a+ * bare basename that resolves to no artifact - the same fail-open by a+ * longer route. Only the brackets come off; the anchor / alias+ * decoration inside them is handled by the id-resolution step, which+ * simply finds no file and treats the row as naming nothing.+ */+function unbracket(ref: string): string {+ const match = ANCHORED_WIKILINK_RE.exec(ref.trim());+ return match === null ? ref : match[1]!.trim();+}++/** The visibility decision, bound to one vault and one scope. */+export interface OwnerScopeView {+ /** The enforced scope, or `null` when no ownership filtering applies. */+ readonly scope: string | null;+ /** May the caller see the artifact or page this reference names? */+ readonly visible: (ref: OwnerScopeRef) => boolean;+ /**+ * May the caller see a row that names ALL of these? One hidden+ * reference hides the row: a row survives only when every artifact it+ * would disclose is one the caller may already see.+ */+ readonly row: (...refs: ReadonlyArray<OwnerScopeRef>) => boolean;+ /** Drop the rows whose references are not all visible. */+ readonly keep: <T>(+ rows: ReadonlyArray<T>,+ refsOf: (row: T) => ReadonlyArray<OwnerScopeRef>,+ ) => ReadonlyArray<T>;+}++/** A view that hides nothing, allocated once. */+const UNFILTERED: OwnerScopeView = Object.freeze({+ scope: null,+ visible: () => true,+ row: () => true,+ keep: <T>(rows: ReadonlyArray<T>) => rows,+});++/**+ * Resolve a bare Brain artifact id to its vault-relative path, or `null`+ * when no artifact of that id is on disk.+ *+ * ## Why the directory list is the whole boundary+ *+ * `visible()` reads an id that resolves to no file as "this row names+ * nothing that could be owned" and lets the row through. That reading is+ * true only for ids this function would have FOUND had the artifact+ * existed - so every directory omitted here is a directory whose pages+ * are silently unownable, and the module's fail-closed promise turns+ * into a fail-open one for exactly those pages. The list is therefore+ * every `Brain/` directory holding id-addressable Markdown:+ *+ * - `preferences` / `retired` carry `owner:` through the preference+ * writer;+ * - `inbox` / `processed` / `pending` carry whatever an operator or an+ * importer wrote into a signal's frontmatter;+ * - `sources` (`src-<slug>.md`) and `entities` are owner-taggable the+ * same way, and `brain_search_by_source` already filters the first+ * of them by owner on the search side - so an id-shaped reference to+ * one reaching THIS view and passing was the two halves disagreeing.+ *+ * `log` is deliberately absent - a log shard is named by date, is shared+ * by construction, and has no owner to read. `bases` holds `.base` view+ * definitions rather than Markdown pages, and `snapshots` holds dated+ * copies addressed by path rather than by id.+ */+function artifactPath(vault: string, id: string): string | null {+ const dirs = brainDirs(vault);+ for (const dir of [+ dirs.preferences,+ dirs.retired,+ dirs.inbox,+ dirs.processed,+ dirs.pending,+ join(vault, BRAIN_SOURCES_REL),+ dirs.entities,+ ]) {+ const abs = join(dir, `${id}${MARKDOWN_EXT}`);+ if (existsSync(abs)) return abs.slice(vault.length + 1);+ }+ return null;+}++/**+ * Bind the ownership rule to one vault and one scope.+ *+ * `scope === null` returns the shared no-op view, so a caller that+ * threads this through unconditionally costs nothing on a vault that+ * never opted in.+ */+export function ownerScopeView(vault: string, scope: string | null): OwnerScopeView {+ if (scope === null) return UNFILTERED;+ // One frontmatter read per (vault, path) for the whole response, the+ // same sharing `search()` gives its filter stages.+ const cache: FrontmatterCache = new Map();+ const visible = (ref: OwnerScopeRef): boolean => {+ if (ref === null || ref === undefined || ref.length === 0) return true;+ // A reference that names a path is resolved as one; anything else is+ // a Brain artifact id, and an id with no artifact on disk names+ // nothing that could be owned - see {@link artifactPath} for why+ // that reading is only true while its directory list is complete.+ const bare = unbracket(ref);+ if (bare.length === 0) return true;+ const rel = bare.endsWith(MARKDOWN_EXT) ? bare : artifactPath(vault, bare);+ if (rel === null) return true;+ return isPathOwnerVisible(vault, rel, scope, cache);+ };+ const row = (...refs: ReadonlyArray<OwnerScopeRef>): boolean => refs.every(visible);+ return Object.freeze({+ scope,+ visible,+ row,+ keep: <T>(rows: ReadonlyArray<T>, refsOf: (r: T) => ReadonlyArray<OwnerScopeRef>) =>+ rows.filter((r) => refsOf(r).every(visible)),+ });+}++/**+ * The view a surface that takes no `agent_scope` argument must use.+ *+ * These surfaces cannot be told which owner is asking, so the scope is+ * the server-resolved identity and it applies only under+ * `integrity.owner_scope_delivery: fail` — the same gate, read through+ * the same resolver, as every preference-delivery surface. Under `off`+ * and `warn` `enforcedScope` is `null` and the view hides nothing, which+ * is what keeps a vault that never opted in byte-identical.+ */+export function gatedOwnerScopeView(vault: string, agentName: string | undefined): OwnerScopeView {+ return ownerScopeView(vault, resolveOwnerScopeDelivery(vault, agentName).enforcedScope);+}diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex e11c491c..177784b1 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -55,6 +55,7 @@ export {loadBrainConfigDetailed,loadFeedbackDefaultScopeSafe,loadGuardrailsConfigSafe,+ loadIntegrityConfigForWrite,loadIntegrityConfigSafe,loadMaintenanceConfigSafe,loadNotesConfigSafe,diff --git a/src/core/brain/policy/load.ts b/src/core/brain/policy/load.tsindex 86c08e5e..2fb9c7d7 100644--- a/src/core/brain/policy/load.ts+++ b/src/core/brain/policy/load.ts@@ -355,3 +355,35 @@ export function loadIntegrityConfigSafe(vault: string): ResolvedBrainIntegrityCoreturn brainConfigExists(vault) ? BRAIN_INTEGRITY_STRICT_FALLBACK : BRAIN_INTEGRITY_DEFAULTS;}}++/**+ * Load + resolve the `integrity:` block for a WRITER.+ *+ * The reader/writer asymmetry, stated on the side it belongs to. This+ * sits on the WRITE side, and it is the absent-tolerant loader every+ * other block already uses ({@link makeAbsentTolerantLoader}) - absent+ * config resolves to the documented defaults, an unreadable one raises.+ *+ * It is NOT {@link loadIntegrityConfigSafe}, and the difference is the+ * point. That loader's strict fallback has a rationale scoped entirely+ * to READERS: "the unreadable config cannot loosen a gate, it can only+ * close one". Closing a gate a reader cannot read is conservative -+ * the reader withholds more than it had to, and nothing on disk+ * changes. Handing the same strict verdict to a writer inverts it:+ * `owner_scope_delivery` in its strict reading STAMPS, so one bad token+ * anywhere in `_brain.yaml` made a preference writer start marking new+ * pages `owner: <whoever wrote them>` - permanently, because ownership+ * is carried forward and never re-derived, so the pages outlived the+ * repair of the typo that caused them. On an install with no resolvable+ * identity the same typo turned every preference write into a hard+ * failure instead.+ *+ * A writer cannot infer an operator's intent to enable ownership from a+ * file it could not read, so it does not try. It raises, naming the+ * parse failure, and writes nothing: never a silent stamp, never a+ * silent skip.+ */+export const loadIntegrityConfigForWrite = makeAbsentTolerantLoader(+ resolveIntegrity,+ BRAIN_INTEGRITY_DEFAULTS,+);diff --git a/src/core/brain/portability/okf.ts b/src/core/brain/portability/okf.tsindex f43c4caa..7d4a4c01 100644--- a/src/core/brain/portability/okf.ts+++ b/src/core/brain/portability/okf.ts@@ -56,9 +56,9 @@ import {extractFrontmatterRelations,normalizeRelationTarget,} from "../../graph/frontmatter-relations.ts";+import { listLogShardFiles } from "../log-jsonl.ts";import {BRAIN_ROOT_REL,- BRAIN_LOG_REL,BRAIN_SOURCES_REL,BRAIN_REPORTS_REL,ensureInsideVault,@@ -160,7 +160,11 @@ export interface OkfManifest {readonly generated_at: string;readonly vault_basename: string;readonly pages: ReadonlyArray<OkfManifestPage>;- /** Count of `Brain/log/<date>.md` days folded into `log.md`. */+ /**+ * Count of DAYS folded into `log.md`, across every markdown shard of+ * `Brain/log/` - `<date>.md` and `<date>.<deviceId>.md` alike. Two+ * shards of one day are one day here, not two.+ */readonly log_days: number;}@@ -322,31 +326,48 @@ function listMarkdown(root: string, skipDirs: ReadonlyArray<string>): string[] {return found;}-/** Read and date-group `Brain/log/<date>.md` into a single change log. */+/**+ * Read and date-group the markdown side of `Brain/log/` into one change+ * log.+ *+ * Days come from {@link listLogShardFiles}, the recogniser in the module+ * that owns the log layout, rather than from a pattern of this module's+ * own. The local pattern here matched `<date>.md` only, while every+ * default install has written the per-device `<date>.<deviceId>.md` since+ * sharding landed - so a vault with a full change log exported an empty+ * `log.md` and a manifest reading `0 log day(s)`, with nothing to+ * distinguish that from a vault that had never logged anything.+ *+ * Shards of one day fold into ONE dated section, ordered by shard id+ * (`listLogShardFiles` sorts by name), so the bundle is byte-identical+ * whatever order Syncthing delivered the shards in.+ */function buildLog(vault: string): { contents: string; days: number } {- const dir = join(vault, BRAIN_LOG_REL);- let entries: string[];- try {- entries = readdirSync(dir);- } catch {- return { contents: "", days: 0 };- }- const dateRe = /^(\d{4}-\d{2}-\d{2})\.md$/;- const days = entries- .map((name) => dateRe.exec(name)?.[1])- .filter((d): d is string => typeof d === "string")- .toSorted();- const sections: string[] = [];- for (const date of days) {+ const bodiesByDate = new Map<string, string[]>();+ for (const shard of listLogShardFiles(vault)) {+ // The bundle is markdown; the JSONL sidecar of a day carries the same+ // entries in machine form and would duplicate every line.+ if (shard.ext !== "md") continue;let body: string;try {- body = readFileSync(join(dir, `${date}.md`), "utf8").trimEnd();- } catch {- continue;+ body = readFileSync(shard.path, "utf8").trimEnd();+ } catch (err) {+ // Never `continue`: a shard the export could not read is a day of+ // the change log missing from the bundle, and a bundle that is+ // silently short a day is exactly what this export must not produce.+ throw new Error(+ `okf export: cannot read log shard ${shard.name}: ${err instanceof Error ? err.message : String(err)}`,+ );}- sections.push(`## ${date}\n\n${body}`);+ if (body.length === 0) continue;+ const bodies = bodiesByDate.get(shard.date);+ if (bodies === undefined) bodiesByDate.set(shard.date, [body]);+ else bodies.push(body);}- return { contents: sections.join("\n\n"), days: days.length };+ const sections = [...bodiesByDate.keys()]+ .toSorted()+ .map((date) => `## ${date}\n\n${bodiesByDate.get(date)!.join("\n\n")}`);+ return { contents: sections.join("\n\n"), days: bodiesByDate.size };}function renderIndex(manifest: OkfManifest): string {diff --git a/src/core/brain/portability/origin-reach.ts b/src/core/brain/portability/origin-reach.tsnew file mode 100644index 00000000..1a0f85d3--- /dev/null+++ b/src/core/brain/portability/origin-reach.ts@@ -0,0 +1,123 @@+/**+ * Whether a search origin can be read at all (a-label-is-not-a-boundary, U5).+ *+ * `listSearchOrigins` used to drop an origin whose directory had gone away+ * before the search fan-out ever saw it, so a union over N origins with one+ * dead origin answered as though that origin had honestly contributed+ * nothing. An origin that was never read is not an origin that held no+ * match, and the two must not arrive at a caller wearing the same face.+ *+ * The split is the one {@link statOrAbsent} already draws for the plugin+ * config and {@link RecallSourceStatus} draws for the registry: absence is+ * ENOENT on the path itself, and every other errno is a failure to ANSWER+ * the question rather than an answer. `isDir` deliberately collapses the+ * two - its own docblock says a caller whose OUTPUT distinguishes them must+ * probe with `statOrAbsent` and report the reason - and this is that caller.+ */++import { statOrAbsent } from "../../fs-utils.ts";++/** How much a probe learned about one origin. */+export const ORIGIN_REACH = Object.freeze({+ /** The path is a directory: the origin can be searched. */+ reachable: "reachable",+ /** The probe answered, and the origin is not there. */+ unreachable: "unreachable",+ /** The probe could not answer; nothing was learned. Never a synonym for absent. */+ unknown: "unknown",+} as const);++/** Closed union over {@link ORIGIN_REACH}. */+export type OriginReach = (typeof ORIGIN_REACH)[keyof typeof ORIGIN_REACH];++/** Membership list, from most-known to least-known. */+export const ORIGIN_REACHES: ReadonlyArray<OriginReach> = Object.freeze([+ ORIGIN_REACH.reachable,+ ORIGIN_REACH.unreachable,+ ORIGIN_REACH.unknown,+]);++/** Narrow a value read back off a payload or across a tool boundary. */+export function isOriginReach(value: unknown): value is OriginReach {+ return typeof value === "string" && (ORIGIN_REACHES as ReadonlyArray<string>).includes(value);+}++/**+ * Why an origin is not reachable. Each member is a fact the probe+ * established, never a guess, and each names a different repair: a missing+ * vault is detached or restored, a path that is not a directory is a+ * mistyped registry entry, and an unreadable one is a permission or device+ * fault on a vault that may be perfectly intact.+ *+ * These values ride the retrieval trail's `detail`, so they are identifiers+ * under {@link RETRIEVAL_DETAIL_IDENTIFIER} and carry no path and no errno+ * message.+ */+export const ORIGIN_REACH_REASON = Object.freeze({+ /** Nothing exists at the registered path. */+ vaultMissing: "vault-missing",+ /** Something exists there and it is not a directory. */+ vaultNotDirectory: "vault-not-directory",+ /** The path could not be examined, so the origin's state is unknown. */+ vaultUnreadable: "vault-unreadable",+} as const);++/** Closed union over {@link ORIGIN_REACH_REASON}. */+export type OriginReachReason = (typeof ORIGIN_REACH_REASON)[keyof typeof ORIGIN_REACH_REASON];++/** Membership list, in probe order. */+export const ORIGIN_REACH_REASONS: ReadonlyArray<OriginReachReason> = Object.freeze([+ ORIGIN_REACH_REASON.vaultMissing,+ ORIGIN_REACH_REASON.vaultNotDirectory,+ ORIGIN_REACH_REASON.vaultUnreadable,+]);++/** Narrow a value read back off a payload or across a tool boundary. */+export function isOriginReachReason(value: unknown): value is OriginReachReason {+ return (+ typeof value === "string" && (ORIGIN_REACH_REASONS as ReadonlyArray<string>).includes(value)+ );+}++/** One probe's verdict. `reason` is absent exactly when the origin is reachable. */+export interface OriginReachVerdict {+ readonly reach: OriginReach;+ readonly reason?: OriginReachReason;+}++const REACHABLE: OriginReachVerdict = Object.freeze({ reach: ORIGIN_REACH.reachable });++/**+ * Errno of a stat that failed for a reason other than ENOENT (which+ * `statOrAbsent` reports as `undefined` instead of throwing). ENOTDIR means+ * a component of the path is a file, so the vault provably is not there;+ * anything else left the question unanswered.+ */+const ERRNO_NOT_A_DIRECTORY = "ENOTDIR";++function verdict(reason: OriginReachReason, reach: OriginReach): OriginReachVerdict {+ return Object.freeze({ reach, reason });+}++/**+ * Probe one origin path. Never throws: the failure to look IS one of the+ * three answers, and a caller enumerating origins must not lose the other+ * origins to one bad entry.+ */+export function probeOriginReach(vault: string): OriginReachVerdict {+ try {+ const stats = statOrAbsent(vault);+ if (stats === undefined) {+ return verdict(ORIGIN_REACH_REASON.vaultMissing, ORIGIN_REACH.unreachable);+ }+ if (!stats.isDirectory()) {+ return verdict(ORIGIN_REACH_REASON.vaultNotDirectory, ORIGIN_REACH.unreachable);+ }+ return REACHABLE;+ } catch (exc) {+ const code = (exc as NodeJS.ErrnoException | undefined)?.code;+ return code === ERRNO_NOT_A_DIRECTORY+ ? verdict(ORIGIN_REACH_REASON.vaultNotDirectory, ORIGIN_REACH.unreachable)+ : verdict(ORIGIN_REACH_REASON.vaultUnreadable, ORIGIN_REACH.unknown);+ }+}diff --git a/src/core/brain/portability/origins.ts b/src/core/brain/portability/origins.tsindex 02f40c18..c0b8231f 100644--- a/src/core/brain/portability/origins.ts+++ b/src/core/brain/portability/origins.ts@@ -4,23 +4,33 @@* One place answers "which vaults participate in cross-vault recall":* the active vault first (label `local`), then registered profile* vaults (`profile/<name>`), then read-only recall sources- * (`source/<alias>`), deduped by resolved path with earlier kinds- * winning. Labels are namespaced by kind so a profile and a source can- * never collide, and they double as the `origin:` reason prefix on- * search results.+ * (`source/<alias>`), then the shared namespace (`shared`), deduped by+ * resolved path with earlier kinds winning. Labels are namespaced by kind+ * so a profile and a source can never collide, and they double as the+ * `origin:` reason prefix on search results.*- * Only existing directories are enumerated: broken sources stay- * visible through `listRecallSources` / `o2b brain source list`, but- * they never reach the search fan-out.+ * Every registered origin is enumerated, each carrying the verdict of one+ * reachability probe (a-label-is-not-a-boundary, U5). Removing an origin+ * that could not be read used to happen HERE, one layer above the fan-out+ * that maintains the warnings array, so a union over three origins with one+ * dead origin came back as though that origin had honestly contributed+ * nothing. `recall-sources.ts` states the rule for the same fact one layer+ * down - reported, never dropped, the operator decides - and this module+ * used to undo it. Deciding whether to search an unreachable origin belongs+ * to the caller; deciding not to MENTION it never did.*/import { resolve } from "node:path";-import { isDir as isDirectory } from "../../fs-utils.ts";+import { resolveSharedNamespace } from "../../config.ts";+import { probeOriginReach, type OriginReach, type OriginReachReason } from "./origin-reach.ts";import { listProfiles } from "./profiles.ts";import { listRecallSources } from "./recall-sources.ts";-export type SearchOriginKind = "active" | "profile" | "source";+export type SearchOriginKind = "active" | "profile" | "source" | "shared";++/** Label of the shared namespace: one key, so one origin, so no namespace segment. */+const SHARED_ORIGIN_LABEL = "shared";export interface SearchOrigin {/** Bare name: profile name, source alias, or "local". */@@ -29,6 +39,29 @@ export interface SearchOrigin {readonly label: string;readonly vault: string;readonly kind: SearchOriginKind;+ /** What a probe learned about this origin's vault directory. */+ readonly reach: OriginReach;+ /** Why the origin is not reachable. Absent exactly when it is. */+ readonly reason?: OriginReachReason;+}++/**+ * Freeze one origin with its probe verdict.+ *+ * The probe runs for every kind including the active vault: an active vault+ * that has been unmounted answers nothing either, and a caller reading the+ * verdict must not have to know which kinds were measured.+ */+function origin(alias: string, label: string, vault: string, kind: SearchOriginKind): SearchOrigin {+ const verdict = probeOriginReach(vault);+ return Object.freeze({+ alias,+ label,+ vault,+ kind,+ reach: verdict.reach,+ ...(verdict.reason !== undefined ? { reason: verdict.reason } : {}),+ });}export function listSearchOrigins(@@ -37,39 +70,32 @@ export function listSearchOrigins(): ReadonlyArray<SearchOrigin> {const activeResolved = resolve(activeVault);const seen = new Set<string>([activeResolved]);- const origins: SearchOrigin[] = [- Object.freeze({- alias: "local",- label: "local",- vault: activeResolved,- kind: "active" as const,- }),- ];+ const origins: SearchOrigin[] = [origin("local", "local", activeResolved, "active")];for (const profile of listProfiles(configPath).profiles) {const vault = resolve(profile.vault);- if (seen.has(vault) || !isDirectory(vault)) continue;+ if (seen.has(vault)) continue;seen.add(vault);- origins.push(- Object.freeze({- alias: profile.name,- label: `profile/${profile.name}`,- vault,- kind: "profile" as const,- }),- );+ origins.push(origin(profile.name, `profile/${profile.name}`, vault, "profile"));}+ // `RecallSourceStatus.broken` is deliberately not consulted: it is one+ // boolean over "absent" and "could not look", and the whole point of the+ // verdict is that those are different answers with different repairs.for (const source of listRecallSources(configPath, activeVault)) {const vault = resolve(source.vault);- if (seen.has(vault) || source.broken) continue;+ if (seen.has(vault)) continue;seen.add(vault);- origins.push(- Object.freeze({- alias: source.alias,- label: `source/${source.alias}`,- vault,- kind: "source" as const,- }),- );+ origins.push(origin(source.alias, `source/${source.alias}`, vault, "source"));+ }+ // The shared namespace is a WRITE target for the mirror; enumerating it+ // here is what makes it readable at all, so a vault an agent mirrors into+ // stops being a sink with no way back out.+ const shared = resolveSharedNamespace(configPath);+ if (shared !== null) {+ const vault = resolve(shared);+ if (!seen.has(vault)) {+ seen.add(vault);+ origins.push(origin(SHARED_ORIGIN_LABEL, SHARED_ORIGIN_LABEL, vault, "shared"));+ }}return Object.freeze(origins);}diff --git a/src/core/brain/portability/preference-restore.ts b/src/core/brain/portability/preference-restore.tsindex c510b197..2cf8c3c8 100644--- a/src/core/brain/portability/preference-restore.ts+++ b/src/core/brain/portability/preference-restore.ts@@ -66,7 +66,11 @@*/import { REDACTION_PLACEHOLDER } from "../../redactor.ts";-import { collectExportRows, type ExportedPreferenceRow } from "../export.ts";+import {+ collectPreferenceRows,+ type ExportedPreferenceRow,+ type PreferenceParseFailure,+} from "../export.ts";import { topicKey } from "../dream-plan.ts";import {BrainCollisionError,@@ -232,8 +236,30 @@ export interface PreferenceRestoreResult {* Folded topic keys that more than one raw topic now claims in the* destination vault as a result of this restore. Empty for a restore that* created none - the ordinary case.+ *+ * Read together with {@link topicScanUnreadable}: an empty list beside a+ * non-empty one is "no collision among the rules I could read", not "no+ * collision".*/readonly topicKeyCollisions: ReadonlyArray<RestoredTopicKeyCollision>;+ /**+ * Destination preference files the prior-topic scan could not parse.+ *+ * The scan reads the DESTINATION vault to learn which topics each+ * existing rule already claims, and `collectExportRows` refuses the whole+ * directory when any file in it is unreadable - correctly, for an export,+ * where "there is no caller for whom a shorter list is the right answer".+ * An import is that caller. Letting the refusal through made one+ * pre-existing malformed rule in the destination abort an entire import,+ * wholesale, on a condition that has nothing to do with the bundle being+ * carried; the rows would have written fine.+ *+ * So the import proceeds on the readable rules and says so here. Empty+ * for a healthy destination, which is every ordinary run, so a clean+ * result is unchanged. Non-empty means {@link topicKeyCollisions} is a+ * partial answer and every surface that renders one must render this too.+ */+ readonly topicScanUnreadable: ReadonlyArray<PreferenceParseFailure>;}export interface RestorePreferencesOptions {@@ -523,8 +549,10 @@ export function restorePreferences(const derived: PreferenceRestoreDerivation[] = [];// The destination's topics BEFORE this run, so a row that overwrites a// rule of the same id replaces its claim rather than contending with it.+ // Partial by design, and reported: see `topicScanUnreadable`.+ const scan = collectPreferenceRows(vault);const priorTopics = new Map<string, string>();- for (const existing of collectExportRows(vault)) priorTopics.set(existing.id, existing.topic);+ for (const existing of scan.rows) priorTopics.set(existing.id, existing.topic);const restoredTopics = new Map<string, string>();for (let index = 0; index < rows.length; index++) {@@ -563,6 +591,7 @@ export function restorePreferences(fieldsNotRestored: PREFERENCE_FIELDS_NOT_RESTORED,derived: Object.freeze(derived),topicKeyCollisions: collisionsAfterRestore(priorTopics, restoredTopics),+ topicScanUnreadable: Object.freeze(scan.failures),});}diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex 53dd5f2f..c75b86f7 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -37,7 +37,12 @@ import { existsSync, readFileSync, unlinkSync } from "node:fs";import { basename, dirname, join, relative } from "node:path";import type { FrontmatterMap } from "../types.ts";-import { formatFrontmatter, parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";+import {+ formatFrontmatter,+ parseFrontmatter,+ parseFrontmatterWithNotices,+ writeFrontmatterAtomic,+} from "../vault.ts";import { BrainParseError } from "./parse-error.ts";import { FrontmatterTierConflictError, mergeFrontmatterTiered } from "./frontmatter-tiers.ts";import { loadSchemaPack } from "./schema-pack.ts";@@ -49,7 +54,11 @@ import {} from "./schema-vocab.ts";import { brainDirsForWrite, preferencePath, retiredPath, validateSlug } from "./paths.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";-import { OWNER_UNRESOLVED } from "../graph/agent-scope.ts";+import { OWNER_UNRESOLVED, ownerStampFor } from "../graph/agent-scope.ts";+import { resolveAgentName, UNCONFIGURED_AGENT_NAME } from "../config.ts";+import { DEGRADATION_CODE } from "../integrity/degradation.ts";+import { GATE_MODE } from "../integrity/stamp.ts";+import { loadIntegrityConfigForWrite } from "./policy.ts";import { asProvenanceLevel, type ProvenanceLevel } from "./provenance/provenance.ts";import { sanitisePrinciple } from "./text/sanitize-principle.ts";import {@@ -263,6 +272,16 @@ export interface WritePreferenceInput {export interface WritePreferenceOptions {/** When true, overwrite an existing file at the target path. */readonly overwrite?: boolean;+ /**+ * Plugin config the writing agent's identity is resolved from when the+ * ownership gate stamps a newly created preference. Absent falls back+ * to the default config discovery, which is what every other core+ * writer that takes an identity does (`note.ts`, `decisions/record.ts`).+ * A surface that runs against a non-default config - the MCP server+ * started with `--config`, any `o2b brain` verb - passes its own, so+ * the stamped owner is the identity that surface answers under.+ */+ readonly configPath?: string;}export interface ParsePreferenceOptions {@@ -361,12 +380,18 @@ export function writePreference(const path = preferencePath(vault, slug);const id = `pref-${slug}`;+ // Ownership (a-label-is-not-a-boundary, U1). Resolved BEFORE the+ // idempotency hash so a write that changes the owner cannot dedupe+ // against one that did not - the hash already folds `owner` in for+ // exactly that reason.+ const owned = withResolvedOwner(vault, path, input, options.configPath);+// Idempotency consult (C1): a repeat with the same key + same payload// dedupes; the same key + a different payload throws before any write.- const idKey = input.idempotency_key?.trim();+ const idKey = owned.idempotency_key?.trim();let idContentHash: string | undefined;if (idKey) {- idContentHash = computePayloadHash(preferencePayloadFields(input, slug));+ idContentHash = computePayloadHash(preferencePayloadFields(owned, slug));const existing = lookupKey(vault, idKey);if (existing) {if (existing.contentHash === idContentHash) {@@ -376,8 +401,8 @@ export function writePreference(}}- let metadata = preferenceFrontmatter(input, id);- const body = renderPreferenceBody(input);+ let metadata = preferenceFrontmatter(owned, id);+ const body = renderPreferenceBody(owned);if (options.overwrite && existsSync(path)) {// Tier guard (write-time-integrity-governance): rewrites merge@@ -404,7 +429,7 @@ export function writePreference(const next = formatFrontmatter(metadata, body);const prev = readFileSync(path, "utf8");if (next === prev) {- recordPreferenceKey(vault, idKey, idContentHash, input.created_at, id, path);+ recordPreferenceKey(vault, idKey, idContentHash, owned.created_at, id, path);return { path, id };}} catch {@@ -419,10 +444,150 @@ export function writePreference(vaultForRelativePath: vault,});- recordPreferenceKey(vault, idKey, idContentHash, input.created_at, id, path);+ recordPreferenceKey(vault, idKey, idContentHash, owned.created_at, id, path);return { path, id };}+/**+ * The `owner:` a write emits, in one place for every writer.+ *+ * Three sources, in this order, and the order is the whole rule:+ *+ * 1. **The caller's explicit token.** Unchanged from before this+ * existed - an importer restoring a page, or a surface that knows+ * better, still decides.+ * 2. **What the file already says.** A rewrite NEVER re-owns. Ownership+ * is a property of the agent that created the memory, so a dream+ * pass, a merge or a refresh run by anyone cannot quietly transfer+ * it, and a page created before the gate was switched on stays+ * shared rather than being retro-owned by whoever rewrote it first.+ * 3. **The server-resolved writing identity**, and only when creating a+ * new file with `integrity.owner_scope_delivery` switched on.+ *+ * With the gate `off` this returns the input untouched, so a vault that+ * never opted in is byte-identical - the same contract `agent-scope.ts`+ * and the delivery collector state for the read side.+ *+ * `warn` stamps as `fail` does, deliberately: it exists so an operator+ * can see what `fail` would withhold before tightening the gate, and a+ * mode that wrote no ownership would leave nothing to look at.+ *+ * Where they look is the FILES. This stamp is the whole of `warn`'s+ * observability today: the read surfaces are inert under `warn`+ * (`owner-scope-view.ts` states why), so the population `fail` would+ * start withholding is visible by reading `owner:` off+ * `Brain/preferences/`, not by any per-response field.+ *+ * The gate is read through {@link loadIntegrityConfigForWrite}, NOT the+ * safe loader every reader uses. This is the WRITE side of the+ * reader/writer asymmetry that loader documents: an unreadable+ * `_brain.yaml` resolves STRICT for a reader, which only withholds more,+ * but strict here means STAMP - so a single bad token in the YAML would+ * have started marking new pages with an owner the operator never asked+ * for, permanently, since ownership is carried forward and never+ * re-derived. A writer cannot infer an intent to enable ownership from a+ * file it could not read, so the write is refused with the parse failure+ * named. Absent config is a different condition and still resolves to+ * the defaults, i.e. `off`.+ */+function withResolvedOwner(+ vault: string,+ path: string,+ input: WritePreferenceInput,+ configPath: string | undefined,+): WritePreferenceInput {+ const owner = resolvedOwnerFor(vault, path, input.owner, configPath);+ return owner === undefined ? input : { ...input, owner };+}++/**+ * The `owner:` value a NEW preference file at `path` must carry, or+ * `undefined` for "write no `owner:` field".+ *+ * The rule {@link withResolvedOwner} documents, exposed on its own so a+ * writer that does not build a {@link WritePreferenceInput} can still+ * ask it. `import-claude-memory.ts` is that writer: it renders its own+ * frontmatter and calls `atomicWriteFileSync` directly, so it never+ * reached `writePreference` and every memory it imported landed+ * ownerless and was then delivered to every agent - while the claim+ * "every production preference writer stamps the identity" was held true+ * by a hand-written list of four writers that did not include it.+ *+ * Exported rather than duplicated for that reason: a second copy of this+ * decision is how the fifth writer gets it wrong again.+ */+export function resolvedOwnerFor(+ vault: string,+ path: string,+ explicit: string | undefined,+ configPath: string | undefined,+): string | undefined {+ const given = explicit?.trim();+ if (given) return given;+ let mode: string;+ try {+ mode = loadIntegrityConfigForWrite(vault).owner_scope_delivery;+ } catch (err) {+ throw new Error(+ `preference owner cannot be resolved: Brain/_brain.yaml exists but could not be ` ++ `read (${err instanceof Error ? err.message : String(err)}), so whether ` ++ `integrity.owner_scope_delivery asks this write to stamp an owner is unknown. ` ++ `A writer does not guess that: stamping would mark this page with an owner the ` ++ `operator may never have asked for, and skipping would leave it shared under a ` ++ `gate that may be on. Fix the file, then re-run.`,+ { cause: err },+ );+ }+ if (mode === GATE_MODE.off) return undefined;+ if (existsSync(path)) return carriedOwner(path).owner;+ const agent = resolveAgentName(configPath);+ const stamp = ownerStampFor(agent);+ if (stamp === null) {+ throw new Error(+ `preference owner cannot be resolved: integrity.owner_scope_delivery is ` ++ `${JSON.stringify(mode)}, which stamps the writing agent onto every new ` ++ `preference, and the resolved identity ${JSON.stringify(agent)} does not ` ++ `reduce to one ownership token - it is blank, it is not one string, or it is a ` ++ `placeholder name (${JSON.stringify(UNCONFIGURED_AGENT_NAME)} and the rest of ` ++ `PLACEHOLDER_AGENT_VALUES), which owner-scope delivery refuses as an identity ` ++ `and therefore refuses as an owner; set VAULT_AGENT_NAME or 'agent_name' in ` ++ `the plugin config to a real, non-placeholder name`,+ );+ }+ return stamp;+}++/** Attribution recorded on the notices the ownership carry-forward reads produce. */+const OWNER_CARRY_SITE = "brain.preference.owner";++/**+ * The ownership claim an existing preference file already carries, as a+ * spreadable slice - `{}` when the file makes no claim this parser can+ * reduce to one token.+ *+ * An unreadable file RAISES rather than resolving to `{}`. Every other+ * degraded read on this path can afford to fall soft, but this one+ * decides a boundary: resolving to "no claim" would republish an+ * owner-private memory to every agent on the next rewrite, and nothing+ * would have said so. A claim the parser cannot reduce to one token+ * (`owner:` as a list or a mapping) is left alone instead, because the+ * tiered frontmatter merge preserves it verbatim and re-emitting it as a+ * normalised string would rewrite bytes this writer does not own.+ */+function carriedOwner(path: string): { owner?: string } {+ const [meta, , notices] = parseFrontmatterWithNotices(path, { site: OWNER_CARRY_SITE });+ const unreadable = notices.find((n) => n.code === DEGRADATION_CODE.frontmatterUnreadable);+ if (unreadable) {+ throw new Error(+ `preference owner cannot be carried forward: ${path} exists but could not be ` ++ `read (${unreadable.detail}), so the ownership this rewrite must preserve ` ++ `is unknown`,+ );+ }+ const raw = meta["owner"];+ return typeof raw === "string" && raw.trim().length > 0 ? { owner: raw.trim() } : {};+}+/*** The identity-defining fields of a preference for idempotency hashing.* Timestamps, dream-owned counters, and confidence are excluded so a@@ -487,8 +652,15 @@ export function wouldRewritePreference(vault: string, input: WritePreferenceInpuif (!existsSync(path)) return true;try {const id = `pref-${slug}`;- const metadata = preferenceFrontmatter(input, id);- const body = renderPreferenceBody(input);+ // The same ownership resolution the write performs, or this+ // predicate reports "would change" on every owner-carrying+ // preference forever: `writePreference` carries the existing owner+ // forward, and a render that omitted it would never match the bytes+ // on disk. No config path is needed - the file exists, so the+ // resolution can only carry forward, never stamp.+ const owned = withResolvedOwner(vault, path, input, undefined);+ const metadata = preferenceFrontmatter(owned, id);+ const body = renderPreferenceBody(owned);const next = formatFrontmatter(metadata, body);const prev = readFileSync(path, "utf8");return next !== prev;diff --git a/src/core/brain/query-demand.ts b/src/core/brain/query-demand.tsindex e377b484..16f24546 100644--- a/src/core/brain/query-demand.ts+++ b/src/core/brain/query-demand.ts@@ -178,9 +178,8 @@ export const DEMAND_SECRET_TOKEN_MIN_LEN = 20;/*** Normalize a raw query into the terms actually stored: the significant- * terms (length ≥ 3, deduped) sorted for a stable bucket key, with the- * privacy filters below applied. Capped at- * {@link DEMAND_MAX_TERMS_PER_RECORD}.+ * terms, deduped and sorted for a stable bucket key, with the privacy+ * filters below applied. Capped at {@link DEMAND_MAX_TERMS_PER_RECORD}.*/export function normalizeQueryTerms(query: string): string[] {return sanitizeTerms(significantTerms(query));@@ -190,7 +189,15 @@ function sanitizeTerms(terms: ReadonlyArray<string>): string[] {const out = new Set<string>();for (const raw of terms) {const term = raw.toLocaleLowerCase().trim();- if (term.length < 3 || term.length > DEMAND_TERM_MAX_LEN) continue;+ // Upper bound only. The lower bound of three characters used to sit+ // here too, mirroring the one `significantTerms` carried, and it+ // carried the same defect: a query written in a script whose words+ // are one or two characters produced no terms, so it could never+ // form a demand bucket and its recall gaps were invisible to the+ // promotion loop - a whole language silently unrepresented in the+ // measurement. Nothing about a short term makes it more identifying,+ // which is what the remaining filters here are for.+ if (term.length === 0 || term.length > DEMAND_TERM_MAX_LEN) continue;if (isSecretShapedTerm(term)) continue;// Belt-and-suspenders: a term the key/value redactor still rewrites// is secret-shaped — never a legitimate query word, so drop it ratherdiff --git a/src/core/brain/query.ts b/src/core/brain/query.tsindex 1cbf8172..bb4c34cd 100644--- a/src/core/brain/query.ts+++ b/src/core/brain/query.ts@@ -34,6 +34,7 @@ import { filterExpired, isExpired } from "./expiration.ts";import type { BrainLogEntry } from "./log.ts";import { listLogDates, readLogDay } from "./log-jsonl.ts";import { parsePreference, parseRetired } from "./preference.ts";+import { ownerScopeView, type OwnerScopeView } from "./owner-scope-view.ts";import { parseSignal } from "./signal.ts";import { isTombstoned } from "./lifecycle/tombstone.ts";import { parseFrontmatter } from "../vault.ts";@@ -112,6 +113,20 @@ export interface QueryByTopicOptions {readonly showExpired?: boolean;/** Wall clock the expiration is compared against. Defaults to `new Date()`. */readonly now?: Date;+ /**+ * Owner scope the topic's CURRENT RULE is selected under+ * (a-label-is-not-a-boundary, U3). Absent / `null` selects as before.+ *+ * It has to reach the selection rather than filter the result,+ * because a topic resolves to exactly one preference - the first+ * match by filename - and several preferences may carry the topic.+ * Filtering afterwards would drop the row and report the topic as+ * having no rule at all, so one owner's private preference sorting+ * ahead of the shared one would HIDE the shared one from everybody+ * else. Skipping the invisible candidates during the walk returns the+ * rule this caller actually has.+ */+ readonly ownerScope?: string | null;}// ----- Public API -----------------------------------------------------------@@ -234,10 +249,11 @@ export function queryByTopic(signals = filterExpired(signals, { now, showExpired });// Current rule — prefer the active preference; fall back to retired.+ const view = ownerScopeView(vault, options.ownerScope ?? null);let preference: BrainPreference | BrainRetired | null = null;- preference = findPreferenceForTopic(dirs.preferences, want, "preference");+ preference = findPreferenceForTopic(dirs.preferences, want, "preference", view);if (!preference) {- preference = findPreferenceForTopic(dirs.retired, want, "retired");+ preference = findPreferenceForTopic(dirs.retired, want, "retired", view);}// Expiration filter (C5): an active preference past its expiration_date// is dropped from the default result (surfaced only under showExpired).@@ -356,6 +372,7 @@ function findPreferenceForTopic(dir: string,topic: string,kind: "preference" | "retired",+ view: OwnerScopeView,): BrainPreference | BrainRetired | null {if (!existsSync(dir)) return null;const prefix = kind === "preference" ? "pref-" : "ret-";@@ -378,7 +395,9 @@ function findPreferenceForTopic(if (isTombstoned(parseFrontmatter(path)[0])) continue;try {const parsed = kind === "preference" ? parsePreference(path) : parseRetired(path);- if (parsed.topic === topic) return parsed;+ // Skipped, not returned-then-dropped: see `ownerScope` on+ // {@link QueryByTopicOptions}.+ if (parsed.topic === topic && view.visible(parsed.id)) return parsed;} catch {// Unit F, deliberately NOT converted - same reasoning as// collectSignals above: `parsePreference` / `parseRetired` throw ondiff --git a/src/core/brain/recall-adequacy.ts b/src/core/brain/recall-adequacy.tsindex 854a403d..d8c38874 100644--- a/src/core/brain/recall-adequacy.ts+++ b/src/core/brain/recall-adequacy.ts@@ -34,14 +34,57 @@ export const RECALL_ADEQUACY_ACTIONS = ["proceed", "re_recall", "abstain"] as coexport type RecallAdequacyAction = (typeof RECALL_ADEQUACY_ACTIONS)[number];export interface RecallAdequacyThresholds {- /** Top score at/above which recall is sufficient. */+ /** Match quality at/above which recall is sufficient. */readonly sufficient: number;- /** Top score at/above which recall is at least weak (below => insufficient). */+ /** Match quality at/above which recall is at least weak (below => insufficient). */readonly weak: number;/** Minimum usable-result count below which recall cannot be sufficient. */readonly minResults: number;}+/**+ * One recall attempt, as the verdict reads it.+ *+ * The level is decided by {@link matchQuality} and never by+ * {@link scores}. It used to be decided by the top score, and that could+ * not work: the keyword lane is min-max normalised inside the candidate+ * set, so the top row of any recall with a non-empty keyword lane sits at+ * or above the configured `keywordWeight` whatever it matched -+ * `DEFAULT_KEYWORD_WEIGHT`, shipped at 0.6, which is exactly+ * {@link DEFAULT_RECALL_ADEQUACY_THRESHOLDS}.sufficient, and measured at+ * 0.65 on a freshly written keyword-only vault once the additive boost+ * layers are on top. Every keyword recall in the product graded+ * `sufficient / proceed`, `weak` and `insufficient` were unreachable, and+ * a hundredth of a point on either constant would have inverted the+ * verdict for every query at once.+ *+ * `scores` is still read, for the two things it can honestly answer: how+ * many usable results there were, and what their spread was.+ */+export interface RecallAdequacyInput {+ /**+ * Absolute match quality in `[0,1]` - the share of the query's IDF mass+ * the retrieved material covers (`SearchOutcome.idfWeightedCoverage`).+ *+ * Absolute in the sense that separates it from a score: it does not+ * depend on rank position, lane magnitude or fusion mode, so two+ * retrievals for one query are comparable. It is NOT independent of+ * which rows were delivered - see that field's docblock, which used to+ * claim it was.+ *+ * A `number`, never null, and this is a boundary rather than an+ * oversight: the producer reports `null` for a query it could not+ * weigh, and the surfaces that reach this function take the value from+ * a CALLER (`match_quality`, `src/mcp/coerce.ts`), which supplies a+ * measured number or omits the pair entirely and gets no verdict. A+ * caller holding an unmeasurable quality must omit it; forwarding a+ * substitute number is the exact move this release removed.+ */+ readonly matchQuality: number;+ /** Per-result relevance scores: the count and the mean, never the level. */+ readonly scores: ReadonlyArray<number>;+}+export const DEFAULT_RECALL_ADEQUACY_THRESHOLDS: RecallAdequacyThresholds = Object.freeze({sufficient: 0.6,weak: 0.3,@@ -54,10 +97,16 @@ export interface RecallAdequacyVerdict {/** True when the result should be flagged for review / surfaced to an operator. */readonly escalate: boolean;readonly resultCount: number;- /** Highest usable score, or 0 when there are no usable results. */+ /**+ * Highest usable score, or 0 when there are no usable results.+ * Descriptive: it reports where the top row sat in its own pool and+ * decides nothing.+ */readonly topScore: number;/** Mean of usable scores, or 0 when there are no usable results. */readonly meanScore: number;+ /** The quantity the level was decided by; see {@link RecallAdequacyInput}. */+ readonly matchQuality: number;readonly reason: string;}@@ -97,16 +146,36 @@ function round4(value: number): number {}/**- * Classify recall fitness from the relevance scores of a recall attempt- * and name the explicit action. Non-finite scores are dropped; negative- * scores clamp to 0 (search scores are normalized to [0,1]).+ * Reject a match quality that cannot be compared against the thresholds.+ *+ * An out-of-range or non-finite quality is a caller defect, not a weak+ * recall: clamping it would produce a confident `insufficient` from a+ * broken measurement, which is indistinguishable from a genuine one.+ */+function requireMatchQuality(value: number): number {+ if (!Number.isFinite(value) || value < 0 || value > 1) {+ throw new Error(`recall adequacy: matchQuality must be in [0,1]; got ${value}`);+ }+ return value;+}++/**+ * Classify recall fitness from the match quality of a recall attempt and+ * name the explicit action.+ *+ * The level comes from {@link RecallAdequacyInput.matchQuality} alone. The+ * scores decide only how many usable results there were - which is what+ * `minResults` gates - and what their spread was. Non-finite scores are+ * dropped; negative scores clamp to 0 (search scores are normalized to+ * [0,1]).*/export function assessRecallAdequacy(- scores: ReadonlyArray<number>,+ input: RecallAdequacyInput,overrides?: Partial<RecallAdequacyThresholds>,): RecallAdequacyVerdict {const thresholds = resolveThresholds(overrides);- const usable = scores.filter((s) => Number.isFinite(s)).map((s) => Math.max(0, s));+ const matchQuality = requireMatchQuality(input.matchQuality);+ const usable = input.scores.filter((s) => Number.isFinite(s)).map((s) => Math.max(0, s));const resultCount = usable.length;if (resultCount === 0) {@@ -114,46 +183,43 @@ export function assessRecallAdequacy(resultCount: 0,topScore: 0,meanScore: 0,+ matchQuality,reason: "no recall results — insufficient grounding",});}- const topScore = Math.max(...usable);- const meanScore = usable.reduce((a, b) => a + b, 0) / resultCount;+ const parts = {+ resultCount,+ topScore: Math.max(...usable),+ meanScore: usable.reduce((a, b) => a + b, 0) / resultCount,+ matchQuality,+ };- if (topScore >= thresholds.sufficient) {+ if (matchQuality >= thresholds.sufficient) {if (resultCount >= thresholds.minResults) {return finalize("sufficient", {- resultCount,- topScore,- meanScore,- reason: `top score ${round4(topScore)} >= sufficient ${thresholds.sufficient} across ${resultCount} result(s) — sufficient grounding`,+ ...parts,+ reason: `match quality ${round4(matchQuality)} >= sufficient ${thresholds.sufficient} across ${resultCount} result(s) — sufficient grounding`,});}- // Strong single hit but too few corroborating results: re-recall to+ // Strong coverage from too few corroborating results: re-recall to// broaden before answering rather than proceed on a lone signal.return finalize("weak", {- resultCount,- topScore,- meanScore,- reason: `strong top score ${round4(topScore)} but only ${resultCount} result(s) < min_results ${thresholds.minResults} — re-recall to broaden`,+ ...parts,+ reason: `strong match quality ${round4(matchQuality)} but only ${resultCount} result(s) < min_results ${thresholds.minResults} — re-recall to broaden`,});}- if (topScore >= thresholds.weak) {+ if (matchQuality >= thresholds.weak) {return finalize("weak", {- resultCount,- topScore,- meanScore,- reason: `top score ${round4(topScore)} in [${thresholds.weak}, ${thresholds.sufficient}) — weak grounding, re-recall via alternate strategy`,+ ...parts,+ reason: `match quality ${round4(matchQuality)} in [${thresholds.weak}, ${thresholds.sufficient}) — weak grounding, re-recall via alternate strategy`,});}return finalize("insufficient", {- resultCount,- topScore,- meanScore,- reason: `top score ${round4(topScore)} < weak ${thresholds.weak} — insufficient grounding, abstain`,+ ...parts,+ reason: `match quality ${round4(matchQuality)} < weak ${thresholds.weak} — insufficient grounding, abstain`,});}@@ -163,6 +229,7 @@ function finalize(readonly resultCount: number;readonly topScore: number;readonly meanScore: number;+ readonly matchQuality: number;readonly reason: string;},): RecallAdequacyVerdict {@@ -173,6 +240,7 @@ function finalize(resultCount: parts.resultCount,topScore: round4(parts.topScore),meanScore: round4(parts.meanScore),+ matchQuality: round4(parts.matchQuality),reason: parts.reason,});}diff --git a/src/core/brain/recall-inject.ts b/src/core/brain/recall-inject.tsindex b83355ca..5036dcca 100644--- a/src/core/brain/recall-inject.ts+++ b/src/core/brain/recall-inject.ts@@ -36,9 +36,27 @@ export const RECALL_INJECT_MAX_CHARS = 900;export const RECALL_INJECT_TIME_BUDGET_MS = 2_500;/**- * Normalized-score floor ([0,1]) below which the top match is too weak to be- * worth injecting, so the hook abstains. Sits well below the cross-vault- * chain-stop "confident" threshold: this gate only filters out noise.+ * Match-quality floor ([0,1]) below which the retrieved material is too+ * weak to be worth injecting, so the hook abstains.+ *+ * Compared against {@link RecallResultSet.idfWeightedCoverage} - the share+ * of the prompt's IDF mass the retrieved notes actually cover - and NOT+ * against a result score. A score cannot carry a floor here: the keyword+ * lane is min-max normalised within the candidate set, so whenever that+ * lane is non-empty the top row's score sits at or above the configured+ * `keywordWeight` (`DEFAULT_KEYWORD_WEIGHT`, 0.6; 0.65 measured on a+ * freshly written keyword-only vault) no matter how well it matched, and+ * the bottom row's at zero no matter how well IT matched.+ * Against that number this constant measured which rows the filter stack+ * had removed - it abstained hardest exactly when a visibility or owner+ * scope had just taken the pool's best row, which is the one moment the+ * survivors were still a genuine match.+ *+ * The value is unchanged at 0.35 because it is the quantity that was+ * wrong, not the bound: a brief is worth injecting once the notes cover+ * about a third of what was asked, which sits below+ * `COMPLETENESS_PARTIAL_THRESHOLD` (0.4) - this gate filters noise, it+ * does not demand a complete retrieval.*/export const RECALL_INJECT_CONFIDENCE_FLOOR = 0.35;@@ -59,6 +77,20 @@ export interface RecallCandidate {export interface RecallResultSet {readonly candidates: ReadonlyArray<RecallCandidate>;readonly total: number;+ /**+ * Absolute match quality of this retrieval in `[0,1]`: the share of the+ * query's IDF mass the candidates cover+ * (`SearchOutcome.idfWeightedCoverage`). Required, so a retriever cannot+ * leave the floor with nothing to read and no consumer can fall back to+ * a rank position.+ *+ * `null` when the retrieval had no IDF mass to weigh - the prompt+ * carried no word characters, or the corpus is empty. Nullable rather+ * than optional for the same reason: an absent field would be a+ * retriever that forgot to report, and this is a retriever reporting+ * that there is nothing to report.+ */+ readonly idfWeightedCoverage: number | null;}/** Relevance retriever: maps a query to a candidate set. */@@ -71,7 +103,22 @@ export interface RecallInjectOptions {readonly confidenceFloor?: number;}-export type RecallAbstainReason = "empty_prompt" | "no_matches" | "below_floor";+/**+ * Why the hook injected nothing.+ *+ * `unmeasurable_quality` is the fourth member and the one that is not a+ * judgement about the material: the floor reads a match quality, and for+ * a prompt with no IDF mass to weigh there is no quality to compare. The+ * hook abstains, because injecting on a measurement that did not happen+ * is the false fire the floor exists to prevent - but the reason says+ * which of the two it was, since the repairs differ (a weak match is a+ * corpus problem, an unmeasurable one is a prompt or an empty index).+ */+export type RecallAbstainReason =+ | "empty_prompt"+ | "no_matches"+ | "below_floor"+ | "unmeasurable_quality";/*** Why an attempt failed, as a closed vocabulary rather than as prose.@@ -124,8 +171,21 @@ export type RecallInjectDecision =readonly brief: string;readonly noteCount: number;readonly topScore: number;+ /** The quantity the floor was compared against; see the floor's docblock. */+ readonly matchQuality: number;+ }+ | {+ readonly kind: "abstain";+ readonly reason: RecallAbstainReason;+ readonly topScore: number;+ /**+ * The quantity the floor was compared against; see the floor's+ * docblock. `null` on the abstains where there was no comparison to+ * make - `unmeasurable_quality` always, and the earlier+ * short-circuits when the retrieval could not weigh the prompt.+ */+ readonly matchQuality: number | null;}- | { readonly kind: "abstain"; readonly reason: RecallAbstainReason; readonly topScore: number }| {readonly kind: "error";readonly fault: RecallInjectFault;@@ -159,7 +219,7 @@ export async function decideRecallInject(): Promise<RecallInjectDecision> {const query = prompt.trim();if (query.length === 0) {- return Object.freeze({ kind: "abstain", reason: "empty_prompt", topScore: 0 });+ return Object.freeze({ kind: "abstain", reason: "empty_prompt", topScore: 0, matchQuality: 0 });}const maxNotes = options.maxNotes ?? RECALL_INJECT_MAX_NOTES;const maxChars = options.maxChars ?? RECALL_INJECT_MAX_CHARS;@@ -183,17 +243,35 @@ export async function decideRecallInject(const ranked = resultSet.candidates.toSorted((a, b) => b.score - a.score || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0),);+ const matchQuality = resultSet.idfWeightedCoverage;if (ranked.length === 0) {- return Object.freeze({ kind: "abstain", reason: "no_matches", topScore: 0 });+ return Object.freeze({ kind: "abstain", reason: "no_matches", topScore: 0, matchQuality });}const topScore = ranked[0]!.score;- if (topScore < floor) {- return Object.freeze({ kind: "abstain", reason: "below_floor", topScore });+ // The floor reads match quality, never the rank position `topScore`+ // reports. `topScore` is still carried on the decision because it is+ // what the brief's bullets show and what the audit line records - it is+ // simply no longer allowed to decide anything.+ //+ // No quality means no comparison. Abstaining is the explicit choice+ // this branch makes rather than a fallback: the alternative was the+ // producer's old `1`, which put every unweighable prompt above every+ // floor and injected on it.+ if (matchQuality === null) {+ return Object.freeze({+ kind: "abstain",+ reason: "unmeasurable_quality",+ topScore,+ matchQuality,+ });+ }+ if (matchQuality < floor) {+ return Object.freeze({ kind: "abstain", reason: "below_floor", topScore, matchQuality });}const chosen = ranked.slice(0, maxNotes);const { brief, noteCount } = renderRecallBrief(chosen, resultSet.total, maxChars);- return Object.freeze({ kind: "inject", brief, noteCount, topScore });+ return Object.freeze({ kind: "inject", brief, noteCount, topScore, matchQuality });}/**@@ -304,6 +382,7 @@ export function recallInjectTelemetryMetadata(decision: "inject",note_count: decision.noteCount,top_score: decision.topScore,+ match_quality: decision.matchQuality,});}if (decision.kind === "abstain") {@@ -311,6 +390,7 @@ export function recallInjectTelemetryMetadata(decision: "abstain",reason: decision.reason,top_score: decision.topScore,+ match_quality: decision.matchQuality,});}return Object.freeze({ decision: "error", fault: decision.fault });@@ -376,6 +456,10 @@ export function defaultRecallRetriever(...(result.origin !== undefined ? { origin: result.origin } : {}),}),);- return Object.freeze({ candidates: Object.freeze(candidates), total: outcome.total });+ return Object.freeze({+ candidates: Object.freeze(candidates),+ total: outcome.total,+ idfWeightedCoverage: outcome.idfWeightedCoverage,+ });};}diff --git a/src/core/brain/schema-admin.ts b/src/core/brain/schema-admin.tsindex 349d5502..31ba176a 100644--- a/src/core/brain/schema-admin.ts+++ b/src/core/brain/schema-admin.ts@@ -276,11 +276,23 @@ export function explainSchemaToken(vault: string, rawToken: string): SchemaExpla};}+/**+ * The declarations nothing uses - and, beside them, the artifacts this+ * scan could not read.+ *+ * The second half is not a courtesy: "nothing uses this token" is a+ * claim about every artifact in the vault, so an artifact that could not+ * be read makes it provisional. Filtering the unreadable rows out would+ * hand the caller a confident orphan list computed over a partial+ * corpus, which is the shape a-label-is-not-a-boundary exists to remove.+ */export function reviewSchemaOrphans(vault: string): SchemaOrphanReport {+ const reported: ReadonlyArray<SchemaReportFinding["kind"]> = [+ "unused-declaration",+ "unreadable-artifact",+ ];return {- orphans: buildSchemaReport(vault).findings.filter(- (finding) => finding.kind === "unused-declaration",- ),+ orphans: buildSchemaReport(vault).findings.filter((finding) => reported.includes(finding.kind)),};}diff --git a/src/core/brain/schema-report.ts b/src/core/brain/schema-report.tsindex fcbfdb72..bb55f251 100644--- a/src/core/brain/schema-report.ts+++ b/src/core/brain/schema-report.ts@@ -3,6 +3,7 @@ import { join } from "node:path";import { listVaultPages } from "../vault.ts";import { loadBrainConfig } from "./policy.ts";+import { hostPathFreeReason } from "./host-path-free.ts";import { brainDirs, vaultRelative } from "./paths.ts";import { parsePreference, parseRetired } from "./preference.ts";import {@@ -44,6 +45,35 @@ export type SchemaReportFinding =readonly target: string;readonly source_type: string | null;readonly target_type: string | null;+ }+ | {+ /**+ * An artifact this report could not read or parse+ * (a-label-is-not-a-boundary, U12).+ *+ * The scans used to let a parse failure escape the whole report,+ * so ONE malformed file cost the caller every finding in the+ * vault - from the two views (`lint`, `orphans`) whose entire+ * purpose is to report malformed files. The log scan had the+ * opposite failure and the same effect: a bare `catch { continue }`+ * over the read, so an unreadable shard contributed nothing and+ * said nothing.+ *+ * It is a FINDING rather than a raise because it is also a caveat+ * on the rest of the report: a token used only inside an artifact+ * that could not be read is invisible to the usage maps, so an+ * `unused-declaration` verdict computed beside one of these is not+ * final. Both views carry these for that reason.+ *+ * `path` is vault-relative like every other finding's, which is+ * also what keeps the absolute host path out of a payload that+ * lands in model context; `detail` is the failure with no location+ * in it, so a renderer supplies the location once.+ */+ readonly kind: "unreadable-artifact";+ readonly category: SchemaVocabularyCategory;+ readonly path: string;+ readonly detail: string;};export interface BrainSchemaUsage {@@ -85,6 +115,60 @@ export function buildSchemaReport(vault: string): BrainSchemaReport {});}+/**+ * The failure text with no host location in it.+ *+ * A {@link BrainParseError} already separates the two - `detail` is the+ * prose, `path` is the location - but the scans also meet plain+ * `node:fs` and YAML errors, and those carry the absolute path INSIDE+ * the message (`ENOENT: … open '/home/…/Brain/log/x.md'`). This report+ * states its locations as vault-relative paths in a `path` field, so the+ * detail is rewritten to match rather than trusted to be clean.+ *+ * The rewrite itself is {@link hostPathFreeReason}: the export collector+ * needs the identical guarantee for the identical reason, and two copies+ * would let one of them go stale on the next error shape.+ */+function locationFreeDetail(+ err: unknown,+ vault: string,+ absolutePath: string,+ rel: string,+): string {+ return hostPathFreeReason(err, vault, absolutePath, rel);+}++/**+ * Read one artifact, or record why it could not be read and move on.+ *+ * The scans reach files whose bytes this report does not control, which+ * is the point of the two views built on it: `lint` and `orphans` exist+ * to REPORT malformed artifacts. Letting the parse escape made one bad+ * file cost the caller every finding in the vault; swallowing it (the+ * log scan's `catch { continue }`) made the same file invisible. Neither+ * is an answer, so the failure becomes a row.+ */+function readArtifact<T>(+ vault: string,+ path: string,+ category: SchemaVocabularyCategory,+ findings: SchemaReportFinding[],+ read: (path: string) => T,+): T | undefined {+ try {+ return read(path);+ } catch (err) {+ const rel = vaultRelative(path, vault);+ findings.push({+ kind: "unreadable-artifact",+ category,+ path: rel,+ detail: locationFreeDetail(err, vault, path, rel),+ });+ return undefined;+ }+}+function scanPreferences(vault: string,vocabulary: BrainSchemaVocabulary,@@ -93,7 +177,8 @@ function scanPreferences(): void {const dirs = brainDirs(vault);for (const path of listMarkdown(dirs.preferences, "pref-")) {- const pref = parsePreference(path);+ const pref = readArtifact(vault, path, "preference_types", findings, parsePreference);+ if (pref === undefined) continue;recordSchemaType(vault,path,@@ -105,7 +190,8 @@ function scanPreferences();}for (const path of listMarkdown(dirs.retired, "ret-")) {- const retired = parseRetired(path);+ const retired = readArtifact(vault, path, "preference_types", findings, parseRetired);+ if (retired === undefined) continue;recordSchemaType(vault,path,@@ -125,13 +211,20 @@ function scanSignals(findings: SchemaReportFinding[],): void {const dirs = brainDirs(vault);- for (const path of listMarkdown(dirs.inbox, "sig-")) {- const signal = parseSignal(path);- recordSchemaType(vault, path, "signal_types", signal.schema_type, vocabulary, counts, findings);- }- for (const path of listMarkdown(dirs.processed, "sig-")) {- const signal = parseSignal(path);- recordSchemaType(vault, path, "signal_types", signal.schema_type, vocabulary, counts, findings);+ for (const dir of [dirs.inbox, dirs.processed]) {+ for (const path of listMarkdown(dir, "sig-")) {+ const signal = readArtifact(vault, path, "signal_types", findings, parseSignal);+ if (signal === undefined) continue;+ recordSchemaType(+ vault,+ path,+ "signal_types",+ signal.schema_type,+ vocabulary,+ counts,+ findings,+ );+ }}}@@ -159,12 +252,10 @@ function scanLogEventKinds(findings: SchemaReportFinding[],): void {for (const path of listMarkdown(brainDirs(vault).log, "")) {- let text: string;- try {- text = readFileSync(path, "utf8");- } catch {- continue;- }+ const text = readArtifact(vault, path, "log_event_kinds", findings, (p) =>+ readFileSync(p, "utf8"),+ );+ if (text === undefined) continue;for (const line of text.split(/\r?\n/)) {const match = LOG_EVENT_HEADER_RE.exec(line.trim());if (!match) continue;diff --git a/src/core/brain/secrets/store.ts b/src/core/brain/secrets/store.tsindex 67485dae..5992ec2c 100644--- a/src/core/brain/secrets/store.ts+++ b/src/core/brain/secrets/store.ts@@ -18,6 +18,7 @@ import lockfile from "proper-lockfile";import { appendAuditRecord } from "../../reliability/audit.ts";import { brainDirsForWrite } from "../paths.ts";+import { isoSecond } from "../time.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";import { decryptValue, encryptValue, loadOrCreateKey, type EncryptedValue } from "./crypto.ts";@@ -305,7 +306,3 @@ function audit(details,});}--function isoSecond(date: Date): string {- return date.toISOString().replace(/\.\d{3}Z$/, "Z");-}diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.tsindex 2fb0c892..96bff588 100644--- a/src/core/brain/session-lifecycle.ts+++ b/src/core/brain/session-lifecycle.ts@@ -1,6 +1,7 @@import { existsSync, readFileSync } from "node:fs";import { basename, join } from "node:path";+import { delegatedAgentName } from "../agent-identity.ts";import { appendAuditRecord } from "../reliability/audit.ts";import { appendLogEvent } from "./log.ts";import { brainDirsForWrite } from "./paths.ts";@@ -12,6 +13,7 @@ import { discoverMarkersDetailed, isFeedbackMarker } from "./inline.ts";import { writeSignal } from "./signal.ts";import { isoDate, isoSecond } from "./time.ts";import { BRAIN_LOG_EVENT_KIND, BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";+import { isToolResponseError } from "./tool-outcome.ts";import { validateBrainFeedbackInput } from "./sessions/validate-feedback.ts";import { resolveSearchConfig } from "../search/index.ts";import { clearSessionFocus, sessionFocusPath } from "../search/session-focus.ts";@@ -44,9 +46,21 @@ export interface CaptureSessionLifecycleOptions {export interface CaptureSessionLifecycleResult {readonly event: string;readonly session_id?: string;+ /**+ * Host-assigned id of the delegated sub-agent this event closed. Present+ * only on `SubagentStop`, so a flat session's result shape is unchanged.+ */+ readonly agent_id?: string;readonly signals_created: number;readonly signals_deduped: number;readonly tool_replays: number;+ /**+ * Tool calls this event declined to replay because the host reported+ * them as failed. Absent when nothing was declined, so a run with+ * nothing to report keeps its previous shape and a real zero stays+ * distinguishable from a silent skip.+ */+ readonly tool_calls_failed?: number;readonly malformed: number;/** Capture-boundary verdict for this event (Memory Integrity Suite). */readonly boundary_decision: SessionCaptureDecision;@@ -87,7 +101,25 @@ interface NormalizedPayload {readonly promptText?: string;readonly toolName?: string;readonly toolInput?: unknown;+ /**+ * What the host reported the tool call returned. Declared on the hook+ * payload since the grok adapter landed and lifted past here until+ * v1.49.0, which meant a `brain_feedback` call the host REFUSED was+ * still replayed into a signal - a record for a write that never+ * happened. Read only through {@link isToolResponseError}; the response+ * body itself never reaches disk.+ */+ readonly toolResponse?: unknown;readonly cwd?: string;+ /**+ * Host-assigned id of the delegated sub-agent a `SubagentStop` event is+ * closing (Claude Code delivers `agent_id` on that event and no other).+ * Its sibling `agent_transcript_path` is deliberately NOT lifted: it is+ * a machine-local host path, this vault syncs between devices, and the+ * sub-agent's turns reach memory through `o2b brain import-session`,+ * which reads the sidechain flag and the id off the transcript itself.+ */+ readonly agentId?: string;readonly parentSessionId?: string;readonly rootSessionId?: string;readonly compressionDepth?: number;@@ -136,6 +168,18 @@ export async function captureSessionLifecycleEvent(const decision = boundary.sessionDecision(normalized.sessionId, normalized.transcriptPath);const mayWrite = decision === "capture";+ // Delegation boundary (t_0c6f31ee): `SubagentStop` is the one event that+ // names a sub-agent, and a sub-agent reuses its parent's session id - so+ // without a distinct identity here the dispatched worker's observation+ // reads as the orchestrator's own and the roster cannot tell them apart.+ // Every other event resolves to `opts.agent` exactly as before.+ const capturingAgent =+ normalized.agentId !== undefined+ ? delegatedAgentName(opts.agent, normalized.agentId)+ : opts.agent;+ const captureOpts: CaptureSessionLifecycleOptions =+ capturingAgent === opts.agent ? opts : { ...opts, agent: capturingAgent };+// Session lineage (continuity-hygiene-freshness): resolve BEFORE// recording this session's own ledger observation - the crutch// treats prior unlinked history as proof of a parallel session.@@ -240,12 +284,12 @@ export async function captureSessionLifecycleEvent(}if (mayWrite && promptText !== undefined) {- captureMarkers(vault, normalized, promptText, opts, now, ensureDedup(), counters);+ captureMarkers(vault, normalized, promptText, captureOpts, now, ensureDedup(), counters);// Fact extraction runs strictly AFTER the boundary: only captured,// unsuppressed user text reaches the pattern table.const routed = routeExtractedFacts(vault, {facts: extractFacts(promptText),- agent: opts.agent,+ agent: capturingAgent,now,sessionRef: sessionReference(normalized),dedup: ensureDedup(),@@ -255,8 +299,17 @@ export async function captureSessionLifecycleEvent(counters.facts_deduped += routed.deduped;}+ // A call the host reported as FAILED is not replayed: `brain_feedback`+ // refused to write, and replaying its input would mint the very record+ // the tool declined to create. The decline is counted rather than+ // swallowed, so a run that dropped something says so.+ let toolCallsFailed = 0;if (mayWrite && normalized.toolName === "brain_feedback") {- captureToolFeedback(vault, normalized, opts, now, ensureDedup(), counters);+ if (isToolResponseError(normalized.toolResponse)) {+ toolCallsFailed++;+ } else {+ captureToolFeedback(vault, normalized, captureOpts, now, ensureDedup(), counters);+ }}// Session-scoped focus lifecycle (Agent Surface Suite, t_5b478e47):@@ -309,10 +362,10 @@ export async function captureSessionLifecycleEvent(counters.suppressed_messages++;continue;}- captureMarkers(vault, normalized, turn.text, opts, now, ensureDedup(), counters);+ captureMarkers(vault, normalized, turn.text, captureOpts, now, ensureDedup(), counters);const routed = routeExtractedFacts(vault, {facts: extractFacts(turn.text),- agent: opts.agent,+ agent: capturingAgent,now,sessionRef: sessionReference(normalized),dedup: ensureDedup(),@@ -342,7 +395,7 @@ export async function captureSessionLifecycleEvent(resolveSessionHandoff()) {try {- handoffPath = (await writeHandoffNoteFromTranscript(vault, normalized, opts.agent, now))+ handoffPath = (await writeHandoffNoteFromTranscript(vault, normalized, capturingAgent, now))?.path;} catch {// ignore - a malformed transcript never blocks lifecycle capture@@ -372,7 +425,7 @@ export async function captureSessionLifecycleEvent(let logPath: string | undefined;if (mayWrite && !opts.dryRun) {- logPath = appendLifecycleLog(vault, normalized, opts.agent, now, counters);+ logPath = appendLifecycleLog(vault, normalized, capturingAgent, now, counters);// Dedup observability (Unit F): persist the exact-hash drop counts// this event produced, keyed by the session being re-ingested.// Signals and facts are one count - both are items this event tried@@ -391,13 +444,15 @@ export async function captureSessionLifecycleEvent(const auditPath = appendAuditRecord(join(brainDirsForWrite(vault).log, "session-lifecycle"), {timestamp: now.toISOString(),- actor: opts.agent,+ actor: capturingAgent,action: "session_lifecycle_capture",target: "Brain/session-lifecycle",ok: true,details: {event: normalized.event,...(normalized.sessionId ? { session_id: normalized.sessionId } : {}),+ ...(normalized.agentId ? { agent_id: normalized.agentId } : {}),+ ...(toolCallsFailed > 0 ? { tool_calls_failed: toolCallsFailed } : {}),dry_run: opts.dryRun === true,boundary_decision: decision,...(normalized.interrupted === true ? { interrupted: true } : {}),@@ -429,9 +484,11 @@ export async function captureSessionLifecycleEvent(return {event: normalized.event,...(normalized.sessionId ? { session_id: normalized.sessionId } : {}),+ ...(normalized.agentId ? { agent_id: normalized.agentId } : {}),signals_created: counters.signals_created,signals_deduped: counters.signals_deduped,tool_replays: counters.tool_replays,+ ...(toolCallsFailed > 0 ? { tool_calls_failed: toolCallsFailed } : {}),malformed: counters.malformed,boundary_decision: decision,suppressed_messages: counters.suppressed_messages,@@ -549,9 +606,11 @@ function normalizePayload(payload: unknown): NormalizedPayload {const sessionStartSource = readNonEmptyString(record["source"]);const workId = readNonEmptyString(record["work_id"]);const laneId = readNonEmptyString(record["lane_id"]);+ const agentId = readNonEmptyString(record["agent_id"]);return {event,...(sessionId ? { sessionId } : {}),+ ...(agentId ? { agentId } : {}),...(transcriptPath ? { transcriptPath } : {}),...(cwd ? { cwd } : {}),...(parentSessionId ? { parentSessionId } : {}),@@ -566,6 +625,7 @@ function normalizePayload(payload: unknown): NormalizedPayload {? { toolName: readNonEmptyString(record["tool_name"])! }: {}),...("tool_input" in record ? { toolInput: record["tool_input"] } : {}),+ ...("tool_response" in record ? { toolResponse: record["tool_response"] } : {}),malformed: 0,};}diff --git a/src/core/brain/session-recall.ts b/src/core/brain/session-recall.tsindex cc388a7f..fbbbb79a 100644--- a/src/core/brain/session-recall.ts+++ b/src/core/brain/session-recall.ts@@ -7,7 +7,11 @@ import {clipPayloadToBudget,listContinuityRecords,} from "./continuity/store.ts";-import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";+import {+ CONTINUITY_AGENT_ID_KEY,+ type ContinuityRecord,+ type ContinuitySourceRef,+} from "./continuity/types.ts";import { readLineageLedger } from "./lineage/ledger.ts";import type { SessionLineage } from "./lineage/types.ts";import type { SessionTurn } from "./sessions/types.ts";@@ -361,10 +365,29 @@ function importRawTurn(text_hash: textHash,dedupe_key: dedupeKey,...lineagePayloadFields(lineage),+ ...delegationPayloadFields(turn),},});}+/**+ * The delegation boundary, as additive payload fields.+ *+ * A sub-agent's transcript reuses its parent's session id, so without+ * these two keys a recalled turn cannot say which agent produced it -+ * which is what `docs/observability.md` recorded as the missing+ * parent/child thread. `agent_id` is the key the envelope already+ * protects from an output-budget clip, so a clipped delegated turn stays+ * attributable. Absent on a flat turn, so an ordinary session's records+ * are byte-identical to what they were.+ */+function delegationPayloadFields(turn: SessionTurn): Record<string, unknown> {+ return {+ ...(turn.agentId !== undefined ? { [CONTINUITY_AGENT_ID_KEY]: turn.agentId } : {}),+ ...(turn.sidechain === true ? { sidechain: true } : {}),+ };+}+function importSummaryDepth(vault: string,sessionId: string,diff --git a/src/core/brain/sessions/claude.ts b/src/core/brain/sessions/claude.tsindex b60589be..4dc7a95a 100644--- a/src/core/brain/sessions/claude.ts+++ b/src/core/brain/sessions/claude.ts@@ -15,6 +15,13 @@* `text` (flat-text view) and optional `toolCalls`. `system` and* `tool` roles are not emitted by Claude Code's JSONL — we map any* non-user/non-assistant `type` to skip.+ *+ * Delegated work is written to its own file under+ * `<session>/subagents/agent-<id>.jsonl`, whose lines carry the PARENT's+ * `sessionId` plus their own `agentId` and `isSidechain: true`. Those two+ * fields are the only record that a turn crossed a delegation boundary,+ * so the adapter lifts them onto {@link SessionTurn}; without them a+ * sub-agent transcript parses as an ordinary session of its parent.*/import { readFileSync } from "node:fs";@@ -29,6 +36,20 @@ interface ClaudeBlock {readonly input?: Record<string, unknown>;}+/**+ * Delegation discriminators a sidechain line carries, in the additive+ * shape {@link SessionTurn} declares them: absent on an ordinary turn, so+ * a flat transcript parses to exactly the object it did before.+ */+function delegationOf(o: Record<string, unknown>): Pick<SessionTurn, "agentId" | "sidechain"> {+ const rawId = o["agentId"];+ const agentId = typeof rawId === "string" && rawId.trim().length > 0 ? rawId.trim() : undefined;+ return {+ ...(o["isSidechain"] === true ? { sidechain: true } : {}),+ ...(agentId !== undefined ? { agentId } : {}),+ };+}+/** Parse a single Claude JSONL line into a `SessionTurn`, or null to skip. */function turnFromLine(obj: unknown, fallbackIndex: number): SessionTurn | null {if (obj === null || typeof obj !== "object") return null;@@ -38,6 +59,7 @@ function turnFromLine(obj: unknown, fallbackIndex: number): SessionTurn | null {const role = o["type"];if (role !== "user" && role !== "assistant") return null;+ const delegation = delegationOf(o);const turnId =typeof o["uuid"] === "string" && o["uuid"].length > 0 ? o["uuid"] : `synth-${fallbackIndex}`;const timestamp =@@ -48,15 +70,15 @@ function turnFromLine(obj: unknown, fallbackIndex: number): SessionTurn | null {const message = o["message"];if (message === null || typeof message !== "object") {// Turn without payload — emit empty (still distinguishes user-vs-assistant).- return { turnId, timestamp, role };+ return { turnId, timestamp, role, ...delegation };}const content = (message as Record<string, unknown>)["content"];if (typeof content === "string") {- return { turnId, timestamp, role, text: content };+ return { turnId, timestamp, role, text: content, ...delegation };}if (!Array.isArray(content)) {- return { turnId, timestamp, role };+ return { turnId, timestamp, role, ...delegation };}const texts: string[] = [];const tools: SessionToolCall[] = [];@@ -79,13 +101,13 @@ function turnFromLine(obj: unknown, fallbackIndex: number): SessionTurn | null {role,...(texts.length > 0 ? { text: texts.join("\n") } : {}),...(tools.length > 0 ? { toolCalls: tools } : {}),+ ...delegation,};return turn;}export const claudeAdapter: SessionAdapter = {id: "claude",- defaultAgent: "claude",detect(firstLine: string): boolean {let obj: unknown;try {diff --git a/src/core/brain/sessions/codex.ts b/src/core/brain/sessions/codex.tsindex ac0071e4..fe3d9869 100644--- a/src/core/brain/sessions/codex.ts+++ b/src/core/brain/sessions/codex.ts@@ -107,7 +107,6 @@ function buildFunctionCallTurn(export const codexAdapter: SessionAdapter = {id: "codex",- defaultAgent: "codex",detect(firstLine: string): boolean {let obj: unknown;try {diff --git a/src/core/brain/sessions/grok.ts b/src/core/brain/sessions/grok.tsindex 2ba91976..f16e5982 100644--- a/src/core/brain/sessions/grok.ts+++ b/src/core/brain/sessions/grok.ts@@ -96,7 +96,6 @@ const ROLE_BY_KIND: Readonly<Record<string, "user" | "assistant">> = {export const grokAdapter: SessionAdapter = {id: "grok",- defaultAgent: "grok",detect(firstLine: string): boolean {return parseUpdateLine(firstLine) !== null;diff --git a/src/core/brain/sessions/hermes.ts b/src/core/brain/sessions/hermes.tsindex 305c4064..5d6e57d2 100644--- a/src/core/brain/sessions/hermes.ts+++ b/src/core/brain/sessions/hermes.ts@@ -97,7 +97,6 @@ function buildTurn(obj: Record<string, unknown>, fallbackIndex: number): Sessionexport const hermesAdapter: SessionAdapter = {id: "hermes",- defaultAgent: "hermes",detect(firstLine: string): boolean {let obj: unknown;try {diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.tsindex 1eac669c..39fbca52 100644--- a/src/core/brain/sessions/import.ts+++ b/src/core/brain/sessions/import.ts@@ -28,6 +28,7 @@import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";import { basename, join, resolve } from "node:path";+import { delegatedAgentName } from "../../agent-identity.ts";import { readSkillOfferId, SKILL_OFFER_ID_KEY } from "../../surface/skill-offer.ts";import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "../dedup-hash.ts";import { appendContinuityRecord } from "../continuity/store.ts";@@ -424,7 +425,7 @@ export async function importSession(if (mayWrite && turn.text && turn.role === "user") {const routed = routeExtractedFacts(vault, {facts: extractFacts(turn.text),- agent: agentLabelForTurn(turn, adapter.id, opts.agent),+ agent: agentLabelForTurn(turn, opts.agent),now,sessionRef: `${sessionKey}#${turn.turnId}`,dedup,@@ -455,7 +456,7 @@ export async function importSession(signal: m.signal,principle: m.principle,...(m.scope ? { scope: m.scope } : {}),- agent: m.agent ?? agentLabelForTurn(turn, adapter.id, opts.agent),+ agent: m.agent ?? agentLabelForTurn(turn, opts.agent),...(m.note ? { note: m.note } : {}),turnId: turn.turnId,eventTimestamp: turn.timestamp,@@ -487,7 +488,7 @@ export async function importSession(sourceRefs: [{ id: `${sessionKey}:${call.id ?? turn.turnId}:${invokedSkill}` }],payload: {skill: invokedSkill,- agent: agentLabelForTurn(turn, adapter.id, opts.agent),+ agent: agentLabelForTurn(turn, opts.agent),tool: call.name,runtime: adapter.id,...(citedOffer !== null ? { [SKILL_OFFER_ID_KEY]: citedOffer } : {}),@@ -517,7 +518,7 @@ export async function importSession(signal: v.signal,principle: v.principle,...(v.scope ? { scope: v.scope } : {}),- agent: v.agent ?? agentLabelForTurn(turn, adapter.id, opts.agent),+ agent: v.agent ?? agentLabelForTurn(turn, opts.agent),...(v.raw ? { note: v.raw } : {}),turnId: call.id ?? turn.turnId,eventTimestamp: turn.timestamp,@@ -594,13 +595,28 @@ export async function importSession(/*** Compose the `agent` field for a session-imported signal. Order of- * preference: the marker / tool-input's explicit agent (handled by- * the caller, not here), then a per-adapter default, finally- * `opts.agent`.+ * preference, highest first:+ *+ * 1. the marker / tool-input's explicit agent (handled by the caller,+ * not here);+ * 2. the DELEGATED identity, when the turn carries the host's sub-agent+ * id - a sidechain turn was written by a different agent than the one+ * that opened the session, and a sub-agent transcript reuses the+ * parent's session id, so this is the only place the boundary+ * survives;+ * 3. `opts.agent` - `--agent` when the operator passed one, otherwise the+ * server-resolved identity.+ *+ * There is no per-adapter constant below that any more. It sat at the TOP+ * of this order while being non-empty in every shipped adapter, so+ * `opts.agent` was unreachable and `--agent` was validated and discarded;+ * and the three constants it stamped - `claude`, `codex`, `hermes` - are+ * strings `normalizeAgentArgument` rejects as placeholders on every other+ * surface, so imported memory was attributed to a name no writer could+ * have named itself.*/-function agentLabelForTurn(turn: SessionTurn, adapter: string, fallback: string): string {- void turn; // reserved for future per-turn role-aware fallback- return getAdapter(adapter).defaultAgent.trim() || fallback;+function agentLabelForTurn(turn: SessionTurn, fallback: string): string {+ return turn.agentId !== undefined ? delegatedAgentName(fallback, turn.agentId) : fallback;}/**diff --git a/src/core/brain/sessions/opencode.ts b/src/core/brain/sessions/opencode.tsindex 64418347..1272ee83 100644--- a/src/core/brain/sessions/opencode.ts+++ b/src/core/brain/sessions/opencode.ts@@ -78,7 +78,6 @@ function buildTurn(obj: Record<string, unknown>): SessionTurn | null {export const opencodeAdapter: SessionAdapter = {id: "opencode",- defaultAgent: "opencode",detect(firstLine: string): boolean {return parseMetaLine(firstLine) !== null;},diff --git a/src/core/brain/sessions/types.ts b/src/core/brain/sessions/types.tsindex 17758171..254e0101 100644--- a/src/core/brain/sessions/types.ts+++ b/src/core/brain/sessions/types.ts@@ -12,6 +12,14 @@* Closed-set ID enum: extending to a new runtime requires adding a* new id literal here, a new module under `sessions/`, and a registry* entry — no other code path needs to change.+ *+ * An adapter no longer carries a `defaultAgent`. It duplicated `id` in all+ * five shipped adapters, and its single consumer stamped it onto every+ * imported signal ahead of the operator's own `--agent` - so three+ * runtimes attributed memory to `claude` / `codex` / `hermes`, strings+ * `normalizeAgentArgument` rejects as placeholders everywhere else, and+ * the flag the CLI validated could never take effect. Identity now comes+ * from the caller, or from the delegated turn itself.*//**@@ -70,6 +78,23 @@ export interface SessionTurn {readonly text?: string;/** Tool-use blocks emitted by the agent in this turn. */readonly toolCalls?: ReadonlyArray<SessionToolCall>;+ /**+ * Host-assigned id of the DELEGATED agent that wrote this turn.+ *+ * A sub-agent's transcript reuses its parent's session id, so the id is+ * the only thing distinguishing the two; present only where the runtime+ * records one, absent everywhere else so a flat transcript keeps the+ * pre-delegation shape exactly.+ */+ readonly agentId?: string;+ /**+ * True when the runtime marked this turn as a delegated sidechain turn.+ *+ * Only `true` is carried - an absent or false flag emits no key, for the+ * same reason the id does: an ordinary turn must stay byte-identical to+ * what it was before the boundary was readable.+ */+ readonly sidechain?: boolean;}export interface SessionAdapter {@@ -81,8 +106,6 @@ export interface SessionAdapter {* The shipped adapters carry ids from {@link SESSION_ADAPTER_ID}.*/readonly id: string;- /** Default `agent` label stamped on imported signals for this runtime. */- readonly defaultAgent: string;/*** Match the first line of the session file. Adapters identify by* structural fields (`"originator":"codex_exec"`, `"role":"session_meta"`,diff --git a/src/core/brain/shared-namespace.ts b/src/core/brain/shared-namespace.tsindex 714a881f..f8537827 100644--- a/src/core/brain/shared-namespace.ts+++ b/src/core/brain/shared-namespace.ts@@ -7,31 +7,102 @@* narrative notes) MIRROR there after the primary write succeeds, so* facts learned by one agent become visible to every agent sharing the* namespace. Attribution is carried twice: the existing `agent` field- * plus `origin_vault` (basename of the primary vault).+ * plus `origin_vault` (basename of the primary vault), which+ * `parseSignal` reads back and the agent-source provider surfaces.*- * Mirror semantics are FAIL-SOFT by contract: any mirror failure is- * swallowed and reported as `"failed"` - it must never break, delay,- * or alter the primary write. Default (key absent) is `"off"` with- * zero behavior change. One-way by design: the shared vault's own- * dream pass treats mirrored records as ordinary first-class signals.+ * Mirror semantics are FAIL-SOFT by contract: a mirror failure must never+ * break, delay, or alter the primary write. Fail-soft is not the same as+ * mute, and it used to be (a-label-is-not-a-boundary, U5): both writes sat+ * behind a bare `catch { return "failed" }`, so a permissions problem, a+ * missing shared vault, a full disk and a schema violation reached the+ * operator as one indistinguishable bit - on the one path they cannot+ * observe by any other means. Every outcome that is not `ok` now carries+ * the reason that produced it.+ *+ * Unlike the cross-vault union, the reason here carries the underlying+ * message: the shared vault is the operator's OWN configured path on their+ * OWN machine, not a foreign index whose location is a disclosure.+ *+ * One-way by design: the shared vault's own dream pass treats mirrored+ * records as ordinary first-class signals. Reading it back is a separate+ * mechanism - it is enumerated as a search origin by+ * `portability/origins.ts`.*/import { realpathSync } from "node:fs";import { basename, resolve } from "node:path";-import { discoverConfig } from "../config.ts";+import { resolveSharedNamespace } from "../config.ts";import { appendLogEvent } from "./log.ts";import { writeSignal, type WriteSignalInput, type WriteSignalOptions } from "./signal.ts";import { isoSecond } from "./time.ts";import { BRAIN_LOG_EVENT_KIND } from "./types.ts";-export type MirrorOutcome = "ok" | "failed" | "off";+export { resolveSharedNamespace };++/**+ * How one mirror write ended.+ *+ * `off` is not a member: the key being absent is expressed by the caller+ * never asking, and every caller reports the absence by omitting the field+ * entirely. A member no producer can return is a promise the surface does+ * not keep, so the token was retracted rather than kept "for later".+ *+ * `misconfigured` is split from `failed` because the two are the same word+ * for opposite situations: a shared namespace pointing at the origin vault+ * is decided before any I/O and is repaired by editing one config key,+ * while `failed` is a write that was attempted and raised. Reporting a+ * self-mirror identically to an unmounted disk sent the operator after the+ * wrong fault.+ */+export const MIRROR_OUTCOME = Object.freeze({+ /** The record landed in the shared vault. */+ ok: "ok",+ /** The write was attempted and raised; `reason` carries the message. */+ failed: "failed",+ /** Refused before any I/O; `reason` names the operator's misconfiguration. */+ misconfigured: "misconfigured",+} as const);++/** Closed union over {@link MIRROR_OUTCOME}. */+export type MirrorOutcome = (typeof MIRROR_OUTCOME)[keyof typeof MIRROR_OUTCOME];++/** Membership list, best outcome first. */+export const MIRROR_OUTCOMES: ReadonlyArray<MirrorOutcome> = Object.freeze([+ MIRROR_OUTCOME.ok,+ MIRROR_OUTCOME.failed,+ MIRROR_OUTCOME.misconfigured,+]);++/** Narrow a value read back off a payload or across a tool boundary. */+export function isMirrorOutcome(value: unknown): value is MirrorOutcome {+ return typeof value === "string" && (MIRROR_OUTCOMES as ReadonlyArray<string>).includes(value);+}++/** One mirror write's outcome and, unless it succeeded, why. */+export interface MirrorReport {+ readonly outcome: MirrorOutcome;+ /** Absent exactly when the outcome is `ok`. */+ readonly reason?: string;+}++/** The one sentence the self-mirror guard reports, so no caller reinvents it. */+const SELF_MIRROR_REASON =+ "shared_namespace resolves to the origin vault, which would double-write every record";++const OK: MirrorReport = Object.freeze({ outcome: MIRROR_OUTCOME.ok });-/** Shared-namespace root from the device config, or null when off. */-export function resolveSharedNamespace(configPath?: string | null): string | null {- const discovery = discoverConfig(configPath ?? undefined);- const value = discovery.data["shared_namespace"]?.trim();- return value ? value : null;+const SELF_MIRROR: MirrorReport = Object.freeze({+ outcome: MIRROR_OUTCOME.misconfigured,+ reason: SELF_MIRROR_REASON,+});++/** Keep a thrown non-Error readable instead of casting it to one unchecked. */+function failureReason(exc: unknown): MirrorReport {+ return Object.freeze({+ outcome: MIRROR_OUTCOME.failed,+ reason: exc instanceof Error ? exc.message : String(exc),+ });}/**@@ -44,13 +115,13 @@ export function mirrorSignal(originVault: string,input: WriteSignalInput,options: WriteSignalOptions = {},-): MirrorOutcome {- if (isSelfMirror(sharedVault, originVault)) return "failed";+): MirrorReport {+ if (isSelfMirror(sharedVault, originVault)) return SELF_MIRROR;try {writeSignal(sharedVault, { ...input, origin_vault: basename(originVault) }, options);- return "ok";- } catch {- return "failed";+ return OK;+ } catch (exc) {+ return failureReason(exc);}}@@ -65,8 +136,8 @@ export function mirrorNote(sharedVault: string,originVault: string,input: MirrorNoteInput,-): MirrorOutcome {- if (isSelfMirror(sharedVault, originVault)) return "failed";+): MirrorReport {+ if (isSelfMirror(sharedVault, originVault)) return SELF_MIRROR;try {appendLogEvent(sharedVault, {timestamp: isoSecond(input.now ?? new Date()),@@ -77,17 +148,36 @@ export function mirrorNote(origin_vault: basename(originVault),},});- return "ok";- } catch {- return "failed";+ return OK;+ } catch (exc) {+ return failureReason(exc);}}+/** The fields a result surface adds for a mirror it performed. */+export interface MirrorReportFields {+ readonly mirror?: MirrorOutcome;+ readonly mirror_reason?: string;+}++/**+ * Flatten a report onto a result payload, or contribute nothing when no+ * mirror was configured. One composer for the three surfaces that report a+ * mirror - the MCP feedback tool, the note writer and the CLI - so a+ * diagnosis cannot reach a caller on one surface and be dropped on another.+ */+export function mirrorReportFields(report: MirrorReport | undefined): MirrorReportFields {+ if (report === undefined) return {};+ return {+ mirror: report.outcome,+ ...(report.reason !== undefined ? { mirror_reason: report.reason } : {}),+ };+}+/*** A shared namespace pointing back at the origin vault would* double-write every record into its own store. That is always an- * operator misconfiguration - surface it as `failed` rather than- * silently duplicating.+ * operator misconfiguration, and it is reported as one.*/function isSelfMirror(sharedVault: string, originVault: string): boolean {return canonicalPath(sharedVault) === canonicalPath(originVault);diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex 7499e800..ecb8e7e8 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -597,6 +597,12 @@ export function parseSignal(path: string, options: ParseSignalOptions = {}): Braconst dedup_hash = readOptionalTrimmedString(meta, "dedup_hash", path);const session_ref = readOptionalTrimmedString(meta, "session_ref", path);+ // The write side has emitted `origin_vault` since the shared-namespace+ // mirror shipped and nothing read it back, so a mirrored signal arrived in+ // the shared vault indistinguishable from one written there+ // (a-label-is-not-a-boundary, U5). Absent on every non-mirrored signal,+ // which is every signal a single-vault install writes.+ const origin_vault = readOptionalTrimmedString(meta, "origin_vault", path);const result: BrainSignal = {kind: "brain-signal",@@ -614,6 +620,7 @@ export function parseSignal(path: string, options: ParseSignalOptions = {}): Bra...(schema_type !== undefined ? { schema_type } : {}),...(dedup_hash !== undefined ? { dedup_hash } : {}),...(session_ref !== undefined ? { session_ref } : {}),+ ...(origin_vault !== undefined ? { origin_vault } : {}),...readBiTemporal(meta, path),...(readOptionalTrimmedString(meta, "expiration_date", path) !== undefined? { expiration_date: readOptionalTrimmedString(meta, "expiration_date", path) }diff --git a/src/core/brain/tool-outcome.ts b/src/core/brain/tool-outcome.tsnew file mode 100644index 00000000..6215f750--- /dev/null+++ b/src/core/brain/tool-outcome.ts@@ -0,0 +1,23 @@+/**+ * One reading of a host's `tool_response`, shared by every hook that has+ * to know whether the call it is reacting to actually succeeded.+ *+ * Two hooks fire AFTER a tool ran and both must skip a failure: the+ * post-write reminder must not nudge about an edit that never landed, and+ * lifecycle capture must not replay a `brain_feedback` call the host+ * refused - a replayed failure mints a signal for a write that did not+ * happen, which is the opposite of a record.+ *+ * The shape is Claude Code's: a failed tool result carries+ * `is_error: true`. `success: false` is accepted alongside it because the+ * grok payload spells the same verdict that way. A response the host said+ * nothing about is NOT a failure - absence of a verdict is not a verdict,+ * and treating it as one would silence every runtime that does not report+ * per-call outcomes at all.+ */++export function isToolResponseError(response: unknown): boolean {+ if (response === null || typeof response !== "object") return false;+ const record = response as Record<string, unknown>;+ return record["is_error"] === true || record["success"] === false;+}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 3d399606..1c900307 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -739,6 +739,13 @@ export interface BrainSignal {* `<path>#<turn-id>`. Empty / absent for inline / live signals.*/readonly session_ref?: string;+ /**+ * Basename of the vault this signal was mirrored FROM, stamped by the+ * shared-namespace mirror (t_936a1a61). Absent on every signal written+ * directly into the vault holding it, so a shared vault can tell a+ * mirrored record from a local one.+ */+ readonly origin_vault?: string;/** Bi-temporal event-time start (additive optional, v0.10.18). */readonly valid_from?: string;/** Bi-temporal event-time end (additive optional, v0.10.18). */diff --git a/src/core/config.ts b/src/core/config.tsindex 6e77e6a7..f07ef9f3 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -362,11 +362,32 @@ export function resolveVault(configPath?: string, opts: { cwd?: string } = {}):return null;}+/**+ * The identity every install writes under until one is configured.+ *+ * It is a placeholder, not a name: two unconfigured installs write under+ * the same token, so any surface that folds contributions per agent merges+ * every one of them into a single row that reads as one very busy agent+ * (a-label-is-not-a-boundary, U5). It is exported so the roster can say+ * "unconfigured" instead of repeating the literal in a second place and+ * calling it a name.+ */+export const UNCONFIGURED_AGENT_NAME = "agent";++/**+ * Whether an agent identity was actually chosen by an operator, as opposed+ * to being the placeholder {@link resolveAgentName} falls back to.+ */+export function isConfiguredAgentName(name: string): boolean {+ const trimmed = name.trim();+ return trimmed.length > 0 && trimmed !== UNCONFIGURED_AGENT_NAME;+}+/*** Resolve the agent identity used when no explicit `agent` is supplied.** Order: `VAULT_AGENT_NAME` env → `agent_name`/`agentName` in plugin config →- * the literal placeholder `"agent"`. Used by every Brain writer that needs+ * {@link UNCONFIGURED_AGENT_NAME}. Used by every Brain writer that needs* an `agent:` field (signals, evidence rows, log entries) and by the* Hermes pre_llm_call hook.*/@@ -376,9 +397,29 @@ export function resolveAgentName(configPath?: string): string {const data = discoverConfig(configPath).data;const value = data["agent_name"] ?? data["agentName"];if (value) return value;- return "agent";+ return UNCONFIGURED_AGENT_NAME;}+/**+ * Shared-namespace root from the device config, or null when off+ * (Agent Write Contract Suite, t_936a1a61).+ *+ * Lives here rather than in `brain/shared-namespace.ts` because it is a+ * device-config key resolver like {@link resolveVaultPath} and+ * {@link resolveAgentName}, and because the search-origin enumeration now+ * reads it too: a module on the fan-out path must not have to import the+ * mirror writer - and its signal, log and time dependencies - to learn one+ * config key (a-label-is-not-a-boundary, U5).+ */+export function resolveSharedNamespace(configPath?: string | null): string | null {+ const discovery = discoverConfig(configPath ?? undefined);+ const value = discovery.data[SHARED_NAMESPACE_KEY]?.trim();+ return value ? value : null;+}++/** Device-config key naming the shared vault that remember-writes mirror into. */+const SHARED_NAMESPACE_KEY = "shared_namespace";+/*** Stable per-install device identity (Memory Integrity Suite). Keys the* per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl`), so@@ -836,9 +877,33 @@ export function resolveRecallGateTelemetry(configPath?: string): boolean {/*** Recall adequacy thresholds (retrieval-precision-quality-loop,* t_b8f66fec). Configurable floors that drive the sufficient / weak /- * insufficient verdict over existing recall relevance scores. Defaults- * mirror DEFAULT_RECALL_ADEQUACY_THRESHOLDS (0.6 / 0.3 / 1). Invalid- * values fail fast rather than silently reverting to a default.+ * insufficient verdict. Defaults mirror+ * DEFAULT_RECALL_ADEQUACY_THRESHOLDS (0.6 / 0.3 / 1). Invalid values fail+ * fast rather than silently reverting to a default.+ *+ * What these floors are compared against CHANGED in+ * a-label-is-not-a-boundary, and the numbers kept their values while+ * their meaning moved. They used to bound a recall attempt's top+ * relevance SCORE, which could not work: the keyword lane is min-max+ * normalised inside the candidate set, so the top row of any recall with+ * a non-empty keyword lane scored at or above the configured+ * `search_keyword_weight` whatever it matched - shipped at 0.6, identical+ * to `recall_adequacy_sufficient`, and 0.65 as measured end to end on a+ * freshly written keyword-only vault, where the freshness prior is added+ * on top of the normalised lane. Every keyword recall in the product+ * therefore graded `sufficient / proceed`, `weak` and `insufficient` were+ * unreachable, and a hundredth of a point on either key would have+ * inverted the verdict for every query at once.+ *+ * They now bound MATCH QUALITY: the share of the query's IDF mass the+ * retrieved material covers. That share is absolute where a score was+ * relative - it does not move with rank position, lane magnitude or+ * fusion mode - though it is measured over the rows a search delivers, so+ * a narrower `limit` reports less of it. An operator who tuned these keys+ * against the old quantity was tuning something that never varied, so no+ * setting is being silently reinterpreted - but the keys do decide+ * something now, and 0.6 means "covers at least three fifths of what was+ * asked" rather than "something was returned".*/export function resolveRecallAdequacyThresholds(configPath?: string): {sufficient: number;diff --git a/src/core/egress/registry.ts b/src/core/egress/registry.tsindex 7f8e266d..1c40c172 100644--- a/src/core/egress/registry.ts+++ b/src/core/egress/registry.ts@@ -10,10 +10,21 @@* registry plus `tests/core/architecture/egress-census.test.ts` is what* stops a seventh appearing unredacted.*+ * An eighth appeared anyway, and how it appeared is the more useful half.+ * `o2b brain explorer --export` wrote the whole preference graph to an+ * operator-named file with no scan for a whole release, and the census+ * reported a clean sweep throughout - because its destination rule was a+ * hardcoded list of destination WORDS, and this flag was spelled+ * `export`. A registry whose membership rule is a name list is the same+ * defect as a boundary that is only a label, one level up. The rule was+ * widened, and a second rule added for the destinations that are not+ * files at all: the endpoints this product POSTs vault-derived bytes to.+ ** The census derives the POPULATION from source - a module that declares- * an operator-named destination flag is an egress path - and asks this- * table to account for it. It also checks the declaration against the- * source rather than trusting it: an entry claiming+ * an operator-named destination flag, or sends a body over the network,+ * is an egress path - and asks this table to account for it. It also+ * checks the declaration against the source rather than trusting it: an+ * entry claiming* {@link EGRESS_REDACTION.sharedRedactor} whose module no longer calls* `redactForEgress` fails, and so does one that declares LESS than its* module does - the answer to which is to flip the declaration, never to@@ -44,6 +55,17 @@ export const EGRESS_REDACTION = Object.freeze({sharedRedactor: "shared_redactor",/** The destination carries no vault content, so there is nothing to scan. */noVaultContent: "no_vault_content",+ /**+ * Vault-derived bytes go to a network destination without passing the+ * shared guard. Unlike the status this registry deleted, it is decidable+ * from the module's own text - the census asserts such an entry does NOT+ * call `redactForEgress`, so the day one starts scanning, the+ * declaration has to be flipped rather than left describing a gap that+ * closed. It exists because a continuous unscanned egress that no table+ * mentions is worse than one that is written down: the entry's `reason`+ * is where the decision and its cost are stated.+ */+ unscannedNetworkPayload: "unscanned_network_payload",} as const);export type EgressRedactionStatus = (typeof EGRESS_REDACTION)[keyof typeof EGRESS_REDACTION];@@ -51,6 +73,7 @@ export type EgressRedactionStatus = (typeof EGRESS_REDACTION)[keyof typeof EGRESexport const EGRESS_REDACTION_STATUSES: ReadonlyArray<EgressRedactionStatus> = Object.freeze([EGRESS_REDACTION.sharedRedactor,EGRESS_REDACTION.noVaultContent,+ EGRESS_REDACTION.unscannedNetworkPayload,]);/** Takes `unknown`: a status can arrive from a hand-edited declaration. */@@ -113,7 +136,10 @@ export const EGRESS_SITES = Object.freeze({"contract and also why it is the widest leak by volume. The manifest is redacted " +"as a tree and `okf.json` re-serialised from it; the markdown files are redacted " +"as text. A bundle whose secrets were removed is no longer a lossless round-trip " +- "of the vault, and the verb says so rather than implying otherwise.",+ "of the vault, and the verb says so rather than implying otherwise. What it does NOT " ++ "do is filter by label: a page carrying `private: true` in its frontmatter exports in " ++ "full, because the `<private>` region marker is this product's only content-derived " ++ "privacy primitive and these composers are content composers, not visibility filters.",},"brain-preference-export": {id: "brain-preference-export",@@ -151,6 +177,88 @@ export const EGRESS_SITES = Object.freeze({"the read model never re-scans. The verb now scans what it READ, which answers " +"both, and gains the truncation refusal the other five already had.",},+ "brain-explorer-export": {+ id: "brain-explorer-export",+ verb: "o2b brain explorer --export",+ module: "src/cli/brain/verbs/explorer.ts",+ redaction: R.sharedRedactor,+ reason:+ "a self-contained HTML file with the whole rule graph embedded as JSON: every " ++ "preference and retired principle verbatim, plus each one's topic, scope and " ++ "provenance counts. It is the export most likely to be handed to a person rather " ++ "than a program - it opens in a browser - and it was the one export that never " ++ "scanned anything. Redaction runs over the graph TREE before the template " ++ "substitution, so a principle whose text contains a quote cannot disturb the " ++ "document. The label rule holds here too: a preference is not withheld for carrying " ++ "a `private` tag, because the `<private>` region marker is the only content-derived " ++ "privacy primitive in this product.",+ },+ "search-embedding-openai-compat": {+ id: "search-embedding-openai-compat",+ verb: "o2b search index (embedding provider)",+ module: "src/core/search/embeddings/openai-compat.ts",+ redaction: R.unscannedNetworkPayload,+ reason:+ "the largest and most continuous egress in this product: every indexed chunk BODY " ++ "is POSTed verbatim to whichever endpoint the operator configured, for every " ++ "reindex, and nothing scans it. It is declared unscanned rather than wired to the " ++ "guard because redaction here would corrupt the thing being built - a vector " ++ "computed over a placeholder is a vector for the placeholder, so the chunk would " ++ "come back unfindable while the index reported success, which is a silent failure " ++ "where this one is at least a stated exposure. The controls that do exist are " ++ "the operator's: semantic search is off until an endpoint and a key are configured, " ++ "and the endpoint is whichever host they name, including a local one.",+ },+ "search-embedding-zeroentropy": {+ id: "search-embedding-zeroentropy",+ verb: "o2b search index (zeroentropy provider)",+ module: "src/core/search/embeddings/zeroentropy.ts",+ redaction: R.unscannedNetworkPayload,+ reason:+ "the same chunk bodies as the OpenAI-compatible provider, to a second vendor's " ++ "embed endpoint under the same operator-configured base URL. Listed separately " ++ "rather than folded into one 'embedding' entry because the census keys on the " ++ "module, and a provider that stops being reachable from the resolver would " ++ "otherwise leave a declaration covering a path nobody can find.",+ },+ "search-rerank-cross-encoder": {+ id: "search-rerank-cross-encoder",+ verb: "o2b search query --rerank",+ module: "src/core/search/rerank/cross-encoder.ts",+ redaction: R.unscannedNetworkPayload,+ reason:+ "sends the QUERY plus the candidate documents to a rerank endpoint, so it carries " ++ "vault text the embedding path may never have seen - the top-of-pool bodies of the " ++ "current result set, chosen by relevance to what the operator just asked. Unscanned " ++ "for the same reason as the embedding path: a reranker scoring placeholders returns " ++ "an order computed over text nobody wrote.",+ },+ "brain-telegram-capture": {+ id: "brain-telegram-capture",+ verb: "o2b brain telegram-run",+ module: "src/core/brain/capture/telegram-capture.ts",+ redaction: R.unscannedNetworkPayload,+ reason:+ "POSTs reply text to the Telegram Bot API, and the `/catchup` reply is composed " ++ "from vault content. The transport is built only by the CLI runner verb, so an " ++ "install that never starts the runner never reaches this path at all - which is " ++ "why it is a declared narrow exposure rather than a guard call: the bytes are a " ++ "chat message the operator asked to be sent, and refusing to send one because it " ++ "quotes a credential-shaped string would break the surface without protecting a " ++ "destination the operator did not already choose.",+ },+ "research-external-fetch": {+ id: "research-external-fetch",+ verb: "o2b brain research",+ module: "src/core/brain/research/external-fetch.ts",+ redaction: R.unscannedNetworkPayload,+ reason:+ "the one transport every research provider's POST goes through, which is why it is " ++ "declared here rather than at the provider modules that name the endpoints and " ++ "never call the network themselves. What leaves is an agent-composed search query, " ++ "not a page body, and the path is key-gated: with no key configured every call is " ++ "a typed `disabled` error, so an install that never sets one has no egress here.",+ },"install-adapter-out": {id: "install-adapter-out",verb: "o2b install --out",diff --git a/src/core/graph/agent-scope.ts b/src/core/graph/agent-scope.tsindex 495d4fc6..dedd4857 100644--- a/src/core/graph/agent-scope.ts+++ b/src/core/graph/agent-scope.ts@@ -24,6 +24,7 @@* nothing here hardcodes a natural-language phrase or a closed enum.*/+import { normalizeAgentArgument } from "../agent-identity.ts";import type { FrontmatterMap } from "../types.ts";/** NFC + trim + lower-case a single ownership token. */@@ -84,6 +85,44 @@ export function pageOwner(meta: FrontmatterMap): string | null {return ownerToken(meta["owner"]);}+/**+ * The owner token a writer stamps on a page it CREATES on behalf of+ * `agent`, or `null` when that identity cannot be reduced to one token.+ *+ * `null` is a refusal for the caller to raise. It is deliberately NOT+ * {@link OWNER_UNRESOLVED}: that token is the fail-closed reading of a+ * claim already on disk, and writing it would hide the new page from+ * every scope INCLUDING its author's - the author could not read back+ * what they had just written, and nothing would ever say why. An+ * identity a writer cannot spell is an error to report, not a page to+ * bury.+ *+ * ## Why the placeholder is refused here and not only at the reader+ *+ * `normalizeAgentArgument` is the predicate the whole product uses for+ * "is this a real identity or a name a model guessed": it rejects+ * `agent`, `assistant`, `claude`, `gpt` and the rest, and+ * `refuseOwnerScopeRequest` cites it when it refuses a caller asking to+ * be answered as one of them - "the bottom of the identity chain is the+ * literal `agent`, which that predicate rejects, so an unconfigured+ * install cannot silently become an owner"+ * (`src/mcp/owner-scope-refusal.ts`).+ *+ * That sentence was false while this function accepted the same string.+ * `resolveAgentName` never fails; it returns `UNCONFIGURED_AGENT_NAME`+ * (`"agent"`), so on an install with no `agent_name` and the gate on,+ * every new preference was stamped `owner: agent` while every caller+ * asking for `agent_scope: "agent"` was refused as unverifiable - the+ * vault accumulated owner-private memories no caller could ever be+ * shown to own. One predicate, both halves: an identity that cannot be+ * requested cannot be stamped either.+ */+export function ownerStampFor(agent: string): string | null {+ if (normalizeAgentArgument(agent) === null) return null;+ const token = ownerToken(agent);+ return token === null || token === OWNER_UNRESOLVED ? null : token;+}+/*** Normalise a caller's requested agent scope. `undefined` / blank becomes* `null`, which means "no scope requested" - no ownership filtering.diff --git a/src/core/identity-reminder.ts b/src/core/identity-reminder.tsindex 0882d1fa..1865f60d 100644--- a/src/core/identity-reminder.ts+++ b/src/core/identity-reminder.ts@@ -38,12 +38,27 @@ const TEMPLATE_PATH = resolve(* delivered by `hooks/lib/messages.ts:postWriteReminder`, which is* a different mechanism.*/-export const KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"] as const;--export type RuntimeTarget = (typeof KNOWN_RUNTIME_TARGETS)[number];--export function isRuntimeTarget(value: string | undefined): value is RuntimeTarget {- return typeof value === "string" && (KNOWN_RUNTIME_TARGETS as readonly string[]).includes(value);+export const RUNTIME_TARGET = Object.freeze({+ /** Hermes, through its Python `pre_llm_call` shim. */+ hermes: "hermes",+ /** OpenClaw, through its native `before_prompt_build` hook. */+ openclaw: "openclaw",+} as const);++/** Closed union over {@link RUNTIME_TARGET}. */+export type RuntimeTarget = (typeof RUNTIME_TARGET)[keyof typeof RUNTIME_TARGET];++/** Membership list, in the order the templates were added. */+export const KNOWN_RUNTIME_TARGETS: ReadonlyArray<RuntimeTarget> = Object.freeze([+ RUNTIME_TARGET.hermes,+ RUNTIME_TARGET.openclaw,+]);++/** Narrow a target name arriving from the environment or a caller. */+export function isRuntimeTarget(value: unknown): value is RuntimeTarget {+ return (+ typeof value === "string" && (KNOWN_RUNTIME_TARGETS as ReadonlyArray<string>).includes(value)+ );}let commonTemplateCache: string | undefined;diff --git a/src/core/install/grok-asset.ts b/src/core/install/grok-asset.tsindex 13e48121..f5ce00bc 100644--- a/src/core/install/grok-asset.ts+++ b/src/core/install/grok-asset.ts@@ -77,13 +77,31 @@ interface HookGroupSpec {* grok's rules: lifecycle events (SessionStart, UserPromptSubmit, Stop,* SessionEnd) reject a `matcher`, so they carry none; PostToolUse keeps a* matcher and lists grok's `search_replace` alongside the Claude tool names.+ *+ * "Mirroring" is asserted rather than claimed:+ * `tests/core/install/adapters/grok-hook-parity.test.ts` derives the+ * plugin's own event -> hook-name map out of `hooks/hooks.json` and+ * requires this table to cover it, with every deliberate difference+ * declared there by name and reason. It was a claim for two releases, and+ * for two releases this table was missing `SubagentStop` and `PreToolUse`+ * - so a grok install got no delegated-sub-agent capture at all, which is+ * the headline capability of one of the units that shipped alongside it.+ *+ * The MATCHERS still differ, and only the matchers: grok rejects one on a+ * lifecycle event, so `SessionStart` / `PostCompact` / `PreToolUse` carry+ * none where the plugin narrows them. That is grok's rule, not a reduced+ * hook set - an absent matcher fires on every trigger of the event.*/const HOOK_SPEC: ReadonlyArray<{ event: string; groups: ReadonlyArray<HookGroupSpec> }> = [{event: "SessionStart",groups: [{ hooks: ["active-inject", "gap-agenda", "session-capture"] }],},- { event: "UserPromptSubmit", groups: [{ hooks: ["session-capture", "recall-inject"] }] },+ {+ event: "UserPromptSubmit",+ groups: [{ hooks: ["session-capture", "recall-inject", "nav-inject"] }],+ },+ { event: "PreToolUse", groups: [{ hooks: ["pretool-orient"] }] },{event: "PostToolUse",groups: [@@ -95,6 +113,10 @@ const HOOK_SPEC: ReadonlyArray<{ event: string; groups: ReadonlyArray<HookGroupS],},{ event: "Stop", groups: [{ hooks: ["session-capture", "stop-log-guardrail"] }] },+ // 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 transcript+ // reuses the PARENT's session id - so the loss is invisible in the data.+ { event: "SubagentStop", groups: [{ hooks: ["session-capture"] }] },{ event: "SessionEnd", groups: [{ hooks: ["session-capture", "gap-promote"] }] },{ event: "PostCompact", groups: [{ hooks: ["active-inject", "session-capture"] }] },];diff --git a/src/core/redactor.ts b/src/core/redactor.tsindex 94a22563..59e867e2 100644--- a/src/core/redactor.ts+++ b/src/core/redactor.ts@@ -357,6 +357,53 @@ function isContentAddress(run: string): boolean {return CONTENT_ADDRESS_RE.test(run);}+/**+ * A SIGNAL ID: `sig-<YYYY-MM-DD>-<slug>`, the filename and frontmatter+ * `id` every taste signal in a Brain vault carries, and the target every+ * preference's `_evidenced_by` wikilink points at. The same carve-out+ * argument as {@link CONTENT_ADDRESS_RE}, arriving through a second+ * shape: 26 characters of `[A-Za-z0-9_-]` mixing letters and digits, not+ * pure hexadecimal, so `HIGH_ENTROPY_TOKEN_RE` claimed it. A slug of nine+ * characters is enough to cross the gate, which is routine, so an export+ * shipped `_evidenced_by: ["[[***REDACTED***]]"]` and the import wrote+ * that back verbatim - reporting a full success while every preference+ * that lost a signal id landed on ONE dangling wikilink. A placeholder is+ * a constant, so replacing an identifier merges the things it identified.+ *+ * The carve-out is the SHAPE, not the prefix: an ISO date, then lowercase+ * alphanumeric runs joined by dashes, which is exactly what `slugify`+ * emits plus the `-<n>` collision suffix `allocateAndCreate` appends. A+ * credential wearing a `sig-` prefix is still redacted whenever it fails+ * either half - no ISO date, or the mixed case, underscore or other+ * punctuation a slug cannot carry - which covers every credential format+ * this redactor was written against.+ *+ * It is not an absolute, and the earlier wording here said it was. A+ * secret that is entirely lowercase alphanumeric AND is written behind+ * `sig-` AND behind an ISO date passes: `sig-2026-08-16-<secret>` is+ * indistinguishable from a signal id whose slug happens to be that+ * string, because at that point it IS one by shape. Nothing narrower+ * would do without keying on the prefix, which is what the paragraph+ * above rejects - and a key wearing three disguises to reach a Brain+ * signal filename is a different threat from the one this pass is for.+ */+const SIGNAL_ID_RE = /^sig-\d{4}-\d{2}-\d{2}-[a-z0-9]+(?:-[a-z0-9]+)*$/;++function isSignalId(run: string): boolean {+ return SIGNAL_ID_RE.test(run);+}++/**+ * True when a high-entropy run is an IDENTIFIER this boundary must hand+ * through unchanged rather than a payload it may replace. One predicate+ * so the two passes that ask the question - the bare-token replacer and+ * the identifier scan - cannot drift into disagreeing about what an+ * identifier is.+ */+function isPreservedIdentifier(run: string): boolean {+ return isContentAddress(run) || isSignalId(run);+}+/*** A base64 credential: the shape `HIGH_ENTROPY_TOKEN_RE` cannot see,* because its class excludes `+` and `/`. An AWS secret access key@@ -394,7 +441,9 @@ function redactBareTokens(text: string): string {return text.replace(VENDOR_TOKEN_RE, PLACEHOLDER).replace(BASE64_SECRET_RE, PLACEHOLDER)- .replace(HIGH_ENTROPY_TOKEN_RE, (run: string) => (isContentAddress(run) ? run : PLACEHOLDER));+ .replace(HIGH_ENTROPY_TOKEN_RE, (run: string) =>+ isPreservedIdentifier(run) ? run : PLACEHOLDER,+ );}/**@@ -740,7 +789,7 @@ function identifierCarriesSecret(value: string): boolean {function keyNameCarriesSecret(name: string): boolean {if (identifierCarriesSecret(name)) return true;for (const match of name.matchAll(HIGH_ENTROPY_TOKEN_RE)) {- if (!isContentAddress(match[0])) return true;+ if (!isPreservedIdentifier(match[0])) return true;}return false;}diff --git a/src/core/search/coverage.ts b/src/core/search/coverage.tsindex 72800ddd..3ca56403 100644--- a/src/core/search/coverage.ts+++ b/src/core/search/coverage.ts@@ -20,7 +20,8 @@ import type { CompletenessReport, CompletenessVerdict } from "./types.ts";export const RARE_TERM_CORPUS_SHARE = 0.02;/**- * Significant query terms: length >= 3, deduplicated, in query order.+ * Significant query terms: every word-character run, deduplicated, in+ * query order.** Language-agnostic by construction: there is deliberately NO stopword* list. A per-language stopword set (the old English-only one) would@@ -29,15 +30,48 @@ export const RARE_TERM_CORPUS_SHARE = 0.02;* {@link buildCoverageReport} — a term that appears in most documents* earns near-zero IDF and contributes almost nothing to the weighted* coverage, in any language, without a vocabulary list.+ *+ * ## Why there is no length floor any more+ *+ * There used to be one: a token had to be three characters. It was a+ * stopword list in disguise, written for a script whose function words+ * are short and whose content words are not, and it did not survive+ * contact with a script where the common word length IS one or two+ * characters. `検索` ("search") is two characters and was dropped whole;+ * so was every one- and two-character Chinese or Japanese query, which+ * left the report with nothing to weigh and — before this changed —+ * scoring a perfect 1.0 for a retrieval that matched nothing.+ *+ * A character count cannot be made script-neutral: the same count means+ * "a function word" in one writing system and "a full noun" in another.+ * So the count is gone rather than tuned, and the job it was pretending+ * to do is left where it was always actually done, in the IDF weight. A+ * one-character term that appears in most documents earns near-zero IDF+ * in exactly the same way a three-character one does; a one-character+ * term that appears in two documents is a discriminating term and is now+ * treated as one.+ *+ * The visible cost is on the preview surfaces that share this splitter:+ * `matchOffset` can now anchor a snippet on a one-character common word+ * where it previously anchored on a three-character one. That cost is+ * the same one its docblock already accepted, one character smaller.*/export function significantTerms(query: string): string[] {const terms = new Set<string>();for (const token of query.toLocaleLowerCase().split(/[^\p{L}\p{N}_-]+/u)) {- if (token.length >= 3) terms.add(token);+ // At least one letter or digit. The splitter keeps `-` and `_` inside+ // a token so `well-known` and `snake_case` survive whole, which means+ // a run of pure punctuation (`--`) also survives the split; it is not+ // a word in any language, and with the length floor gone nothing else+ // would have stopped it from earning IDF mass.+ if (HAS_WORD_CHARACTER.test(token)) terms.add(token);}return [...terms];}+/** A token counts as a word once it carries one letter or digit. */+const HAS_WORD_CHARACTER = /[\p{L}\p{N}]/u;+/** Case-folded containment check shared by pack record building. */export function termIncludedIn(haystack: string, term: string): boolean {return haystack.toLocaleLowerCase().includes(term);@@ -99,8 +133,17 @@ export interface CoverageReport {* Support coverage weighted by IDF: the share of the query's total* IDF mass the covered terms carry. A result set matching only the* common words scores low even when it matches most terms by count.+ *+ * `null` when the query carries no IDF mass to weigh at all — see+ * {@link buildCoverageReport}. NOT a number, deliberately: the previous+ * shape reported that case as `1`, so a query nothing could be measured+ * about was indistinguishable from a complete retrieval, and every+ * threshold reading it fired at maximum confidence. A nullable field+ * makes the type system ask each consumer what it wants to do about an+ * unmeasurable query, which is the same question the code was silently+ * answering "perfect" to.*/- readonly idfWeightedCoverage: number;+ readonly idfWeightedCoverage: number | null;readonly rareTerms: ReadonlyArray<string>;readonly uncoveredRareTerms: ReadonlyArray<string>;}@@ -110,15 +153,27 @@ export const COMPLETENESS_COMPLETE_THRESHOLD = 0.8;/** IDF-weighted coverage at/above this (below complete) is partial. */export const COMPLETENESS_PARTIAL_THRESHOLD = 0.4;+/**+ * The three-way verdict, plus the fourth state that is not a verdict.+ *+ * An unmeasurable coverage (`null`) becomes `unmeasurable` rather than+ * being folded into `sparse`: "the retrieval missed" and "there was+ * nothing here to weigh" call for different repairs, and reporting the+ * second as the first would tell a reader the corpus is thin when the+ * measurement never ran.+ */export function buildCompletenessReport(coverage: CoverageReport): CompletenessReport {const covered = coverage.terms.filter((t) => t.covered).map((t) => t.term);const uncovered = coverage.terms.filter((t) => !t.covered);+ const weighted = coverage.idfWeightedCoverage;const verdict: CompletenessVerdict =- coverage.idfWeightedCoverage >= COMPLETENESS_COMPLETE_THRESHOLD- ? "complete"- : coverage.idfWeightedCoverage >= COMPLETENESS_PARTIAL_THRESHOLD- ? "partial"- : "sparse";+ weighted === null+ ? "unmeasurable"+ : weighted >= COMPLETENESS_COMPLETE_THRESHOLD+ ? "complete"+ : weighted >= COMPLETENESS_PARTIAL_THRESHOLD+ ? "partial"+ : "sparse";return Object.freeze({verdict,idfWeightedCoverage: coverage.idfWeightedCoverage,@@ -151,7 +206,13 @@ export interface TargetedRetryPlan {}export function planTargetedRetry(coverage: CoverageReport): TargetedRetryPlan {- const belowThreshold = coverage.idfWeightedCoverage < COMPLETENESS_COMPLETE_THRESHOLD;+ // An unmeasurable coverage does not fire the retry. Stated rather than+ // left to the empty rare-term list that would also stop it: a retry+ // aimed at "the specifically-missing high-signal facts" needs a+ // measurement naming them, and there is none.+ const belowThreshold =+ coverage.idfWeightedCoverage !== null &&+ coverage.idfWeightedCoverage < COMPLETENESS_COMPLETE_THRESHOLD;const fire = belowThreshold && coverage.uncoveredRareTerms.length > 0;return Object.freeze({fire,@@ -159,6 +220,15 @@ export function planTargetedRetry(coverage: CoverageReport): TargetedRetryPlan {});}+/**+ * The report, and the one condition under which there is no number.+ *+ * `idfWeightedCoverage` is a SHARE of the query's IDF mass, so it exists+ * only when there is mass to take a share of. Two inputs leave none: a+ * query with no word characters at all, and a corpus with no documents+ * (every `idfForTerm` is then `ln(1) = 0`). Both are reported as `null`,+ * because neither is a statement about how well the retrieval did.+ */export function buildCoverageReport(inputs: CoverageInputs): CoverageReport {const terms: TermCoverage[] = inputs.significantTerms.map((term) => {const df = inputs.dfByTerm.get(term) ?? 0;@@ -180,7 +250,9 @@ export function buildCoverageReport(inputs: CoverageInputs): CoverageReport {const uncoveredRareTerms = terms.filter((t) => t.rare && !t.covered).map((t) => t.term);return Object.freeze({terms: Object.freeze(terms),- idfWeightedCoverage: totalIdf === 0 ? 1 : coveredIdf / totalIdf,+ // No IDF mass means there is nothing to take a share OF, so there is+ // no coverage — not full coverage. `null`, and every consumer decides.+ idfWeightedCoverage: totalIdf === 0 ? null : coveredIdf / totalIdf,rareTerms: Object.freeze(rareTerms),uncoveredRareTerms: Object.freeze(uncoveredRareTerms),});diff --git a/src/core/search/cross-vault.ts b/src/core/search/cross-vault.tsindex d01a5e65..f2bc4bcd 100644--- a/src/core/search/cross-vault.ts+++ b/src/core/search/cross-vault.ts@@ -24,6 +24,7 @@import { resolve } from "node:path";+import { ORIGIN_REACH, ORIGIN_REACH_REASON } from "../brain/portability/origin-reach.ts";import { listSearchOrigins } from "../brain/portability/origins.ts";import { resolveSearchConfig } from "./index.ts";import { RETRIEVAL_DEGRADATION, buildRetrievalTrail, noteDegradation } from "./retrieval-trail.ts";@@ -73,6 +74,16 @@ function labelledCard(card: SearchCard, label: string): SearchCard {const ORIGIN_UNREACHABLE_UNCLASSIFIED = "unclassified";const ORIGIN_UNREACHABLE_FIX = "run: o2b search check against that vault";+/**+ * The fix for an origin that was never opened at all. Deliberately not the+ * one above: `o2b search check` inspects an index, and there is no index to+ * inspect when the vault directory itself could not be read. The path stays+ * out of the sentence for the same reason it does everywhere on this+ * channel - the label is the actionable part and the reason says which+ * repair applies.+ */+const ORIGIN_UNREACHABLE_REGISTRY_FIX = "check the origin's registered vault path";+/** The fields the merge order reads - shared by results and cards. */interface MergeKey {readonly score: number;@@ -118,6 +129,17 @@ export async function searchAcrossVaults(// question an operator asks when their own vault answers nothing.let activeCorpus: RetrievalCorpusStatement | null = null;let total = 0;+ // Match quality of the union, folded from the origins that answered.+ //+ // Starts at `null` - unmeasurable - and becomes a number the moment any+ // origin returns one. Not zero: zero is the claim "the union covered+ // nothing of the query", and before an origin has answered, and for a+ // query no origin could weigh at all, that claim has not been earned+ // either. A union in which every origin FAILED is a different thing+ // again, and it reads null too: nothing measured it. Reporting a full+ // cover for any of these would be the exact over-claim the confidence+ // thresholds downstream now depend on not making.+ let unionCoverage: number | null = null;// Session focus resolves ONCE in the active-vault context: otherwise// each origin would load ITS OWN persisted search-focus state and@@ -148,6 +170,22 @@ export async function searchAcrossVaults(for (let i = 0; i < origins.length; i++) {const origin = origins[i]!;const isActive = origin.kind === "active";+ // An origin that could not be read is REPORTED, never dropped: it was+ // dropped one layer up until this release, which made a dead origin+ // indistinguishable from one that honestly held no match. `unreachable`+ // and `unknown` both land here, each carrying its own reason, because+ // "it is not there" and "I could not look" have different repairs.+ if (origin.reach !== ORIGIN_REACH.reachable) {+ const cause = origin.reason ?? ORIGIN_REACH_REASON.vaultUnreadable;+ warnings.push(+ `[${origin.label}] origin not searched [${cause}]: ${ORIGIN_UNREACHABLE_REGISTRY_FIX}`,+ );+ noteDegradation(degraded, RETRIEVAL_DEGRADATION.crossVaultOriginFailed, {+ origin: origin.label,+ cause,+ });+ continue;+ }try {const base =isActive && activeConfig !== undefined@@ -177,27 +215,58 @@ export async function searchAcrossVaults(activeCorpus = outcome.retrievalTrail.empty;}total += outcome.total;- // Chain-stop: if this origin answered confidently (its top NORMALIZED- // [0,1] result score reached the threshold) and origins remain, skip- // them. Take the MAX score over the origin's results rather than `[0]`:- // the final result order is not always score-desc (rerank and MMR reorder- // by relevance/diversity), so the positional first element is not- // necessarily the score-max. The gate reads the normalized result score,- // never the raw lane score, so a tiny-corpus origin with a high raw score- // does not short-circuit. Only recorded when origins were actually- // skipped, keeping the single-origin and never-triggered paths identical.+ // The union's own match quality. Taking the MAX over the origins is+ // the conservative fold: the merged window is a superset of any one+ // origin's rows, so its true coverage is at least the best origin's+ // and never less. Summing or averaging would invent a number no+ // origin measured. An origin that could not measure the query+ // contributes nothing to the fold - it is skipped, not read as a+ // zero, because a zero would drag a max nowhere but would read as a+ // measurement if it were the only origin.+ const originCoverage = outcome.idfWeightedCoverage;+ if (originCoverage !== null) {+ unionCoverage =+ unionCoverage === null ? originCoverage : Math.max(unionCoverage, originCoverage);+ }+ // Chain-stop: if this origin answered the QUESTION - covered the+ // query's IDF mass to the configured share - and origins remain,+ // skip them.+ //+ // It used to read the origin's top result score, which meant two+ // different things under the two fusion modes and neither of them+ // "answered confidently": in `linear` mode the keyword lane's+ // min-max normalisation puts the top row of any origin with a+ // non-empty keyword lane at or above `keywordWeight`+ // (`DEFAULT_KEYWORD_WEIGHT`, plus whichever boost layers fired -+ // 0.65 measured on a freshly written keyword-only vault), so the+ // shipped 0.8 threshold was out of reach there and the chain never+ // stopped; in `rrf` mode the fused lane is min-max normalised to+ // exactly 1.0 at the top, so the same 0.8 was met by every+ // non-empty origin and the chain always stopped after the first.+ // `idfWeightedCoverage` measures the match rather than the pool's+ // shape, so the knob now means one thing in both modes - and 0.8 is+ // the share `COMPLETENESS_COMPLETE_THRESHOLD` already calls a+ // complete retrieval. Only recorded when origins were actually+ // skipped, keeping the single-origin and never-triggered paths+ // identical.+ //+ // An origin whose coverage is unmeasurable never stops the chain:+ // "I could not weigh this query" is not "I answered it", and+ // treating the two alike is what the old `totalIdf === 0 ? 1`+ // shortcut did - it would have stopped the chain on the FIRST+ // origin for every query the report could not weigh.const remaining = origins.slice(i + 1);// Gate on whichever collection THIS mode populates: in cards mode results// is empty, so reading it would never short-circuit (the latent bug).const hits: ReadonlyArray<{ readonly score: number }> = cardsMode? (outcome.cards ?? []): outcome.results;- const topScore = hits.reduce((max, h) => Math.max(max, h.score), 0);if (activeRecall.chainStopEnabled &&remaining.length > 0 &&hits.length > 0 &&- topScore >= activeRecall.chainStopScore+ originCoverage !== null &&+ originCoverage >= activeRecall.chainStopScore) {chainStop = Object.freeze({triggered: true as const,@@ -247,6 +316,7 @@ export async function searchAcrossVaults(// Sum of per-origin totals - informational, mirrors single-vault// semantics where `total` can exceed the capped result/card length.total,+ idfWeightedCoverage: unionCoverage,...(chainStop ? { chainStop } : {}),...(retrievalTrail !== undefined ? { retrievalTrail } : {}),});diff --git a/src/core/search/evidence-verification.ts b/src/core/search/evidence-verification.tsindex c2a9aff5..794a134c 100644--- a/src/core/search/evidence-verification.ts+++ b/src/core/search/evidence-verification.ts@@ -64,12 +64,25 @@ export function coverageOverChunks(});}-export function buildEvidenceVerification(+/**+ * IDF-weighted coverage of the query over the RESULT SET a search is+ * about to return.+ *+ * Split out of {@link buildEvidenceVerification} because it is no longer+ * an evidence-pack-only quantity: it is the absolute match-quality number+ * every confidence threshold in the product now reads+ * (`SearchOutcome.idfWeightedCoverage`) - absolute as against a score,+ * not independent of `results`, which is exactly the argument it is+ * given. Evidence-pack mode calls+ * it through {@link buildEvidenceVerification}, which takes the finished+ * report rather than recomputing it, so one query performs exactly one+ * document-frequency read whichever mode it runs in.+ */+export function coverageOverResults(store: Store,query: string,results: ReadonlyArray<BrainSearchResult>,- pathPrefix: string | undefined,-): EvidenceVerification {+): CoverageReport {const terms = significantTerms(query);const dfByTerm = store.documentFrequencies(terms);const documentCount = store.counts().documents;@@ -80,13 +93,26 @@ export function buildEvidenceVerification(if (!covered.has(t) && termIncludedIn(haystack, t)) covered.add(t);}}- const coverage = buildCoverageReport({+ return buildCoverageReport({significantTerms: terms,coveredTerms: covered,documentCount,dfByTerm,});+}+export function buildEvidenceVerification(+ store: Store,+ pathPrefix: string | undefined,+ /**+ * The coverage report the outcome already built for this exact result+ * set. A parameter rather than a second computation: an internally+ * rebuilt report would buy a second document-frequency read, and a+ * report built over a DIFFERENT result set would make the evidence pack+ * disagree with the outcome's own match quality.+ */+ coverage: CoverageReport,+): EvidenceVerification {const unionRecords: EvidenceUnionRecord[] = [];for (const t of coverage.terms) {if (t.covered || t.df === 0) continue; // nothing in the corpus covers a df=0 termdiff --git a/src/core/search/index.ts b/src/core/search/index.tsindex 4f8b5179..9aa7fb61 100644--- a/src/core/search/index.ts+++ b/src/core/search/index.ts@@ -14,6 +14,7 @@ import { resolveVaultScope } from "../vault-scope/index.ts";import { resolveIndexPath, SEARCH_DB_CONFIG_KEY, SEARCH_DB_ENV } from "./paths.ts";import { buildFtsTokenize } from "./schema.ts";import { isFusionMode, DEFAULT_RRF_K } from "./fusion.ts";+import { DEFAULT_RECENCY } from "./recency.ts";import {loadProviderRegistry,expandRegisteredProvider,@@ -147,11 +148,57 @@ export {type RecallFeedbackEvent,} from "./feedback.ts";+/**+ * Shipped keyword-lane weight.+ *+ * Named because it is quoted outside this module. `rankResults` min-max+ * normalises the keyword lane, so the top-ranked row of any recall whose+ * KEYWORD lane is non-empty carries exactly this much keyword term+ * whatever it matched - and every layer `rankResults` adds on top of that+ * term (freshness, link, tag, entity, activation, co-access, reuse,+ * temporal intent, session focus) is non-negative. So this number is a+ * FLOOR on that row's score, not the score: `>=`, never `=`.+ *+ * The distinction is not academic. Measured on a keyword-only vault whose+ * files were just written, the top row scores 0.6499997... - this weight+ * plus the freshness prior sitting at its amplitude, which is the one+ * other layer such a vault has live ({@link FRESH_KEYWORD_ONLY_TOP_SCORE}).+ * On the committed benchmark corpus a row that also draws a link or entity+ * boost reaches 0.67, and with the semantic lane on the pinned window runs+ * from 0.2675 to 0.9405. What is invariant is the floor, and only while+ * the keyword lane is non-empty.+ *+ * Prose that states the pin - `src/core/bench/failure-modes.ts`,+ * `src/core/config.ts`, `src/core/brain/recall-adequacy.ts`,+ * `src/core/brain/gaps/gap-loop.ts`, `src/core/search/types.ts` - cites+ * these two symbols rather than repeating the digits, and+ * `tests/core/search/keyword-lane-top-score.test.ts` drives the shipped+ * pipeline over such a vault and asserts both numbers against these+ * bindings, so the stated number cannot drift from the shipped one again.+ */+export const DEFAULT_KEYWORD_WEIGHT = 0.6;++/**+ * What the top row of a keyword-only recall over freshly written files+ * actually scores: {@link DEFAULT_KEYWORD_WEIGHT} plus the freshness+ * prior at its full amplitude.+ *+ * Derived rather than written out, because it is the sum of two shipped+ * defaults and a hand-copied 0.65 is exactly the digit that drifted.+ * An upper bound for that vault only - nothing else is live there - and+ * not a ceiling in general: the other eight boost layers are additive.+ * The real content of the number is the pair of unreachability facts the+ * threshold moves rest on: it clears every floor a score used to be+ * compared against (0.35, 0.5, 0.6), and it falls short of the 0.8 chain+ * stop.+ */+export const FRESH_KEYWORD_ONLY_TOP_SCORE = DEFAULT_KEYWORD_WEIGHT + DEFAULT_RECENCY.amplitude;+const DEFAULTS = {chunkSize: 800,chunkOverlap: 100,chunkMinSize: 100,- keywordWeight: 0.6,+ keywordWeight: DEFAULT_KEYWORD_WEIGHT,semanticWeight: 0.4,provider: "openai-compat" as const,timeoutMs: 10_000,@@ -163,9 +210,12 @@ const DEFAULTS = {maxHops: 1,hopDecay: 0.5,maxExpansionPerHit: 3,- recencyShape: 0.8,- recencyScale: 30,- recencyAmplitude: 0.05,+ // Read off the curve module rather than copied: `FRESH_KEYWORD_ONLY_TOP_SCORE`+ // is derived from the amplitude, so a second copy of it here could make+ // the derived constant describe a curve the resolver does not ship.+ recencyShape: DEFAULT_RECENCY.shape,+ recencyScale: DEFAULT_RECENCY.scale,+ recencyAmplitude: DEFAULT_RECENCY.amplitude,synonymMaxTerms: 3,cacheTtlSeconds: 300,fusionMode: "linear" as const,diff --git a/src/core/search/pipeline/assemble.ts b/src/core/search/pipeline/assemble.tsindex 5b24fa4e..30f5bfea 100644--- a/src/core/search/pipeline/assemble.ts+++ b/src/core/search/pipeline/assemble.ts@@ -406,6 +406,7 @@ function rankCandidates(input: AssemblyInput, rankCap: number): BrainSearchResul? { coAccessByChunk: signals.coAccessByChunk }: {}),...(signals.trendByDoc !== undefined ? { trendByDoc: signals.trendByDoc } : {}),+ ...(signals.tierByDoc !== undefined ? { tierByDoc: signals.tierByDoc } : {}),...(signals.reuseRateByChunk !== undefined? { reuseRateByChunk: signals.reuseRateByChunk }: {}),diff --git a/src/core/search/pipeline/candidate-signals.ts b/src/core/search/pipeline/candidate-signals.tsindex bf6dec6b..012c05d0 100644--- a/src/core/search/pipeline/candidate-signals.ts+++ b/src/core/search/pipeline/candidate-signals.ts@@ -8,6 +8,7 @@* carries none of these signals ranks bit-identically.*/+import { PAGE_TIER_DEFAULT, readTier, type PageTier } from "../../brain/page-meta/tier.ts";import { parseFreshnessTrend } from "../../brain/temporal/freshness-trend.ts";import { observedReuseRates } from "../../brain/observed-use.ts";import { effectiveActivation, halfLifeDays, resolveActivationKind } from "../activation/decay.ts";@@ -48,6 +49,13 @@ export interface CandidateSignals {readonly activationByChunk: ReadonlyMap<number, number> | undefined;readonly coAccessByChunk: ReadonlyMap<number, ReadonlyMap<number, number>> | undefined;readonly trendByDoc: ReadonlyMap<number, string> | undefined;+ /**+ * Operator-declared importance tier per document, carrying only the+ * documents whose tier is NOT the default. The ranker's tier weight for+ * `supporting` is the identity, so an untagged vault produces no map at+ * all and ranks bit-identically.+ */+ readonly tierByDoc: ReadonlyMap<number, PageTier> | undefined;readonly reuseRateByChunk: ReadonlyMap<number, number> | undefined;readonly eventTimeMsByChunk: ReadonlyMap<number, number> | undefined;}@@ -88,6 +96,7 @@ export function collectCandidateSignals(input: CandidateSignalsInput): CandidateactivationByChunk: activation.activationByChunk,coAccessByChunk: activation.coAccessByChunk,trendByDoc: collectFreshnessTrend(input),+ tierByDoc: collectPageTier(input),reuseRateByChunk: collectReuseRates(input),eventTimeMsByChunk: input.temporalIntentActive ? collectDeclaredEventTimes(input) : undefined,};@@ -205,10 +214,10 @@ function coAccessCompanions(* `freshness_trend` by the dream refresh get a bounded relevance* multiplier. O(candidate preference pages) frontmatter reads.*- * Cache note: like the tier signal, the stamp is read from frontmatter at- * query time and is NOT part of the query-cache key; a dream re-stamp- * reaches cached queries on the next reindex (the content change bumps the- * corpus generation).+ * Cache note: like the tier signal in {@link collectPageTier}, the stamp+ * is read from frontmatter at query time and is NOT part of the+ * query-cache key; a dream re-stamp reaches cached queries on the next+ * reindex (the content change bumps the corpus generation).*/function collectFreshnessTrend(input: CandidateSignalsInput,@@ -232,6 +241,43 @@ function collectFreshnessTrend(return byDoc.size > 0 ? byDoc : undefined;}+/**+ * Operator-declared importance tier, the producer `tierByDoc` never had.+ *+ * `readTier` and `tierWeight` shipped together with the ranker input and+ * its docblock, and nothing ever populated the map: a page stamped+ * `tier: peripheral` reported `breakdown.tier === 1` and ranked+ * identically to an untagged one, so the documented, hand-editable knob+ * could not change an outcome. This is the missing half, not a new+ * signal.+ *+ * Entries equal to {@link PAGE_TIER_DEFAULT} are omitted and an all-default+ * candidate set produces no map, because that tier's weight is the+ * identity - which is what keeps an untagged vault bit-identical.+ *+ * Cost is one frontmatter read per candidate DOCUMENT (not chunk), taken+ * from the same request-scoped cache the sibling collectors use.+ */+function collectPageTier(input: CandidateSignalsInput): ReadonlyMap<number, PageTier> | undefined {+ const { config, ids, hydrated, frontmatterCache } = input;+ const byDoc = new Map<number, PageTier>();+ const seenDocs = new Set<number>();+ for (const chunkId of ids) {+ const h = hydrated.get(chunkId);+ if (h === undefined || seenDocs.has(h.documentId)) continue;+ seenDocs.add(h.documentId);+ try {+ const tier = readTier(readCachedFrontmatter(frontmatterCache, config.vault, h.path));+ if (tier !== PAGE_TIER_DEFAULT) byDoc.set(h.documentId, tier);+ } catch {+ // Unreadable frontmatter stays at the default tier, whose weight is+ // the identity: a page this pass could not read is ranked exactly as+ // it was before tiers existed, never demoted for being unreadable.+ }+ }+ return byDoc.size > 0 ? byDoc : undefined;+}+/*** Observed-reuse boost (t_65588d8b): fold the session-end USED/IGNORED/* CONTRADICTED verdicts into a per-document reuse score and map it ontodiff --git a/src/core/search/pipeline/outcome.ts b/src/core/search/pipeline/outcome.tsindex a060e862..77c5b79c 100644--- a/src/core/search/pipeline/outcome.ts+++ b/src/core/search/pipeline/outcome.ts@@ -14,7 +14,7 @@ import { toSearchCard } from "../cards.ts";import { classifyNegativeRecall } from "../../brain/negative-recall.ts";import { buildEvidencePack, downrankTerminalEvidenceResults } from "../evidence-pack.ts";import { buildRetrievalTrail, corpusStatementFor } from "../retrieval-trail.ts";-import { buildEvidenceVerification } from "../evidence-verification.ts";+import { buildEvidenceVerification, coverageOverResults } from "../evidence-verification.ts";import { fnv1aHex } from "../feedback.ts";import {attachTrustMetadata,@@ -59,12 +59,17 @@ export interface EmptyOutcomeInput {/** The zero-candidate outcome: no pool to rank, filter or attribute. */export function emptyOutcome(input: EmptyOutcomeInput): SearchOutcome {+ // Match quality is stated on every outcome, including this one: a+ // retrieval that returned nothing covers none of the query's IDF mass,+ // and saying so is what lets a floor distinguish "nothing matched" from+ // "something matched badly" instead of inferring both from one score.+ const coverage = coverageOverResults(input.store, input.query, NO_RESULTS);const evidencePack =input.opts.evidencePack === true? buildEvidencePack(input.query,[],- buildEvidenceVerification(input.store, input.query, [], input.pathPrefix),+ buildEvidenceVerification(input.store, input.pathPrefix, coverage),): undefined;// A zero-candidate outcome is always attributable: either a lane@@ -79,6 +84,7 @@ export function emptyOutcome(input: EmptyOutcomeInput): SearchOutcome {results: NO_RESULTS,warnings: Object.freeze(input.warnings),total: 0,+ idfWeightedCoverage: coverage.idfWeightedCoverage,...(evidencePack !== undefined ? { evidencePack } : {}),...(input.routedSurface === "summary" ? { surface: input.routedSurface } : {}),...(retrievalTrail !== undefined ? { retrievalTrail } : {}),@@ -145,11 +151,18 @@ export function buildSearchOutcome(input: OutcomeInput): SearchOutcome {const finalResults = wantsEvidencePack? downrankTerminalEvidenceResults(input.results, terminalPaths): input.results;+ // Built once, over the rows this outcome actually carries, and read by+ // both consumers: the evidence pack's verification block and the+ // outcome's own `idfWeightedCoverage`. Computing it here rather than+ // only in evidence-pack mode is the whole change - the number existed+ // and was thrown away on every ordinary search, while four thresholds+ // downstream had nothing absolute left to read.+ const coverage = coverageOverResults(input.store, query, finalResults);const evidencePack = wantsEvidencePack? buildEvidencePack(query,finalResults,- buildEvidenceVerification(input.store, query, finalResults, input.pathPrefix),+ buildEvidenceVerification(input.store, input.pathPrefix, coverage),terminalPaths,): undefined;@@ -191,6 +204,7 @@ export function buildSearchOutcome(input: OutcomeInput): SearchOutcome {});const tail = {+ idfWeightedCoverage: coverage.idfWeightedCoverage,...(retrievalTrail !== undefined ? { retrievalTrail } : {}),...(evidencePack !== undefined ? { evidencePack } : {}),...(input.secondPass !== undefined ? { secondPass: input.secondPass } : {}),diff --git a/src/core/search/pipeline/second-pass.ts b/src/core/search/pipeline/second-pass.tsindex d3003a50..39419692 100644--- a/src/core/search/pipeline/second-pass.ts+++ b/src/core/search/pipeline/second-pass.ts@@ -151,7 +151,10 @@ function runTargetedRetry(input: SecondPassInput): SecondPassOutcome {secondPass: Object.freeze({triggered: true,kind: "targeted",- reason: `partial coverage ${poolCoverage.idfWeightedCoverage.toFixed(2)} < ${COMPLETENESS_COMPLETE_THRESHOLD}; targeted retry on uncovered rare terms: ${retryPlan.terms.join(", ")}`,+ // `retryPlan.fire` is false for an unmeasurable coverage, so the+ // non-null assertion below is the plan's own precondition rather+ // than an assumption: this line is unreachable without a number.+ reason: `partial coverage ${poolCoverage.idfWeightedCoverage!.toFixed(2)} < ${COMPLETENESS_COMPLETE_THRESHOLD}; targeted retry on uncovered rare terms: ${retryPlan.terms.join(", ")}`,added: newHits.length,targetedTerms: retryPlan.terms,}),diff --git a/src/core/search/query-cache.ts b/src/core/search/query-cache.tsindex ba22840a..a988ba81 100644--- a/src/core/search/query-cache.ts+++ b/src/core/search/query-cache.ts@@ -135,6 +135,12 @@ export function getCachedOutcome(if (nowMs - row.createdAt > ttlMs) return null;try {const parsed = JSON.parse(row.payload) as SearchOutcome;+ // A row written before `idfWeightedCoverage` existed carries no match+ // quality, and a hit that served one would hand every downstream+ // confidence threshold `undefined` to compare against - the silent+ // fallback those thresholds are being repaired to stop making. Such a+ // row is a miss, so the outcome is recomputed with the number in it.+ if (typeof parsed.idfWeightedCoverage !== "number") return null;// Match the fresh-compute path's immutability: freeze the results// array and each result so a hit is indistinguishable from a miss.for (const r of parsed.results) Object.freeze(r);diff --git a/src/core/search/types.ts b/src/core/search/types.tsindex aefdd748..e6ec9eca 100644--- a/src/core/search/types.ts+++ b/src/core/search/types.ts@@ -599,7 +599,13 @@ export interface EvidenceUnionRecord {readonly chunkId: number;}-export type CompletenessVerdict = "complete" | "partial" | "sparse";+/**+ * Three grades and one non-grade. `unmeasurable` is what a query with no+ * IDF mass to weigh returns; it is not a worse `sparse`, it is the+ * absence of a measurement, and folding it into either end of the scale+ * is what let a query nothing could be said about read as a perfect one.+ */+export type CompletenessVerdict = "complete" | "partial" | "sparse" | "unmeasurable";/*** Search-completeness guard (Feature E): a deterministic verdict over@@ -610,7 +616,8 @@ export type CompletenessVerdict = "complete" | "partial" | "sparse";*/export interface CompletenessReport {readonly verdict: CompletenessVerdict;- readonly idfWeightedCoverage: number;+ /** `null` exactly when `verdict` is `unmeasurable`. */+ readonly idfWeightedCoverage: number | null;readonly coveredTerms: ReadonlyArray<string>;readonly uncoveredTerms: ReadonlyArray<string>;readonly uncoveredButPresentInCorpus: ReadonlyArray<string>;@@ -629,10 +636,12 @@ export interface EvidencePack {readonly abstention: string | null;/*** IDF-weighted support coverage (Feature C): the share of the query's- * IDF mass the covered terms carry. Present only when the search ran- * with coverage verification.+ * IDF mass the covered terms carry. Absent when the search ran without+ * coverage verification; `null` when it ran WITH verification and the+ * query had no IDF mass to weigh. Two different facts, kept apart on+ * the wire too: no key at all, versus an explicit null.*/- readonly idfWeightedCoverage?: number;+ readonly idfWeightedCoverage?: number | null;/** Rare (high-signal) significant terms per the corpus statistics. */readonly rareTerms?: ReadonlyArray<string>;/** Rare terms no returned record covers — the abstention trigger. */@@ -842,6 +851,48 @@ export interface SearchOutcome {* {@link SearchOutcome.retrievalDecisionTrace}.*/readonly total: number;+ /**+ * Absolute match quality of this retrieval: the share of the query's+ * IDF mass that the returned material actually covers, in `[0,1]`+ * (`buildCoverageReport`, `search/coverage.ts`).+ *+ * `null` when there was no IDF mass to take a share of - a query with+ * no word characters, or an empty corpus. Not a number, and in+ * particular not `1`: an unmeasurable query is not a complete+ * retrieval, and the nullable type is what forces each threshold to say+ * which it is treating it as.+ *+ * This is the ONLY number on the outcome that a confidence threshold+ * may be compared against. `BrainSearchResult.score` cannot be: the+ * keyword lane is min-max normalised within the candidate set+ * (`normalizeBm25`), so whenever that lane is non-empty the top row's+ * score sits at or above the configured `keywordWeight` whatever it+ * matched, and the bottom row's at zero whatever IT matched. A constant+ * compared against that measures which rows survived the filter stack,+ * not how well anything matched - which is exactly what four separate+ * thresholds in this product used to do.+ *+ * ## What "absolute" does and does not claim+ *+ * Absolute in the sense that separates it from a score: it is a share+ * of a fixed quantity - the query's own IDF mass, computed from corpus+ * document frequencies - so it does not depend on rank position, on+ * lane magnitudes, on the fusion mode, or on how the pool's best and+ * worst rows happened to compare. Two different retrievals for one+ * query are comparable numbers.+ *+ * It is NOT independent of which rows this outcome carries, and an+ * earlier draft of this docblock claimed it was. It is computed over+ * `finalResults` - the limit-sliced, filter-survived window - so the+ * same query at `limit: 1` and at `limit: 20` can report different+ * coverage, and a row an owner or visibility filter removed takes its+ * terms' IDF mass out of the numerator with it. It measures how much of+ * the query the DELIVERED material covers, which is the question every+ * consumer of it is actually asking; it is not a statement about the+ * corpus. `tests/core/search/coverage-window-dependence.test.ts` pins+ * that dependence so the stronger claim cannot regrow.+ */+ readonly idfWeightedCoverage: number | null;/*** Layer-1 compact cards (progressive disclosure). Present only when the* caller set `disclosure: "cards"`; in that mode `results` is empty anddiff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.tsindex 4731ed6c..00cb6e9a 100644--- a/src/mcp/brain/admin-tools.ts+++ b/src/mcp/brain/admin-tools.ts@@ -31,7 +31,7 @@ import {} from "../../core/brain/link-graph/communities.ts";import { appendMetric } from "../../core/brain/metrics.ts";import type { ProgressSink } from "../../core/brain/progress.ts";-import { toolSafeguard } from "./shared.ts";+import { requiredStringArg, toolSafeguard } from "./shared.ts";import { currentLease } from "../../core/brain/maintenance/lease.ts";import { listJournal } from "../../core/brain/maintenance/journal.ts";import { runMaintenance, type DailyWindow } from "../../core/brain/maintenance/lane.ts";@@ -55,10 +55,17 @@ function toolBrainLabels(if (op !== "assign" && op !== "remove" && op !== "show") {throw new MCPError(INVALID_PARAMS, "brain_labels: operation must be assign|remove|show");}- const path = args["path"];- if (typeof path !== "string" || path.trim() === "") {- throw new MCPError(INVALID_PARAMS, "brain_labels: path must be a vault-relative string");- }+ // a-label-is-not-a-boundary, U12: the ARGUMENT is right and the+ // VALIDATOR's message was wrong. `path` is the only name this tool+ // declares for the note - a caller passing `id` is refused by name by+ // the unknown-argument gate (`src/mcp/argument-guard.ts`) before the+ // handler runs - but this check answered an ABSENT `path` with a+ // sentence about its SHAPE, so a caller who sent the wrong name read+ // it as "my path is malformed" and retried the same call. The shared+ // coercion already tells absence and malformation apart, and stamps+ // the operation into both, so the two failures no longer share a+ // sentence.+ const path = requiredStringArg(`brain_labels ${op}`, args, "path");if (op === "show") {const [metadata] = parseFrontmatter(vaultContainedPath(ctx.vault, path, "brain_labels show"));return { path, labels: readLabels(metadata) };@@ -123,10 +130,11 @@ async function toolBrainTiers(await store.close();}}- const path = args["path"];- if (typeof path !== "string" || path.trim() === "") {- throw new MCPError(INVALID_PARAMS, `brain_tiers ${op}: path must be a vault-relative string`);- }+ // Same conflation as `brain_labels` above, same cure: `path` is+ // optional for `check` and required for the two write operations, and+ // "you did not send it" is a different sentence from "what you sent is+ // not a path".+ const path = requiredStringArg(`brain_tiers ${op}`, args, "path");if (op === "restore" && args["apply"] !== true) {throw new MCPError(INVALID_PARAMS,diff --git a/src/mcp/brain/analytics-tools.ts b/src/mcp/brain/analytics-tools.tsindex 12537366..6f2af4a3 100644--- a/src/mcp/brain/analytics-tools.ts+++ b/src/mcp/brain/analytics-tools.ts@@ -12,6 +12,7 @@ import {type IngestDedupSurface,} from "../../core/brain/dedup-telemetry.ts";import { buildConceptCluster } from "../../core/brain/link-graph/concept-cluster.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";import { selectEvents } from "../../core/brain/temporal/select-events.ts";import { buildBeliefEvolution } from "../../core/brain/temporal/belief-evolution.ts";@@ -24,6 +25,7 @@ import {import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import {coerceIsoTimestampOrDate,@@ -71,11 +73,18 @@ async function toolBrainTimeline(...(since !== undefined ? { since } : {}),...(until !== undefined ? { until } : {}),});- const sliced = limit !== undefined ? events.slice(0, limit) : events;+ // A timeline row names the preference the event was about, its topic,+ // and the file the event was read from (a-label-is-not-a-boundary,+ // U3). Filtered BEFORE the limit and before `total`, so the count is+ // the visible one - a total that still included the hidden rows would+ // leak their number.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ const visible = view.keep(events, (ev) => [ev.source.path, ev.prefId, ev.artifact]);+ const sliced = limit !== undefined ? visible.slice(0, limit) : visible;return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),window: index.window,- total: events.length,+ total: visible.length,events: sliced.map((ev) => ({at: ev.at,kind: ev.kind,@@ -114,12 +123,24 @@ async function toolBrainBeliefEvolution(: { topic: (topicRaw as string).trim() };const index = buildTimelineIndex(ctx.vault, {});const evo = buildBeliefEvolution(index, ctx.vault, target);+ // A topic target fans out to every pref/ret carrying that topic, so+ // one `topic` argument reaches artifacts the caller never named+ // (a-label-is-not-a-boundary, U3). Every row names its subject: a+ // transition by `prefId` and by the wikilink the dream summary used,+ // an evidence row by `prefId` and by the `artifact` it was applied to,+ // a retirement by its whole supersession chain.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),target: evo.target,- transitions: evo.transitions,- evidence: evo.evidence,- retirements: evo.retirements,+ transitions: view.keep(evo.transitions, (t) => [t.prefId, t.link]),+ evidence: view.keep(evo.evidence, (e) => [e.prefId, e.artifact]),+ retirements: view.keep(evo.retirements, (r) => [+ r.prefId,+ r.retiredBy,+ r.supersededBy,+ r.supersedes,+ ]),generated_at: evo.generatedAt,};}@@ -151,11 +172,16 @@ async function toolBrainConceptSynthesis(includeUnlinked = includeUnlinkedRaw;}const targetId = normaliseWikilinkTarget(idRaw);+ // `linkers[].source` names every artifact pointing at the target and+ // `unlinkedMentions[]` carries a VERBATIM line of the mentioning+ // page's body (a-label-is-not-a-boundary, U3). Both producers already+ // take the scope; passing it is the whole fix.const cluster = buildConceptCluster(ctx.vault, targetId, {includeUnlinked,+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,});return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),target_id: cluster.targetId,target_title: cluster.targetTitle,linkers: cluster.linkers,@@ -219,13 +245,22 @@ async function toolBrainDedup(}const since = coerceIsoTimestampOrDate("brain_analytics", "since", args["since"]);const until = coerceIsoTimestampOrDate("brain_analytics", "until", args["until"]);+ const summary = summarizeIngestDedup(ctx.vault, {+ ...(typeof surface === "string" ? { surface: surface as IngestDedupSurface } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ });+ // `by_source[].ref` is the one field here with a per-artifact subject:+ // "a session id, or a vault-relative note path - whatever the run keys+ // provenance by" (`dedup-telemetry.ts`), and a note path is+ // owner-taggable (a-label-is-not-a-boundary, U3). The totals and the+ // per-run trend beside it are folds over ingest RUNS with no artifact+ // in them, so they stay as measured.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);return {- vault_path: ctx.vault,- ...summarizeIngestDedup(ctx.vault, {- ...(typeof surface === "string" ? { surface: surface as IngestDedupSurface } : {}),- ...(since !== undefined ? { since } : {}),- ...(until !== undefined ? { until } : {}),- }),+ vault_path: vaultPathField(ctx),+ ...summary,+ by_source: view.keep(summary.by_source, (row) => [row.ref]),};}diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.tsindex 7138347b..36a97890 100644--- a/src/mcp/brain/brief-tools.ts+++ b/src/mcp/brain/brief-tools.ts@@ -34,6 +34,7 @@ import { isoDate } from "../../core/brain/time.ts";import { captureReportDelta } from "../../core/brain/report-snapshot.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import {AGENT_SCOPE_ARG_NAME,@@ -213,7 +214,7 @@ async function toolBrainDailyBrief(offsetHours: cfg.daily_window_offset_hours,});const envelope: Record<string, unknown> = {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),date: brief.date,window: brief.window,events_by_kind: brief.eventsByKind,@@ -254,7 +255,7 @@ async function toolBrainWeeklySynthesis(const index = buildTimelineIndex(ctx.vault, {});const synth = buildWeeklySynthesis(index, ctx.vault, weekEnd, cfg);const envelope: Record<string, unknown> = {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),window_start: synth.windowStart,window_end: synth.windowEnd,events_by_kind: synth.eventsByKind,@@ -386,7 +387,7 @@ async function toolBrainOperatorSummary(...(topActionsN !== undefined ? { topActionsN } : {}),});return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),trust_verdict: summary.trust_verdict,digest_summary: summary.digest_summary,doctor_summary: {@@ -432,7 +433,7 @@ async function toolBrainToday(...(limit !== undefined ? { activityLimit: limit } : {}),});return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),text: dashboard.text,obligations: dashboard.obligations,open_loops: dashboard.openLoops,diff --git a/src/mcp/brain/context-tools.ts b/src/mcp/brain/context-tools.tsindex b0e3512a..26e70db3 100644--- a/src/mcp/brain/context-tools.ts+++ b/src/mcp/brain/context-tools.ts@@ -49,6 +49,7 @@ import {} from "../../core/brain/pinned.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { VAULT_PATH_OUTPUT_SCHEMA, vaultPathField } from "../vault-path-field.ts";import { coerceStr, coerceInt } from "../coerce.ts";import { vaultRelativeSafe } from "./shared.ts";@@ -339,7 +340,7 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknif (!existsSync(dirs.brain)) {return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),present: false,active_path: activePath,content: prependStandingBlock(standing, ""),@@ -427,7 +428,7 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unkn}return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),present: true,active_path: activePath,content,@@ -535,7 +536,7 @@ const BRAIN_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> =type: "object",required: ["vault_path", "present", "active_path", "content", "counts", "generated_at", "pinned"],properties: {- vault_path: { type: "string" },+ vault_path: VAULT_PATH_OUTPUT_SCHEMA,present: { type: "boolean" },active_path: { type: "string" },content: { type: "string" },diff --git a/src/mcp/brain/derive-tools.ts b/src/mcp/brain/derive-tools.tsindex 8e0f80ef..1a02464c 100644--- a/src/mcp/brain/derive-tools.ts+++ b/src/mcp/brain/derive-tools.ts@@ -39,7 +39,12 @@ async function toolBrainDeriveFact(// Shape first: the payload is validated before any field is read, so a// structurally wrong request never reaches the premise lookup or a write.const input = parseDeriveFactInput(args);- const res = deriveFact(ctx.vault, input, { now: new Date() });+ const res = deriveFact(ctx.vault, input, {+ now: new Date(),+ // The ownership stamp resolves the writing identity from the+ // server's own config, not from anything the caller sent.+ ...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),+ });return { id: res.id, level: input.level, premises: input.premises };});}diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.tsindex db9291fb..b710527a 100644--- a/src/mcp/brain/feedback-tools.ts+++ b/src/mcp/brain/feedback-tools.ts@@ -43,6 +43,8 @@ import {} from "../../core/brain/write-advisory.ts";import { loadFeedbackDefaultScopeSafe } from "../../core/brain/policy.ts";import { writePreference } from "../../core/brain/preference.ts";+import { gatedOwnerScopeView, type OwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { brainArtifactSlug } from "../../core/brain/wikilink.ts";import { validateBrainFeedbackInput } from "../../core/brain/sessions/validate-feedback.ts";import { isoDate, isoSecond } from "../../core/brain/time.ts";import { slugify } from "../../core/vault.ts";@@ -56,7 +58,11 @@ import {} from "../../core/brain/types.ts";import { appendLogEvent } from "../../core/brain/log.ts";import { appendBrainNote } from "../../core/brain/note.ts";-import { mirrorSignal, resolveSharedNamespace } from "../../core/brain/shared-namespace.ts";+import {+ mirrorReportFields,+ mirrorSignal,+ resolveSharedNamespace,+} from "../../core/brain/shared-namespace.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import {@@ -228,27 +234,35 @@ async function toolBrainFeedback(// `confirmed_at` is now; `unconfirmed_until` is also now so the trial// window collapses on inspection. The just-written signal is recorded// as the rule's origin under `evidenced_by`.- prefResult = writePreference(ctx.vault, {- slug,- topic: topic.trim(),- principle: principle.trim(),- created_at: createdAt,- unconfirmed_until: createdAt,- status: BRAIN_PREFERENCE_STATUS.confirmed,- evidenced_by: [`[[${sigResult.id}]]`],- confirmed_at: createdAt,- // Issue #149: an explicit zero, not an absent value. The- // on-disk encoding of "absent" is the literal `null`, and two- // ranking surfaces (`pre-compress-pack`, `morning-brief`) map- // `null` to negative infinity before sorting - so a rule- // force-confirmed a second ago would sort BELOW every rule- // that has a number, including one measured at zero. Zero is- // also the true Wilson lower bound on no evidence, which is- // why the dream pass already pre-seeds it for new- // preferences. This writer now matches it.- confidence_value: 0,- ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),- });+ prefResult = writePreference(+ ctx.vault,+ {+ slug,+ topic: topic.trim(),+ principle: principle.trim(),+ created_at: createdAt,+ unconfirmed_until: createdAt,+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[${sigResult.id}]]`],+ confirmed_at: createdAt,+ // Issue #149: an explicit zero, not an absent value. The+ // on-disk encoding of "absent" is the literal `null`, and two+ // ranking surfaces (`pre-compress-pack`, `morning-brief`) map+ // `null` to negative infinity before sorting - so a rule+ // force-confirmed a second ago would sort BELOW every rule+ // that has a number, including one measured at zero. Zero is+ // also the true Wilson lower bound on no evidence, which is+ // why the dream pass already pre-seeds it for new+ // preferences. This writer now matches it.+ confidence_value: 0,+ ...(effectiveScope !== undefined ? { scope: effectiveScope } : {}),+ },+ // Ownership is resolved by the writer, never echoed from `agent`:+ // that argument is caller-supplied, and a caller must not be able to+ // name whose memory this becomes. The server's config path is handed+ // over rather than a resolved name for the same reason.+ ctx.configPath !== null ? { configPath: ctx.configPath } : {},+ );try {// Offset by 1s so the force-confirmed event sorts after the feedback// event on the same UTC second (parseLogDay is stable on ties, but a@@ -270,7 +284,7 @@ async function toolBrainFeedback(return {kind: prefResult ? "preference" : "signal",- ...(mirror !== undefined ? { mirror } : {}),+ ...mirrorReportFields(mirror),...(advisory !== null ? { advisory } : {}),// Same key and same resolution as the CLI's `--json` renderer, from// the one composer: an agent that learns the exit on one surface@@ -343,6 +357,52 @@ function readDreamGates(args: Record<string, unknown>): DreamGateOverrides | und}}+/**+ * The rows of a dream plan or run summary the caller may see+ * (a-label-is-not-a-boundary, U3).+ *+ * Every list here names a preference or a signal by id, and the pass+ * that produced them is vault-wide by construction: consolidation reads+ * every topic, and clustering only half a vault would produce different+ * preferences for every caller. So the PASS stays unscoped and the+ * REPORT is filtered - a caller is told what it did to the artifacts+ * that caller may see, and nothing about the rest.+ *+ * `contradictions`, `quarantined` and `intent_reviews` are absent from+ * the fold on purpose: their subject is a TOPIC over inbox signals, and+ * a signal carries no `owner:` anywhere in this product, so there is no+ * ownership claim on disk to read.+ */+function scopedDreamRows<R extends string>(+ view: OwnerScopeView,+ plan: {+ readonly new_unconfirmed: ReadonlyArray<string>;+ readonly confirmed: ReadonlyArray<string>;+ readonly retired: ReadonlyArray<{ readonly id: string; readonly reason: R }>;+ readonly moved_to_processed: ReadonlyArray<string>;+ readonly suppressed: ReadonlyArray<string>;+ },+): {+ new_unconfirmed: ReadonlyArray<string>;+ confirmed: ReadonlyArray<string>;+ retired: ReadonlyArray<{ id: string; reason: R }>;+ moved_to_processed: ReadonlyArray<string>;+ suppressed: ReadonlyArray<string>;+} {+ const ids = (list: ReadonlyArray<string>): ReadonlyArray<string> => view.keep(list, (id) => [id]);+ return {+ new_unconfirmed: ids(plan.new_unconfirmed),+ confirmed: ids(plan.confirmed),+ // A retire names the preference by BOTH spellings across the move:+ // `ret-<slug>` after the pass, `pref-<slug>` before it.+ retired: view+ .keep(plan.retired, (r) => [r.id, `pref-${brainArtifactSlug(r.id)}`])+ .map((r) => ({ id: r.id, reason: r.reason })),+ moved_to_processed: ids(plan.moved_to_processed),+ suppressed: ids(plan.suppressed),+ };+}+async function toolBrainDream(ctx: ServerContext,args: Record<string, unknown>,@@ -368,6 +428,9 @@ async function toolBrainDream(const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);const gates = readDreamGates(args);const stepArg = coerceStr(args, "step", false);+ // One view for the whole call: every branch below reports preference+ // and signal ids, and the staged lifecycle reports them twice.+ const dreamView = gatedOwnerScopeView(ctx.vault, ctx.agentName);// Single-step requests (no-dead-ends, Unit E - operator surface).// Deliberately checked before any environment work: a step the pass@@ -434,7 +497,7 @@ async function toolBrainDream(return {action,run_id: bundle.runId,- plan: bundle.plan,+ plan: { ...bundle.plan, ...scopedDreamRows(dreamView, bundle.plan) },sources: bundle.sources.length,dir: `Brain/dream/staged/${bundle.runId}`,};@@ -451,12 +514,7 @@ async function toolBrainDream(applied: outcome.applied,drift: [...outcome.validation.drift],...(outcome.summary !== undefined- ? {- changed: outcome.summary.changed,- new_unconfirmed: [...outcome.summary.new_unconfirmed],- confirmed: [...outcome.summary.confirmed],- retired: outcome.summary.retired.map((r) => ({ id: r.id, reason: r.reason })),- }+ ? { changed: outcome.summary.changed, ...scopedDreamRows(dreamView, outcome.summary) }: {}),};}@@ -534,12 +592,8 @@ async function toolBrainDream(matched: changeList.length,changed_count: dryRun ? 0 : changeList.length,dry_run: dryRun,- new_unconfirmed: [...summary.new_unconfirmed],- confirmed: [...summary.confirmed],- retired: summary.retired.map((r) => ({ id: r.id, reason: r.reason })),+ ...scopedDreamRows(dreamView, summary),contradictions: [...summary.contradictions],- moved_to_processed: [...summary.moved_to_processed],- suppressed: [...summary.suppressed],warnings: summary.warnings.map((w) => ({code: w.code,message: w.message,diff --git a/src/mcp/brain/generation-tools.ts b/src/mcp/brain/generation-tools.tsindex 5ca1d6dc..b5862e04 100644--- a/src/mcp/brain/generation-tools.ts+++ b/src/mcp/brain/generation-tools.ts@@ -30,6 +30,7 @@ import { isCanonicalUtcTimestamp } from "../../core/brain/continuity/store.ts";import type { ContinuitySourceRef } from "../../core/brain/continuity/types.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";@@ -43,7 +44,7 @@ async function toolBrainGenerationReports(if (action === "record") return recordAction(ctx, args);if (action === "list") {const reports = listGenerationReports(ctx.vault, readFilter(args));- return { vault_path: ctx.vault, total: reports.length, reports };+ return { vault_path: vaultPathField(ctx), total: reports.length, reports };}if (action === "summary") {return { ...summarizeGenerationReports(ctx.vault, readFilter(args)) };@@ -107,8 +108,8 @@ function recordAction(ctx: ServerContext, args: Record<string, unknown>): Record);return record !== null- ? { vault_path: ctx.vault, recorded: true, id: record.id }- : { vault_path: ctx.vault, recorded: false, reason: "disabled" };+ ? { vault_path: vaultPathField(ctx), recorded: true, id: record.id }+ : { vault_path: vaultPathField(ctx), recorded: false, reason: "disabled" };}function readFilter(args: Record<string, unknown>): GenerationReportFilter {diff --git a/src/mcp/brain/health-tools.ts b/src/mcp/brain/health-tools.tsindex 7e36ab72..a234f8aa 100644--- a/src/mcp/brain/health-tools.ts+++ b/src/mcp/brain/health-tools.ts@@ -13,6 +13,12 @@ import { applyRepair } from "../../core/brain/diagnostics.ts";import { nextCommandField } from "../../core/brain/next-step.ts";import { NO_EXIT_KEY, noExitReasons } from "../../core/brain/doctor-exits.ts";import { buildOperatorSnapshot } from "../../core/brain/operator-snapshot.ts";+import { foldSemanticHealthVerdict } from "../../core/brain/health/reconcile.ts";+import {+ extractWikilinkRichBodies,+ parseWikilinkRich,+} from "../../core/brain/link-graph/parse-wikilink.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import type { DoctorIssue } from "../../core/brain/types.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceBool, coerceFormat } from "../coerce.ts";@@ -68,6 +74,12 @@ async function toolBrainDoctor(const outcome = applyRepair(ctx.vault, {dryRun: !apply,...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),+ // The repair branch returns HERE, before the diagnostic streams+ // below are filtered - so until this argument existed a scoped+ // caller both read and REWROTE another owner's preferences+ // (a-label-is-not-a-boundary, U3). The scope bounds the plan, so+ // the write is bounded too, not just the report.+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,});return { format, repair: outcome };}@@ -82,18 +94,51 @@ async function toolBrainDoctor(...(ctx.configPath !== null ? { configPath: ctx.configPath } : {}),});+ // Every issue names the artifact it is about - `path`, `target`, the+ // referencing `sources`, and the message prose that repeats them - so+ // an unscoped report enumerated another owner's preferences, retired+ // pages and inbox signals by path (a-label-is-not-a-boundary, U3).+ // Filtered BEFORE `ok` is decided: an `ok: false` beside an empty error+ // list would say a hidden artifact is broken without naming it, which+ // is the existence leak with the evidence removed.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ /** Generic over the three streams: they share the naming fields, not a type. */+ const visibleIssues = <+ T extends {+ readonly message: string;+ readonly path?: string;+ readonly target?: string;+ readonly sources?: ReadonlyArray<string>;+ },+ >(+ issues: ReadonlyArray<T>,+ ): ReadonlyArray<T> =>+ view.keep(issues, (i) => [+ i.path === undefined ? undefined : vaultRelativeSafe(ctx.vault, i.path),+ i.target,+ ...(i.sources ?? []),+ // The semantic-health codes (`low-evidence-confirmed`,+ // `batch-concept-inflation`) carry NO structured target - they name+ // their subjects inside the message, as `[[pref-x]]`. Read through+ // the shared wikilink lexer rather than by matching prose, so this+ // is a structural read of the same link syntax the rest of the+ // vault uses and no natural-language pattern is involved.+ ...extractWikilinkRichBodies(i.message).map((b) => parseWikilinkRich(b).target),+ ]);+ const errors = visibleIssues(result.errors);+ const warnings = visibleIssues(result.warnings);+ const uncertain = result.uncertain === undefined ? undefined : visibleIssues(result.uncertain);+// Decide a single ok flag — `strict` only changes the CLI exit code,// so we mirror that semantic here: with `strict`, warnings demote ok// to false. Errors always do.- const ok = result.errors.length === 0 && (!strict || result.warnings.length === 0);+ const ok = errors.length === 0 && (!strict || warnings.length === 0);// Why a reported code carries no `next_command`. Without it the field's// absence has two readings - a class no single command resolves, and a// class nobody has registered - and an agent cannot tell them apart.// Resolved through the same table the CLI renderer reads.- const noExit = noExitReasons(- [...result.errors, ...result.warnings, ...(result.uncertain ?? [])].map((i) => i.code),- );+ const noExit = noExitReasons([...errors, ...warnings, ...(uncertain ?? [])].map((i) => i.code));return {format,@@ -105,19 +150,21 @@ async function toolBrainDoctor(// uses so the two surfaces cannot drift. Absent - not null - for a// code with no registered signal, because there is no honest command// to name and a generic one would be invented.- errors: result.errors.map((i) => issueView(ctx, i)),- warnings: result.warnings.map((i) => issueView(ctx, i)),+ errors: errors.map((i) => issueView(ctx, i)),+ warnings: warnings.map((i) => issueView(ctx, i)),// v0.10.15: ranked maintenance actions surfaced as a parallel// signal to errors/warnings. The list is independent of `strict`// because nothing here downgrades the `ok` flag - actions are// suggestions, not invariant violations.- suggested_actions: collectMaintenanceActions(ctx.vault).map((a) => ({- id: a.id,- category: a.category,- title: a.title,- impact: a.impact,- ...(a.target !== undefined ? { target: a.target } : {}),- })),+ suggested_actions: view+ .keep(collectMaintenanceActions(ctx.vault), (a) => [a.target])+ .map((a) => ({+ id: a.id,+ category: a.category,+ title: a.title,+ impact: a.impact,+ ...(a.target !== undefined ? { target: a.target } : {}),+ })),// v0.10.16: trust-layer fields. `trust_verdict` is always populated// by runDoctor; `verification_delta_summary` only when the caller// threads a dream summary through (not exposed via this tool's@@ -141,9 +188,9 @@ async function toolBrainDoctor(// clean vault's payload is byte-identical to the pre-`uncertain`// shape. Additive-safe: this tool declares no `outputSchema`, so no// structured-output contract constrains the key set.- ...(result.uncertain !== undefined && result.uncertain.length > 0+ ...(uncertain !== undefined && uncertain.length > 0? {- uncertain: result.uncertain.map((u) => ({+ uncertain: uncertain.map((u) => ({code: u.code,...(u.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, u.path) } : {}),message: u.message,@@ -168,10 +215,33 @@ async function toolBrainHealth(const format = coerceFormat(args);const result = runDoctor(ctx.vault);const sh = result.semantic_health;+ // Three of the four finding families name preferences by id, and the+ // batch-inflation family names their topics as well+ // (a-label-is-not-a-boundary, U3). A finding whose members are not all+ // visible is dropped WHOLE rather than trimmed: its `count` and its+ // `topics` describe the batch the detector measured, so a batch of five+ // reported as four is not a narrower true finding, it is a false one.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ const contradictions = view.keep(sh?.contradictions ?? [], (c) => [c.aId, c.bId]);+ const conceptGaps = sh?.conceptGaps ?? [];+ const staleClaims = view.keep(sh?.staleClaims ?? [], (s) => [s.id]);+ const batchInflation = view.keep(sh?.batchInflation ?? [], (b) => b.ids);return {format,- verdict: sh?.verdict ?? "clean",- contradictions: (sh?.contradictions ?? []).map((c) => ({+ // Folded over the FILTERED families, through the same arithmetic+ // that produced the unfiltered one. `sh.verdict` summarises findings+ // this caller may not see, so shipping it beside the emptied arrays+ // said `watch` with nothing to point at - which tells the caller a+ // hidden artifact tripped a detector, the existence leak with the+ // evidence removed. `toolBrainDoctor` above recomputes its `ok` for+ // exactly this reason.+ verdict: foldSemanticHealthVerdict({+ contradictions,+ conceptGaps,+ staleClaims,+ batchInflation,+ }),+ contradictions: contradictions.map((c) => ({a: c.aId,b: c.bId,...(c.scope !== null ? { scope: c.scope } : {}),@@ -179,16 +249,17 @@ async function toolBrainHealth(a_sign: c.aSign,b_sign: c.bSign,})),- concept_gaps: (sh?.conceptGaps ?? []).map((g) => ({+ // A term and its frequency; the only family that names no artifact.+ concept_gaps: conceptGaps.map((g) => ({term: g.term,frequency: g.frequency,})),- stale_claims: (sh?.staleClaims ?? []).map((s) => ({+ stale_claims: staleClaims.map((s) => ({id: s.id,last_evidence_at: s.lastEvidenceAt,age_days: s.ageDays,})),- batch_inflation: (sh?.batchInflation ?? []).map((b) => ({+ batch_inflation: batchInflation.map((b) => ({ids: b.ids,window_start: b.windowStart,window_end: b.windowEnd,diff --git a/src/mcp/brain/hygiene-tools.ts b/src/mcp/brain/hygiene-tools.tsindex 96041af7..800e35ca 100644--- a/src/mcp/brain/hygiene-tools.ts+++ b/src/mcp/brain/hygiene-tools.ts@@ -19,6 +19,7 @@import { resolveAgentName } from "../../core/config.ts";import { loadBrainConfig } from "../../core/brain/policy.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import { applyHygienePlan } from "../../core/brain/hygiene/apply.ts";import { buildHygienePlan } from "../../core/brain/hygiene/plan.ts";import { resolveConflictFindings } from "../../core/brain/hygiene/resolve-conflicts.ts";@@ -76,15 +77,24 @@ function scanWithResolver(});}+/**+ * The artifacts one finding would disclose, as the owner-scope view+ * spells references: an absolute path rendered vault-relative, anything+ * else left as the Brain artifact id it already is.+ */+function findingRefs(vault: string, finding: HygieneFinding): ReadonlyArray<string> {+ return finding.targets.map((target) =>+ target.startsWith("/") ? vaultRelativeSafe(vault, target) : target,+ );+}+function findingView(vault: string, finding: HygieneFinding): Record<string, unknown> {return {id: finding.id,detector: finding.detector,severity: finding.severity,title: finding.title,- targets: finding.targets.map((target) =>- target.startsWith("/") ? vaultRelativeSafe(vault, target) : target,- ),+ targets: findingRefs(vault, finding),proposed_action: finding.proposed_action,evidence: finding.evidence,};@@ -143,6 +153,26 @@ async function linkIntegrityView(ctx: ServerContext): Promise<Record<string, unk};}+/**+ * Per-detector counts over the findings actually returned.+ *+ * Every detector that RAN keeps a key, so a detector with nothing to say+ * is still reported as having run with zero - the distinction between+ * "not run" and "found nothing" that `detectors_run` and `counts`+ * together carry.+ */+function countByDetector(+ detectorsRun: ReadonlyArray<HygieneDetectorId>,+ findings: ReadonlyArray<HygieneFinding>,+): Record<string, number> {+ const counts: Record<string, number> = {};+ for (const detector of detectorsRun) counts[detector] = 0;+ for (const finding of findings) {+ counts[finding.detector] = (counts[finding.detector] ?? 0) + 1;+ }+ return counts;+}+async function toolBrainHygiene(ctx: ServerContext,args: Record<string, unknown>,@@ -184,15 +214,43 @@ async function toolBrainHygiene("'detectors' entries must be: conflicts, dedup, freshness, usefulness",);}- const report = scanWithResolver(ctx.vault, detectors, now);+ const scanned = scanWithResolver(ctx.vault, detectors, now);++ // The owner boundary is applied to the REPORT, once, before EITHER mode+ // reads it. `findings[].targets` are artifact ids (or absolute paths+ // rendered vault-relative) and the `title` spells the same artifact out+ // in prose (a-label-is-not-a-boundary, U3, recon C2).+ //+ // Hoisted out of the `scan` branch on purpose. While it lived there,+ // `apply` planned against the UNFILTERED report, so a caller scoped to+ // one owner whose scan correctly returned nothing could still hand a+ // finding id to `apply` and merge, retire or archive another owner's+ // preference - and read both hidden ids back out of the applier's+ // `detail`. Finding ids are derivable rather than secret+ // (`hygiene/detectors/id.ts` hashes the sorted target list), so+ // withholding them from the scan was never the boundary; this is.+ //+ // Filtering the report rather than the plan is also what makes a hidden+ // finding IDENTICAL TO ABSENT: `buildHygienePlan` indexes what it is+ // given, so an id it cannot see lands in `unknown_ids` exactly as an id+ // nobody ever issued does. A separate "withheld" bucket - or a hidden+ // id landing in `excluded_review` while a nonexistent one lands in+ // `unknown_ids` - would be an existence oracle over the same+ // population the scan just refused to enumerate+ // (`preferences-collect.ts` states the convention).+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ const findings = view.keep(scanned.findings, (f) => findingRefs(ctx.vault, f));+ const report: HygieneScanReport = Object.freeze({ ...scanned, findings });if (mode === "scan") {+ // `counts` is recomputed from the visible findings: a count over the+ // unfiltered set would report how many findings were withheld.return {mode,generated_at: report.generated_at,detectors_run: report.detectors_run,- counts: report.counts,- findings: report.findings.map((finding) => findingView(ctx.vault, finding)),+ counts: countByDetector(report.detectors_run, findings),+ findings: findings.map((finding) => findingView(ctx.vault, finding)),errors: report.errors,link_integrity: await linkIntegrityView(ctx),};diff --git a/src/mcp/brain/ingest-tools.ts b/src/mcp/brain/ingest-tools.tsindex 53100c0f..bbff20fb 100644--- a/src/mcp/brain/ingest-tools.ts+++ b/src/mcp/brain/ingest-tools.ts@@ -23,7 +23,13 @@ import {import { resolveAgentName } from "../../core/config.ts";import { normalizeAgentScope } from "../../core/graph/agent-scope.ts";import { isPathOwnerVisible, type FrontmatterCache } from "../../core/search/result-filters.ts";-import { coerceBoolOptional, coerceInt, coerceStr, coerceStrList } from "../coerce.ts";+import {+ coerceAgentScope,+ coerceBoolOptional,+ coerceInt,+ coerceStr,+ coerceStrList,+} from "../coerce.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { parseExtractionIntakeArgs } from "./intake-args.ts";@@ -145,7 +151,7 @@ async function toolBrainSearchBySource(// fail-closed treatment of frontmatter that will not parse. `total`// counts what is returned; a total over the hidden pages would leak// their number. An absent scope filters nothing.- const scope = normalizeAgentScope(coerceStr(args, "agent_scope", false) ?? undefined);+ const scope = normalizeAgentScope(coerceAgentScope(ctx, args, false));const cache: FrontmatterCache = new Map();const visible =scope === nulldiff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.tsindex 476db69c..fcc0b1de 100644--- a/src/mcp/brain/knowledge-tools.ts+++ b/src/mcp/brain/knowledge-tools.ts@@ -37,6 +37,7 @@ import {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 { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";import { isoSecond } from "../../core/brain/time.ts";import { normalizeAgentArgument } from "../../core/agent-identity.ts";@@ -62,6 +63,7 @@ import {} from "../../core/brain/claim-graph.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { AGENT_SCOPE_SCHEMA, coerceAgentScope, coerceStr, coerceBool } from "../coerce.ts";import { coercePositiveInteger, toolSafeguard } from "./shared.ts";@@ -285,15 +287,42 @@ async function toolBrainClusters(} catch {// Metrics are observability, not correctness.}+ // A community is reported by the pages it contains: `members` are+ // vault-relative paths, `id` is derived from the seed page's path,+ // and the materialised `written` note is named after the same seed+ // (a-label-is-not-a-boundary, U3). A community is dropped WHOLE+ // rather than trimmed - its `size` and `density` describe the+ // subgraph the detector measured, so a community of seven reported+ // as four is not a narrower true finding, it is a false one, and the+ // same argument `brain_health` makes about a batch-inflation burst.+ //+ // Detection and materialisation stay vault-wide: clustering the+ // visible half of a link graph would produce different communities+ // for every caller and write them over each other. This filters what+ // the CALLER is told, which is the boundary the gate declares.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ const visible = view.keep(communities, (c) => c.members.map((m) => m.path));+ // `written` / `removed` are the cluster NOTES, and a cluster note is+ // named `cluster-<community id>.md` after the seed page - so its own+ // frontmatter carries no owner while its filename spells one. They+ // are therefore filtered by which community they belong to, through+ // the materialiser's own naming rule, not by asking the note file+ // what it owns.+ const visibleNotes = new Set(visible.map((c) => `Brain/clusters/cluster-${c.id}.md`));return {- communities: communities.map((c) => ({+ communities: visible.map((c) => ({id: c.id,size: c.size,density: c.density,members: c.members.map((m) => m.path),})),- written: materialized.written,- removed: materialized.removed,+ written: materialized.written.filter((p) => visibleNotes.has(p)),+ // A removal names a community that no longer exists, so there is+ // no surviving membership to ask about. Under a scope the list is+ // withheld whole: it is the one field here whose subject cannot be+ // resolved, and a `removed` entry naming a hidden seed is the same+ // disclosure as a `written` one.+ removed: view.scope === null ? materialized.removed : [],...(materialized.batches ? { batches: materialized.batches } : {}),};} finally {@@ -319,9 +348,14 @@ async function toolBrainMocAudit(}const targetId = normaliseWikilinkTarget(idRaw);try {- const report = auditMoc(ctx.vault, targetId);+ // `fragile[].id`, `bodyChars` and the exists-vs-missing verdict all+ // describe cluster members; unscoped they described another owner's+ // (a-label-is-not-a-boundary, U3, recon C4).+ const report = auditMoc(ctx.vault, targetId, {+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,+ });return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),hub_id: report.hubId,outbound_count: report.outboundCount,well_covered: report.wellCovered,@@ -445,7 +479,12 @@ function toolBrainIdeaDiscovery(}const enqueue = coerceBool(args, "triggers");const now = new Date();- const ideas = discoverIdeas(ctx.vault, { now, cap });+ // `source_artifacts` are vault-relative artifact paths and the `reason`+ // sentence spells one out, so an unscoped ranking named another owner's+ // notes (a-label-is-not-a-boundary, U3). Filtered BEFORE the trigger+ // pass so a hidden artifact cannot be enqueued either.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ const ideas = view.keep(discoverIdeas(ctx.vault, { now, cap }), (i) => i.sourceArtifacts);let triggersCreated: number | undefined;if (enqueue) {const result = createTriggers(ctx.vault, ideaCandidates(ideas), {@@ -658,19 +697,33 @@ function toolBrainClaims(args: Record<string, unknown>,): Record<string, unknown> {const operation = coerceStr(args, "operation", false) ?? "current";+ // A claim row carries the artifact's id, its vault-relative path, its+ // topic AND its full principle text - the sharpest counter-example in+ // recon C6 to the "this bucket is metadata" label. Every row-returning+ // operation is filtered, and so is the rebuild count: a count the+ // caller cannot decompose still says how many claims exist.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ const visible = (rows: ReadonlyArray<ClaimNode>): ReadonlyArray<ClaimNode> =>+ view.keep(rows, (n) => [n.path, n.id]);switch (operation) {case "rebuild": {const graph = rebuildClaimGraph(ctx.vault);- return { operation, rebuilt: true, node_count: graph.node_count, truncated: graph.truncated };+ return {+ operation,+ rebuilt: true,+ node_count: visible(allClaims(graph)).length,+ truncated: graph.truncated,+ };}case "replaced": {const id = coerceStr(args, "id", true)!;const tip = whatReplaced(resolveClaimGraph(ctx.vault), id);- return { operation, id, tip: tip ? renderClaimNode(tip) : null };+ const shown = tip !== null && view.row(tip.path, tip.id) ? tip : null;+ return { operation, id, tip: shown ? renderClaimNode(shown) : null };}case "contests": {const id = coerceStr(args, "id", true)!;- const rows = whatContests(resolveClaimGraph(ctx.vault), id);+ const rows = visible(whatContests(resolveClaimGraph(ctx.vault), id));return { operation, id, claims: rows.map(renderClaimNode) };}case "at": {@@ -683,15 +736,15 @@ function toolBrainClaims(`brain_claims: 'at' must be an ISO instant or YYYY-MM-DD date; got ${at}`,);}- const rows = truthAt(resolveClaimGraph(ctx.vault), probe);+ const rows = visible(truthAt(resolveClaimGraph(ctx.vault), probe));return { operation, at, count: rows.length, claims: rows.map(renderClaimNode) };}case "history": {- const rows = allClaims(resolveClaimGraph(ctx.vault));+ const rows = visible(allClaims(resolveClaimGraph(ctx.vault)));return { operation, count: rows.length, claims: rows.map(renderClaimNode) };}case "current": {- const rows = currentTruth(resolveClaimGraph(ctx.vault));+ const rows = visible(currentTruth(resolveClaimGraph(ctx.vault)));return { operation, count: rows.length, claims: rows.map(renderClaimNode) };}default:diff --git a/src/mcp/brain/landscape-tools.ts b/src/mcp/brain/landscape-tools.tsindex 9dddaee9..020eda59 100644--- a/src/mcp/brain/landscape-tools.ts+++ b/src/mcp/brain/landscape-tools.ts@@ -8,11 +8,12 @@import { buildMcpLandscape } from "../../core/graph/mcp-config.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { VAULT_PATH_OUTPUT_SCHEMA, vaultPathField } from "../vault-path-field.ts";async function toolMcpLandscape(ctx: ServerContext): Promise<Record<string, unknown>> {const landscape = buildMcpLandscape(ctx.vault);return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),servers: landscape.servers.map((s) => ({name: s.name,source: s.source,@@ -38,7 +39,7 @@ export const LANDSCAPE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "object",required: ["vault_path", "servers"],properties: {- vault_path: { type: "string" },+ vault_path: VAULT_PATH_OUTPUT_SCHEMA,servers: {type: "array",items: {diff --git a/src/mcp/brain/lifecycle-file-tools.ts b/src/mcp/brain/lifecycle-file-tools.tsindex 505d28d4..54109971 100644--- a/src/mcp/brain/lifecycle-file-tools.ts+++ b/src/mcp/brain/lifecycle-file-tools.ts@@ -35,6 +35,7 @@ import {ScaffoldStubError,} from "../../core/brain/notes/scaffold-stub.ts";import { CountGuardError } from "../../core/brain/count-guard.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import {CreateNoteError,CREATE_NOTE_IF_EXISTS,@@ -262,7 +263,13 @@ async function toolBrainScaffoldStub(if (action === STUB_SCAFFOLD_ACTION.list) {const limit = coerceNonNegativeInteger(STUB_TOOL, "limit", args["limit"]);- const scan = await listDanglingTargets(ctx.vault, limit !== undefined ? { limit } : {});+ // `sources` are vault-relative document paths and `target` is the+ // link spelling, so an unscoped listing published both for a note+ // this caller may not read (a-label-is-not-a-boundary, U3).+ const scan = await listDanglingTargets(ctx.vault, {+ ...(limit !== undefined ? { limit } : {}),+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,+ });return {action,state: scan.state,diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.tsindex 25102adc..c17a924c 100644--- a/src/mcp/brain/pack-tools.ts+++ b/src/mcp/brain/pack-tools.ts@@ -46,13 +46,18 @@ import {} from "../../core/brain/context-presets.ts";import { extractPreCompactRecords } from "../../core/brain/pre-compact-extract.ts";import { EventTraceSelectorError, resolveLogEventTraces } from "../../core/brain/event-trace.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "../../core/brain/types.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import {AGENT_SCOPE_SCHEMA,+ MATCH_QUALITY_SCHEMA,+ RECALL_SCORES_SCHEMA,coerceAgentScope,+ coerceRecallAdequacyInput,coerceStr,coerceStrList,coerceBool,@@ -96,11 +101,11 @@ async function toolBrainContextPack(// Adequacy verdict (t_b8f66fec): when the caller passes the recall// scores that produced this material, classify grounding fitness and// name the action; also persist it in the receipt for the audit trail.- const recallScores = parseRecallScores(args["recall_scores"]);+ const recallAttempt = coerceRecallAdequacyInput("brain_context_pack", args, "recall_scores");const adequacy =- recallScores !== undefined+ recallAttempt !== undefined? assessRecallAdequacy(- recallScores,+ recallAttempt,resolveRecallAdequacyThresholds(ctx.configPath ?? undefined),): undefined;@@ -175,7 +180,7 @@ async function toolBrainContextPack(...(attentionFlowIds.length > 0 ? { attentionFlowIds } : {}),});return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),max_tokens: report.maxTokens,tokens_used: report.tokensUsed,items: report.items.map((i) => ({@@ -218,36 +223,6 @@ async function toolBrainContextPack(};}-/**- * Parse the optional `recall_scores` argument. Returns `undefined` when- * absent (verdict skipped) and throws INVALID_PARAMS on a malformed- * shape. An empty array is a valid "no results" signal.- */-function parseRecallScores(raw: unknown): ReadonlyArray<number> | undefined {- if (raw === undefined || raw === null) return undefined;- if (!Array.isArray(raw)) {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack: recall_scores must be an array of numbers",- );- }- if (raw.length > 200) {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack: recall_scores must not exceed 200 items",- );- }- for (const item of raw) {- if (typeof item !== "number") {- throw new MCPError(- INVALID_PARAMS,- "brain_context_pack: recall_scores must contain only numbers",- );- }- }- return raw as ReadonlyArray<number>;-}-// ----- brain_context_receipts ---------------------------------------------async function toolBrainContextReceipts(@@ -274,7 +249,7 @@ async function toolBrainContextReceipts(});const summaries = receipts.map(summarizeContextReceipt);return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),total: summaries.length,receipts: summaries,};@@ -370,7 +345,7 @@ async function summarizeReceipts(});if (!fold.recorded) {return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),recorded: false,max_receipts: fold.max_receipts,note: "no receipts recorded for this filter; receipt emission is opt-in per call",@@ -387,7 +362,7 @@ async function summarizeReceipts(const items = limit === undefined ? fold.items : fold.items.slice(0, limit);return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),recorded: true,receipt_count: fold.receipt_count,item_total: fold.item_total,@@ -450,6 +425,9 @@ async function toolBrainEventTrace(...(sessionId !== undefined ? { sessionId } : {}),...(limit !== undefined ? { limit } : {}),...(keepPrivate === true ? { keepPrivate: true } : {}),+ // The event body is echoed verbatim and log payloads carry+ // artifact paths (a-label-is-not-a-boundary, U3).+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,});} catch (err) {// A selector-validation error (bad date/at/kind, checked before any IO) is@@ -463,7 +441,7 @@ async function toolBrainEventTrace(}return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),total: events.length,trace_total: events.reduce((sum, e) => sum + e.traceCount, 0),events,@@ -577,7 +555,7 @@ async function toolBrainPreCompressPack(...(telemetry !== undefined ? { telemetry } : {}),});return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),text: pack.text,active_head_included: pack.activeHeadIncluded,...(pack.activeHeadSafety ? { active_head_safety: pack.activeHeadSafety } : {}),@@ -758,13 +736,8 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "string",description: "Optional host/runtime name for emitted receipts; defaults to `mcp`.",},- recall_scores: {- type: "array",- maxItems: 200,- items: { type: "number" },- description:- "Optional relevance scores of the recall behind this material. When given, the response adds an adequacy verdict (level + action) and persists it in the receipt.",- },+ recall_scores: RECALL_SCORES_SCHEMA,+ match_quality: MATCH_QUALITY_SCHEMA,telemetry: {type: "boolean",description:diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.tsindex b409eae1..f99fa064 100644--- a/src/mcp/brain/query-tools.ts+++ b/src/mcp/brain/query-tools.ts@@ -7,6 +7,7 @@*/import { buildBacklinkIndex } from "../../core/brain/backlinks.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import { readPrefAudit } from "../../core/brain/pref-audit.ts";import { aggregateSources } from "../../core/brain/portability/sources.ts";import { findUnlinkedMentions } from "../../core/brain/link-graph/unlinked-mentions.ts";@@ -29,8 +30,10 @@ import {import type { BrainLogEntry } from "../../core/brain/log.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import {+ coerceAgentScope,coerceStr,coerceStrList,coerceBoolOptional,@@ -139,9 +142,9 @@ async function toolBrainQuery(// Owner-scoped fact recall (Knowledge Provenance suite, v1.7). Off by// default: when the guardrail flag is off (or no scope is requested) the// scope is null and every fact is visible exactly as before.- const requestedScope = coerceStr(args, "agent_scope", false);+ const requestedScope = coerceAgentScope(ctx, args, false);const ownerScope = loadGuardrailsConfigSafe(ctx.vault).owner_scoped_facts- ? normalizeAgentScope(requestedScope ?? undefined)+ ? normalizeAgentScope(requestedScope): null;const startedAtMs = Date.now();@@ -240,13 +243,13 @@ async function toolBrainAgentQuery(// Owner-scope isolation (context-integrity-gates, Unit A): the// provenance view reads the same preference and retired pages the// delivery surfaces do, so it honours the same ownership rule.- const ownerScope = coerceStr(args, "agent_scope", false);+ const ownerScope = coerceAgentScope(ctx, args, false);return queryAgentSources(ctx.vault, {agents: coerceStrList(args, "agents"),...(topic !== null ? { topic } : {}),...(query !== null ? { query } : {}),...(kind !== null ? { kind } : {}),- ...(ownerScope !== null ? { ownerScope } : {}),+ ...(ownerScope !== undefined ? { ownerScope } : {}),limit: coerceInt(args, "limit", 50, 1, 500),}) as unknown as Record<string, unknown>;}@@ -259,8 +262,16 @@ async function toolBrainAgentDiff(const topic = coerceStr(args, "topic", false);const query = coerceStr(args, "query", false);const kind = coerceAgentContributionKind(args, "kind");+ // The twin of `brain_agent_query` over the same provenance fold, and+ // it returns the same contribution rows - ids, topics and the record+ // text. `brain_agent_query` honours an explicit `agent_scope`; this+ // tool declares no such argument, so it takes the GATED server+ // identity, which is `null` unless the operator set+ // `integrity.owner_scope_delivery: fail` (a-label-is-not-a-boundary, U3).+ const ownerScope = gatedOwnerScopeView(ctx.vault, ctx.agentName).scope;return diffAgentSources(ctx.vault, {...(mode !== null ? { mode } : {}),+ ...(ownerScope !== null ? { ownerScope } : {}),agents: coerceStrList(args, "agents"),...(topic !== null ? { topic } : {}),...(query !== null ? { query } : {}),@@ -311,7 +322,11 @@ async function toolBrainBacklinks(// `[[pref-foo|Alias]]`, and `Brain/preferences/pref-foo.md` all// resolve to the same lookup.const target = normaliseWikilinkTarget(id);- const index = buildBacklinkIndex(ctx.vault);+ // The refs name the artifacts that WROTE them, so an unscoped index+ // published another owner's preference and retired ids to any caller+ // (a-label-is-not-a-boundary, U3). The scope is the gated one: no+ // argument exists on this tool, and under `off` the view hides nothing.+ const index = buildBacklinkIndex(ctx.vault, gatedOwnerScopeView(ctx.vault, ctx.agentName).scope);const refs = index.get(target) ?? [];return {id: target,@@ -322,6 +337,20 @@ async function toolBrainBacklinks(field: r.field,...(r.timestamp !== undefined ? { timestamp: r.timestamp } : {}),})),+ // A `count` beside a non-empty `unparsed` is not a measurement: the+ // walk skipped artifacts whose references it could not read, and a+ // caller told only the count would read a legacy vault's zero as a+ // genuine zero. Omitted entirely when the walk was clean, so a+ // healthy vault's payload is byte-identical.+ ...(index.unparsed.length > 0+ ? {+ unparsed: index.unparsed.map((u) => ({+ source: u.source,+ source_kind: u.sourceKind,+ reason: u.reason,+ })),+ }+ : {}),};}@@ -414,9 +443,14 @@ async function toolBrainUnlinkedMentions();}}- const mentions = findUnlinkedMentions(ctx.vault, targetId, limit !== undefined ? { limit } : {});+ // `context` is the source artifact's own line of prose, so an+ // unscoped scan republished an owner-private body (U3, recon C3).+ const mentions = findUnlinkedMentions(ctx.vault, targetId, {+ ...(limit !== undefined ? { limit } : {}),+ ownerScope: gatedOwnerScopeView(ctx.vault, ctx.agentName).scope,+ });return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),target_id: targetId,mentions: mentions.map((m) => ({source: m.source,diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.tsindex fa79316a..18b78aa0 100644--- a/src/mcp/brain/recall-tools.ts+++ b/src/mcp/brain/recall-tools.ts@@ -74,6 +74,7 @@ import { buildRetrievalPlan, serializeRetrievalPlan } from "../../core/brain/retimport { isoSecond } from "../../core/brain/time.ts";import { INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";import { AGENT_SCOPE_SCHEMA, coerceAgentScope } from "../coerce.ts";@@ -203,7 +204,7 @@ async function toolBrainRecallTelemetry(if (operation === "list") {const records = listRecallTelemetry(ctx.vault, filter);- return { vault_path: ctx.vault, total: records.length, records };+ return { vault_path: vaultPathField(ctx), total: records.length, records };}if (operation === "summary") {const summary = summarizeRecallTelemetry(ctx.vault, filter);@@ -218,7 +219,7 @@ async function toolBrainRecallTelemetry(...(filter.until !== undefined ? { until: filter.until } : {}),...(filter.limit !== undefined ? { limit: filter.limit } : {}),});- return { vault_path: ctx.vault, total: records.length, records };+ return { vault_path: vaultPathField(ctx), total: records.length, records };}if (operation === "gate_summary") {const summary = summarizeGateTelemetry(ctx.vault, {@@ -235,7 +236,7 @@ async function toolBrainRecallTelemetry(const artifacts = [...observedReuseRates(ctx.vault).entries()].map(([key, r]) => ({ key, ...r })).toSorted((a, b) => (a.score !== b.score ? b.score - a.score : a.key < b.key ? -1 : 1));- return { vault_path: ctx.vault, total: artifacts.length, artifacts };+ return { vault_path: vaultPathField(ctx), total: artifacts.length, artifacts };}// Write-vs-read cost meter (memory cost meter): folds write volume// against the read telemetry above. Period-based; mode/status/host/limit@@ -267,7 +268,7 @@ async function toolBrainRecallTelemetry(: {}),...(writeHeavyRatio !== undefined ? { writeHeavyRatio } : {}),});- return { vault_path: ctx.vault, ...meter };+ return { vault_path: vaultPathField(ctx), ...meter };}throw new MCPError(INVALID_PARAMS,@@ -355,11 +356,11 @@ async function toolBrainRouteMetrics(if (operation === "list") {const records = listMcpRouteLatency(ctx.vault, filter);- return { vault_path: ctx.vault, total: records.length, records };+ return { vault_path: vaultPathField(ctx), total: records.length, records };}if (operation === "summary") {const summary = summarizeMcpRouteLatency(ctx.vault, filter);- return { vault_path: ctx.vault, ...summary };+ return { vault_path: vaultPathField(ctx), ...summary };}throw new MCPError(INVALID_PARAMS, "brain_route_metrics: operation must be list or summary");}@@ -381,7 +382,7 @@ async function toolBrainRetrievalPlan(...(tokenBudget !== undefined ? { tokenBudget } : {}),...(agentScope !== undefined ? { agentScope } : {}),});- return { vault_path: ctx.vault, ...serializeRetrievalPlan(plan) };+ return { vault_path: vaultPathField(ctx), ...serializeRetrievalPlan(plan) };}function routeMetricsFilter(args: Record<string, unknown>): McpRouteLatencyFilter {@@ -466,10 +467,10 @@ async function toolBrainTokenImpact(enabled || undefined,);if (record === null) {- return { vault_path: ctx.vault, recorded: false, enabled };+ return { vault_path: vaultPathField(ctx), recorded: false, enabled };}return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),recorded: true,enabled,id: record.id,@@ -504,18 +505,18 @@ async function toolBrainTokenImpact(enabled || undefined,);if (record === null) {- return { vault_path: ctx.vault, recorded: false, enabled };+ return { vault_path: vaultPathField(ctx), recorded: false, enabled };}- return { vault_path: ctx.vault, recorded: true, enabled, id: record.id, outcome };+ return { vault_path: vaultPathField(ctx), recorded: true, enabled, id: record.id, outcome };}const filter = tokenImpactFilter(args);if (operation === "list") {const records = listTokenImpact(ctx.vault, filter);- return { vault_path: ctx.vault, total: records.length, records };+ return { vault_path: vaultPathField(ctx), total: records.length, records };}if (operation === "summary") {- return { vault_path: ctx.vault, ...summarizeTokenImpact(ctx.vault, filter) };+ return { vault_path: vaultPathField(ctx), ...summarizeTokenImpact(ctx.vault, filter) };}throw new MCPError(INVALID_PARAMS,@@ -704,10 +705,10 @@ async function toolBrainContextPackOutcome(enabled || undefined,);if (post === null) {- return { vault_path: ctx.vault, recorded: false, enabled };+ return { vault_path: vaultPathField(ctx), recorded: false, enabled };}return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),recorded: true,enabled,id: post.outcome.id,@@ -724,10 +725,10 @@ async function toolBrainContextPackOutcome(const filter = contextPackOutcomeFilter(args);if (operation === "list") {const records = listContextPackOutcomes(ctx.vault, filter);- return { vault_path: ctx.vault, total: records.length, records };+ return { vault_path: vaultPathField(ctx), total: records.length, records };}if (operation === "summary") {- return { vault_path: ctx.vault, ...summarizeContextPackOutcomes(ctx.vault, filter) };+ return { vault_path: vaultPathField(ctx), ...summarizeContextPackOutcomes(ctx.vault, filter) };}throw new MCPError(INVALID_PARAMS,@@ -861,7 +862,7 @@ async function toolBrainKnowledgeGaps(...(maxSatisfaction !== undefined ? { maxSatisfaction } : {}),...(limit !== undefined ? { limit } : {}),});- return { vault_path: ctx.vault, ...serializeQueryDemandReport(report) };+ return { vault_path: vaultPathField(ctx), ...serializeQueryDemandReport(report) };}function coerceUnitInterval(name: string, raw: unknown): number | undefined {diff --git a/src/mcp/brain/review-tools.ts b/src/mcp/brain/review-tools.tsindex ec872a7d..c7772df1 100644--- a/src/mcp/brain/review-tools.ts+++ b/src/mcp/brain/review-tools.ts@@ -13,9 +13,12 @@ import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";import { buildIntentReview } from "../../core/brain/intent-review.ts";import { buildRetentionReview } from "../../core/brain/retention.ts";import { buildReviewCandidates } from "../../core/brain/review-candidates.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";+import { brainArtifactSlug } from "../../core/brain/wikilink.ts";import { OPERATION } from "../../core/brain/safeguard.ts";import type { ProgressSink } from "../../core/brain/progress.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";+import { vaultPathField } from "../vault-path-field.ts";import { coerceIsoDate } from "../coerce.ts";import { toolSafeguard } from "./shared.ts";@@ -25,6 +28,14 @@ async function toolBrainIntentReview(): Promise<Record<string, unknown>> {const nowDate = coerceIsoDate(args, "now");const report = buildIntentReview(ctx.vault, nowDate ? { now: nowDate } : {});+ // Deliberately unfiltered, and the reason is on the record rather than+ // implied by silence (a-label-is-not-a-boundary, U3). Every row here is+ // a fold over INBOX SIGNAL clusters - a topic, a decision, a count -+ // and a signal carries no `owner:` anywhere in this product, so there+ // is no ownership claim on disk for this surface to read. A filter+ // keyed on "does a preference of this topic exist and may you see it"+ // would withhold a row whose whole content came from artifacts the+ // caller is entitled to, which is a narrowing nobody asked for.return {schema_version: report.schema_version,generated_at: report.generated_at,@@ -45,17 +56,22 @@ async function toolBrainRetention(): Promise<Record<string, unknown>> {const nowDate = coerceIsoDate(args, "now");const report = buildRetentionReview(ctx.vault, nowDate ? { now: nowDate } : {});+ // Each recommendation names a retired preference or a processed signal+ // by id and by vault-relative path (a-label-is-not-a-boundary, U3).+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);return {schema_version: report.schema_version,generated_at: report.generated_at,summary: report.summary,- recommendations: report.recommendations.map((recommendation) => ({- id: recommendation.id,- artifact_type: recommendation.artifact_type,- action: recommendation.action,- reason: recommendation.reason,- path: recommendation.path,- })),+ recommendations: view+ .keep(report.recommendations, (r) => [r.path, r.id])+ .map((recommendation) => ({+ id: recommendation.id,+ artifact_type: recommendation.artifact_type,+ action: recommendation.action,+ reason: recommendation.reason,+ path: recommendation.path,+ })),};}@@ -86,18 +102,42 @@ async function toolBrainReviewCandidates(...(nowDate ? { now: nowDate } : {}),...(searchConfig !== undefined ? { searchConfig } : {}),});+ // The projected rows name preferences that EXIST by the id they would+ // get after the pass, so `ret-<slug>` is resolved back through the+ // shared slug fold and both spellings are asked about+ // (a-label-is-not-a-boundary, U3).+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);+ const bothSpellings = (id: string): ReadonlyArray<string> => {+ const slug = brainArtifactSlug(id);+ return [`pref-${slug}`, `ret-${slug}`];+ };+ // `clusters_below_threshold` and `intent_reviews` stay unfiltered, for+ // the reason `brain_intent_review` states above: both are keyed by a+ // topic over inbox signals, and signals carry no owner.return {- ...(report.signal_novelty !== undefined ? { signal_novelty: report.signal_novelty } : {}),- would_create: [...report.would_create],- would_promote: [...report.would_promote],- would_retire: report.would_retire.map((r) => ({- id: r.id,- reason: r.reason,- })),- would_supersede: report.would_supersede.map((r) => ({- id: r.id,- reason: r.reason,- })),+ // Signal rows name an inbox signal by id AND by vault-relative path.+ ...(report.signal_novelty !== undefined+ ? { signal_novelty: view.keep(report.signal_novelty, (s) => [s.path, s.id]) }+ : {}),+ // `would_create` names ids the pass has not written yet, so most of+ // them resolve to nothing and pass; asking anyway is what keeps a+ // projection over an id that DOES already exist from crossing.+ would_create: view.keep(report.would_create, (id) => bothSpellings(id)),+ // `would_promote` is the one that always names live pages: an+ // unconfirmed preference on disk, transitioning to confirmed.+ would_promote: view.keep(report.would_promote, (id) => bothSpellings(id)),+ would_retire: view+ .keep(report.would_retire, (r) => bothSpellings(r.id))+ .map((r) => ({+ id: r.id,+ reason: r.reason,+ })),+ would_supersede: view+ .keep(report.would_supersede, (r) => bothSpellings(r.id))+ .map((r) => ({+ id: r.id,+ reason: r.reason,+ })),clusters_below_threshold: report.clusters_below_threshold.map((c) => ({topic: c.topic,signal_count: c.signal_count,@@ -105,14 +145,16 @@ async function toolBrainReviewCandidates(age_days: c.age_days,failed_gates: [...c.failed_gates],})),- gated_retires: report.gated_retires.map((g) => ({- pref_id: g.pref_id,- topic: g.topic,- applied_count: g.applied_count,- violated_count: g.violated_count,- threshold: g.threshold,- attempted_reason: g.attempted_reason,- })),+ gated_retires: view+ .keep(report.gated_retires, (g) => bothSpellings(g.pref_id))+ .map((g) => ({+ pref_id: g.pref_id,+ topic: g.topic,+ applied_count: g.applied_count,+ violated_count: g.violated_count,+ threshold: g.threshold,+ attempted_reason: g.attempted_reason,+ })),intent_reviews: report.intent_reviews.map((review) => ({topic: review.topic,decision: review.decision,@@ -139,11 +181,15 @@ async function toolBrainStaleScan(const cfg = loadTemporalConfigSafe(ctx.vault);const index = buildTimelineIndex(ctx.vault, {});const report = findStaleEntries(index, ctx.vault, cfg);+ // Every stale row names its artifact by id, topic and vault-relative+ // path (a-label-is-not-a-boundary, U3). Log shards are named by date+ // and shared by construction, so they carry no ownership to read.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);return {- vault_path: ctx.vault,+ vault_path: vaultPathField(ctx),thresholds: report.thresholds,- stale_preferences: report.stalePreferences,- stale_signals: report.staleSignals,+ stale_preferences: view.keep(report.stalePreferences, (r) => [r.path, r.prefId]),+ stale_signals: view.keep(report.staleSignals, (r) => [r.path, r.signalId]),stale_log_files: report.staleLogFiles,generated_at: report.generatedAt,};diff --git a/src/mcp/brain/workspace-tools.ts b/src/mcp/brain/workspace-tools.tsindex 6e894fc1..be86f0d0 100644--- a/src/mcp/brain/workspace-tools.ts+++ b/src/mcp/brain/workspace-tools.ts@@ -14,6 +14,11 @@ import {unreadableTriggerJson,type TriggerAction,} from "../../core/brain/triggers/store.ts";+import {+ extractWikilinkRichBodies,+ parseWikilinkRich,+} from "../../core/brain/link-graph/parse-wikilink.ts";+import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";import {isTriggerStatus,TRIGGER_STATUSES,@@ -128,23 +133,53 @@ function isTriggerTransition(operation: string): operation is TriggerAction {return (TRIGGER_TRANSITIONS as ReadonlyArray<string>).includes(operation);}+/**+ * Every artifact one trigger record names+ * (a-label-is-not-a-boundary, U3).+ *+ * A trigger is not the ownerless lane its classification once claimed.+ * `source_artifacts` is a list of wikilinks to the preferences and+ * retired pages the detector fired on, `reason` spells the same ids and+ * their topics out in prose, and `cooldown_key` embeds them again - so a+ * `batch_inflation` trigger enumerated every owner's preference by id to+ * whoever ran the scan.+ */+function triggerRefs(record: TriggerRecord): ReadonlyArray<string> {+ return [+ ...record.sourceArtifacts,+ ...extractWikilinkRichBodies(record.reason).map((b) => parseWikilinkRich(b).target),+ ];+}+function toolBrainTrigger(ctx: ServerContext,args: Record<string, unknown>,): Record<string, unknown> {const operation = coerceStr(args, "operation", true)!;const now = new Date();+ // A trigger row is dropped WHOLE when any artifact it names is+ // withheld: `reason` and `cooldown_key` repeat the same ids the+ // `source_artifacts` list holds, so trimming the list alone would+ // leave the prose naming what the list no longer does.+ const view = gatedOwnerScopeView(ctx.vault, ctx.agentName);if (operation === "scan") {const cooldownDays = resolveTriggerCooldownDays(ctx.configPath ?? undefined);const result = scanTriggers(ctx.vault, { now, cooldownDays });return {operation,candidates: result.candidates,- created: result.created.map(triggerToJson),- skipped: result.skipped.map((skip) => ({- cooldown_key: skip.cooldownKey,- reason: skip.reason,- })),+ created: view.keep(result.created, triggerRefs).map(triggerToJson),+ // A cooldown key is `<kind>:<artifact>:<artifact-or-action>` - it+ // is BUILT from the ids the candidate fired on, so a `skipped` row+ // names the same preferences a `created` one does. Split on the+ // key's own separator and ask about every segment; a segment that+ // is a kind or an action resolves to no artifact and passes.+ skipped: view+ .keep(result.skipped, (skip) => skip.cooldownKey.split(":"))+ .map((skip) => ({+ cooldown_key: skip.cooldownKey,+ reason: skip.reason,+ })),// A scan that walked around a broken record is not a clean scan.unreadable: result.unreadable.map(unreadableTriggerJson),};@@ -168,13 +203,23 @@ function toolBrainTrigger(// read and held nothing rather than that part of it was skipped.return {operation,- triggers: records.map(triggerToJson),+ triggers: view.keep(records, triggerRefs).map(triggerToJson),unreadable: scan.unreadable.map(unreadableTriggerJson),};}if (isTriggerTransition(operation)) {const id = coerceStr(args, "id", true)!;try {+ // Checked BEFORE the transition, not after it: `transitionTrigger`+ // writes, so a check on its return value would have moved another+ // owner's trigger through the lifecycle and only then declined to+ // say so. A trigger this caller may not see answers exactly as an+ // absent id does - same message, byte for byte, from the store's+ // own error - because a distinguishable refusal confirms it exists.+ const target = readTriggers(ctx.vault, { now }).records.find((r) => r.id === id);+ if (target !== undefined && !view.row(...triggerRefs(target))) {+ throw new Error(`unknown trigger: ${id}`);+ }return {operation,trigger: triggerToJson(transitionTrigger(ctx.vault, id, operation, { now })),diff --git a/src/mcp/coerce.ts b/src/mcp/coerce.tsindex 2549d103..58c93d89 100644--- a/src/mcp/coerce.ts+++ b/src/mcp/coerce.ts@@ -6,6 +6,7 @@* with `INVALID_PARAMS` on bad input.*/+import { refuseOwnerScopeRequest } from "./owner-scope-refusal.ts";import { INVALID_PARAMS, MCPError } from "./protocol.ts";export function coerceStr(@@ -102,7 +103,11 @@ export const AGENT_SCOPE_SCHEMA = Object.freeze({});/**- * Read the owner scope a content-returning tool was called with.+ * Read the owner scope a content-returning tool was called with - the+ * ONE reader of {@link AGENT_SCOPE_ARG_NAME} in this tree, asserted by+ * `tests/mcp/owner-scope-refusal.test.ts`. A tool that spells the+ * argument itself would opt out of the identity check below, which is+ * the class of defect this seam exists to make impossible.** `fallbackToServerIdentity` is for the GATED preference-backed* surfaces: with no explicit argument they scope to the process's own@@ -111,15 +116,110 @@ export const AGENT_SCOPE_SCHEMA = Object.freeze({* and only there, because those surfaces filter nothing until the* operator sets the gate. The ungated search-backed surfaces pass* `false`, so an omitted argument keeps them byte-identical.+ *+ * An EXPLICIT argument is checked against the server-resolved identity+ * under `owner_scope_delivery: fail` and refused when it names another+ * owner - see {@link refuseOwnerScopeRequest} for why refusing beats+ * narrowing. `ctx.agentName` is read only on that path and only when a+ * scope was supplied, so a call that asks for nothing costs nothing and+ * a vault that never opted in is untouched.*/export function coerceAgentScope(- ctx: { readonly agentName?: string },+ ctx: { readonly vault: string; readonly agentName?: string },args: Record<string, unknown>,fallbackToServerIdentity: boolean,): string | undefined {const explicit = coerceStringOptional(args, AGENT_SCOPE_ARG_NAME, AGENT_SCOPE_MAX_LEN);- if (explicit !== undefined) return explicit;- return fallbackToServerIdentity ? ctx.agentName : undefined;+ if (explicit === undefined) return fallbackToServerIdentity ? ctx.agentName : undefined;+ const refused = refuseOwnerScopeRequest(ctx.vault, {+ argument: AGENT_SCOPE_ARG_NAME,+ requested: explicit,+ identity: ctx.agentName,+ });+ if (refused !== null) throw new MCPError(INVALID_PARAMS, refused.message);+ return explicit;+}++/** Longest accepted recall-score array; a top-k list, not a corpus. */+const RECALL_SCORES_MAX_ITEMS = 200;++export const MATCH_QUALITY_ARG_NAME = "match_quality";++/**+ * Input-schema fragments for the two arguments an adequacy verdict needs.+ * Declared once, beside {@link AGENT_SCOPE_SCHEMA}, because the two tools+ * that accept them spelled the score parser out twice already and the+ * second argument would have made it three descriptions of one contract.+ */+export const RECALL_SCORES_SCHEMA = Object.freeze({+ type: "array",+ maxItems: RECALL_SCORES_MAX_ITEMS,+ items: { type: "number" },+ description:+ "Optional top-k recall scores; requires `match_quality`. Together they add an adequacy verdict: sufficient/proceed, weak/re_recall, insufficient/abstain.",+});++export const MATCH_QUALITY_SCHEMA = Object.freeze({+ type: "number",+ minimum: 0,+ maximum: 1,+ description:+ "Absolute match quality in [0,1]: the `idf_weighted_coverage` a search outcome reports. Required with scores; the adequacy level reads this, never a score.",+});++/**+ * One recall attempt as {@link assessRecallAdequacy} reads it, or+ * `undefined` when the caller asked for no verdict.+ *+ * The two arguments stand or fall together. Scores without a quality+ * cannot be graded - the level is decided by the quality alone - and+ * inventing one from the scores is exactly the substitution this release+ * removes, so an incomplete pair is refused rather than half-honoured.+ */+export function coerceRecallAdequacyInput(+ tool: string,+ args: Record<string, unknown>,+ scoresKey: string,+): { readonly matchQuality: number; readonly scores: ReadonlyArray<number> } | undefined {+ const rawScores = args[scoresKey];+ const rawQuality = args[MATCH_QUALITY_ARG_NAME];+ const hasScores = rawScores !== undefined && rawScores !== null;+ const hasQuality = rawQuality !== undefined && rawQuality !== null;+ if (!hasScores && !hasQuality) return undefined;+ if (!hasScores || !hasQuality) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: '${scoresKey}' and '${MATCH_QUALITY_ARG_NAME}' must be given together; ` ++ `the adequacy level is decided by ${MATCH_QUALITY_ARG_NAME} and cannot be derived from scores`,+ );+ }+ if (!Array.isArray(rawScores)) {+ throw new MCPError(INVALID_PARAMS, `${tool}: '${scoresKey}' must be an array of numbers`);+ }+ if (rawScores.length > RECALL_SCORES_MAX_ITEMS) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: '${scoresKey}' must not exceed ${RECALL_SCORES_MAX_ITEMS} items`,+ );+ }+ for (const item of rawScores) {+ if (typeof item !== "number") {+ throw new MCPError(INVALID_PARAMS, `${tool}: '${scoresKey}' must contain only numbers`);+ }+ }+ if (typeof rawQuality !== "number" || !Number.isFinite(rawQuality)) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: '${MATCH_QUALITY_ARG_NAME}' must be a finite number`,+ );+ }+ if (rawQuality < 0 || rawQuality > 1) {+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: '${MATCH_QUALITY_ARG_NAME}' must be in [0,1]; got ${rawQuality}`,+ );+ }+ return { matchQuality: rawQuality, scores: rawScores as ReadonlyArray<number> };}export function coerceIsoDate(args: Record<string, unknown>, key: string): Date | null {diff --git a/src/mcp/http.ts b/src/mcp/http.tsindex c8677849..3524e437 100644--- a/src/mcp/http.ts+++ b/src/mcp/http.ts@@ -5,7 +5,7 @@* through MCPServer.handleRequest, the same core used by stdio.*/-import { createHash, randomUUID, timingSafeEqual } from "node:crypto";+import { createHash, timingSafeEqual } from "node:crypto";import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";import { once } from "node:events";import type { Writable } from "node:stream";@@ -162,11 +162,16 @@ async function handleHttpRequest(res.end();return;}- const headers: Record<string, string> = {};- if (jsonReq["method"] === "initialize") headers["mcp-session-id"] = randomUUID();+ // No `mcp-session-id`. The header is a promise of per-session state, and+ // this transport has none: one MCPServer instance serves every request+ // (see `startHttp`), identity and scope are process-global, and the id+ // that used to be minted here was never read back on any later request.+ // A client that received it would be entitled to expect the server to+ // recognise it - and to be told 404 once it expired - so advertising one+ // was a claim nothing behind it could honour.const accept = String(req.headers.accept ?? "");- if (accept.includes("text/event-stream")) writeSse(res, response, headers);- else writeJson(res, response, headers);+ if (accept.includes("text/event-stream")) writeSse(res, response);+ else writeJson(res, response);}function authorized(req: IncomingMessage, apiKey: string): boolean {@@ -270,24 +275,15 @@ async function readBody(req: IncomingMessage): Promise<string> {return Buffer.concat(chunks).toString("utf8");}-function writeJson(- res: ServerResponse,- response: JsonRpcResponse,- extraHeaders: Record<string, string> = {},-): void {- res.writeHead(200, { "content-type": "application/json", ...extraHeaders });+function writeJson(res: ServerResponse, response: JsonRpcResponse): void {+ res.writeHead(200, { "content-type": "application/json" });res.end(JSON.stringify(response));}-function writeSse(- res: ServerResponse,- response: JsonRpcResponse,- extraHeaders: Record<string, string> = {},-): void {+function writeSse(res: ServerResponse, response: JsonRpcResponse): void {res.writeHead(200, {"content-type": "text/event-stream","cache-control": "no-cache",- ...extraHeaders,});res.end(`event: message\ndata: ${JSON.stringify(response)}\n\n`);}diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex 507af2ee..9e34be53 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -8,7 +8,7 @@* the deferred full server.*/-import type { ToolScope } from "./tool-contract.ts";+import { TOOL_SCOPE, type ToolScope } from "./tool-contract.ts";export interface BuildInstructionsOpts {/**@@ -23,12 +23,13 @@ export interface BuildInstructionsOpts {* refusal is rendered in its place instead, naming the file.*/readonly agent: string | Error;- /** Vault path — reserved for future per-vault customisation. */- readonly vault?: string;- /** When "writer", return the trimmed writer-surface text. */+ /** Which surface's body follows the identity line. Defaults to full. */readonly scope?: ToolScope;}+/** Separator between the identity sentence and every paragraph after it. */+const PARAGRAPH_BREAK = "\n\n";+const WRITER_INSTRUCTIONS = `Open Second Brain — always-loaded MCP surface.Five tools live here (four writers + one reader; the server's name is@@ -77,7 +78,37 @@ Do not invent substitute workflows for a capability you cannot see:hydrate the catalog first; the tool is almost certainly already here.`;/**- * The opening identity sentence of the full-surface instructions.+ * The body every scope other than writer and catalog carries.+ *+ * Deliberately terse (token-diet): per-tool detail lives in the tool+ * descriptions and docs/mcp.md; this text carries only the contract that+ * cannot be read off the schemas.+ */+const FULL_INSTRUCTIONS =+ "Memory contract: call brain_feedback once per taste signal the " ++ "user expresses; brain_apply_evidence right after producing a " ++ "durable artifact a preference in `Brain/preferences/` scopes to " ++ "(result: applied | violated | outdated); brain_note for narrative " ++ "milestones that fit neither; brain_pinned_context for current-task " ++ "facts that must survive context rotation. brain_context " ++ "bootstraps a session when the host injects no active.md hook. " ++ "Skip Brain calls for casual chat, exploration, and trivial edits - " ++ "a misrecorded signal is worse than a missed one." ++ PARAGRAPH_BREAK ++ "Consolidated read views: brain_brief (view: morning | daily | " ++ "weekly | monthly | operator | digest), brain_analytics (view: " ++ "timeline | attention_flows | belief_evolution | concept_synthesis), " ++ "schema_inspect (view: graph | lint | stats | orphans | " ++ "explain_type | active_pack | packs). The per-view predecessor " ++ "names still resolve via tools/call as deprecated aliases." ++ PARAGRAPH_BREAK ++ "Preview budget: a large result may arrive as a JSON envelope with " ++ "`preview_truncated: true` and an `artifact_id`; fetch the full " ++ "payload with brain_artifact_get only when the preview is not " ++ "enough.";++/**+ * The opening identity sentence of every scope's instructions.** Both branches are an instruction, not a report: the resolved branch says* which name to log under, and the unresolved branch says that there is@@ -102,38 +133,30 @@ function identityLine(agent: string | Error): string {);}-export function buildInstructions(opts: BuildInstructionsOpts | string): string {- // Legacy call-site compat: plain string → full-surface branch.- const agent = typeof opts === "string" ? opts : opts.agent;- const scope = typeof opts === "string" ? undefined : opts.scope;-- if (scope === "writer") return WRITER_INSTRUCTIONS;- if (scope === "catalog") return CATALOG_INSTRUCTIONS;+/**+ * The body each scope carries after the identity line.+ *+ * A total map rather than a chain of `if`s: a scope added to+ * {@link TOOL_SCOPE} without a body here fails to compile, which is the+ * only reason the omission that this function used to carry - two of three+ * scopes returning before `agent` was read - could not recur.+ */+const SCOPE_BODIES: Readonly<Record<ToolScope, string>> = Object.freeze({+ [TOOL_SCOPE.full]: FULL_INSTRUCTIONS,+ [TOOL_SCOPE.writer]: WRITER_INSTRUCTIONS,+ [TOOL_SCOPE.catalog]: CATALOG_INSTRUCTIONS,+});- // Deliberately terse (token-diet): per-tool detail lives in the tool- // descriptions and docs/mcp.md; this text carries only the contract- // that cannot be read off the schemas.- return (- identityLine(agent) +- "\n\n" +- "Memory contract: call brain_feedback once per taste signal the " +- "user expresses; brain_apply_evidence right after producing a " +- "durable artifact a preference in `Brain/preferences/` scopes to " +- "(result: applied | violated | outdated); brain_note for narrative " +- "milestones that fit neither; brain_pinned_context for current-task " +- "facts that must survive context rotation. brain_context " +- "bootstraps a session when the host injects no active.md hook. " +- "Skip Brain calls for casual chat, exploration, and trivial edits - " +- "a misrecorded signal is worse than a missed one.\n\n" +- "Consolidated read views: brain_brief (view: morning | daily | " +- "weekly | monthly | operator | digest), brain_analytics (view: " +- "timeline | attention_flows | belief_evolution | concept_synthesis), " +- "schema_inspect (view: graph | lint | stats | orphans | " +- "explain_type | active_pack | packs). The per-view predecessor " +- "names still resolve via tools/call as deprecated aliases.\n\n" +- "Preview budget: a large result may arrive as a JSON envelope with " +- "`preview_truncated: true` and an `artifact_id`; fetch the full " +- "payload with brain_artifact_get only when the preview is not " +- "enough."- );+/**+ * Build the `initialize.instructions` block for one server process.+ *+ * Every scope opens with the identity line. The writer scope is the+ * always-loaded surface and its four writers are exactly the+ * identity-bearing ones, so the surface where the name matters most was+ * the one that used to omit it; the catalog scope hydrates into the same+ * writers.+ */+export function buildInstructions(opts: BuildInstructionsOpts): string {+ const body = SCOPE_BODIES[opts.scope ?? TOOL_SCOPE.full];+ return identityLine(opts.agent) + PARAGRAPH_BREAK + body;}diff --git a/src/mcp/owner-scope-refusal.ts b/src/mcp/owner-scope-refusal.tsnew file mode 100644index 00000000..26c5a0e1--- /dev/null+++ b/src/mcp/owner-scope-refusal.ts@@ -0,0 +1,144 @@+/**+ * Why a caller-supplied owner scope is REFUSED instead of honoured.+ *+ * `integrity.owner_scope_delivery: fail` reads as an isolation boundary,+ * and until this module it was the inverse of one. `coerceAgentScope`+ * returned the caller's `agent_scope` argument unconditionally and+ * `resolveOwnerScopeDelivery` enforced exactly that argument, so under+ * the gate a caller read ANY owner's private memories by naming that+ * owner - and the gate's presence implied a check nobody performed. An+ * identity that is echoed back from the request is not an identity.+ *+ * The rule stated here, once: under {@link GATE_MODE.fail} the+ * server-resolved identity is authoritative, and a caller-supplied scope+ * may only AGREE with it. A disagreement is refused by name. Silently+ * substituting the caller's own scope is deliberately not an option -+ * the caller would then believe it had read what it asked for, which is+ * the quiet fallback this repository forbids.+ *+ * Two things this module is careful about:+ *+ * - The comparison is {@link normalizeAgentScope} on both sides, the+ * same token normalisation {@link isOwnerVisible} compares with. A+ * second spelling of "the same owner" would be a second ownership+ * rule, and the release this module ships in exists because a rule+ * with two spellings is a rule with none.+ * - "The server has an identity" is {@link normalizeAgentArgument},+ * the same predicate every write surface already uses to reject a+ * guessed name. The bottom of the identity chain is the literal+ * `"agent"`, which that predicate rejects, so an unconfigured+ * install cannot silently become an owner.+ *+ * Scope of the refusal: every surface that ACCEPTS the argument, not+ * only the gated preference-delivery ones. The search-backed surfaces+ * are not narrowed by the gate today (see+ * `tests/mcp/agent-scope-matrix.test.ts`), so refusing a foreign scope+ * there closes nothing on its own - but an operator who set the gate has+ * declared owner scope a boundary rather than a filter, and leaving the+ * echo in place on half the surfaces is how it would be re-opened the+ * day those surfaces are gated.+ *+ * Under `warn` and `off` nothing is refused: neither mode withholds+ * anything, so a foreign scope cannot deliver what an absent one would+ * not, and refusing would break `warn`'s whole purpose - watching what+ * `fail` would do before turning it on.+ */++import { normalizeAgentArgument } from "../core/agent-identity.ts";+import { loadIntegrityConfigSafe } from "../core/brain/policy.ts";+import { normalizeAgentScope } from "../core/graph/agent-scope.ts";+import { GATE_MODE } from "../core/integrity/stamp.ts";++/** The operator key that makes the resolved identity authoritative. */+export const OWNER_SCOPE_GATE_KEY = "integrity.owner_scope_delivery";++/** The setting an operator changes to stop being refused. */+const IDENTITY_SETTINGS = "agent_name in the plugin config, or VAULT_AGENT_NAME";++export const OWNER_SCOPE_REFUSAL = Object.freeze({+ /** The request named an owner other than the caller's resolved identity. */+ foreignOwner: "foreign-owner",+ /**+ * The server resolved no usable identity, so no requested owner can be+ * shown to be the caller's own. Fail closed: an unverifiable scope is+ * refused rather than trusted.+ */+ unresolvedIdentity: "unresolved-identity",+} as const);++/** Closed union over {@link OWNER_SCOPE_REFUSAL}. */+export type OwnerScopeRefusal = (typeof OWNER_SCOPE_REFUSAL)[keyof typeof OWNER_SCOPE_REFUSAL];++/** Membership list, in the order the checks are made. */+export const OWNER_SCOPE_REFUSALS: ReadonlyArray<OwnerScopeRefusal> = Object.freeze([+ OWNER_SCOPE_REFUSAL.unresolvedIdentity,+ OWNER_SCOPE_REFUSAL.foreignOwner,+]);++/** Narrow a refusal token read back off a wire or a stored envelope. */+export function isOwnerScopeRefusal(value: unknown): value is OwnerScopeRefusal {+ return (+ typeof value === "string" && (OWNER_SCOPE_REFUSALS as ReadonlyArray<string>).includes(value)+ );+}++/** One caller's request to be answered under a named owner scope. */+export interface OwnerScopeRequest {+ /** The argument the scope arrived in, named in the refusal. */+ readonly argument: string;+ /** The owner the caller asked to be answered as, verbatim. */+ readonly requested: string;+ /** The identity this server resolved for the caller, if it has one. */+ readonly identity: string | undefined;+}++/** A refusal, with the sentence that diagnoses it. */+export interface OwnerScopeRefusalOutcome {+ readonly refusal: OwnerScopeRefusal;+ /** Names both owners, the gate, and what would change the answer. */+ readonly message: string;+}++/**+ * Decide whether `request` may be answered on `vault`, or must be+ * refused. `null` means the request stands: the gate is not `fail`, the+ * requested scope is blank (which narrows nothing), or the caller named+ * its own identity.+ *+ * The gate is read FIRST so a vault that never opted in pays neither the+ * config read's cost nor its verdict.+ */+export function refuseOwnerScopeRequest(+ vault: string,+ request: OwnerScopeRequest,+): OwnerScopeRefusalOutcome | null {+ if (loadIntegrityConfigSafe(vault).owner_scope_delivery !== GATE_MODE.fail) return null;++ const requested = normalizeAgentScope(request.requested);+ if (requested === null) return null;++ const resolved = normalizeAgentScope(normalizeAgentArgument(request.identity) ?? undefined);+ if (resolved === null) {+ return Object.freeze({+ refusal: OWNER_SCOPE_REFUSAL.unresolvedIdentity,+ message:+ `${request.argument} refused (${OWNER_SCOPE_REFUSAL.unresolvedIdentity}): ` ++ `${JSON.stringify(request.requested)} cannot be checked because this ` ++ `server resolved no agent identity, so no requested owner can be shown to be the ` ++ `caller's own. ${OWNER_SCOPE_GATE_KEY}=${GATE_MODE.fail} refuses an owner scope it ` ++ `cannot verify. Set ${IDENTITY_SETTINGS}.`,+ });+ }+ if (resolved === requested) return null;++ return Object.freeze({+ refusal: OWNER_SCOPE_REFUSAL.foreignOwner,+ message:+ `${request.argument} refused (${OWNER_SCOPE_REFUSAL.foreignOwner}): ` ++ `${JSON.stringify(request.requested)} names an owner other than the ` ++ `identity this server resolved for the caller, ${JSON.stringify(resolved)}. ` ++ `${OWNER_SCOPE_GATE_KEY}=${GATE_MODE.fail} makes the resolved identity authoritative, so ` ++ `the request is refused rather than answered as ${JSON.stringify(requested)} or narrowed ` ++ `to ${JSON.stringify(resolved)} behind the caller's back.`,+ });+}diff --git a/src/mcp/resources.ts b/src/mcp/resources.tsindex abdee416..36448a83 100644--- a/src/mcp/resources.ts+++ b/src/mcp/resources.ts@@ -31,6 +31,30 @@* - Missing files produce `INTERNAL_ERROR` with a `not found` message* — same shape as `brain_query`'s `BrainNotFoundError` so callers* can treat both surfaces consistently.+ *+ * ## Ownership (a-label-is-not-a-boundary, U3)+ *+ * This surface is `resources/*`, and the isolation matrix's population+ * was `tools/*`. So while every delivery tool learned to ask the+ * ownership rule, `resources/read osb://preference/{id}` still handed+ * back another owner's page in full - frontmatter, `owner:` line and+ * body prose - under the same `integrity.owner_scope_delivery: fail`+ * that made the tool withhold it. A boundary one protocol verb honours+ * and its neighbour ignores is not a boundary.+ *+ * The four templated readers that reach owner-taggable content -+ * `preference/{id}`, `topic/{slug}`, `backlinks/{id}`, `log/{date}` -+ * therefore go through {@link gatedOwnerScopeView}, the same adapter and+ * the same gate the tools use. A withheld artifact is reported with the+ * `not found` message an ABSENT one produces, because a distinguishable+ * refusal would announce the page it is meant to hide.+ *+ * The three whole-vault readers (`preferences/active`, `lessons`,+ * `digest/latest`, `status`) are deliberately NOT filtered here: they+ * serve generated files that are shared by construction and regenerated+ * unscoped (see `brain_context`, which returns a scoped PROJECTION while+ * leaving `Brain/active.md` untouched). Scoping the file itself is a+ * different decision from scoping a delivery, and it is not made here.*/import { existsSync, readFileSync } from "node:fs";@@ -51,12 +75,29 @@ import {validateSlug,} from "../core/brain/paths.ts";import { BrainNotFoundError, queryByPreference, queryByTopic } from "../core/brain/query.ts";+import { gatedOwnerScopeView, type OwnerScopeView } from "../core/brain/owner-scope-view.ts";+import { extractWikilinkRichBodies } from "../core/brain/link-graph/parse-wikilink.ts";import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";+import type { BrainLogEntry } from "../core/brain/log.ts";import type { BrainPreference, BrainRetired } from "../core/brain/types.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";export interface ResourceContext {readonly vault: string;+ /**+ * The identity this server resolved for the caller, threaded from+ * `MCPServer.agentName` exactly as `ServerContext.agentName` is+ * threaded into every tool.+ *+ * `resources/read` carries no arguments beyond the URI, so - like+ * `brain_context` - this surface cannot be TOLD which owner is asking+ * and the server identity is the only scope available. Absent means+ * exactly what it means for a tool: `resolveOwnerScopeDelivery` reads+ * no requested scope, `enforcedScope` is `null`, and nothing is+ * filtered - the same behaviour, from the same resolver, so the two+ * surfaces cannot disagree about what an unidentified caller sees.+ */+ readonly agentName?: string | undefined;}export interface ResourceDescriptor {@@ -161,16 +202,41 @@ export function readResource(ctx: ResourceContext, uri: string): ResourceContentcase "status":return readStatus(ctx, uri);case "preference":- return readPreference(ctx, uri, parsed.id);+ return readPreference(ctx, uri, parsed.id, ownerView(ctx));case "topic":- return readTopic(ctx, uri, parsed.slug);+ return readTopic(ctx, uri, parsed.slug, ownerView(ctx));case "log":- return readLog(ctx, uri, parsed.date);+ return readLog(ctx, uri, parsed.date, ownerView(ctx));case "backlinks":- return readBacklinks(ctx, uri, parsed.id);+ return readBacklinks(ctx, uri, parsed.id, ownerView(ctx));}}+/**+ * The ownership rule bound to this request, built once per read.+ *+ * Constructed at the switch rather than inside each reader so a reader+ * added later cannot be the one that forgot: the four templated cases+ * pass it explicitly and the compiler requires it.+ */+function ownerView(ctx: ResourceContext): OwnerScopeView {+ return gatedOwnerScopeView(ctx.vault, ctx.agentName);+}++/**+ * The error a resource raises for something the caller may not see.+ *+ * Byte-identical to the one a genuinely ABSENT artifact produces+ * (`BrainNotFoundError`, rendered as `INTERNAL_ERROR` above), because a+ * distinguishable refusal is an existence oracle over exactly the+ * population the gate exists to hide - the same convention+ * `preferences-collect.ts` states for counts and `brain_search_expand`+ * already follows for a chunk id.+ */+function notFound(id: string): MCPError {+ return new MCPError(INTERNAL_ERROR, new BrainNotFoundError(id).message);+}+// ----- URI parsing ---------------------------------------------------------type Parsed =@@ -278,7 +344,12 @@ function readStatus(ctx: ResourceContext, uri: string): ResourceContent {};}-function readPreference(ctx: ResourceContext, uri: string, rawId: string): ResourceContent {+function readPreference(+ ctx: ResourceContext,+ uri: string,+ rawId: string,+ view: OwnerScopeView,+): ResourceContent {if (!rawId.trim()) {throw new MCPError(INVALID_PARAMS, `resource id must not be empty: ${uri}`);}@@ -320,31 +391,75 @@ function readPreference(ctx: ResourceContext, uri: string, rawId: string): Resouconst filePath = resolvedId.startsWith("pref-")? preferencePath(ctx.vault, resolvedSlug): retiredPath(ctx.vault, resolvedSlug);+ // The whole file, `owner:` line and body prose included, is what this+ // reader hands back - so the ownership question is asked before the+ // read, not filtered out of the bytes afterwards.+ if (!view.visible(resolvedId)) throw notFound(rawId);return readMarkdown(uri, filePath);}-function readTopic(ctx: ResourceContext, uri: string, rawSlug: string): ResourceContent {+function readTopic(+ ctx: ResourceContext,+ uri: string,+ rawSlug: string,+ view: OwnerScopeView,+): ResourceContent {if (!rawSlug.trim()) {throw new MCPError(INVALID_PARAMS, `topic slug must not be empty: ${uri}`);}validateSlug(rawSlug);let result;try {- result = queryByTopic(ctx.vault, rawSlug);+ // The scope reaches the SELECTION, not the result: a topic resolves+ // to one preference and several may carry it, so filtering afterwards+ // would report the topic as having no rule whenever another owner's+ // preference happened to sort first.+ result = queryByTopic(ctx.vault, rawSlug, { ownerScope: view.scope });} catch (err) {if (err instanceof BrainNotFoundError) {throw new MCPError(INTERNAL_ERROR, err.message);}throw err;}+ // The two remaining owner-bearing streams, filtered before the+ // renderer sees them: each signal row names its id and its author, and+ // the log rows are the same events `brain_event_trace` filters. A+ // topic whose ONLY rule is one this caller may not see is reported as+ // a topic with no rule, not as a topic that refused - the renderer+ // already has that shape for a topic that never reached promotion.+ const scoped = Object.freeze({+ ...result,+ signals: view.keep(result.signals, (s) => [s.id]),+ all_log_events: view.keep(result.all_log_events, (e) => logEventRefs(e)),+ });return {uri,mimeType: MIME_MARKDOWN,- text: renderTopicMarkdown(rawSlug, result),+ text: renderTopicMarkdown(rawSlug, scoped),};}-function readLog(ctx: ResourceContext, uri: string, rawDate: string): ResourceContent {+/**+ * Every artifact one log entry would name, as the owner-scope view+ * spells references.+ *+ * A log body is an untyped payload record; the fields that carry an+ * artifact are the wikilink-shaped ones, and the view unbrackets them+ * itself. `path` is the vault-relative page the event was about.+ */+function logEventRefs(entry: BrainLogEntry): ReadonlyArray<string | undefined> {+ const body = (entry.body ?? {}) as Record<string, unknown>;+ const field = (key: string): string | undefined =>+ typeof body[key] === "string" ? (body[key] as string) : undefined;+ return [field("path"), field("preference"), field("signal"), field("artifact")];+}++function readLog(+ ctx: ResourceContext,+ uri: string,+ rawDate: string,+ view: OwnerScopeView,+): ResourceContent {validateIsoDate(rawDate);// Per-device shards (Memory Integrity Suite): a day's human view can// span several markdown files. The legacy single file is returned@@ -354,20 +469,77 @@ function readLog(ctx: ResourceContext, uri: string, rawDate: string): ResourceCoif (files.length === 0) {throw new MCPError(INTERNAL_ERROR, `no log file for date '${rawDate}'`);}- if (files.length === 1) return readMarkdown(uri, files[0]!.path);- const text = files.map((f) => readFileSync(f.path, "utf8").trimEnd()).join("\n\n");- return { uri, mimeType: MIME_MARKDOWN, text };+ const shard = (f: { path: string }): string =>+ withVisibleLogEvents(readFileSync(f.path, "utf8"), view);+ // The single-shard read stays verbatim (trailing newline included), so+ // a vault with the gate off is byte-identical to the pre-filter shape.+ if (files.length === 1) return { uri, mimeType: MIME_MARKDOWN, text: shard(files[0]!) };+ return { uri, mimeType: MIME_MARKDOWN, text: files.map((f) => shard(f).trimEnd()).join("\n\n") };+}++/** Start of one rendered log event: `## <time> — <kind>`. */+const LOG_EVENT_HEADING = "\n## ";++/**+ * Drop the rendered log events naming an artifact this caller may not+ * see, keeping the shard's frontmatter and day heading.+ *+ * A shard is shared by construction - it is named by date and carries no+ * `owner:`, which is why `owner-scope-view.ts` leaves `Brain/log/` out+ * of its id-resolution directories. Its CONTENTS are not: every+ * `apply-evidence`, `promote` and `retire` event names the preference it+ * was about, by id and by vault-relative path, and `brain_event_trace`+ * already filters exactly those rows. Serving the same events as raw+ * markdown was the tool's boundary re-opened one protocol verb along.+ *+ * The split is structural - the `## ` heading the log renderer emits per+ * event, and the wikilink / `.md` path tokens inside the section - not a+ * match on any event's prose.+ */+function withVisibleLogEvents(markdown: string, view: OwnerScopeView): string {+ if (view.scope === null) return markdown;+ const parts = markdown.split(LOG_EVENT_HEADING);+ const head = parts[0]!;+ const kept = parts+ .slice(1)+ .filter((section) => view.row(...logSectionRefs(section)))+ .map((section) => LOG_EVENT_HEADING + section);+ return head + kept.join("");+}++/** Every artifact one rendered log section names, id- or path-shaped. */+function logSectionRefs(section: string): ReadonlyArray<string> {+ const refs = [...extractWikilinkRichBodies(section)];+ for (const token of section.split(/\s+/)) {+ if (token.endsWith(".md")) refs.push(token);+ }+ return refs;}-function readBacklinks(ctx: ResourceContext, uri: string, rawId: string): ResourceContent {+function readBacklinks(+ ctx: ResourceContext,+ uri: string,+ rawId: string,+ view: OwnerScopeView,+): ResourceContent {if (!rawId.trim()) {throw new MCPError(INVALID_PARAMS, `backlinks target must not be empty: ${uri}`);}// Normalise to the same form the index keys use so `[[pref-foo]]`,// `pref-foo`, and `Brain/preferences/pref-foo.md` all resolve.const target = normaliseWikilinkTarget(rawId);- const index = buildBacklinkIndex(ctx.vault);- const refs = index.get(target) ?? [];+ // The last unscoped `buildBacklinkIndex` call in the product. Every+ // ref it yields names its SOURCE artifact by id, so an unscoped index+ // here published the same list `brain_backlinks` had already learned+ // to withhold.+ //+ // A hidden TARGET answers exactly as an ABSENT one does - the empty+ // backlink document - rather than refusing: this reader has no+ // not-found path at all (an unknown target is a legitimate zero), so a+ // refusal here would be the one response shape that proves the page+ // exists. The echoed target is the caller's own argument.+ const index = buildBacklinkIndex(ctx.vault, view.scope);+ const refs = view.visible(target) ? (index.get(target) ?? []) : [];return {uri,mimeType: MIME_MARKDOWN,diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex 407c3489..30b326c5 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -52,8 +52,12 @@ import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";import type { ServerContext, ToolDefinition } from "./tool-contract.ts";import {AGENT_SCOPE_SCHEMA,+ MATCH_QUALITY_ARG_NAME,+ MATCH_QUALITY_SCHEMA,+ RECALL_SCORES_SCHEMA,coerceAgentScope,coerceBoolOptional,+ coerceRecallAdequacyInput,coerceStr,coerceStringOptional,} from "./coerce.ts";@@ -513,6 +517,22 @@ const SEARCH_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {},};+/** The argument name the scores are paired with, as the schema spells it. */+const RECALL_SCORES_ARG_NAME = "scores";++/**+ * "Both or neither", said in the schema rather than only in the refusal.+ *+ * `coerceRecallAdequacyInput` answers an incomplete pair with+ * INVALID_PARAMS, and until this keyword landed the pairing appeared in no+ * `required` array anywhere, so the only way a client could discover it was+ * to make the call the server refuses.+ */+const RECALL_ADEQUACY_PAIRING = Object.freeze({+ [RECALL_SCORES_ARG_NAME]: Object.freeze([MATCH_QUALITY_ARG_NAME]),+ [MATCH_QUALITY_ARG_NAME]: Object.freeze([RECALL_SCORES_ARG_NAME]),+});+const RECALL_GATE_INPUT_SCHEMA: Record<string, unknown> = {type: "object",properties: {@@ -543,15 +563,18 @@ const RECALL_GATE_INPUT_SCHEMA: Record<string, unknown> = {maxLength: 512,description: "Optional session correlation id recorded on the telemetry record.",},- scores: {- type: "array",- maxItems: 200,- items: { type: "number" },- description:- "Optional top-k recall scores. Adds an adequacy verdict: sufficient/proceed, weak/re_recall, insufficient/abstain. An empty array adds the negative verdict.",- },+ scores: RECALL_SCORES_SCHEMA,+ match_quality: MATCH_QUALITY_SCHEMA,},required: ["prompt"],+ // `scores` and `match_quality` stand or fall together, and neither can+ // sit in `required` - both are optional on their own. `dependentRequired`+ // is the one keyword that states "both or neither" declaratively, so a+ // schema-driven client can discover the pairing instead of learning it+ // from an INVALID_PARAMS at call time. A client on a draft that predates+ // the keyword ignores it, which is why the two property descriptions and+ // the tool description say it in prose as well.+ dependentRequired: RECALL_ADEQUACY_PAIRING,additionalProperties: false,};@@ -593,6 +616,11 @@ const RECALL_GATE_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {"result_count","top_score","mean_score",+ // Required, not optional: the block used to return the two scores+ // that decide NOTHING and withhold the one that decides the level,+ // so a caller could not check the verdict against its own input or+ // tell which threshold band it landed beside.+ MATCH_QUALITY_ARG_NAME,"reason",],properties: {@@ -602,6 +630,7 @@ const RECALL_GATE_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {result_count: { type: "integer" },top_score: { type: "number" },mean_score: { type: "number" },+ [MATCH_QUALITY_ARG_NAME]: { type: "number" },reason: { type: "string" },},},@@ -878,7 +907,7 @@ async function toolBrainSearch(const properties = parsePropertiesArgument(args["properties"]);const degreeFilters = parseDegreeArgument(args["degree"]);const visibility = parseVisibilityArgument(args["visibility"]);- const agentScope = coerceStringOptional(args, "agent_scope", 128);+ const agentScope = coerceAgentScope(ctx, args, false);const sessionScope = coerceStringOptional(args, "session_scope", 128);const projectScope = coerceStringOptional(args, "project_scope", 128);const scope =@@ -1147,13 +1176,13 @@ async function toolBrainRecallGate(...(sessionId !== undefined ? { sessionId } : {}),});});- // Adequacy verdict (t_b8f66fec): thin verdict + action layer over the- // relevance scores of a recall attempt. Only computed when the caller- // passes `scores`, keeping the pure structural-gate contract otherwise.- const scores = parseRecallScores(args["scores"]);- if (scores === undefined) return { ...decision };+ // Adequacy verdict (t_b8f66fec): thin verdict + action layer over one+ // recall attempt. Only computed when the caller passes the pair,+ // keeping the pure structural-gate contract otherwise.+ const attempt = coerceRecallAdequacyInput("brain_recall_gate", args, "scores");+ if (attempt === undefined) return { ...decision };const thresholds = resolveRecallAdequacyThresholds(ctx.configPath ?? undefined);- const verdict = assessRecallAdequacy(scores, thresholds);+ const verdict = assessRecallAdequacy(attempt, thresholds);// signals-that-survive, unit 6: an unmet verdict is stamped onto the// cross-query demand log under the bucket key normalizeQueryTerms already// computes, so the knowledge-gap loop can aggregate recurrence without a@@ -1192,6 +1221,10 @@ async function toolBrainRecallGate(result_count: verdict.resultCount,top_score: verdict.topScore,mean_score: verdict.meanScore,+ // The quantity the level was decided by. Returning only the two+ // descriptive scores left the caller unable to reconstruct the+ // verdict from its own inputs.+ [MATCH_QUALITY_ARG_NAME]: verdict.matchQuality,reason: verdict.reason,},// Absent, never null, when the attempt had usable results - the@@ -1220,28 +1253,6 @@ async function assessNegativeRecall(ctx: ServerContext): Promise<NegativeRecallV);}-/**- * Parse the optional `scores` argument for the recall gate. Returns- * `undefined` when absent (verdict skipped) and throws INVALID_PARAMS on- * a malformed shape so callers get a clear error rather than a silently- * dropped verdict. An empty array is a valid "no results" signal.- */-function parseRecallScores(raw: unknown): ReadonlyArray<number> | undefined {- if (raw === undefined || raw === null) return undefined;- if (!Array.isArray(raw)) {- throw new MCPError(INVALID_PARAMS, "argument 'scores' must be an array of numbers");- }- if (raw.length > 200) {- throw new MCPError(INVALID_PARAMS, "argument 'scores' must not exceed 200 items");- }- for (const item of raw) {- if (typeof item !== "number") {- throw new MCPError(INVALID_PARAMS, "argument 'scores' must contain only numbers");- }- }- return raw as ReadonlyArray<number>;-}-const RECALL_FEEDBACK_INPUT_SCHEMA: Record<string, unknown> = {type: "object",properties: {@@ -1739,7 +1750,7 @@ export const SEARCH_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_recall_gate",description:- "Classify whether an automatic recall/surfacing attempt should run. Diagnostics only; does not search. Pass `scores` (a recall attempt's top-k relevance scores) to also get an adequacy verdict — sufficient (proceed) / weak (re_recall) / insufficient (abstain + escalate).",+ "Classify whether an automatic recall attempt should run. Diagnostics only; does not search. Pass `scores` AND `match_quality` TOGETHER for an adequacy verdict — sufficient/proceed, weak/re_recall, insufficient/abstain; either alone is INVALID_PARAMS (see `dependentRequired`).",inputSchema: RECALL_GATE_INPUT_SCHEMA,outputSchema: RECALL_GATE_OUTPUT_SCHEMA,handler: toolBrainRecallGate,diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex dbfa6af7..e639408b 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -345,7 +345,7 @@ export class MCPServer {if (typeof uri !== "string") {throw new MCPError(INVALID_PARAMS, "resources/read requires a string `uri`");}- const content = readResource({ vault: this.vault }, uri);+ const content = readResource({ vault: this.vault, agentName: this.context.agentName }, uri);return { contents: [content] };}diff --git a/src/mcp/tool-contract.ts b/src/mcp/tool-contract.tsindex 76da8032..2412a408 100644--- a/src/mcp/tool-contract.ts+++ b/src/mcp/tool-contract.ts@@ -16,7 +16,38 @@ import type { OutputSchema } from "./output-contract.ts";import type { ArtifactStore } from "./artifact-store.ts";import type { ProgressSink } from "../core/brain/progress.ts";-export type ToolScope = "full" | "writer" | "catalog";+/**+ * The tool surfaces a server process can advertise.+ *+ * A closed vocabulary rather than a bare union because the members were+ * hand-copied into four places - the union, the `second_brain_capabilities`+ * output schema, the `--scope` validity check and the `--scope` error+ * message - with nothing asserting the four agreed. Every one of those+ * sites now derives from this object.+ */+export const TOOL_SCOPE = Object.freeze({+ /** Every tool advertised. */+ full: "full",+ /** The always-loaded Brain writer/reader set, and nothing else. */+ writer: "writer",+ /** Two-pass catalog: a compact advertised set, everything still callable. */+ catalog: "catalog",+} as const);++/** Closed union over {@link TOOL_SCOPE}. */+export type ToolScope = (typeof TOOL_SCOPE)[keyof typeof TOOL_SCOPE];++/** Membership list, in widest-surface-first order. */+export const TOOL_SCOPES: ReadonlyArray<ToolScope> = Object.freeze([+ TOOL_SCOPE.full,+ TOOL_SCOPE.writer,+ TOOL_SCOPE.catalog,+]);++/** Narrow a scope name arriving from argv, a config file or a profile. */+export function isToolScope(value: unknown): value is ToolScope {+ return typeof value === "string" && (TOOL_SCOPES as ReadonlyArray<string>).includes(value);+}export interface ToolCapabilityEntry {readonly name: string;diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 5ec79b8b..11b93a71 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -21,12 +21,7 @@* only assembles them in a stable order and applies scope filtering.*/-import {- ConfigReadError,- discoverConfig,- resolveExposeHostPaths,- vaultStoreReference,-} from "../core/config.ts";+import { ConfigReadError, discoverConfig } from "../core/config.ts";import { redactConfigMapping } from "../core/egress/guard.ts";import type { ConfigDiscovery } from "../core/types.ts";import { REMOVED_TOOLS } from "../core/removed-surfaces.ts";@@ -52,11 +47,14 @@ import { AGENT_SCOPE_SCHEMA, coerceAgentScope, coerceStr, coerceInt } from "./coimport type { OutputSchema } from "./output-contract.ts";import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";import { CAPABILITY_DIAGNOSTIC_TOOL } from "./capabilities.ts";-import type {- ServerContext,- ToolCapabilityReport,- ToolDefinition,- ToolScope,+import { unresolvedField, vaultPathField } from "./vault-path-field.ts";+import {+ TOOL_SCOPE,+ TOOL_SCOPES,+ type ServerContext,+ type ToolCapabilityReport,+ type ToolDefinition,+ type ToolScope,} from "./tool-contract.ts";// PLACEHOLDER_AGENT_VALUES + normalizeAgentArgument live in@@ -79,44 +77,12 @@ function vaultRelpath(target: string, vault: string): string {}}-/**- * A field whose value could not be resolved, carrying the reason. Same- * shape `toolStatus` already degrades the `vault` block to when the vault- * scope cannot be resolved, and `buildSearchStatusBlock` its own: the- * failure is a value the consumer reads, never a key it has to notice is- * missing.- */--function unresolved(err: Error): UnresolvedField {- return { error: err.message };-}--/**- * The `vault_path` field for an MCP response. By default this is the- * opaque, stable store reference (`vault://<hex>`) rather than the- * absolute host path, since MCP responses land in model context. The- * `expose_host_paths` config escape hatch restores the raw path for- * operators whose tooling depends on it (D2).- *- * Both branches read the device-local config - the escape hatch is a- * config flag and the reference is keyed by a config-held secret - so an- * unreadable config leaves this field, and ONLY this field, unresolvable.- * It reports the reason rather than raising, because raising here took- * down whole diagnostic payloads on their very last field. Degrading to- * the raw host path instead would breach the redaction contract this- * function exists to enforce, so there is no value to fall back to.- */-function vaultPathField(ctx: ServerContext): string | UnresolvedField {- const configPath = ctx.configPath ?? undefined;- try {- return resolveExposeHostPaths(configPath)- ? ctx.vault- : vaultStoreReference(ctx.vault, configPath);- } catch (err) {- if (err instanceof ConfigReadError) return unresolved(err);- throw err;- }-}+// The `vault_path` field and its unresolved-value shape live in+// `./vault-path-field.ts`: every module that emits the field has to be+// able to reach the one function that enforces its contract, and this+// aggregator imports those modules, so it cannot be the one that holds+// it. `unresolvedField` comes back from there too, so the degraded-value+// shape has one definition as well.// ── Tool implementations ────────────────────────────────────────────────────@@ -156,7 +122,8 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>// did, which is precisely what the probe could not determine. The absent// branch keeps omitting them, because there the omission IS the answer.const { present: vaultExists, unexaminable } = probeVaultDirectory(ctx.vault);- const configKeys = broken === null ? Object.keys(discovery.data).toSorted() : unresolved(broken);+ const configKeys =+ broken === null ? Object.keys(discovery.data).toSorted() : unresolvedField(broken);// Safe to call on a vault that has no Brain layer yet — returns// `present: false` with zero counts.const brain = vaultExists ? computeBrainStatus(ctx.vault) : unexaminable;@@ -204,7 +171,7 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>config_path: String(discovery.path),config_exists: discovery.exists,config_keys: configKeys,- config: broken === null ? redactConfigMapping(discovery.data) : unresolved(broken),+ config: broken === null ? redactConfigMapping(discovery.data) : unresolvedField(broken),vault_path: vaultPathField(ctx),// `boolean | { error }`. Both answerable cases keep their exact literal// - `true` when the directory is there, `false` when it is genuinely@@ -375,7 +342,7 @@ const CAPABILITIES_OUTPUT_SCHEMA: OutputSchema = {"withheld",],properties: {- scope: { type: "string", enum: ["full", "writer", "catalog"] },+ scope: { type: "string", enum: TOOL_SCOPES },server_name: { type: "string" },static_tool_count: { type: "integer" },available_tool_count: { type: "integer" },@@ -435,7 +402,7 @@ const CATALOG_ADVERTISED_NAMES: ReadonlySet<string> = new Set([TOOL_HYDRATE_NAME,]);-export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {+export function buildToolTable(scope: ToolScope = TOOL_SCOPE.full): ToolDefinition[] {const all: ToolDefinition[] = [{name: CAPABILITY_DIAGNOSTIC_TOOL,@@ -531,12 +498,12 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {...WATCHDOG_TOOLS,...SKILL_TOOLS,];- if (scope === "writer") return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));+ if (scope === TOOL_SCOPE.writer) return all.filter((t) => WRITER_TOOL_NAMES.has(t.name));// The hydrate tool closes over the finished table (itself included)// so its catalog and schema lookups always reflect this process's// real surface.all.push(buildHydrateTool(() => all));- if (scope === "full") return all;+ if (scope === TOOL_SCOPE.full) return all;// Catalog scope: the compact first-pass set stays advertised; every// other tool keeps `hidden` semantics - callable, not listed.return all.map((t) =>diff --git a/src/mcp/vault-path-field.ts b/src/mcp/vault-path-field.tsnew file mode 100644index 00000000..eb21d18e--- /dev/null+++ b/src/mcp/vault-path-field.ts@@ -0,0 +1,92 @@+/**+ * The `vault_path` field an MCP tool response carries.+ *+ * By default this is the opaque, stable store reference+ * (`vault://<hex>`) rather than the absolute host path, since MCP+ * responses land in model context. The `expose_host_paths` config escape+ * hatch restores the raw path for operators whose tooling depends on it+ * (D2).+ *+ * Both branches read the device-local config - the escape hatch is a+ * config flag and the reference is keyed by a config-held secret - so an+ * unreadable config leaves this field, and ONLY this field, unresolvable.+ * It reports the reason rather than raising, because raising here took+ * down whole diagnostic payloads on their very last field. Degrading to+ * the raw host path instead would breach the redaction contract this+ * function exists to enforce, so there is no value to fall back to.+ *+ * ## Why it is a module of its own+ *+ * It used to be a private function inside `./tools.ts`, where the ten+ * Brain domain modules that emit the same field could not reach it -+ * `tools.ts` imports them, so importing it back would close the cycle+ * `tests/core/architecture/import-cycles.test.ts` gates. So they emitted+ * `ctx.vault` instead, and the contract above was honoured at three+ * sites of forty-four. A contract with one implementation needs that+ * implementation to be reachable from every site it governs; this leaf+ * imports nothing from the tool surface, so it is.+ *+ * `tests/core/architecture/vault-path-census.test.ts` is what keeps the+ * next site from finding its own way to say `ctx.vault`.+ */++import { ConfigReadError, resolveExposeHostPaths, vaultStoreReference } from "../core/config.ts";+import type { UnresolvedField } from "../core/vault-presence.ts";+import type { OutputSchema } from "./output-contract.ts";++/**+ * A field whose value could not be resolved, carrying the reason. Same+ * shape `toolStatus` already degrades the `vault` block to when the vault+ * scope cannot be resolved, and `buildSearchStatusBlock` its own: the+ * failure is a value the consumer reads, never a key it has to notice is+ * missing.+ */+export function unresolvedField(err: Error): UnresolvedField {+ return { error: err.message };+}++/**+ * How a declared `outputSchema` describes the field.+ *+ * The value is `string | { error: string }` and the output-contract+ * descriptor language (`src/core/brain/response-shape.ts`) has no union+ * form - no `oneOf`, no `anyOf`. Two schemas used to say `type:+ * "string"`, which was true of what they emitted (the raw host path) and+ * false of what this function returns: on an unreadable config the+ * server's `assertOutputContract` would reject the degraded value and+ * destroy the whole payload, on precisely the condition the degraded+ * value exists to report.+ *+ * So the descriptor widens to the honest form the same schemas already+ * use for a field they cannot narrow (`generated_at: {}`), and it is+ * named ONCE here rather than spelled twice, so the two schemas cannot+ * drift from each other or from the producer above.+ */+export const VAULT_PATH_OUTPUT_SCHEMA: OutputSchema = Object.freeze({});++/**+ * The two fields this producer reads, and nothing else.+ *+ * Declared structurally rather than as {@link ServerContext} so the+ * OpenClaw plugin - a second runtime with its own context shape, and+ * three emissions of this same field - can reach it. A contract honoured+ * on one runtime and not the other is the defect this module exists to+ * close, one surface over.+ */+export interface VaultPathSource {+ readonly vault: string;+ readonly configPath?: string | null;+}++/** The contract above, as the one value every emitting site returns. */+export function vaultPathField(ctx: VaultPathSource): string | UnresolvedField {+ const configPath = ctx.configPath ?? undefined;+ try {+ return resolveExposeHostPaths(configPath)+ ? ctx.vault+ : vaultStoreReference(ctx.vault, configPath);+ } catch (err) {+ if (err instanceof ConfigReadError) return unresolvedField(err);+ throw err;+ }+}diff --git a/src/openclaw/index.ts b/src/openclaw/index.tsindex 996a3f0d..90ccf927 100644--- a/src/openclaw/index.ts+++ b/src/openclaw/index.ts@@ -20,6 +20,7 @@ import { listVaultPages } from "../core/vault.ts";import { ENTITY_STATUS_SCOPE, vaultPageInStatusScope } from "../core/brain/entities/page-scope.ts";import { deriveRuntimeAgentName, normalizeAgentArgument } from "../core/agent-identity.ts";import { vaultRelative as vaultRelativePath } from "../core/path-safety.ts";+import { vaultPathField } from "../mcp/vault-path-field.ts";interface PluginConfig {vault?: string;@@ -79,7 +80,7 @@ export default definePluginEntry({config_exists: discovery.exists,config_keys: Object.keys(discovery.data).toSorted(),config: redactConfigMapping(discovery.data),- vault_path: vault,+ vault_path: vaultPathField({ vault }),vault_exists: presence.unexaminable ?? presence.present,};return {@@ -139,7 +140,7 @@ export default definePluginEntry({}));const result = {- vault_path: vault,+ vault_path: vaultPathField({ vault }),total_pages: pages.length,returned: matched.length,limit,@@ -174,7 +175,7 @@ export default definePluginEntry({const repoRoot = (params["repo"] as string | undefined) ?? null;const results = doctor({ vault, repoRoot });const result = {- vault_path: vault,+ vault_path: vaultPathField({ vault }),ok: results.every((r) => r.ok),checks: results.map((r) => ({name: r.name,diff --git a/tests/cli/brain-backlinks-reporting.test.ts b/tests/cli/brain-backlinks-reporting.test.tsnew file mode 100644index 00000000..95b9b9f8--- /dev/null+++ b/tests/cli/brain-backlinks-reporting.test.ts@@ -0,0 +1,121 @@+/**+ * `o2b brain backlinks` reports what it could not read+ * (a-label-is-not-a-boundary review, C7).+ *+ * `buildBacklinkIndex` stopped swallowing parse failures and started+ * carrying them on the returned index; `brain_backlinks` renders them.+ * This verb - the surface an operator debugging a legacy vault reaches+ * FIRST, before any MCP client is involved - kept printing `Backlinks to+ * <id>: 0` and nothing else, which is the same confident zero the core+ * change removed, one layer up.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";+import { brainDirs } from "../../src/core/brain/paths.ts";++let tmp: string;+let vault: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-backlinks-cli-"));+ vault = join(tmp, "vault");+ config = join(tmp, "config.yaml");+});+afterEach(() => rmSync(tmp, { recursive: true, force: true }));++const env = (): Record<string, string> => ({ OPEN_SECOND_BRAIN_CONFIG: config });++async function bootstrap(): Promise<void> {+ const init = await runCli(["init", "--vault", vault, "--name", "TestBacklinks"], { env: env() });+ expect(init.returncode).toBe(0);+ const brainInit = await runCli(["brain", "init", "--vault", vault], { env: env() });+ expect(brainInit.returncode).toBe(0);+}++/**+ * A preference whose frontmatter the collector cannot read, holding a+ * reference to the target. The legacy shape: Group C derived keys written+ * WITHOUT the `_` prefix, which `normalizeDerivedKeys` refuses - the exact+ * vault the swallowed `catch { continue }` used to hide.+ */+function seedUnreadableReferrer(slug: string, target: string): void {+ writeFileSync(+ join(brainDirs(vault).preferences, `pref-${slug}.md`),+ [+ "---",+ "kind: brain-preference",+ "id: `pref-" + slug + "`",+ "status: confirmed",+ "_status: confirmed",+ "topic: legacy",+ `evidenced_by: ["[[${target}]]"]`,+ "---",+ "",+ `## Principle`,+ "",+ `see [[${target}]]`,+ "",+ ].join("\n"),+ );+}++describe("brain backlinks does not report an unmeasured zero", () => {+ test("an unparseable referrer is named on the human surface", async () => {+ await bootstrap();+ seedUnreadableReferrer("legacy-rule", "pref-target");++ const r = await runCli(["brain", "backlinks", "--vault", vault, "pref-target"], {+ env: env(),+ });++ expect(r.returncode).toBe(0);+ // The count is still printed - it is what the caller asked for…+ expect(r.stdout).toContain("Backlinks to pref-target: 0");+ // …but it no longer stands alone. The artifact and the reason travel+ // with it, in the same vocabulary `brain_backlinks` uses.+ expect(r.stderr).toContain("pref-legacy-rule");+ expect(r.stderr).toContain("incomplete");+ // No host path in the reason: `buildBacklinkIndex` strips it, and this+ // verb must not put one back.+ expect(r.stderr).not.toContain(vault);+ });++ test("--json carries the same failures under the MCP tool's key", async () => {+ await bootstrap();+ seedUnreadableReferrer("legacy-rule", "pref-target");++ const r = await runCli(["brain", "backlinks", "--vault", vault, "--json", "pref-target"], {+ env: env(),+ });++ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ count: number;+ unparsed?: ReadonlyArray<{ source: string; sourceKind: string; reason: string }>;+ };+ expect(payload.count).toBe(0);+ expect(payload.unparsed?.map((u) => u.source)).toEqual(["pref-legacy-rule"]);+ expect(payload.unparsed?.[0]?.sourceKind).toBe("preference");+ });++ test("a healthy vault's output is unchanged - no key, no note", async () => {+ await bootstrap();++ const r = await runCli(["brain", "backlinks", "--vault", vault, "--json", "pref-target"], {+ env: env(),+ });++ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;+ // Absent, never an empty array: an empty list would make every caller+ // branch on a state that cannot happen on a healthy vault.+ expect("unparsed" in payload).toBe(false);+ expect(r.stderr).not.toContain("incomplete");+ });+});diff --git a/tests/cli/brain-explorer.test.ts b/tests/cli/brain-explorer.test.tsindex 3a5d4260..3ddb2f6b 100644--- a/tests/cli/brain-explorer.test.ts+++ b/tests/cli/brain-explorer.test.ts@@ -12,8 +12,16 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { writePreference } from "../../src/core/brain/preference.ts";+import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";import { runCli } from "../helpers/run-cli.ts";+/**+ * A vendor-prefixed credential shape, synthesised for this test. Caught by+ * shape rather than by a word list, which is why an obviously fake body is+ * enough to prove the boundary runs.+ */+const FAKE_VENDOR_TOKEN = "sk-live-FAKEEXAMPLE0000111122223333";+let tmp: string;let vault: string;let config: string;@@ -93,6 +101,55 @@ describe("o2b brain explorer --export", () => {expect(parsed.nodes[0].id).toBe("pref-explorer-seed");});+ test("the exported graph goes through the shared egress guard", async () => {+ // The eighth egress site. Every other export path scans its bytes;+ // this one wrote the preference graph - principles verbatim - to an+ // operator-named path with no scan at all.+ await bootstrap();+ writePreference(vault, {+ slug: "secret-leak",+ topic: "secret-leak",+ principle: `Always deploy with OPENAI_API_KEY=${FAKE_VENDOR_TOKEN} set`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: "confirmed",+ evidenced_by: ["[[sig-2026-05-01-secret-leak]]"],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-02T00:00:00Z",+ confidence: "high",+ confidence_value: 0.8,+ pinned: false,+ });+ const out = join(tmp, "brain.html");+ const r = await runCli(["brain", "explorer", "--vault", vault, "--export", out], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ const body = readFileSync(out, "utf8");+ expect(body).not.toContain(FAKE_VENDOR_TOKEN);+ expect(body).toContain(REDACTION_PLACEHOLDER);+ // stdout stays the parseable line it was; the notice goes to stderr.+ expect(r.stdout).toContain("exported");+ expect(r.stderr).toContain("no longer matches the vault byte for byte");+ });++ test("a preference that cannot be parsed refuses the export by name", async () => {+ // An export that omits a rule reads identically to a vault that never+ // had it, so the graph is not written at all.+ await bootstrap();+ seedOnePref();+ writeFileSync(join(vault, "Brain", "preferences", "pref-broken.md"), "no frontmatter here\n");+ const out = join(tmp, "brain.html");+ const r = await runCli(["brain", "explorer", "--vault", vault, "--export", out], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("pref-broken.md");+ expect(existsSync(out)).toBe(false);+ });+test("refuses to overwrite without --force", async () => {await bootstrap();seedOnePref();diff --git a/tests/cli/brain-export.test.ts b/tests/cli/brain-export.test.tsindex 1ef8606d..7fa086b5 100644--- a/tests/cli/brain-export.test.ts+++ b/tests/cli/brain-export.test.ts@@ -96,6 +96,21 @@ describe("brain export", () => {expect(payload.preferences.map((p) => p.id).toSorted()).toEqual(["pref-alpha", "pref-beta"]);});+ test("a preference that cannot be parsed refuses the export by name", async () => {+ // An export that omits a rule reads identically to a vault that never+ // had it, so a row that cannot be read stops the whole export rather+ // than shrinking the list under a success exit.+ await bootstrap();+ await seedPreference("alpha");+ writeFileSync(join(vault, "Brain", "preferences", "pref-broken.md"), "no frontmatter here\n");+ const r = await runCli(["brain", "export", "--vault", vault, "--format", "json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(1);+ expect(r.stderr).toContain("pref-broken.md");+ expect(r.stdout).toBe("");+ });+test("--format llms-txt emits H1 + section + bullet", async () => {await bootstrap();await seedPreference("alpha");diff --git a/tests/cli/cli-json-contract.test.ts b/tests/cli/cli-json-contract.test.tsindex 9693512c..b5e767a7 100644--- a/tests/cli/cli-json-contract.test.ts+++ b/tests/cli/cli-json-contract.test.ts@@ -5,9 +5,14 @@ import { join } from "node:path";import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";import { runCli } from "../helpers/run-cli.ts";+import { redactSecrets } from "../../src/cli/json-helpers.ts";+import { redactRawOutput } from "../../src/core/redactor.ts";setDefaultTimeout(CLI_SPAWN_BUDGET_MS);+/** A signal id: the shape every `_evidenced_by` wikilink points through. */+const SIGNAL_ID = "sig-2026-08-16-secret-leak";+let tempDir: string;let vault: string;let configPath: string;@@ -84,4 +89,35 @@ describe("inherited CLI --json contract", () => {expect(serialized).not.toContain("super-secret-value");expect(serialized).toContain("[REDACTED]");});++ test("the envelope hands a signal id back verbatim", async () => {+ // The knock-on of the egress guard's signal-id carve-out, pinned on+ // the OTHER redactor. `redactSecrets` here is assignment-shaped only -+ // it has no high-entropy pass at all - so this envelope never ate a+ // `sig-<date>-<slug>`, while the shared redactor behind+ // `redactForEgress` did. The two surfaces now agree, and that+ // agreement is what this asserts: the same identifier survives both,+ // so an operator cannot get one answer from a bundle and a different+ // one from `--json`.+ const nested = join(tempDir, SIGNAL_ID, "vault");+ const result = await runCli(["init", "--vault", nested, "--json"], { env: env() });++ expect(result.returncode).toBe(0);+ const parsed = JSON.parse(result.stdout) as { stdout: string };+ expect(parsed.stdout).toContain(SIGNAL_ID);+ expect(JSON.stringify(parsed)).not.toContain("[REDACTED]");+ // And the shared egress redactor, which is the one that used to+ // rewrite it, leaves the same string alone.+ expect(redactRawOutput(`_evidenced_by: [[${SIGNAL_ID}]]`, { redactTokens: true })).toBe(+ `_evidenced_by: [[${SIGNAL_ID}]]`,+ );+ });++ test("redactSecrets still replaces an assignment wearing a signal id", () => {+ // The complement: the carve-out is about a BARE identifier, so a+ // credential assigned under a secret-shaped key is still replaced+ // whatever its value looks like.+ const redacted = redactSecrets({ note: `token=${SIGNAL_ID}` }) as { note: string };+ expect(redacted.note).toBe("token=[REDACTED]");+ });});diff --git a/tests/cli/export-identifier-integrity.test.ts b/tests/cli/export-identifier-integrity.test.tsindex 467ce433..feb41df1 100644--- a/tests/cli/export-identifier-integrity.test.ts+++ b/tests/cli/export-identifier-integrity.test.ts@@ -52,6 +52,8 @@ const DIGEST = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90const UUID = "f6f02ff9-6785-4ac9-8e4c-95f95be29cb5";/** 25 mixed characters that are NOT a content address: the old false positive. */const BUILD_ID = "release2024buildXYZabcdef";+/** A signal id: 26 characters of the shape every OSB provenance link uses. */+const SIGNAL_ID = "sig-2026-08-16-secret-leak";let tmp: string;let vault: string;@@ -162,6 +164,37 @@ describe("the guard never rewrites an identifier", () => {expect(verdict.redacted).toBe(false);});+ test("a signal id survives, because a placeholder is a shared target", () => {+ // `sig-<date>-<slug>` crosses the 24-character entropy gate as soon as+ // the slug reaches nine characters, which is routine. Replacing it+ // wrote `[[***REDACTED***]]` into `_evidenced_by`, and the import+ // reported a full success while landing every preference that lost a+ // signal id on one dangling wikilink - the merge the identifier rule+ // exists to prevent, arriving through the payload pass instead.+ const body = `evidence: [[${SIGNAL_ID}]]`;+ const verdict = redactForEgress("brain-bank-export", {+ body,+ evidenced_by: [`[[${SIGNAL_ID}]]`],+ });+ expect(verdict.outcome).toBe(EGRESS_OUTCOME.released);+ if (verdict.outcome !== EGRESS_OUTCOME.released) throw new Error("unreachable");+ expect(verdict.payload.body).toBe(body);+ expect(verdict.payload.evidenced_by[0]).toBe(`[[${SIGNAL_ID}]]`);+ expect(verdict.redacted).toBe(false);+ });++ test("a token wearing a signal prefix is still redacted", () => {+ // The carve-out is the signal-id SHAPE, not the prefix: a date and a+ // lowercase slug. A vendor token behind `sig-` matches neither.+ const verdict = redactForEgress("brain-bank-export", {+ body: `sig-${VENDOR_TOKEN} and sig-2026-08-16-Zq7Xb2Kd9Lm4Np6Rt8Vw1Yc9`,+ });+ expect(verdict.outcome).toBe(EGRESS_OUTCOME.released);+ if (verdict.outcome !== EGRESS_OUTCOME.released) throw new Error("unreachable");+ expect(verdict.payload.body).not.toContain(VENDOR_TOKEN);+ expect(verdict.payload.body).not.toContain("Zq7Xb2Kd9Lm4Np6Rt8Vw1Yc9");+ });+test("a URL credential under an identifier key is still scrubbed", () => {// The one thing removed from an identifier, and not a collapse: the// authority is not part of what the identifier identifies, so thediff --git a/tests/cli/progress-emitter-census.test.ts b/tests/cli/progress-emitter-census.test.tsindex 822d10c7..c4dabb32 100644--- a/tests/cli/progress-emitter-census.test.ts+++ b/tests/cli/progress-emitter-census.test.ts@@ -64,6 +64,19 @@* - **A surface that is not the CLI.** The MCP progress transport has* its own tests; an emitter reachable only from there would have to* name an entry point this file can drive, and today none does.+ *+ * ## Why the population is read off a lexed view+ *+ * A census that matched raw text would count `progressCounter(` inside a+ * docblock as an emitter, and two docblocks in `src/` discuss the counter+ * by name. This file used to blank comments with a scanner of its own+ * that treated a quote as a string opener with no regex rule, so a line+ * such as `/["]/` above a docblock left that docblock unblanked and the+ * prose counted. It now reads {@link lexCode} from+ * `tests/helpers/source-lexer.ts`, which is the lexer the three other+ * source-reading censuses run and is tested beside itself. Blanking+ * rather than deleting keeps every offset usable for the+ * enclosing-function scan that follows.*/import { beforeAll, afterAll, describe, expect, test } from "bun:test";@@ -78,6 +91,7 @@ import { writeSignal } from "../../src/core/brain/signal.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { progressRecords } from "../helpers/progress-records.ts";import { runCli, type RunResult } from "../helpers/run-cli.ts";+import { lexCode } from "../helpers/source-lexer.ts";const SRC = resolve(import.meta.dir, "..", "..", "src");@@ -85,52 +99,6 @@ const SRC = resolve(import.meta.dir, "..", "..", "src");// The population: every `progressCounter(` call site in src/// ─────────────────────────────────────────────────────────────────────────────-/**- * Blank every comment body in `source`, preserving length and therefore- * every offset.- *- * A census that matched raw text would count `progressCounter(` inside a- * docblock as an emitter, and two docblocks in `src/` discuss the counter- * by name. Blanking rather than deleting keeps the offsets usable for the- * enclosing-function scan that follows.- */-function blankComments(source: string): string {- const out = source.split("");- let i = 0;- while (i < source.length) {- const ch = source[i]!;- const next = source[i + 1];- if (ch === "/" && next === "/") {- while (i < source.length && source[i] !== "\n") out[i++] = " ";- continue;- }- if (ch === "/" && next === "*") {- out[i++] = " ";- out[i++] = " ";- while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) {- if (source[i] !== "\n") out[i] = " ";- i++;- }- if (i < source.length) {- out[i++] = " ";- out[i++] = " ";- }- continue;- }- if (ch === '"' || ch === "'" || ch === "`") {- i++;- while (i < source.length && source[i] !== ch) {- if (source[i] === "\\") i++;- i++;- }- i++;- continue;- }- i++;- }- return out.join("");-}-/** Every `.ts` file under `dir`, recursively. */function tsFiles(dir: string): ReadonlyArray<string> {const out: string[] = [];@@ -155,7 +123,7 @@ const FUNCTION_RE = /^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+([A-Zfunction enumerateCallSites(): ReadonlyArray<string> {const sites: string[] = [];for (const file of tsFiles(SRC)) {- const code = blankComments(readFileSync(file, "utf8"));+ const code = lexCode(readFileSync(file, "utf8"));const functions: Array<{ at: number; name: string }> = [];FUNCTION_RE.lastIndex = 0;for (let m = FUNCTION_RE.exec(code); m !== null; m = FUNCTION_RE.exec(code)) {diff --git a/tests/cli/search-card-duplicates.test.ts b/tests/cli/search-card-duplicates.test.tsindex 90bbad03..ef6ca76b 100644--- a/tests/cli/search-card-duplicates.test.ts+++ b/tests/cli/search-card-duplicates.test.ts@@ -67,6 +67,9 @@ function cardsOutcome(duplicates?: ReadonlyArray<DuplicatePassageLocation>): Seacards: Object.freeze([toSearchCard(resultWith(duplicates), QUERY)]),warnings: Object.freeze([]),total: 1,+ // Neutral match quality: the folding assertions never read it, and 1 is+ // what the coverage report yields when there is no term mass to weigh.+ idfWeightedCoverage: 1,});}diff --git a/tests/cli/search-duplicate-locations.test.ts b/tests/cli/search-duplicate-locations.test.tsindex 142cc626..30a783ea 100644--- a/tests/cli/search-duplicate-locations.test.ts+++ b/tests/cli/search-duplicate-locations.test.ts@@ -54,6 +54,9 @@ function outcomeWith(duplicates?: ReadonlyArray<DuplicatePassageLocation>): Searresults: Object.freeze([resultWith(duplicates)]),warnings: Object.freeze([]),total: 1,+ // Neutral match quality: the folding assertions never read it, and 1 is+ // what the coverage report yields when there is no term mass to weigh.+ idfWeightedCoverage: 1,});}diff --git a/tests/cli/search-explain-trace.test.ts b/tests/cli/search-explain-trace.test.tsindex 0031e7a9..019a44c5 100644--- a/tests/cli/search-explain-trace.test.ts+++ b/tests/cli/search-explain-trace.test.ts@@ -84,6 +84,9 @@ function outcome(withReceipts: boolean): SearchOutcome {results: Object.freeze([RESULT]),warnings: Object.freeze([]),total: 2,+ // Neutral match quality: this test weighs the receipts, not the match,+ // and 1 is what the coverage report yields with no term mass to weigh.+ idfWeightedCoverage: 1,...(withReceipts ? { retrievalDecisionTrace: TRACE, memoryTrustAssessment: ASSESSMENT } : {}),});}diff --git a/tests/cli/search-retrieval-trail.test.ts b/tests/cli/search-retrieval-trail.test.tsindex e1875f81..badacf57 100644--- a/tests/cli/search-retrieval-trail.test.ts+++ b/tests/cli/search-retrieval-trail.test.ts@@ -89,6 +89,9 @@ function outcome(trail?: RetrievalTrail): SearchOutcome {results: Object.freeze([RESULT]),warnings: Object.freeze([]),total: 2,+ // Neutral match quality: the trail assertions never read it, and 1 is+ // what the coverage report yields when there is no term mass to weigh.+ idfWeightedCoverage: 1,...(trail !== undefined ? { retrievalTrail: trail } : {}),});}@@ -98,6 +101,8 @@ function emptyOutcomeWith(trail?: RetrievalTrail): SearchOutcome {results: Object.freeze([]),warnings: Object.freeze([]),total: 0,+ // A zero-result answer covers none of the query's IDF mass.+ idfWeightedCoverage: 0,...(trail !== undefined ? { retrievalTrail: trail } : {}),});}diff --git a/tests/core/architecture/destructive-site-census.test.ts b/tests/core/architecture/destructive-site-census.test.tsindex 4a44a428..80c0c835 100644--- a/tests/core/architecture/destructive-site-census.test.ts+++ b/tests/core/architecture/destructive-site-census.test.ts@@ -53,6 +53,14 @@* preserved), so a removal named in a comment is not a site and a site is* not hidden by a quote inside a regular expression.*+ * That lexer used to live in this file, and a character-identical copy of+ * it lived in the progress census while two further censuses ran partial+ * maskers of their own - one of which was wrong on shipped source. It is+ * now `tests/helpers/source-lexer.ts`, tested there in its own right, and+ * this census reads both of its views: {@link LexedSource.withoutComments}+ * for the import specifiers the binding detector needs, and+ * {@link LexedSource.code} for the calls and the gate spans.+ ** ## Gating is per SITE, not per file** `gated` used to be a file-level boolean: any file containing the string@@ -130,6 +138,7 @@ import {isRecoveryCoverage,RECOVERABILITY_STATE,} from "../../../src/core/brain/gates/recoverability.ts";+import { type LexedSource, lexSource } from "../../helpers/source-lexer.ts";const REPO_ROOT = join(import.meta.dir, "..", "..", "..");const BRAIN_ROOT = join(REPO_ROOT, "src", "core", "brain");@@ -163,181 +172,6 @@ const WRITE_SITE_CENSUS = readFileSync("utf8",);-// ----- Lexing -----------------------------------------------------------------/**- * Two views of one module, both the same LENGTH as the source so every- * offset still points at the same character.- *- * `withoutComments` keeps string literals, because an import's specifier- * IS a string and the binding detector has to read it. `code` blanks the- * body of every string, template and regex literal too, and is what the- * call and gate detectors run over: a `rmSync(` inside a quoted example- * is not a call, and a comment naming the gate does not gate anything.- */-interface SourceViews {- readonly withoutComments: string;- readonly code: string;-}--/** Characters after which a `/` opens a regex rather than divides. */-const REGEX_PRECEDING = new Set([- "",- "(",- ",",- "=",- ":",- "[",- "!",- "&",- "|",- "?",- "{",- "}",- ";",- "+",- "-",- "*",- "%",- "~",- "^",- "<",- ">",-]);--/** Keywords after which a `/` opens a regex, e.g. `return /x/.test(s)`. */-const REGEX_PRECEDING_KEYWORDS = new Set([- "return",- "typeof",- "instanceof",- "in",- "of",- "case",- "do",- "else",- "yield",- "await",- "void",- "delete",- "new",-]);--function regexCanStart(text: string, at: number, prev: string): boolean {- if (REGEX_PRECEDING.has(prev)) return true;- const before = text.slice(0, at).trimEnd();- const word = /[A-Za-z_$][\w$]*$/.exec(before);- return word !== null && REGEX_PRECEDING_KEYWORDS.has(word[0]);-}--function lex(text: string): SourceViews {- const n = text.length;- const withoutComments = [...text];- const code = [...text];- const blank = (arr: string[], from: number, to: number): void => {- for (let k = Math.max(from, 0); k < Math.min(to, n); k++) {- if (arr[k] !== "\n") arr[k] = " ";- }- };- // Top of the stack is the current mode. A template literal pushes- // `template`; a `${` inside one pushes `code` back on, with its own- // brace counter, so an interpolated expression is read as code.- const modes: string[] = ["code"];- const braces: number[] = [0];- let prev = "";- let i = 0;- while (i < n) {- const c = text[i]!;- if (modes[modes.length - 1] === "template") {- if (c === "\\") {- blank(code, i, i + 2);- i += 2;- continue;- }- if (c === "`") {- modes.pop();- prev = "`";- i += 1;- continue;- }- if (c === "$" && text[i + 1] === "{") {- modes.push("code");- braces.push(0);- prev = "{";- i += 2;- continue;- }- blank(code, i, i + 1);- i += 1;- continue;- }- const next = text[i + 1];- if (c === "/" && next === "/") {- let end = text.indexOf("\n", i);- if (end === -1) end = n;- blank(withoutComments, i, end);- blank(code, i, end);- i = end;- continue;- }- if (c === "/" && next === "*") {- const close = text.indexOf("*/", i + 2);- const end = close === -1 ? n : close + 2;- blank(withoutComments, i, end);- blank(code, i, end);- i = end;- continue;- }- if (c === '"' || c === "'") {- let j = i + 1;- while (j < n && text[j] !== c) j += text[j] === "\\" ? 2 : 1;- blank(code, i + 1, j);- prev = c;- i = j + 1;- continue;- }- if (c === "`") {- modes.push("template");- i += 1;- continue;- }- if (c === "/" && regexCanStart(text, i, prev)) {- let j = i + 1;- let inClass = false;- while (j < n) {- const e = text[j]!;- if (e === "\\") {- j += 2;- continue;- }- if (e === "\n") break;- if (e === "[") inClass = true;- else if (e === "]") inClass = false;- else if (e === "/" && !inClass) break;- j += 1;- }- blank(code, i + 1, j);- prev = "/";- i = j + 1;- continue;- }- if (c === "{") {- braces[braces.length - 1]! += 1;- } else if (c === "}") {- if (braces[braces.length - 1] === 0 && modes.length > 1) {- modes.pop();- braces.pop();- prev = "}";- i += 1;- continue;- }- braces[braces.length - 1]! -= 1;- }- if (!/\s/.test(c)) prev = c;- i += 1;- }- return { withoutComments: withoutComments.join(""), code: code.join("") };-}-// ----- Binding detection ----------------------------------------------------interface CensusFile {@@ -528,15 +362,15 @@ function gateSpans(code: string): Array<readonly [number, number]> {* once and the whole suite reuses it.*/interface CensusSource extends CensusFile {- readonly views: SourceViews;+ readonly views: LexedSource;}function lexed(file: CensusFile): CensusSource {- return { ...file, views: lex(file.text) };+ return { ...file, views: lexSource(file.text) };}function classify(file: CensusFile | CensusSource): CensusRow | null {- const views = "views" in file ? file.views : lex(file.text);+ const views = "views" in file ? file.views : lexSource(file.text);const sites = removalSites(views.code, fsImports(views.withoutComments));if (sites.length === 0) return null;const spans = gateSpans(views.code);diff --git a/tests/core/architecture/egress-census.test.ts b/tests/core/architecture/egress-census.test.tsindex 64d5b92c..9bb2508e 100644--- a/tests/core/architecture/egress-census.test.ts+++ b/tests/core/architecture/egress-census.test.ts@@ -22,8 +22,9 @@** ## The population, defined structurally*- * Two rules, because one name means two different things depending on- * what the module does with it.+ * Three rules. The first two are about a FILE destination, and differ+ * because one name means two different things depending on what the+ * module does with it. The third is about a NETWORK destination.** 1. UNAMBIGUOUS: the module declares a string parameter whose name is* one of {@link DESTINATION_FLAGS} (`out`, `outdir`, `dest`, …). Those@@ -47,6 +48,22 @@* Rule 2 adds no module today, which is the point - it is a tripwire, not* a backlog.*+ * 3. NETWORK DESTINATION: the module sends an HTTP request carrying a+ * BODY ({@link NETWORK_POST_RE} inside a module that calls `fetch`).+ * That is the network analogue of putting bytes on disk, and it is a+ * SEPARATE rule rather than a widened rule 1 because the file rules+ * read a declared destination PARAMETER, which a network caller does+ * not have: its destination is an operator-configured URL resolved at+ * construction time. Declaring the embedding endpoint under rule 1+ * would have failed+ * {@link "no declaration outlives the module it describes"}, since+ * that assertion requires the declared module to be in a population+ * derived from a parameter spec plus a raw file write.+ *+ * Rule 3 is what admits the largest and most continuous egress in the+ * product - every indexed chunk body, sent to whichever endpoint the+ * operator configured - which the file rules could not see at all.+ ** ## What it does not cover, stated rather than implied** - A destination taken as a POSITIONAL argument, or a flag spec built@@ -64,6 +81,11 @@* would make both unreadable.* - `process.stdout`. Every CLI verb writes there, so including it would* make the population the whole CLI.+ * - A network destination reached by a method other than POST - vault+ * content packed into a query string on a GET, say. Rule 3 reads the+ * method because a body is what makes a request an egress rather than a+ * lookup; a GET that smuggles content past it is the shape to add here+ * the day one appears.* - Per-WRITE coverage. The guard is asserted per declared DESTINATION* ({@link "every declared destination in a redacting module is matched* by a guard call"}), which catches a new unguarded verb appended to an@@ -87,11 +109,28 @@ import {const REPO_ROOT = join(import.meta.dir, "..", "..", "..");+/**+ * Where an operator is told what leaves the machine unscanned.+ *+ * The registry's `reason` fields are the decision record and live in+ * `src/`; this file is the surface someone configuring an endpoint+ * actually opens.+ */+const OPERATOR_EGRESS_DISCLOSURE_DOC = "docs/cli-reference.md";+/*** Flag names that name a destination the operator chose. `target` is* deliberately absent: `o2b install --target` names an ADAPTER, not a* path, and admitting it would put a name-selector in a destination* census.+ *+ * `export` is here because leaving it out is what hid the eighth site:+ * `o2b brain explorer --export <path>` wrote the whole preference graph,+ * principles verbatim, to an operator-named file with no scan, and this+ * census reported a clean sweep because the flag was spelled with a word+ * the list did not carry. It is unambiguous in the same way as `out` -+ * nothing reads FROM an `--export` - so it belongs in rule 1 rather than+ * beside the ambiguous names.*/const DESTINATION_FLAGS: ReadonlyArray<string> = Object.freeze(["out",@@ -101,6 +140,7 @@ const DESTINATION_FLAGS: ReadonlyArray<string> = Object.freeze(["out-dir","dest","destination",+ "export",]);/**@@ -145,6 +185,26 @@ const ANY_DESTINATION_G_RE = namedStringParamRe(const RAW_WRITE_RE =/\b(?:writeFileSync|appendFileSync|copyFileSync|cpSync|createWriteStream|atomicWriteFileSync|writeFile)\s*\(|\bBun\.write\s*\(/;+/**+ * An outbound HTTP request that carries a body, in the two shapes this+ * tree writes it: the request object literal (`method: "POST"`) and the+ * branch a delegating client takes before handing the request to an+ * injected transport (`method === "POST"`). The second form is not+ * decoration - without it `external-fetch.ts`, which is where every+ * research provider's POST actually reaches the network, is invisible+ * while the provider module that names the endpoint has no `fetch` of its+ * own. That pair is the network twin of the delegated-write gap this+ * census already states for files.+ *+ * Read alongside {@link NETWORK_FETCH_RE}, so a route table naming an+ * HTTP verb cannot enrol a module by itself. A server that both branches+ * on an inbound method and calls out with a body is in population by this+ * rule, which is the syntactic answer on purpose: deciding whether that+ * particular POST carries vault content is what a registry entry is for.+ */+const NETWORK_POST_RE = /\bmethod\s*(?::|===)\s*"POST"/;+const NETWORK_FETCH_RE = /\bfetch\s*\(/;+/** The shared egress guard. A module that calls it redacts on the way out. */const EGRESS_GUARD_CALL_RE = /\bredactForEgress\s*\(/;const EGRESS_GUARD_CALL_G_RE = /\bredactForEgress\s*\(/g;@@ -162,23 +222,55 @@ function readSourceTree(): ReadonlyArray<{ path: string; text: string }> {}/**- * True when this module declares an operator-named output destination:- * an unambiguous destination name, or an ambiguous one in a module that- * also writes bytes. See the two rules in the docblock.+ * True when this module declares an operator-named output FILE: an+ * unambiguous destination name, or an ambiguous one in a module that also+ * writes bytes. Rules 1 and 2 in the docblock.*/-function declaresDestination(text: string): boolean {+function declaresFileDestination(text: string): boolean {if (DESTINATION_FLAG_RE.test(text)) return true;return AMBIGUOUS_DESTINATION_RE.test(text) && RAW_WRITE_RE.test(text);}+/**+ * True when this module sends bytes to a NETWORK destination. Rule 3 in+ * the docblock: a body-carrying HTTP request in a module that fetches.+ */+function declaresNetworkDestination(text: string): boolean {+ return NETWORK_FETCH_RE.test(text) && NETWORK_POST_RE.test(text);+}++/** In population under any of the three rules. */+function declaresDestination(text: string): boolean {+ return declaresFileDestination(text) || declaresNetworkDestination(text);+}+function countMatches(text: string, re: RegExp): number {return (text.match(re) ?? []).length;}+/** One file as the census reads it: a repo-relative path and its bytes. */+interface CensusFile {+ readonly path: string;+ readonly text: string;+}++/**+ * The census itself, over whatever tree it is handed.+ *+ * Taking the tree as an ARGUMENT is what makes the synthetic controls+ * below able to fail. They used to append a fabricated path string to an+ * already-derived `POPULATION`, so the synthetic module's SOURCE never+ * reached this rule set: replacing the derivation with `[]` left both+ * "must be declared" tests green over a fully blinded census. Feeding the+ * intruder's real text through here is the shape+ * `write-site-census.test.ts` already uses for the same purpose.+ */+function census(files: ReadonlyArray<CensusFile>): ReadonlyArray<string> {+ return files.filter((f) => declaresDestination(f.text)).map((f) => f.path);+}+const SOURCE_TREE = readSourceTree();-const POPULATION: ReadonlyArray<string> = SOURCE_TREE.filter((f) =>- declaresDestination(f.text),-).map((f) => f.path);+const POPULATION: ReadonlyArray<string> = census(SOURCE_TREE);const ENTRIES: ReadonlyArray<EgressSite> = Object.values(EGRESS_SITES);const DECLARED_MODULES: ReadonlySet<string> = new Set(ENTRIES.map((e) => e.module));@@ -267,6 +359,21 @@ describe("egress site census", () => {}});+ test("every unscanned network egress is disclosed where an operator reads", () => {+ // The registry is a source file. An operator deciding whether to point+ // an embedding endpoint at a vendor reads the CLI reference, and four+ // of the five unscanned network payloads appeared nowhere outside+ // `src/`. Keyed on the entry ID rather than on prose, so a new+ // declaration is undisclosed until someone writes the disclosure.+ const doc = readFileSync(join(REPO_ROOT, OPERATOR_EGRESS_DISCLOSURE_DOC), "utf8");+ const undisclosed = ENTRIES.filter(+ (entry) => entry.redaction === EGRESS_REDACTION.unscannedNetworkPayload,+ )+ .filter((entry) => !doc.includes(entry.id))+ .map((entry) => entry.id);+ expect(undisclosed).toEqual([]);+ });+test("ids and module paths are unique", () => {expect(new Set(ENTRIES.map((e) => e.id)).size).toBe(ENTRIES.length);expect(DECLARED_MODULES.size).toBe(ENTRIES.length);@@ -280,14 +387,30 @@ describe("egress site census", () => {});describe("the census cannot pass by finding nothing", () => {+ /**+ * Run the REAL census over the real tree plus one synthetic module, and+ * report which of the resulting population nobody declared.+ *+ * The intruder arrives as a path AND its source, so the derivation is+ * what puts it in population. A control that appended the path alone+ * asserted a set operation over a constant and passed with the+ * derivation blinded to `[]`.+ */+ function unlistedWith(intruder: CensusFile): ReadonlyArray<string> {+ return census([...SOURCE_TREE, intruder]).filter((path) => !DECLARED_MODULES.has(path));+ }+test("the detector still sees the sites it measures", () => {// A regex that stopped matching would report a clean sweep over an// empty set. Floors sit just under the live measurement, not an order// of magnitude under it.- expect(POPULATION.length).toBeGreaterThan(5);+ expect(POPULATION.length).toBeGreaterThan(10);expect(ENTRIES.filter((e) => e.redaction === EGRESS_REDACTION.sharedRedactor).length,).toBeGreaterThan(4);+ expect(+ ENTRIES.filter((e) => e.redaction === EGRESS_REDACTION.unscannedNetworkPayload).length,+ ).toBeGreaterThan(3);});test("the five verbs this unit wired are all declared as redacting", () => {@@ -335,14 +458,117 @@ describe("the census cannot pass by finding nothing", () => {"a verb that delegates the write but names --outdir",' outdir: { type: "string" },\n writeBundle(outdir, plan);\n',],+ [+ "a destination flag spelled --export",+ ' export: { type: "string" },\n atomicWriteFileSync(exportPath, html);\n',+ ],]);for (const [shape, source] of INTRUDER_SHAPES) {test(`a new export path using ${shape} is in population`, () => {- expect(declaresDestination(source)).toBe(true);+ expect(declaresFileDestination(source)).toBe(true);+ });+ }++ /**+ * The synthetic destination the file rule missed for a whole release.+ * `--export` reads as a mode name rather than a path name, which is+ * exactly why a hardcoded list of destination words is the same defect+ * class this census exists to catch, one level up.+ */+ test("a synthetic --export module is in population and must be declared", () => {+ const intruder: CensusFile = {+ path: "src/cli/brain/verbs/synthetic-export-flag.ts",+ text: 'export: { type: "string" },\n atomicWriteFileSync(dest, body);\n',+ };+ expect(declaresFileDestination(intruder.text)).toBe(true);+ expect(unlistedWith(intruder)).toEqual([intruder.path]);+ });++ /**+ * Rule 3's own shapes. A network destination arrives as a `fetch` with a+ * body, never as a parameter spec, so none of the file shapes above can+ * stand in for these.+ */+ const NETWORK_INTRUDER_SHAPES: ReadonlyArray<readonly [string, string]> = Object.freeze([+ [+ "a provider client POSTing vault text to a configured endpoint",+ "const res = await fetch(this.http.url, {\n" ++ ' method: "POST",\n' ++ " body: JSON.stringify({ input: texts }),\n" ++ "});\n",+ ],+ [+ "a bare POST helper with the url inline",+ 'await fetch(`${base}/rerank`, { method: "POST", body });\n',+ ],+ ]);++ for (const [shape, source] of NETWORK_INTRUDER_SHAPES) {+ test(`${shape} is in population under the network rule`, () => {+ expect(declaresNetworkDestination(source)).toBe(true);+ // And not through a file rule, so the two populations stay legible.+ expect(declaresFileDestination(source)).toBe(false);});}+ test("a synthetic network-destination module must be declared too", () => {+ const intruder: CensusFile = {+ path: "src/core/search/embeddings/synthetic-provider.ts",+ text:+ "const response = await fetch(endpoint.url, {\n" ++ ' method: "POST",\n' ++ " body: JSON.stringify({ input: chunkBodies }),\n" ++ "});\n",+ };+ expect(declaresDestination(intruder.text)).toBe(true);+ expect(unlistedWith(intruder)).toEqual([intruder.path]);+ });++ test("reading a URL is not egress", () => {+ // The rule is about bytes going UP. A GET, however many, is ingress.+ expect(declaresNetworkDestination("const r = await fetch(url);\n")).toBe(false);+ expect(declaresNetworkDestination('const r = await fetch(url, { method: "GET" });\n')).toBe(+ false,+ );+ });++ test("a POST that reaches no network is not this census's subject", () => {+ // A route table, or a server reading an inbound method, without a call+ // out. The pair of conditions is what keeps `src/mcp/http.ts` and the+ // explorer's own loopback server out of population.+ expect(declaresNetworkDestination('if (req.method === "POST") return handle(req);\n')).toBe(+ false,+ );+ expect(declaresNetworkDestination('const route = { method: "POST" };\n')).toBe(false);+ for (const path of ["src/mcp/http.ts", "src/core/brain/explorer.ts"]) {+ const text = moduleText(path);+ expect(`${path}: ${declaresNetworkDestination(text)}`).toBe(`${path}: false`);+ }+ });++ test("a client that delegates its POST to an injected transport is seen", () => {+ // The provider module names the endpoint and never calls `fetch`; the+ // transport calls `fetch` and takes the method as a variable. Reading+ // only the request-literal form leaves the pair invisible.+ expect(+ declaresNetworkDestination(+ 'const body = method === "POST" ? JSON.stringify(req.body) : null;\n' ++ " const res = await fetch(input.url, { method: input.method, body });\n",+ ),+ ).toBe(true);+ });++ test("the network rule finds the modules it was written for", () => {+ // Named rather than counted: a regex narrowed by a later edit shows up+ // as a missing path, not as a smaller number.+ const network = SOURCE_TREE.filter((f) => declaresNetworkDestination(f.text)).map(+ (f) => f.path,+ );+ expect(network).toContain("src/core/search/embeddings/openai-compat.ts");+ expect(network.length).toBeGreaterThan(2);+ });+test("an identifier that merely ends in a destination name is not one", () => {expect(declaresDestination(' stdout: { type: "string" },\n')).toBe(false);expect(declaresDestination(' about: { type: "string" },\n')).toBe(false);@@ -363,7 +589,7 @@ describe("the census cannot pass by finding nothing", () => {// and the failure above will name it. Pinned so the rule cannot be// widened into a backlog by accident.const byAmbiguousOnly = SOURCE_TREE.filter(- (f) => !DESTINATION_FLAG_RE.test(f.text) && declaresDestination(f.text),+ (f) => !DESTINATION_FLAG_RE.test(f.text) && declaresFileDestination(f.text),).map((f) => f.path);expect(byAmbiguousOnly).toEqual([]);});@@ -373,8 +599,10 @@ describe("the census cannot pass by finding nothing", () => {});test("an undeclared module in population is reported by name", () => {- const intruder = "src/cli/brain/verbs/synthetic-export.ts";- const population = [...POPULATION, intruder];- expect(population.filter((path) => !DECLARED_MODULES.has(path))).toEqual([intruder]);+ const intruder: CensusFile = {+ path: "src/cli/brain/verbs/synthetic-export.ts",+ text: ' out: { type: "string" },\n writeFileSync(out, body, "utf8");\n',+ };+ expect(unlistedWith(intruder)).toEqual([intruder.path]);});});diff --git a/tests/core/architecture/progress-census.test.ts b/tests/core/architecture/progress-census.test.tsindex 478d42cb..94556780 100644--- a/tests/core/architecture/progress-census.test.ts+++ b/tests/core/architecture/progress-census.test.ts@@ -49,11 +49,15 @@* mis-parse reports a fact about a block that was never examined.** So the population is now read from a lexed view of each module rather- * than from its raw text. {@link lex} blanks comment bodies and string,+ * than from its raw text. {@link lexCode}, the shared lexer in+ * `tests/helpers/source-lexer.ts`, blanks comment bodies and string,* template and regex CONTENTS while preserving every offset, so brace* matching cannot be steered by a `"{"` in a string or by a commented-out* member, and a rule that needs the literal value reads it back out of- * the original text at the same offset. On top of that view sit three+ * the original text at the same offset. This file used to carry its own+ * character-identical copy of that lexer; the copy is gone, and the+ * helper is tested in its own right rather than only through this+ * census. On top of that view sit three* small parsers - one for declarations (`interface`, `class` and `type`* alike, with generic constraints skipped rather than walked into), one* for object members, and one for the string constants a stage can be@@ -89,6 +93,8 @@ import { describe, expect, test } from "bun:test";import { readFileSync, readdirSync } from "node:fs";import { join, relative, sep } from "node:path";+import { lexCode } from "../../helpers/source-lexer.ts";+const SRC_ROOT = join(import.meta.dir, "..", "..", "..", "src");/** Directories with no operation code in them. */@@ -116,174 +122,6 @@ const STAGE_IDENTIFIER = /^[a-z0-9]+([-_][a-z0-9]+)*$/;/** Constants whose values are stage names by their own name. */const STAGE_CONSTANT = /(?:^|_)STAGES?$/;-// ----------------------------------------------------------------------------// Lexing-// -----------------------------------------------------------------------------/** Characters after which a `/` opens a regex rather than divides. */-const REGEX_PRECEDING: ReadonlySet<string> = new Set([- "",- "(",- ",",- "=",- ":",- "[",- "!",- "&",- "|",- "?",- "{",- "}",- ";",- "+",- "-",- "*",- "%",- "~",- "^",- "<",- ">",-]);--/** Keywords after which a `/` opens a regex, e.g. `return /x/.test(s)`. */-const REGEX_PRECEDING_KEYWORDS: ReadonlySet<string> = new Set([- "return",- "typeof",- "instanceof",- "in",- "of",- "case",- "do",- "else",- "yield",- "await",- "void",- "delete",- "new",-]);--function regexCanStart(text: string, at: number, prev: string): boolean {- if (REGEX_PRECEDING.has(prev)) return true;- const before = text.slice(0, at).trimEnd();- const word = /[A-Za-z_$][\w$]*$/.exec(before);- return word !== null && REGEX_PRECEDING_KEYWORDS.has(word[0]);-}--/**- * `text` with comment bodies and string, template and regex CONTENTS- * replaced by spaces, every other character and every offset preserved.- *- * Quotes and delimiters survive so a literal is still recognisable as- * one; what does not survive is anything a literal could be carrying that- * a structural scan would otherwise read as syntax. This is the same- * lexer the destructive-site census runs, for the same reason.- */-function lex(text: string): string {- const n = text.length;- const code = [...text];- const blank = (from: number, to: number): void => {- for (let k = Math.max(from, 0); k < Math.min(to, n); k++) {- if (code[k] !== "\n") code[k] = " ";- }- };- // Top of the stack is the current mode. A template literal pushes- // `template`; a `${` inside one pushes `code` back on, with its own- // brace counter, so an interpolated expression is read as code.- const modes: string[] = ["code"];- const braces: number[] = [0];- let prev = "";- let i = 0;- while (i < n) {- const c = text[i]!;- if (modes[modes.length - 1] === "template") {- if (c === "\\") {- blank(i, i + 2);- i += 2;- continue;- }- if (c === "`") {- modes.pop();- prev = "`";- i += 1;- continue;- }- if (c === "$" && text[i + 1] === "{") {- modes.push("code");- braces.push(0);- prev = "{";- i += 2;- continue;- }- blank(i, i + 1);- i += 1;- continue;- }- const next = text[i + 1];- if (c === "/" && next === "/") {- let end = text.indexOf("\n", i);- if (end === -1) end = n;- blank(i, end);- i = end;- continue;- }- if (c === "/" && next === "*") {- const close = text.indexOf("*/", i + 2);- const end = close === -1 ? n : close + 2;- blank(i, end);- i = end;- continue;- }- if (c === '"' || c === "'") {- let j = i + 1;- while (j < n && text[j] !== c) j += text[j] === "\\" ? 2 : 1;- blank(i + 1, j);- prev = c;- i = j + 1;- continue;- }- if (c === "`") {- modes.push("template");- i += 1;- continue;- }- if (c === "/" && regexCanStart(text, i, prev)) {- let j = i + 1;- let inClass = false;- while (j < n) {- const e = text[j]!;- if (e === "\\") {- j += 2;- continue;- }- if (e === "\n") break;- if (e === "[") inClass = true;- else if (e === "]") inClass = false;- else if (e === "/" && !inClass) break;- j += 1;- }- blank(i + 1, j);- prev = "/";- i = j + 1;- continue;- }- if (c === "{") {- braces[braces.length - 1]! += 1;- } else if (c === "}") {- if (braces[braces.length - 1] === 0 && modes.length > 1) {- modes.pop();- braces.pop();- prev = "}";- i += 1;- continue;- }- braces[braces.length - 1]! -= 1;- }- if (!/\s/.test(c)) prev = c;- i += 1;- }- return code.join("");-}-/*** Bracket depth before each character, counting `{}`, `()` and `[]` only.*@@ -619,7 +457,7 @@ function analyze(files: ReadonlyArray<CensusFile>): ReadonlyArray<CensusSource>return files.map((file) => {const cached = ANALYZED.get(file.path);if (cached !== undefined && cached.text === file.text) return cached;- const code = lex(file.text);+ const code = lexCode(file.text);const nesting = depths(code);const source: CensusSource = {...file,diff --git a/tests/core/architecture/vault-path-census.test.ts b/tests/core/architecture/vault-path-census.test.tsnew file mode 100644index 00000000..0584a936--- /dev/null+++ b/tests/core/architecture/vault-path-census.test.ts@@ -0,0 +1,323 @@+/**+ * Census over the `vault_path` field every MCP tool response may carry.+ *+ * ## The defect+ *+ * `src/mcp/vault-path-field.ts` states the contract: an MCP response+ * lands in model context, so `vault_path` is the opaque store reference+ * `vault://<hex>` unless the operator has switched `expose_host_paths`+ * on, and a config that cannot be read makes the field report its reason+ * rather than degrade to the raw path. One function implements all of+ * that. Three sites called it. Forty-one returned `ctx.vault` - the+ * absolute host path - straight into the payload.+ *+ * That is this release's own thesis on the tool surface: a rule stated+ * once in prose, with nothing enumerating the sites it governs. Wiring+ * the forty-one fixes forty-one. What makes the forty-second impossible+ * is this file.+ *+ * ## Why here rather than beside the hardcoded-path scanner+ *+ * `tests/core/hygiene/hardcoded-paths.test.ts` gates the same class of+ * leak one layer up: a home path written INTO the source as a literal.+ * It cannot see this one, because nothing is hardcoded here - the path+ * is discovered at runtime and the source says only `ctx.vault`. The two+ * checks answer different questions over different populations (that one+ * scans shipped text including docs and templates; this one scans the+ * tool surface for a structural emission), so this is a sibling census,+ * not a rule to bolt onto that scanner.+ *+ * ## The population, defined structurally+ *+ * Every `.ts` module under {@link TOOL_SURFACE_ROOT} is read, lexed by+ * the shared {@link lexCode} view (comments and literal CONTENTS blanked,+ * so a `vault_path:` inside a docblock or a quoted example is not a+ * site), and every object property named `vault_path` is collected with+ * the expression it is assigned.+ *+ * Two dispositions, and no third:+ *+ * - a value that is a JSON-SCHEMA NODE - inline (`{ type: "string" }`,+ * recognised by the leading brace plus a `type:` member) or the+ * shared {@link VAULT_PATH_SCHEMA_DESCRIPTOR} - is a DECLARATION of+ * the field, not an emission of it. `outputSchema` blocks declare+ * `vault_path` and emit nothing.+ * - anything else is an EMISSION, and must be produced by+ * {@link VAULT_PATH_PRODUCER}. Not "must not be `ctx.vault`": a rule+ * that enumerated the wrong spellings would be the hand-kept list+ * this census exists to replace, and the next site would find a+ * forty-second way to say the same thing.+ *+ * A property whose value this file cannot classify is REPORTED, because+ * "I could not tell" is not a pass.+ *+ * ## What this census cannot see, stated rather than implied+ *+ * - An emission assigned through a local variable+ * (`const v = ctx.vault; return { vault_path: v }`) reads as an+ * unclassified expression and is reported, which is the safe+ * direction, but the report names the variable rather than the leak.+ * - A field spread in from elsewhere (`...block`) carries no+ * `vault_path:` property text and is invisible here. The payload+ * assertions in `tests/mcp/mcp.test.ts` are what cover the value+ * that actually ships.+ * - The OpenClaw native runtime (`src/openclaw/index.ts`) registers+ * three tools of its own that emit this field, and they are outside+ * this population for one reason only: the scan is rooted at+ * {@link TOOL_SURFACE_ROOT}, and that file is not under it. The+ * earlier wording here said OpenClaw "cannot import from `src/mcp/`+ * by construction", and this branch falsified it - `src/openclaw/+ * index.ts:23` imports {@link VAULT_PATH_PRODUCER} from exactly+ * there, which is what makes its three emissions correct.+ *+ * Those three are covered, by the second `describe` below rather than+ * by a widened root: it runs the same scanner over that one file and+ * requires the same producer, while {@link TOOL_SURFACE_ROOT} keeps+ * meaning "the modules that answer a `tools/call`". A count in a+ * population of three is an equality, so a fourth emission - or a+ * rewritten bundle that stops calling the producer - fails by name.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync, readdirSync } from "node:fs";+import { join, relative, resolve } from "node:path";++import { lexCode } from "../../helpers/source-lexer.ts";++/** The MCP tool surface: every module that can answer a `tools/call`. */+const TOOL_SURFACE_ROOT = resolve(import.meta.dir, "..", "..", "..", "src", "mcp");++/** The field this census is about. */+const FIELD = "vault_path";++/** The one function permitted to produce an emitted {@link FIELD}. */+const VAULT_PATH_PRODUCER = "vaultPathField";++/** The one descriptor an `outputSchema` declares the field with. */+const VAULT_PATH_SCHEMA_DESCRIPTOR = "VAULT_PATH_OUTPUT_SCHEMA";++/**+ * The measured population, as an EQUALITY.+ *+ * It was a floor of 20 against a real 44, which is the shape this release+ * spent two other censuses removing: a floor that loose lets more than+ * half the scanner's reach disappear and still reports a pass, so the+ * one failure it exists to catch - a scanner that quietly stops matching+ * - is exactly the one it would sleep through.+ *+ * The number moves when the tool surface does, and that is the point: a+ * changed count is a fact about this release that someone states, in the+ * same commit, rather than a drift nobody sees. Re-measure it only after+ * deciding the move is intended.+ */+const EMITTING_SITES = 44;++/** One `vault_path:` property found in the source. */+interface FieldSite {+ /** Path relative to the repository root. */+ readonly file: string;+ /** 1-based line of the property. */+ readonly line: number;+ /** The assigned expression, whitespace-collapsed. */+ readonly expression: string;+}++/** Every `.ts` module under `dir`, recursively, in stable order. */+function modules(dir: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>+ a.name.localeCompare(b.name),+ )) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...modules(path));+ else if (entry.name.endsWith(".ts")) out.push(path);+ }+ return out;+}++/** Closing bracket for each opener the value walk tracks. */+const BRACKET_PAIRS: Readonly<Record<string, string>> = Object.freeze({+ "(": ")",+ "[": "]",+ "{": "}",+});++/**+ * The expression assigned at `from`, ending at the first `,` or closing+ * bracket that is not nested inside one the expression itself opened.+ */+function readValueExpression(code: string, from: number): string {+ const stack: string[] = [];+ let i = from;+ for (; i < code.length; i++) {+ const c = code[i]!;+ if (stack.length === 0 && (c === "," || c === ")" || c === "]" || c === "}")) break;+ const closer = BRACKET_PAIRS[c];+ if (closer !== undefined) stack.push(closer);+ else if (c === stack[stack.length - 1]) stack.pop();+ }+ return code.slice(from, i).trim().replace(/\s+/g, " ");+}++/**+ * Every `vault_path:` property in one module's source.+ *+ * `label` is the reported file name; `text` is the raw source, lexed+ * here so the caller cannot pass the wrong view by accident.+ */+function fieldSites(label: string, text: string): FieldSite[] {+ const code = lexCode(text);+ const probe = new RegExp(String.raw`(^|[^\w$.])${FIELD}\s*:`, "g");+ const sites: FieldSite[] = [];+ for (const match of code.matchAll(probe)) {+ const at = match.index + match[0].length;+ sites.push({+ file: label,+ line: code.slice(0, at).split("\n").length,+ // Read the value back out of the ORIGINAL text at the same offset:+ // the views share every offset, and the code view has blanked the+ // literal contents this census wants to see (`{ type: "string" }`).+ expression: readValueExpression(text, skipSpace(code, at)),+ });+ }+ return sites;+}++/** First non-space offset at or after `from`. */+function skipSpace(code: string, from: number): number {+ let i = from;+ while (i < code.length && /\s/.test(code[i]!)) i++;+ return i;+}++/** A JSON-schema node declaring the field, rather than emitting a value. */+function isSchemaDeclaration(expression: string): boolean {+ if (expression === VAULT_PATH_SCHEMA_DESCRIPTOR) return true;+ return expression.startsWith("{") && /\btype\s*:/.test(expression);+}++/** The sites that emit a value, i.e. everything that is not a declaration. */+function emittingSites(sites: ReadonlyArray<FieldSite>): FieldSite[] {+ return sites.filter((site) => !isSchemaDeclaration(site.expression));+}++/** The emitting sites that do not go through {@link VAULT_PATH_PRODUCER}. */+function offendingSites(sites: ReadonlyArray<FieldSite>): FieldSite[] {+ const producer = new RegExp(String.raw`^${VAULT_PATH_PRODUCER}\s*\(`);+ return emittingSites(sites).filter((site) => !producer.test(site.expression));+}++const ROOT = resolve(import.meta.dir, "..", "..", "..");+const ALL_SITES: ReadonlyArray<FieldSite> = modules(TOOL_SURFACE_ROOT).flatMap((path) =>+ fieldSites(relative(ROOT, path), readFileSync(path, "utf8")),+);++/** `src/mcp/x.ts:12 -> ctx.vault`, the form a failure is read in. */+function render(site: FieldSite): string {+ return `${site.file}:${site.line} -> ${site.expression}`;+}++describe("vault_path emission census", () => {+ test("the population is read off the tool surface, not remembered", () => {+ // A scanner that silently matched nothing would report a clean sweep+ // over a surface it never examined - the false-clean signature these+ // censuses exist to prevent.+ expect(emittingSites(ALL_SITES).length).toBe(EMITTING_SITES);+ // The three tools defined in the aggregator itself are in population.+ expect(ALL_SITES.some((site) => site.file === join("src", "mcp", "tools.ts"))).toBe(true);+ // …and so is at least one Brain domain module.+ expect(ALL_SITES.some((site) => site.file.includes(join("src", "mcp", "brain")))).toBe(true);+ });++ test("every emitted vault_path is produced by vaultPathField", () => {+ expect(offendingSites(ALL_SITES).map(render)).toEqual([]);+ });++ test("an outputSchema declaration of the field is not an emission", () => {+ for (const value of [`{ type: "string" }`, VAULT_PATH_SCHEMA_DESCRIPTOR]) {+ const declared = fieldSites(+ "synthetic.ts",+ `const s = { properties: { ${FIELD}: ${value} } };`,+ );+ expect(declared).toHaveLength(1);+ expect(emittingSites(declared)).toEqual([]);+ }+ });++ test("both declaring schemas use the shared descriptor", () => {+ const declarations = ALL_SITES.filter((site) => !emittingSites([site]).length);+ expect(declarations.length).toBeGreaterThan(0);+ expect(declarations.map((site) => site.expression)).toEqual(+ declarations.map(() => VAULT_PATH_SCHEMA_DESCRIPTOR),+ );+ });+});++describe("the census can fail", () => {+ /** Sources a reviewer dropped in; each must be answered, not walked past. */+ const cases: ReadonlyArray<readonly [string, string, boolean]> = [+ ["the raw host path", `return { ${FIELD}: ctx.vault };`, true],+ ["the producer", `return { ${FIELD}: ${VAULT_PATH_PRODUCER}(ctx) };`, false],+ [+ "a producer call carrying arguments",+ `return { ${FIELD}: ${VAULT_PATH_PRODUCER}(ctx, { reason: "x" }) };`,+ false,+ ],+ ["a lookalike helper", `return { ${FIELD}: vaultPathFieldish(ctx) };`, true],+ ["a hoisted local", `const v = ctx.vault; return { ${FIELD}: v };`, true],+ ["a template of the host path", `return { ${FIELD}: \`\${ctx.vault}\` };`, true],+ ["the last property in the object", `return { a: 1, ${FIELD}: ctx.vault };`, true],+ ];+ for (const [label, source, offends] of cases) {+ test(`${offends ? "reports" : "accepts"}: ${label}`, () => {+ expect(offendingSites(fieldSites("synthetic.ts", source)).length > 0).toBe(offends);+ });+ }++ test("a mention inside a comment or a string literal is not a site", () => {+ const source = [+ `// ${FIELD}: ctx.vault`,+ `/** ${FIELD}: ctx.vault */`,+ `const doc = "${FIELD}: ctx.vault";`,+ `const tpl = \`${FIELD}: ctx.vault\`;`,+ ].join("\n");+ expect(fieldSites("synthetic.ts", source)).toEqual([]);+ });++ test("a longer property name ending in the field name is not a site", () => {+ expect(fieldSites("synthetic.ts", `return { origin_${FIELD}: ctx.vault };`)).toEqual([]);+ });+});++/**+ * The OpenClaw native runtime, scanned by the same rule.+ *+ * It is a separate `describe` rather than a wider root because it is a+ * separate transport: {@link TOOL_SURFACE_ROOT} is the set of modules+ * that answer a `tools/call`, and widening it to keep one file in scope+ * would cost that root its meaning. What must not differ is the RULE, so+ * the same scanner and the same producer requirement run over it here.+ */+describe("vault_path emission census (OpenClaw runtime)", () => {+ const OPENCLAW_ENTRY = join("src", "openclaw", "index.ts");+ const OPENCLAW_SITES = fieldSites(+ OPENCLAW_ENTRY,+ readFileSync(resolve(ROOT, OPENCLAW_ENTRY), "utf8"),+ );++ /** Measured, and an equality: the runtime registers exactly three. */+ const OPENCLAW_EMITTING_SITES = 3;++ test("the three emissions are found and none is outside the producer", () => {+ expect(emittingSites(OPENCLAW_SITES).length).toBe(OPENCLAW_EMITTING_SITES);+ expect(offendingSites(OPENCLAW_SITES).map(render)).toEqual([]);+ });++ test("it reaches the producer by importing it, which is why it can", () => {+ // The docblock above used to give "cannot import from `src/mcp/` by+ // construction" as the exclusion reason. This is the line that+ // falsified it, asserted so the reason cannot be restated.+ const source = readFileSync(resolve(ROOT, OPENCLAW_ENTRY), "utf8");+ expect(source).toContain(`import { ${VAULT_PATH_PRODUCER} } from "../mcp/vault-path-field.ts"`);+ });+});diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.tsindex 759c362d..60822866 100644--- a/tests/core/architecture/verdict-vocabulary-census.test.ts+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts@@ -147,6 +147,12 @@ import {SNAPSHOT_PRUNE_REFUSALS,} from "../../../src/core/brain/snapshot.ts";import { GATE_MODE, GATE_MODES, isGateMode } from "../../../src/core/integrity/stamp.ts";+import { isToolScope, TOOL_SCOPE, TOOL_SCOPES } from "../../../src/mcp/tool-contract.ts";+import {+ isRuntimeTarget,+ KNOWN_RUNTIME_TARGETS,+ RUNTIME_TARGET,+} from "../../../src/core/identity-reminder.ts";import {isTriggerStatus,TRIGGER_STATUS,@@ -343,6 +349,25 @@ import {isHostPressureState,isHostPressureUnmeasurableReason,} from "../../../src/core/brain/maintenance/host-pressure.ts";+import {+ isOwnerScopeRefusal,+ OWNER_SCOPE_REFUSAL,+ OWNER_SCOPE_REFUSALS,+} from "../../../src/mcp/owner-scope-refusal.ts";+import {+ isOriginReach,+ isOriginReachReason,+ ORIGIN_REACH,+ ORIGIN_REACH_REASON,+ ORIGIN_REACH_REASONS,+ ORIGIN_REACHES,+} from "../../../src/core/brain/portability/origin-reach.ts";+import {+ isMirrorOutcome,+ MIRROR_OUTCOME,+ MIRROR_OUTCOMES,+} from "../../../src/core/brain/shared-namespace.ts";+import { lexCode } from "../../helpers/source-lexer.ts";interface VocabularyUnderCensus {/** Identifies the vocabulary in a failure message. */@@ -1001,6 +1026,68 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([members: SNAPSHOT_ENTRY_SKIP_REASONS,guard: isSnapshotEntrySkipReason,},+ {+ // U6. Which tool surface a server process advertises. It shipped as a+ // bare union with its three members hand-copied into four places - the+ // union, the `second_brain_capabilities` output schema, the `--scope`+ // validity check and the `--scope` error message - and nothing+ // asserting the four agreed, which is the drift class this census+ // exists for, one level up from the vocabularies it already held.+ name: "TOOL_SCOPE",+ values: TOOL_SCOPE,+ members: TOOL_SCOPES,+ guard: isToolScope,+ },+ {+ // U6. Which host runtime the per-turn identity reminder is rendered+ // for. It was the nearest thing to a selector in the tree and followed+ // three of the four pieces: an array, a derived type and a guard typed+ // `string | undefined`, which kept it out of this population entirely.+ // The guard now takes `unknown`, so a target name read off an+ // environment variable is narrowed by the same rule as every other+ // persisted member here.+ name: "RUNTIME_TARGET",+ values: RUNTIME_TARGET,+ members: KNOWN_RUNTIME_TARGETS,+ guard: isRuntimeTarget,+ },+ {+ // U2. A caller-supplied owner scope naming someone other than the+ // server-resolved identity. Refused rather than narrowed: a silent+ // narrowing leaves the caller believing it read what it asked for.+ name: "OWNER_SCOPE_REFUSAL",+ values: OWNER_SCOPE_REFUSAL,+ members: OWNER_SCOPE_REFUSALS,+ guard: isOwnerScopeRefusal,+ },+ {+ // U5. Whether a registered search origin could be read at all.+ // `unreachable` and `unknown` are distinct members because "it is not+ // there" and "I could not look" have different repairs, and neither+ // may read as a zero contribution the way a dropped origin did.+ name: "ORIGIN_REACH",+ values: ORIGIN_REACH,+ members: ORIGIN_REACHES,+ guard: isOriginReach,+ },+ {+ // U5. Why an origin was not reachable - the axis that makes the+ // verdict actionable rather than merely honest.+ name: "ORIGIN_REACH_REASON",+ values: ORIGIN_REACH_REASON,+ members: ORIGIN_REACH_REASONS,+ guard: isOriginReachReason,+ },+ {+ // U5. The shared-namespace mirror's verdict. It was a two-piece type+ // alias outside this population, and it conflated operator+ // misconfiguration with an I/O failure under one token, so the caller+ // could not tell a vault that never opted in from a write that broke.+ name: "MIRROR_OUTCOME",+ values: MIRROR_OUTCOME,+ members: MIRROR_OUTCOMES,+ guard: isMirrorOutcome,+ },]);// ---------------------------------------------------------------------------@@ -1036,71 +1123,6 @@ function readSourceTree(): SourceFile[] {return files;}-/**- * The same source with comment bodies and string CONTENTS replaced by- * spaces, character offsets preserved.- *- * Structure is read off the mask and content off the original at the same- * index. This is what makes bracket matching honest: a `"}"` inside a- * value cannot close an object, and `// }` in a comment cannot either.- */-function maskSource(text: string): string {- const out = text.split("");- const blank = (from: number, to: number): void => {- for (let k = from; k < to && k < out.length; k += 1) if (out[k] !== "\n") out[k] = " ";- };- let i = 0;- while (i < text.length) {- const char = text[i]!;- const next = text[i + 1];- if (char === "/" && next === "/") {- const end = text.indexOf("\n", i);- const stop = end === -1 ? text.length : end;- blank(i, stop);- i = stop;- continue;- }- if (char === "/" && next === "*") {- const end = text.indexOf("*/", i + 2);- const stop = end === -1 ? text.length : end + 2;- blank(i, stop);- i = stop;- continue;- }- if (char === '"' || char === "'" || char === "`") {- let k = i + 1;- while (k < text.length) {- if (text[k] === "\\") {- k += 2;- continue;- }- if (text[k] === char) break;- // A `"` or `'` with no partner before the newline is not a string- // opener - it is a quote inside a regular expression literal,- // `/["']/` being the shape that occurs here. Treating it as an- // opener would blank real code from that point to the next quote- // ANYWHERE in the file, which is worse than a miss: the scan would- // report a fact about a module it never read. Only a template can- // legally span lines.- if (char !== "`" && text[k] === "\n") {- k = i;- break;- }- k += 1;- }- if (k === i) {- i += 1;- continue;- }- blank(i + 1, k);- i = k + 1;- continue;- }- i += 1;- }- return out.join("");-}-const CLOSER: Readonly<Record<string, string>> = Object.freeze({"{": "}","[": "]",@@ -1285,7 +1307,7 @@ interface ScannedVocabulary {function scanVocabularies(files: ReadonlyArray<SourceFile>): ScannedVocabulary[] {const found: ScannedVocabulary[] = [];for (const file of files) {- const masked = maskSource(file.text);+ const masked = lexCode(file.text);const declared = bindings(masked);const guards = guardCandidates(masked);for (const binding of declared) {@@ -1325,6 +1347,12 @@ function scanVocabularies(files: ReadonlyArray<SourceFile>): ScannedVocabulary[]const SOURCE_TREE = readSourceTree();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 = 63;const REGISTERED = new Map(CENSUS.map((entry) => [entry.name, entry] as const));describe("verdict vocabulary census", () => {@@ -1445,10 +1473,16 @@ describe("the census reads the tree", () => {});test("the scan still finds the population it measures", () => {- // A scanner that matched nothing would report a clean sweep over an- // empty set. Set just under the measurement: a floor of 20 against 57- // would let two thirds of the population stop being seen.- expect(SCANNED.length).toBeGreaterThan(50);+ // An EQUALITY, not a floor. A scanner that matched nothing would+ // report a clean sweep over an empty set, and a floor of 50 against a+ // real 63 would let a fifth of the population stop being seen without+ // anything going red - which is the same shape of defect this census+ // exists to catch, one level up.+ //+ // Adding a vocabulary therefore means bumping this number, which is+ // the point: the count is the measurement, and a measurement nobody+ // has to keep true is not one.+ expect(SCANNED.length).toBe(VOCABULARY_POPULATION);expect(SOURCE_TREE.length).toBeGreaterThan(500);});@@ -1537,6 +1571,22 @@ describe("the scan sees the shapes it claims to", () => {FROZEN_LIST +GUARD,],+ [+ // The positive control for the backtick hole. The regex line is+ // `src/core/vault.ts:88` verbatim, and before the shared lexer+ // landed it opened a phantom template that blanked 9,706 of that+ // module's 31,608 bytes - hiding `DOUBLE_QUOTED_ESCAPES`, the one+ // frozen binding in the tree this census could not see. A masker+ // that reads a backtick inside a regex as a template opener+ // reports this file as carrying no vocabulary at all.+ "a vocabulary behind a regex literal holding a backtick",+ "const CODE_BLOCK_RE = /```[\\s\\S]*?```|`[^`]+`/g;\n" ++ "export const source = CODE_BLOCK_RE.source;\n" ++ OBJECT ++ DERIVED ++ FROZEN_LIST ++ GUARD,+ ],]);for (const [shape, source] of INTRUDER_SHAPES) {diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.tsindex 8161925b..83f6f5b1 100644--- a/tests/core/architecture/write-site-census.test.ts+++ b/tests/core/architecture/write-site-census.test.ts@@ -70,6 +70,8 @@ import { describe, expect, test } from "bun:test";import { readdirSync, readFileSync } from "node:fs";import { join, relative } from "node:path";+import { type LexedSource, lexSource } from "../../helpers/source-lexer.ts";+const REPO_ROOT = join(import.meta.dir, "..", "..", "..");const SRC_ROOT = join(REPO_ROOT, "src");@@ -738,11 +740,17 @@ function readSourceTree(): CensusFile[] {return files;}-/** Whether this module can address the vault - see the docblock. */-function addressesVault(file: CensusFile): boolean {- if (VAULT_WRITE_ROOTS.some((root) => file.path.startsWith(root))) return true;- if (VAULT_WRITER_FILES.includes(file.path)) return true;- return VAULT_PATHS_IMPORT_RE.test(file.text);+/**+ * Whether this module can address the vault - see the docblock.+ *+ * `withoutComments` rather than `code`, because the clause that matters+ * reads an import SPECIFIER, which is a string: the other view blanks it+ * and no module would ever be found to import `paths.ts` again.+ */+function addressesVault(path: string, withoutComments: string): boolean {+ if (VAULT_WRITE_ROOTS.some((root) => path.startsWith(root))) return true;+ if (VAULT_WRITER_FILES.includes(path)) return true;+ return VAULT_PATHS_IMPORT_RE.test(withoutComments);}interface FsImports {@@ -799,11 +807,40 @@ function directWriteCalls(text: string, imported: FsImports): Set<string> {return direct;}-/** Classify one file into its direct and shared write sites. */+/**+ * One lex per module, kept, because the fixtures below re-run the whole+ * tree once per intruder shape and lexing is the expensive step. Keyed by+ * path and re-checked against the text, so a synthetic module reusing a+ * real path cannot read a stale view.+ */+const LEXED = new Map<string, { readonly text: string; readonly views: LexedSource }>();++function lexedViews(file: CensusFile): LexedSource {+ const cached = LEXED.get(file.path);+ if (cached !== undefined && cached.text === file.text) return cached.views;+ const views = lexSource(file.text);+ LEXED.set(file.path, { text: file.text, views });+ return views;+}++/**+ * Classify one file into its direct and shared write sites.+ *+ * The two views are not interchangeable and the census dies quietly if+ * they are swapped: imports are read off {@link LexedSource.withoutComments}+ * because a specifier is a string, and calls off+ * {@link LexedSource.code} because a `writeFileSync(` inside a quoted+ * example is not a call. Routing the import read through `code` was+ * measured to drop this census from 64 direct rows to zero with an EMPTY+ * failure list - a clean sweep over nothing, which is the reading this+ * file exists to remove. `the specifier view is the one imports are read+ * from` below pins that.+ */function classify(file: CensusFile): CensusRow | null {- if (!addressesVault(file)) return null;- const direct = directWriteCalls(file.text, fsImports(file.text));- const shared = [...file.text.matchAll(SHARED_WRITE_RE)].length;+ const views = lexedViews(file);+ if (!addressesVault(file.path, views.withoutComments)) return null;+ const direct = directWriteCalls(views.code, fsImports(views.withoutComments));+ const shared = [...views.code.matchAll(SHARED_WRITE_RE)].length;if (direct.size === 0 && shared === 0) return null;return { path: file.path, directCalls: [...direct].toSorted(), sharedCalls: shared };}@@ -821,6 +858,12 @@ const SOURCE_TREE = readSourceTree();const ROWS = census(SOURCE_TREE);const DIRECT_ROWS = ROWS.filter((row) => row.directCalls.length > 0);+/** Measured modules calling a filesystem write directly. An equality. */+const DIRECT_WRITE_ROWS = 64;++/** Measured modules reaching a write through a shared helper. An equality. */+const SHARED_HELPER_ROWS = 94;+describe("in-vault write-site census", () => {test("every direct-fs write site carries a written exclusion", () => {const unlisted = DIRECT_ROWS.filter((row) => !(row.path in DIRECT_WRITE_EXCLUSIONS)).map(@@ -949,11 +992,17 @@ describe("the census can fail", () => {test("the detectors still match the shapes they measure", () => {// A regex that stopped matching would report a clean sweep over an- // empty set. Pin the measurement, not only its verdict.- // Set just under the measurement, not an order of magnitude under it:- // a floor of 40 against 63 would let a third of the tree stop being- // seen and still report a clean sweep.- expect(DIRECT_ROWS.length).toBeGreaterThan(58);- expect(ROWS.filter((row) => row.sharedCalls > 0).length).toBeGreaterThan(88);+ // empty set. Pin the measurement, not only its verdict - and pin it+ // as an EQUALITY. These were floors of 58 and 88 against a measured+ // 64 and 94, and one of the two comments explaining the gap already+ // named a stale figure (63), which is what a floor does to the+ // number under it: nobody is keeping it. A floor also cannot fail on+ // the drift it exists to catch until six sites have already gone+ // dark.+ //+ // A moved number is a finding, not a re-measurement chore: state in+ // the same commit what added or removed a write site.+ expect(DIRECT_ROWS.length).toBe(DIRECT_WRITE_ROWS);+ expect(ROWS.filter((row) => row.sharedCalls > 0).length).toBe(SHARED_HELPER_ROWS);});});diff --git a/tests/core/bench/failure-modes.test.ts b/tests/core/bench/failure-modes.test.tsindex 3bf3f890..751f4af3 100644--- a/tests/core/bench/failure-modes.test.ts+++ b/tests/core/bench/failure-modes.test.ts@@ -36,6 +36,7 @@ import {type RecallResultSet,} from "../../../src/core/brain/recall-inject.ts";import { resolveSearchConfig, search } from "../../../src/core/search/index.ts";+import { lexSource } from "../../helpers/source-lexer.ts";const FIXTURE_PATH = join("tests", "fixtures", "bench", "failure-modes.json");@@ -72,6 +73,9 @@ async function alwaysConfident(): Promise<RecallResultSet> {}),]),total: 1,+ // The gaming strategy claims a perfect match for every prompt - that+ // unconditional confidence is exactly what the floor has to see through.+ idfWeightedCoverage: 1,});}@@ -308,9 +312,10 @@ describe("metric 4: exactly one token estimator is reachable from the bench", ().filter((file) => file.endsWith(".ts")).map((file) => ({file,- code: readFileSync(join(BENCH_DIR, file), "utf8")- .replace(/\/\*[\s\S]*?\*\//g, "")- .replace(/^\s*\/\/.*$/gm, ""),+ // The shared census lexer rather than two regexes, and the+ // `withoutComments` view specifically: every assertion below+ // reads an import specifier, which IS a string literal.+ code: lexSource(readFileSync(join(BENCH_DIR, file), "utf8")).withoutComments,}));}diff --git a/tests/core/brain.sessions.registry.test.ts b/tests/core/brain.sessions.registry.test.tsindex d9f8d6ff..0d714a28 100644--- a/tests/core/brain.sessions.registry.test.ts+++ b/tests/core/brain.sessions.registry.test.ts@@ -43,15 +43,14 @@ describe("registry — single source of adapters", () => {expect(isSessionAdapterId("copilot")).toBe(false);});- test("exposes the default agent label per adapter", () => {- const labels = Object.fromEntries(SESSION_ADAPTERS.map((a) => [a.id, a.defaultAgent]));- expect(labels).toEqual({- claude: "claude",- codex: "codex",- hermes: "hermes",- opencode: "opencode",- grok: "grok",- });+ test("no adapter carries an identity label of its own", () => {+ // Retracted in v1.49.0: `defaultAgent` duplicated `id` in all five+ // adapters and outranked the operator's `--agent`, so three runtimes+ // attributed imported memory to `claude` / `codex` / `hermes` - the+ // very strings `normalizeAgentArgument` rejects as placeholders.+ for (const adapter of SESSION_ADAPTERS) {+ expect(Object.hasOwn(adapter, "defaultAgent")).toBe(false);+ }});test("getAdapter returns each by id", () => {diff --git a/tests/core/brain.sessions.types.test.ts b/tests/core/brain.sessions.types.test.tsindex 3af8f588..b1b9d959 100644--- a/tests/core/brain.sessions.types.test.ts+++ b/tests/core/brain.sessions.types.test.ts@@ -29,7 +29,6 @@ describe("SessionAdapter / SessionTurn / SessionToolCall shape (compile-time)",test("a minimal stub adapter satisfies the interface", () => {const stub: SessionAdapter = {id: "claude",- defaultAgent: "claude",detect: () => false,iterate: async function* (_path: string) {void _path;diff --git a/tests/core/brain.time.test.ts b/tests/core/brain.time.test.tsindex c69596e5..e630eda5 100644--- a/tests/core/brain.time.test.ts+++ b/tests/core/brain.time.test.ts@@ -3,11 +3,36 @@*/import { describe, expect, test } from "bun:test";+import { readFileSync, readdirSync } from "node:fs";+import { join, relative, resolve } from "node:path";-import { relativeAge } from "../../src/core/brain/time.ts";+import { isoSecond, relativeAge } from "../../src/core/brain/time.ts";+import { lexCode } from "../helpers/source-lexer.ts";const now = new Date("2026-05-29T12:00:00Z");+const SRC = resolve(import.meta.dir, "..", "..", "src");++/** Every `.ts` module under `src/`, recursively. */+function sourceFiles(dir: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...sourceFiles(path));+ else if (entry.name.endsWith(".ts")) out.push(path);+ }+ return out;+}++/** A `function <name>(` declaration, read off the code view only. */+function declarationSites(name: string): string[] {+ const probe = new RegExp(String.raw`\bfunction\s+${name}\s*\(`);+ return sourceFiles(SRC)+ .filter((path) => probe.test(lexCode(readFileSync(path, "utf8"))))+ .map((path) => relative(SRC, path))+ .toSorted();+}+describe("relativeAge", () => {test("formats recent gaps with compact labels", () => {expect(relativeAge("2026-05-29T11:59:30Z", now)).toBe("just now");@@ -28,3 +53,23 @@ describe("relativeAge", () => {expect(relativeAge("2026-05-29T12:01:00Z", now)).toBe("just now");});});++describe("isoSecond", () => {+ test("renders whole-second UTC and defaults to the current instant", () => {+ expect(isoSecond(new Date("2026-05-29T12:00:00.789Z"))).toBe("2026-05-29T12:00:00Z");+ expect(isoSecond()).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/);+ });++ /**+ * a-label-is-not-a-boundary, U12: the secret-custody store carried its+ * own character-identical copy of this function. Two copies of a+ * timestamp format is how two timestamp formats begin - the copy took+ * no default argument, so it was already the narrower of the two - and+ * a duplicate is invisible in review at the site that has it. This+ * module owns the format, so this is where "and nowhere else" is+ * asserted; the population is read off `src/`, not remembered.+ */+ test("is the tree's only definition", () => {+ expect(declarationSites("isoSecond")).toEqual([join("core", "brain", "time.ts")]);+ });+});diff --git a/tests/core/brain/backlinks-owner-scope.test.ts b/tests/core/brain/backlinks-owner-scope.test.tsnew file mode 100644index 00000000..0a15870c--- /dev/null+++ b/tests/core/brain/backlinks-owner-scope.test.ts@@ -0,0 +1,162 @@+/**+ * `buildBacklinkIndex`'s two U3 obligations (a-label-is-not-a-boundary).+ *+ * 1. An optional owner scope, second parameter, that drops refs whose+ * SOURCE artifact the scope may not see. Nine existing call sites pass+ * nothing and keep the index they always got.+ * 2. An artifact the collector cannot parse is REPORTED. The `catch {+ * continue; }` this replaced returned a confident `count: 0` on a+ * vault whose preferences use the un-prefixed Group C frontmatter+ * shape, and the caller had no way to tell that from a genuine zero.+ */++import { afterEach, beforeEach, 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 { buildBacklinkIndex } from "../../../src/core/brain/backlinks.ts";+import { brainDirs } from "../../../src/core/brain/paths.ts";++/** Pinned per file; nothing in this repository pins it globally. */+process.env["HOME"] = mkdtempSync(join(tmpdir(), "o2b-backlinks-scope-home-"));++const OWNER_A = "agent-a";+const OWNER_B = "agent-b";+const TARGET = "pref-shared";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-backlinks-scope-vault-"));+ for (const sub of ["preferences", "retired", "inbox", "processed", "log"]) {+ mkdirSync(join(vault, "Brain", sub), { recursive: true });+ }+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++/**+ * A preference in the CURRENT frontmatter shape (`_`-prefixed Group C+ * keys), optionally owner-tagged.+ */+function writePref(slug: string, owner: string | null, body: string): void {+ writeFileSync(+ join(brainDirs(vault).preferences, `pref-${slug}.md`),+ [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ ...(owner === null ? [] : [`owner: ${owner}`]),+ "created_at: 2026-05-01T00:00:00Z",+ "unconfirmed_until: 2026-05-08T00:00:00Z",+ "tags: []",+ `topic: ${slug}`,+ `principle: principle for ${slug}`,+ "_status: confirmed",+ "_confirmed_at: 2026-05-02T00:00:00Z",+ "_evidenced_by: []",+ "_applied_count: 0",+ "_violated_count: 0",+ "---",+ "",+ body,+ "",+ ].join("\n"),+ );+}++/**+ * The Group C shape a legacy vault carries: `status:` un-prefixed.+ * `normalizeDerivedKeys` throws on it, which is what the collector used+ * to swallow.+ */+function writeLegacyPref(slug: string, body: string): void {+ writeFileSync(+ join(brainDirs(vault).preferences, `pref-${slug}.md`),+ [+ "---",+ "kind: brain-preference",+ `id: pref-${slug}`,+ "created_at: 2026-05-01T00:00:00Z",+ "unconfirmed_until: 2026-05-08T00:00:00Z",+ "tags: []",+ `topic: ${slug}`,+ `principle: principle for ${slug}`,+ "status: confirmed",+ "_status: confirmed",+ "---",+ "",+ body,+ "",+ ].join("\n"),+ );+}++test("an owner scope drops refs written by another owner's artifact", () => {+ writePref("shared", null, "the target");+ writePref("owned-by-a", OWNER_A, `points at [[${TARGET}]]`);+ writePref("also-shared", null, `points at [[${TARGET}]]`);++ const unscoped = buildBacklinkIndex(vault);+ expect((unscoped.get(TARGET) ?? []).map((r) => r.source).toSorted()).toEqual([+ "pref-also-shared",+ "pref-owned-by-a",+ ]);++ const scoped = buildBacklinkIndex(vault, OWNER_B);+ expect((scoped.get(TARGET) ?? []).map((r) => r.source)).toEqual(["pref-also-shared"]);++ // The owner still sees its own, and an absent scope still sees both -+ // the nine existing call sites pass nothing and are unaffected.+ const asOwner = buildBacklinkIndex(vault, OWNER_A);+ expect((asOwner.get(TARGET) ?? []).map((r) => r.source).toSorted()).toEqual([+ "pref-also-shared",+ "pref-owned-by-a",+ ]);+});++test("a legacy-frontmatter preference is reported, not silently dropped", () => {+ writePref("shared", null, "the target");+ writeLegacyPref("legacy", `points at [[${TARGET}]]`);++ const index = buildBacklinkIndex(vault);+ // The ref is still absent - the fields could not be read - but the+ // caller is now told which artifact was skipped and why, so a `count`+ // of 0 beside a non-empty report is distinguishable from a real zero.+ expect(index.get(TARGET)).toBeUndefined();+ expect(index.unparsed.map((u) => u.source)).toEqual(["pref-legacy"]);+ expect(index.unparsed[0]!.sourceKind).toBe("preference");+ expect(index.unparsed[0]!.reason).toContain("'_status'");+ // The reason crosses the MCP boundary: no absolute host path in it.+ expect(index.unparsed[0]!.reason).not.toContain(vault);+});++test("a clean vault reports no failures at all", () => {+ writePref("shared", null, "the target");+ writePref("other", null, `points at [[${TARGET}]]`);+ expect(buildBacklinkIndex(vault).unparsed).toEqual([]);+});++test("another owner's unparseable artifact is withheld from the failure report", () => {+ // Reporting it would name the artifact the ref filter just withheld,+ // which is the leak with the evidence moved one field over. The+ // artifact's owner is still readable from its frontmatter - it is the+ // DERIVED keys that fail - so the ownership rule still has a subject.+ writePref("shared", null, "the target");+ const legacy = join(brainDirs(vault).preferences, "pref-legacy.md");+ writeLegacyPref("legacy", `points at [[${TARGET}]]`);+ writeFileSync(+ legacy,+ readFileSync(legacy, "utf8").replace(+ "kind: brain-preference",+ `kind: brain-preference\nowner: ${OWNER_A}`,+ ),+ );++ expect(buildBacklinkIndex(vault).unparsed.map((u) => u.source)).toEqual(["pref-legacy"]);+ expect(buildBacklinkIndex(vault, OWNER_B).unparsed).toEqual([]);+ expect(buildBacklinkIndex(vault, OWNER_A).unparsed.map((u) => u.source)).toEqual(["pref-legacy"]);+});diff --git a/tests/core/brain/continuity/reader-census.test.ts b/tests/core/brain/continuity/reader-census.test.tsindex 3d3a174f..6c7769db 100644--- a/tests/core/brain/continuity/reader-census.test.ts+++ b/tests/core/brain/continuity/reader-census.test.ts@@ -123,15 +123,21 @@ const DIRECT_STORE_READERS: Readonly<Record<string, string>> = Object.freeze({* these say how far the counts may fall before the split stops describing* anything.*- * Four modules read through the read-model and twenty read the store- * directly. The read-model floor is AT today's count because losing one- * of four is a real regression; the direct floor sits one under, because- * that set is the one this wave is actively adding to and an exact pin- * would fail on another unit's honest new reader rather than on a lost- * measurement.+ * Four modules read through the read-model and twenty-one read the store+ * directly. Both numbers are EQUALITIES, not floors.+ *+ * The direct floor used to sit at twenty against a reality of+ * twenty-one, on the reasoning that an exact pin would fail on another+ * unit's honest new reader. What it actually bought was room for the+ * count to drift by one in either direction unseen - and the drift had+ * already happened. A floor that is looser than the measurement is a+ * measurement nobody is keeping, which is the defect this release is+ * about; the two tables below are declared by name anyway, so a new+ * reader has to be added to one of them regardless and the number costs+ * nothing extra to keep true.*/-const MIN_READ_MODEL_READERS = 4;-const MIN_DIRECT_STORE_READERS = 20;+const READ_MODEL_READER_COUNT = 4;+const DIRECT_STORE_READER_COUNT = 21;/** A file the classifier must see, and that `grep` alone does not. */@@ -197,8 +203,8 @@ describe("continuity reader census", () => {expect(pathsVia(rows, "viaStore").length).toBeGreaterThan(pathsVia(rows, "viaReadModel").length,);- expect(pathsVia(rows, "viaReadModel").length).toBeGreaterThanOrEqual(MIN_READ_MODEL_READERS);- expect(pathsVia(rows, "viaStore").length).toBeGreaterThanOrEqual(MIN_DIRECT_STORE_READERS);+ expect(pathsVia(rows, "viaReadModel").length).toBe(READ_MODEL_READER_COUNT);+ expect(pathsVia(rows, "viaStore").length).toBe(DIRECT_STORE_READER_COUNT);});test("the census reads bytes, so a NUL-carrying reader is not invisible to it", () => {diff --git a/tests/core/brain/doctor/recovery-point-liveness.test.ts b/tests/core/brain/doctor/recovery-point-liveness.test.tsindex 50eec564..c670cd36 100644--- a/tests/core/brain/doctor/recovery-point-liveness.test.ts+++ b/tests/core/brain/doctor/recovery-point-liveness.test.ts@@ -46,6 +46,7 @@ import { DOCTOR_EXIT_EXCLUSIONS } from "../../../../src/core/brain/doctor-exits.import { bootstrapBrain } from "../../../../src/core/brain/init.ts";import { SNAPSHOT_ARCHIVE_SUFFIX, snapshotsDir } from "../../../../src/core/brain/paths.ts";import type { DoctorIssue } from "../../../../src/core/brain/types.ts";+import { lexCode } from "../../../helpers/source-lexer.ts";let vault: string;@@ -235,7 +236,9 @@ describe("the verdict comes from the injected clock, never from the wall", () =>),);return source.text().then((text) => {- const code = text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");+ // The shared census lexer, `code` view: the subject here is a CALL,+ // so a `Date.now(` quoted inside a string is correctly not one.+ const code = lexCode(text);expect(code.includes("Date.now(")).toBe(false);expect(code.includes("new Date()")).toBe(false);});diff --git a/tests/core/brain/export-refusal-locations.test.ts b/tests/core/brain/export-refusal-locations.test.tsnew file mode 100644index 00000000..65f78fa2--- /dev/null+++ b/tests/core/brain/export-refusal-locations.test.ts@@ -0,0 +1,201 @@+/**+ * What the preference collector's refusals SAY, and who they refuse+ * (a-label-is-not-a-boundary review, C5 + C6).+ *+ * Two defects, one collector.+ *+ * C6: the refusal interpolated `parsePreference`'s raw message, and+ * `BrainParseError` composes that message as `<detail> (<absolute+ * path>)`. So the export that exists to keep vault content honest handed+ * back the operator's home directory - and `collectExportRows` is+ * reachable from an MCP error path, where `src/mcp/tools.ts` forbids+ * exactly that. The same release rewrote host paths out of the+ * `schema-report`, `backlinks` and `scaffold-stub` messages and left this+ * one. The `cannot list <dir>` branch one line above had no test at all.+ *+ * C5: the refusal is right for an export and wrong for the bank import,+ * which calls the same collector against the DESTINATION vault to learn+ * which topics its existing rules claim. One malformed preference already+ * sitting in the destination aborted the whole import - a write verb,+ * failing wholesale, on a condition unrelated to the data being carried.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, relative } from "node:path";++import {+ PreferenceParseError,+ collectExportRows,+ collectPreferenceRows,+} from "../../../src/core/brain/export.ts";+import { brainDirs, preferencePath } from "../../../src/core/brain/paths.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";+import { restorePreferences } from "../../../src/core/brain/portability/preference-restore.ts";+import { BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";++let src: string;+let dest: string;++beforeEach(() => {+ src = mkdtempSync(join(tmpdir(), "o2b-export-loc-src-"));+ dest = mkdtempSync(join(tmpdir(), "o2b-export-loc-dest-"));+ for (const vault of [src, dest]) {+ mkdirSync(brainDirs(vault).preferences, { recursive: true });+ mkdirSync(brainDirs(vault).log, { recursive: true });+ }+});++afterEach(() => {+ for (const vault of [src, dest]) rmSync(vault, { recursive: true, force: true });+});++function seed(vault: string, slug: string, topic = "writing"): void {+ writePreference(vault, {+ slug,+ topic,+ principle: `state the ${slug} rule and name the artifact it governs`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ confirmed_at: "2026-05-02T00:00:00Z",+ evidenced_by: [],+ });+}++/**+ * A preference file the parser cannot read: frontmatter is present and+ * parses as YAML, but `topic` - which `parsePreference` requires - is not+ * there. The failure is a `BrainParseError`, whose `message` carries the+ * absolute path and whose `detail` does not.+ */+function seedUnparseable(vault: string, slug: string): string {+ const path = preferencePath(vault, slug);+ writeFileSync(+ path,+ [+ "---",+ "kind: brain-preference",+ "_status: confirmed",+ `id: pref-${slug}`,+ "---",+ "",+ "body",+ "",+ ].join("\n"),+ );+ return relative(vault, path);+}++describe("the export refusal names a vault-relative location", () => {+ test("a parse failure carries no host path", () => {+ seed(src, "alpha-rule");+ const rel = seedUnparseable(src, "broken-rule");++ let raised: unknown;+ try {+ collectExportRows(src);+ } catch (exc) {+ raised = exc;+ }++ expect(raised).toBeInstanceOf(PreferenceParseError);+ const err = raised as PreferenceParseError;+ // The path field, the reason, and the composed message the CLI prints+ // are three separate strings and the host path used to be in two of+ // them.+ expect(err.failures.map((f) => f.path)).toEqual([rel]);+ expect(err.failures[0]?.reason ?? "").not.toContain(src);+ expect(err.message).not.toContain(src);+ // Named, not merely scrubbed: the operator has to know which file.+ expect(err.message).toContain(rel);+ });++ test("a directory that cannot be listed raises with the reason", () => {+ // `Brain/preferences` as a FILE: `existsSync` says yes, `readdirSync`+ // fails ENOTDIR. Before this branch existed the collector answered+ // this with `[]` - a permission or filesystem fault reported as an+ // empty Brain. It had no test in the tree at all.+ rmSync(brainDirs(src).preferences, { recursive: true, force: true });+ writeFileSync(brainDirs(src).preferences, "not a directory\n");++ let raised: unknown;+ try {+ collectExportRows(src);+ } catch (exc) {+ raised = exc;+ }++ expect(raised).toBeInstanceOf(Error);+ const message = (raised as Error).message;+ expect(message).toContain("cannot list Brain/preferences");+ // The reason travels, so the operator is not left to guess between a+ // permission fault and a broken mount…+ expect(message).toMatch(/ENOTDIR|not a directory/i);+ // …and the host path does not.+ expect(message).not.toContain(src);+ });+});++describe("the bank import survives an unreadable rule in the destination", () => {+ test("the import lands and names the file the topic scan could not read", () => {+ seed(src, "alpha-rule", "writing");+ const rows = collectExportRows(src);+ // The destination already holds one good rule and one the parser+ // cannot read. Neither is what the bundle carries.+ seed(dest, "existing-rule", "reviewing");+ const brokenRel = seedUnparseable(dest, "legacy-rule");++ const result = restorePreferences(dest, rows, { agent: "bank-import" });++ // The rows the caller actually asked for are on disk.+ expect(result.restored).toEqual(["pref-alpha-rule"]);+ expect(result.failed).toEqual([]);+ expect(result.carried).toBe(1);+ // And the incompleteness of the topic-key check is stated rather than+ // left for the reader to infer from an empty collision list.+ expect(result.topicScanUnreadable.map((f) => f.path)).toEqual([brokenRel]);+ expect(result.topicScanUnreadable[0]?.reason ?? "").not.toContain(dest);+ });++ test("a healthy destination reports an empty scan, so nothing changes for it", () => {+ seed(src, "alpha-rule");+ seed(dest, "existing-rule", "reviewing");++ const result = restorePreferences(dest, collectExportRows(src), { agent: "bank-import" });++ expect(result.topicScanUnreadable).toEqual([]);+ expect(result.topicKeyCollisions).toEqual([]);+ });++ test("the collision check still works over the rules it could read", () => {+ // A destination rule claiming the same FOLDED topic key under a+ // different spelling is the finding this scan exists for, and an+ // unreadable neighbour must not suppress it.+ seed(src, "alpha-rule", "code review");+ seed(dest, "existing-rule", "Code Review");+ seedUnparseable(dest, "legacy-rule");++ const result = restorePreferences(dest, collectExportRows(src), { agent: "bank-import" });++ expect(result.restored).toEqual(["pref-alpha-rule"]);+ expect(result.topicKeyCollisions.map((c) => c.key)).toEqual(["code review"]);+ expect(result.topicScanUnreadable.length).toBe(1);+ });+});++describe("the partial collector is the only one that tolerates a failure", () => {+ test("collectPreferenceRows returns the readable rows beside the failures", () => {+ seed(src, "alpha-rule");+ const rel = seedUnparseable(src, "broken-rule");++ const collection = collectPreferenceRows(src);++ expect(collection.rows.map((r) => r.id)).toEqual(["pref-alpha-rule"]);+ expect(collection.failures.map((f) => f.path)).toEqual([rel]);+ // The refusing wrapper is the same walk: a caller that cannot use a+ // partial answer still gets none.+ expect(() => collectExportRows(src)).toThrow(PreferenceParseError);+ });+});diff --git a/tests/core/brain/gap-loop-adequacy.test.ts b/tests/core/brain/gap-loop-adequacy.test.tsindex e846ba5c..bd752de4 100644--- a/tests/core/brain/gap-loop-adequacy.test.ts+++ b/tests/core/brain/gap-loop-adequacy.test.ts@@ -44,13 +44,29 @@ const QUERY = "widget calibration procedure";/** The bucket key `normalizeQueryTerms` derives for {@link QUERY}. */const QUERY_BUCKET = normalizeQueryTerms(QUERY).join(" ");-/** Scores producing each verdict level under the default thresholds. */-const WEAK_SCORES = [0.4];-const SUFFICIENT_SCORES = [0.9];-const INSUFFICIENT_SCORES: ReadonlyArray<number> = [];+/**+ * Recall attempts producing each verdict level under the default+ * thresholds. The level follows `matchQuality`; the scores only carry the+ * usable-result count that `minResults` gates on.+ *+ * Each pair puts its score on the OPPOSITE side of the boundary from its+ * quality, so no case here can be produced by reading the score instead -+ * the substitution this release removed and which several sibling+ * fixtures still could not have detected.+ */+const WEAK_RECALL = Object.freeze({ matchQuality: 0.4, scores: [0.9] });+const SUFFICIENT_RECALL = Object.freeze({ matchQuality: 0.9, scores: [0.1] });+const INSUFFICIENT_RECALL = Object.freeze({+ matchQuality: 0,+ scores: [] as ReadonlyArray<number>,+});-function stampUnmet(query: string, times: number, scores: ReadonlyArray<number>): void {- const verdict = assessRecallAdequacy(scores);+function stampUnmet(+ query: string,+ times: number,+ attempt: { readonly matchQuality: number; readonly scores: ReadonlyArray<number> },+): void {+ const verdict = assessRecallAdequacy(attempt);for (let i = 0; i < times; i++) {recordRecallAdequacyDemand(vault, {query,@@ -75,13 +91,30 @@ function seedStructuralGap(topic: string, times: number): void {}}-function retrieverWithScore(score: number): RecallRetriever {+/**+ * A retrieval that covers `matchQuality` of the topic with a candidate+ * scoring `score`.+ *+ * Both are parameters, and callers pass them on opposite sides of the+ * floor. The score used to be hardcoded at 0.92 while every caller passed+ * 0.92 as the coverage too, which made the fixture unable to tell the+ * coverage gate from a score gate.+ */+function retrieverWithCoverage(matchQuality: number, score: number): RecallRetriever {return async () =>({candidates: [- { path: "Brain/x.md", title: "X", score, searchType: "hybrid", startLine: 1, endLine: 2 },+ {+ path: "Brain/x.md",+ title: "X",+ score,+ searchType: "hybrid",+ startLine: 1,+ endLine: 2,+ },],total: 1,+ idfWeightedCoverage: matchQuality,}) satisfies RecallResultSet;}@@ -89,7 +122,7 @@ describe("recall-adequacy stamps the demand record (signals-that-survive, unit 6test("a weak verdict stamps the record under the normalizeQueryTerms bucket key", () => {const record = recordRecallAdequacyDemand(vault, {query: QUERY,- verdict: assessRecallAdequacy(WEAK_SCORES),+ verdict: assessRecallAdequacy(WEAK_RECALL),});expect(record).not.toBeNull();expect(record!.adequacy).toBe("weak");@@ -102,7 +135,7 @@ describe("recall-adequacy stamps the demand record (signals-that-survive, unit 6});test("an insufficient verdict stamps the record and carries its result count", () => {- const verdict = assessRecallAdequacy(INSUFFICIENT_SCORES);+ const verdict = assessRecallAdequacy(INSUFFICIENT_RECALL);const record = recordRecallAdequacyDemand(vault, { query: QUERY, verdict });expect(record!.adequacy).toBe("insufficient");expect(record!.results).toBe(verdict.resultCount);@@ -111,7 +144,7 @@ describe("recall-adequacy stamps the demand record (signals-that-survive, unit 6test("a sufficient verdict stamps nothing — only unmet recall is demand", () => {const record = recordRecallAdequacyDemand(vault, {query: QUERY,- verdict: assessRecallAdequacy(SUFFICIENT_SCORES),+ verdict: assessRecallAdequacy(SUFFICIENT_RECALL),});expect(record).toBeNull();expect(readQueryDemand(vault)).toHaveLength(0);@@ -119,8 +152,11 @@ describe("recall-adequacy stamps the demand record (signals-that-survive, unit 6test("a query with no significant terms records nothing rather than an empty bucket", () => {const record = recordRecallAdequacyDemand(vault, {- query: "a b c",- verdict: assessRecallAdequacy(WEAK_SCORES),+ // Punctuation only. "a b c" used to land here, because the term+ // floor dropped every token under three characters - which also+ // dropped every CJK query, so those gaps could never be counted.+ query: "?!? ...",+ verdict: assessRecallAdequacy(WEAK_RECALL),});expect(record).toBeNull();expect(readQueryDemand(vault)).toHaveLength(0);@@ -129,7 +165,7 @@ describe("recall-adequacy stamps the demand record (signals-that-survive, unit 6describe("verdict recurrence feeds the gap loop (signals-that-survive, unit 6)", () => {test("a bucket at or above the threshold surfaces as an adequacy-sourced gap", () => {- stampUnmet(QUERY, 3, WEAK_SCORES);+ stampUnmet(QUERY, 3, WEAK_RECALL);const gaps = detectRecurringGaps(vault, { threshold: 3 });expect(gaps).toHaveLength(1);expect(gaps[0]?.topic).toBe(QUERY_BUCKET);@@ -138,7 +174,7 @@ describe("verdict recurrence feeds the gap loop (signals-that-survive, unit 6)",});test("a bucket below the threshold mints nothing", () => {- stampUnmet(QUERY, 2, WEAK_SCORES);+ stampUnmet(QUERY, 2, WEAK_RECALL);expect(detectRecurringGaps(vault, { threshold: 3 })).toHaveLength(0);const result = promoteGapsToTasks(vault, { threshold: 3, now: NOW });expect(result.created).toHaveLength(0);@@ -146,7 +182,7 @@ describe("verdict recurrence feeds the gap loop (signals-that-survive, unit 6)",});test("a recurring bucket promotes to exactly one gap task carrying its source", () => {- stampUnmet(QUERY, 3, WEAK_SCORES);+ stampUnmet(QUERY, 3, WEAK_RECALL);const result = promoteGapsToTasks(vault, { threshold: 3, now: NOW });const key = gapTaskKey(QUERY_BUCKET, GAP_SOURCE_ADEQUACY);expect(result.created).toEqual([key]);@@ -161,7 +197,7 @@ describe("verdict recurrence feeds the gap loop (signals-that-survive, unit 6)",});test("an existing open gap task for the same key is not duplicated", () => {- stampUnmet(QUERY, 3, WEAK_SCORES);+ stampUnmet(QUERY, 3, WEAK_RECALL);const first = promoteGapsToTasks(vault, { threshold: 3, now: NOW });const second = promoteGapsToTasks(vault, { threshold: 3, now: NOW });expect(first.created).toHaveLength(1);@@ -173,7 +209,7 @@ describe("verdict recurrence feeds the gap loop (signals-that-survive, unit 6)",test("promotion is capped per run at the named constant", () => {const buckets = GAP_LOOP_MAX_PROMOTIONS_PER_RUN + 1;for (let i = 0; i < buckets; i++) {- stampUnmet(`coverage gap topic${i}`, 3 + (buckets - i), WEAK_SCORES);+ stampUnmet(`coverage gap topic${i}`, 3 + (buckets - i), WEAK_RECALL);}expect(detectRecurringGaps(vault, { threshold: 3 })).toHaveLength(buckets);const first = promoteGapsToTasks(vault, { threshold: 3, now: NOW });@@ -186,9 +222,10 @@ describe("verdict recurrence feeds the gap loop (signals-that-survive, unit 6)",});test("an adequacy gap task auto-closes once its topic recalls with sufficient confidence", async () => {- stampUnmet(QUERY, 3, WEAK_SCORES);+ stampUnmet(QUERY, 3, WEAK_RECALL);promoteGapsToTasks(vault, { threshold: 3, now: NOW });- const result = await autoCloseRecalledGaps(vault, retrieverWithScore(0.92), {+ // Coverage above the floor, score far below it.+ const result = await autoCloseRecalledGaps(vault, retrieverWithCoverage(0.92, 0.05), {confidenceFloor: 0.5,now: NOW,});@@ -203,7 +240,7 @@ describe("the two occurrence sources stay distinguishable (signals-that-survive,// Same literal topic string from BOTH sources: a coarse telemetry code// bucket and a fine term bucket that happen to collide textually.seedStructuralGap(QUERY_BUCKET, 3);- stampUnmet(QUERY, 4, WEAK_SCORES);+ stampUnmet(QUERY, 4, WEAK_RECALL);const gaps = detectRecurringGaps(vault, { threshold: 3 });expect(gaps).toHaveLength(2);@@ -217,7 +254,7 @@ describe("the two occurrence sources stay distinguishable (signals-that-survive,test("a textually identical topic from each source mints two separate tasks", () => {seedStructuralGap(QUERY_BUCKET, 3);- stampUnmet(QUERY, 4, WEAK_SCORES);+ stampUnmet(QUERY, 4, WEAK_RECALL);const result = promoteGapsToTasks(vault, { threshold: 3, now: NOW });expect(result.created).toHaveLength(2);// The keys are namespaced by source, so the two rows can never collapse@@ -235,7 +272,7 @@ describe("the two occurrence sources stay distinguishable (signals-that-survive,test("the agenda labels each row by its source", () => {seedStructuralGap("alpha topic", 3);- stampUnmet(QUERY, 4, WEAK_SCORES);+ stampUnmet(QUERY, 4, WEAK_RECALL);promoteGapsToTasks(vault, { threshold: 3, now: NOW });const agenda = renderGapAgenda(vault, NOW);// The structural row keeps its existing wording verbatim.diff --git a/tests/core/brain/gap-loop.test.ts b/tests/core/brain/gap-loop.test.tsindex 36ecf74e..14cc6511 100644--- a/tests/core/brain/gap-loop.test.ts+++ b/tests/core/brain/gap-loop.test.ts@@ -19,9 +19,11 @@ import {listGapTasks,promoteGapsToTasks,renderGapAgenda,+ GapRecallScopeError,+ type GapRecallRetriever,} from "../../../src/core/brain/gaps/gap-loop.ts";import { brainGapTasksDir } from "../../../src/core/brain/paths.ts";-import type { RecallRetriever, RecallResultSet } from "../../../src/core/brain/recall-inject.ts";+import type { RecallResultSet } from "../../../src/core/brain/recall-inject.ts";import { parseFrontmatterText, writeFrontmatterAtomic } from "../../../src/core/vault.ts";let vault: string;@@ -51,16 +53,76 @@ function seedGap(topic: string, times: number): void {const NOW = new Date("2026-06-01T12:00:00.000Z");-function retrieverWithScore(score: number): RecallRetriever {+/** Path of the one ordinary note the fixtures below recall. */+const ORDINARY_NOTE = "Brain/x.md";++/** Path of a gap-task note - the row the membership rule excludes. */+const GAP_TASK_NOTE = "Brain/gap-tasks/gap-abc.md";++/**+ * A retrieval that covers `matchQuality` of the topic with a candidate+ * scoring `score`.+ *+ * Both are parameters, and callers are required to pass them on OPPOSITE+ * sides of the floor. A fixture where the two agree cannot tell the gate+ * apart from the substitution this release removed: with `score` and+ * coverage both at 0.92, reverting the gate to `topScore >= floor` leaves+ * the test green, so it asserts the outcome without asserting the reason.+ */+function retrieverWithCoverage(matchQuality: number | null, score: number): GapRecallRetriever {return async () =>({candidates: [- { path: "Brain/x.md", title: "X", score, searchType: "hybrid", startLine: 1, endLine: 2 },+ {+ path: ORDINARY_NOTE,+ title: "X",+ score,+ searchType: "hybrid",+ startLine: 1,+ endLine: 2,+ },],total: 1,+ idfWeightedCoverage: matchQuality,}) satisfies RecallResultSet;}+/** One row of the fixture corpus {@link retrieverOverRows} recalls. */+interface FixtureRow {+ readonly path: string;+ readonly score: number;+ /** Share of the topic this row alone covers. */+ readonly coverage: number;+}++/**+ * A retrieval that honours its membership rule the way a real one must:+ * the predicate selects the rows BEFORE the quality is measured, so the+ * number describes the rows the gate is about to judge.+ *+ * Coverage over the admitted rows is modelled as the best admitted row's+ * share, and zero when none survived - a measured zero, since the topic+ * has terms and nothing covered them.+ */+function retrieverOverRows(rows: ReadonlyArray<FixtureRow>): GapRecallRetriever {+ return async (_topic, admits) => {+ const admitted = rows.filter((row) => admits(row.path));+ return {+ candidates: admitted.map((row) => ({+ path: row.path,+ title: "X",+ score: row.score,+ searchType: "hybrid" as const,+ startLine: 1,+ endLine: 2,+ })),+ total: admitted.length,+ idfWeightedCoverage:+ admitted.length === 0 ? 0 : Math.max(...admitted.map((row) => row.coverage)),+ } satisfies RecallResultSet;+ };+}+describe("gap loop (A3 / t_67d38036)", () => {test("detects only gaps at or above the recurrence threshold, most-frequent first", () => {seedGap("alpha topic", 3);@@ -112,7 +174,9 @@ describe("gap loop (A3 / t_67d38036)", () => {test("auto-closes a gap task once its topic is recalled with sufficient confidence", async () => {seedGap("alpha topic", 3);promoteGapsToTasks(vault, { threshold: 2, now: NOW });- const result = await autoCloseRecalledGaps(vault, retrieverWithScore(0.92), {+ // Coverage above the floor, score far below it: only the gate that+ // reads coverage can close this task.+ const result = await autoCloseRecalledGaps(vault, retrieverWithCoverage(0.92, 0.05), {confidenceFloor: 0.5,now: NOW,});@@ -126,15 +190,41 @@ describe("gap loop (A3 / t_67d38036)", () => {expect(typeof fm["closed_at"]).toBe("string");});- test("never self-closes: a hit on the gap-task note itself does not count as coverage", async () => {+ test("never self-closes: the gap-task note cannot supply the coverage the floor reads", async () => {+ seedGap("alpha topic", 3);+ promoteGapsToTasks(vault, { threshold: 2, now: NOW });+ // The gap-task note covers its own topic completely - it carries the+ // topic verbatim - and one ordinary note mentions it in passing. The+ // membership rule excludes the first, so the quality the floor reads+ // must be the second's 0.1, not the pair's 1.0.+ //+ // This is the case the previous shape got wrong. It filtered the task+ // note out of `coveredElsewhere` but read a coverage number measured+ // over BOTH rows, so the note it was excluding still cleared the floor+ // for it and the task closed on its own text.+ const result = await autoCloseRecalledGaps(+ vault,+ retrieverOverRows([+ { path: GAP_TASK_NOTE, score: 0.99, coverage: 1 },+ { path: ORDINARY_NOTE, score: 0.4, coverage: 0.1 },+ ]),+ { confidenceFloor: 0.5, now: NOW },+ );+ expect(result.closed).toHaveLength(0);+ expect(listGapTasks(vault, { status: GAP_TASK_STATUS_OPEN })).toHaveLength(1);+ });++ test("a retriever that answers outside the membership rule is refused by name", async () => {seedGap("alpha topic", 3);promoteGapsToTasks(vault, { threshold: 2, now: NOW });- // The only confident hit is the gap-task note itself; it must be ignored.- const selfMatch: RecallRetriever = async () =>+ // Ignores `admits` and returns the excluded row anyway. Its quality+ // number therefore describes rows the gate rejects, and reading it+ // would be reading a measurement of something else.+ const ignoresTheRule: GapRecallRetriever = async () =>({candidates: [{- path: "Brain/gap-tasks/gap-abc.md",+ path: GAP_TASK_NOTE,title: "gap",score: 0.99,searchType: "hybrid",@@ -143,8 +233,20 @@ describe("gap loop (A3 / t_67d38036)", () => {},],total: 1,+ idfWeightedCoverage: 1,}) satisfies RecallResultSet;- const result = await autoCloseRecalledGaps(vault, selfMatch, {+ await expect(+ autoCloseRecalledGaps(vault, ignoresTheRule, { confidenceFloor: 0.5, now: NOW }),+ ).rejects.toThrow(GapRecallScopeError);+ expect(listGapTasks(vault, { status: GAP_TASK_STATUS_OPEN })).toHaveLength(1);+ });++ test("keeps a gap task open when recall stays below the confidence floor", async () => {+ seedGap("alpha topic", 3);+ promoteGapsToTasks(vault, { threshold: 2, now: NOW });+ // Coverage below the floor, score far above it: only the gate that+ // reads coverage can keep this task open.+ const result = await autoCloseRecalledGaps(vault, retrieverWithCoverage(0.2, 0.99), {confidenceFloor: 0.5,now: NOW,});@@ -152,10 +254,13 @@ describe("gap loop (A3 / t_67d38036)", () => {expect(listGapTasks(vault, { status: GAP_TASK_STATUS_OPEN })).toHaveLength(1);});- test("keeps a gap task open when recall stays below the confidence floor", async () => {+ test("an unmeasurable recall never closes a task", async () => {seedGap("alpha topic", 3);promoteGapsToTasks(vault, { threshold: 2, now: NOW });- const result = await autoCloseRecalledGaps(vault, retrieverWithScore(0.2), {+ // A confident-looking row with no measurable quality behind it: the+ // exact pair the old `totalIdf === 0 ? 1` produced, which cleared+ // every floor.+ const result = await autoCloseRecalledGaps(vault, retrieverWithCoverage(null, 0.99), {confidenceFloor: 0.5,now: NOW,});diff --git a/tests/core/brain/notes/scaffold-stub.test.ts b/tests/core/brain/notes/scaffold-stub.test.tsindex 9a3037c6..c8963171 100644--- a/tests/core/brain/notes/scaffold-stub.test.ts+++ b/tests/core/brain/notes/scaffold-stub.test.ts@@ -124,6 +124,47 @@ describe("listing dangling targets", () => {expect(scan.state).toBe(DANGLING_SCAN.measured);expect(scan.targets.map((t) => t.target)).toContain("Projects/Ghost");});++ /**+ * a-label-is-not-a-boundary, U3. `sources` are vault-relative document+ * paths and `target` is the link spelling the source wrote, so a+ * dangling listing over an owner-tagged note published both.+ */+ test("an owner scope drops the whole target when every source is hidden", async () => {+ note("Projects/Private.md", `---\nowner: agent-a\n---\n\n[[Projects/PrivateGhost]]\n`);+ note("Projects/Shared.md", "[[Projects/SharedGhost]]\n");+ await indexVault(resolveSearchConfig({ vault }), { force: true });++ const unscoped = await listDanglingTargets(vault);+ expect(unscoped.targets.map((t) => t.target).toSorted()).toEqual([+ "Projects/PrivateGhost",+ "Projects/SharedGhost",+ ]);++ const scoped = await listDanglingTargets(vault, { ownerScope: "agent-b" });+ expect(scoped.state).toBe(DANGLING_SCAN.measured);+ // Not a target with an empty `sources` array - the target string is+ // itself the private note's outbound link, so it goes with it.+ expect(scoped.targets.map((t) => t.target)).toEqual(["Projects/SharedGhost"]);+ expect(JSON.stringify(scoped.targets)).not.toContain("Private");++ const asOwner = await listDanglingTargets(vault, { ownerScope: "agent-a" });+ expect(asOwner.targets.map((t) => t.target).toSorted()).toEqual([+ "Projects/PrivateGhost",+ "Projects/SharedGhost",+ ]);+ });++ test("an owner scope keeps a target that still has a visible source", async () => {+ note("Projects/Private.md", `---\nowner: agent-a\n---\n\n[[Projects/Ghost]]\n`);+ note("Projects/Shared.md", "[[Projects/Ghost]]\n");+ await indexVault(resolveSearchConfig({ vault }), { force: true });++ const scoped = await listDanglingTargets(vault, { ownerScope: "agent-b" });+ const ghost = scoped.targets.find((t) => t.target === "Projects/Ghost");+ expect(ghost).toBeDefined();+ expect([...ghost!.sources]).toEqual(["Projects/Shared.md"]);+ });});describe("scaffolding a stub", () => {diff --git a/tests/core/brain/owner-scope-delivery.test.ts b/tests/core/brain/owner-scope-delivery.test.tsindex 47f8e818..c4e72479 100644--- a/tests/core/brain/owner-scope-delivery.test.ts+++ b/tests/core/brain/owner-scope-delivery.test.ts@@ -36,17 +36,33 @@ import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/braconst OWNER_A = "agent-a";const OWNER_B = "agent-b";const NOW = new Date("2026-05-10T00:00:00Z");+/**+ * The identity the WRITER resolves to for this file.+ *+ * Pinned because `writePreference` refuses to stamp a placeholder+ * (a-label-is-not-a-boundary, U3): with no `agent_name` configured,+ * `resolveAgentName` answers `"agent"`, which owner-scope delivery+ * refuses as an unverifiable identity and therefore also refuses as an+ * owner. Unpinned, the `warn` case below wrote pages owned by the+ * literal `agent` - the state no caller can ever be shown to own.+ */+const WRITER = "agent-writer";let vault: string;+let savedAgentName: string | undefined;beforeEach(() => {vault = mkdtempSync(join(tmpdir(), "o2b-owner-delivery-"));for (const sub of ["preferences", "retired", "inbox", "log"]) {mkdirSync(join(vault, "Brain", sub), { recursive: true });}+ savedAgentName = process.env["VAULT_AGENT_NAME"];+ process.env["VAULT_AGENT_NAME"] = WRITER;});afterEach(() => {rmSync(vault, { recursive: true, force: true });+ if (savedAgentName === undefined) delete process.env["VAULT_AGENT_NAME"];+ else process.env["VAULT_AGENT_NAME"] = savedAgentName;});function setGate(mode: string | null): void {@@ -124,8 +140,13 @@ test("gate off: explicit off behaves exactly like an absent block", () => {});test("gate fail: another owner's preference is absent from every surface", () => {- setGate(GATE_MODE.fail);+ // The shared preference is written BEFORE the gate goes on, because+ // that is the only way a shared one comes to exist: with the gate on,+ // every new preference is stamped with the identity of the agent that+ // wrote it, and a page created before the gate stays shared rather than+ // being retro-owned by whoever rewrites it first.makePref("shared");+ setGate(GATE_MODE.fail);makePref("owned-by-a", OWNER_A);const asB = renderAll(OWNER_B);@@ -143,8 +164,13 @@ test("gate fail: another owner's preference is absent from every surface", () =>});test("gate fail with no scope requested still delivers everything", () => {- setGate(GATE_MODE.fail);+ // The shared preference is written BEFORE the gate goes on, because+ // that is the only way a shared one comes to exist: with the gate on,+ // every new preference is stamped with the identity of the agent that+ // wrote it, and a page created before the gate stays shared rather than+ // being retro-owned by whoever rewrites it first.makePref("shared");+ setGate(GATE_MODE.fail);makePref("owned-by-a", OWNER_A);expect(renderAll()["pack"]).toContain("pref-owned-by-a");@@ -251,8 +277,13 @@ for (const mode of [null, GATE_MODE.off, GATE_MODE.warn]) {* trivially true for it.*/test("a retired memory keeps its owner on every delivery surface", () => {- setGate(GATE_MODE.fail);+ // The shared preference is written BEFORE the gate goes on, because+ // that is the only way a shared one comes to exist: with the gate on,+ // every new preference is stamped with the identity of the agent that+ // wrote it, and a page created before the gate stays shared rather than+ // being retro-owned by whoever rewrites it first.makePref("shared");+ setGate(GATE_MODE.fail);makePref("owned-by-a", OWNER_A);moveToRetired(vault, preferencePath(vault, "owned-by-a"), "stale-no-evidence", {now: NOW,diff --git a/tests/core/brain/owner-scope-view.test.ts b/tests/core/brain/owner-scope-view.test.tsnew file mode 100644index 00000000..f870732c--- /dev/null+++ b/tests/core/brain/owner-scope-view.test.ts@@ -0,0 +1,115 @@+/**+ * The adapter's own fail-closed promise, executed+ * (a-label-is-not-a-boundary, U3).+ *+ * `owner-scope-view.ts` says it FAILS CLOSED, and it decided visibility+ * for fifteen report-shaped surfaces. Two shapes of reference walked+ * straight through it and were reported visible without any ownership+ * being read:+ *+ * - an id whose artifact lives in a `Brain/` directory the resolver+ * did not search. It searched four; `Brain/sources/src-*.md`,+ * `Brain/entities/` and `Brain/pending/` hold id-addressable pages+ * that carry `owner:` the same way, and `brain_search_by_source`+ * already filters the first of them on the search side - so the two+ * halves of the product disagreed about whether a source page can be+ * owned;+ * - a reference still wearing its wikilink brackets. A retirement's+ * `retired_by`, a dream transition's `link` and an evidence row's+ * `artifact` all arrive as `[[…]]` straight out of frontmatter or a+ * log body, and `[[pref-x]]` matched neither the path branch nor the+ * id branch.+ *+ * Both are one-line reads that returned `true`, which is the shape a+ * boundary fails in silence.+ */++import { beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { ownerScopeView } from "../../../src/core/brain/owner-scope-view.ts";++const OWNER_A = "agent-a";+const OWNER_B = "agent-b";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-owner-view-"));+ for (const sub of ["preferences", "retired", "inbox", "pending", "sources", "entities"]) {+ mkdirSync(join(vault, "Brain", sub), { recursive: true });+ }+});++/** An owner-tagged page at a vault-relative path, with a bare id filename. */+function ownedPage(relDir: string, id: string): void {+ writeFileSync(+ join(vault, relDir, `${id}.md`),+ `---\nid: ${id}\nowner: ${OWNER_A}\n---\n\nbody of ${id}\n`,+ );+}++/**+ * Every `Brain/` directory holding id-addressable Markdown that can+ * carry `owner:`. A directory missing from the resolver makes its pages+ * silently unownable, so the population is asserted directly.+ */+const OWNER_TAGGABLE_DIRS = [+ ["Brain/preferences", "pref-owned"],+ ["Brain/retired", "ret-owned"],+ ["Brain/inbox", "sig-2026-05-01-owned"],+ ["Brain/pending", "sig-2026-05-02-owned"],+ ["Brain/sources", "src-owned"],+ ["Brain/entities", "ent-owned"],+] as const;++for (const [dir, id] of OWNER_TAGGABLE_DIRS) {+ test(`an id-shaped reference to ${dir} is hidden from another owner`, () => {+ ownedPage(dir, id);+ const view = ownerScopeView(vault, OWNER_B);+ expect(view.visible(id), `${dir}/${id}.md declares owner: ${OWNER_A}`).toBe(false);+ // Its own owner still sees it, so the rule is not a blanket hide.+ expect(ownerScopeView(vault, OWNER_A).visible(id)).toBe(true);+ });+}++test("a wikilink-shaped reference resolves to the same page as its bare id", () => {+ ownedPage("Brain/preferences", "pref-owned");+ const view = ownerScopeView(vault, OWNER_B);+ for (const ref of [+ "pref-owned",+ "[[pref-owned]]",+ "Brain/preferences/pref-owned.md",+ "[[Brain/preferences/pref-owned.md]]",+ ]) {+ expect(`${ref} -> ${String(view.visible(ref))}`).toBe(`${ref} -> false`);+ }+});++test("a reference naming nothing on disk is visible, and so is an empty one", () => {+ const view = ownerScopeView(vault, OWNER_B);+ // A row with no subject cannot disclose one; an id with no artifact+ // names nothing that could be owned.+ for (const ref of [null, undefined, "", "pref-never-existed", "[[pref-never-existed]]"]) {+ expect(view.visible(ref)).toBe(true);+ }+});++test("an unscoped view reads nothing and hides nothing", () => {+ ownedPage("Brain/sources", "src-owned");+ const view = ownerScopeView(vault, null);+ expect(view.scope).toBeNull();+ expect(view.visible("src-owned")).toBe(true);+ expect(view.row("src-owned", "[[src-owned]]")).toBe(true);+});++test("one hidden reference hides the whole row", () => {+ ownedPage("Brain/sources", "src-owned");+ const view = ownerScopeView(vault, OWNER_B);+ expect(view.row("pref-never-existed", "[[src-owned]]")).toBe(false);+ expect(+ view.keep([{ refs: ["[[src-owned]]"] }, { refs: ["pref-never-existed"] }], (r) => r.refs),+ ).toHaveLength(1);+});diff --git a/tests/core/brain/owner-stamp.test.ts b/tests/core/brain/owner-stamp.test.tsnew file mode 100644index 00000000..1c7dd529--- /dev/null+++ b/tests/core/brain/owner-stamp.test.ts@@ -0,0 +1,580 @@+/**+ * Ownership is WRITTEN, or it is not a boundary.+ *+ * `integrity.owner_scope_delivery` withholds a preference whose+ * `owner:` frontmatter names another agent, and every read-side surface+ * honours it. Nothing wrote the field. Every production writer omitted+ * `owner`, so `pageOwner` returned `null` for every page ever produced+ * by this product, `isOwnerVisible` was trivially true, and the gate+ * filtered a population that could not exist. A predicate over an empty+ * set is a label, not a boundary.+ *+ * This file is the enforcement: with the gate switched on, a preference+ * created through any production writer carries the server-resolved+ * agent identity as its owner; with the gate off, not one byte moves.+ *+ * Two properties are load-bearing and asserted separately:+ *+ * - ownership is stamped at CREATION only. A rewrite carries the+ * existing owner forward and never re-owns, so a dream pass run by+ * one agent cannot quietly transfer another agent's memories, and a+ * page created before the gate was switched on stays shared.+ * - the identity is SERVER-resolved. No test in this file passes an+ * `owner` argument to reach the withholding assertion; the vault is+ * written entirely through shipped surfaces.+ */++import { afterEach, beforeEach, expect, setDefaultTimeout, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../../src/mcp/index.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { deriveFact } from "../../../src/core/brain/derived-fact.ts";+import { mergePreferences } from "../../../src/core/brain/merge.ts";+import { brainConfigPath, brainDirs, preferencePath } from "../../../src/core/brain/paths.ts";+import { brainConfigKnownKeys } from "../../../src/core/brain/policy.ts";+import { parsePreference, writePreference } from "../../../src/core/brain/preference.ts";+import { PLACEHOLDER_AGENT_VALUES } from "../../../src/core/agent-identity.ts";+import { ownerStampFor } from "../../../src/core/graph/agent-scope.ts";+import { writePreferenceTxn } from "../../../src/core/brain/preference-txn.ts";+import {+ collectPreferences,+ type OwnerScopeDelivery,+} from "../../../src/core/brain/preferences-collect.ts";+import { resetVaultIdentityPins } from "../../../src/core/brain/vault-identity.ts";+import { BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";+import { GATE_MODE } from "../../../src/core/integrity/stamp.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import { CLI_SPAWN_BUDGET_MS } from "../../helpers/cli-timeout.ts";+import { changedPaths, digestVaultFiles, digestVaultTree } from "../../helpers/vault-digest.ts";+import { runCli } from "../../helpers/run-cli.ts";++setDefaultTimeout(CLI_SPAWN_BUDGET_MS);++/** Wall clock every core writer in this file is pinned to. */+const NOW = new Date("2026-05-10T00:00:00Z");+/** The identity the ambient config resolves to, i.e. what a writer stamps. */+const SELF = "agent-self";+/** A second identity, used to prove the withholding is not vacuous. */+const OTHER = "agent-other";++/**+ * Env this file owns. `HOME` is pinned per test file by convention+ * (nothing pins it globally) and the identity vars are cleared so the+ * developer's own install cannot decide what a writer stamps.+ */+const OWNED_ENV = [+ "HOME",+ "VAULT_AGENT_NAME",+ "VAULT_DIR",+ "VAULT_TIMEZONE",+ "OPEN_SECOND_BRAIN_CONFIG",+] as const;++let tmp: string;+let home: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-owner-stamp-"));+ home = join(tmp, "home");+ mkdirSync(home, { recursive: true });+ for (const key of OWNED_ENV) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }+ process.env["HOME"] = home;+ resetVaultIdentityPins();+});++afterEach(() => {+ resetVaultIdentityPins();+ rmSync(tmp, { recursive: true, force: true });+ for (const [key, value] of Object.entries(savedEnv)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+});++/** A bare vault: Brain directories and a `_brain.yaml`, nothing else. */+function makeVault(name: string, gate: string | null, agent = SELF): string {+ const vault = join(tmp, name);+ for (const sub of ["preferences", "retired", "inbox", "log"]) {+ mkdirSync(join(vault, "Brain", sub), { recursive: true });+ }+ atomicWriteFileSync(+ brainConfigPath(vault),+ `schema_version: 1\n${gate === null ? "" : `integrity:\n owner_scope_delivery: ${gate}\n`}`,+ );+ const configPath = join(tmp, `${name}-config.yaml`);+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: ${agent}\n`);+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ return vault;+}++/** The `owner:` a preference file carries on disk, or `null`. */+function ownerOf(vault: string, slug: string): string | null {+ return parsePreference(preferencePath(vault, slug)).owner ?? null;+}++/** Minimal valid preference input; never carries an `owner`. */+function prefInput(slug: string): Parameters<typeof writePreference>[1] {+ return {+ slug,+ topic: slug,+ principle: `principle for ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],+ confirmed_at: "2026-05-02T00:00:00Z",+ };+}++/** A gate verdict that actually withholds, i.e. `fail` with a scope. */+function enforcing(scope: string): OwnerScopeDelivery {+ return { mode: GATE_MODE.fail, enforcedScope: scope, requestedScope: scope };+}++/**+ * Every core writer that creates a preference, driven once, under a+ * pinned clock. The two feedback surfaces are excluded here and covered+ * by their own tests: both stamp `new Date()` into the signal they write+ * alongside the preference, so two runs can never be byte-identical.+ */+function writeThroughEveryCoreWriter(vault: string): void {+ writePreference(vault, prefInput("direct"));+ writePreferenceTxn(vault, prefInput("txn"), []);+ writePreference(vault, prefInput("premise"));+ deriveFact(+ vault,+ {+ slug: "derived",+ topic: "derived",+ principle: "a derived rule",+ level: "deduced",+ premises: ["pref-premise"],+ },+ { now: NOW },+ );+ writePreference(vault, { ...prefInput("merge-keep"), topic: "merge" });+ writePreference(vault, { ...prefInput("merge-drop"), topic: "merge" });+ mergePreferences(vault, "pref-merge-keep", "pref-merge-drop", { now: NOW, agentName: SELF });+}++async function callTool(+ server: MCPServer,+ name: string,+ args: Record<string, unknown>,+): Promise<{ isError: boolean; structuredContent: Record<string, unknown> }> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "owner-stamp", version: "0" },+ },+ });+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });+ const response = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/call",+ params: { name, arguments: args },+ })) as { result: { isError: boolean; structuredContent: Record<string, unknown> } };+ return response.result;+}++// ----- The gate on: every production writer stamps ---------------------------++test("gate fail: every core preference writer stamps the resolved identity", () => {+ const vault = makeVault("stamped", GATE_MODE.fail);+ writeThroughEveryCoreWriter(vault);++ for (const slug of ["direct", "txn", "derived"]) {+ expect(`${slug}=${ownerOf(vault, slug)}`).toBe(`${slug}=${SELF}`);+ }+});++test("gate warn: ownership is written so the operator can watch what fail would remove", () => {+ const vault = makeVault("warned", GATE_MODE.warn);+ writePreference(vault, prefInput("direct"));++ expect(ownerOf(vault, "direct")).toBe(SELF);+});++test("gate fail: the MCP feedback writer stamps the server-resolved identity", async () => {+ const vault = makeVault("mcp", GATE_MODE.fail);+ const configPath = process.env["OPEN_SECOND_BRAIN_CONFIG"] as string;+ const result = await callTool(new MCPServer({ vault, configPath }), "brain_feedback", {+ topic: "mcp-topic",+ signal: "positive",+ principle: "A rule recorded through the MCP writer.",+ force_confirmed: true,+ });++ expect(result.isError).toBe(false);+ expect(ownerOf(vault, "mcp-topic")).toBe(SELF);+});++test("gate fail: the CLI feedback writer stamps the server-resolved identity", async () => {+ const vault = makeVault("cli", GATE_MODE.fail);+ const configPath = process.env["OPEN_SECOND_BRAIN_CONFIG"] as string;+ const run = await runCli(+ [+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ "cli-topic",+ "--signal",+ "positive",+ "--principle",+ "A rule recorded through the CLI writer.",+ "--force-confirmed",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath, HOME: home } },+ );++ expect(`exit ${run.returncode}\n${run.stderr}`).toBe("exit 0\n");+ expect(ownerOf(vault, "cli-topic")).toBe(SELF);+});++// ----- Creation-only: a rewrite never re-owns --------------------------------++test("a rewrite carries the existing owner forward and never transfers ownership", () => {+ const vault = makeVault("carry", GATE_MODE.fail, OTHER);+ writePreference(vault, prefInput("owned"));+ expect(ownerOf(vault, "owned")).toBe(OTHER);++ // A second agent rewrites the same preference. Ownership must not move.+ atomicWriteFileSync(+ process.env["OPEN_SECOND_BRAIN_CONFIG"] as string,+ `vault: ${vault}\nagent_name: ${SELF}\n`,+ );+ writePreference(vault, { ...prefInput("owned"), principle: "rewritten" }, { overwrite: true });+ expect(ownerOf(vault, "owned")).toBe(OTHER);+});++test("a page that predates the gate stays shared when the gate is switched on", () => {+ const vault = makeVault("legacy", GATE_MODE.off);+ writePreference(vault, prefInput("legacy"));+ expect(ownerOf(vault, "legacy")).toBeNull();++ // REWRITTEN, not appended: `makeVault` already emitted an `integrity:`+ // block for the `off` gate, and appending a second one produces a+ // duplicate top-level key - i.e. a config the parser rejects. That is+ // the F5 condition, not this test's subject, and a writer now refuses+ // it rather than inferring an owner from a file it could not read.+ atomicWriteFileSync(+ brainConfigPath(vault),+ `schema_version: 1\nintegrity:\n owner_scope_delivery: ${GATE_MODE.fail}\n`,+ );+ writePreference(vault, { ...prefInput("legacy"), principle: "rewritten" }, { overwrite: true });+ expect(ownerOf(vault, "legacy")).toBeNull();+});++test("merge keeps the surviving preference's owner instead of stripping it", () => {+ const vault = makeVault("merged", GATE_MODE.fail);+ writeThroughEveryCoreWriter(vault);++ expect(ownerOf(vault, "merge-keep")).toBe(SELF);+});++test("an explicit caller-supplied owner still wins over the resolved identity", () => {+ const vault = makeVault("explicit", GATE_MODE.fail);+ writePreference(vault, { ...prefInput("explicit"), owner: OTHER });++ expect(ownerOf(vault, "explicit")).toBe(OTHER);+});++// ----- The gate off: not one byte moves --------------------------------------++test("gate off: two vaults written by the same script are byte-identical and ownerless", () => {+ const first = makeVault("digest-a", GATE_MODE.off);+ writeThroughEveryCoreWriter(first);+ const second = makeVault("digest-b", GATE_MODE.off);+ writeThroughEveryCoreWriter(second);++ // `_brain.yaml` names the vault only through the config file outside+ // the tree, so the two trees are comparable file-for-file.+ expect(digestVaultTree(second)).toBe(digestVaultTree(first));+ expect(changedPaths(digestVaultFiles(first), digestVaultFiles(second))).toEqual([]);++ const dir = brainDirs(first).preferences;+ for (const file of collectPreferences(dir).entries) {+ expect(`${file.name}: ${readFileSync(file.path, "utf8")}`).not.toContain("\nowner:");+ }+});++test("gate off vs gate fail: the only files that differ are the preferences", () => {+ const off = makeVault("off-tree", GATE_MODE.off);+ writeThroughEveryCoreWriter(off);+ const on = makeVault("on-tree", GATE_MODE.fail);+ writeThroughEveryCoreWriter(on);++ // `retired/` is in the expected set on purpose: `moveToRetired` copies+ // every inherited field, so retiring an owner-private memory must not+ // publish it. Nothing else in the tree may move.+ const differing = changedPaths(digestVaultFiles(off), digestVaultFiles(on)).filter(+ (path) => path !== "Brain/_brain.yaml",+ );+ expect(+ differing.filter(+ (path) => !path.startsWith("Brain/preferences/") && !path.startsWith("Brain/retired/"),+ ),+ ).toEqual([]);+ expect(differing.length).toBeGreaterThan(0);+});++// ----- No new config key ------------------------------------------------------++test("owner stamping adds no config key: the integrity block is unchanged", () => {+ const known = brainConfigKnownKeys();+ expect([...(known.subKeys.get("integrity") ?? [])].toSorted()).toEqual([+ "embedding_abi",+ "owner_scope_delivery",+ "pack_validity_seconds",+ ]);+});++// ----- The boundary, on a vault written entirely through production surfaces ---++test("withholding works on a vault no test-only owner argument ever touched", async () => {+ const vault = makeVault("two-agents", GATE_MODE.fail, SELF);+ const selfConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"] as string;+ bootstrapBrain(vault, { configPath: selfConfig });++ await callTool(new MCPServer({ vault, configPath: selfConfig }), "brain_feedback", {+ topic: "self-rule",+ signal: "positive",+ principle: "A rule only the first agent may read.",+ force_confirmed: true,+ });++ const otherConfig = join(tmp, "other-config.yaml");+ atomicWriteFileSync(otherConfig, `vault: ${vault}\nagent_name: ${OTHER}\n`);+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = otherConfig;+ await callTool(new MCPServer({ vault, configPath: otherConfig }), "brain_feedback", {+ topic: "other-rule",+ signal: "positive",+ principle: "A rule only the second agent may read.",+ force_confirmed: true,+ });++ const dir = brainDirs(vault).preferences;+ const asSelf = collectPreferences(dir, { ownerScope: enforcing(SELF) });+ const asOther = collectPreferences(dir, { ownerScope: enforcing(OTHER) });++ expect(asSelf.entries.map((e) => e.pref.id)).toEqual(["pref-self-rule"]);+ expect(asOther.entries.map((e) => e.pref.id)).toEqual(["pref-other-rule"]);+ expect(asSelf.hiddenByOwnerScope).toBe(1);+});++// ----- An identity that cannot be reduced to a token is a refusal --------------++test("an unusable resolved identity refuses the write instead of hiding the page", () => {+ const vault = makeVault("blank-identity", GATE_MODE.fail);+ process.env["VAULT_AGENT_NAME"] = " ";++ expect(() => writePreference(vault, prefInput("blank"))).toThrow(/owner/i);+});++/**+ * F4: an unconfigured install must not become a real owner named `agent`.+ *+ * `resolveAgentName` never fails - it returns `UNCONFIGURED_AGENT_NAME`,+ * the literal `"agent"` - and `ownerStampFor` accepted it, so a vault+ * with the gate on and no `agent_name` accumulated preferences owned by+ * `agent` while `refuseOwnerScopeRequest` refused every caller asking to+ * be answered as `agent` because that name is unverifiable. The two+ * halves must agree: the predicate that refuses the placeholder as an+ * identity is the one that prevents it becoming an owner.+ */+test("gate fail: the placeholder identity refuses the write instead of owning the page", () => {+ const vault = join(tmp, "unconfigured");+ for (const sub of ["preferences", "retired", "inbox", "log"]) {+ mkdirSync(join(vault, "Brain", sub), { recursive: true });+ }+ atomicWriteFileSync(+ brainConfigPath(vault),+ `schema_version: 1\nintegrity:\n owner_scope_delivery: ${GATE_MODE.fail}\n`,+ );+ // A config with NO `agent_name`: the state `resolveAgentName` answers+ // with the placeholder.+ const configPath = join(tmp, "unconfigured-config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;++ expect(() => writePreference(vault, prefInput("unowned"))).toThrow(/placeholder/i);+ expect(existsSync(preferencePath(vault, "unowned"))).toBe(false);+});++test("every placeholder identity is refused as an owner, not just the bare default", () => {+ for (const name of PLACEHOLDER_AGENT_VALUES) {+ expect(`${name} -> ${String(ownerStampFor(name))}`).toBe(`${name} -> null`);+ }+ // A real name still stamps, so the refusal is not a blanket one.+ expect(ownerStampFor("claude-vps-agent")).toBe("claude-vps-agent");+});++/**+ * F5: an unreadable `_brain.yaml` silently switched stamping ON, forever.+ *+ * `loadIntegrityConfigSafe`'s strict fallback is scoped to READERS - "the+ * unreadable config cannot loosen a gate, it can only close one" - and a+ * writer was wired to it. Strict here means STAMP, so one bad token in+ * the YAML made every new preference carry an owner the operator never+ * asked for, and ownership is carried forward, so the pages outlived the+ * repair of the typo.+ */+test("an unreadable Brain config refuses the write rather than inferring an owner", () => {+ const vault = makeVault("unreadable-config", GATE_MODE.off);+ atomicWriteFileSync(brainConfigPath(vault), "schema_version: 1\nintegrity: [ this is not yaml\n");++ let message = "";+ try {+ writePreference(vault, prefInput("guessed"));+ } catch (err) {+ message = (err as Error).message;+ }+ // Explicit on both counts: it names the unreadable config, and it says+ // the writer will not guess - never a silent stamp, never a silent skip.+ expect(message).toContain("Brain/_brain.yaml");+ expect(existsSync(preferencePath(vault, "guessed"))).toBe(false);+});++test("an ABSENT Brain config still writes, ownerless, as the documented default", () => {+ // The other half of the reader/writer split: absent is not unreadable.+ const vault = join(tmp, "no-config");+ for (const sub of ["preferences", "retired", "inbox", "log"]) {+ mkdirSync(join(vault, "Brain", sub), { recursive: true });+ }+ const configPath = join(tmp, "no-config-config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: ${SELF}\n`);+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;++ writePreference(vault, prefInput("defaulted"));+ expect(ownerOf(vault, "defaulted")).toBeNull();+});++/**+ * A3: the writer census - "every production writer stamps" measured, not+ * listed.+ *+ * The claim above this line used to be held true by+ * {@link writeThroughEveryCoreWriter}, a HAND-WRITTEN list of four+ * writers. `import-claude-memory.ts` renders its own frontmatter and+ * calls `atomicWriteFileSync` directly, so it was not on the list, never+ * reached `withResolvedOwner`, and shipped every imported memory+ * ownerless into a gated vault. A list is the failure mode this release+ * is about.+ *+ * The population is SYNTACTIC and read off source: a module that both+ * builds a preference path and writes bytes is a preference writer. Each+ * one must reach the shared ownership resolution - `writePreference`,+ * `writePreferenceTxn` or `resolvedOwnerFor` - or carry an entry here+ * saying what it does instead. Never both, never neither.+ */+const PREFERENCE_PATH_BUILDERS = ["preferencePath(", "retiredPath("];+const FS_BYTE_WRITES = [+ "atomicWriteFileSync(",+ "writeFileSync(",+ "appendFileSync(",+ "renameSync(",+ "copyFileSync(",+ "cpSync(",+ "writeFrontmatterAtomic(",+];+/** The three entry points that resolve ownership for a new preference. */+const OWNERSHIP_RESOLVERS = ["writePreference(", "writePreferenceTxn(", "resolvedOwnerFor("];++/** Modules in the syntactic population that write no preference bytes. */+const NO_PREFERENCE_BYTES: Readonly<Record<string, string>> = Object.freeze({+ "src/core/brain/write-batch.ts":+ "builds a preference path only to ASSERT the target exists before an apply-evidence " ++ "operation; every byte it writes goes to a caller-named note path.",+ "src/core/brain/pin.ts":+ "flips ONE existing frontmatter field on an EXISTING page (`{...meta, pinned}`) and never " ++ "creates one, so the `owner:` already on disk is preserved by construction - the same " ++ "outcome the carry-forward branch of the resolver produces, reached without re-deriving it.",+ "src/core/brain/health/remediation.ts":+ "re-stamps ONE derived frontmatter field (`_content_hash`) on an EXISTING page by spreading " ++ "the parsed metadata, so ownership travels untouched and nothing new is created.",+});++test("every module that writes preference bytes reaches the ownership resolver", async () => {+ const { readFileSync: readFile } = await import("node:fs");+ const { lexSource } = await import("../../helpers/source-lexer.ts");+ const root = join(import.meta.dir, "..", "..", "..", "src");++ const walk = (dir: string): string[] =>+ readdirSync(dir, { withFileTypes: true }).flatMap((e) =>+ e.isDirectory() ? walk(join(dir, e.name)) : e.name.endsWith(".ts") ? [join(dir, e.name)] : [],+ );+ const offenders: string[] = [];+ for (const abs of walk(root)) {+ const rel = abs.slice(abs.indexOf("src/"));+ if (rel === "src/core/brain/preference.ts") continue; // the resolver's own home+ const code = lexSource(readFile(abs, "utf8")).code;+ const buildsPath = PREFERENCE_PATH_BUILDERS.some((p) => code.includes(p));+ const writesBytes = FS_BYTE_WRITES.some((p) => code.includes(p));+ if (!buildsPath || !writesBytes) continue;+ if (OWNERSHIP_RESOLVERS.some((p) => code.includes(p))) continue;+ if (rel in NO_PREFERENCE_BYTES) continue;+ offenders.push(rel);+ }++ expect(+ offenders,+ "each of these writes preference bytes without reaching the ownership resolver; " ++ "route it through one, or declare it in NO_PREFERENCE_BYTES with a reason",+ ).toEqual([]);+});++test("the claude-memory importer stamps the resolved identity like every other writer", async () => {+ const vault = makeVault("imported", GATE_MODE.fail);+ const memoryDir = join(tmp, "memory");+ mkdirSync(memoryDir, { recursive: true });+ atomicWriteFileSync(+ join(memoryDir, "feedback_probe.md"),+ "---\ntype: feedback\nname: feedback probe\ndescription: An imported rule.\n---\n\nscope: writing\n",+ );++ const { importClaudeMemory } = await import("../../../src/core/brain/import-claude-memory.ts");+ const result = importClaudeMemory({+ vault,+ memoryDir,+ mode: "apply",+ now: NOW,+ allowArbitraryMemoryPath: true,+ });+ expect(result.applied.length).toBe(1);++ expect(ownerOf(vault, "feedback-probe")).toBe(SELF);+});++test("with the gate off the importer writes no owner at all", async () => {+ const vault = makeVault("imported-off", GATE_MODE.off);+ const memoryDir = join(tmp, "memory-off");+ mkdirSync(memoryDir, { recursive: true });+ atomicWriteFileSync(+ join(memoryDir, "feedback_probe.md"),+ "---\ntype: feedback\nname: feedback probe\ndescription: An imported rule.\n---\n\nscope: writing\n",+ );++ const { importClaudeMemory } = await import("../../../src/core/brain/import-claude-memory.ts");+ importClaudeMemory({+ vault,+ memoryDir,+ mode: "apply",+ now: NOW,+ allowArbitraryMemoryPath: true,+ });+ expect(ownerOf(vault, "feedback-probe")).toBeNull();+});diff --git a/tests/core/brain/portability/okf.test.ts b/tests/core/brain/portability/okf.test.tsindex d6049d78..5de097bb 100644--- a/tests/core/brain/portability/okf.test.ts+++ b/tests/core/brain/portability/okf.test.ts@@ -88,6 +88,52 @@ describe("buildOkfBundle", () => {expect(page).toContain("body.");});+ test("a per-device log shard is a log day, not an invisible file", () => {+ // `Brain/log/` writes `<date>.<deviceId>.md` on every default install+ // since the per-device shard layout landed, so a pattern that matched+ // only the legacy un-sharded name reported `0 log day(s)` and an empty+ // `log.md` for a vault with a full change log.+ note("Brain/log/2026-06-01.bb4363ed.md", "- sharded entry\n");+ note("Brain/log/2026-06-02.md", "- legacy entry\n");++ const bundle = buildOkfBundle(vault);+ const log = fileOf(bundle.files, "log.md");+ expect(log).toContain("## 2026-06-01");+ expect(log).toContain("sharded entry");+ expect(bundle.manifest.log_days).toBe(2);+ });++ test("two shards of one day fold into one dated section", () => {+ note("Brain/log/2026-06-01.aaaaaaaa.md", "- from device a\n");+ note("Brain/log/2026-06-01.bbbbbbbb.md", "- from device b\n");++ const bundle = buildOkfBundle(vault);+ const log = fileOf(bundle.files, "log.md");+ expect(log.match(/## 2026-06-01/g)?.length).toBe(1);+ expect(log).toContain("from device a");+ expect(log).toContain("from device b");+ expect(bundle.manifest.log_days).toBe(1);+ });++ test("a `private: true` page exports in full - the key is not a boundary", () => {+ // Retraction, asserted rather than assumed. Nothing under+ // `portability/` reads this frontmatter key, the export composers are+ // content composers rather than visibility filters, and the+ // `<private>` REGION marker is the product's only content-derived+ // privacy primitive. The test exists so the label cannot be re-read as+ // a boundary by a later reader.+ note(+ "Notes/Labelled.md",+ "---\ntitle: Labelled\nprivate: true\ntags: [private, confidential]\n---\nsalary discussion.\n",+ );++ const bundle = buildOkfBundle(vault);+ const page = fileOf(bundle.files, "concepts/Labelled.md");+ expect(page).toContain("private: true");+ expect(page).toContain("salary discussion.");+ expect(bundle.manifest.pages.map((p) => p.path)).toContain("Notes/Labelled.md");+ });+test("excludes Brain machinery (preferences, inbox) from pages", () => {note("Notes/Real.md", "---\ntitle: Real\n---\nx\n");note("Brain/preferences/pref-foo.md", "---\nid: pref-foo\n---\nrule\n");diff --git a/tests/core/brain/pre-compact-extract.test.ts b/tests/core/brain/pre-compact-extract.test.tsindex f6a4460b..668d2a36 100644--- a/tests/core/brain/pre-compact-extract.test.ts+++ b/tests/core/brain/pre-compact-extract.test.ts@@ -5,6 +5,7 @@ import { join } from "node:path";import { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";import { extractPreCompactRecords } from "../../../src/core/brain/pre-compact-extract.ts";+import { lexSource } from "../../helpers/source-lexer.ts";let vault: string;@@ -152,7 +153,10 @@ describe("the label recognizer is structural, not a natural-language word list",const source = await Bun.file(new URL("../../../src/core/brain/pre-compact-extract.ts", import.meta.url).pathname,).text();- const code = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");+ // The shared census lexer. `withoutComments`, not `code`: a word list+ // would be written as string literals, and the code view would blank+ // exactly what this test is looking for.+ const code = lexSource(source).withoutComments;for (const word of ["decision", "commitment", "outcome", "rule", "open question"]) {expect(code.toLowerCase()).not.toContain(word);}diff --git a/tests/core/brain/query-demand.test.ts b/tests/core/brain/query-demand.test.tsindex de068614..4ed7afe5 100644--- a/tests/core/brain/query-demand.test.ts+++ b/tests/core/brain/query-demand.test.ts@@ -45,8 +45,14 @@ describe("normalizeQueryTerms", () => {expect(terms.some((t) => t.includes("REDACTED"))).toBe(false);});- test("empty when no significant terms", () => {- expect(normalizeQueryTerms("a it")).toEqual([]);+ test("empty only when the query carries no word characters at all", () => {+ // Short tokens are terms now. The three-character floor that dropped+ // them was an English-shaped stopword rule: it also erased every+ // one- and two-character CJK query, so a whole class of recall gap+ // could never form a bucket and was invisible to the promotion loop.+ expect(normalizeQueryTerms("a it")).toEqual(["a", "it"]);+ expect(normalizeQueryTerms("検索")).toEqual(["検索"]);+ expect(normalizeQueryTerms("?? -- ??")).toEqual([]);});});@@ -74,7 +80,8 @@ describe("recordQueryDemand", () => {});test("does not record a query with no significant terms", () => {- const record = recordQueryDemand(vault, { query: "a of to", resultCount: 5 });+ // Punctuation only: nothing to bucket in any language.+ const record = recordQueryDemand(vault, { query: "?!? ...", resultCount: 5 });expect(record).toBeNull();expect(existsSync(queryDemandLogPath(vault))).toBe(false);});diff --git a/tests/core/brain/recall-adequacy.test.ts b/tests/core/brain/recall-adequacy.test.tsindex 1e25a263..0164765a 100644--- a/tests/core/brain/recall-adequacy.test.ts+++ b/tests/core/brain/recall-adequacy.test.ts@@ -5,31 +5,61 @@ import {DEFAULT_RECALL_ADEQUACY_THRESHOLDS,} from "../../../src/core/brain/recall-adequacy.ts";-test("a strong top hit is sufficient and proceeds", () => {- const verdict = assessRecallAdequacy([0.82, 0.5, 0.31]);+/**+ * Three usable scores, so `minResults` is never what a case turns on -+ * and all three deliberately BELOW every threshold in this file.+ *+ * The scores in these fixtures used to echo the match quality beside+ * them, and a fixture where the two agree cannot tell this function from+ * the substitution it exists to have removed: reverting the verdict to+ * `topScore >=` left ten of these thirteen cases green. Every case below+ * now puts the score on the opposite side of the boundary from the+ * quality, so the substitution fails on each of them by name.+ */+const THREE_SCORES: ReadonlyArray<number> = [0.28, 0.2, 0.1];++test("strong coverage is sufficient and proceeds", () => {+ const verdict = assessRecallAdequacy({ matchQuality: 0.82, scores: THREE_SCORES });expect(verdict.level).toBe("sufficient");expect(verdict.action).toBe("proceed");expect(verdict.escalate).toBe(false);- expect(verdict.topScore).toBeCloseTo(0.82);+ expect(verdict.matchQuality).toBeCloseTo(0.82);expect(verdict.resultCount).toBe(3);+ // Every score is under the `weak` floor, so nothing but the coverage+ // could have produced `sufficient`.+ expect(verdict.topScore).toBeLessThan(DEFAULT_RECALL_ADEQUACY_THRESHOLDS.weak);});-test("a middling top hit is weak and triggers re-recall", () => {- const verdict = assessRecallAdequacy([0.42, 0.3]);+test("middling coverage is weak and triggers re-recall", () => {+ const verdict = assessRecallAdequacy({ matchQuality: 0.42, scores: [0.9, 0.85] });expect(verdict.level).toBe("weak");expect(verdict.action).toBe("re_recall");expect(verdict.escalate).toBe(false);});-test("a poor top hit is insufficient, abstains, and escalates", () => {- const verdict = assessRecallAdequacy([0.12, 0.08]);+test("poor coverage is insufficient, abstains, and escalates", () => {+ const verdict = assessRecallAdequacy({ matchQuality: 0.12, scores: [0.9, 0.85] });expect(verdict.level).toBe("insufficient");expect(verdict.action).toBe("abstain");expect(verdict.escalate).toBe(true);});+test("the level is decided by coverage, never by the top score", () => {+ // The regression this unit exists to prevent. Both attempts carry the+ // score the shipped keyword lane pins its top row at, so under the old+ // score-driven rule both graded `sufficient` and `weak` was unreachable.+ const pinnedTopRow: ReadonlyArray<number> = [0.6, 0.3];+ const weak = assessRecallAdequacy({ matchQuality: 0.31, scores: pinnedTopRow });+ const strong = assessRecallAdequacy({ matchQuality: 0.95, scores: pinnedTopRow });+ expect(weak.level).toBe("weak");+ expect(strong.level).toBe("sufficient");+ expect(weak.topScore).toBe(strong.topScore);+});+test("no results is insufficient with zero scores and escalates", () => {- const verdict = assessRecallAdequacy([]);+ // Coverage can be high while nothing survived the filter stack, and the+ // verdict still has to abstain: there is no material to ground on.+ const verdict = assessRecallAdequacy({ matchQuality: 0.9, scores: [] });expect(verdict.level).toBe("insufficient");expect(verdict.action).toBe("abstain");expect(verdict.escalate).toBe(true);@@ -38,29 +68,39 @@ test("no results is insufficient with zero scores and escalates", () => {expect(verdict.resultCount).toBe(0);});-test("min_results downgrades a strong-but-lonely hit to weak/re-recall", () => {- const verdict = assessRecallAdequacy([0.9], { minResults: 2 });+test("min_results downgrades strong-but-lonely coverage to weak/re-recall", () => {+ const verdict = assessRecallAdequacy({ matchQuality: 0.9, scores: [0.1] }, { minResults: 2 });expect(verdict.level).toBe("weak");expect(verdict.action).toBe("re_recall");expect(verdict.escalate).toBe(false);});test("custom thresholds move the boundaries", () => {- // Raise the sufficient floor so 0.7 is no longer sufficient.- const verdict = assessRecallAdequacy([0.7, 0.4], { sufficient: 0.8, weak: 0.5 });+ // Raise the sufficient floor so 0.7 coverage is no longer sufficient.+ const verdict = assessRecallAdequacy(+ // Scores above the raised floor, coverage below it: the substitution+ // would grade this `sufficient`.+ { matchQuality: 0.7, scores: [0.95, 0.9] },+ { sufficient: 0.8, weak: 0.5 },+ );expect(verdict.level).toBe("weak");});-test("non-finite scores are ignored; the rest still classify", () => {- const verdict = assessRecallAdequacy([Number.NaN, Infinity, 0.75]);+test("non-finite scores are ignored; the count still reflects the rest", () => {+ const verdict = assessRecallAdequacy({+ matchQuality: 0.75,+ scores: [Number.NaN, Infinity, 0.1],+ });expect(verdict.resultCount).toBe(1);expect(verdict.level).toBe("sufficient");- expect(verdict.topScore).toBeCloseTo(0.75);+ expect(verdict.topScore).toBeCloseTo(0.1);});test("negative scores clamp to zero", () => {- const verdict = assessRecallAdequacy([-0.3, 0.05]);- expect(verdict.topScore).toBeCloseTo(0.05);+ const verdict = assessRecallAdequacy({ matchQuality: 0.05, scores: [-0.3, 0.95] });+ expect(verdict.topScore).toBeCloseTo(0.95);+ // A confident-looking top row over material that covers almost none of+ // the query: insufficient, and the score had no say.expect(verdict.level).toBe("insufficient");});@@ -73,12 +113,27 @@ test("defaults are the documented 0.6 / 0.3 / 1", () => {});test("invalid thresholds throw", () => {- expect(() => assessRecallAdequacy([0.5], { sufficient: 0.2, weak: 0.5 })).toThrow();- expect(() => assessRecallAdequacy([0.5], { sufficient: 1.5 })).toThrow();- expect(() => assessRecallAdequacy([0.5], { minResults: 0 })).toThrow();+ const attempt = { matchQuality: 0.5, scores: [0.5] };+ expect(() => assessRecallAdequacy(attempt, { sufficient: 0.2, weak: 0.5 })).toThrow();+ expect(() => assessRecallAdequacy(attempt, { sufficient: 1.5 })).toThrow();+ expect(() => assessRecallAdequacy(attempt, { minResults: 0 })).toThrow();+});++test("a match quality outside [0,1] throws rather than clamping", () => {+ // Clamping would turn a broken measurement into a confident+ // `insufficient` indistinguishable from a genuine one.+ expect(() => assessRecallAdequacy({ matchQuality: 1.4, scores: [0.5] })).toThrow(/matchQuality/u);+ expect(() => assessRecallAdequacy({ matchQuality: -0.1, scores: [0.5] })).toThrow(+ /matchQuality/u,+ );+ expect(() => assessRecallAdequacy({ matchQuality: Number.NaN, scores: [0.5] })).toThrow(+ /matchQuality/u,+ );});-test("verdict carries a human-readable reason", () => {- expect(assessRecallAdequacy([0.9]).reason).toContain("sufficient");- expect(assessRecallAdequacy([]).reason.length).toBeGreaterThan(0);+test("verdict carries a human-readable reason naming the quantity it read", () => {+ const sufficient = assessRecallAdequacy({ matchQuality: 0.9, scores: [0.9] });+ expect(sufficient.reason).toContain("sufficient");+ expect(sufficient.reason).toContain("match quality");+ expect(assessRecallAdequacy({ matchQuality: 0, scores: [] }).reason.length).toBeGreaterThan(0);});diff --git a/tests/core/brain/recall-inject.test.ts b/tests/core/brain/recall-inject.test.tsindex e706efa6..67e759a7 100644--- a/tests/core/brain/recall-inject.test.ts+++ b/tests/core/brain/recall-inject.test.ts@@ -23,8 +23,18 @@ function candidate(overrides: Partial<RecallCandidate> = {}): RecallCandidate {};}-function retrieverOf(set: RecallResultSet): RecallRetriever {- return async () => set;+/**+ * Wrap a candidate set as a retriever.+ *+ * `idfWeightedCoverage` defaults to full coverage because most cases below+ * are about briefs, caps and fences rather than about the floor: they have+ * to clear it deliberately, not by whatever a candidate's score happened to+ * be. The cases that ARE about the floor state their own coverage.+ */+function retrieverOf(+ set: Omit<RecallResultSet, "idfWeightedCoverage"> & { readonly idfWeightedCoverage?: number },+): RecallRetriever {+ return async () => ({ ...set, idfWeightedCoverage: set.idfWeightedCoverage ?? 1 });}describe("decideRecallInject (A2 / t_2ce46130)", () => {@@ -32,27 +42,64 @@ describe("decideRecallInject (A2 / t_2ce46130)", () => {let called = false;const decision = await decideRecallInject(" ", async () => {called = true;- return { candidates: [], total: 0 };+ return { candidates: [], total: 0, idfWeightedCoverage: 0 };+ });+ expect(decision).toEqual({+ kind: "abstain",+ reason: "empty_prompt",+ topScore: 0,+ matchQuality: 0,});- expect(decision).toEqual({ kind: "abstain", reason: "empty_prompt", topScore: 0 });expect(called).toBe(false);});test("abstains when the retriever returns no matches", async () => {const decision = await decideRecallInject("how do receipts work",- retrieverOf({ candidates: [], total: 0 }),+ retrieverOf({ candidates: [], total: 0, idfWeightedCoverage: 0 }),);- expect(decision).toEqual({ kind: "abstain", reason: "no_matches", topScore: 0 });+ expect(decision).toEqual({+ kind: "abstain",+ reason: "no_matches",+ topScore: 0,+ matchQuality: 0,+ });});test("abstains below the confidence floor", async () => {- const weak = RECALL_INJECT_CONFIDENCE_FLOOR - 0.05;+ // A high-scoring candidate that barely covers the prompt. Under the old+ // rule the floor read the score and this injected; it is the case the+ // shipped keyword lane produces on every off-topic prompt, because that+ // lane pins its top row's score regardless of how well it matched.+ const weakCoverage = RECALL_INJECT_CONFIDENCE_FLOOR - 0.05;const decision = await decideRecallInject("receipts",- retrieverOf({ candidates: [candidate({ score: weak })], total: 1 }),+ retrieverOf({+ candidates: [candidate({ score: 0.99 })],+ total: 1,+ idfWeightedCoverage: weakCoverage,+ }),);- expect(decision).toMatchObject({ kind: "abstain", reason: "below_floor" });+ expect(decision).toMatchObject({+ kind: "abstain",+ reason: "below_floor",+ matchQuality: weakCoverage,+ });+ });++ test("a low-scoring candidate that covers the prompt still injects", async () => {+ // The mirror of the case above, and the reason the floor moved: a row+ // the filter stack left at the bottom of its pool can still be the+ // material the prompt asked for.+ const decision = await decideRecallInject(+ "receipts",+ retrieverOf({+ candidates: [candidate({ score: 0.01 })],+ total: 1,+ idfWeightedCoverage: 0.8,+ }),+ );+ expect(decision.kind).toBe("inject");});test("injects a bounded brief above the floor", async () => {diff --git a/tests/core/brain/schema-report.test.ts b/tests/core/brain/schema-report.test.tsindex 4066bb2f..9db35e49 100644--- a/tests/core/brain/schema-report.test.ts+++ b/tests/core/brain/schema-report.test.ts@@ -131,6 +131,42 @@ describe("buildSchemaReport", () => {});});+ /**+ * a-label-is-not-a-boundary, U12: one malformed artifact used to cost+ * the caller the whole report - the parse escaped `buildSchemaReport`+ * and every finding in the vault went with it.+ */+ test("a malformed artifact becomes a finding and the rest of the report survives", () => {+ writeBrainConfig(+ ["schema_version: 1", "schema:", " preference_types: [research, decision]"].join("\n"),+ );+ writePreference(vault, basePref("research-pref", { schema_type: "research" }));+ // Missing `retired_at`: `parseRetired` raises with the absolute path.+ writeFileSync(+ join(vault, "Brain", "retired", "ret-broken.md"),+ ["---", "kind: brain-retired", "_status: retired", "id: ret-broken", "---", "", "x"].join(+ "\n",+ ),+ "utf8",+ );++ const report = buildSchemaReport(vault);++ expect(report.findings).toContainEqual({+ kind: "unreadable-artifact",+ category: "preference_types",+ path: "Brain/retired/ret-broken.md",+ detail: "preference missing field: retired_at",+ });+ // The readable half of the vault is still measured and still linted.+ expect(report.usage.preference_types).toEqual([{ token: "research", count: 1 }]);+ expect(report.findings).toContainEqual({+ kind: "unused-declaration",+ category: "preference_types",+ token: "decision",+ });+ });+test("default vault has built-in vocabulary and no findings", () => {writeBrainConfig("schema_version: 1\n");diff --git a/tests/core/brain/sessions/adapter-registry.test.ts b/tests/core/brain/sessions/adapter-registry.test.tsindex abf1dd21..15ba5c81 100644--- a/tests/core/brain/sessions/adapter-registry.test.ts+++ b/tests/core/brain/sessions/adapter-registry.test.ts@@ -40,7 +40,6 @@ const FIXTURE_MARKER = `"runtime":"fixture-runtime"`;const fixtureAdapter: SessionAdapter = {id: "fixture",- defaultAgent: "fixture-agent",detect(firstLine: string): boolean {return firstLine.includes(FIXTURE_MARKER);},diff --git a/tests/core/brain/sessions/delegation-boundary.test.ts b/tests/core/brain/sessions/delegation-boundary.test.tsnew file mode 100644index 00000000..d66bf46a--- /dev/null+++ b/tests/core/brain/sessions/delegation-boundary.test.ts@@ -0,0 +1,220 @@+/**+ * The delegation boundary the host already delivers (U7 / t_0c6f31ee).+ *+ * The defects this suite exists to catch:+ *+ * - A sub-agent transcript imported as an ordinary session of its+ * parent. The host writes delegated turns to their own file carrying+ * `isSidechain: true` and an `agentId`, under the PARENT's `sessionId`;+ * the claude adapter read neither field, so the only record of the+ * boundary was destroyed before any consumer saw it.+ * - `--agent` on `o2b brain import-session` validated and then discarded:+ * `agentLabelForTurn` returned the adapter's own constant, which is+ * always non-empty, so the operator-supplied identity was unreachable.+ * - Three of the five shipped adapters stamped `claude`, `codex` and+ * `hermes` - strings `normalizeAgentArgument` rejects as placeholders+ * everywhere else in the product, so an imported signal was attributed+ * to a name no writer could ever have named itself.+ *+ * Fixtures are committed under `tests/fixtures/sessions/delegation/` and+ * mirror the on-disk layout the host produces: one parent transcript plus+ * a `subagents/` sibling. Nothing here reads a home directory.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";++import { normalizeAgentArgument } from "../../../../src/core/agent-identity.ts";+import { listContinuityRecords } from "../../../../src/core/brain/continuity/store.ts";+import { CONTINUITY_AGENT_ID_KEY } from "../../../../src/core/brain/continuity/types.ts";+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../../src/core/brain/config-template.ts";+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";+import { brainDirs } from "../../../../src/core/brain/paths.ts";+import { claudeAdapter } from "../../../../src/core/brain/sessions/claude.ts";+import { importSession, importSessionPath } from "../../../../src/core/brain/sessions/import.ts";+import { SESSION_ADAPTERS } from "../../../../src/core/brain/sessions/registry.ts";+import type { SessionTurn } from "../../../../src/core/brain/sessions/types.ts";+import { parseSignal } from "../../../../src/core/brain/signal.ts";++/** Every test in this file pins HOME; nothing pins it globally. */+process.env["HOME"] = mkdtempSync(join(tmpdir(), "o2b-delegation-home-"));++const DELEGATION_DIR = resolve("tests/fixtures/sessions/delegation");+const PARENT_FIXTURE = join(DELEGATION_DIR, "parent-session.jsonl");+const SUBAGENT_FIXTURE = join(DELEGATION_DIR, "subagents", "agent-7f3c21ab.jsonl");++/** Turn counts the committed fixtures hold, pinned so a fixture edit shows up. */+const PARENT_TURNS = 3;+const SIDECHAIN_TURNS = 2;++/** The distinct sub-agent id the committed sidechain fixture carries. */+const SUBAGENT_ID = "7f3c21ab-9d40-4c6e-8b21-0e5c7a1d33f2";+/** The session id BOTH fixtures share - the parent's. */+const SHARED_SESSION_ID = "11111111-2222-3333-4444-555555555555";++/** An operator identity `normalizeAgentArgument` accepts. */+const OPERATOR_AGENT = "claude-vps-agent";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-delegation-"));+ const dirs = brainDirs(tmp);+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ dirs.snapshots,+ ]) {+ mkdirSync(d, { recursive: true });+ }+ atomicWriteFileSync(join(dirs.brain, "_brain.yaml"), DEFAULT_BRAIN_CONFIG_YAML);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++async function turnsOf(path: string): Promise<SessionTurn[]> {+ const turns: SessionTurn[] = [];+ for await (const turn of claudeAdapter.iterate(path)) turns.push(turn);+ return turns;+}++/** `agent:` frontmatter of every signal the import wrote, keyed by topic. */+function agentByTopic(vault: string): Record<string, string> {+ const inbox = brainDirs(vault).inbox;+ const out: Record<string, string> = {};+ for (const name of readdirSync(inbox)) {+ if (!name.startsWith("sig-") || !name.endsWith(".md")) continue;+ const sig = parseSignal(join(inbox, name));+ out[sig.topic] = sig.agent;+ }+ return out;+}++describe("claude adapter — the sidechain discriminators", () => {+ test("the parent transcript yields only parent turns", async () => {+ const turns = await turnsOf(PARENT_FIXTURE);+ expect(turns.length).toBe(PARENT_TURNS);+ for (const turn of turns) {+ expect(turn.sidechain).toBeUndefined();+ expect(turn.agentId).toBeUndefined();+ }+ });++ test("the sidechain transcript flags every turn and names one distinct agent id", async () => {+ const turns = await turnsOf(SUBAGENT_FIXTURE);+ expect(turns.length).toBe(SIDECHAIN_TURNS);+ for (const turn of turns) {+ expect(turn.sidechain).toBe(true);+ expect(turn.agentId).toBe(SUBAGENT_ID);+ }+ });++ test("both fixtures carry the SAME session id, so the count separation is not the id", () => {+ for (const path of [PARENT_FIXTURE, SUBAGENT_FIXTURE]) {+ for (const line of readFileSync(path, "utf8").split("\n")) {+ if (line.trim() === "") continue;+ expect((JSON.parse(line) as { sessionId?: string }).sessionId).toBe(SHARED_SESSION_ID);+ }+ }+ });+});++describe("importSession — attribution across the delegation boundary", () => {+ test("--agent is honoured on a parent transcript, not overruled by the adapter", async () => {+ await importSession(tmp, PARENT_FIXTURE, { agent: OPERATOR_AGENT });+ expect(agentByTopic(tmp)["delegation-parent"]).toBe(OPERATOR_AGENT);+ });++ test("a delegated turn is attributed to a derived sub-agent identity", async () => {+ await importSession(tmp, SUBAGENT_FIXTURE, { agent: OPERATOR_AGENT });+ const worker = agentByTopic(tmp)["delegation-worker"];+ expect(worker).toBe(`${OPERATOR_AGENT}-sub-7f3c21ab`);+ expect(worker).not.toBe(OPERATOR_AGENT);+ expect(normalizeAgentArgument(worker)).toBe(worker!);+ });++ test("a directory walk keeps the parent and its worker apart", async () => {+ const result = await importSessionPath(tmp, DELEGATION_DIR, { agent: OPERATOR_AGENT });+ const scanned = Object.fromEntries(+ result.files.map((f) => [f.file.endsWith("parent-session.jsonl") ? "parent" : "sub", f]),+ );+ expect(result.files.length).toBe(2);+ expect(scanned["parent"]!.turns_scanned).toBe(PARENT_TURNS);+ expect(scanned["sub"]!.turns_scanned).toBe(SIDECHAIN_TURNS);+ const byTopic = agentByTopic(tmp);+ expect(byTopic["delegation-parent"]).toBe(OPERATOR_AGENT);+ expect(byTopic["delegation-worker"]).toBe(`${OPERATOR_AGENT}-sub-7f3c21ab`);+ });++ test("no shipped adapter stamps a label the identity normaliser rejects", async () => {+ for (const adapter of SESSION_ADAPTERS) {+ expect(Object.hasOwn(adapter, "defaultAgent")).toBe(false);+ }+ const fixtures = [+ "claude-minimal.jsonl",+ "codex-minimal.jsonl",+ "hermes-minimal.jsonl",+ "opencode-minimal.jsonl",+ "grok-minimal.jsonl",+ ];+ for (const name of fixtures) {+ const vault = mkdtempSync(join(tmpdir(), "o2b-delegation-agree-"));+ try {+ const dirs = brainDirs(vault);+ for (const d of [dirs.brain, dirs.inbox, dirs.processed, dirs.preferences, dirs.log]) {+ mkdirSync(d, { recursive: true });+ }+ atomicWriteFileSync(join(dirs.brain, "_brain.yaml"), DEFAULT_BRAIN_CONFIG_YAML);+ await importSession(vault, resolve("tests/fixtures/sessions", name), {+ agent: OPERATOR_AGENT,+ });+ for (const stamped of Object.values(agentByTopic(vault))) {+ expect(`${name}:${normalizeAgentArgument(stamped)}`).toBe(`${name}:${stamped}`);+ }+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ }+ });+});++describe("session recall — the continuity payload names both ids", () => {+ test("a delegated turn's session_turn record carries the agent id and the flag", async () => {+ await importSession(tmp, SUBAGENT_FIXTURE, {+ agent: OPERATOR_AGENT,+ recall: true,+ recallSessionId: SHARED_SESSION_ID,+ });+ const records = listContinuityRecords(tmp).filter((r) => r.kind === "session_turn");+ expect(records.length).toBe(SIDECHAIN_TURNS);+ for (const record of records) {+ const payload = record.payload as Record<string, unknown>;+ expect(payload["session_id"]).toBe(SHARED_SESSION_ID);+ expect(payload[CONTINUITY_AGENT_ID_KEY]).toBe(SUBAGENT_ID);+ expect(payload["sidechain"]).toBe(true);+ }+ });++ test("a parent turn's session_turn record carries neither", async () => {+ await importSession(tmp, PARENT_FIXTURE, {+ agent: OPERATOR_AGENT,+ recall: true,+ recallSessionId: SHARED_SESSION_ID,+ });+ const records = listContinuityRecords(tmp).filter((r) => r.kind === "session_turn");+ expect(records.length).toBe(PARENT_TURNS);+ for (const record of records) {+ const payload = record.payload as Record<string, unknown>;+ expect(CONTINUITY_AGENT_ID_KEY in payload).toBe(false);+ expect("sidechain" in payload).toBe(false);+ }+ });+});diff --git a/tests/core/brain/shared-namespace.test.ts b/tests/core/brain/shared-namespace.test.tsindex d1b55d3f..59ec7dda 100644--- a/tests/core/brain/shared-namespace.test.ts+++ b/tests/core/brain/shared-namespace.test.ts@@ -10,6 +10,9 @@ import { tmpdir } from "node:os";import { join } from "node:path";import {+ MIRROR_OUTCOME,+ MIRROR_OUTCOMES,+ isMirrorOutcome,mirrorNote,mirrorSignal,resolveSharedNamespace,@@ -57,7 +60,7 @@ test("resolveSharedNamespace reads the config key; absent means off", () => {});test("mirrorSignal lands the signal in the shared vault with origin attribution", () => {- expect(mirrorSignal(shared, vault, SIGNAL_INPUT)).toBe("ok");+ expect(mirrorSignal(shared, vault, SIGNAL_INPUT)).toEqual({ outcome: MIRROR_OUTCOME.ok });const inbox = join(shared, "Brain", "inbox");const files = readdirSync(inbox).filter((f) => f.endsWith(".md"));expect(files).toHaveLength(1);@@ -67,19 +70,54 @@ test("mirrorSignal lands the signal in the shared vault with origin attribution"expect(text).toContain("origin_vault: vault");});-test("a broken shared namespace degrades to failed without throwing", () => {+/**+ * Fail-soft is not the same as mute. Both writes used to sit behind a bare+ * `catch { return "failed" }`, so a permissions problem, a missing shared+ * vault, a full disk and a schema violation reached the operator as one+ * indistinguishable bit - on the one path they cannot observe any other way,+ * because nothing read the shared vault back.+ */+test("a broken shared namespace degrades to failed and says why", () => {rmSync(shared, { recursive: true, force: true });writeFileSync(shared, "not a directory");- expect(mirrorSignal(shared, vault, SIGNAL_INPUT)).toBe("failed");- expect(mirrorNote(shared, vault, { text: "hello", agent: "coding-agent" })).toBe("failed");+ const signal = mirrorSignal(shared, vault, SIGNAL_INPUT);+ expect(signal.outcome).toBe(MIRROR_OUTCOME.failed);+ expect(signal.reason).toBeDefined();+ expect(signal.reason).not.toBe("");+ const note = mirrorNote(shared, vault, { text: "hello", agent: "coding-agent" });+ expect(note.outcome).toBe(MIRROR_OUTCOME.failed);+ expect(note.reason).toBeDefined();});-test("a shared namespace pointing at the origin vault is refused as failed", () => {- expect(mirrorSignal(vault, vault, SIGNAL_INPUT)).toBe("failed");- expect(mirrorNote(vault, vault, { text: "self", agent: "a" })).toBe("failed");+/**+ * A self-mirror is decided before any I/O and is repaired by editing one+ * config key; a failed write is repaired on the filesystem. Reporting both+ * as `failed` sent the operator after the wrong fault.+ */+test("a shared namespace pointing at the origin vault is misconfigured, not failed", () => {+ const signal = mirrorSignal(vault, vault, SIGNAL_INPUT);+ expect(signal.outcome).toBe(MIRROR_OUTCOME.misconfigured);+ expect(signal.outcome).not.toBe(MIRROR_OUTCOME.failed);+ expect(signal.reason).toContain("shared_namespace");+ expect(mirrorNote(vault, vault, { text: "self", agent: "a" }).outcome).toBe(+ MIRROR_OUTCOME.misconfigured,+ );expect(readdirSync(join(vault, "Brain")).some((f) => f === "inbox")).toBe(false);});+test("the mirror outcome vocabulary is closed, and carries no member nothing produces", () => {+ expect([...MIRROR_OUTCOMES]).toEqual([+ MIRROR_OUTCOME.ok,+ MIRROR_OUTCOME.failed,+ MIRROR_OUTCOME.misconfigured,+ ]);+ for (const member of MIRROR_OUTCOMES) expect(isMirrorOutcome(member)).toBe(true);+ // `off` was retracted: the key being absent is reported by omitting the+ // field, so no producer could ever return the token.+ expect(isMirrorOutcome("off")).toBe(false);+ expect(isMirrorOutcome(null)).toBe(false);+});+test("mirrorNote lands a note event with origin attribution", () => {expect(mirrorNote(shared, vault, {@@ -87,7 +125,7 @@ test("mirrorNote lands a note event with origin attribution", () => {agent: "coding-agent",now: new Date("2026-06-04T10:00:00Z"),}),- ).toBe("ok");+ ).toEqual({ outcome: MIRROR_OUTCOME.ok });const { entries } = parseLogDay(shared, "2026-06-04");expect(entries).toHaveLength(1);expect(entries[0]!.eventType).toBe("note");@@ -103,7 +141,8 @@ test("appendBrainNote mirrors when configured and reports the outcome", () => {configPath,now: new Date("2026-06-04T10:00:00Z"),});- expect(res.mirror).toBe("ok");+ expect(res.mirror).toBe(MIRROR_OUTCOME.ok);+ expect(res.mirror_reason).toBeUndefined();expect(parseLogDay(shared, "2026-06-04").entries).toHaveLength(1);// Primary log always lands regardless of mirror state.expect(parseLogDay(vault, "2026-06-04").entries).toHaveLength(1);@@ -124,7 +163,7 @@ test("MCP brain_feedback mirrors the signal and reports mirror: ok", async () =>principle: "Mirrored facts stay attributed.",agent: "coding-agent",})) as Record<string, unknown>;- expect(res["mirror"]).toBe("ok");+ expect(res["mirror"]).toBe(MIRROR_OUTCOME.ok);const files = readdirSync(join(shared, "Brain", "inbox")).filter((f) => f.endsWith(".md"));expect(files).toHaveLength(1);});@@ -140,7 +179,10 @@ test("MCP brain_feedback mirror failure never breaks the primary write", async (principle: "Primary write survives.",agent: "coding-agent",})) as Record<string, unknown>;- expect(res["mirror"]).toBe("failed");+ expect(res["mirror"]).toBe(MIRROR_OUTCOME.failed);+ // The diagnosis reaches the caller on the MCP surface too, not only the+ // bit that something went wrong.+ expect(typeof res["mirror_reason"]).toBe("string");const files = readdirSync(join(vault, "Brain", "inbox")).filter((f) => f.endsWith(".md"));expect(files).toHaveLength(1);});@@ -156,4 +198,5 @@ test("unconfigured setups keep the previous result shape (no mirror key)", asyncagent: "coding-agent",})) as Record<string, unknown>;expect("mirror" in res).toBe(false);+ expect("mirror_reason" in res).toBe(false);});diff --git a/tests/core/brain/token-impact.test.ts b/tests/core/brain/token-impact.test.tsindex 231b2325..358b4f1a 100644--- a/tests/core/brain/token-impact.test.ts+++ b/tests/core/brain/token-impact.test.ts@@ -15,6 +15,7 @@ import {TOKEN_COUNT_METHOD,TOKEN_COUNT_METHODS,} from "../../../src/core/brain/token-impact.ts";+import { lexSource } from "../../helpers/source-lexer.ts";let tmp: string;let vault: string;@@ -326,7 +327,10 @@ describe("the ledger no longer claims exactness over caller-supplied integers",).text();// Comments may (and do) explain the retired label; code may not use it// for anything but the documented legacy read.- const code = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");+ // The shared census lexer. `withoutComments`, not `code`: the strings+ // below ARE the subject, and the code view would blank them and make+ // every assertion here vacuously true.+ const code = lexSource(source).withoutComments;expect(code).not.toContain('"exact"');expect(code).not.toContain('"fallback"');expect(code).not.toContain("byMethod.exact");diff --git a/tests/core/brain/vault-identity.test.ts b/tests/core/brain/vault-identity.test.tsindex 6fd153aa..52fd67e6 100644--- a/tests/core/brain/vault-identity.test.ts+++ b/tests/core/brain/vault-identity.test.ts@@ -328,6 +328,9 @@ describe("the guard fires on Brain write paths", () => {},],total: 1,+ // A hit good enough to clear the 0.5 floor, so the guard under test is+ // reached by a retriever that actually closes the gap task.+ idfWeightedCoverage: 1,} satisfies RecallResultSet);function seedSnapshotArchive(vaultRoot: string): void {diff --git a/tests/core/install/adapters/grok-hook-parity.test.ts b/tests/core/install/adapters/grok-hook-parity.test.tsnew file mode 100644index 00000000..e8803b1c--- /dev/null+++ b/tests/core/install/adapters/grok-hook-parity.test.ts@@ -0,0 +1,130 @@+/**+ * The grok installer's claim to mirror the plugin's hooks, measured+ * (a-label-is-not-a-boundary review, C9).+ *+ * `src/core/install/grok-asset.ts` says its table mirrors the Claude Code+ * plugin's behaviour. Nothing checked it, and it did not: `SubagentStop`+ * and `PreToolUse` were absent, so a grok install captured nothing from a+ * delegated sub-agent - the headline capability of a unit that shipped in+ * the same release - and ran no orientation gate. `UserPromptSubmit` was+ * missing `nav-inject` on top of that.+ *+ * The existing adapter test asserts `readFileSync(hooksPath()) ===+ * grokHooksJson(payload())`, which is true of any hook set the generator+ * emits, including an empty one. This one derives the expectation from+ * `hooks/hooks.json` - the plugin's own source of truth - so a hook added+ * there is a failure here until grok either registers it or declares why+ * it does not.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { join } from "node:path";++import { grokHooksJson } from "../../../../src/core/install/grok-asset.ts";+import { buildPayload } from "../../../../src/core/install/payload.ts";+import type { McpPayload } from "../../../../src/core/install/types.ts";++const REPO_ROOT = join(import.meta.dir, "..", "..", "..", "..");+const PLUGIN_HOOKS_JSON = join(REPO_ROOT, "hooks", "hooks.json");++/**+ * Hooks the plugin registers that grok deliberately does not, keyed+ * `<event>:<hook>`, each with the reason an operator would need.+ *+ * Empty today, and that is the contract: a divergence is a written+ * decision or it is a defect. A stale entry fails too - see the test+ * below - so this cannot become a list of things that used to be true.+ */+const DECLARED_GROK_DIVERGENCES: Readonly<Record<string, string>> = Object.freeze({});++/** `<event>:<hook-script-name>` for every hook one JSON hooks file registers. */+function registeredHooks(hooksJson: string): ReadonlySet<string> {+ const parsed = JSON.parse(hooksJson) as {+ hooks: Record<string, ReadonlyArray<{ hooks: ReadonlyArray<{ command: string }> }>>;+ };+ const out = new Set<string>();+ for (const [event, groups] of Object.entries(parsed.hooks)) {+ for (const group of groups) {+ for (const entry of group.hooks) {+ const name = hookScriptName(entry.command);+ expect(`${event}: ${name}`).not.toContain("<unrecognised>");+ out.add(`${event}:${name}`);+ }+ }+ }+ return out;+}++/**+ * The hook entry point a command invokes, in both shapes this repo writes+ * it: the plugin's `o2b-hook <name>` shell line and grok's absolute+ * `<bun> run <repo>/hooks/<name>.ts`.+ */+function hookScriptName(command: string): string {+ const viaFile = /\/hooks\/([a-z0-9-]+)\.ts\b/.exec(command);+ if (viaFile?.[1] !== undefined) return viaFile[1];+ const viaLauncher = /o2b-hook\s+([a-z0-9-]+)/.exec(command);+ if (viaLauncher?.[1] !== undefined) return viaLauncher[1];+ return "<unrecognised>";+}++function payload(): McpPayload {+ return buildPayload({+ vault: "/tmp/o2b-parity-vault",+ agent_name: "claude-dev-agent",+ timezone: "UTC",+ });+}++describe("grok registers the plugin's hooks", () => {+ const plugin = registeredHooks(readFileSync(PLUGIN_HOOKS_JSON, "utf8"));+ const grok = registeredHooks(grokHooksJson(payload()));++ test("the derivation reads a real hook set, not an empty one", () => {+ // Both floors sit just under the live measurement. Without them a+ // parser that stopped recognising commands would report a clean sweep+ // over two empty sets, which is the failure mode this file replaces.+ expect(plugin.size).toBeGreaterThan(10);+ expect(grok.size).toBeGreaterThan(10);+ expect([...plugin].filter((k) => k.startsWith("SubagentStop:"))).toEqual([+ "SubagentStop:session-capture",+ ]);+ });++ test("every plugin hook is registered for grok or declared as a divergence", () => {+ // Named, not counted: the failure has to say which hook.+ const missing = [...plugin]+ .filter((key) => !grok.has(key))+ .filter((key) => !(key in DECLARED_GROK_DIVERGENCES))+ .toSorted();+ expect(missing).toEqual([]);+ });++ test("the two hooks this review found missing are registered", () => {+ // Pinned by name rather than by count, because "eight events" is a+ // number that goes stale and these two are the capability.+ expect(grok.has("SubagentStop:session-capture")).toBe(true);+ expect(grok.has("PreToolUse:pretool-orient")).toBe(true);+ expect(grok.has("UserPromptSubmit:nav-inject")).toBe(true);+ });++ test("no divergence outlives the hook it excuses", () => {+ const stale = Object.keys(DECLARED_GROK_DIVERGENCES)+ .filter((key) => !plugin.has(key) || grok.has(key))+ .toSorted();+ expect(stale).toEqual([]);+ });++ test("every declared divergence carries a reason", () => {+ for (const [key, reason] of Object.entries(DECLARED_GROK_DIVERGENCES)) {+ expect(`${key}: ${reason.trim().length > 0}`).toBe(`${key}: true`);+ }+ });++ test("grok registers nothing the plugin does not", () => {+ // The complement: a hook grok runs alone would be an install-specific+ // behaviour nobody reading `hooks/hooks.json` could find.+ expect([...grok].filter((key) => !plugin.has(key)).toSorted()).toEqual([]);+ });+});diff --git a/tests/core/install/ownership.test.ts b/tests/core/install/ownership.test.tsindex 5a6ef5b6..31201c8c 100644--- a/tests/core/install/ownership.test.ts+++ b/tests/core/install/ownership.test.ts@@ -60,6 +60,7 @@ import {VAULT_BACKING,VAULT_BACKING_UNDETERMINED_REASON,} from "../../../src/core/vault-backing.ts";+import { lexSource } from "../../helpers/source-lexer.ts";const REPO_ROOT = resolve(import.meta.dir, "..", "..", "..");const VAULT = "/tmp/some-vault";@@ -518,7 +519,11 @@ const OUT_OF_VAULT_ANCHOR_RE =* `[^:]` guard keeps `https://` out of the line-comment arm.*/function code(source: string): string {- return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");+ // The shared census lexer. The `[^:]` guard this replaces was one+ // patch for one shape of "a `//` inside a string is not a comment"; the+ // lexer answers the whole class. `withoutComments` keeps the path+ // literals the anchor pattern matches on.+ return lexSource(source).withoutComments;}function walk(dir: string, out: string[]): string[] {diff --git a/tests/core/layering.test.ts b/tests/core/layering.test.tsindex d729d1db..d6dc56b3 100644--- a/tests/core/layering.test.ts+++ b/tests/core/layering.test.ts@@ -6,15 +6,39 @@* diagnostics on stderr (process.stderr.write, console.error) are an* established core pattern and stay allowed.*- * This is a source scan, not an AST pass: comment-only lines are- * skipped, everything else that mentions a banned call fails with a- * file:line pointer.+ * This is a source scan, not an AST pass, and it reads the shared census+ * lexer's code view rather than deciding "is a comment" from a line+ * prefix. The prefix rule was wrong in both directions: a continuation+ * line inside a block comment does not start with `*` and was scanned as+ * code, while a banned call quoted inside a string literal was reported+ * as a violation.+ *+ * Both shapes are CONSTRUCTED in the positive controls below rather than+ * observed in this tree, and saying so is the point: `src/core` mentions+ * a banned pattern exactly twice, both times as `process.exit` in a line+ * or block comment that the prefix rule blanked correctly too. The two+ * rules therefore agree on today's tree, and this change fixes no live+ * miscount - it closes a class the tree can re-enter with one sentence,+ * which is a smaller claim than the one this docblock used to make. The+ * last test measures those two mentions rather than asserting them from+ * memory.+ *+ * One thing the lexer view is BLINDER about than the prefix rule, stated+ * because it is a real narrowing: template-literal text is blanked, so a+ * banned pattern written inside a template is invisible here where the+ * prefix rule would have reported it. That is the intended reading - text+ * a module emits is not a call the module makes, exactly as a quoted+ * string is not - and `${…}` interpolations stay code, so a banned call+ * INSIDE an interpolation is still caught. The control below pins both+ * halves.*/import { describe, expect, test } from "bun:test";import { readFileSync, readdirSync, statSync } from "node:fs";import { join } from "node:path";+import { lexCode } from "../helpers/source-lexer.ts";+const CORE_ROOT = join(import.meta.dir, "..", "..", "src", "core");const BANNED = [@@ -36,33 +60,85 @@ function walk(dir: string): string[] {return out;}-function isCommentLine(line: string): boolean {- const trimmed = line.trimStart();- return trimmed.startsWith("//") || trimmed.startsWith("*") || trimmed.startsWith("/*");+/**+ * Banned calls in `text`, as `line:pattern` pairs. The code view blanks+ * comment bodies and string / template / regex CONTENTS while preserving+ * every offset, so a line number here still points at the same line of+ * the original file.+ */+function bannedCallsIn(text: string): string[] {+ const found: string[] = [];+ lexCode(text)+ .split("\n")+ .forEach((line, i) => {+ for (const { pattern, reason } of BANNED) {+ if (line.includes(pattern)) found.push(`${i + 1} uses ${pattern} (${reason})`);+ }+ });+ return found;}describe("core layering", () => {test("src/core never calls process.exit, process.stdout.write, or console.log", () => {const violations: string[] = [];for (const file of walk(CORE_ROOT)) {- const lines = readFileSync(file, "utf8").split("\n");- lines.forEach((line, i) => {- if (isCommentLine(line)) return;- for (const { pattern, reason } of BANNED) {- if (line.includes(pattern)) {- violations.push(`${file}:${i + 1} uses ${pattern} (${reason})`);- }- }- });+ for (const hit of bannedCallsIn(readFileSync(file, "utf8"))) {+ violations.push(`${file}:${hit}`);+ }}expect(violations).toEqual([]);});- test("the scan actually detects a banned call", () => {- // Self-check so a broken walk or pattern list cannot rot into a- // vacuously green guard.- expect(isCommentLine(" // process.exit(1)")).toBe(true);- expect(isCommentLine(" process.exit(1);")).toBe(false);+ test("the scan detects a banned call, and only where it is really code", () => {+ // Positive control first: a guard that cannot fail proves nothing.+ expect(bannedCallsIn("process.exit(1);\n")).toHaveLength(1);++ // A line comment, the one shape the old prefix rule got right.+ expect(bannedCallsIn(" // process.exit(1)\n")).toEqual([]);++ // A CONTINUATION line of a block comment. It starts with neither+ // `//`, `*` nor `/*`, so the prefix rule scanned it as code and this+ // was a false violation waiting for someone to write the sentence.+ expect(bannedCallsIn("/* explaining why\nconsole.log( is banned here\n*/\n")).toEqual([]);++ // The other direction: the pattern quoted inside a string literal is+ // not a call, and the prefix rule reported it as one.+ expect(bannedCallsIn('const banned = "console.log(";\n')).toEqual([]);+expect(walk(CORE_ROOT).length).toBeGreaterThan(100);});++ test("template text is not a call, but an interpolation still is", () => {+ // The stated narrowing, pinned in both directions. A module that+ // BUILDS the text `console.log(` is emitting a string, and the+ // prefix rule used to call that a violation…+ expect(bannedCallsIn("const snippet = `console.log(x)`;\n")).toEqual([]);+ // …while a banned call written inside an interpolation is code, and+ // is still reported.+ expect(bannedCallsIn("const s = `a ${process.exit(1)} b`;\n")).toHaveLength(1);+ });++ test("every mention of a banned pattern in src/core is already a comment", () => {+ // The measurement behind the docblock's claim that the controls above+ // are constructed rather than observed. A RAW text scan, no lexing,+ // and then the same files through the lexer: every raw mention must+ // disappear, which is what "the two rules agree on today's tree"+ // means. A hit that survives is either a real violation (the test+ // above fails too) or a mention in a string, at which point the+ // docblock's "constructed, not observed" sentence is what changes.+ const rawMentions: string[] = [];+ for (const file of walk(CORE_ROOT)) {+ const text = readFileSync(file, "utf8");+ for (const { pattern } of BANNED) {+ if (text.includes(pattern)) rawMentions.push(`${file} mentions ${pattern}`);+ if (lexCode(text).includes(pattern)) {+ throw new Error(`${file}: ${pattern} survives the code view`);+ }+ }+ }+ // Not zero, and the count is the point: there ARE mentions, all of+ // them prose about why the pattern is banned.+ expect(rawMentions).toHaveLength(2);+ expect(rawMentions.every((hit) => hit.endsWith("process.exit"))).toBe(true);+ });});diff --git a/tests/core/search/coverage-unmeasurable.test.ts b/tests/core/search/coverage-unmeasurable.test.tsnew file mode 100644index 00000000..f236d3ff--- /dev/null+++ b/tests/core/search/coverage-unmeasurable.test.ts@@ -0,0 +1,105 @@+/**+ * Match quality for a query the report cannot weigh, end to end.+ *+ * The coverage engine used to answer `totalIdf === 0 ? 1` - maximum+ * confidence for a query it had measured nothing about. Two inputs+ * produced it, and one of them was routine rather than exotic: the+ * significant-term splitter dropped tokens under three characters, and+ * `\p{L}` matches CJK, so every one- or two-character Chinese or Japanese+ * query - the common word length in those scripts - arrived at the report+ * with no terms and left it with a perfect score. Four thresholds read+ * that number, two of them with no result-count guard at all.+ *+ * This file drives the shipped indexer and search rather than the pure+ * engine, because the defect was only visible end to end: the pure report+ * looked correct in isolation, and it was the SPLITTER upstream that+ * emptied it.+ */++import { test, expect, describe, beforeAll, afterAll } from "bun:test";++import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { decideRecallInject } from "../../../src/core/brain/recall-inject.ts";+import { createTempVault, writeMd, makeConfig } from "../../helpers/search-fixtures.ts";++const { vault, dbPath, cleanup } = createTempVault("coverage-unmeasurable");+afterAll(cleanup);++const config = makeConfig({ vault, dbPath });++beforeAll(async () => {+ writeMd(vault, "ai.md", "# AI notes\n\nai systems and their evaluation.\n");+ writeMd(vault, "kensaku.md", "# 検索\n\n検索 は 全文 の 索引 を 使う。\n");+ writeMd(vault, "other.md", "# Other\n\nA note about gardening tools.\n");+ await indexVault(config);+});++describe("unmeasurable match quality", () => {+ test("a two-character query is weighed rather than dropped", async () => {+ // Before: `significantTerms("検索")` was empty, coverage came back 1,+ // and a query that matched a real note was indistinguishable from one+ // that matched nothing. Now the term is weighed, and because the note+ // does cover it the coverage is a real number at the top of the range.+ const outcome = await search(config, { query: "検索", limit: 5 });+ expect(outcome.results.length).toBeGreaterThan(0);+ expect(outcome.idfWeightedCoverage).not.toBeNull();+ expect(outcome.idfWeightedCoverage).toBe(1);+ });++ test("a two-character query that matches nothing scores zero, not one", async () => {+ // The reviewer's reproduction, inverted into an assertion: a CJK+ // query the corpus does not answer reported `results=0 coverage=1`.+ const outcome = await search(config, { query: "犬猫", limit: 5 });+ expect(outcome.results).toHaveLength(0);+ expect(outcome.idfWeightedCoverage).toBe(0);+ });++ test("a two-character latin query is weighed the same way", async () => {+ // Same rule, different script, and that is the point: nothing here+ // behaves differently because of which writing system the query used.+ const hit = await search(config, { query: "ai", limit: 5 });+ expect(hit.results.length).toBeGreaterThan(0);+ expect(hit.idfWeightedCoverage).toBe(1);+ const miss = await search(config, { query: "qz", limit: 5 });+ expect(miss.results).toHaveLength(0);+ expect(miss.idfWeightedCoverage).toBe(0);+ });++ test("a query with no word characters reports no measurement at all", async () => {+ // The residual unmeasurable case, and the one that stays unmeasurable+ // in every language: there is no term to weigh, so there is no share+ // to report. Null, not one, and not zero either - zero would be the+ // claim that the retrieval covered none of a query that asked nothing.+ const outcome = await search(config, { query: "???", limit: 5 });+ expect(outcome.idfWeightedCoverage).toBeNull();+ });++ test("the recall-inject floor abstains on an unmeasurable quality, by name", async () => {+ // Two consumers had no result-count guard and fired on quality 1.0 the+ // moment any candidate existed. The floor now has a state for "there+ // was no quality", and it abstains under its own reason rather than+ // borrowing `below_floor`, which would report a weak match.+ const decision = await decideRecallInject("???", async () => ({+ candidates: [+ {+ path: "Brain/x.md",+ title: "X",+ score: 0.99,+ searchType: "hybrid",+ startLine: 1,+ endLine: 2,+ },+ ],+ total: 1,+ idfWeightedCoverage: null,+ }));+ expect(decision.kind).toBe("abstain");+ if (decision.kind !== "abstain") return;+ expect(decision.reason).toBe("unmeasurable_quality");+ expect(decision.matchQuality).toBeNull();+ // The score was high, and it decided nothing - which is the whole+ // point of the floor reading quality instead.+ expect(decision.topScore).toBe(0.99);+ });+});diff --git a/tests/core/search/coverage-window-dependence.test.ts b/tests/core/search/coverage-window-dependence.test.tsnew file mode 100644index 00000000..502e7900--- /dev/null+++ b/tests/core/search/coverage-window-dependence.test.ts@@ -0,0 +1,106 @@+/**+ * What `SearchOutcome.idfWeightedCoverage` depends on, measured.+ *+ * Its docblock claimed the number was "pool-independent by construction:+ * removing, fading or re-weighting a candidate cannot move it". That was+ * false, and provably so from one line of the producer: the coverage is+ * computed over `finalResults`, the limit-sliced window the caller+ * receives. Narrow the window and the terms only the dropped rows carried+ * leave the numerator with them.+ *+ * The claim is now narrowed to what the code does, and the reason for the+ * narrower wording lives here rather than only in prose: this file pins+ * the dependence itself, so a later reader who re-derives the stronger+ * claim fails a test instead of shipping a docblock.+ *+ * Getting a PARTIAL coverage at all takes a fixture worth naming, and the+ * reason is a finding in its own right. The keyword lane matches with an+ * implicit AND, so every row it returns contains every query term, and+ * coverage over a keyword-only window is 1 whenever anything came back+ * and 0 when nothing did. A window whose rows differ in what they cover+ * needs a lane that admits rows matching only part of the query: the+ * broadened OR retry of the second pass is the one that needs no+ * embedding provider, so that is what this fixture drives.+ */++import { test, expect, describe, beforeAll, afterAll } from "bun:test";++import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { createTempVault, writeMd, makeConfig } from "../../helpers/search-fixtures.ts";++const { vault, dbPath, cleanup } = createTempVault("coverage-window");+afterAll(cleanup);++const config = makeConfig({ vault, dbPath });++/**+ * Two rare terms living in two different notes. No chunk contains both,+ * so the implicit-AND first pass finds nothing and the broadened OR retry+ * returns one row per term - a window whose rows genuinely differ in+ * which part of the query they cover.+ */+const QUERY = "basilisk quinine";++beforeAll(async () => {+ writeMd(vault, "two.md", "# Two\n\nthe basilisk in the cellar with many other words here.\n");+ writeMd(vault, "three.md", "# Three\n\nquinine and other bitter compounds in the pantry.\n");+ writeMd(vault, "four.md", "# Four\n\nzephyr winds again and again over the plateau.\n");+ await indexVault(config);+});++describe("idf-weighted coverage and the delivered window", () => {+ test("a narrower limit reports lower coverage for the same query", async () => {+ const wide = await search(config, { query: QUERY, limit: 20, evidencePack: true });+ const narrow = await search(config, { query: QUERY, limit: 1, evidencePack: true });+ // The ranked pool is identical; only the delivered window differs.+ expect(narrow.total).toBe(wide.total);+ expect(wide.results).toHaveLength(2);+ expect(narrow.results).toHaveLength(1);+ expect(wide.idfWeightedCoverage).toBe(1);+ // Half the query's IDF mass, because half the rows were sliced off.+ expect(narrow.idfWeightedCoverage).toBeCloseTo(0.5, 6);+ });++ test("the completeness verdict moves with the window too", async () => {+ // Same query, same corpus, same ranking - two different published+ // verdicts. This is the honest reading of the field: it grades the+ // ANSWER, not the vault.+ const wide = await search(config, { query: QUERY, limit: 20, evidencePack: true });+ const narrow = await search(config, { query: QUERY, limit: 1, evidencePack: true });+ expect(wide.evidencePack?.completeness?.verdict).toBe("complete");+ expect(narrow.evidencePack?.completeness?.verdict).toBe("partial");+ });++ test("but it does not move with rank position", async () => {+ // The property that separates it from a score, and the entire reason+ // four thresholds moved onto it: the top row's score is pinned by+ // min-max normalisation whatever it matched, while coverage over the+ // same window is the same number however the rows are ordered inside+ // it. Naming the terms in the other order delivers the same rows and+ // the same coverage.+ const forward = await search(config, { query: QUERY, limit: 20, evidencePack: true });+ const reversed = await search(config, {+ query: "quinine basilisk",+ limit: 20,+ evidencePack: true,+ });+ expect(new Set(reversed.results.map((r) => r.path))).toEqual(+ new Set(forward.results.map((r) => r.path)),+ );+ expect(reversed.idfWeightedCoverage).toBe(forward.idfWeightedCoverage);+ });++ test("the keyword lane alone cannot produce a partial coverage", async () => {+ // Stated as an assertion because it bounds what the four thresholds+ // can currently see on a default install: with no embedding provider+ // and no second pass, every returned row contains every query term,+ // so the number is 1 or it is 0.+ const hit = await search(config, { query: "basilisk cellar", limit: 20 });+ expect(hit.results.length).toBeGreaterThan(0);+ expect(hit.idfWeightedCoverage).toBe(1);+ const miss = await search(config, { query: QUERY, limit: 20 });+ expect(miss.results).toHaveLength(0);+ expect(miss.idfWeightedCoverage).toBe(0);+ });+});diff --git a/tests/core/search/coverage.test.ts b/tests/core/search/coverage.test.tsindex 45a073a8..c909147f 100644--- a/tests/core/search/coverage.test.ts+++ b/tests/core/search/coverage.test.ts@@ -23,18 +23,71 @@ import { search } from "../../../src/core/search/search.ts";import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";describe("coverage engine (pure)", () => {- test("significantTerms drops short tokens but keeps every word - no stopword list", () => {- // Language-agnostic: there is no stopword list. Tokens under length 3- // are dropped structurally ("is"); common words like "the"/"what" are- // kept here and deprioritised downstream by IDF, in any language.+ test("significantTerms keeps every word - no stopword list, no length rule", () => {+ // Language-agnostic: there is no stopword list and no longer a length+ // floor. "is" is kept for the same reason "the" always was - it is a+ // word the query asked with, and how much it is worth is the IDF+ // weighting's answer downstream, in any language.expect(significantTerms("what is the alpha zephyr")).toEqual(["what",+ "is","the","alpha","zephyr",]);});+ test("a query whose words are one or two characters is weighed, not dropped", () => {+ // The length floor was an English-shaped stopword rule wearing a+ // structural disguise: it removed every term of a CJK query, whose+ // common word length IS one or two characters, and the report then+ // had nothing to weigh. Nothing here is about CJK specifically - the+ // splitter never asks what script a token is in - it is about a+ // character count meaning different things in different ones.+ expect(significantTerms("検索")).toEqual(["検索"]);+ expect(significantTerms("ai")).toEqual(["ai"]);+ expect(significantTerms("x")).toEqual(["x"]);+ });++ test("a token of pure punctuation is not a word in any language", () => {+ // The splitter keeps `-` and `_` inside tokens so `well-known` and+ // `snake_case` survive whole, which lets a run of them survive the+ // split as well. With the length floor gone, this is what stops it+ // earning IDF mass.+ expect(significantTerms("?? -- ??")).toEqual([]);+ expect(significantTerms("well-known snake_case")).toEqual(["well-known", "snake_case"]);+ });++ test("an unweighable query reports no coverage, not perfect coverage", () => {+ // The defect: `totalIdf === 0 ? 1` scored a query nothing could be+ // measured about as a complete retrieval, at maximum confidence, for+ // every threshold reading it.+ const noTerms = buildCoverageReport({+ significantTerms: [],+ coveredTerms: new Set(),+ documentCount: 100,+ dfByTerm: new Map(),+ });+ expect(noTerms.idfWeightedCoverage).toBeNull();+ // An empty corpus is the other unweighable input: every IDF is+ // ln(1 + 0/(1+df)) = 0, so there is no mass to take a share of.+ const emptyCorpus = buildCoverageReport({+ significantTerms: ["alpha"],+ coveredTerms: new Set(),+ documentCount: 0,+ dfByTerm: new Map(),+ });+ expect(emptyCorpus.idfWeightedCoverage).toBeNull();+ // And a genuine zero is still a zero: measured, and distinguishable.+ const missed = buildCoverageReport({+ significantTerms: ["alpha"],+ coveredTerms: new Set(),+ documentCount: 100,+ dfByTerm: new Map([["alpha", 1]]),+ });+ expect(missed.idfWeightedCoverage).toBe(0);+ });+test("idf is monotonically decreasing in document frequency", () => {const n = 100;expect(idfForTerm(0, n)).toBeGreaterThan(idfForTerm(5, n));diff --git a/tests/core/search/cross-vault.test.ts b/tests/core/search/cross-vault.test.tsindex 1cc94d70..b19edce4 100644--- a/tests/core/search/cross-vault.test.ts+++ b/tests/core/search/cross-vault.test.ts@@ -36,11 +36,22 @@ beforeEach(async () => {configPath = join(tmp, "config.yaml");writeFileSync(configPath, `vault: "${active}"\n`);- writeMd(active, "Brain/notes/local-note.md", "# Local\n\nThe griffin nests in the local vault.");+ // The active note answers "griffin" completely and "aviary-keeper"+ // only in part: SQLite's tokenizer splits the hyphen, so the row MATCHES+ // on `aviary` + `keeper`, while the coverage engine's containment test+ // looks for the literal term and does not find it. That is what gives+ // the chain-stop test below an origin that genuinely returns rows and+ // genuinely half-answers - see its own comment for why a fixture that+ // returns no rows cannot test that gate at all.+ writeMd(+ active,+ "Brain/notes/local-note.md",+ "# Local\n\nThe griffin nests in the local vault beside the aviary keeper.",+ );writeMd(external,"Brain/notes/external-note.md",- "# External\n\nThe griffin also visits the external vault aviary.",+ "# External\n\nThe griffin also visits the external vault aviary-keeper.",);await indexVault(resolveSearchConfig({ vault: active, configPath }));await indexVault(resolveSearchConfig({ vault: external, configPath }));@@ -196,17 +207,59 @@ test("chain-stop on: a confident active origin skips the remaining origins", asyexpect(stopped?.detail).toEqual({ stoppedAfter: "local", skipped: 1 });});-test("chain-stop gates on the normalized score, never raw: a sub-threshold top does not stop", async () => {+test("chain-stop gates on coverage: an origin that half-answers does not stop the chain", async () => {addRecallSource(configPath, active, "team", external);- // The active origin's top NORMALIZED score for this fixture is ~0.65,- // well under 0.9, so the gate must not fire and every origin is searched.- // The raw FTS/BM25 lane score is far higher than 0.9, so this also proves- // the gate reads the normalized result score, not the raw lane score.+ // The active origin RETURNS A ROW for this query and covers only half+ // of it: `aviary-keeper` matches its note through the tokenizer's+ // hyphen split, and is not contained in it as a term. Under a 0.9+ // coverage threshold the chain must walk on and find the origin that+ // holds the missing half.+ //+ // The row count is the whole point of the fixture. An earlier version+ // of this test asked for terms the active vault did not have at all, so+ // the origin returned ZERO rows and the gate short-circuited on+ // `hits.length > 0` before reading any threshold - reverting the gate+ // to the old top-score rule left it green. A test of a threshold has to+ // reach the threshold.+ //+ // This is the assertion the old score-based gate could not make. Its+ // quantity was the top NORMALIZED result score, which the keyword lane+ // min-max normalises within each origin's own pool - so it said the same+ // thing about an origin that answered everything and one that answered a+ // fragment, and it meant opposite things under the two fusion modes+ // (unreachable in `linear`, always met in `rrf`).+ // 0.6 rather than 0.9, and the band matters: the active origin's+ // coverage here is 0.5 - the two terms carry equal IDF and one is+ // covered - while its top SCORE is ~0.65, so this threshold sits+ // BETWEEN the two quantities. A threshold above both (0.9) is cleared+ // by neither, which is why the earlier 0.9 version of this test stayed+ // green when the gate was reverted to the score.+ withChainStop(0.6);+ const outcome = await searchAcrossVaults(configPath, active, {+ query: "griffin aviary-keeper",+ limit: 10,+ });+ // The gate was reached with rows in hand…+ expect(outcome.results.some((r) => r.origin === "local")).toBe(true);+ // …and refused them, so the origin holding the other half is searched.+ expect(outcome.chainStop).toBeUndefined();+ expect(new Set(outcome.results.map((r) => r.origin))).toContain("source/team");+ // The union's quality is the best origin's, and the external origin+ // covers the query whole.+ expect(outcome.idfWeightedCoverage).toBe(1);+});++test("chain-stop fires when the first origin covers the question", async () => {+ addRecallSource(configPath, active, "team", external);+ // The mirror of the case above: every significant term of this query is+ // covered by the active origin, so the remaining origins add nothing the+ // caller asked for and the chain stops - which is what the knob has+ // always claimed to do and, on the shipped default fusion mode, never+ // did.withChainStop(0.9);const outcome = await searchAcrossVaults(configPath, active, { query: "griffin", limit: 10 });- const labels = new Set(outcome.results.map((r) => r.origin));- expect(labels).toEqual(new Set(["local", "source/team"]));- expect(outcome.chainStop).toBeUndefined();+ expect(outcome.chainStop?.triggered).toBe(true);+ expect(new Set(outcome.results.map((r) => r.origin))).toEqual(new Set(["local"]));});/**@@ -229,11 +282,11 @@ test("cross-vault detail values are identifiers under the trail's shared rule",addRecallSource(configPath, active, "other", other);withChainStop(0);- // "aviary" is absent from the active vault, so the union walks past it:- // source/bare cannot be read, source/team answers confidently, and- // source/other is deliberately skipped - one origin-failed entry and one+ // "feeds" is absent from the active vault, so the union walks past it:+ // source/bare cannot be read, source/other answers confidently, and+ // source/team is deliberately skipped - one origin-failed entry and one// chain-stopped entry, each keyed by a namespaced origin label.- const outcome = await searchAcrossVaults(configPath, active, { query: "aviary", limit: 10 });+ const outcome = await searchAcrossVaults(configPath, active, { query: "feeds", limit: 10 });const degraded = outcome.retrievalTrail?.degraded ?? [];const codes = degraded.map((d) => d.code);diff --git a/tests/core/search/keyword-lane-top-score.test.ts b/tests/core/search/keyword-lane-top-score.test.tsnew file mode 100644index 00000000..aaae7bd3--- /dev/null+++ b/tests/core/search/keyword-lane-top-score.test.ts@@ -0,0 +1,119 @@+/**+ * The keyword-lane top-score pin, measured rather than asserted.+ *+ * Five docblocks and a CHANGELOG entry state what the top row of a+ * keyword-only recall scores, and the whole threshold rework rests on it:+ * a floor a score could never fall below is why four constants stopped+ * being compared against a score at all. The branch that made that+ * argument stated the number as `0.6` and as an equality, and both were+ * wrong - the shipped pipeline returns `0.6499997...`, because the+ * freshness prior is added after the lane is normalised, and a row that+ * also draws a link or entity boost goes higher still.+ *+ * Nothing tied the stated number to the shipped one, which is how a claim+ * about a measurement drifted from the measurement. This file is that+ * tie: it drives the real indexer and the real search over a vault with+ * no embeddings, and compares what comes back against the exported+ * bindings the prose cites - never against a literal. A digit typed into+ * a docblock cannot be checked; a symbol can.+ */++import { test, expect, describe, afterAll } from "bun:test";++import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import {+ DEFAULT_KEYWORD_WEIGHT,+ FRESH_KEYWORD_ONLY_TOP_SCORE,+ resolveSearchConfig,+} from "../../../src/core/search/index.ts";+import { DEFAULT_RECENCY } from "../../../src/core/search/recency.ts";+import { createTempVault, writeMd, makeConfig } from "../../helpers/search-fixtures.ts";++/**+ * The queries driven through the pipeline. Four rather than one, and each+ * matching a different note, because the claim is about EVERY non-empty+ * keyword recall and a single query could be a coincidence.+ */+const QUERIES: ReadonlyArray<string> = Object.freeze([+ "fox",+ "postgres",+ "forest",+ "aviary griffin",+]);++/**+ * Slack allowed between the measured top score and+ * {@link FRESH_KEYWORD_ONLY_TOP_SCORE}.+ *+ * The freshness prior decays continuously from the file's mtime, so a+ * vault written milliseconds ago sits a hair under the full amplitude -+ * measured at 2.5e-7 over a run. A tolerance three orders of magnitude+ * looser than that is still four orders tighter than the 0.05 the prior+ * itself is worth, so a prior that stopped firing could not hide inside+ * it.+ */+const FRESHNESS_SLACK = 1e-4;++const { vault, dbPath, cleanup } = createTempVault("keyword-top-score");+afterAll(cleanup);++writeMd(vault, "alpha.md", "# Alpha\n\nThe quick brown fox jumps over the lazy dog.\n");+writeMd(vault, "beta.md", "# Beta\n\nDatabase migration notes about postgres and indexes.\n");+writeMd(vault, "gamma.md", "# Gamma\n\nA note about the fox and the hound in the forest.\n");+writeMd(vault, "delta.md", "# Delta\n\nThe griffin aviary keeps its own weather.\n");++/** No embeddings configured: the semantic lane cannot contribute. */+const config = makeConfig({ vault, dbPath });++describe("keyword-lane top score", () => {+ test("the shipped default is the weight the pin is stated in", () => {+ // The RESOLVER, not the fixture: the claim is about what a default+ // install ships, and a fixture asserting against itself would prove+ // nothing. The fixture is then held to the same values, so a drifted+ // fixture cannot make the measurement below describe another vault.+ const resolved = resolveSearchConfig({ vault });+ expect(resolved.keywordWeight).toBe(DEFAULT_KEYWORD_WEIGHT);+ expect(resolved.recall.recencyAmplitude).toBe(DEFAULT_RECENCY.amplitude);+ expect(config.keywordWeight).toBe(resolved.keywordWeight);+ expect(config.recall.recencyAmplitude).toBe(resolved.recall.recencyAmplitude);+ });++ test("every non-empty keyword recall clears the weight, and only just", async () => {+ await indexVault(config);+ const measured: string[] = [];+ for (const query of QUERIES) {+ // eslint-disable-next-line no-await-in-loop -- one measurement per query, sequential by design+ const outcome = await search(config, { query, limit: 5 });+ const top = outcome.results[0];+ expect(top).toBeDefined();+ if (top === undefined) continue;+ measured.push(`${query}=${top.score.toFixed(6)}`);+ // The floor: min-max normalisation pins the best keyword lane value+ // at 1, so the relevance term alone is the configured weight, and+ // every layer above it is non-negative.+ expect(top.keywordScore).toBe(1);+ expect(top.semanticScore).toBe(0);+ expect(top.score).toBeGreaterThanOrEqual(DEFAULT_KEYWORD_WEIGHT);+ // …and NOT equal to it, which is the sentence this file exists to+ // correct. The excess is the freshness prior and nothing else on a+ // vault with no links, tags, entities or activation history.+ expect(top.score).toBeGreaterThan(DEFAULT_KEYWORD_WEIGHT);+ expect(top.score - top.recencyBoost).toBeCloseTo(DEFAULT_KEYWORD_WEIGHT, 10);+ expect(top.score).toBeGreaterThan(FRESH_KEYWORD_ONLY_TOP_SCORE - FRESHNESS_SLACK);+ expect(top.score).toBeLessThanOrEqual(FRESH_KEYWORD_ONLY_TOP_SCORE);+ }+ // Printed so a re-measurement never has to reconstruct the harness.+ expect(measured.length).toBe(QUERIES.length);+ });++ test("the two unreachability facts the threshold rework rests on", () => {+ // Every floor a score used to be compared against is below the top+ // row's floor, so none of them could ever refuse anything…+ for (const floor of [0.35, 0.5, DEFAULT_KEYWORD_WEIGHT]) {+ expect(FRESH_KEYWORD_ONLY_TOP_SCORE).toBeGreaterThanOrEqual(floor);+ }+ // …and the chain stop sits above it, so it could never fire.+ expect(FRESH_KEYWORD_ONLY_TOP_SCORE).toBeLessThan(0.8);+ });+});diff --git a/tests/core/search/origin-reachability.test.ts b/tests/core/search/origin-reachability.test.tsnew file mode 100644index 00000000..8a4db8b0--- /dev/null+++ b/tests/core/search/origin-reachability.test.ts@@ -0,0 +1,192 @@+/**+ * An unreachable origin is reported, never dropped (a-label-is-not-a-boundary,+ * U5; t_a160764a, t_77efc212).+ *+ * `listSearchOrigins` used to remove a broken recall source from the fan-out+ * before `cross-vault.ts` could see it, so a union over three origins with one+ * dead origin came back as though that origin had honestly contributed+ * nothing. `warnings` was maintained one layer down and could not be+ * populated, because the information was destroyed upstream.+ *+ * The three verdicts are distinct on purpose: `reachable` was read,+ * `unreachable` was looked at and is not there, `unknown` could not be looked+ * at at all. None of the three is a count of zero.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ ORIGIN_REACH,+ ORIGIN_REACHES,+ ORIGIN_REACH_REASON,+ ORIGIN_REACH_REASONS,+ isOriginReach,+ isOriginReachReason,+ probeOriginReach,+} from "../../../src/core/brain/portability/origin-reach.ts";+import { listSearchOrigins } from "../../../src/core/brain/portability/origins.ts";+import { addRecallSource } from "../../../src/core/brain/portability/recall-sources.ts";+import { RETRIEVAL_DEGRADATION } from "../../../src/core/search/retrieval-trail.ts";+import { searchAcrossVaults } from "../../../src/core/search/cross-vault.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { resolveSearchConfig } from "../../../src/core/search/index.ts";+import { writeMd } from "../../helpers/search-fixtures.ts";++let tmp: string;+let active: string;+let external: string;+let configPath: string;++beforeEach(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-origin-reach-"));+ active = join(tmp, "active-vault");+ external = join(tmp, "external-vault");+ mkdirSync(join(active, "Brain"), { recursive: true });+ mkdirSync(join(external, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${active}"\n`);++ writeMd(active, "Brain/notes/local-note.md", "# Local\n\nThe griffin nests in the local vault.");+ writeMd(+ external,+ "Brain/notes/external-note.md",+ "# External\n\nThe griffin also visits the external vault aviary.",+ );+ await indexVault(resolveSearchConfig({ vault: active, configPath }));+ await indexVault(resolveSearchConfig({ vault: external, configPath }));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** Register a source that existed at registration time and then vanished. */+function registerVanishedSource(alias: string): string {+ const vault = join(tmp, `${alias}-vault`);+ mkdirSync(join(vault, "Brain"), { recursive: true });+ addRecallSource(configPath, active, alias, vault);+ rmSync(vault, { recursive: true, force: true });+ return vault;+}++test("a union across three origins with one unreachable warns by name", async () => {+ addRecallSource(configPath, active, "team", external);+ const gone = registerVanishedSource("gone");++ const outcome = await searchAcrossVaults(configPath, active, { query: "griffin", limit: 10 });++ // The two origins that could be read still answer.+ expect(new Set(outcome.results.map((r) => r.origin))).toEqual(new Set(["local", "source/team"]));+ // And the third is NAMED rather than silently absent.+ const warning = outcome.warnings.find((w) => w.includes("source/gone"));+ expect(warning).toBeDefined();+ expect(warning).toContain(ORIGIN_REACH_REASON.vaultMissing);+ // The origin's path never crosses this boundary - the label is the+ // actionable part, and warnings travel verbatim into MCP payloads.+ expect(outcome.warnings.some((w) => w.includes(gone))).toBe(false);+ // The same fact as a code, so a caller does not have to read prose.+ const entry = outcome.retrievalTrail?.degraded.find(+ (d) => d.code === RETRIEVAL_DEGRADATION.crossVaultOriginFailed,+ );+ expect(entry?.detail).toEqual({+ origin: "source/gone",+ cause: ORIGIN_REACH_REASON.vaultMissing,+ });+});++test("listSearchOrigins reports an unreachable origin rather than dropping it", () => {+ addRecallSource(configPath, active, "team", external);+ registerVanishedSource("gone");++ const origins = listSearchOrigins(configPath, active);+ expect(origins.map((o) => o.label)).toEqual(["local", "source/gone", "source/team"]);++ const dead = origins.find((o) => o.label === "source/gone");+ expect(dead?.reach).toBe(ORIGIN_REACH.unreachable);+ expect(dead?.reason).toBe(ORIGIN_REACH_REASON.vaultMissing);+ expect(origins.find((o) => o.label === "local")?.reach).toBe(ORIGIN_REACH.reachable);+ expect(origins.find((o) => o.label === "source/team")?.reason).toBeUndefined();+});++test("unreachable and unknown are different values, and neither reads as zero", async () => {+ const holder = join(tmp, "holder");+ const shielded = join(holder, "shielded-vault");+ mkdirSync(join(shielded, "Brain"), { recursive: true });+ addRecallSource(configPath, active, "shielded", shielded);+ registerVanishedSource("gone");+ // An unreadable parent makes the probe fail with something other than+ // ENOENT: the origin may well be there, and nothing was learned about it.+ chmodSync(holder, 0o000);+ try {+ const origins = listSearchOrigins(configPath, active);+ const unknown = origins.find((o) => o.label === "source/shielded");+ const missing = origins.find((o) => o.label === "source/gone");+ expect(unknown?.reach).toBe(ORIGIN_REACH.unknown);+ expect(missing?.reach).toBe(ORIGIN_REACH.unreachable);+ expect(unknown?.reach).not.toBe(missing?.reach);+ expect(unknown?.reason).toBe(ORIGIN_REACH_REASON.vaultUnreadable);++ const outcome = await searchAcrossVaults(configPath, active, { query: "griffin", limit: 10 });+ // Neither origin contributed a result, and neither is reported as a+ // zero contribution: both are named, each with its own reason.+ expect(outcome.warnings.some((w) => w.includes("source/shielded"))).toBe(true);+ expect(outcome.warnings.some((w) => w.includes("source/gone"))).toBe(true);+ const causes = (outcome.retrievalTrail?.degraded ?? [])+ .filter((d) => d.code === RETRIEVAL_DEGRADATION.crossVaultOriginFailed)+ .map((d) => d.detail?.["cause"]);+ expect(causes).toContain(ORIGIN_REACH_REASON.vaultUnreadable);+ } finally {+ chmodSync(holder, 0o755);+ }+});++test("the shared namespace is enumerable as a read origin", () => {+ const shared = join(tmp, "shared-vault");+ mkdirSync(join(shared, "Brain"), { recursive: true });+ writeFileSync(configPath, `vault: "${active}"\nshared_namespace: "${shared}"\n`);++ const origins = listSearchOrigins(configPath, active);+ const sharedOrigin = origins.find((o) => o.kind === "shared");+ expect(sharedOrigin?.label).toBe("shared");+ expect(sharedOrigin?.vault).toBe(shared);+ expect(sharedOrigin?.reach).toBe(ORIGIN_REACH.reachable);+});++test("a shared namespace pointing at the active vault is deduped, not listed twice", () => {+ writeFileSync(configPath, `vault: "${active}"\nshared_namespace: "${active}"\n`);+ expect(listSearchOrigins(configPath, active).map((o) => o.label)).toEqual(["local"]);+});++test("probeOriginReach splits absent, not-a-directory, and could-not-look", () => {+ expect(probeOriginReach(active).reach).toBe(ORIGIN_REACH.reachable);+ expect(probeOriginReach(join(tmp, "never-existed"))).toEqual({+ reach: ORIGIN_REACH.unreachable,+ reason: ORIGIN_REACH_REASON.vaultMissing,+ });+ const file = join(tmp, "a-file");+ writeFileSync(file, "not a vault");+ expect(probeOriginReach(file)).toEqual({+ reach: ORIGIN_REACH.unreachable,+ reason: ORIGIN_REACH_REASON.vaultNotDirectory,+ });+ expect(probeOriginReach(join(file, "under-a-file"))).toEqual({+ reach: ORIGIN_REACH.unreachable,+ reason: ORIGIN_REACH_REASON.vaultNotDirectory,+ });+});++test("the reachability vocabulary is closed in both directions", () => {+ expect([...ORIGIN_REACHES]).toEqual([+ ORIGIN_REACH.reachable,+ ORIGIN_REACH.unreachable,+ ORIGIN_REACH.unknown,+ ]);+ for (const member of ORIGIN_REACHES) expect(isOriginReach(member)).toBe(true);+ for (const member of ORIGIN_REACH_REASONS) expect(isOriginReachReason(member)).toBe(true);+ expect(isOriginReach("reachable-ish")).toBe(false);+ expect(isOriginReach(0)).toBe(false);+ expect(isOriginReachReason(null)).toBe(false);+});diff --git a/tests/core/search/score-stability.test.ts b/tests/core/search/score-stability.test.tsnew file mode 100644index 00000000..1986fd39--- /dev/null+++ b/tests/core/search/score-stability.test.ts@@ -0,0 +1,203 @@+/**+ * Score stability over the committed benchmark corpus+ * (a-label-is-not-a-boundary, U4).+ *+ * U4 moved four absolute thresholds off the result score and onto+ * IDF-weighted coverage, and wired the tier producer that `tierByDoc`+ * never had. Both claims include "no search score moves", and a claim of+ * byte-identity needs an instrument that can see a moved byte.+ * `recall-benchmark.test.ts` cannot: it pins hit@5 / MRR / containment+ * floors, and every score in the corpus could shift while all three stay+ * exactly where they are.+ *+ * So this pins the ordered `(path, score)` window itself. The corpus is+ * committed, the embedding provider is the deterministic local one, and+ * the ranker resolves its clock from the request, so the list is+ * reproducible run to run.+ *+ * The corpus stamps no `tier:` on any note, which is the condition under+ * which the tier producer must be inert: `supporting` is the identity+ * weight, so an untagged vault emits no tier map at all. A tier layer that+ * multiplied by one instead of being absent would move nothing here+ * either - `tier-producer.test.ts` is what separates those two.+ *+ * Re-pinning protocol, same as the benchmark gate's: a number that moves+ * is a finding first. Re-measure only after deciding the move is intended,+ * and say in the commit message which change moved it. Never re-pin to+ * make a red suite green.+ */++import { test, expect, beforeAll, afterAll, describe } from "bun:test";+import { cpSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { parseRecallBenchmarkDataset } from "../../../src/core/search/benchmark.ts";+import { makeConfig } from "../../helpers/search-fixtures.ts";+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";++const FIXTURE = join(import.meta.dir, "..", "..", "fixtures", "recall-benchmark");++/** The window each query is pinned over; the benchmark gate's own k. */+const WINDOW = 5;++/**+ * Decimals the comparison keeps.+ *+ * Four, not more, and the reason is a property of this corpus worth+ * stating: no note in it declares an `authored_at`, so the freshness+ * prior falls back to storage mtime - which is the instant the fixture+ * was copied into a temp vault. Two runs seconds apart therefore differ+ * in the sixth decimal on the rows freshness touches. Four decimals is+ * reproducible run to run (verified by measuring twice) and still an+ * order of magnitude finer than any ranking change this pin exists to+ * catch.+ */+const SCORE_PRECISION = 4;++/**+ * Measured 2026-08-16 on the committed fixture vault with the local+ * 256-dimension embedding provider. Keyed by the dataset's own query ids.+ *+ * The rows are NOT score-descending, and that is the shipped order, not a+ * transcription slip: MMR and the relevance rerank re-order a ranked+ * window by diversity, so position and score genuinely disagree. Pinning+ * the emitted order rather than a sorted copy is the point - a change that+ * reshuffled the window while preserving every score would otherwise pass.+ */+const PINNED: Readonly<Record<string, ReadonlyArray<readonly [string, number]>>> = Object.freeze({+ canary: [+ ["deploy-canary.md", 0.8716],+ ["link-source.md", 0.1343],+ ["deploy-bluegreen.md", 0.1353],+ ["style-guide.md", 0.1256],+ ["incident-2026-05.md", 0.0986],+ ],+ bluegreen: [+ ["deploy-bluegreen.md", 0.907],+ ["search-tuning.md", 0.1711],+ ["deploy-canary.md", 0.1487],+ ["incident-2026-05.md", 0.1471],+ ["db-backups.md", 0.1503],+ ],+ oauth: [+ ["auth-oauth.md", 0.9139],+ ["incident-2026-05.md", 0.1388],+ ["search-tuning.md", 0.1385],+ ["style-guide.md", 0.1154],+ ["deploy-canary.md", 0.1323],+ ],+ passwords: [+ ["auth-passwords.md", 0.9393],+ ["recipe-borscht.md", 0.1765],+ ["embeddings-pipeline.md", 0.1671],+ ["deploy-bluegreen.md", 0.1573],+ ["db-indexing.md", 0.1626],+ ],+ backups: [+ ["db-backups.md", 0.8881],+ ["style-guide.md", 0.1376],+ ["deploy-canary.md", 0.1543],+ ["notes-standup.md", 0.1294],+ ["project-alpha.md", 0.15],+ ],+ indexing: [+ ["db-indexing.md", 0.8823],+ ["project-alpha.md", 0.1683],+ ["db-backups.md", 0.1714],+ ["style-guide.md", 0.1434],+ ["embeddings-pipeline.md", 0.1423],+ ],+ incident: [+ ["incident-2026-05.md", 0.8523],+ ["deploy-bluegreen.md", 0.1556],+ ["style-guide.md", 0.1257],+ ["deploy-canary.md", 0.1433],+ ["link-source.md", 0.1096],+ ],+ "alias-hop": [+ ["link-source.md", 0.8768],+ ["project-alpha.md", 0.2478],+ ["auth-passwords.md", 0.166],+ ["notes-standup.md", 0.1761],+ ["project-alpha.md", 0.2065],+ ],+ embeddings: [+ ["embeddings-pipeline.md", 0.9405],+ ["style-guide.md", 0.1943],+ ["incident-2026-05.md", 0.1909],+ ["project-alpha.md", 0.1744],+ ["vacation-policy.md", 0.15],+ ],+ tuning: [+ ["search-tuning.md", 0.2675],+ ["project-alpha.md", 0.201],+ ["deploy-bluegreen.md", 0.1724],+ ["notes-standup.md", 0.1538],+ ["deploy-canary.md", 0.1565],+ ],+ standup: [+ ["notes-standup.md", 0.8499],+ ["db-indexing.md", 0.1761],+ ["incident-2026-05.md", 0.1626],+ ["project-alpha.md", 0.1705],+ ["style-guide.md", 0.136],+ ],+ style: [+ ["style-guide.md", 0.8835],+ ["incident-2026-05.md", 0.2101],+ ["auth-oauth.md", 0.1788],+ ["db-backups.md", 0.1871],+ ["vacation-policy.md", 0.1718],+ ],+});++let vault: string;+let config: ResolvedSearchConfig;++beforeAll(async () => {+ vault = mkdtempSync(join(tmpdir(), "o2b-score-pin-"));+ cpSync(join(FIXTURE, "vault"), vault, { recursive: true });+ config = makeConfig({+ vault,+ dbPath: join(vault, "index.sqlite"),+ semantic: { enabled: true, provider: "local", dimension: 256 },+ });+ await indexVault(config, { embeddings: true });+});++afterAll(() => {+ rmSync(vault, { recursive: true, force: true });+});++function loadDataset() {+ return parseRecallBenchmarkDataset(+ JSON.parse(readFileSync(join(FIXTURE, "dataset.json"), "utf8")),+ );+}++describe("the ranked window over the committed corpus", () => {+ test("every dataset query is pinned, so a new query cannot slip in unpinned", () => {+ const ids = loadDataset()+ .queries.map((q) => q.id)+ .toSorted();+ expect(ids).toEqual(Object.keys(PINNED).toSorted());+ });++ test("the ordered (path, score) window is unchanged", async () => {+ const dataset = loadDataset();+ const actual: Record<string, Array<readonly [string, number]>> = {};+ for (const query of dataset.queries) {+ // eslint-disable-next-line no-await-in-loop -- one indexed corpus, sequential by design+ const outcome = await search(config, { query: query.query, limit: WINDOW });+ actual[query.id] = outcome.results.map(+ (r) => [r.path, Number(r.score.toFixed(SCORE_PRECISION))] as const,+ );+ }+ // One comparison over the whole corpus: a per-query loop of assertions+ // stops at the first mismatch and hides how wide a ranking change was.+ expect(actual).toEqual(PINNED as unknown as typeof actual);+ });+});diff --git a/tests/core/search/snippet-match-anchor.test.ts b/tests/core/search/snippet-match-anchor.test.tsindex fff516b0..21573fdf 100644--- a/tests/core/search/snippet-match-anchor.test.ts+++ b/tests/core/search/snippet-match-anchor.test.ts@@ -79,6 +79,9 @@ function outcomeWith(content: string): SearchOutcome {results: Object.freeze([resultWith(content)]),warnings: Object.freeze([]),total: 1,+ // Neutral match quality: the snippet assertions never read it, and 1 is+ // what the coverage report yields when there is no term mass to weigh.+ idfWeightedCoverage: 1,});}@@ -101,10 +104,18 @@ describe("the anchoring kernel", () => {expect(windowStart(10, 200)).toBe(HEAD_WINDOW_START);});- test("terms shorter than the significance floor never anchor a window", () => {- // `significantTerms` keeps tokens of length >= 3, with no stop-word- // list anywhere. A two-character query therefore has no terms at all.- expect(matchOffset("an ox in the field", "ox")).toBe(NO_MATCH_OFFSET);+ test("a short term anchors a window like any other", () => {+ // There used to be a length floor here, inherited from+ // `significantTerms`, and a two-character query therefore had no+ // terms at all and anchored nothing. That floor was an English-shaped+ // stopword rule: it also erased every one- and two-character CJK+ // query, whose words are that long. With it gone, a short term is a+ // term, and the only cost is the one this module's docblock already+ // accepted - a window may open where a common word does.+ expect(matchOffset("an ox in the field", "ox")).toBe("an ox in the field".indexOf("ox"));+ expect(matchOffset("the 検索 pipeline", "検索")).toBe("the 検索 pipeline".indexOf("検索"));+ // A term genuinely absent still reports the sentinel.+ expect(matchOffset("an ox in the field", "zz")).toBe(NO_MATCH_OFFSET);});test("the earliest occurrence among several terms wins", () => {diff --git a/tests/core/search/snippet-window-bounds.test.ts b/tests/core/search/snippet-window-bounds.test.tsindex e439cdc9..87f3ea41 100644--- a/tests/core/search/snippet-window-bounds.test.ts+++ b/tests/core/search/snippet-window-bounds.test.ts@@ -95,6 +95,9 @@ function outcomeWith(content: string): SearchOutcome {results: Object.freeze([resultWith(content)]),warnings: Object.freeze([]),total: 1,+ // Neutral match quality: the window assertions never read it, and 1 is+ // what the coverage report yields when there is no term mass to weigh.+ idfWeightedCoverage: 1,});}diff --git a/tests/core/search/tier-producer.test.ts b/tests/core/search/tier-producer.test.tsnew file mode 100644index 00000000..39e48a8d--- /dev/null+++ b/tests/core/search/tier-producer.test.ts@@ -0,0 +1,98 @@+/**+ * The tier producer (a-label-is-not-a-boundary, U4).+ *+ * `tier:` shipped as a documented, hand-editable frontmatter knob with a+ * ranker input (`tierByDoc`), a weight table and a breakdown line - and no+ * producer. Nothing in the pipeline populated the map, so a page stamped+ * `tier: peripheral` scored bit-identically to an untagged one: the label+ * named a boundary and nothing stood behind it.+ *+ * These tests drive the SHIPPED search entry point rather than the ranker+ * directly. `tests/core/search/ranker-tier.test.ts` already proves the+ * ranker honours a hand-supplied map, which is exactly the assertion that+ * passed while the knob did nothing.+ */++import { test, expect, beforeEach, afterEach, describe } from "bun:test";++import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++let vault: string;+let dbPath: string;+let cleanup: () => void;++const QUERY = "gearbox lubrication policy";++/** One page body, identical but for the tier stamp, so tier is the only variable. */+function pageBody(tier: string | null): string {+ const tierLine = tier === null ? "" : `tier: ${tier}\n`;+ return `---\n${tierLine}---\n\n# Policy\n\nGearbox lubrication policy applies before deployment.\n`;+}++function tierReason(reasons: ReadonlyArray<string>): string | null {+ return reasons.find((r) => r.startsWith("tier: ")) ?? null;+}++beforeEach(() => {+ ({ vault, dbPath, cleanup } = createTempVault("tier-producer"));+});++afterEach(() => {+ cleanup();+});++describe("tier reaches the ranker from frontmatter", () => {+ test("core outranks untagged, which outranks peripheral", async () => {+ writeMd(vault, "notes/core.md", pageBody("core"));+ writeMd(vault, "notes/plain.md", pageBody(null));+ writeMd(vault, "notes/peripheral.md", pageBody("peripheral"));+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);++ const outcome = await search(config, { query: QUERY, limit: 10 });+ const score = (path: string): number => outcome.results.find((r) => r.path === path)!.score;+ expect(score("notes/core.md")).toBeGreaterThan(score("notes/plain.md"));+ expect(score("notes/peripheral.md")).toBeLessThan(score("notes/plain.md"));+ });++ test("the breakdown names the tier multiplier that moved the score", async () => {+ writeMd(vault, "notes/peripheral.md", pageBody("peripheral"));+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);++ const outcome = await search(config, { query: QUERY, limit: 10 });+ const row = outcome.results.find((r) => r.path === "notes/peripheral.md");+ expect(row).toBeDefined();+ // Before the producer existed this read `tier: 1` at best, and in+ // practice was absent entirely because the multiplier never moved.+ expect(tierReason(row!.reasons)).not.toBeNull();+ });++ test("an untagged vault ranks exactly as it did before tiers had a producer", async () => {+ // The non-regression anchor: `supporting` is the identity weight, so a+ // vault that never stamped a tier must produce no tier layer at all -+ // not a layer that happens to multiply by one.+ writeMd(vault, "notes/a.md", pageBody(null));+ writeMd(vault, "notes/b.md", pageBody(null));+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);++ const outcome = await search(config, { query: QUERY, limit: 10 });+ expect(outcome.results.length).toBeGreaterThan(0);+ expect(outcome.results.every((r) => tierReason(r.reasons) === null)).toBe(true);+ });++ test("an unrecognised tier value stays at the default rather than demoting the page", async () => {+ // `readTier` folds a typo back to the default; the producer must not+ // turn that into an omission that reads as a distinct tier.+ writeMd(vault, "notes/typo.md", pageBody("cor"));+ writeMd(vault, "notes/plain.md", pageBody(null));+ const config = makeConfig({ vault, dbPath, maxHops: 0, mmrLambda: 1 });+ await indexVault(config);++ const outcome = await search(config, { query: QUERY, limit: 10 });+ expect(outcome.results.every((r) => tierReason(r.reasons) === null)).toBe(true);+ });+});diff --git a/tests/core/vault-backing.test.ts b/tests/core/vault-backing.test.tsindex 705606bb..35231eea 100644--- a/tests/core/vault-backing.test.ts+++ b/tests/core/vault-backing.test.ts@@ -31,6 +31,7 @@ import {VAULT_BACKING_UNDETERMINED_REASON,VAULT_BACKING_UNDETERMINED_REASONS,} from "../../src/core/vault-backing.ts";+import { lexSource } from "../helpers/source-lexer.ts";const EXT4 = 0xef53;const TMPFS = 0x01021994;@@ -149,7 +150,12 @@ describe("no container signal reaches this verdict", () => {* order to explain why it reads none of them, and a scan that counted* the explanation as a use would force the reasoning out of the file.*/- const CODE = SOURCE.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");+ // The shared census lexer, not a pair of regexes: the old strip read+ // a `//` inside a string as a comment opener (hence the `[^:]` guard+ // for `https://`, which is one shape of that bug, not all of them).+ // `withoutComments`, because this scan reads STRING literals - a marker+ // path and an import specifier are both strings.+ const CODE = lexSource(SOURCE).withoutComments;test("the module never reads a one-way container marker", () => {// Naming them, not counting them: every one of these is evidence of adiff --git a/tests/docs/behaviour-break-disclosure.test.ts b/tests/docs/behaviour-break-disclosure.test.tsnew file mode 100644index 00000000..eeb772dc--- /dev/null+++ b/tests/docs/behaviour-break-disclosure.test.ts@@ -0,0 +1,105 @@+/**+ * Behaviour breaks are written down where the operator looks+ * (a-label-is-not-a-boundary review, C4).+ *+ * `docs/stability.md` lists "tightening validation so previously accepted+ * input is rejected" verbatim as a breaking change, and says breaking+ * changes are listed in `docs/updating.md`. 1.49.0 shipped six such+ * changes as a MINOR release with no section there at all - so the only+ * way to discover any of them was to hit one.+ *+ * The table below is the contract: each entry names one shipped break and+ * a token that must appear in the upgrade note. It is not a prose check -+ * the tokens are the identifiers an operator would search for (the flag,+ * the config key, the error code), so a section rewritten in different+ * words still passes and a section that drops a break does not.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { join } from "node:path";++const REPO_ROOT = join(import.meta.dir, "..", "..");+const UPDATING = join(REPO_ROOT, "docs", "updating.md");+const CLI_REFERENCE = join(REPO_ROOT, "docs", "cli-reference.md");++/** The release whose breaks this table describes. */+const RELEASE = "1.49.0";++/**+ * One shipped behaviour break -> the tokens the upgrade note must carry+ * for it. Every token, not any: an entry that names the surface but not+ * the new value leaves the reader mid-repair.+ */+const DISCLOSED_BREAKS: Readonly<Record<string, ReadonlyArray<string>>> = Object.freeze({+ "recall-gate argument pairing": ["match_quality", "scores", "INVALID_PARAMS"],+ "export refuses an unreadable preference": [+ "o2b brain export",+ "o2b brain bank-export",+ "o2b brain explorer --export",+ ],+ "bank-import keeps importing": ["o2b brain bank-import", "topic-key check incomplete"],+ "explorer live mode refuses to start": ["live mode"],+ "export content changes under the redactor": ["redactor"],+ "feedback --json mirror vocabulary": [+ "o2b brain feedback --json",+ "mirror_reason",+ "misconfigured",+ ],+ "four thresholds read a different quantity": [+ "recall_adequacy_sufficient",+ "search_chain_stop_score",+ "GAP_LOOP_AUTO_CLOSE_FLOOR",+ "RECALL_INJECT_CONFIDENCE_FLOOR",+ "idf_weighted_coverage",+ ],+});++/**+ * Verbs whose behaviour changed and whose one-line entry in the CLI+ * reference is what an operator reads first. The upgrade note is where+ * someone who already knows something changed goes; this is where+ * everybody else is.+ */+const CLI_REFERENCE_TOKENS: ReadonlyArray<string> = Object.freeze([+ "o2b brain export ",+ "o2b brain bank-export ",+ "o2b brain bank-import ",+ "o2b brain explorer ",+]);++describe(`docs/updating.md discloses the ${RELEASE} behaviour breaks`, () => {+ const updating = readFileSync(UPDATING, "utf8");++ test("the release has a section of its own", () => {+ expect(updating).toContain(`## Upgrading to ${RELEASE}`);+ });++ for (const [name, tokens] of Object.entries(DISCLOSED_BREAKS)) {+ test(`it covers: ${name}`, () => {+ // Named, not counted: the failure has to say which token is absent.+ const absent = tokens.filter((token) => !updating.includes(token));+ expect(absent).toEqual([]);+ });+ }+});++describe("the CLI reference says it too", () => {+ const reference = readFileSync(CLI_REFERENCE, "utf8");++ test("every changed verb has an entry", () => {+ const absent = CLI_REFERENCE_TOKENS.filter((token) => !reference.includes(token));+ expect(absent).toEqual([]);+ });++ test("each of those entries names the change rather than only the verb", () => {+ // The four lines were byte-identical to their pre-release form while+ // three of the verbs had gained a new non-zero exit and the fourth a+ // new refusal, so presence alone is not the assertion.+ const lines = reference.split("\n");+ const undated = CLI_REFERENCE_TOKENS.filter(+ (token) => !lines.some((line) => line.includes(token) && line.includes(`v${RELEASE}`)),+ );+ expect(undated).toEqual([]);+ });+});diff --git a/tests/e2e/agent-write-contract.integration.test.ts b/tests/e2e/agent-write-contract.integration.test.tsindex 99c513a5..d69488e4 100644--- a/tests/e2e/agent-write-contract.integration.test.ts+++ b/tests/e2e/agent-write-contract.integration.test.ts@@ -133,7 +133,7 @@ test("shared namespace: signal and note mirror with attribution; primary alwayscreated_at: "2026-06-04T12:00:00Z",date: "2026-06-04",slug: "e2e-topic",- }),+ }).outcome,).toBe("ok");const inbox = readdirSync(join(shared, "Brain", "inbox")).filter((f) => f.endsWith(".md"));expect(inbox).toHaveLength(1);diff --git a/tests/fixtures/sessions/delegation/parent-session.jsonl b/tests/fixtures/sessions/delegation/parent-session.jsonlnew file mode 100644index 00000000..e79f5ea6--- /dev/null+++ b/tests/fixtures/sessions/delegation/parent-session.jsonl@@ -0,0 +1,3 @@+{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":"Have a worker check the session adapters.\n@osb feedback positive topic=delegation-parent principle=\"the delegating identity stamps the parent turns\" scope=sessions"},"uuid":"parent-turn-1","timestamp":"2026-06-01T09:00:00.000Z","permissionMode":"default","userType":"external","entrypoint":"sdk-cli","cwd":"/tmp","sessionId":"11111111-2222-3333-4444-555555555555","version":"2.1.126","gitBranch":"HEAD"}+{"parentUuid":"parent-turn-1","isSidechain":false,"type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Dispatching a worker."},{"type":"tool_use","id":"tu-delegate-1","name":"Agent","input":{"description":"Check session adapters","prompt":"Read the session adapters and report."}}]},"uuid":"parent-turn-2","timestamp":"2026-06-01T09:00:01.000Z","sessionId":"11111111-2222-3333-4444-555555555555"}+{"parentUuid":"parent-turn-2","isSidechain":false,"type":"user","message":{"role":"user","content":"<task-notification><task-id>7f3c21ab-9d40-4c6e-8b21-0e5c7a1d33f2</task-id><tool-use-id>tu-delegate-1</tool-use-id><status>completed</status><summary>The worker reported back.</summary></task-notification>"},"uuid":"parent-turn-3","timestamp":"2026-06-01T09:00:30.000Z","sessionId":"11111111-2222-3333-4444-555555555555"}diff --git a/tests/fixtures/sessions/delegation/subagents/agent-7f3c21ab.jsonl b/tests/fixtures/sessions/delegation/subagents/agent-7f3c21ab.jsonlnew file mode 100644index 00000000..a3ec9628--- /dev/null+++ b/tests/fixtures/sessions/delegation/subagents/agent-7f3c21ab.jsonl@@ -0,0 +1,2 @@+{"parentUuid":null,"isSidechain":true,"agentId":"7f3c21ab-9d40-4c6e-8b21-0e5c7a1d33f2","type":"user","message":{"role":"user","content":"Read the session adapters and report.\n@osb feedback positive topic=delegation-worker principle=\"a delegated turn keeps the worker identity\" scope=sessions"},"uuid":"sub-turn-1","timestamp":"2026-06-01T09:00:02.000Z","permissionMode":"default","userType":"external","entrypoint":"sdk-cli","cwd":"/tmp","sessionId":"11111111-2222-3333-4444-555555555555","version":"2.1.126","gitBranch":"HEAD"}+{"parentUuid":"sub-turn-1","isSidechain":true,"agentId":"7f3c21ab-9d40-4c6e-8b21-0e5c7a1d33f2","type":"assistant","message":{"role":"assistant","content":[{"type":"text","text":"Five adapters ship in this tree."}]},"uuid":"sub-turn-2","timestamp":"2026-06-01T09:00:25.000Z","sessionId":"11111111-2222-3333-4444-555555555555"}diff --git a/tests/helpers/source-lexer.test.ts b/tests/helpers/source-lexer.test.tsnew file mode 100644index 00000000..377b816b--- /dev/null+++ b/tests/helpers/source-lexer.test.ts@@ -0,0 +1,209 @@+/**+ * The lexer four censuses run, tested directly rather than through them.+ *+ * Every census that reads this repository's source used to carry its own+ * copy of this scanner, and not one of the four had a test for the case+ * its own docblock argued about. That is exactly where the live defect+ * was: a backtick inside a regex literal opened a phantom template,+ * blanked 31 % of `src/core/vault.ts`, and hid a frozen binding the+ * vocabulary census was written to find. A mis-parse is worse than a miss+ * - it reports a fact about a block that was never examined - so the+ * shapes that produce one are pinned here, in the module that owns them.+ *+ * No helper under `tests/helpers/` had its own test before this file.+ * The convention it sets: a helper whose behaviour other tests draw+ * conclusions from is exercised on its own, so a regression fails by name+ * here instead of surfacing as a quietly smaller population somewhere+ * else.+ */++import { describe, expect, test } from "bun:test";++import { lexCode, lexSource } from "./source-lexer.ts";++/**+ * `src/core/vault.ts:88` verbatim: the line that made the vocabulary+ * census blind. The backtick inside the regex is the whole defect.+ */+const REGEX_WITH_BACKTICK = "const CODE_BLOCK_RE = /```[\\s\\S]*?```|`[^`]+`/g;\n";++/** The shape stated in the vocabulary census's own docblock. */+const REGEX_WITH_QUOTE = "const QUOTED = /[\"']/;\n";++/** Divisions that a naive regex-opener heuristic reads as literals. */+const DIVISIONS =+ "const q = total / count;\n" ++ "const r = (total) / count;\n" ++ "const s = items[0] / count;\n" ++ "const t = a > b / c;\n" ++ "const u = i++ / 2;\n";++/** A statement no rule may blank, appended after each hazard above. */+const TAIL = "export const AFTER_THE_HAZARD = 1;\n";++/**+ * An astral character in a docblock, which shipped source really carries+ * (`src/core/discipline/render.ts`).+ *+ * It is one code POINT and two UTF-16 code UNITS, and the scanner indexes+ * code units (`text[i]`, `text.length`). A view built out of code points+ * is therefore one slot SHORTER than the source for every astral+ * character before the current offset, so every blanking window past it+ * lands early and the offsets a census reads back out of the original+ * text point at the wrong character. The statement after the comment is+ * what makes that visible: it sits one slot early in the view, and a+ * census that took its position from the view and its text from the+ * source would read the character before it.+ */+const ASTRAL_IN_A_COMMENT = "/** \u{1D54F} astral. */\nconst after = 1;\n";++/** Every input below, so length and newline preservation is asserted once. */+const ALL_INPUTS: ReadonlyArray<readonly [string, string]> = Object.freeze([+ ["a regex holding a backtick", REGEX_WITH_BACKTICK + TAIL],+ ["a regex holding a quote", REGEX_WITH_QUOTE + TAIL],+ ["divisions", DIVISIONS + TAIL],+ ["a brace in a string", 'const s = "closes nothing: }";\n' + TAIL],+ ["a brace in a comment", "// closes nothing: }\n/* nor this: } */\n" + TAIL],+ ["a nested interpolation", "const t = `a ${`b ${inner} c`} d`;\n" + TAIL],+ ["an interpolated string", 'const t = `x ${label("y")} z`;\n' + TAIL],+ ["an escaped backslash", 'const p = "ends with a backslash \\\\";\nconst q = 1;\n' + TAIL],+ ["an import specifier", 'import { writeFileSync } from "node:fs";\n' + TAIL],+ ["an unterminated template", "const t = `never closed\n" + TAIL],+ ["an astral character in a comment", ASTRAL_IN_A_COMMENT + TAIL],+ ["an astral character in a string", 'const s = "\u{1D54F}";\n' + TAIL],+]);++describe("source lexer", () => {+ test("a regex literal holding a backtick does not open a template", () => {+ // The regression test for the defect this helper was extracted to+ // close. Read as a template opener, the backtick blanks everything to+ // the next backtick anywhere in the file - here, the whole tail.+ const code = lexCode(REGEX_WITH_BACKTICK + TAIL);+ expect(code).toContain("export const AFTER_THE_HAZARD = 1;");+ expect(code).toContain("const CODE_BLOCK_RE = /");+ expect(code).not.toContain("[^`]");+ });++ test("a regex literal holding a quote does not open a string", () => {+ const code = lexCode(REGEX_WITH_QUOTE + TAIL);+ expect(code).toContain("export const AFTER_THE_HAZARD = 1;");+ expect(code).not.toContain('["');+ });++ test("division is not read as a regex opener", () => {+ // No literal appears in this input at all, so a correct lexer changes+ // nothing. A `/` misread as an opener swallows the rest of its line.+ expect(lexCode(DIVISIONS)).toBe(DIVISIONS);+ });++ test("a brace inside a string cannot close a block", () => {+ const code = lexCode('const s = "closes nothing: }";\n' + TAIL);+ expect(code).not.toContain("}");+ expect(code).toContain('const s = "');+ expect(code).toContain("export const AFTER_THE_HAZARD = 1;");+ });++ test("a brace inside a comment cannot close a block either", () => {+ const source = "// closes nothing: }\n/* nor this: } */\n" + TAIL;+ const views = lexSource(source);+ expect(views.code).not.toContain("}");+ expect(views.withoutComments).not.toContain("}");+ expect(views.code).toContain("export const AFTER_THE_HAZARD = 1;");+ });++ test("a nested interpolation is read as code, its template text is not", () => {+ // Pinned as an exact string: the interpolated identifier survives at+ // its own offset, every character of template TEXT becomes a space,+ // and the two `${` boundaries are still where they were.+ const code = lexCode("const t = `a ${`b ${inner} c`} d`;\n" + TAIL);+ expect(code).toBe("const t = ` ${` ${inner} `} `;\n" + TAIL);+ });++ test("a string inside an interpolation keeps its call and loses its value", () => {+ const code = lexCode('const t = `x ${label("y")} z`;\n' + TAIL);+ expect(code).toContain("label(");+ expect(code).not.toContain('"y"');+ expect(code).toContain("export const AFTER_THE_HAZARD = 1;");+ });++ test("an escaped backslash does not swallow the closing quote", () => {+ const code = lexCode('const p = "ends with a backslash \\\\";\nconst q = 1;\n' + TAIL);+ expect(code).toContain("const q = 1;");+ expect(code).toContain("export const AFTER_THE_HAZARD = 1;");+ });++ test("withoutComments keeps an import specifier that code blanks", () => {+ // The invariant the write-site and destructive-site censuses depend+ // on: an import's specifier IS a string, so a binding detector has to+ // read it. Routing that read through `code` instead drops the+ // write-site census from 64 rows to zero with an EMPTY failure list,+ // which is the false-clean signature these censuses exist to prevent.+ const source = 'import { writeFileSync } from "node:fs";\n' + TAIL;+ const views = lexSource(source);+ expect(views.withoutComments).toContain('from "node:fs"');+ expect(views.code).not.toContain("node:fs");+ expect(views.code).toContain('from "');+ });++ test("withoutComments blanks a comment while keeping the string beside it", () => {+ const source = '/** Mentions progressCounter( in prose. */\nconst tail = "x";\n';+ const views = lexSource(source);+ expect(views.withoutComments).not.toContain("progressCounter(");+ expect(views.withoutComments).toContain('const tail = "x";');+ expect(views.code).not.toContain("progressCounter(");+ expect(views.code).not.toContain('"x"');+ });++ test("a comment behind a regex holding a quote is still blanked", () => {+ // The latent defect in the fourth copy: with no regex rule, the `"`+ // inside `/["]/` opened a string that ran to the next quote, so the+ // docblock after it was never blanked and `progressCounter(` in prose+ // counted as an emitter.+ const source =+ REGEX_WITH_QUOTE + '/** Mentions progressCounter( in prose. */\nconst t = "x";\n';+ expect(lexCode(source)).not.toContain("progressCounter(");+ });++ test("both views preserve length and every newline offset", () => {+ for (const [label, source] of ALL_INPUTS) {+ const views = lexSource(source);+ const report = (view: string, name: string): string =>+ `${label} (${name}): ${view.length} chars, newlines at ${newlineOffsets(view).join(",")}`;+ const expected = `${label} (x): ${source.length} chars, newlines at ${newlineOffsets(source).join(",")}`;+ expect(report(views.withoutComments, "x")).toBe(expected);+ expect(report(views.code, "x")).toBe(expected);+ }+ });++ test("an astral character does not shift every offset after it", () => {+ // The offset invariant, asserted where it can actually fail. Both+ // views are indexed by UTF-16 code unit because the scanner is; a+ // view built out of code points is one slot short per astral+ // character, and every offset after it addresses the character+ // before the one it names.+ const views = lexSource(ASTRAL_IN_A_COMMENT);+ expect(views.code).toBe(" ".repeat(17) + "\nconst after = 1;\n");+ expect(views.withoutComments).toBe(views.code);+ // The character at every offset past the astral one is unchanged, so+ // a rule that reads a literal back out of the source at an offset the+ // view gave it reads the character the view was describing.+ const source = ASTRAL_IN_A_COMMENT + TAIL;+ const code = lexCode(source);+ for (let i = 0; i < source.length; i += 1) {+ if (code[i] !== " ") expect(code[i]).toBe(source[i]!);+ }+ expect(code.length).toBe(source.length);+ });++ test("lexCode is the code view of lexSource", () => {+ for (const [, source] of ALL_INPUTS) {+ expect(lexCode(source)).toBe(lexSource(source).code);+ }+ });+});++function newlineOffsets(text: string): ReadonlyArray<number> {+ const out: number[] = [];+ for (let i = 0; i < text.length; i += 1) if (text[i] === "\n") out.push(i);+ return out;+}diff --git a/tests/helpers/source-lexer.ts b/tests/helpers/source-lexer.tsnew file mode 100644index 00000000..0b88a369--- /dev/null+++ b/tests/helpers/source-lexer.ts@@ -0,0 +1,294 @@+/**+ * One lexer for every census that reads this repository's own source.+ *+ * ## Why a census lexes at all+ *+ * The first version of the progress census was a handful of regexes over+ * raw source, and four independent reviewers walked past it with a+ * positive control each. A required `safeguard` escaped because the file+ * filter was a literal string. A `type X = { … }` alias escaped because+ * only `interface` was enumerated. And a generic constraint containing a+ * brace did not merely hide a violation - it made the block matcher read+ * the wrong body, which is worse than a miss, because a mis-parse reports+ * a fact about a block that was never examined. A census that reports a+ * pass over a mis-parsed block is the failure these files exist to+ * prevent.+ *+ * This project has one runtime dependency and no TypeScript AST, so a+ * real parser is out. What is in reach is a lexer that is CORRECT about+ * the two things a census gets wrong - what is code, and where a block+ * ends - and that is what this is.+ *+ * ## Why it lives here rather than in four census files+ *+ * Four census files had grown their own copy. Two of them+ * (destructive-site and progress) were one implementation typed twice,+ * character-identical apart from the second view. The other two were+ * partial maskers with no regex rule, and one of those was WRONG on+ * shipped source: it read a backtick inside a regex literal as a template+ * opener, blanked 9,706 of the 31,608 bytes of `src/core/vault.ts`, and+ * hid the only frozen binding in the tree its census could not otherwise+ * see. A defect fixed in one copy of four is a defect still live in+ * three, which is why there is now one.+ *+ * ## The two views+ *+ * {@link lexSource} returns both, each the same LENGTH as the source -+ * measured in UTF-16 code units, the unit `String.length` and `text[i]`+ * both speak, and the unit {@link toCodeUnits} builds the views in - so+ * every offset still points at the same character and a rule that needs a+ * literal value reads it back out of the original text at the same index.+ *+ * - {@link LexedSource.withoutComments} blanks comment bodies only. It+ * keeps string, template and regex CONTENTS on purpose: an import's+ * specifier IS a string, and a binding detector that cannot read+ * `"node:fs"` finds no imports at all. Routing such a read through+ * the other view is measured to drop the write-site census from 64+ * rows to zero with an EMPTY failure list - the false-clean signature+ * these censuses exist to prevent.+ * - {@link LexedSource.code} blanks comment bodies AND the contents of+ * every string, template and regex literal. Delimiters survive, so a+ * literal is still recognisable as one; what does not survive is+ * anything a literal could carry that a structural scan would read as+ * syntax. A `rmSync(` inside a quoted example is not a call, and a+ * comment naming a gate gates nothing.+ *+ * {@link lexCode} is `lexSource(text).code`, for the callers that need+ * one view.+ *+ * ## What the lexer cannot see, stated rather than implied+ *+ * The union of the limits its four callers used to state separately.+ * Each census's remaining blind spots are about its own rule and stay+ * with it; these are the ones that belong to the lexing:+ *+ * - Code inside a `${…}` interpolation is read as CODE, which is what+ * it is - but it is not attributed to the template that encloses it.+ * A census that reports positions inside a template reports them as+ * ordinary code.+ * - A regex whose opening `/` sits in a position the heuristic reads as+ * division is read as division. {@link REGEX_PRECEDING} and+ * {@link REGEX_PRECEDING_KEYWORDS} are the whole of that heuristic.+ * - Angle brackets are not brackets here. `<` is a comparison as often+ * as it is a type argument, and a depth map that counted `i < n`+ * would be wrong for the rest of the file. The two places generics+ * matter - an interface header and a type alias's left side - are+ * scanned locally by the census that needs them.+ * - `withoutComments` carries literal contents by design, so a census+ * that reads structure off it reads whatever a string is carrying+ * too. That view answers "what did this module import", never "what+ * does this module call".+ *+ * One more caller could use this next: `import-cycles.test.ts` anchors+ * its specifier match on `^[ \t]*`, so a specifier inside a docblock does+ * not match - but one written at column zero inside a template literal+ * would.+ */++/** Two views of one module, both the same LENGTH as the source. */+export interface LexedSource {+ /** Comments blanked; string, template and regex CONTENTS kept. */+ readonly withoutComments: string;+ /** Comments and all literal CONTENTS blanked; `${…}` code kept. */+ readonly code: string;+}++/** Characters after which a `/` opens a regex rather than divides. */+const REGEX_PRECEDING: ReadonlySet<string> = new Set([+ "",+ "(",+ ",",+ "=",+ ":",+ "[",+ "!",+ "&",+ "|",+ "?",+ "{",+ "}",+ ";",+ "+",+ "-",+ "*",+ "%",+ "~",+ "^",+ "<",+ ">",+]);++/** Keywords after which a `/` opens a regex, e.g. `return /x/.test(s)`. */+const REGEX_PRECEDING_KEYWORDS: ReadonlySet<string> = new Set([+ "return",+ "typeof",+ "instanceof",+ "in",+ "of",+ "case",+ "do",+ "else",+ "yield",+ "await",+ "void",+ "delete",+ "new",+]);++/**+ * Postfix operators whose last character is also a prefix operator.+ *+ * `prev` is a single character, so `i++ / 2` and `"x" + /a/` both present+ * a `+`, and {@link REGEX_PRECEDING} answers both the same way: regex.+ * That reads the division as an opener and blanks the rest of the line -+ * a mis-parse of exactly the class this helper exists to close, found by+ * this module's own tests rather than by a census going quiet. A postfix+ * increment yields a value, so what follows it divides.+ */+const POSTFIX_OPERATORS: ReadonlyArray<string> = Object.freeze(["++", "--"]);++/** The mode a template literal pushes; anything else is read as code. */+const TEMPLATE_MODE = "template";++/** The mode the scanner starts in, and the one a `${` pushes back on. */+const CODE_MODE = "code";++function regexCanStart(text: string, at: number, prev: string): boolean {+ const before = text.slice(0, at).trimEnd();+ if (POSTFIX_OPERATORS.some((operator) => before.endsWith(operator))) return false;+ if (REGEX_PRECEDING.has(prev)) return true;+ const word = /[A-Za-z_$][\w$]*$/.exec(before);+ return word !== null && REGEX_PRECEDING_KEYWORDS.has(word[0]);+}++/**+ * Split into UTF-16 code UNITS, the unit the scanner indexes in.+ *+ * `[...text]` and `Array.from(text)` iterate code POINTS, so an astral+ * character (one point, two units) makes the array one slot shorter than+ * the string it came from - and every offset the scanner computed with+ * `text[i]` / `text.length` then addresses the wrong slot. Shipped source+ * really carries one: `src/core/discipline/render.ts`, where the two+ * views measured 4359 against a 4360-character file and every blanking+ * window past the astral character landed a slot early. `split("")`+ * yields code units, and joining surrogate halves back in order rebuilds+ * the same string.+ */+function toCodeUnits(text: string): string[] {+ return text.split("");+}++/** Both views of `text`, with every offset and every newline preserved. */+export function lexSource(text: string): LexedSource {+ const n = text.length;+ const withoutComments = toCodeUnits(text);+ const code = toCodeUnits(text);+ const blank = (arr: string[], from: number, to: number): void => {+ for (let k = Math.max(from, 0); k < Math.min(to, n); k++) {+ if (arr[k] !== "\n") arr[k] = " ";+ }+ };+ // Top of the stack is the current mode. A template literal pushes+ // `template`; a `${` inside one pushes `code` back on, with its own+ // brace counter, so an interpolated expression is read as code.+ const modes: string[] = [CODE_MODE];+ const braces: number[] = [0];+ let prev = "";+ let i = 0;+ while (i < n) {+ const c = text[i]!;+ if (modes[modes.length - 1] === TEMPLATE_MODE) {+ if (c === "\\") {+ blank(code, i, i + 2);+ i += 2;+ continue;+ }+ if (c === "`") {+ modes.pop();+ prev = "`";+ i += 1;+ continue;+ }+ if (c === "$" && text[i + 1] === "{") {+ modes.push(CODE_MODE);+ braces.push(0);+ prev = "{";+ i += 2;+ continue;+ }+ blank(code, i, i + 1);+ i += 1;+ continue;+ }+ const next = text[i + 1];+ if (c === "/" && next === "/") {+ let end = text.indexOf("\n", i);+ if (end === -1) end = n;+ blank(withoutComments, i, end);+ blank(code, i, end);+ i = end;+ continue;+ }+ if (c === "/" && next === "*") {+ const close = text.indexOf("*/", i + 2);+ const end = close === -1 ? n : close + 2;+ blank(withoutComments, i, end);+ blank(code, i, end);+ i = end;+ continue;+ }+ if (c === '"' || c === "'") {+ let j = i + 1;+ while (j < n && text[j] !== c) j += text[j] === "\\" ? 2 : 1;+ blank(code, i + 1, j);+ prev = c;+ i = j + 1;+ continue;+ }+ if (c === "`") {+ modes.push(TEMPLATE_MODE);+ i += 1;+ continue;+ }+ if (c === "/" && regexCanStart(text, i, prev)) {+ let j = i + 1;+ let inClass = false;+ while (j < n) {+ const e = text[j]!;+ if (e === "\\") {+ j += 2;+ continue;+ }+ if (e === "\n") break;+ if (e === "[") inClass = true;+ else if (e === "]") inClass = false;+ else if (e === "/" && !inClass) break;+ j += 1;+ }+ blank(code, i + 1, j);+ prev = "/";+ i = j + 1;+ continue;+ }+ if (c === "{") {+ braces[braces.length - 1]! += 1;+ } else if (c === "}") {+ if (braces[braces.length - 1] === 0 && modes.length > 1) {+ modes.pop();+ braces.pop();+ prev = "}";+ i += 1;+ continue;+ }+ braces[braces.length - 1]! -= 1;+ }+ if (!/\s/.test(c)) prev = c;+ i += 1;+ }+ return { withoutComments: withoutComments.join(""), code: code.join("") };+}++/** {@link lexSource}'s `code` view, for the callers that need one view. */+export function lexCode(text: string): string {+ return lexSource(text).code;+}diff --git a/tests/hooks/gap-loop.test.ts b/tests/hooks/gap-loop.test.tsindex 699137c8..7ab129b1 100644--- a/tests/hooks/gap-loop.test.ts+++ b/tests/hooks/gap-loop.test.ts@@ -87,7 +87,7 @@ const ADEQUACY_BUCKET = normalizeQueryTerms(ADEQUACY_QUERY).join(" ");/** Seed a recurring weak-recall bucket (signals-that-survive, unit 6). */function seedUnmetRecall(times: number): void {- const verdict = assessRecallAdequacy([0.4]);+ const verdict = assessRecallAdequacy({ matchQuality: 0.4, scores: [0.9] });for (let i = 0; i < times; i++) {recordRecallAdequacyDemand(vault, {query: ADEQUACY_QUERY,@@ -148,7 +148,7 @@ describe("gap-promote hook (SessionEnd)", () => {});});-describe("gap-promote hook audit line", () => {+describe("gap-promote hook audit line and auto-close", () => {/** Every `gap_loop_run` details object the hook appended, oldest first. */function auditDetails(): ReadonlyArray<Record<string, unknown>> {const dir = join(vault, ".open-second-brain", "hook-audit");@@ -163,20 +163,39 @@ describe("gap-promote hook audit line", () => {}/** Write one gap-task note directly, bypassing the hook's mint budget. */- function writeTask(key: string, status: string, closedAt?: string): void {+ function writeTask(+ key: string,+ status: string,+ opts: { closedAt?: string; topic?: string } = {},+ ): void {+ const topic = opts.topic ?? key;writeFrontmatterAtomic(join(brainGapTasksDir(vault), `${key}.md`),{kind: GAP_TASK_KIND,gap_key: key,- gap_topic: key,+ gap_topic: topic,gap_source: GAP_SOURCE_TELEMETRY,status,occurrences: "3",created_at: "2026-01-01T00:00:00.000Z",- ...(closedAt !== undefined ? { closed_at: closedAt, closed_reason: "recalled" } : {}),+ ...(opts.closedAt !== undefined+ ? { closed_at: opts.closedAt, closed_reason: "recalled" }+ : {}),},- "body",+ // The body repeats the topic, exactly as a minted note does: that is+ // why the auto-close gate excludes gap-task notes by path.+ `Recurring recall gap for ${topic}.`,+ { vaultForRelativePath: vault, overwrite: true },+ );+ }++ /** A plain vault note that genuinely covers `topic`, outside the gap area. */+ function writeCoveringNote(topic: string): void {+ writeFrontmatterAtomic(+ join(vault, "notes", "coverage.md"),+ { title: topic },+ `This note documents ${topic} end to end. The ${topic} steps are recorded here.`,{ vaultForRelativePath: vault, overwrite: true },);}@@ -211,7 +230,7 @@ describe("gap-promote hook audit line", () => {test("reports a closed task removed under the retention window as pruned", async () => {const stale = new Date(Date.now() - GAP_TASK_CLOSED_RETENTION_MS - 60_000).toISOString();- writeTask("gap-stale", GAP_TASK_STATUS_CLOSED, stale);+ writeTask("gap-stale", GAP_TASK_STATUS_CLOSED, { closedAt: stale });const run = await runHook("gap-promote",{ hook_event_name: "SessionEnd" },@@ -228,7 +247,7 @@ describe("gap-promote hook audit line", () => {// auto-close pass anything to recall.const recent = new Date().toISOString();for (let i = 0; i < GAP_TASKS_MAX_NOTES; i++) {- writeTask(`gap-filler-${i}`, GAP_TASK_STATUS_CLOSED, recent);+ writeTask(`gap-filler-${i}`, GAP_TASK_STATUS_CLOSED, { closedAt: recent });}seedGap("alpha topic", 3);const run = await runHook(@@ -242,6 +261,52 @@ describe("gap-promote hook audit line", () => {expect(details?.["promoted"]).toBe(0);expect(listGapTasks(vault)).toHaveLength(GAP_TASKS_MAX_NOTES);});++ // The two tests below drive the WHOLE hook, not `autoCloseRecalledGaps`+ // in isolation, because the fault they exist to catch lives in the+ // wiring rather than in either piece. The gate takes a retriever of+ // `(topic, admits)`; a plain one-argument `RecallRetriever` is+ // structurally assignable to that type, so passing one type-checks+ // cleanly, ignores the membership rule, returns the gap-task note+ // itself and makes the gate throw - into the hook's outer catch, which+ // left every run doing nothing. Only an end-to-end run can tell the+ // difference: a core-level test supplies its own retriever and so can+ // never observe which one the hook actually passes.+ const COVERED_TOPIC = "widget calibration procedure";++ test("closes a gap task the vault now covers outside the gap area", async () => {+ writeTask("gap-covered", GAP_TASK_STATUS_OPEN, { topic: COVERED_TOPIC });+ writeCoveringNote(COVERED_TOPIC);+ const run = await runHook(+ "gap-promote",+ { hook_event_name: "SessionEnd" },+ { VAULT_DIR: vault, ...FLAG_ON },+ );+ expect(run.exit).toBe(0);+ const [details] = auditDetails();+ expect(details).toBeDefined();+ expect(details?.["closed"]).toBe(1);+ expect(details?.["kept"]).toBe(0);+ expect(listGapTasks(vault, { status: GAP_TASK_STATUS_CLOSED }).map((t) => t.key)).toEqual([+ "gap-covered",+ ]);+ });++ test("keeps a gap task whose only match is its own note", async () => {+ writeTask("gap-uncovered", GAP_TASK_STATUS_OPEN, { topic: COVERED_TOPIC });+ const run = await runHook(+ "gap-promote",+ { hook_event_name: "SessionEnd" },+ { VAULT_DIR: vault, ...FLAG_ON },+ );+ expect(run.exit).toBe(0);+ const [details] = auditDetails();+ expect(details?.["closed"]).toBe(0);+ expect(details?.["kept"]).toBe(1);+ expect(listGapTasks(vault, { status: GAP_TASK_STATUS_OPEN }).map((t) => t.key)).toEqual([+ "gap-uncovered",+ ]);+ });});describe("gap-agenda hook (SessionStart)", () => {diff --git a/tests/hooks/recall-inject.test.ts b/tests/hooks/recall-inject.test.tsindex 93e51009..bf4beb96 100644--- a/tests/hooks/recall-inject.test.ts+++ b/tests/hooks/recall-inject.test.ts@@ -190,17 +190,82 @@ describe("recall-inject telemetry", () => {expect(String(details["detail"])).toContain("brain.sqlite");});- test("the two projections agree wherever nothing is being withheld", () => {- const decisions: ReadonlyArray<RecallInjectDecision> = [- { kind: "inject", brief: "a fenced brief", noteCount: 2, topScore: 0.9 },- { kind: "abstain", reason: "empty_prompt", topScore: 0 },- { kind: "error", fault: RECALL_INJECT_FAULT.timeout },- ];- for (const decision of decisions) {- expect(recallInjectAuditDetails(decision), decision.kind).toEqual(- recallInjectTelemetryMetadata(decision) as Record<string, unknown>,- );- }+ test("the telemetry projection carries the whole decision, match quality included", () => {+ // Asserted against literals rather than against the other projection.+ // Comparing the two proves nothing: `recallInjectAuditDetails` RETURNS+ // the telemetry object unchanged except on `error` with a `detail`, so+ // over these three fixtures the comparison is an identity, and every+ // field could be deleted from both with the test still green.+ // `match_quality` is the field that reaches the synced continuity log+ // and `brain_recall_telemetry`, so it is the one that needs naming.+ expect(+ recallInjectTelemetryMetadata({+ kind: "inject",+ brief: "a fenced brief",+ noteCount: 2,+ topScore: 0.9,+ matchQuality: 0.8,+ }),+ ).toEqual({ decision: "inject", note_count: 2, top_score: 0.9, match_quality: 0.8 });+ expect(+ recallInjectTelemetryMetadata({+ kind: "abstain",+ reason: "below_floor",+ topScore: 0.65,+ matchQuality: 0.2,+ }),+ ).toEqual({+ decision: "abstain",+ reason: "below_floor",+ top_score: 0.65,+ match_quality: 0.2,+ });+ // An unmeasurable quality travels as null, not as a substituted+ // number: the log must be able to say "there was no measurement".+ expect(+ recallInjectTelemetryMetadata({+ kind: "abstain",+ reason: "unmeasurable_quality",+ topScore: 0.65,+ matchQuality: null,+ }),+ ).toEqual({+ decision: "abstain",+ reason: "unmeasurable_quality",+ top_score: 0.65,+ match_quality: null,+ });+ expect(recallInjectTelemetryMetadata({ kind: "error", fault: RECALL_INJECT_FAULT.timeout }))+ // The error projection carries no quality and no score at all.+ .toEqual({ decision: "error", fault: RECALL_INJECT_FAULT.timeout });+ });++ test("the audit projection adds the message and nothing else", () => {+ // The one place the two projections may differ, stated as a+ // difference rather than as an identity over fixtures that cannot+ // produce one.+ const withDetail: RecallInjectDecision = {+ kind: "error",+ fault: RECALL_INJECT_FAULT.retrieverFailed,+ detail: "disk I/O error",+ };+ expect(recallInjectAuditDetails(withDetail)).toEqual({+ decision: "error",+ fault: RECALL_INJECT_FAULT.retrieverFailed,+ detail: "disk I/O error",+ });+ const noDetail: RecallInjectDecision = { kind: "error", fault: RECALL_INJECT_FAULT.timeout };+ expect(recallInjectAuditDetails(noDetail)).toEqual(+ recallInjectTelemetryMetadata(noDetail) as Record<string, unknown>,+ );+ // And an abstain never grows one, however the retriever failed.+ const abstain: RecallInjectDecision = {+ kind: "abstain",+ reason: "no_matches",+ topScore: 0,+ matchQuality: 0,+ };+ expect(Object.keys(recallInjectAuditDetails(abstain))).not.toContain("detail");});test("every fault a decision can carry is a member of the closed vocabulary", () => {diff --git a/tests/hooks/subagent-stop.test.ts b/tests/hooks/subagent-stop.test.tsnew file mode 100644index 00000000..f4ca17c6--- /dev/null+++ b/tests/hooks/subagent-stop.test.ts@@ -0,0 +1,201 @@+/**+ * The delegation boundary the host already delivers (U7 / t_0c6f31ee).+ *+ * Three defects this suite exists to catch:+ *+ * - `SubagentStop` is in the host's official event list and+ * `hooks/hooks.json` registered seven events without it, so the one+ * event that names a delegation boundary was never delivered anywhere.+ * - The delegated identity the event carries (`agent_id`) was not+ * normalised, so a sub-agent's lifecycle observation was attributed to+ * the session's own agent and the roster could not tell the two apart.+ * - `tool_response` is declared on the hook payload and was lifted past+ * by the lifecycle normaliser, so a `brain_feedback` call the host+ * reported as FAILED was still replayed into a signal - a record for a+ * write that never happened.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { captureSessionLifecycleEvent } from "../../src/core/brain/session-lifecycle.ts";++const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");+const HOOKS_JSON = join(REPO, "hooks", "hooks.json");+const HOOK = join(REPO, "hooks", "session-capture.ts");++/** The event name the host fires when a delegated sub-agent finishes. */+const SUBAGENT_STOP = "SubagentStop";+/** A delegated agent id in the shape the host delivers it. */+const AGENT_ID = "7f3c21ab-9d40-4c6e-8b21-0e5c7a1d33f2";++let vault: string;+let configHome: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-subagent-stop-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-subagent-stop-home-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++async function runHook(+ payload: unknown,+): Promise<{ stdout: string; stderr: string; exit: number }> {+ const proc = Bun.spawn(["bun", "run", HOOK], {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ env: {+ PATH: process.env["PATH"] ?? "",+ HOME: configHome,+ VAULT_DIR: vault,+ VAULT_AGENT_NAME: "claude-vps-agent",+ },+ });+ proc.stdin.write(JSON.stringify(payload));+ await proc.stdin.end();+ const [stdout, stderr] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ return { stdout, stderr, exit: await proc.exited };+}++function logBodies(root: string): string {+ const dir = join(root, "Brain", "log");+ return readdirSync(dir)+ .filter((name) => name.endsWith(".md"))+ .map((name) => readFileSync(join(dir, name), "utf8"))+ .join("\n");+}++describe("hooks.json — SubagentStop registration", () => {+ const parsed = JSON.parse(readFileSync(HOOKS_JSON, "utf8")) as {+ hooks: Record<string, Array<{ matcher?: string; hooks: Array<{ command: string }> }>>;+ };++ test("registers the delegation boundary alongside Stop", () => {+ const groups = parsed.hooks[SUBAGENT_STOP];+ expect(groups).toBeDefined();+ expect(groups!.length).toBeGreaterThan(0);+ const commands = groups!.flatMap((group) => group.hooks.map((h) => h.command));+ expect(commands.some((cmd) => cmd.includes("session-capture"))).toBe(true);+ });+});++describe("SubagentStop capture", () => {+ test("the hook records the event and stays silent to the runtime", async () => {+ const result = await runHook({+ hook_event_name: SUBAGENT_STOP,+ session_id: "delegation-session",+ agent_id: AGENT_ID,+ cwd: "/tmp",+ stop_hook_active: false,+ });++ expect(result.exit).toBe(0);+ expect(result.stdout).toBe("");+ expect(result.stderr).toBe("");+ expect(logBodies(vault)).toContain(SUBAGENT_STOP);+ });++ test("the observation is attributed to the delegated identity", async () => {+ const result = await captureSessionLifecycleEvent(+ vault,+ {+ hook_event_name: SUBAGENT_STOP,+ session_id: "delegation-session",+ agent_id: AGENT_ID,+ },+ { agent: "claude-vps-agent", now: new Date("2026-06-01T09:00:30Z") },+ );++ expect(result.event).toBe(SUBAGENT_STOP);+ expect(result.agent_id).toBe(AGENT_ID);+ const log = logBodies(vault);+ expect(log).toContain("claude-vps-agent-sub-7f3c21ab");+ });++ test("an ordinary Stop carries no delegated identity", async () => {+ const result = await captureSessionLifecycleEvent(+ vault,+ { hook_event_name: "Stop", session_id: "delegation-session" },+ { agent: "claude-vps-agent", now: new Date("2026-06-01T09:01:00Z") },+ );+ expect(result.agent_id).toBeUndefined();+ expect(logBodies(vault)).not.toContain("-sub-");+ });+});++describe("tool_response — carried, not dropped", () => {+ const feedback = {+ topic: "tool-response",+ signal: "positive",+ principle: "a failed tool call is not a record",+ };++ test("a failed brain_feedback call is not replayed as a signal", async () => {+ const result = await captureSessionLifecycleEvent(+ vault,+ {+ hook_event_name: "PostToolUse",+ session_id: "tool-response-session",+ tool_name: "brain_feedback",+ tool_input: feedback,+ tool_response: { is_error: true, content: "write refused" },+ },+ { agent: "claude-vps-agent", now: new Date("2026-06-01T10:00:00Z") },+ );++ expect(result.signals_created).toBe(0);+ expect(result.tool_replays).toBe(0);+ expect(result.malformed).toBe(0);+ expect(result.tool_calls_failed).toBe(1);+ expect(+ readdirSync(join(vault, "Brain", "inbox")).filter((name) => name.endsWith(".md")),+ ).toHaveLength(0);+ });++ test("a successful call is replayed and reports no failure", async () => {+ const result = await captureSessionLifecycleEvent(+ vault,+ {+ hook_event_name: "PostToolUse",+ session_id: "tool-response-session",+ tool_name: "brain_feedback",+ tool_input: feedback,+ tool_response: { is_error: false },+ },+ { agent: "claude-vps-agent", now: new Date("2026-06-01T10:00:01Z") },+ );++ expect(result.signals_created).toBe(1);+ expect(result.tool_replays).toBe(1);+ expect(result.tool_calls_failed).toBeUndefined();+ });++ test("a call the host said nothing about is replayed exactly as before", async () => {+ const result = await captureSessionLifecycleEvent(+ vault,+ {+ hook_event_name: "PostToolUse",+ session_id: "tool-response-quiet",+ tool_name: "brain_feedback",+ tool_input: { ...feedback, topic: "tool-response-quiet" },+ },+ { agent: "claude-vps-agent", now: new Date("2026-06-01T10:00:02Z") },+ );++ expect(result.signals_created).toBe(1);+ expect(result.tool_calls_failed).toBeUndefined();+ });+});diff --git a/tests/mcp/agent-scope-matrix.test.ts b/tests/mcp/agent-scope-matrix.test.tsindex db588639..eba5bacc 100644--- a/tests/mcp/agent-scope-matrix.test.ts+++ b/tests/mcp/agent-scope-matrix.test.ts@@ -13,24 +13,73 @@* test until someone classifies it, and a removed tool fails it until* someone deletes the entry. That is the mechanism; the per-surface* assertions below are what it protects.+ *+ * ## What the partition was worth on its own (a-label-is-not-a-boundary, U3)+ *+ * Nothing. `SCOPED_SURFACES` carried behavioural tests; the other two+ * buckets carried a name and, in one of them, a prose reason nothing+ * read. A sweep against a two-owner vault under+ * `integrity.owner_scope_delivery: fail` found TEN classified-as-safe+ * tools returning another owner's artifact ids, paths, titles and body+ * prose. A bucket whose membership claim is never executed is a label,+ * and the release this unit belongs to is about what a label is worth.+ *+ * So both unasserted buckets now carry `{name, args, reason}`: the+ * arguments that DRIVE the tool, and a written reason for the+ * classification. {@link assertProbeEntry} refuses an entry without+ * them at module load, and {@link ProbeEntry} refuses one at+ * `bun run typecheck`, so the bucket cannot regrow as a bare name list.+ * Every entry is then driven against one two-owner fixture and its+ * response — or the message it threw — is asserted to carry no marker+ * unique to the other owner's artifacts.*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { indexVault, resolveSearchConfig, search } from "../../src/core/search/index.ts";import { GATE_MODE } from "../../src/core/integrity/stamp.ts";-import { brainActivePath, brainConfigPath } from "../../src/core/brain/paths.ts";+import { brainActivePath, brainConfigPath, brainDirs } from "../../src/core/brain/paths.ts";import { regenerateActive } from "../../src/core/brain/active.ts";+import { appendLogEvent } from "../../src/core/brain/log.ts";import { writePreference } from "../../src/core/brain/preference.ts";+import { runHygieneScan } from "../../src/core/brain/hygiene/scan.ts";+import { scanTriggers } from "../../src/core/brain/triggers/scan.ts";+import { transitionTrigger } from "../../src/core/brain/triggers/store.ts";import { writeSignal } from "../../src/core/brain/signal.ts";-import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";+import {+ BRAIN_CONFIDENCE,+ BRAIN_LOG_EVENT_KIND,+ BRAIN_PREFERENCE_STATUS,+} from "../../src/core/brain/types.ts";+import { OWNER_SCOPE_REFUSAL } from "../../src/mcp/owner-scope-refusal.ts";import { buildToolTable } from "../../src/mcp/tools.ts";import type { ServerContext, ToolDefinition } from "../../src/mcp/tool-contract.ts";+/**+ * HOME is pinned for THIS file, and nothing pins it globally.+ *+ * `resolveDeviceId`, `resolveAgentName` and the profile writer all fall+ * back to the operator's real `~/.config/open-second-brain/config.yaml`+ * when a call supplies no explicit config path, and the isolation probe+ * below drives every writer in the tool table. A global pin would hide+ * the config-reading behaviour other suites exist to exercise, so the+ * file that needs the pin sets it - at module scope, which runs before+ * any test body and before any of these tools is ever called.+ */+process.env["HOME"] = mkdtempSync(join(tmpdir(), "o2b-scope-matrix-home-"));+const OWNER_A = "agent-a";const OWNER_B = "agent-b";const QUERY = "lattice widgets";@@ -38,6 +87,39 @@ const QUERY = "lattice widgets";const PROBE = "lattice.md";const PROBE_TERMS = `${PROBE} lattice`;+/**+ * The string the isolation probe hunts for.+ *+ * It appears ONLY inside artifacts owned by {@link OWNER_A} - in their+ * ids, their paths, their topics, their titles and their body prose - so+ * one `not.toContain` catches every channel a surface might use to name+ * one of them, without the probe having to know which field carried it.+ */+const CROSS_OWNER_MARKER = "secretmarkerzz";++/** The UTC day the fixture's log event lands on; `brain_event_trace` selects by date. */+const LOG_EVENT_DATE = "2026-05-04";++/** Shared hub the fixture's MOC audit is driven against. */+const HUB_ID = "pref-hub";+/** Shared preference every owner-A artifact references, and the probe's link target. */+const SHARED_ID = "pref-shared";+/** Title of {@link SHARED_ID}; the term `brain_unlinked_mentions` matches on. */+const SHARED_TITLE = "Shared Pref";+/**+ * Topic of {@link SHARED_ID}, and deliberately ALSO the topic of one+ * owner-A preference.+ *+ * A `topic:` argument is a fan-out: `buildBeliefEvolution` resolves it to+ * every `pref-`/`ret-` page carrying that topic, so a caller naming a+ * topic it is entitled to still reaches preferences it is not. Probing+ * that with a marker-bearing topic would prove nothing - the marker+ * would be the caller's own argument echoed back.+ */+const SHARED_TOPIC = "shared";+/** Slug of the ownerless signal that evidences the owner-A preference. */+const NEUTRAL_SIGNAL_SLUG = "neutral-probe-signal";+/** How a surface learns which agent is asking. */const SCOPE_SOURCE = Object.freeze({/** An explicit `agent_scope` input argument. */@@ -80,129 +162,895 @@ const SCOPED_SURFACES: ReadonlyArray<ScopedSurface> = [{ name: "brain_agent_query", source: SCOPE_SOURCE.argument, gated: false },];+/**+ * One probe recipe: the arguments that DRIVE one mode / view / operation+ * of a tool against the two-owner fixture, and a written reason for the+ * classification THAT CALL carries.+ *+ * The reason lives on the call rather than on the tool because a tool is+ * not one classification. `brain_analytics view=concept_synthesis`+ * reaches another owner's body prose and `view=dedup` reaches an ingest+ * counter; one entry claiming one reason for both is the same+ * unexecuted label this file exists to remove, and it is how+ * `concept_synthesis` shipped unfiltered behind a green `view=timeline`.+ */+interface ProbeCall {+ /**+ * Arguments the isolation probe calls the tool with, or a function of+ * the vault that computes them after the fixture is seeded.+ *+ * `{}` only where the tool's input schema declares no property the+ * probe needs, never as a stand-in for "I did not work out what+ * drives this one". The function form exists for the one recipe whose+ * arguments are derived from vault state - `brain_hygiene mode=apply`+ * selects findings by id, and a static id would drive a call that+ * matches nothing.+ */+ readonly args: Record<string, unknown> | ((vault: string) => Record<string, unknown>);+ /** Why THIS call sits in the bucket it sits in. */+ readonly reason: string;+ /**+ * Test-name suffix for a recipe whose arguments are computed, where+ * the dispatch key cannot be read off a literal record.+ */+ readonly label?: string;+}++/** One tool, and every call recipe the probe drives it with. */+interface ProbeEntry {+ readonly name: string;+ readonly calls: ReadonlyArray<ProbeCall>;+}++/** A single-recipe entry, spelled without the array ceremony. */+function one(args: ProbeCall["args"], reason: string): ReadonlyArray<ProbeCall> {+ return [{ args, reason }];+}++/**+ * Shortest reason this file accepts. A one-word reason is the bare name+ * list with extra punctuation, so the floor is set above it.+ */+const REASON_MIN_CHARS = 24;++/**+ * Refuse an entry that carries no call recipes or no reason.+ *+ * `unknown` rather than {@link ProbeEntry}: the compiler already rejects+ * a bare name, and this is the second lock, for a `satisfies`-free cast+ * or a bucket built at runtime. It runs at module load over every entry,+ * so a nameless-args entry fails the whole file rather than one test.+ */+function assertProbeEntry(bucket: string, entry: unknown): ProbeEntry {+ if (typeof entry !== "object" || entry === null) {+ throw new Error(`${bucket}: every entry must be a {name, calls} record`);+ }+ const row = entry as Partial<ProbeEntry>;+ if (typeof row.name !== "string" || row.name.length === 0) {+ throw new Error(`${bucket}: every entry must name a tool`);+ }+ if (!Array.isArray(row.calls) || row.calls.length === 0) {+ throw new Error(+ `${bucket}: ${row.name} has no 'calls'; a bucket entry the probe cannot call is a label`,+ );+ }+ for (const recipe of row.calls) {+ const shaped = recipe as Partial<ProbeCall>;+ const args = shaped.args;+ const argsOk =+ typeof args === "function" ||+ (typeof args === "object" && args !== null && !Array.isArray(args));+ if (!argsOk) {+ throw new Error(+ `${bucket}: ${row.name} has a call with no 'args'; a recipe the probe cannot call is a label`,+ );+ }+ if (typeof shaped.reason !== "string" || shaped.reason.trim().length < REASON_MIN_CHARS) {+ throw new Error(+ `${bucket}: ${row.name} needs a reason of at least ${REASON_MIN_CHARS} characters`,+ );+ }+ }+ return row as ProbeEntry;+}++/**+ * Reasons shared by more than one call, named once.+ *+ * The alternative - hundreds of hand-written sentences, most of them+ * saying the same thing in different words - is the natural-language+ * word list this repository forbids, and it would make two calls with+ * the same classification look like two different classifications.+ *+ * Each of these is a CLAIM the differential below executes. Every reason+ * except {@link REASON.ownerFiltered} asserts that the call cannot name+ * an owner-private artifact AT ALL, so the probe requires the marker to+ * be absent even with the gate OFF, where nothing is hidden. A call that+ * surfaces the marker unscoped has a false reason and fails here, which+ * is the difference between a classification and a label.+ */+const REASON = Object.freeze({+ sessionLane:+ "session transcript lane: the records are keyed by session and turn, not by an " ++ "owner-taggable page, so `pageOwner` has no subject to read.",+ catalog:+ "a catalog of this server's own surface - the tool table, the skills manifest, the " ++ "preset list - answered without opening a vault page, so no page's owner is reachable.",+ writerEcho:+ "a writer: the response echoes the artifact this very call created, planned or refused, " ++ "so the only ownership it can name is the one the caller supplied.",+ callerNamedArtifact:+ "answers only about the artifact the caller already named, and every response shape it " ++ "can produce is distinguishable from a refusal - so a filter here would announce the " ++ "existence of the page it is meant to hide.",+ ownerlessLane:+ "reads a lane that carries no `owner:` field at all - triggers, entities, decisions, " ++ "obligations, telemetry ledgers - so there is no ownership claim on disk to enforce.",+ aggregateOnly:+ "reports counts, rates and verdicts over the vault with no per-artifact identity in the " ++ "payload; a hidden page contributes to a number the caller cannot decompose.",+ ownerFiltered:+ "reaches owner-taggable artifacts and is filtered through the ownership rule before it " ++ "answers (a-label-is-not-a-boundary, U3); the probe below is what holds that true.",+ configuredCorpus:+ "operates on an operator-configured corpus outside `Brain/` - a dataset file, a source " ++ "directory, a codegraph index - which carries no page frontmatter to own.",+ signalCluster:+ "reads the pre-dream review over INBOX SIGNAL clusters. A signal carries no `owner:` " ++ "anywhere in this product, so every row here - a topic, a decision, a count - is a fold " ++ "over shared artifacts and names no owner-private page.",+ recompileLane:+ "plans a recompile of DERIVED pages whose sources moved (`Brain/sources`, `Brain/reports`). " ++ "The fixture holds no derived page, so this recipe reaches no owner-taggable content; the " ++ "gap is recorded rather than papered over with a recipe that cannot fail.",+ signalAuthorship:+ "groups SIGNALS by the `agent:` that wrote them. A signal carries no `owner:` anywhere in " ++ "this product, so the agent column names the author of a SHARED artifact - the same fact " ++ "`brain_agent_query`'s roster publishes by design - and never an owner-private page.",+});++/**+ * The one reason that claims a call REACHES owner-bearing content.+ *+ * Named as a set rather than compared inline so the differential's+ * exemption is an explicit list of classifications, not a silence: every+ * other reason in {@link REASON} asserts unreachability, and the probe+ * holds it to that.+ */+const REASONS_REACHING_OWNER_CONTENT: ReadonlySet<string> = new Set([REASON.ownerFiltered]);++/**+ * Measured shape of the probe, quoted in `docs/architecture.md`,+ * `docs/mcp.md` and the release notes. Equalities, not floors - see the+ * test that reads them.+ */+const PROBE_ENTRY_COUNT = 96;+const PROBE_RECIPE_COUNT = 220;+const PROBE_TWO_SIDED_COUNT = 31;++/**+ * `brain_trigger` read arguments, with the queue populated first.+ *+ * `list` and `history` read what a PRIOR scan persisted, so against an+ * empty queue their isolation claim is untestable - the "clean sweep+ * over an empty fixture" this file exists to prevent. The scan is done+ * HERE rather than in {@link seedTwoOwnerFixture} because a populated+ * queue suppresses `brain_idea_discovery`: idea discovery skips+ * candidates already queued, so seeding globally would silently empty+ * that probe instead.+ *+ * `terminal` dismisses what the scan created, because `history` reports+ * only terminal records and `list` reports only non-terminal ones - one+ * queue state cannot exercise both. Each recipe gets its own vault, so+ * the two states never collide.+ */+function triggerQueueArgs(+ operation: string,+ terminal = false,+): (vault: string) => Record<string, unknown> {+ return (vault: string) => {+ const now = new Date();+ const scan = scanTriggers(vault, { now });+ if (terminal) {+ for (const record of scan.created) transitionTrigger(vault, record.id, "dismiss", { now });+ }+ return { operation };+ };+}++/**+ * `brain_hygiene mode=apply` arguments, derived from a live scan.+ *+ * A finding id is `sha256(targets.sorted().join("\0")).slice(0, 12)`+ * (`hygiene/detectors/id.ts`) - derivable rather than secret, which is+ * why withholding it from the scan was never the boundary. A LITERAL id+ * in the recipe would select nothing and the probe would go green over+ * an apply that did nothing, which is exactly how this mode shipped+ * planning against the unfiltered report.+ */+function hygieneApplyArgs(vault: string): Record<string, unknown> {+ return {+ mode: "apply",+ ids: runHygieneScan(vault, { now: new Date() }).findings.map((f) => f.id),+ };+}+/*** Tools that return vault content but are NOT owner-scoped after this* wave. Listed with a reason so the gap is recorded rather than* forgotten — this is the honest half of the matrix.*/-const UNSCOPED_CONTENT: ReadonlyArray<{ readonly name: string; readonly reason: string }> = [- { name: "brain_session_grep", reason: "session transcript lane, not owner-taggable pages" },- { name: "brain_session_expand", reason: "session transcript lane, not owner-taggable pages" },- { name: "brain_session_summary", reason: "session transcript lane, not owner-taggable pages" },- { name: "brain_session_describe", reason: "session transcript lane, not owner-taggable pages" },+const UNSCOPED_CONTENT: ReadonlyArray<ProbeEntry> = [+ { name: "brain_session_grep", calls: one({ query: QUERY }, REASON.sessionLane) },+ { name: "brain_session_expand", calls: one({ id: "sess-probe:0" }, REASON.sessionLane) },+ {+ name: "brain_session_summary",+ calls: [+ { args: { operation: "list" }, reason: REASON.sessionLane },+ { args: { operation: "get", session_id: "sess-probe" }, reason: REASON.sessionLane },+ {+ args: { operation: "write", session_id: "sess-probe", request: "probe digest" },+ reason: REASON.sessionLane,+ },+ ],+ },+ {+ name: "brain_session_describe",+ calls: one({ session_id: "sess-probe" }, REASON.sessionLane),+ },{name: "brain_note_history",- reason:+ calls: one(+ { path: "notes/shared.md" },"git commit metadata (subjects, authors, dates) for a path the caller already names, " +- "read from the repository rather than from page frontmatter. Every response shape it " +- "can produce - no repo, no commits, N phases - is distinguishable from a refusal, so a " +- "filter here would announce the existence of the page it is meant to hide while the " +- "same history stays readable through git itself.",+ "read from the repository rather than from page frontmatter. Every response shape it " ++ "can produce - no repo, no commits, N phases - is distinguishable from a refusal, so a " ++ "filter here would announce the existence of the page it is meant to hide while the " ++ "same history stays readable through git itself.",+ ),},{name: "brain_artifact_get",- reason:+ calls: one(+ { artifact_id: "art-never-issued" },"replays, by opaque id, a payload this process already returned to this caller - and " +- "already filtered under whatever scope produced it. The stored envelope keeps no page " +- "identity, so there is nothing left to re-apply the ownership rule to.",+ "already filtered under whatever scope produced it. The stored envelope keeps no page " ++ "identity, so there is nothing left to re-apply the ownership rule to.",+ ),},{name: "brain_pre_compact_extract",- reason: "extracts from caller-supplied text, not the vault",+ calls: one(+ { session_id: "sess-probe", turn_start: 1, turn_end: 2, text: QUERY },+ "extracts from caller-supplied text, not the vault: every byte of the response is " ++ "derived from the `text` argument the caller passed in.",+ ),+ },+ {+ name: "brain_recall_gate",+ calls: one(+ { prompt: QUERY },+ "a verdict over a caller-supplied question - recall/skip and why - with no artifact " ++ "identity and no body prose in the payload.",+ ),+ },+];++/**+ * Everything else: metadata, analytics, maintenance, writers, catalog.+ *+ * A tool with several modes, views or operations carries one recipe per+ * mode, view or operation. One executed view is not an executed+ * classification, and the two leaks this file missed - `brain_hygiene+ * mode=apply` writing across the boundary, and three of+ * `brain_analytics`' five views returning another owner's prose - were+ * both hidden behind a single green recipe for a sibling mode.+ */+const NON_CONTENT: ReadonlyArray<ProbeEntry> = [+ { name: "brain_agenda", calls: one({ events: [] }, REASON.writerEcho) },+ {+ name: "brain_agent_diff",+ calls: [+ { args: { mode: "browse" }, reason: REASON.ownerFiltered },+ { args: { mode: "search", query: CROSS_OWNER_MARKER }, reason: REASON.ownerFiltered },+ { args: { mode: "diff" }, reason: REASON.ownerFiltered },+ { args: { mode: "map" }, reason: REASON.ownerFiltered },+ ],+ },+ {+ name: "brain_analytics",+ calls: [+ { args: { view: "timeline" }, reason: REASON.ownerFiltered },+ { args: { view: "attention_flows", operation: "list" }, reason: REASON.ownerlessLane },+ // The topic is the SHARED one on purpose. A marker-bearing topic+ // would be the caller's own argument echoed back, which is not a+ // disclosure; the fixture instead gives an owner-A preference that+ // shared topic, so the fan-out from one topic to every preference+ // carrying it is what the probe measures.+ { args: { view: "belief_evolution", topic: SHARED_TOPIC }, reason: REASON.ownerFiltered },+ {+ args: { view: "concept_synthesis", id: SHARED_ID, include_unlinked: true },+ reason: REASON.ownerFiltered,+ },+ { args: { view: "dedup" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_append_note",+ calls: one({ path: "notes/shared.md", content: "probe append" }, REASON.writerEcho),+ },+ {+ name: "brain_apply_evidence",+ calls: one(+ { pref_id: "pref-shared", artifact: "[[notes/shared.md]]", result: "applied" },+ REASON.writerEcho,+ ),+ },+ { name: "brain_audit", calls: one({ pref_id: "pref-shared" }, REASON.callerNamedArtifact) },+ { name: "brain_backlinks", calls: one({ id: SHARED_ID }, REASON.ownerFiltered) },+ {+ name: "brain_benchmark",+ calls: one(+ { operation: "run", dataset: "datasets/probe-absent.jsonl" },+ REASON.configuredCorpus,+ ),+ },+ {+ name: "brain_bridges",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ { args: { operation: "discover" }, reason: REASON.ownerlessLane },+ {+ args: { operation: "accept", source: "notes/shared.md", target: "notes/owned-a.md" },+ reason: REASON.ownerlessLane,+ },+ {+ args: { operation: "dismiss", source: "notes/shared.md", target: "notes/owned-a.md" },+ reason: REASON.ownerlessLane,+ },+ ],+ },+ {+ name: "brain_claims",+ calls: [+ { args: { operation: "current" }, reason: REASON.ownerFiltered },+ { args: { operation: "at", at: LOG_EVENT_DATE }, reason: REASON.ownerFiltered },+ { args: { operation: "history" }, reason: REASON.ownerFiltered },+ { args: { operation: "replaced", id: SHARED_ID }, reason: REASON.callerNamedArtifact },+ { args: { operation: "contests", id: SHARED_ID }, reason: REASON.callerNamedArtifact },+ { args: { operation: "rebuild" }, reason: REASON.aggregateOnly },+ ],+ },+ {+ name: "brain_clusters",+ calls: [+ { args: { operation: "list" }, reason: REASON.aggregateOnly },+ { args: { operation: "run" }, reason: REASON.ownerFiltered },+ ],+ },+ { name: "brain_codegraph_report", calls: one({}, REASON.configuredCorpus) },+ {+ name: "brain_context_pack_outcome",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ { args: { operation: "summary" }, reason: REASON.ownerlessLane },+ {+ args: { operation: "post", sample_id: "probe-sample", first_pass_success: true },+ reason: REASON.ownerlessLane,+ },+ ],+ },+ {+ name: "brain_context_presets",+ calls: [+ { args: { operation: "show" }, reason: REASON.catalog },+ { args: { operation: "suggest" }, reason: REASON.catalog },+ { args: { operation: "diff" }, reason: REASON.catalog },+ ],+ },+ {+ name: "brain_context_receipts",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ { args: { operation: "summary" }, reason: REASON.ownerlessLane },+ { args: { operation: "show", id: "rcpt-probe-absent" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_create_note",+ calls: one({ path: "notes/probe-created.md" }, REASON.writerEcho),+ },+ {+ name: "brain_dead_ends",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ {+ args: { operation: "record", approach: "probe approach", reason: "probe reason" },+ reason: REASON.ownerlessLane,+ },+ ],+ },+ {+ name: "brain_decision",+ calls: [+ { args: { action: "list" }, reason: REASON.ownerlessLane },+ { args: { action: "show", id: "dec-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { action: "history" }, reason: REASON.ownerlessLane },+ { args: { action: "recall" }, reason: REASON.ownerlessLane },+ { args: { action: "similar", id: "dec-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { action: "compare", id: "dec-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { action: "outcome", id: "dec-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { action: "rate", id: "dec-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { action: "record", title: "probe decision" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_delete_by_source",+ calls: one({ source_file: "sources/paper.md" }, REASON.writerEcho),+ },+ {+ name: "brain_derive_fact",+ calls: one(+ {+ slug: "probe-derived",+ topic: "probe",+ principle: "probe derived principle",+ premises: [`[[${SHARED_ID}]]`],+ level: "deduced",+ },+ REASON.writerEcho,+ ),+ },+ { name: "brain_diarize", calls: one({ entity: "probe-entity" }, REASON.ownerlessLane) },+ {+ name: "brain_distill_source",+ calls: one({ source_path: "sources/paper.md", claims: ["probe claim"] }, REASON.writerEcho),+ },+ {+ name: "brain_doctor",+ calls: [+ { args: {}, reason: REASON.ownerFiltered },+ { args: { strict: true }, reason: REASON.ownerFiltered },+ { args: { repair: true }, reason: REASON.ownerFiltered },+ ],+ },+ {+ name: "brain_dream",+ calls: [+ { args: { action: "list" }, reason: REASON.aggregateOnly },+ { args: { action: "run", dry_run: true }, reason: REASON.ownerFiltered },+ { args: { action: "stage" }, reason: REASON.ownerFiltered },+ { args: { action: "validate", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },+ { args: { action: "apply", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },+ { args: { action: "discard", run_id: "run-probe-absent" }, reason: REASON.aggregateOnly },+ ],+ },+ {+ name: "brain_entity",+ calls: [+ { args: { view: "list" }, reason: REASON.ownerlessLane },+ { args: { view: "get", query: "probe-entity" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_eval",+ calls: one({ dataset: "datasets/probe-absent.jsonl" }, REASON.configuredCorpus),+ },+ { name: "brain_event_trace", calls: one({ date: LOG_EVENT_DATE }, REASON.ownerFiltered) },+ {+ name: "brain_feedback",+ calls: one(+ { topic: "probe", signal: "positive", principle: "probe principle" },+ REASON.writerEcho,+ ),+ },+ { name: "brain_foresight", calls: one({}, REASON.aggregateOnly) },+ {+ name: "brain_generation_reports",+ calls: [+ { args: { action: "list" }, reason: REASON.ownerlessLane },+ { args: { action: "summary" }, reason: REASON.ownerlessLane },+ {+ args: {+ action: "record",+ handoff_kind: "context_pack",+ ref: "probe-ref",+ agent: OWNER_B,+ prompt: "probe prompt",+ enable: true,+ },+ reason: REASON.ownerlessLane,+ },+ ],+ },+ { name: "brain_health", calls: one({}, REASON.ownerFiltered) },+ {+ name: "brain_hygiene",+ calls: [+ { args: { mode: "scan" }, reason: REASON.ownerFiltered },+ { args: { mode: "refresh", dry_run: true }, reason: REASON.recompileLane },+ // The ids come from a LIVE scan of the seeded fixture. A literal+ // id here would select nothing, and a recipe that selects nothing+ // is how `apply` kept a green probe while planning against the+ // unfiltered report and retiring another owner's preference.+ { args: hygieneApplyArgs, label: "mode=apply", reason: REASON.ownerFiltered },+ ],+ },+ { name: "brain_idea_discovery", calls: one({}, REASON.ownerFiltered) },+ { name: "brain_idea_lineage", calls: one({ id: SHARED_ID }, REASON.callerNamedArtifact) },+ {+ name: "brain_ingest_batch_plan",+ calls: one({ source_dir: "sources" }, REASON.configuredCorpus),+ },+ {+ name: "brain_ingest_source",+ calls: one(+ { source_path: "sources/paper.md", summary: "probe summary", entities: [] },+ REASON.writerEcho,+ ),+ },+ {+ name: "brain_intake_entities",+ calls: one({ entities: [], source: "sources/paper.md" }, REASON.writerEcho),+ },+ { name: "brain_intent_review", calls: one({}, REASON.signalCluster) },+ {+ name: "brain_intention",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ { args: { operation: "show" }, reason: REASON.ownerlessLane },+ { args: { operation: "set", text: "probe intention" }, reason: REASON.ownerlessLane },+ { args: { operation: "move", scope: "probe-scope" }, reason: REASON.ownerlessLane },+ ],+ },+ { name: "brain_knowledge_gaps", calls: one({}, REASON.aggregateOnly) },+ {+ name: "brain_labels",+ calls: [+ { args: { operation: "show", path: "notes/shared.md" }, reason: REASON.callerNamedArtifact },+ {+ args: {+ operation: "assign",+ path: "notes/shared.md",+ dimension: "probe",+ value: "probe",+ },+ reason: REASON.callerNamedArtifact,+ },+ {+ args: { operation: "remove", path: "notes/shared.md", dimension: "probe" },+ reason: REASON.callerNamedArtifact,+ },+ ],+ },+ {+ name: "brain_lifecycle",+ calls: [+ { args: { action: "curator" }, reason: REASON.aggregateOnly },+ { args: { action: "tip", id: SHARED_ID }, reason: REASON.callerNamedArtifact },+ {+ args: { action: "tombstone", path: "notes/shared.md", reason: "probe" },+ reason: REASON.writerEcho,+ },+ {+ args: {+ action: "supersede",+ predecessor: "notes/shared.md",+ successor: `[[${SHARED_ID}]]`,+ reason: "probe",+ },+ reason: REASON.writerEcho,+ },+ {+ args: {+ action: "temporal-replace",+ predecessor: "notes/shared.md",+ successor: "notes/renamed.md",+ at: LOG_EVENT_DATE,+ },+ reason: REASON.writerEcho,+ },+ ],+ },+ {+ name: "brain_maintenance",+ calls: [+ { args: { operation: "status" }, reason: REASON.aggregateOnly },+ { args: { operation: "run", force: true }, reason: REASON.aggregateOnly },+ ],+ },+ { name: "brain_mcp_landscape", calls: one({}, REASON.catalog) },+ {+ name: "brain_memory_bridge",+ calls: [+ { args: {}, reason: REASON.writerEcho },+ {+ args: { action: "add", target: "memory", content: "probe memory" },+ reason: REASON.writerEcho,+ },+ {+ args: { action: "replace", target: "memory", content: "probe memory" },+ reason: REASON.writerEcho,+ },+ ],+ },+ { name: "brain_moc_audit", calls: one({ id: HUB_ID }, REASON.ownerFiltered) },+ { name: "brain_note", calls: one({ text: "probe note" }, REASON.writerEcho) },+ {+ name: "brain_note_lifecycle",+ calls: [+ {+ args: { action: "rename", path: "notes/shared.md", to: "notes/renamed.md" },+ reason: REASON.writerEcho,+ },+ {+ args: { action: "move", path: "notes/shared.md", to: "notes/moved.md" },+ reason: REASON.writerEcho,+ },+ { args: { action: "archive", path: "notes/shared.md" }, reason: REASON.writerEcho },+ { args: { action: "delete", path: "notes/shared.md" }, reason: REASON.writerEcho },+ ],+ },+ {+ name: "brain_obligation",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ { args: { operation: "show", slug: "probe-obligation" }, reason: REASON.ownerlessLane },+ {+ args: { operation: "add", title: "probe obligation", cadence: "weekly" },+ reason: REASON.ownerlessLane,+ },+ { args: { operation: "done", slug: "probe-obligation" }, reason: REASON.ownerlessLane },+ { args: { operation: "remove", slug: "probe-obligation" }, reason: REASON.ownerlessLane },+ ],+ },+ { name: "brain_observed_use", calls: one({ entries: [] }, REASON.writerEcho) },+ {+ name: "brain_pinned_context",+ calls: [+ { args: { operation: "read" }, reason: REASON.ownerlessLane },+ { args: { operation: "write", content: "probe pinned" }, reason: REASON.ownerlessLane },+ { args: { operation: "append", content: "probe pinned" }, reason: REASON.ownerlessLane },+ { args: { operation: "clear" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_procedural_graph",+ calls: [+ { args: { operation: "show" }, reason: REASON.ownerlessLane },+ { args: { operation: "rebuild" }, reason: REASON.ownerlessLane },+ { args: { operation: "hints" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_procedural_memory",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ { args: { operation: "reconcile" }, reason: REASON.ownerlessLane },+ { args: { operation: "mark_used", id: "proc-probe-absent" }, reason: REASON.ownerlessLane },+ {+ args: { operation: "mark_outcome", id: "proc-probe-absent", outcome: "success" },+ reason: REASON.ownerlessLane,+ },+ ],},- { name: "brain_recall_gate", reason: "verdict over a caller-supplied question, no bodies" },+ {+ name: "brain_recall_feedback",+ calls: one({ query: QUERY, result_path: "notes/shared.md", verdict: "up" }, REASON.writerEcho),+ },+ {+ name: "brain_recall_telemetry",+ calls: [+ { args: { operation: "summary" }, reason: REASON.ownerlessLane },+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ { args: { operation: "gate_list" }, reason: REASON.ownerlessLane },+ { args: { operation: "gate_summary" }, reason: REASON.ownerlessLane },+ { args: { operation: "observed_reuse" }, reason: REASON.ownerlessLane },+ { args: { operation: "cost" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_recurrence",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ { args: { operation: "show", content_hash: "probe-hash" }, reason: REASON.ownerlessLane },+ {+ args: { operation: "learn", content_hash: "probe-hash", scope: "probe" },+ reason: REASON.ownerlessLane,+ },+ {+ args: { operation: "forget", content_hash: "probe-hash", scope: "probe" },+ reason: REASON.ownerlessLane,+ },+ { args: { operation: "purge_source", source_id: "probe" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_research_report",+ calls: one(+ { title: "probe report", sources: ["sources/paper.md"], findings: ["probe finding"] },+ REASON.writerEcho,+ ),+ },+ { name: "brain_retention", calls: one({}, REASON.ownerFiltered) },+ { name: "brain_review_candidates", calls: one({}, REASON.ownerFiltered) },+ {+ name: "brain_route_metrics",+ calls: [+ { args: { operation: "summary" }, reason: REASON.ownerlessLane },+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_scaffold_stub",+ calls: [+ { args: { action: "list" }, reason: REASON.ownerFiltered },+ // A neutral target: naming the marker here would be the caller's+ // own argument echoed back by the writer, not a disclosure.+ { args: { action: "write", target: "Projects/ProbeStub" }, reason: REASON.writerEcho },+ ],+ },+ {+ name: "brain_secrets",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ {+ args: { operation: "run", name: "probe-secret", command: ["true"] },+ reason: REASON.ownerlessLane,+ },+ ],+ },+ {+ name: "brain_session_checkpoint",+ calls: one({ session_id: "sess-probe" }, REASON.writerEcho),+ },+ {+ name: "brain_skill_proposals",+ calls: [+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ { args: { operation: "learn" }, reason: REASON.ownerlessLane },+ { args: { operation: "usage" }, reason: REASON.ownerlessLane },+ { args: { operation: "recover" }, reason: REASON.ownerlessLane },+ { args: { operation: "evidence", slug: "probe-proposal" }, reason: REASON.ownerlessLane },+ { args: { operation: "accept", slug: "probe-proposal" }, reason: REASON.ownerlessLane },+ {+ args: { operation: "reject", slug: "probe-proposal", note: "probe" },+ reason: REASON.ownerlessLane,+ },+ ],+ },+ { name: "brain_sources", calls: one({}, REASON.signalAuthorship) },+ { name: "brain_stale_scan", calls: one({}, REASON.ownerFiltered) },+ { name: "brain_status", calls: one({}, REASON.aggregateOnly) },+ { name: "brain_switch_vault", calls: one({ name: "probe-profile" }, REASON.writerEcho) },+ {+ name: "brain_tension",+ calls: [+ { args: { action: "list" }, reason: REASON.ownerlessLane },+ { args: { action: "detect" }, reason: REASON.ownerlessLane },+ { args: { action: "show", id: "tension-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { action: "confirm", id: "tension-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { action: "dismiss", id: "tension-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { action: "resolve", id: "tension-probe-absent" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_tiers",+ calls: [+ { args: { operation: "check" }, reason: REASON.aggregateOnly },+ { args: { operation: "restore", path: "notes/shared.md" }, reason: REASON.aggregateOnly },+ { args: { operation: "accept", path: "notes/shared.md" }, reason: REASON.aggregateOnly },+ ],+ },+ {+ name: "brain_token_impact",+ calls: [+ { args: { operation: "summary" }, reason: REASON.ownerlessLane },+ { args: { operation: "list" }, reason: REASON.ownerlessLane },+ {+ args: { operation: "record", baseline_tokens: 100, packed_tokens: 50 },+ reason: REASON.ownerlessLane,+ },+ { args: { operation: "outcome", outcome: "first_pass" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_trigger",+ calls: [+ { args: triggerQueueArgs("list"), label: "operation=list", reason: REASON.ownerFiltered },+ { args: { operation: "scan" }, reason: REASON.ownerFiltered },+ {+ args: triggerQueueArgs("history", true),+ label: "operation=history",+ reason: REASON.ownerFiltered,+ },+ { args: { operation: "acknowledge", id: "trg-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { operation: "dismiss", id: "trg-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { operation: "act", id: "trg-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { operation: "suppress", id: "trg-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { operation: "unsuppress", id: "trg-probe-absent" }, reason: REASON.ownerlessLane },+ ],+ },+ {+ name: "brain_truth",+ calls: [+ { args: { operation: "slots" }, reason: REASON.ownerlessLane },+ { args: { operation: "conflicts" }, reason: REASON.ownerlessLane },+ { args: { operation: "collisions" }, reason: REASON.ownerlessLane },+ { args: { operation: "aggregate" }, reason: REASON.ownerlessLane },+ {+ args: {+ operation: "ingest",+ entity: "probe-entity",+ aspect: "probe-aspect",+ value: "probe",+ source: "[[notes/shared.md]]",+ },+ reason: REASON.ownerlessLane,+ },+ ],+ },+ {+ name: "brain_tune",+ calls: [+ { args: { operation: "status" }, reason: REASON.aggregateOnly },+ { args: { operation: "reset" }, reason: REASON.aggregateOnly },+ { args: { operation: "run" }, reason: REASON.aggregateOnly },+ ],+ },+ { name: "brain_unlinked_mentions", calls: one({ id: SHARED_ID }, REASON.ownerFiltered) },+ {+ name: "brain_update_note",+ calls: one({ path: "notes/shared.md", content: "probe update" }, REASON.writerEcho),+ },+ { name: "brain_watchdog", calls: one({}, REASON.aggregateOnly) },+ { name: "brain_write_batch", calls: one({ operations: [] }, REASON.writerEcho) },+ {+ name: "brain_write_session",+ calls: [+ { args: { op: "list" }, reason: REASON.ownerlessLane },+ { args: { op: "status", session_id: "ws-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { op: "open", target: "Brain/probe-session.md" }, reason: REASON.ownerlessLane },+ {+ args: { op: "submit", session_id: "ws-probe-absent", text: "probe text" },+ reason: REASON.ownerlessLane,+ },+ { args: { op: "approve", session_id: "ws-probe-absent" }, reason: REASON.ownerlessLane },+ { args: { op: "abandon", session_id: "ws-probe-absent" }, reason: REASON.ownerlessLane },+ ],+ },+ { name: "get_skill", calls: one({ name: "open-second-brain" }, REASON.catalog) },+ { name: "list_skills", calls: one({}, REASON.catalog) },+ { name: "schema_apply_mutations", calls: one({ mutations: [] }, REASON.writerEcho) },+ {+ name: "schema_inspect",+ calls: [+ { args: { view: "stats" }, reason: REASON.aggregateOnly },+ { args: { view: "graph" }, reason: REASON.aggregateOnly },+ { args: { view: "lint" }, reason: REASON.aggregateOnly },+ { args: { view: "orphans" }, reason: REASON.aggregateOnly },+ { args: { view: "packs" }, reason: REASON.catalog },+ { args: { view: "active_pack" }, reason: REASON.catalog },+ { args: { view: "explain_type", type: "brain-preference" }, reason: REASON.catalog },+ ],+ },+ { name: "second_brain_capabilities", calls: one({}, REASON.catalog) },+ { name: "second_brain_status", calls: one({}, REASON.aggregateOnly) },+ { name: "skills_attach", calls: one({ query: QUERY }, REASON.catalog) },+ { name: "tool_hydrate", calls: one({}, REASON.catalog) },+ { name: "vault_health", calls: one({}, REASON.aggregateOnly) },];-/** Everything else: metadata, analytics, maintenance, writers, catalog. */-const NON_CONTENT: ReadonlyArray<string> = [- "brain_agenda",- "brain_agent_diff",- "brain_analytics",- "brain_append_note",- "brain_apply_evidence",- "brain_audit",- "brain_backlinks",- "brain_benchmark",- "brain_bridges",- "brain_claims",- "brain_clusters",- "brain_codegraph_report",- "brain_context_pack_outcome",- "brain_context_presets",- "brain_context_receipts",- "brain_create_note",- "brain_dead_ends",- "brain_decision",- "brain_delete_by_source",- "brain_derive_fact",- "brain_diarize",- "brain_distill_source",- "brain_doctor",- "brain_dream",- "brain_entity",- "brain_eval",- "brain_event_trace",- "brain_feedback",- "brain_foresight",- "brain_generation_reports",- "brain_health",- "brain_hygiene",- "brain_idea_discovery",- "brain_idea_lineage",- "brain_ingest_batch_plan",- "brain_ingest_source",- "brain_intake_entities",- "brain_intent_review",- "brain_intention",- "brain_knowledge_gaps",- "brain_labels",- "brain_lifecycle",- "brain_maintenance",- "brain_mcp_landscape",- "brain_memory_bridge",- "brain_moc_audit",- "brain_note",- "brain_note_lifecycle",- "brain_obligation",- "brain_observed_use",- "brain_pinned_context",- "brain_procedural_graph",- "brain_procedural_memory",- "brain_recall_feedback",- "brain_recall_telemetry",- "brain_recurrence",- "brain_research_report",- "brain_retention",- "brain_review_candidates",- "brain_route_metrics",- "brain_scaffold_stub",- "brain_secrets",- "brain_session_checkpoint",- "brain_skill_proposals",- "brain_sources",- "brain_stale_scan",- "brain_status",- "brain_switch_vault",- "brain_tension",- "brain_tiers",- "brain_token_impact",- "brain_trigger",- "brain_truth",- "brain_tune",- "brain_unlinked_mentions",- "brain_update_note",- "brain_watchdog",- "brain_write_batch",- "brain_write_session",- "get_skill",- "list_skills",- "schema_apply_mutations",- "schema_inspect",- "second_brain_capabilities",- "second_brain_status",- "skills_attach",- "tool_hydrate",- "vault_health",+/**+ * Every entry the isolation probe drives, checked at module load.+ *+ * Both unasserted buckets, in one list: `SCOPED_SURFACES` is excluded+ * because its members are already driven, per surface, by the fifteen+ * behavioural tests below.+ */+const PROBE_ENTRIES: ReadonlyArray<ProbeEntry> = [+ ...UNSCOPED_CONTENT.map((e) => assertProbeEntry("UNSCOPED_CONTENT", e)),+ ...NON_CONTENT.map((e) => assertProbeEntry("NON_CONTENT", e)),];const TOOLS = buildToolTable("full");@@ -246,7 +1094,11 @@ function setGate(mode: string | null): void {writeFileSync(brainConfigPath(vault), `schema_version: 1\n${body}`);}-function makePref(slug: string, owner?: string): void {+function makePref(+ slug: string,+ owner?: string,+ overrides: Partial<Parameters<typeof writePreference>[1]> = {},+): void {writePreference(vault, {slug,topic: slug,@@ -262,6 +1114,7 @@ function makePref(slug: string, owner?: string): void {confidence: BRAIN_CONFIDENCE.high,confidence_value: 0.8,...(owner !== undefined ? { owner } : {}),+ ...overrides,});}@@ -297,11 +1150,7 @@ function contributionIds(result: { contributions: Array<{ id: string }> }): stri// ----- the mechanism --------------------------------------------------------test("the matrix classifies every tool exactly once", () => {- const classified = [- ...SCOPED_SURFACES.map((s) => s.name),- ...UNSCOPED_CONTENT.map((s) => s.name),- ...NON_CONTENT,- ];+ const classified = [...SCOPED_SURFACES.map((s) => s.name), ...PROBE_ENTRIES.map((s) => s.name)];expect(new Set(classified).size).toBe(classified.length);const actual = TOOLS.map((t) => t.name).toSorted();@@ -444,17 +1293,34 @@ test("brain_brief still serves those views without the argument", async () => {for (const out of served) expect(typeof out).toBe("string");});+/**+ * This test used to drive the same tool twice from ONE caller - `agent-b`+ * - naming `agent-a` once and itself once, and asserted that naming+ * `agent-a` returned MORE items. It passed, and what it pinned was the+ * leak: under `fail` the gate enforced the scope the caller asked for,+ * so a caller selected which owner's private memory it received+ * (a-label-is-not-a-boundary, U2). The count difference is still the+ * measurement, but each caller now names only itself, and the crossing+ * call is refused by name rather than counted.+ */test("brain_retrieval_plan counts only the memories its caller may see", async () => {setGate(GATE_MODE.fail);const asA = JSON.parse(- await call("brain_retrieval_plan", { question: QUERY, agent_scope: OWNER_A }),+ await call("brain_retrieval_plan", { question: QUERY, agent_scope: OWNER_A }, OWNER_A),);const asB = JSON.parse(- await call("brain_retrieval_plan", { question: QUERY, agent_scope: OWNER_B }),+ await call("brain_retrieval_plan", { question: QUERY, agent_scope: OWNER_B }, OWNER_B),);expect(asA.allocation.item_count).toBeGreaterThan(asB.allocation.item_count);});+test("brain_retrieval_plan refuses a caller that names another owner", async () => {+ setGate(GATE_MODE.fail);+ await expect(+ call("brain_retrieval_plan", { question: QUERY, agent_scope: OWNER_A }, OWNER_B),+ ).rejects.toThrow(OWNER_SCOPE_REFUSAL.foreignOwner);+});+// ----- ungated search-backed surfaces ---------------------------------------test("brain_search_expand refuses another owner's chunk as if it were absent", async () => {@@ -613,3 +1479,415 @@ test("brain_file_context and brain_deep_synthesis exclude another owner's page",expect(scoped, `${name} scoped`).toContain("notes/shared.md");}});++// ----- the isolation probe --------------------------------------------------++/**+ * Insert extra frontmatter lines and extra body text into an artifact the+ * shipped writer produced.+ *+ * The writers accept no `title` and no body, and the probe needs both: a+ * title is the only term `findUnlinkedMentions` matches on, and a body is+ * where `auditMoc` reads a hub's outbound cluster from. Patching the+ * writer's own output keeps every schema-owned field exactly as the+ * writer spelled it.+ */+function patchArtifact(rel: string, frontmatter: ReadonlyArray<string>, body: string): void {+ const abs = join(vault, rel);+ const text = readFileSync(abs, "utf8");+ const close = text.indexOf("\n---\n", "---\n".length);+ expect(close, `${rel} has no frontmatter block`).toBeGreaterThan(0);+ const head = frontmatter.length === 0 ? "" : `\n${frontmatter.join("\n")}`;+ const tail = body.length === 0 ? "" : `\n${body}\n`;+ writeFileSync(abs, text.slice(0, close) + head + text.slice(close) + tail);+}++/**+ * The two-owner fixture every {@link PROBE_ENTRIES} entry is driven+ * against.+ *+ * Additive to `beforeEach`, not a replacement for it: the per-surface+ * tests above pin exact ids and exact counts over the smaller vault, and+ * a fixture that grew under them would move those numbers for reasons+ * that have nothing to do with what they assert.+ *+ * Every artifact seeded here that belongs to {@link OWNER_A} carries+ * {@link CROSS_OWNER_MARKER} in its id, so a surface that names one -+ * as an id, a path, a topic, a title or a line of prose - fails the+ * probe without the probe having to know which field it used.+ *+ * The forced full index at the end is a precondition, not a habit:+ * `brain_scaffold_stub action=list` refuses on an incrementally-indexed+ * vault (`notes/scaffold-stub.ts` `partial_resolution`) and returns no+ * targets at all, which would read as a clean probe over a surface that+ * never ran.+ */+async function seedTwoOwnerFixture(): Promise<void> {+ const ownedPref = `${CROSS_OWNER_MARKER}-a`;+ const ownedPref2 = `${CROSS_OWNER_MARKER}-a2`;+ const ownedPrefOnSharedTopic = `${CROSS_OWNER_MARKER}-a3`;+ const ownedPrefDuplicate = `${CROSS_OWNER_MARKER}-a4`;++ // The evidence signal is deliberately NEUTRAL-named and ownerless: a+ // signal carries no `owner:` anywhere in this product (`signal.ts` has+ // no such field), so a marker inside one would be a marker inside a+ // SHARED artifact and every `not.toContain` below would be asserting+ // against something the caller is entitled to read.+ writeSignal(vault, {+ topic: NEUTRAL_SIGNAL_SLUG,+ signal: "positive",+ agent: OWNER_A,+ principle: "principle for the neutral evidence signal",+ created_at: "2026-05-01T00:00:00Z",+ date: "2026-05-01",+ slug: NEUTRAL_SIGNAL_SLUG,+ source: [`[[${SHARED_ID}]]`],+ });++ // `applied_count: 0` is what the hygiene scan's usefulness detector+ // measures, and the finding it emits names the preference by id.+ const unused = { evidenced_by: [`[[sig-2026-05-01-${NEUTRAL_SIGNAL_SLUG}]]`], applied_count: 0 };+ makePref(ownedPref, OWNER_A, unused);+ makePref(ownedPref2, OWNER_A, { applied_count: 0 });+ // A THIRD owner-A preference carrying `ownedPref2`'s principle+ // verbatim, so the dedup detector nominates that pair for a MERGE -+ // the one hygiene action with an applier behind it. Without an+ // applicable finding, `mode=apply` returns nothing but opaque hashes+ // and the probe cannot see whether it wrote across the boundary.+ // Same TOPIC as well as the same principle: `findMergeCandidates`+ // buckets by `(topic, scope)` and only compares inside a bucket, so a+ // duplicate principle under a different topic is never nominated.+ makePref(ownedPrefDuplicate, OWNER_A, {+ applied_count: 0,+ topic: ownedPref2,+ principle: `principle for ${ownedPref2}`,+ });+ // Owner-A's preference on the SHARED topic: the artifact a topic+ // fan-out reaches without the caller ever naming it.+ makePref(ownedPrefOnSharedTopic, OWNER_A, { topic: SHARED_TOPIC });+ makePref("hub");++ // The shared preference gains the title the mention scanner matches on;+ // the owner-A preference gains a body that spells that title in raw+ // prose, which is the unlinked mention that must not cross.+ patchArtifact(`Brain/preferences/${SHARED_ID}.md`, [`title: ${SHARED_TITLE}`], "");+ patchArtifact(+ `Brain/preferences/pref-${ownedPref}.md`,+ [`supersedes: "[[${SHARED_ID}]]"`],+ `See [[${SHARED_ID}]]. Also ${SHARED_TITLE} ${CROSS_OWNER_MARKER} here.`,+ );+ // A shared hub whose outbound cluster names both owner-A members plus a+ // target that does not exist: `wellCovered`/`fragile` classify the two+ // that resolve, `candidateMissing` names the one that does not.+ patchArtifact(+ `Brain/preferences/${HUB_ID}.md`,+ [],+ `Hub. [[pref-${ownedPref}]] [[pref-${ownedPref2}]] [[${SHARED_ID}]] [[missing-shared-member]]`,+ );++ writeFileSync(+ join(brainDirs(vault).retired, `ret-${CROSS_OWNER_MARKER}-a.md`),+ [+ "---",+ "kind: brain-retired",+ `id: ret-${CROSS_OWNER_MARKER}-a`,+ `owner: ${OWNER_A}`,+ "created_at: 2026-05-01T00:00:00Z",+ "tags: []",+ `topic: ${CROSS_OWNER_MARKER}-a`,+ "principle: retired principle",+ "provenance: observed",+ "retired_at: 2026-05-03T00:00:00Z",+ `retired_by: "[[${SHARED_ID}]]"`,+ "retired_reason: superseded-by-context",+ "_status: retired",+ "_evidenced_by: []",+ "---",+ "",+ `See [[${SHARED_ID}]] and ${SHARED_TITLE} ${CROSS_OWNER_MARKER}.`,+ "",+ ].join("\n"),+ );++ writeFileSync(+ join(vault, "notes", `${CROSS_OWNER_MARKER}-a.md`),+ `---\nowner: ${OWNER_A}\n---\n\n${QUERY} ${PROBE_TERMS} [[missing-${CROSS_OWNER_MARKER}-target]]\n`,+ );++ for (const slug of [ownedPref, ownedPrefOnSharedTopic]) {+ appendLogEvent(+ vault,+ {+ timestamp: `${LOG_EVENT_DATE}T00:00:00Z`,+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,+ body: {+ path: `Brain/preferences/pref-${slug}.md`,+ preference: `[[pref-${slug}]]`,+ result: "applied",+ },+ },+ { deviceId: "" },+ );+ }++ await indexVault(resolveSearchConfig({ vault, configPath: ctx.configPath ?? undefined }), {+ force: true,+ });+}++/**+ * Drive one recipe and return everything the caller would see.+ *+ * A thrown message counts: a refusal that quotes the artifact it choked+ * on discloses exactly as much as a successful response would, and this+ * repository has already shipped one of those (`schema_inspect view=lint`+ * naming a host path in its parse error).+ */+async function probeResponse(name: string, args: Record<string, unknown>): Promise<string> {+ try {+ return await call(name, args, OWNER_B);+ } catch (err) {+ return `threw: ${err instanceof Error ? err.message : String(err)}`;+ }+}++/** Resolve a recipe's arguments against the seeded fixture. */+function probeArgs(recipe: ProbeCall): Record<string, unknown> {+ return typeof recipe.args === "function" ? recipe.args(vault) : recipe.args;+}++/**+ * A recipe's test name: the tool plus whatever selects the code path.+ *+ * Read off the recipe rather than hand-written, so a recipe added later+ * cannot be the one with a name that no longer matches its arguments.+ */+const DISPATCH_KEYS = ["mode", "view", "operation", "action", "op"] as const;++function probeLabel(name: string, recipe: ProbeCall, index: number): string {+ if (recipe.label !== undefined) return `${name} ${recipe.label}`;+ if (typeof recipe.args === "function") return `${name} #${index}`;+ for (const key of DISPATCH_KEYS) {+ const value = recipe.args[key];+ if (typeof value === "string") return `${name} ${key}=${value}`;+ }+ return index === 0 ? name : `${name} #${index}`;+}++test("the probe's own fixture puts the marker in front of an unscoped caller", async () => {+ setGate(GATE_MODE.off);+ await seedTwoOwnerFixture();+ // Without this, every `not.toContain` below would pass on a fixture that+ // simply never produced the rows - the failure mode recon named when it+ // said several clean sweeps were clean because the fixture was empty.+ expect(await probeResponse("brain_backlinks", { id: SHARED_ID })).toContain(CROSS_OWNER_MARKER);+});++/**+ * Wall-clock ceiling for one probe.+ *+ * Above bun's 5s default because two entries do real work before they can+ * answer - `brain_codegraph_report` walks the in-scope project and+ * `brain_review_candidates` runs a full dry-run consolidation pass - and+ * a probe that times out reports a leak that is not there.+ */+const PROBE_TIMEOUT_MS = 30_000;++/**+ * The differential: gate OFF versus gate FAIL, per recipe.+ *+ * A one-sided probe cannot fail. `off` discloses a SUPERSET of what+ * `fail` discloses, so a recipe that does not surface the marker+ * unscoped can never surface it scoped either - and a sweep of the+ * previous, one-recipe-per-tool version found 81 of 96 entries in+ * exactly that state, naming artifacts the fixture never created or+ * driving an empty lane. Every one of them read as a clean isolation+ * result over a call that was never isolating anything.+ *+ * So both directions are asserted, and which direction depends on the+ * recipe's own reason:+ *+ * - {@link REASON.ownerFiltered} claims the call REACHES owner-taggable+ * artifacts and filters them. Both halves are executed: the marker+ * MUST appear with the gate off, and MUST NOT with the gate on. The+ * first half is what stops the second from being vacuous.+ * - every other reason in {@link REASON} claims the call cannot name+ * an owner-private artifact at all - a session lane, an ownerless+ * lane, a catalog, a caller-named artifact, a writer's echo, an+ * aggregate with no per-artifact identity. That claim is executed+ * directly: the marker must be absent even with the gate OFF, where+ * nothing is hidden. A recipe that surfaces it there has a FALSE+ * reason, and the fix is to filter the surface and move it to+ * `ownerFiltered` - never to widen the reason.+ *+ * The exemption from the two-sided form is therefore an explicit,+ * enumerated set ({@link REASONS_REACHING_OWNER_CONTENT}) read off the+ * classification each recipe already carries, not a silence.+ *+ * `fail` runs FIRST so the isolation assertion sees the pristine+ * fixture: several recipes are writers, and the reachability half must+ * not be what decides whether the boundary held.+ */+for (const entry of PROBE_ENTRIES) {+ for (const [index, recipe] of entry.calls.entries()) {+ const label = probeLabel(entry.name, recipe, index);+ const reaches = REASONS_REACHING_OWNER_CONTENT.has(recipe.reason);+ test(+ `${label}: ${reaches ? "reaches owner content and withholds it" : "reaches no owner content"}`,+ async () => {+ await seedTwoOwnerFixture();++ setGate(GATE_MODE.fail);+ const scoped = await probeResponse(entry.name, probeArgs(recipe));+ expect(scoped, `${label} under fail\n${recipe.reason}`).not.toContain(CROSS_OWNER_MARKER);++ setGate(GATE_MODE.off);+ const unscoped = await probeResponse(entry.name, probeArgs(recipe));+ if (reaches) {+ expect(unscoped, `${label} under off\n${recipe.reason}`).toContain(CROSS_OWNER_MARKER);+ } else {+ expect(unscoped, `${label} under off\n${recipe.reason}`).not.toContain(+ CROSS_OWNER_MARKER,+ );+ }+ },+ PROBE_TIMEOUT_MS,+ );+ }+}++/**+ * F1: `apply` planned against the UNFILTERED report.+ *+ * The probe above catches the disclosure - the applier's `detail` names+ * both merged ids - but not the WRITE, which is the worse half: a caller+ * whose scan correctly returned nothing could still retire another+ * owner's preference by handing `apply` an id it had never been shown.+ * Finding ids are `sha256(sorted targets).slice(0, 12)`, so they are+ * derivable rather than secret and withholding them was never the+ * boundary.+ */+test("brain_hygiene apply cannot execute a finding the same caller's scan withheld", async () => {+ await seedTwoOwnerFixture();+ setGate(GATE_MODE.fail);++ const hidden = runHygieneScan(vault, { now: new Date() }).findings.filter((f) =>+ f.targets.some((t) => t.includes(CROSS_OWNER_MARKER)),+ );+ expect(hidden.length, "the fixture must produce findings over owner-A artifacts").toBeGreaterThan(+ 0,+ );+ const ids = hidden.map((f) => f.id);++ const scan = JSON.parse(await call("brain_hygiene", { mode: "scan" }, OWNER_B));+ expect(JSON.stringify(scan)).not.toContain(CROSS_OWNER_MARKER);++ const applied = JSON.parse(await call("brain_hygiene", { mode: "apply", ids }, OWNER_B));+ expect(applied.applied).toEqual([]);+ expect(applied.changed).toBe(0);++ // The artifacts are still on disk, still owned, still unmerged.+ for (const slug of [`${CROSS_OWNER_MARKER}-a2`, `${CROSS_OWNER_MARKER}-a4`]) {+ expect(existsSync(join(vault, "Brain", "preferences", `pref-${slug}.md`))).toBe(true);+ }+});++/**+ * F1, second half: the dry run was an existence oracle.+ *+ * A hidden finding came back as `excluded_review:[id]` and an id nobody+ * ever issued came back as `unknown_ids:[id]`, so a caller could+ * enumerate the hidden population one derived id at a time without ever+ * being shown a finding. IDENTICAL TO ABSENT is the convention+ * `preferences-collect.ts` states; this is it, executed.+ */+test("a withheld hygiene finding id answers exactly as an id nobody issued", async () => {+ await seedTwoOwnerFixture();+ setGate(GATE_MODE.fail);++ const hiddenId = runHygieneScan(vault, { now: new Date() }).findings.find((f) =>+ f.targets.some((t) => t.includes(CROSS_OWNER_MARKER)),+ )!.id;+ const inventedId = "dedup:000000000000";++ const withheld = JSON.parse(+ await call("brain_hygiene", { mode: "apply", ids: [hiddenId], dry_run: true }, OWNER_B),+ );+ const absent = JSON.parse(+ await call("brain_hygiene", { mode: "apply", ids: [inventedId], dry_run: true }, OWNER_B),+ );++ expect(withheld.unknown_ids).toEqual([hiddenId]);+ expect(withheld.excluded_review).toEqual([]);+ // Same shape, same fields, same emptiness - only the echoed id differs.+ expect({ ...withheld, unknown_ids: [] }).toEqual({ ...absent, unknown_ids: [] });+});++/**+ * F3: the verdict was folded over findings the arrays no longer carried.+ *+ * `verdict: watch` beside four empty arrays tells the caller that a+ * hidden artifact tripped a detector - the existence leak with the+ * evidence removed.+ */+test("brain_health's verdict is folded over the findings it actually returns", async () => {+ await seedTwoOwnerFixture();++ setGate(GATE_MODE.off);+ const unscoped = JSON.parse(await call("brain_health", {}, OWNER_B));+ expect(unscoped.verdict).not.toBe("clean");+ expect(JSON.stringify(unscoped)).toContain(CROSS_OWNER_MARKER);++ setGate(GATE_MODE.fail);+ const scoped = JSON.parse(await call("brain_health", {}, OWNER_B));+ const named =+ scoped.contradictions.length + scoped.stale_claims.length + scoped.batch_inflation.length;+ if (named === 0 && scoped.concept_gaps.length === 0) {+ expect(scoped.verdict).toBe("clean");+ }+ expect(JSON.stringify(scoped)).not.toContain(CROSS_OWNER_MARKER);+});++/**+ * The probe's own shape, pinned as equalities.+ *+ * Three numbers are quoted outside this file - `docs/architecture.md`,+ * `docs/mcp.md` and the release notes all state how much of the tool+ * surface is really driven - and a number quoted in prose with nothing+ * keeping it true is the defect this whole release is about. The+ * two-sided count is the load-bearing one: it is how many recipes prove+ * their own reachability before asserting withholding, and the release+ * before this one shipped a probe where that number was effectively one.+ *+ * Raising any of these is ordinary; lowering the two-sided count means a+ * surface stopped being exercised, which is exactly the regression a+ * floor would have let through.+ */+test("the probe's population and its two-sided share are what the docs say", () => {+ const recipes = PROBE_ENTRIES.flatMap((entry) => entry.calls);+ const twoSided = recipes.filter((r) => REASONS_REACHING_OWNER_CONTENT.has(r.reason));+ expect(PROBE_ENTRIES.length).toBe(PROBE_ENTRY_COUNT);+ expect(recipes.length).toBe(PROBE_RECIPE_COUNT);+ expect(twoSided.length).toBe(PROBE_TWO_SIDED_COUNT);+});++test("a bucket entry without call recipes is refused", () => {+ expect(() => assertProbeEntry("NON_CONTENT", "brain_backlinks")).toThrow(+ "every entry must be a {name, calls} record",+ );+ expect(() => assertProbeEntry("NON_CONTENT", { name: "brain_backlinks", calls: [] })).toThrow(+ "has no 'calls'",+ );+ expect(() =>+ assertProbeEntry("NON_CONTENT", {+ name: "brain_backlinks",+ calls: [{ reason: REASON.ownerFiltered }],+ }),+ ).toThrow("has a call with no 'args'");+ expect(() =>+ assertProbeEntry("NON_CONTENT", {+ name: "brain_backlinks",+ calls: [{ args: {}, reason: "metadata" }],+ }),+ ).toThrow(`at least ${REASON_MIN_CHARS} characters`);+});diff --git a/tests/mcp/brain-governance.test.ts b/tests/mcp/brain-governance.test.tsindex d0a27bcf..3a1f1859 100644--- a/tests/mcp/brain-governance.test.ts+++ b/tests/mcp/brain-governance.test.ts@@ -118,6 +118,45 @@ test("brain_labels assigns within the vocabulary and fails closed outside it", a).rejects.toThrow(/allowed values: low, high/);});+/**+ * a-label-is-not-a-boundary, U12: the argument name in the complaint.+ *+ * `brain_labels {operation:"show", id:"…"}` answered "path must be a+ * vault-relative string" - a sentence about the SHAPE of an argument the+ * caller never sent, for an argument name (`id`) the tool never declared.+ * A caller reading it has no way to learn that `path` is the name, or+ * that `id` is not one.+ *+ * The resolution is stated at the handler: the argument is right and the+ * VALIDATOR's message was wrong. This test pins all three answers - the+ * documented call, the undeclared name, and the genuinely absent one -+ * because the first two are what tell those two failures apart.+ */+test("brain_labels show names the argument that is actually wrong", async () => {+ mkdirSync(join(vault, "notes"), { recursive: true });+ writeFileSync(join(vault, "notes", "rollout.md"), "# Rollout\n\nCanary first.\n");++ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ // The DOCUMENTED call: `path`, exactly as `inputSchema` declares it.+ const shown = await call(server, "brain_labels", {+ operation: "show",+ path: "notes/rollout.md",+ });+ expect(shown).toEqual({ path: "notes/rollout.md", labels: [] });++ // An undeclared name is refused BY NAME, with the declared set in hand.+ await expect(+ call(server, "brain_labels", { operation: "show", id: "notes/rollout.md" }),+ ).rejects.toThrow(/unknown argument 'id'/);++ // An ABSENT required argument is reported as absent, not as malformed.+ await expect(call(server, "brain_labels", { operation: "show" })).rejects.toThrow(+ /brain_labels show: path is required/,+ );+});+test("brain_tiers check is empty on a fresh vault; restore demands apply", async () => {const server = new MCPServer({ vault, configPath });await initialize(server);diff --git a/tests/mcp/codegraph-report-tool.test.ts b/tests/mcp/codegraph-report-tool.test.tsindex 3c847760..cbb2929a 100644--- a/tests/mcp/codegraph-report-tool.test.ts+++ b/tests/mcp/codegraph-report-tool.test.ts@@ -63,14 +63,29 @@ describe("brain_codegraph_report tool", () => {).toBeUndefined();});- test("returns a schema-versioned read-only report envelope", async () => {- const response = await call();- expect(response.error).toBeUndefined();- const report = payload(response as { result?: unknown });- expect(report["schema_version"]).toBe(1);- expect(report).toHaveProperty("cli");- expect(report).toHaveProperty("index");- expect(report).toHaveProperty("cargo_workspace");- expect(report).toHaveProperty("cargo_workspace_reason");- });+ // Budget, not a guess. `buildCodegraphReport` spawns the `codegraph`+ // binary once per discovered code project under a per-spawn deadline of+ // `CODEGRAPH_PARTNER_TIMEOUT_MS` (10s) - twice bun's 5s default for a+ // test. Measured at 4.21s on an idle machine WITH the binary installed,+ // i.e. 84% of that default, and it crossed it at 5306ms during a loaded+ // full-suite run. A test whose subject may legitimately outlive the+ // harness's default needs the deadline stated rather than the flake+ // rediscovered; the ceiling here sits above the spawn deadline, so a+ // real hang still fails rather than hanging the suite.+ const CODEGRAPH_SPAWN_BUDGET_MS = 20_000;++ test(+ "returns a schema-versioned read-only report envelope",+ async () => {+ const response = await call();+ expect(response.error).toBeUndefined();+ const report = payload(response as { result?: unknown });+ expect(report["schema_version"]).toBe(1);+ expect(report).toHaveProperty("cli");+ expect(report).toHaveProperty("index");+ expect(report).toHaveProperty("cargo_workspace");+ expect(report).toHaveProperty("cargo_workspace_reason");+ },+ CODEGRAPH_SPAWN_BUDGET_MS,+ );});diff --git a/tests/mcp/config-read-failure-server.test.ts b/tests/mcp/config-read-failure-server.test.tsindex 0a540faf..729ddede 100644--- a/tests/mcp/config-read-failure-server.test.ts+++ b/tests/mcp/config-read-failure-server.test.ts@@ -164,6 +164,25 @@ describe("the read-only diagnostics answer through the request path", () => {expect(JSON.stringify(payload!["vault_path"])).not.toContain(vault);});+ /**+ * a-label-is-not-a-boundary, U11: forty-one sites started producing the+ * degraded `{ error }` value here instead of the raw host path, and two+ * of them DECLARE `vault_path` in an `outputSchema` the server asserts+ * on the way out. A descriptor saying `type: "string"` turns the+ * degraded value into an output-contract failure - the whole payload+ * lost, on exactly the condition the field exists to report, which is+ * the failure the degraded value was introduced to prevent.+ */+ test("a tool that declares vault_path in its outputSchema still answers", async () => {+ const { payload, toolError, rpcError } = await callThroughServer("brain_mcp_landscape");+ expect(rpcError).toBeUndefined();+ expect(toolError).toBeUndefined();+ expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toContain(+ configPath,+ );+ expect(payload!["servers"]).toBeDefined();+ });+test("second_brain_status reports the condition instead of collapsing to absent", async () => {const { payload, toolError, rpcError } = await callThroughServer("second_brain_status");expect(rpcError).toBeUndefined();diff --git a/tests/mcp/config-unreadable-tools.test.ts b/tests/mcp/config-unreadable-tools.test.tsindex 444adf94..1f14e11f 100644--- a/tests/mcp/config-unreadable-tools.test.ts+++ b/tests/mcp/config-unreadable-tools.test.ts@@ -131,23 +131,40 @@ describe("brain_pre_compress_pack delivers with the breakage named", () => {expect(result!["warnings"]).toBeUndefined();});- test("a scoped call on an unreadable config still returns a pack", async () => {+ test("an unscoped call on an unreadable config still returns a pack", async () => {breakConfig();- const { result, error } = await callTool("brain_pre_compress_pack", {- top_k: 5,- agent_scope: "agent-a",- });+ const { result, error } = await callTool("brain_pre_compress_pack", { top_k: 5 });expect(error).toBeUndefined();expect(result?.["total_chars"]).toBeDefined();});test("the pack payload names the config the operator has to fix", async () => {breakConfig();- const { result } = await callTool("brain_pre_compress_pack", {+ const { result } = await callTool("brain_pre_compress_pack", { top_k: 5 });+ expect(result!["warnings"]).toEqual([brainConfigUnreadableReport(vault)!]);+ expect(result!["active_head_included"]).toBe(false);+ });++ test("a SCOPED call on an unreadable config is refused, not delivered", async () => {+ // The two rules that meet here, and which one wins.+ //+ // This surface is fail-soft: it delivers a pack and names the broken+ // config rather than going dark. And an unreadable config resolves to+ // the STRICT integrity fallback precisely so it "cannot loosen a gate,+ // it can only close one" (`policy/load.ts`). A call that names an+ // owner scope asks to be answered AS that owner, and under the closed+ // gate no such claim can be verified - so honouring it would be the+ // unreadable config loosening the very gate the fallback closed.+ //+ // Fail-soft therefore keeps its meaning for the unscoped call above,+ // and stops short of answering a scope this server cannot check.+ breakConfig();+ const { result, error } = await callTool("brain_pre_compress_pack", {top_k: 5,agent_scope: "agent-a",});- expect(result!["warnings"]).toEqual([brainConfigUnreadableReport(vault)!]);- expect(result!["active_head_included"]).toBe(false);+ expect(result).toBeUndefined();+ expect(error).toContain("unresolved-identity");+ expect(error).toContain("owner_scope_delivery");});});diff --git a/tests/mcp/http-transport.test.ts b/tests/mcp/http-transport.test.tsindex e7fb825a..56943be7 100644--- a/tests/mcp/http-transport.test.ts+++ b/tests/mcp/http-transport.test.ts@@ -222,7 +222,11 @@ describe("Streamable HTTP MCP transport", () => {{ key: "secret" },);expect(initRes.status).toBe(200);- expect(initRes.headers.get("mcp-session-id")).toBeTruthy();+ // No session header. One MCPServer instance serves every request on+ // this transport and nothing is keyed by a session, so an id here+ // would advertise state that does not exist - and the id that used+ // to be minted was never read back on any later request.+ expect(initRes.headers.get("mcp-session-id")).toBeNull();const init = await responseJson(initRes);expect(init.result.protocolVersion).toBe(PROTOCOL_VERSION);diff --git a/tests/mcp/knowledge-gaps-tool.test.ts b/tests/mcp/knowledge-gaps-tool.test.tsindex 6473128c..36b97068 100644--- a/tests/mcp/knowledge-gaps-tool.test.ts+++ b/tests/mcp/knowledge-gaps-tool.test.ts@@ -96,7 +96,11 @@ describe("brain_knowledge_gaps tool", () => {await initialize(server);const report = await callTool(server, "brain_knowledge_gaps", {});- expect(report["vault_path"]).toBe(vault);+ // The opaque store reference, never the absolute host path+ // (a-label-is-not-a-boundary, U11): this payload lands in model+ // context like every other MCP response.+ expect(report["vault_path"]).toMatch(/^vault:\/\/[0-9a-f]{32}$/);+ expect(report["vault_path"]).not.toBe(vault);expect(report["total_records"]).toBe(5);const gaps = report["gaps"] as ReadonlyArray<Record<string, unknown>>;expect(gaps).toHaveLength(1);diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 7ef24128..62533862 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -783,16 +783,37 @@ describe("serveStdioFromString respects scope+name", () => {"brain_pinned_context",]);});++ test("writer-scope initialize carries the resolved identity to the client", async () => {+ // End to end over the transport the always-loaded server actually+ // runs on, because `buildInstructions` returning the line is only+ // half the claim: the handshake has to deliver it.+ process.env["VAULT_AGENT_NAME"] = "vps-agent";+ const ctx = { vault: "/tmp/x", configPath: null, repoRoot: null };+ const initReq = JSON.stringify({+ jsonrpc: "2.0",+ id: 1,+ method: "initialize",+ params: { protocolVersion: "2025-06-18", capabilities: {} },+ });+ const out = await serveStdioFromString(ctx, `${initReq}\n`, {+ scope: "writer",+ serverName: "open-second-brain-writer",+ });+ const instructions = JSON.parse(out.trim()).result.instructions as string;+ expect(instructions).toContain("You are @vps-agent on this Open Second Brain vault.");+ expect(instructions).toContain("brain_feedback");+ });});import { buildInstructions } from "../../src/mcp/instructions.ts";+import { TOOL_SCOPE, TOOL_SCOPES } from "../../src/mcp/tool-contract.ts";describe("buildInstructions writer mode", () => {test("writer instructions name both tools and point at the full server", () => {const text = buildInstructions({- vault: "/tmp/x",agent: "@agent",- scope: "writer",+ scope: TOOL_SCOPE.writer,});expect(text).toContain("brain_feedback");expect(text).toContain("brain_apply_evidence");@@ -800,3 +821,31 @@ describe("buildInstructions writer mode", () => {expect(text).not.toMatch(/brain_dream/);});});++describe("buildInstructions states the identity on every scope", () => {+ // The writer scope is the always-loaded surface an agent carries into+ // every session, and the four writers on it are exactly the+ // identity-bearing ones - so the surface where the name matters most was+ // the one that never said it. The identity line is not decoration: it is+ // the standing instruction to log under one name and not invent another,+ // and a scope that omits it leaves that instruction to chance.+ const AGENT = "vps-agent";++ // Driven off the membership list, not a copy of it: a fourth scope+ // shipped without an identity line fails here without anyone+ // remembering to extend this loop.+ for (const scope of TOOL_SCOPES) {+ test(`${scope} scope names the resolved agent`, () => {+ const text = buildInstructions({ agent: AGENT, scope });+ expect(text).toContain(`You are @${AGENT} on this Open Second Brain vault.`);+ });++ test(`${scope} scope renders a refusal, never a name, when identity is unresolved`, () => {+ const reason = new Error("config unreadable: /etc/open-second-brain/config.yaml");+ const text = buildInstructions({ agent: reason, scope });+ expect(text).toContain("UNRESOLVED");+ expect(text).toContain(reason.message);+ expect(text).not.toContain("You are @");+ });+ }+});diff --git a/tests/mcp/owner-scope-refusal.test.ts b/tests/mcp/owner-scope-refusal.test.tsnew file mode 100644index 00000000..1f3199a6--- /dev/null+++ b/tests/mcp/owner-scope-refusal.test.ts@@ -0,0 +1,329 @@+/**+ * Identity is resolved, never echoed (a-label-is-not-a-boundary, U2).+ *+ * The defect this file exists to catch: with+ * `integrity.owner_scope_delivery` set to `fail` - the mode that reads as+ * "isolate owners" - a caller read ANY owner's private memories by naming+ * that owner in `agent_scope`. `coerceAgentScope` returned the argument+ * unconditionally and `resolveOwnerScopeDelivery` enforced exactly that+ * argument, so the scope the gate enforced was the one the caller asked+ * for, never the one the caller is. Measured before the fix, on the+ * fixture below: `brain_context_pack {agent_scope: "agent-a"}` called as+ * `agent-b` returned `pref-owned-by-a` - the very page the same call with+ * the caller's own scope withheld.+ *+ * Three things are pinned here:+ *+ * 1. the refusal itself, under `fail`, naming both owners;+ * 2. that nothing else moved - no scope, own scope, `warn` and `off`+ * all answer exactly as they did;+ * 3. that the argument has ONE reader in `src/mcp`, derived from the+ * source rather than listed here, so a tool cannot opt out of the+ * check by reading `agent_scope` itself again. Four tools did+ * exactly that before this unit.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, relative } from "node:path";++import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { brainConfigPath } from "../../src/core/brain/paths.ts";+import { GATE_MODE } from "../../src/core/integrity/stamp.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";+import { AGENT_SCOPE_ARG_NAME } from "../../src/mcp/coerce.ts";+import {+ OWNER_SCOPE_GATE_KEY,+ OWNER_SCOPE_REFUSAL,+ OWNER_SCOPE_REFUSALS,+ isOwnerScopeRefusal,+} from "../../src/mcp/owner-scope-refusal.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";+import type { ServerContext, ToolDefinition } from "../../src/mcp/tool-contract.ts";++const OWNER_A = "agent-a";+const OWNER_B = "agent-b";+/** The private page: delivered to its owner, withheld from everyone else. */+const PRIVATE_ID = "pref-owned-by-a";+/** The ownerless page: delivered to every scope, so it proves a call answered. */+const SHARED_ID = "pref-shared";++/**+ * An identity every write surface already rejects as a guess+ * (`PLACEHOLDER_AGENT_VALUES`), and the literal bottom of the identity+ * chain in `resolveAgentName`. A server holding this holds no identity.+ */+const UNCONFIGURED_IDENTITY = "agent";++/** The tool-table property a caller-supplied writer identity arrives in. */+const AGENT_ARG_NAME = "agent";++/**+ * Tools that accept a caller-supplied writer identity and stamp it onto+ * the record. Derived from the tool table below, never listed - a+ * hand-written list is the defect this release is about. The count is+ * pinned so a tool joining or leaving the set is a decision somebody+ * makes on purpose.+ */+const AGENT_ARGUMENT_TOOL_COUNT = 21;++/** Tools that accept a caller-supplied owner scope, derived the same way. */+const AGENT_SCOPE_TOOL_COUNT = 13;++const TOOLS = buildToolTable("full");+const tool = (name: string): ToolDefinition => {+ const found = TOOLS.find((t) => t.name === name);+ expect(found, `no such tool: ${name}`).toBeDefined();+ return found!;+};++/** Names of the tools whose input schema declares `property`. */+function toolsDeclaring(property: string): string[] {+ return TOOLS.filter((t) => {+ const properties = (t.inputSchema as { properties?: Record<string, unknown> }).properties ?? {};+ return Object.hasOwn(properties, property);+ })+ .map((t) => t.name)+ .toSorted();+}++let vault: string;+let configHome: string;+let ctx: ServerContext;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-owner-refusal-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-owner-refusal-cfg-"));+ const configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: ${OWNER_B}\n`);+ for (const sub of ["preferences", "retired", "inbox", "log"]) {+ mkdirSync(join(vault, "Brain", sub), { recursive: true });+ }+ // Written before any gate exists, so the owner is the one this fixture+ // states rather than one a write-time gate stamped.+ makePref("shared");+ makePref("owned-by-a", OWNER_A);+ ctx = { vault, configPath, repoRoot: null, agentName: OWNER_B };+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++function setGate(mode: string): void {+ writeFileSync(+ brainConfigPath(vault),+ `schema_version: 1\nintegrity:\n owner_scope_delivery: ${mode}\n`,+ );+}++function makePref(slug: string, owner?: string): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle: `principle for ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-02T00:00:00Z",+ confidence: BRAIN_CONFIDENCE.high,+ confidence_value: 0.8,+ ...(owner !== undefined ? { owner } : {}),+ });+}++/** Invoke a tool AS `agentName`, exactly as the server's seam does. */+async function call(+ name: string,+ args: Record<string, unknown>,+ agentName: string = OWNER_B,+): Promise<string> {+ return JSON.stringify(await tool(name).handler({ ...ctx, agentName }, args));+}++/** The message a rejected call carried, or `null` when it answered. */+async function refusalOf(+ name: string,+ args: Record<string, unknown>,+ agentName: string = OWNER_B,+): Promise<string | null> {+ return call(name, args, agentName).then(+ () => null,+ (e: unknown) => (e as Error).message,+ );+}++const PACK_ARGS = { max_tokens: 4000 };++// ----- the refusal ----------------------------------------------------------++test("a foreign agent_scope under a failing gate is refused, not answered", async () => {+ setGate(GATE_MODE.fail);+ const message = await refusalOf("brain_context_pack", { ...PACK_ARGS, agent_scope: OWNER_A });++ expect(message).not.toBeNull();+ // The refusal diagnoses itself: the typed member, both owners, the gate+ // that made the identity authoritative, and the two things it did NOT+ // do (answer as agent-a, or narrow to agent-b behind the caller's back).+ expect(message).toContain(OWNER_SCOPE_REFUSAL.foreignOwner);+ expect(message).toContain(AGENT_SCOPE_ARG_NAME);+ expect(message).toContain(OWNER_A);+ expect(message).toContain(OWNER_B);+ expect(message).toContain(OWNER_SCOPE_GATE_KEY);+ // And nothing crossed: a refusal is not a payload.+ expect(message).not.toContain(PRIVATE_ID);+});++test("a server with no resolved identity refuses any owner scope it cannot check", async () => {+ setGate(GATE_MODE.fail);+ const message = await refusalOf(+ "brain_context_pack",+ { ...PACK_ARGS, agent_scope: OWNER_A },+ UNCONFIGURED_IDENTITY,+ );++ expect(message).toContain(OWNER_SCOPE_REFUSAL.unresolvedIdentity);+ expect(message).not.toContain(PRIVATE_ID);+ // Distinct from the foreign-owner case: an unconfigured server is not a+ // caller that asked for somebody else, and reading it as one would blame+ // the caller for the operator's missing setting.+ expect(message).not.toContain(OWNER_SCOPE_REFUSAL.foreignOwner);+});++test("the refusal reaches every kind of surface that accepts the argument", async () => {+ setGate(GATE_MODE.fail);+ const surfaces: ReadonlyArray<{ name: string; args: Record<string, unknown> }> = [+ { name: "brain_context_pack", args: PACK_ARGS },+ { name: "brain_pre_compress_pack", args: { top_k: 10 } },+ { name: "brain_brief", args: { view: "morning" } },+ { name: "brain_anticipatory_context", args: { session_id: "sess-1" } },+ { name: "brain_retrieval_plan", args: { question: "lattice widgets" } },+ // Not gated by `owner_scope_delivery` today, and refused all the same:+ // the argument means the caller's own owner under `fail`, on every+ // surface that takes it.+ { name: "brain_agent_query", args: { kind: "preference" } },+ { name: "brain_search_by_source", args: { source_file: "sources/paper.md" } },+ ];++ const outcomes = await Promise.all(+ surfaces.map(async (s) => ({+ name: s.name,+ message: await refusalOf(s.name, { ...s.args, agent_scope: OWNER_A }),+ })),+ );+ for (const { name, message } of outcomes) {+ expect(message, `${name} must refuse a foreign owner scope`).toContain(+ OWNER_SCOPE_REFUSAL.foreignOwner,+ );+ }+});++// ----- what did not move ----------------------------------------------------++test("a caller naming its own identity is answered, and still isolated", async () => {+ setGate(GATE_MODE.fail);+ const out = await call("brain_context_pack", { ...PACK_ARGS, agent_scope: OWNER_B });+ expect(out).toContain(SHARED_ID);+ expect(out).not.toContain(PRIVATE_ID);++ const asOwner = await call("brain_context_pack", { ...PACK_ARGS, agent_scope: OWNER_A }, OWNER_A);+ expect(asOwner).toContain(PRIVATE_ID);+});++test("a caller supplying no scope is unaffected", async () => {+ setGate(GATE_MODE.fail);+ const out = await call("brain_context_pack", PACK_ARGS);+ expect(out).toContain(SHARED_ID);+ expect(out).not.toContain(PRIVATE_ID);+});++test("with the gate off or at warn, a foreign scope is answered exactly as before", async () => {+ for (const mode of [GATE_MODE.off, GATE_MODE.warn]) {+ setGate(mode);+ const out = await call("brain_context_pack", { ...PACK_ARGS, agent_scope: OWNER_A });+ // Neither mode withholds anything, so a foreign scope delivers nothing+ // an absent one would not, and refusing would break `warn`'s purpose.+ expect(out, `gate ${mode}`).toContain(PRIVATE_ID);+ }+});++test("a vault with no gate configured at all is unaffected", async () => {+ const out = await call("brain_context_pack", { ...PACK_ARGS, agent_scope: OWNER_A });+ expect(out).toContain(PRIVATE_ID);+});++test("a blank scope narrows nothing, so it is not a conflict", async () => {+ setGate(GATE_MODE.fail);+ const out = await call("brain_context_pack", { ...PACK_ARGS, agent_scope: " " });+ expect(out).toContain(PRIVATE_ID);+});++// ----- the vocabulary -------------------------------------------------------++test("the refusal vocabulary is closed and its guard rejects a near miss", () => {+ expect(OWNER_SCOPE_REFUSALS).toEqual([+ OWNER_SCOPE_REFUSAL.unresolvedIdentity,+ OWNER_SCOPE_REFUSAL.foreignOwner,+ ]);+ for (const member of OWNER_SCOPE_REFUSALS) expect(isOwnerScopeRefusal(member)).toBe(true);+ for (const outsider of ["", "refused", OWNER_A, null, undefined, 42, {}]) {+ expect(isOwnerScopeRefusal(outsider)).toBe(false);+ }+});++// ----- the enumerations, derived from the source ----------------------------++/** Every `.ts` file under `src/mcp`, the tool surface's whole tree. */+function mcpSources(): string[] {+ const root = join(import.meta.dir, "..", "..", "src", "mcp");+ return readdirSync(root, { recursive: true, encoding: "utf8" })+ .filter((entry) => entry.endsWith(".ts"))+ .map((entry) => join(root, entry))+ .toSorted();+}++test("the owner-scope argument has exactly one reader in src/mcp", () => {+ const literal = new RegExp(`["']${AGENT_SCOPE_ARG_NAME}["']`);+ const readers = mcpSources().filter((path) => literal.test(readFileSync(path, "utf8")));+ const repoRoot = join(import.meta.dir, "..", "..");+ // One seam, named once. Before this unit four tools spelled the+ // argument themselves and would have kept the echo the seam removes;+ // a fifth is now a build failure rather than a silent opt-out.+ expect(readers.map((p) => relative(repoRoot, p))).toEqual(["src/mcp/coerce.ts"]);+});++test("every tool declaring agent_scope is covered by that one seam", () => {+ const declaring = toolsDeclaring(AGENT_SCOPE_ARG_NAME);+ expect(declaring.length).toBe(AGENT_SCOPE_TOOL_COUNT);+ for (const name of declaring) {+ const property = (tool(name).inputSchema as { properties: Record<string, { type?: unknown }> })+ .properties[AGENT_SCOPE_ARG_NAME];+ expect(property?.type, `${name}.${AGENT_SCOPE_ARG_NAME}`).toBe("string");+ }+});++/**+ * The write side of the same echo: 21 tools accept a caller-supplied+ * `agent` and stamp it verbatim. That is `passthrough`, shipped and+ * ungated, and this unit does not gate it - `brain_generation_reports`+ * uses the same argument as a LIST FILTER, so a blanket refusal at the+ * seam would change a read as well as a write. What this pins is the+ * population a gate would have to cover, derived from the tool table so+ * it cannot drift the way a hand-written list does.+ */+test("the tools that stamp a caller-supplied agent are enumerated from the tool table", () => {+ const declaring = toolsDeclaring(AGENT_ARG_NAME);+ expect(declaring.length).toBe(AGENT_ARGUMENT_TOOL_COUNT);+ // Disjoint from the scope population: one names who writes, the other+ // names who may read, and conflating them is how a label becomes a+ // boundary in prose only.+ const scoped = new Set(toolsDeclaring(AGENT_SCOPE_ARG_NAME));+ expect(declaring.filter((name) => scoped.has(name))).toEqual([]);+});diff --git a/tests/mcp/recall-adequacy-tool.test.ts b/tests/mcp/recall-adequacy-tool.test.tsindex 73e5acab..bf1cf33b 100644--- a/tests/mcp/recall-adequacy-tool.test.ts+++ b/tests/mcp/recall-adequacy-tool.test.ts@@ -54,10 +54,13 @@ test("gate omits adequacy when no scores are supplied", async () => {expect(out["adequacy"]).toBeUndefined();});-test("gate returns a sufficient/proceed verdict for strong scores", async () => {+test("gate returns a sufficient/proceed verdict for strong coverage", async () => {const out = (await tool("brain_recall_gate").handler(ctx(), {prompt: "what did we decide?",- scores: [0.83, 0.4],+ // Scores below the `weak` floor, coverage above the `sufficient`+ // one: a verdict read off the score would be `insufficient`.+ scores: [0.2, 0.1],+ match_quality: 0.83,})) as { adequacy: Record<string, unknown> };expect(out.adequacy["level"]).toBe("sufficient");expect(out.adequacy["action"]).toBe("proceed");@@ -65,10 +68,15 @@ test("gate returns a sufficient/proceed verdict for strong scores", async () =>expect(out.adequacy["result_count"]).toBe(2);});-test("gate returns weak/re_recall and insufficient/abstain per scores", async () => {+test("gate returns weak/re_recall and insufficient/abstain per coverage", async () => {+ // The scores are deliberately the SAME in both arms and both sit at the+ // value the shipped keyword lane pins its top row to. Under the old+ // score-driven rule both graded `sufficient`; only the coverage differs+ // now, and only the coverage decides.const weak = (await tool("brain_recall_gate").handler(ctx(), {prompt: "x",- scores: [0.4],+ scores: [0.6],+ match_quality: 0.4,})) as { adequacy: Record<string, unknown> };expect(weak.adequacy["level"]).toBe("weak");expect(weak.adequacy["action"]).toBe("re_recall");@@ -76,6 +84,7 @@ test("gate returns weak/re_recall and insufficient/abstain per scores", async ()const insufficient = (await tool("brain_recall_gate").handler(ctx(), {prompt: "x",scores: [],+ match_quality: 0,})) as { adequacy: Record<string, unknown> };expect(insufficient.adequacy["level"]).toBe("insufficient");expect(insufficient.adequacy["action"]).toBe("abstain");@@ -86,9 +95,11 @@ test("gate honours configurable thresholds", async () => {writeFileSync(configPath, `vault: "${vault}"\nrecall_adequacy_sufficient: "0.9"\n`);const out = (await tool("brain_recall_gate").handler(ctx(), {prompt: "x",- scores: [0.7],+ // Score above the raised floor, coverage below it.+ scores: [0.95],+ match_quality: 0.7,})) as { adequacy: Record<string, unknown> };- // 0.7 would be sufficient at the default 0.6 floor, but not at 0.9.+ // 0.7 coverage would be sufficient at the default 0.6 floor, not at 0.9.expect(out.adequacy["level"]).toBe("weak");});@@ -104,6 +115,7 @@ test("gate attaches a negative block when the query yields no usable result", asconst out = (await gate.handler(ctx(), {prompt: "reactor coolant",scores: [],+ match_quality: 0,})) as { negative?: Record<string, unknown> };// The server enforces the declared output schema on every call, so the// block and its declaration have to agree here rather than in@@ -122,6 +134,7 @@ test("gate omits the negative block entirely when scores are usable", async () =const out = (await tool("brain_recall_gate").handler(ctx(), {prompt: "reactor coolant",scores: [0.83],+ match_quality: 0.83,})) as Record<string, unknown>;expect(out["adequacy"]).toBeDefined();// Absent, never null - the convention the explain trace already sets.@@ -152,6 +165,7 @@ test("over a keyword-only index a zero-result attempt is a not_found the receiptconst out = (await gate.handler(ctx(), {prompt: "reactor coolant",scores: [],+ match_quality: 0,})) as { negative: Record<string, unknown> };// The populated-receipt shape has to clear the contract too.assertOutputContract(gate.name, gate.outputSchema, out);@@ -202,6 +216,7 @@ test("an authorized note root the index never reached forces unknown and names iconst out = (await tool("brain_recall_gate").handler(ctx(), {prompt: "reactor coolant",scores: [],+ match_quality: 0,})) as { negative: Record<string, unknown> };expect(out.negative["state"]).toBe("unknown");expect(out.negative["unknown_reason"]).toBe("coverage-divergent");@@ -212,15 +227,43 @@ test("an authorized note root the index never reached forces unknown and names itest("gate rejects a malformed scores argument", async () => {await expect(- tool("brain_recall_gate").handler(ctx(), { prompt: "x", scores: ["nope"] }),+ tool("brain_recall_gate").handler(ctx(), {+ prompt: "x",+ scores: ["nope"],+ match_quality: 0.5,+ }),).rejects.toThrow();});+test("the two adequacy arguments stand or fall together", async () => {+ // Scores alone cannot be graded, and deriving a quality from them is the+ // exact substitution this release removes - so an incomplete pair is+ // refused by name rather than half-honoured.+ await expect(+ tool("brain_recall_gate").handler(ctx(), { prompt: "x", scores: [0.6] }),+ ).rejects.toThrow(/match_quality/u);+ await expect(+ tool("brain_recall_gate").handler(ctx(), { prompt: "x", match_quality: 0.6 }),+ ).rejects.toThrow(/scores/u);+ await expect(+ tool("brain_context_pack").handler(ctx(), { max_tokens: 1000, recall_scores: [0.6] }),+ ).rejects.toThrow(/match_quality/u);+});++test("a match quality outside [0,1] is refused, never clamped", async () => {+ await expect(+ tool("brain_recall_gate").handler(ctx(), { prompt: "x", scores: [0.6], match_quality: 1.4 }),+ ).rejects.toThrow(/match_quality/u);+});+test("context_pack persists the verdict into the receipt and returns it", async () => {const packed = (await tool("brain_context_pack").handler(ctx(), {max_tokens: 1000,receipt: true,- recall_scores: [0.2, 0.1],+ // Scores high, coverage low: only the coverage can produce+ // `insufficient` here.+ recall_scores: [0.95, 0.9],+ match_quality: 0.2,})) as { adequacy?: Record<string, unknown>; receipt_id?: string };expect(packed.adequacy).toBeDefined();expect(packed.adequacy!["level"]).toBe("insufficient");@@ -240,7 +283,8 @@ test("context_pack persists the verdict into the receipt and returns it", async})) as { payload: Record<string, unknown> };const adequacy = shown.payload["adequacy"] as Record<string, unknown>;expect(adequacy["level"]).toBe("insufficient");- expect(adequacy["top_score"]).toBeCloseTo(0.2);+ // The top score rides along as description and decided nothing.+ expect(adequacy["top_score"]).toBeCloseTo(0.95);});test("context_pack omits adequacy when recall_scores is absent", async () => {@@ -264,11 +308,16 @@ function unmetTopics(): ReadonlyArray<string> {}test("with the flag off neither surface writes the demand log", async () => {- await tool("brain_recall_gate").handler(ctx(), { prompt: "reactor coolant", scores: [] });+ await tool("brain_recall_gate").handler(ctx(), {+ prompt: "reactor coolant",+ scores: [],+ match_quality: 0,+ });await tool("brain_context_pack").handler(ctx(), {max_tokens: 1000,query: "reactor coolant",recall_scores: [],+ match_quality: 0,telemetry: true,});expect(unmetTopics()).toEqual([]);@@ -276,7 +325,11 @@ test("with the flag off neither surface writes the demand log", async () => {test("with the flag on both surfaces write it, pack telemetry argument or not", async () => {writeFileSync(configPath, `vault: "${vault}"\nrecall_gate_telemetry: "true"\n`);- await tool("brain_recall_gate").handler(ctx(), { prompt: "reactor coolant", scores: [] });+ await tool("brain_recall_gate").handler(ctx(), {+ prompt: "reactor coolant",+ scores: [],+ match_quality: 0,+ });expect(unmetTopics().length).toBeGreaterThan(0);const before = unmetTopics().length;@@ -284,6 +337,7 @@ test("with the flag on both surfaces write it, pack telemetry argument or not",max_tokens: 1000,query: "turbine bearing vibration",recall_scores: [],+ match_quality: 0,});expect(unmetTopics().length).toBeGreaterThan(before);});diff --git a/tests/mcp/recall-gate-contract.test.ts b/tests/mcp/recall-gate-contract.test.tsnew file mode 100644index 00000000..c65e1dba--- /dev/null+++ b/tests/mcp/recall-gate-contract.test.ts@@ -0,0 +1,120 @@+/**+ * `brain_recall_gate`'s advertised contract against the call it actually+ * accepts (a-label-is-not-a-boundary review, C3).+ *+ * Three things had drifted apart. The tool DESCRIPTION told a caller to+ * "pass `scores` … to also get an adequacy verdict", which is precisely+ * the call `coerceRecallAdequacyInput` refuses with INVALID_PARAMS unless+ * `match_quality` rides along. The INPUT SCHEMA expressed the pairing+ * nowhere - `match_quality` appeared in no `required` array anywhere in+ * the tree - so a schema-driven client could only discover it by making+ * the refused call. And the OUTPUT echoed `top_score` / `mean_score`, the+ * two numbers that decide nothing, while withholding the one that decides+ * the level.+ *+ * These assertions are about the advertised surface, so they read the+ * tool table rather than a transcript: a description is a contract with a+ * model that never sees this file.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { assessRecallAdequacy } from "../../src/core/brain/recall-adequacy.ts";+import { MATCH_QUALITY_ARG_NAME } from "../../src/mcp/coerce.ts";+import { assertOutputContract } from "../../src/mcp/output-contract.ts";+import { MCPError } from "../../src/mcp/protocol.ts";+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext, ToolDefinition } from "../../src/mcp/tool-contract.ts";++const TOOL_NAME = "brain_recall_gate";+const SCORES_ARG_NAME = "scores";++let tmp: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-recall-gate-contract-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function ctx(): ServerContext {+ return { vault, configPath, repoRoot: null };+}++function gate(): ToolDefinition {+ return findTool(buildToolTable("full"), TOOL_NAME);+}++test("the description names the pairing the handler enforces", () => {+ const description = gate().description;+ // Both names, so the sentence a model reads is the call the server+ // accepts rather than the one it refuses.+ expect(description).toContain(MATCH_QUALITY_ARG_NAME);+ expect(description).toContain(SCORES_ARG_NAME);+ // And it says what happens to an incomplete pair, in the vocabulary the+ // refusal itself uses.+ expect(description).toContain("INVALID_PARAMS");+});++test("the input schema states 'both or neither' declaratively", () => {+ const schema = gate().inputSchema as Record<string, unknown>;+ const dependent = schema["dependentRequired"] as+ | Record<string, ReadonlyArray<string>>+ | undefined;+ expect(dependent).toBeDefined();+ expect(dependent?.[SCORES_ARG_NAME]).toEqual([MATCH_QUALITY_ARG_NAME]);+ expect(dependent?.[MATCH_QUALITY_ARG_NAME]).toEqual([SCORES_ARG_NAME]);+ // A keyword a client's draft may not know is not on its own enough, so+ // the property description carries the same rule in prose.+ const properties = schema["properties"] as Record<string, Record<string, unknown>>;+ expect(String(properties[SCORES_ARG_NAME]?.["description"])).toContain(MATCH_QUALITY_ARG_NAME);+});++test("the description's own call is the one the handler accepts", async () => {+ // The regression this file exists for: the shipped description told the+ // caller to pass scores alone, and that call is refused.+ await expect(+ gate().handler(ctx(), { prompt: "what did we decide?", scores: [0.7] }),+ ).rejects.toBeInstanceOf(MCPError);+ const paired = (await gate().handler(ctx(), {+ prompt: "what did we decide?",+ scores: [0.7],+ match_quality: 0.7,+ })) as Record<string, unknown>;+ expect(paired["adequacy"]).toBeDefined();+});++test("the verdict returns the quantity that decided it", async () => {+ const matchQuality = 0.42;+ const out = (await gate().handler(ctx(), {+ prompt: "what did we decide?",+ scores: [0.9, 0.1],+ match_quality: matchQuality,+ })) as { adequacy: Record<string, unknown> };++ expect(out.adequacy[MATCH_QUALITY_ARG_NAME]).toBe(matchQuality);+ // Not reconstructible from what the block used to carry: the top score+ // and the mean are both something else entirely.+ expect(out.adequacy["top_score"]).not.toBe(matchQuality);+ expect(out.adequacy["mean_score"]).not.toBe(matchQuality);+ // And it is the number the core graded on, not a copy of the argument+ // that happens to agree.+ expect(out.adequacy["level"]).toBe(+ assessRecallAdequacy({ matchQuality, scores: [0.9, 0.1] }).level,+ );++ // Declared, not merely emitted: the response is checked against the+ // tool's own output schema, which now requires the field.+ assertOutputContract(TOOL_NAME, gate().outputSchema, out);+});diff --git a/tests/mcp/recall-gate-telemetry.test.ts b/tests/mcp/recall-gate-telemetry.test.tsindex f5a586a9..d2fb8cc4 100644--- a/tests/mcp/recall-gate-telemetry.test.ts+++ b/tests/mcp/recall-gate-telemetry.test.ts@@ -106,6 +106,7 @@ test("fail-open: a broken continuity store never breaks the gate decision", asynconst negative = (await tool("brain_recall_gate").handler(ctx(), {prompt: "what did we decide about the index?",scores: [],+ match_quality: 0,})) as { retrieve: boolean; negative?: Record<string, unknown> };expect(typeof negative.retrieve).toBe("boolean");expect(negative.negative?.["state"]).toBe("unknown");@@ -125,6 +126,7 @@ test("default off: a negative verdict writes no continuity record", async () =>const out = (await tool("brain_recall_gate").handler(ctx(), {prompt: "reactor coolant",scores: [],+ match_quality: 0,})) as { negative?: unknown };expect(out.negative).toBeDefined();expect(negativeRecallRecords()).toHaveLength(0);@@ -132,7 +134,11 @@ test("default off: a negative verdict writes no continuity record", async () =>test("with the opt-in on, a negative verdict lands as a continuity record", async () => {writeFileSync(configPath, `vault: "${vault}"\nrecall_gate_telemetry: "true"\n`);- await tool("brain_recall_gate").handler(ctx(), { prompt: "reactor coolant", scores: [] });+ await tool("brain_recall_gate").handler(ctx(), {+ prompt: "reactor coolant",+ scores: [],+ match_quality: 0,+ });const records = negativeRecallRecords();expect(records).toHaveLength(1);expect(records[0]!.payload["state"]).toBe("unknown");@@ -147,6 +153,10 @@ test("with the opt-in on, a negative verdict lands as a continuity record", asyntest("a usable-score call writes no negative record even with the opt-in on", async () => {writeFileSync(configPath, `vault: "${vault}"\nrecall_gate_telemetry: "true"\n`);- await tool("brain_recall_gate").handler(ctx(), { prompt: "reactor coolant", scores: [0.9] });+ await tool("brain_recall_gate").handler(ctx(), {+ prompt: "reactor coolant",+ scores: [0.9],+ match_quality: 0.9,+ });expect(negativeRecallRecords()).toHaveLength(0);});diff --git a/tests/mcp/resources-owner-scope.test.ts b/tests/mcp/resources-owner-scope.test.tsnew file mode 100644index 00000000..609102c0--- /dev/null+++ b/tests/mcp/resources-owner-scope.test.ts@@ -0,0 +1,193 @@+/**+ * The ownership boundary, on the OTHER protocol verb+ * (a-label-is-not-a-boundary, U3).+ *+ * `tests/mcp/agent-scope-matrix.test.ts` enumerates `tools/*` and drives+ * every entry against a two-owner fixture. Its population is the tool+ * table, so nothing in it ever issued a `resources/read` - and+ * `src/mcp/resources.ts` contained no reference to `agentName`,+ * `ownerScope` or `gatedOwnerScopeView` at all. Under the same+ * `integrity.owner_scope_delivery: fail` that made `brain_query`+ * withhold a preference, `resources/read osb://preference/<id>` returned+ * that preference's file in full: frontmatter, `owner:` line and body+ * prose. A boundary one verb honours and its neighbour ignores is not a+ * boundary.+ *+ * This file is that verb's probe. It drives every templated resource+ * that reaches owner-taggable content, as the OTHER owner, and asserts+ * the same two things the tool matrix does: the marker is reachable with+ * the gate off, and absent with it on. The reachability half is not+ * optional - a resource probe that never saw the marker unscoped would+ * be the "clean sweep over an empty fixture" the tool matrix exists to+ * prevent.+ */++import { beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { appendLogEvent } from "../../src/core/brain/log.ts";+import { brainConfigPath, brainDirs } from "../../src/core/brain/paths.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { BRAIN_LOG_EVENT_KIND, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";+import { GATE_MODE } from "../../src/core/integrity/stamp.ts";+import { readResource, type ResourceContext } from "../../src/mcp/resources.ts";++/** HOME is pinned per file by convention; nothing pins it globally. */+process.env["HOME"] = mkdtempSync(join(tmpdir(), "o2b-resources-scope-home-"));++const OWNER_A = "agent-a";+const OWNER_B = "agent-b";+/** Appears only inside artifacts owned by {@link OWNER_A}. */+const MARKER = "secretmarkerzz";+const LOG_DATE = "2026-05-04";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-resources-scope-vault-"));+ for (const sub of ["preferences", "retired", "inbox", "log"]) {+ mkdirSync(join(vault, "Brain", sub), { recursive: true });+ }+ makePref("shared");+ makePref(`${MARKER}-a`, OWNER_A);+ // The owner-A preference also carries the SHARED topic, so a topic+ // resource the caller is entitled to still fans out to it.+ makePref(`${MARKER}-a2`, OWNER_A, "shared");+ writeFileSync(+ join(brainDirs(vault).preferences, `pref-${MARKER}-a.md`),+ `${readPref(`pref-${MARKER}-a`)}\nSee [[pref-shared]].\n`,+ );+ appendLogEvent(+ vault,+ {+ timestamp: `${LOG_DATE}T00:00:00Z`,+ eventType: BRAIN_LOG_EVENT_KIND.applyEvidence,+ body: {+ path: `Brain/preferences/pref-${MARKER}-a.md`,+ preference: `[[pref-${MARKER}-a]]`,+ result: "applied",+ },+ },+ { deviceId: "" },+ );+});++function readPref(id: string): string {+ return readFileSync(join(brainDirs(vault).preferences, `${id}.md`), "utf8");+}++function makePref(slug: string, owner?: string, topic?: string): void {+ writePreference(vault, {+ slug,+ topic: topic ?? slug,+ principle: `principle for ${slug}`,+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: [`[[sig-2026-05-01-${slug}]]`],+ confirmed_at: "2026-05-02T00:00:00Z",+ ...(owner !== undefined ? { owner } : {}),+ });+}++function setGate(mode: string): void {+ atomicWriteFileSync(+ brainConfigPath(vault),+ `schema_version: 1\nintegrity:\n owner_scope_delivery: ${mode}\n`,+ );+}++/** Read one resource AS `agentName`, folding a refusal into the answer. */+function read(uri: string, agentName: string = OWNER_B): string {+ const ctx: ResourceContext = { vault, agentName };+ try {+ return readResource(ctx, uri).text;+ } catch (err) {+ return `threw: ${err instanceof Error ? err.message : String(err)}`;+ }+}++/**+ * Every templated resource that reaches owner-taggable content, with the+ * URI that reaches it.+ *+ * `osb://preference/<id>` names the hidden artifact directly; the other+ * three name something the caller is entitled to and reach the hidden+ * one through a fan-out - a shared topic, a shared link target, a shared+ * log day - which is the shape a caller cannot be refused for asking.+ */+const OWNER_BEARING_URIS: ReadonlyArray<{ uri: string; why: string }> = [+ { uri: "osb://topic/shared", why: "a topic fans out to every preference carrying it" },+ { uri: "osb://backlinks/pref-shared", why: "every backlink names its source artifact" },+ { uri: `osb://log/${LOG_DATE}`, why: "a log event names the preference it was about" },+];++for (const { uri, why } of OWNER_BEARING_URIS) {+ test(`${uri}: reaches owner content and withholds it under the gate`, () => {+ setGate(GATE_MODE.off);+ expect(read(uri), `${uri} unscoped (${why})`).toContain(MARKER);++ setGate(GATE_MODE.fail);+ expect(read(uri), `${uri} scoped (${why})`).not.toContain(MARKER);+ });++ test(`${uri}: its own owner still reads it`, () => {+ setGate(GATE_MODE.fail);+ expect(read(uri, OWNER_A)).toContain(MARKER);+ });+}++/**+ * `osb://preference/{id}` is probed on its own: the caller NAMES the+ * hidden id, so the refusal echoes it back and a marker check over the+ * whole response would be measuring the caller's own argument. What must+ * not travel is the page.+ */+test("osb://preference returns the page unscoped and none of it under the gate", () => {+ setGate(GATE_MODE.off);+ const unscoped = read(`osb://preference/pref-${MARKER}-a`);+ expect(unscoped).toContain(`owner: ${OWNER_A}`);+ expect(unscoped).toContain(`principle for ${MARKER}-a`);++ setGate(GATE_MODE.fail);+ const scoped = read(`osb://preference/pref-${MARKER}-a`);+ expect(scoped).not.toContain(`owner: ${OWNER_A}`);+ expect(scoped).not.toContain(`principle for ${MARKER}-a`);++ // Its own owner still reads it in full.+ expect(read(`osb://preference/pref-${MARKER}-a`, OWNER_A)).toContain(`principle for ${MARKER}-a`);+});++/**+ * A withheld preference answers exactly as an absent one does.+ *+ * A distinguishable refusal is an existence oracle over the population+ * the gate exists to hide, and preference ids are guessable - they are+ * `pref-<topic-slug>`.+ */+test("a withheld preference resource is reported as an absent one", () => {+ setGate(GATE_MODE.fail);+ const withheld = read(`osb://preference/pref-${MARKER}-a`);+ const absent = read("osb://preference/pref-never-existed");+ expect(withheld).toStartWith("threw:");+ expect(withheld.replace(`${MARKER}-a`, "never-existed")).toBe(absent);+});++test("the shared half of every resource still travels under the gate", () => {+ setGate(GATE_MODE.fail);+ expect(read("osb://topic/shared")).toContain("pref-shared");+ expect(read("osb://preference/pref-shared")).toContain("principle for shared");+ expect(read(`osb://log/${LOG_DATE}`)).toContain(LOG_DATE);+});++/**+ * With the gate off, the resources surface is byte-identical to what it+ * served before any of this existed.+ */+test("gate off leaves every resource unfiltered", () => {+ setGate(GATE_MODE.off);+ for (const { uri } of OWNER_BEARING_URIS) expect(read(uri)).toContain(MARKER);+});diff --git a/tests/mcp/scaffold-stub-boundary.test.ts b/tests/mcp/scaffold-stub-boundary.test.tsindex f8473ca7..109e1ec0 100644--- a/tests/mcp/scaffold-stub-boundary.test.ts+++ b/tests/mcp/scaffold-stub-boundary.test.ts@@ -165,3 +165,41 @@ describe("arguments that belong to the other action (D)", () => {expect(res["action"]).toBe("list");});});++/**+ * The `limit` capped the scan BEFORE the ownership filter ran, so a+ * scoped caller silently received fewer rows than it asked for and than+ * the vault holds - and the shortfall is proportional to how much the+ * other owner wrote, which is a row count read as an existence signal.+ */+describe("limit is applied after the ownership filter", () => {+ test("a scoped caller gets the limit it asked for, not the limit minus what was hidden", async () => {+ const { indexVault, resolveSearchConfig } = await import("../../src/core/search/index.ts");+ const configPath = ctx.configPath!;++ // Three dangling targets from an owner-A note, sorting FIRST, plus+ // three from a shared note. With the limit applied before the filter+ // a scoped caller sees zero of the three it is entitled to.+ writeFileSync(+ join(vault, "aaa-owned.md"),+ "---\nowner: agent-a\n---\n\n[[aaa-1]] [[aaa-2]] [[aaa-3]]\n",+ );+ writeFileSync(join(vault, "zzz-shared.md"), "[[zzz-1]] [[zzz-2]] [[zzz-3]]\n");+ atomicWriteFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\nintegrity:\n owner_scope_delivery: fail\n",+ );+ await indexVault(resolveSearchConfig({ vault, configPath }), { force: true });++ const scoped = (await tool.handler(+ { ...ctx, agentName: "agent-b" },+ {+ action: "list",+ limit: 3,+ },+ )) as { state: string; targets: Array<{ target: string }> };++ expect(scoped.state).toBe("measured");+ expect(scoped.targets.map((t) => t.target).toSorted()).toEqual(["zzz-1", "zzz-2", "zzz-3"]);+ });+});diff --git a/tests/mcp/schema-tools.test.ts b/tests/mcp/schema-tools.test.tsindex 7dda5410..c28b1938 100644--- a/tests/mcp/schema-tools.test.ts+++ b/tests/mcp/schema-tools.test.ts@@ -1,5 +1,13 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdtempSync, readFileSync, rmSync, statSync, utimesSync } from "node:fs";+import {+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ symlinkSync,+ utimesSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -289,3 +297,101 @@ describe("schema MCP tools", () => {expect((response as any).error.message).toContain("mutations must be an array");});});++/**+ * a-label-is-not-a-boundary, U12: the lint that died on its own subject.+ *+ * `view=lint` and `view=orphans` exist to REPORT malformed Brain+ * artifacts, and both raised on the first one they met - the parse error+ * escaped `buildSchemaReport` unhandled, so a single bad file cost the+ * caller every finding in the vault. The message carried the absolute+ * host path as well, which is the leak `vaultPathField` closes on the+ * same surface.+ *+ * Two shapes are driven, because two different mechanisms produced the+ * same silence: a parse failure (a retired preference missing a required+ * field, which THREW) and a read failure (a directory occupying a `.md`+ * name under the log dir, which was swallowed by a bare+ * `catch { continue }` and reported nothing at all).+ */+describe("schema_inspect reports the malformed artifact instead of dying on it", () => {+ /** Plant every malformed artifact; returns their vault-relative paths. */+ function plantMalformedArtifacts(): { retired: string; log: string; dangling: string } {+ const retiredRel = join("Brain", "retired", "ret-broken.md");+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ atomicWriteFileSync(+ join(vault, retiredRel),+ // `retired_at` is required by `parseRetired`; without it the parse+ // throws a BrainParseError naming the absolute path.+ [+ "---",+ "kind: brain-retired",+ "_status: retired",+ "id: ret-broken",+ "---",+ "",+ "body",+ "",+ ].join("\n"),+ );+ // A DIRECTORY under a `.md` name: `readFileSync` fails with EISDIR on+ // every platform and for every user, which a chmod-based fixture does+ // not (a test run as root reads a 0000 file).+ const logRel = join("Brain", "log", "2026-08-16.md");+ mkdirSync(join(vault, logRel), { recursive: true });+ // A DANGLING SYMLINK. Neither fixture above produces a message with a+ // host path in it - `BrainParseError` keeps the location in its own+ // `path` field, and EISDIR reads `illegal operation on a directory,+ // read` with no path at all - so `locationFreeDetail` had nothing to+ // rewrite and its only test could not fail: replacing the whole+ // function body with `return raw` left 15 pass, 0 fail. ENOENT is the+ // shape the function's own docblock cites, and it embeds the absolute+ // path INSIDE the message: `ENOENT: no such file or directory, open+ // '/tmp/…/Brain/log/2026-08-15.md'`.+ const danglingRel = join("Brain", "log", "2026-08-15.md");+ symlinkSync(join(vault, "Brain", "log", "nothing-here.md"), join(vault, danglingRel));+ return { retired: retiredRel, log: logRel, dangling: danglingRel };+ }++ for (const view of ["lint", "orphans"] as const) {+ test(`view=${view} answers with findings, not an error`, async () => {+ const planted = plantMalformedArtifacts();+ const server = makeServer();+ await initialize(server);++ const response = await call(server, "schema_inspect", { view });++ expect((response as any).error).toBeUndefined();+ // A raised handler comes back as `isError: true` with the raw+ // message as text - which is how this surface used to answer, and+ // the message named the absolute host path.+ expect((response as any).result.isError).not.toBe(true);+ const payload = (response as any).result.structuredContent as Record<string, unknown>;+ const findings = (payload["findings"] ?? payload["orphans"]) as ReadonlyArray<+ Record<string, unknown>+ >;+ const unreadable = findings.filter((f) => f["kind"] === "unreadable-artifact");+ expect(unreadable.map((f) => f["path"]).toSorted()).toEqual(+ [planted.dangling, planted.log, planted.retired].toSorted(),+ );+ // The reason travels with the report, so the operator can act on it+ // without re-running the parser by hand.+ expect(unreadable.every((f) => typeof f["detail"] === "string" && f["detail"] !== "")).toBe(+ true,+ );+ // The one fixture whose raw message really carries the host path.+ // Asserted on the DETAIL rather than only on the payload, so the+ // failure names the field that leaked rather than the whole+ // response, and so the rewrite is measured where it happens.+ const dangling = unreadable.find((f) => f["path"] === planted.dangling);+ const detail = String(dangling?.["detail"]);+ expect(detail).toContain("ENOENT");+ expect(detail).not.toContain(vault);+ // Rewritten to the vault-relative form, not merely deleted: a+ // message that lost the filename would name nothing at all.+ expect(detail).toContain(planted.dangling);+ // …and the absolute host path stays out of the payload entirely.+ expect(JSON.stringify(payload)).not.toContain(vault);+ });+ }+});