Skip to content

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: context integrity gates (v1.39.0) (#150)

Sol Aitkenf91a698b8e99
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 6e564a55..061afbb0 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.38.0",
+ "version": "1.39.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.json
index 06032569..1e8986b1 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.38.0",
+ "version": "1.39.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/.github/workflows/ci.yml b/.github/workflows/ci.yml
index d43adac7..70f9018e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -43,6 +43,9 @@ jobs:
- name: Verify manifest version sync
run: bun run sync-version:check
+ - name: Broken-link ratchet
+ run: bun run link-ratchet:check
+
- name: Hardcoded path hygiene (report-only)
run: bun run check:paths
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 636ccbb5..0d930604 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -47,6 +47,9 @@ jobs:
- name: Verify manifest version sync
run: bun run sync-version:check
+ - name: Broken-link ratchet
+ run: bun run link-ratchet:check
+
- name: Run TypeScript typecheck
run: bun run typecheck
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2f992294..1dd60b7f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,7 +5,45 @@ 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.38.0] - 2026-07-21
+## [1.39.0] - 2026-07-26
+
+A context-integrity wave: ten units that convert a silent failure in the read and delivery path into an explicit, named one. Owner-scoped isolation was enforced on one surface out of thirteen; a context pack carried no record of the vault state it was built from; session continuation resolved ambiguity by picking the most recent candidate; the lineage ledger lost history on compaction and had no writer lock; an embedding store written against a different model, dimension, or sqlite-vec ABI returned zero or garbage neighbours with no check on the read path; a frontmatter line the parser did not understand was dropped without a trace; nothing counted broken links vault-wide, nothing measured the SessionStart injection, nothing joined retrieval receipts across a session, and a mis-resolved vault root was materialized by the first write while the doctor reported it clean. Two shared seams carry the wave: a closed-vocabulary degradation channel and a stamp-and-compare module with three-mode gates. The kernel still calls no LLM, and every new surface is byte-identical when its flag, argument, or config key is absent.
+
+### Added
+
+- Typed degradation channel: a closed `DegradationCode` union with a notice record (`code`, `site`, `path?`, `detail`) and a one-line English renderer, carried by the report types that already exist. The union is exhaustive-switchable, so a consumer with a `never`-typed default arm fails to compile on an unhandled member.
+- Stamp-and-compare seam and the `integrity:` block in `_brain.yaml`: `owner_scope_delivery` (default `off`), `embedding_abi` (default `warn`), and `pack_validity_seconds` (default 900). An unrecognised mode or a non-positive validity raises `BrainConfigError` naming the dotted field; an absent block resolves to the documented defaults. Under `off` the gate does not compare at all and returns no evidence.
+- Owner-scope isolation on every content-returning surface, not only search. Preference-backed surfaces (context pack, pre-compress pack, morning brief, digest, `active.md`) route through one shared collector and are gated by `integrity.owner_scope_delivery`; search-backed surfaces filter whenever the caller passes a scope. An optional `agent_scope` argument joins eleven MCP tools and an `--agent-scope` flag joins `o2b search query`, `o2b search expand`, and `o2b brain sgrep`. A table-driven test partitions all 108 tools into scoped, deliberately-unscoped-with-a-reason, and non-content, and fails until a new tool is classified. `brain_search_expand` on another owner's chunk now raises the same `chunk not found` error as a genuinely missing chunk, closing an enumeration surface over sequential integer ids.
+- Context pack provenance: a stamp pairing the index corpus generation with a digest over path, mtime, and size for the directories the pack walks, plus an expiry from `integrity.pack_validity_seconds`. The anticipatory cache stores both and refuses a drifted or expired entry as a miss naming the reason; its schema version bumped so pre-existing cache files read as misses.
+- Embedding ABI detection: the sqlite-vec version joins the model and dimension already stamped in `index_state`, and the three are compared on the read-mode open, where previously nothing checked. `o2b search check` reports drifted fields with a copy-pasteable fix, ungated. Nothing is ever rebuilt automatically - the existing self-heal path rebuilds keyword data only and would leave stale vectors in place.
+- Frontmatter diagnostics: a note whose frontmatter uses grammar the line scanner does not support still indexes, and now leaves a trace. `o2b search index` reports `frontmatter_notices`, `o2b brain doctor` reports `uncertain` entries, each naming the file, the line number, and the offending text. The index run reports files it re-read on that run; the doctor sweeps the whole Brain tree and is the standing report.
+- Vault-wide broken-link ratchet: a deterministic count of link rows the read-time resolution ladder cannot resolve, sharing that ladder's SQL from one constant. `bun run link-ratchet:check` is wired into both CI workflows and exits 1 on a rise, naming `bun run link-ratchet` as the fix. The committed ceiling in `link-ratchet.json` measures the `templates/brain-starter` repository template, not any operator's vault, and encodes the link rot present there today.
+- SessionStart injection meter: one receipt per injection with per-source byte and token attribution for the runtime-notice block, the budgeted `active.md` body, and the `lessons.md` digest, measured after the fail-open loader returns, together with the loader source, the hook event, and the char budget each sub-body was charged against. The meter runs after the context is emitted and inside its own try/catch.
+- Session-scoped retrieval receipt summary: a third `summary` operation on `brain_context_receipts` folding existing records into receipt count, item total, distinct items, and per-item injection frequency and token cost. Receipt emission is opt-in, so a window with no receipts returns `{recorded: false}` carrying no counters at all - the return type is a discriminated union, so "nobody enabled receipts" can never be read as "retrieval injected nothing".
+- Fail-closed session continuation: the crutch resolver returns a discriminated outcome - linked, or an abstention naming `no-candidate`, `self-known`, `no-workspace`, `ambiguous`, `stale`, or `evidence-missing` - instead of a bare `null`. Two concurrent sessions in one directory inside the freshness window both abstain where one was previously stitched to the other. Repo, branch, and commit join `cwd` as required-match predicates, captured through bounded `git` invocations; a remote carrying credentials canonicalizes to the same identity as the same repository cloned without them, and the credential never reaches a recorded field.
+- Lineage ledger integrity: sequence numbers and a hash chain, appends under a writer lock, and compaction that retains recent lines verbatim instead of folding one summary per session - so `firstSeenMs`, per-session event history, and any field a later writer adds all survive. A dropped observation is recorded as a named gap in `Brain/.state/session-lineage-gaps.jsonl` and excluded from continuation matching, so a lost write can never become a false stitch. A tampered, truncated, or unreadable ledger is reported by verification and still resolves; the read path stays fail-soft.
+- Vault identity guard: `o2b brain init` stamps an idempotent `Brain/vault-id.json` carrying an opaque id and no absolute path. Brain writers compare the root's marker against the identity the process pinned on its first write - a present-and-different marker refuses with a named error ahead of the first byte, an absent one warns through the degradation channel and proceeds. Of 106 write-capable modules, 97 carry the guard and 9 are excluded with a stated reason, measured by a census test that names any unguarded module.
+
+### Changed
+
+- `o2b brain doctor` reports a `Brain`-less root as a named `brain-root-absent` warning with an `uncertain` entry recording that every check below was skipped, instead of certifying it clean. `o2b brain doctor --strict` on such a root now exits 2 where it previously exited 0.
+- `vault profile switch` refuses a profile whose vault is not an existing directory, so activation fails at switch time instead of in a later process. A profile can no longer be switched to before its directory exists.
+- The lineage ledger's compaction retention changed from the most recent 256 sessions to the most recent 256 lines, so a chatty session ages other sessions out sooner. The writer lock has no retry: concurrent sessions on one vault can drop lifecycle observations, each named in the gap sidecar rather than lost.
+- Twelve MCP tools gained input arguments - `agent_scope` on eleven, and `since`, `until`, `max_receipts` plus a widened `operation` on `brain_context_receipts`. No tool was added or removed (the count stays 108) and no output schema changed.
+- `brain_hygiene` gains an additive top-level `link_integrity` key. It refuses to produce a number unless the index's last run was a forced full pass, reporting `measured: false` with reason `partial-resolution` rather than a misleading zero.
+- Retirement keeps ownership. `BrainRetired` carries an `owner` field and every retired-page surface applies the same visibility predicate as an active preference - retiring a memory withdraws it from the active set, it does not publish it.
+- Five `brain_brief` views that cannot honour a scope (`daily`, `weekly`, `monthly`, `operator`, `today`) now reject an explicit `agent_scope` with `INVALID_PARAMS` naming the view, rather than accepting and ignoring it. The server-identity fallback is unaffected.
+
+### Fixed
+
+- Ownership resolution fails closed. A page whose frontmatter cannot be read, and a page whose `owner:` is present but not a plain string (a block-style or inline YAML list, or a nested mapping - the shape Obsidian Properties writes), are withheld from a scoped caller instead of being treated as shared.
+- A per-request scope no longer drives a shared write: `brain_context` filters what it returns at render time and leaves `Brain/active.md` complete, and the anticipatory cache path keys on the enforced scope, so a warm cache written by the SessionStart hook is found by the MCP reader under the default gate.
+- The vault write guard runs ahead of the first byte everywhere. The secrets store, the schema mutator, page archiving, hygiene apply, the pinned-context batch path, tension transitions, gap auto-close, and snapshot pruning previously wrote or deleted before their assertion ran.
+- An unreadable `_brain.yaml` no longer silently disables an isolation gate: an absent config resolves to defaults, while a present-but-unreadable one falls back to the strictest mode and surfaces a `brain_config_unreadable` notice.
+- The link-ratchet gate no longer passes on a subject that measures nothing: an empty or fully-excluded subject is an explicit unmeasurable state rather than a ceiling of zero.
+- Four source files carried literal NUL bytes that made git treat them as binary and made `grep` skip them silently.
+
+
A semantic-health baselining release ([#147](https://github.com/itechmeat/open-second-brain/issues/147)): an optional acknowledge-before watermark lets an operator declare "I have seen and accepted the state up to this date", so a one-time bulk seed of preferences no longer pins the health verdict at `watch` forever through the `concept-gap` and `batch-concept-inflation` advisories. Detection and storage are unchanged; the watermark only filters which findings are surfaced, the verdict is computed from the surfaced set, and suppression is always reported explicitly. With no watermark set, every output is byte-identical to 1.37.0.
@@ -6637,6 +6675,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.39.0]: https://github.com/itechmeat/open-second-brain/compare/v1.38.0...v1.39.0
[1.38.0]: https://github.com/itechmeat/open-second-brain/compare/v1.37.0...v1.38.0
[1.37.0]: https://github.com/itechmeat/open-second-brain/compare/v1.36.0...v1.37.0
[1.36.0]: https://github.com/itechmeat/open-second-brain/compare/v1.35.0...v1.36.0
diff --git a/README.md b/README.md
index 2eaee77b..61667fd8 100644
--- a/README.md
+++ b/README.md
@@ -8,9 +8,9 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm
## What is new
-Open Second Brain 1.38.0 adds baselining for semantic-health advisories. When a vault is bulk-seeded with many preferences at once, the `concept-gap` and `batch-concept-inflation` advisories fire permanently and pin the health verdict at `watch`, with no way to acknowledge the burst short of deleting real memory. Now an optional `health.silence_before` watermark in `_brain.yaml` (managed by `o2b brain health-baseline set <date>|now`, `get`, `clear`) declares the state accepted up to that date: findings whose underlying entries are entirely older than the watermark are filtered from the surfaced report, the verdict reflects only what is shown, and the report always says exactly how many findings the baseline hid. Detection and storage are untouched, an entry without a parseable timestamp is never suppressed, and with no watermark set every output is byte-identical to 1.37.0.
+Open Second Brain 1.39.0 is a context-integrity wave: ten units that turn a silent failure in the read and delivery path into an explicit, named one. Owner scoping now reaches every content-returning surface rather than search alone, and fails closed when a page's ownership cannot be read. Context packs carry a stamp of the vault state they were built from and an expiry, so a stale pack is refused instead of served. Session continuation abstains with a named reason when it cannot tell one candidate from another, and the lineage ledger is hash-chained, locked, and compacted without losing history. A frontmatter line the parser does not understand, an embedding store written against a different model or sqlite-vec ABI, a vault root that is not the one you meant, and a broken-link count that only ever rises are each reported now instead of passing quietly. Two shared seams carry the wave - a closed-vocabulary degradation channel and a stamp-and-compare module whose gates the operator sets to `off`, `warn`, or `fail`. Every new surface is byte-identical when its flag, argument, or config key is absent.
-Previous release, 1.37.0, was a retrieval quality and context delivery wave: a typed-edge relational retrieval arm, composite owner/session/project scope keys, an overwrite-only `o2b brain state` lane with a retrieval-time staleness barrier, a deterministic summary-search router, `o2b search rerank-fit`, the read-only `brain_retrieval_plan` MCP tool, a cadence-controlled navigation tier, an opt-in strict orientation hook, and workspace-wide codegraph partnering. Details live in the [CHANGELOG](CHANGELOG.md).
+Previous release, 1.38.0, added baselining for semantic-health advisories: an optional `health.silence_before` watermark in `_brain.yaml`, managed by `o2b brain health-baseline set <date>|now`, `get`, and `clear`, filters findings whose underlying entries are entirely older than the watermark and always reports how many it hid. Details live in the [CHANGELOG](CHANGELOG.md).
## Why
diff --git a/docs/architecture.md b/docs/architecture.md
index 7e6cad2c..66019ee6 100644
--- a/docs/architecture.md
+++ b/docs/architecture.md
@@ -133,6 +133,9 @@ with backup/sync. It describes:
- schema version + dream / retire / confidence / snapshot thresholds;
- optional `notes.read_paths` (user-authored folders the agent may read);
- optional `temporal:`, `link_graph:`, `guardrails:`, `discipline_report:` tuning blocks;
+- optional `integrity:` gates (`owner_scope_delivery`, `embedding_abi`,
+ `pack_validity_seconds`) that decide where a mismatch is reported and
+ where it is refused;
- `vault.ignore_paths` (exclusion policy for every vault walker).
It must not contain secrets.
diff --git a/docs/brainstorm/context-integrity-gates/cli-output/claude.md b/docs/brainstorm/context-integrity-gates/cli-output/claude.md
new file mode 100644
index 00000000..5a1d59d6
--- /dev/null
+++ b/docs/brainstorm/context-integrity-gates/cli-output/claude.md
@@ -0,0 +1,46 @@
+### Variant 1: Two seams, ten adapters
+
+- **Approach**: Build exactly two horizontal shared modules and reduce each of the ten units to a thin adapter onto one or both. Seam 1 is a **typed degradation channel** β€” a non-throwing, named outcome record (`{code, site, path, detail}`) with three carriers already present in the repo: `IndexStats` (new `scanned`/`skipped` fields), `DoctorUncertainEntry`/`CheckResult` for diagnostics, and the conditional-spread MCP field for serving time. Seam 2 is a **stamp-and-verify provenance record**, generalized from the existing `computeSourceStamp` idiom (`freshness.ts:89`) with its `missing`/`unreadable` sentinels, carrying `{corpusGeneration, brainStamp, embeddingAbi, vaultIdentity}` written at build time and compared on read. A third, smaller piece falls out of both: one shared preference collector replacing the ten `readdirSync(dirs.preferences)` loops, which is the single place owner filtering and read diagnostics attach.
+ - Seam 1 carries **F** (all ~15 bare `catch { continue }` sites and the `vault.ts:113` line-drop, following the `dream.ts:974` precedent), **C** (the four null causes become a `LineageOutcome` discriminated union), **D** (compaction records what it discarded instead of dropping `firstSeenMs` silently), **G** (the dangling-link count is a degradation aggregate over `target_document_id IS NULL AND target_path IS NOT NULL`, with the read-time-resolvable ladder recorded as a second, separately-named code), and **A**'s legibility half (an owner-hidden count so a thin pack is distinguishable from an empty vault).
+ - Seam 2 carries **B** (pack stamp plus validity window; `corpusGeneration` alone is a lagging proxy because `packContext` walks the filesystem, so the pack stamp pairs it with a Brain-tree mtime/size stamp rather than a full sha256 manifest), **E** (a `vec_version` + model + dimension ABI token compared on read-mode open, surfaced as a reindex-required warning exactly like `EMBEDDING_PREFIX_QUERY_STATE_KEY`, never routed into `openReadOrSelfHeal` since that path rebuilds keyword-only), **J** (a vault-identity marker file, with `resolveVault` refusing rather than materializing an unmarked root), **H** and **I** (both are the stamp plus a token count riding `emitContextReceipt`, whose trigger enum widens to include a hook-layer value).
+ - Fail boundary follows the line the repo already declares: serving gates fail closed (E's read-mode ABI check, J's write guard, A's filter), capture and injection stay fail-soft but now name what they dropped. **A**'s enforcement half rides an explicit flag so a null scope stays byte-identical; **C** ships abstain-on-ambiguity plus git repo/branch/commit **capture only** (recorded on the lineage event, not yet used for matching); **D** ships sequence numbers, non-lossy compaction, and a `withFileLock` around the read-modify-write, but verification reports rather than refuses to start.
+- **Trade-offs**:
+ - Matches the house release shape exactly: a multi-unit wave with one or two shared seams named in the changelog as carrying it (1.37.0, 1.36.0).
+ - Satisfies the DRY constraint at its sharpest point β€” the ten-loop duplication and the fifteen swallowing catch sites are removed once, not patched per site.
+ - Each unit stays independently testable and independently revertable, so unit-by-unit TDD on one branch works without a big-bang integration step.
+ - The degradation channel risks becoming a dumping ground: without a closed enum reviewed per unit, "named" degrades back into "generic warning".
+ - Seam-first work delays the first visibly shipped unit; the two seams must be designed against all ten consumers before any adapter lands.
+ - Large test surface: every one of the ten units needs a byte-identical-when-absent test in addition to its behavior test.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 2: One delivery envelope
+
+- **Approach**: Collapse the read path into a single mandatory chokepoint. Every content-returning surface β€” the nine that bypass `isOwnerVisible` plus `search()` β€” builds its payload, then hands it to one `deliverContext(request, payload)` pass that resolves caller identity from a new `agent` field on `ServerContext` (via `resolveAgentName`), applies the isolation rule, attaches the provenance stamp and validity window, meters the emitted token count, and optionally emits a receipt. **A**, **B**, **H**, and **I** stop being four units and become four responsibilities of one function; **E**, **F**, **G**, and **J** become preconditions asserted at the envelope's entry (store ABI verified before any semantic hit is admitted, parse diagnostics riding the payload, vault identity checked at open); **C** and **D** shrink to the single job of producing a trustworthy session key the anticipatory cache path is derived from. **G**'s CI ratchet and **D**'s compaction rewrite are deliberately deferred to 1.40.0 as the two pieces that do not touch the envelope.
+- **Trade-offs**:
+ - The fail-closed boundary becomes a single line anyone can point at: inside the envelope closed, outside it soft. No per-unit judgment calls, no policy sprawl.
+ - Structurally forecloses the whole defect class rather than the ten instances β€” a future eleventh delivery surface cannot bypass isolation, because bypassing the envelope means returning nothing.
+ - Fixes `brain_search_expand`'s `chunk_id` enumeration surface as a consequence rather than a special case, since `expandHit` results must also transit the envelope.
+ - Highest threat to the byte-identical contract: nine surfaces change shape in one PR, and `brain_context` takes no arguments at all, so identity must be injected rather than passed.
+ - Fights the stated implementation model β€” unit-by-unit TDD is hard when eight of ten units are facets of one function that is only correct once all eight land.
+ - Blast radius is total: an envelope bug is a simultaneous outage of every context-delivery surface across a 108-tool MCP server.
+ - Deferring **D** and **G** leaves the ledger's clobbering read-modify-write and the absent link counter shipping nothing in this wave.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Evidence plane now, enforcement by policy
+
+- **Approach**: Split the wave along the axis of *does it refuse*. Plane one is evidence and ships complete for all ten units: every defect gets a detector that names it β€” F's parse diagnostics, G's dangling-link counter, H's injection meter, I's session receipt fold, B's stamp recorded, C's outcome union, D's sequence numbers, E's ABI token stamped and surfaced, A's owner-hidden count, J's identity marker written β€” all additive, all fail-soft, all byte-identical when unread. Plane two is a single new `gates:` config block with per-gate `off | warn | fail` modes (invalid value raises `BrainConfigError` at load, per the config contract), where only three gates gain a working `fail` mode in 1.39.0: **E** on read-mode dimension mismatch, **J** on vault-identity mismatch at write, **A** on delivery-surface owner scope. **G** additionally ships the committed baseline plus a `--check` npm script wired into `ci.yml` and `release.yml`, copying `scripts/sync-version.ts` exactly and establishing that convention. **C**'s git repo/branch/commit identity and **D**'s hash chain are explicitly deferred to 1.40.0 and named as deferred in the changelog; **C** ships only the abstain-on-ambiguity tie-break, **D** only non-lossy compaction plus a writer lock.
+- **Trade-offs**:
+ - Lowest-risk path to the wave's thesis: a silent failure becomes a named one on day one even where nobody is ready to refuse on it yet.
+ - The `gates:` block gives the operator, not the release, authority over the fail-closed line β€” which is the honest position for **E**, where `vec_version()` instability across Syncthing peers could otherwise produce a rebuild loop.
+ - Detection-first ordering means the counters and diagnostics exist before any gate is tuned against them, so **G**'s ceiling is derived from a measured baseline rather than guessed.
+ - Half-realizes the thesis in default installs: warn-by-default means the agent still cannot tell a genuine miss from a broken mechanism unless the operator opts in.
+ - A policy plane is itself an untested seam, and gate-mode combinatorics multiply the test matrix faster than the per-unit tests it replaces.
+ - Deferring two of ten units under-delivers against a wave framed as ten units, and **D**'s deferred hash chain leaves the ledger's silent-loss-at-compaction contract only partly closed.
+- **Complexity**: medium
+- **Risk**: low
+
+### Recommended: Variant 1
+
+**Rationale**: It is the only variant that ships all ten units while matching the house release shape β€” a multi-unit wave carried by one or two shared seams named in the changelog β€” and its two seams land precisely on the wave's actual duplication (the ten preference loops, the fifteen swallowing catches), which is what the DRY constraint demands and what Variant 3's per-unit detectors would leave in place. Variant 2's chokepoint is the structurally cleanest end state but puts nine delivery surfaces and the byte-identical contract at risk in a single pull request, and it contradicts the stated unit-by-unit TDD model. Variant 1 should absorb Variant 3's one genuinely better idea: give **E** and **A** graded modes rather than a binary gate, since `vec_version()` instability across peers and the "null scope is byte-identical" contract are both cases where the operator, not the release, should choose when refusal begins.
diff --git a/docs/brainstorm/context-integrity-gates/cli-output/prompt.md b/docs/brainstorm/context-integrity-gates/cli-output/prompt.md
new file mode 100644
index 00000000..e895ad42
--- /dev/null
+++ b/docs/brainstorm/context-integrity-gates/cli-output/prompt.md
@@ -0,0 +1,167 @@
+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 wave called "context integrity gates" across ten units of work in Open Second Brain. The unifying thesis: **every silent failure in the read and delivery path becomes an explicit, named one.** Today each of these ten defects degrades quietly - recall gets thinner, a pack gets staler, a note disappears from the index - and neither the agent nor the operator can distinguish a genuine miss from a broken mechanism.
+
+The ten units, with reconnaissance already completed against the live codebase:
+
+## A. Owner-scope isolation across every context-delivery surface
+
+`isOwnerVisible(owner, scope)` (`src/core/graph/agent-scope.ts:59`) is the single isolation rule. It has exactly two callers: `applyAgentScope` (`src/core/search/result-filters.ts:253`, reached only from `search()` at `src/core/search/search.ts:988` when `SearchOptions.agentScope` is non-null) and `isPreferenceVisible` (`src/core/brain/owner-scoped-facts.ts:30`, used by `brain_query` but gated behind the `guardrails.owner_scoped_facts` flag, default false).
+
+Every other content-returning surface bypasses it: `brain_context_pack`, `brain_anticipatory_context`, `brain_retrieval_plan`, `brain_pre_compress_pack`, `brain_brief`, `brain_file_context`, `brain_search_expand`, `brain_deep_synthesis`, and `brain_context` (the documented session-bootstrap surface, whose input schema is `{properties:{}, additionalProperties:false}` - it takes no arguments at all). `ContextPackOptions` (`src/core/brain/context-pack.ts:136`) has no owner field. `brain_search_expand` reaches full note bodies through `expandHit` (`src/core/search/cards.ts:67`) keyed on a sequential integer `chunk_id`, with no frontmatter check - an enumeration surface. `refreshAnticipatoryCache` (`src/core/brain/anticipatory-cache.ts:186`) persists an unfiltered pack to a disk file whose path is keyed only on the session-lineage root.
+
+Structural obstacle: there is no shared preference collector. Roughly ten independent `readdirSync(dirs.preferences)` loops exist (`active.ts:199`, `context-pack.ts:262`, `pre-compress-pack.ts:88`, `morning-brief.ts:74`, `digest.ts:703`, `dream.ts:1010`, `doctor.ts:1067`, `explorer.ts:95`, `vitals.ts:71`, `attention-flows.ts:196`). There is also no agent identity on `ServerContext` (`src/mcp/tool-contract.ts:34`), though `resolveAgentName(configPath)` exists at `src/core/config.ts:191`.
+
+Mitigating fact: no writer sets `owner` today - `writePreference` accepts `input.owner` (`src/core/brain/preference.ts:421`) but no MCP handler or CLI verb passes it. The leak is latent: it activates for the operator who hand-tags `owner:` in note frontmatter and reasonably assumes isolation holds everywhere.
+
+Tension: every module here documents a "null scope is byte-identical to today" contract. Defaulting a surface's scope from `resolveAgentName` would silently narrow existing vaults.
+
+## B. Context packs bound to a source generation and a validity window
+
+`ContextPackReport` (`src/core/brain/context-pack.ts:118`) carries no timestamp, no generation, no expiry. The one place a pack is serialized is the anticipatory cache: `CacheFile` (`src/core/brain/anticipatory-cache.ts:79`) has `schema`, `generated_at`, `max_tokens`, and the context. On a stale read, `readAnticipatoryContext` (`:199`) silently rebuilds live and reports `cache_state: "stale"` - never an error.
+
+The best existing generation source is `Store.corpusGeneration()` (`src/core/search/store.ts:567`), formatted by `computeCorpusGeneration` (`src/core/search/corpus-generation.ts:29`) as `model|dim|schemaVersion|indexRevision`, where `indexRevision` bumps only when an index run changed something. It is already proven as a fail-closed serving gate: `queryCacheSweep` (`store.ts:604`) deletes cache rows whose generation differs.
+
+Central correctness tension: `packContext` does not read the search index at all - it walks the filesystem directly (`readdirSync` over `brainDirs(vault)`, `context-pack.ts:258`). So `corpusGeneration()` is a lagging proxy: a hand-edited note changes the pack but does not bump `index_revision` until a reindex runs. Alternatives found: `buildManifest` (`src/core/brain/manifest.ts:58`, sha256 per file - byte-accurate but hashes the whole tree per call) and `computeSourceStamp` (`src/core/brain/freshness.ts:89`, the repo's existing "stamp what you were derived from, verify on read" idiom, per-source rather than global, with explicit `missing`/`unreadable` sentinels).
+
+## C. Session continuation, fail-closed
+
+Continuity is selected at exactly one point: `resolveCrutchLineage` (`src/core/brain/lineage/crutch.ts:40`), reached from `resolveSessionLineage` (`lineage/resolve.ts:68`). It matches on a conjunction of: session not already in the ledger, exact string equality on `cwd`, predecessor's latest event carries compression evidence, and age within `CRUTCH_LINK_WINDOW_MS = 900_000` (`lineage/ledger.ts:34`).
+
+Two defects. First, the multi-candidate tie-break is **most-recent-wins** (`crutch.ts:64`), not abstain - two concurrent sessions in the same directory inside the window silently stitch. Second, the return type is `SessionLineage | null`, so four distinct null causes (no candidate / self already known / no cwd / several candidates) are indistinguishable to every caller.
+
+No repo, branch, or commit is captured for a session anywhere. The hook payload carries only `cwd`. `git rev-parse` appears once in the entire repo (`src/core/brain/git/reader.ts:159`); there is no `symbolic-ref`, no `rev-parse HEAD`, no `remote get-url`. There is no git-remote credential normalization: `BASIC_AUTH_URL_RE` (`src/core/redactor.ts:152`) redacts `scheme://user:pass@` but is opt-in (`redactInfra`, default off) and produces a redaction, not a canonical identity key.
+
+Consequence of a mis-stitch: the anticipatory cache path is derived purely from the lineage root (`anticipatory-cache.ts:102`), so a wrong stitch redirects one conversation's cache into another's file.
+
+## D. Session-lineage ledger hardening
+
+`src/core/brain/lineage/ledger.ts` is an append-only JSONL with no sequence numbers, no hash chain, no writer lock, and no startup verification. `recordLineageObservation` (`:173`) wraps its entire body in `try {} catch {}` - fail-soft by explicit contract.
+
+Compaction (`:180-210`) is lossy in four ways: 512 lines collapse to at most 256, one summary line per session; per-session event history is destroyed; `firstSeenMs` is dropped entirely (the compacted line carries only `lastSeenMs`); sessions ranked 257+ by recency are deleted. The re-serializer hard-codes its field list, so any field added to the writer but not mirrored there is silently lost at the next compaction.
+
+The compaction branch is a read-modify-write with no mutual exclusion: two concurrent hooks crossing the cap both read 512 lines, both compact, and the second write clobbers the first.
+
+Design tension recorded during triage: this ledger is *deliberately* fail-soft, because continuity is a best-effort crutch and not a security boundary. A fully fail-closed ledger that refuses to start on a corrupt line could break crutch resolution rather than degrade gracefully.
+
+## E. Embedding-store ABI and dimension mismatch
+
+`index_state` (`src/core/search/schema.ts:173`) already stamps `embedding_model` and `embedding_dimension` (`store.ts:1033`). The sqlite-vec version is stamped nowhere - `SELECT vec_version()` is executed at three sites (`store.ts:221`, `indexer.ts:968`, a test helper) and the row is discarded every time.
+
+The existing compare (`ensureEmbeddingModel`, `store.ts:984`) runs **only on a write-mode open** (`store.ts:470`). A read-only consumer - which is every MCP query - never reaches it, so `semanticTopK` (`store.ts:1712`) runs `WHERE v.embedding MATCH ?` against a `chunk_vec` of unknown declared width with no model or dimension check. That is the silent-garbage path.
+
+Self-heal is `openReadOrSelfHeal` (`src/core/search/search.ts:166`), triggering on exactly `INDEX_MISSING | SCHEMA_MISMATCH | INDEX_UNREADABLE`. Critical trap: it calls `reindexVault(config)` with no options (`search.ts:176`), so `opts.embeddings` is undefined and the rebuild is keyword-only - **routing a vector mismatch into the existing self-heal as-is would not rebuild the vectors.**
+
+Precedent to mirror: the embedding prefix pair (`EMBEDDING_PREFIX_QUERY_STATE_KEY`, `store.ts:47`) is exactly this mechanism - a compat token stamped at build time, compared later, surfaced as a reindex-required warning rather than a hard heal.
+
+Risk: `vec_version()` is not stable across environments. Two Syncthing peers on different sqlite-vec builds would each see a mismatch and each trigger a full rebuild - a possible rebuild loop.
+
+## F. Malformed frontmatter reported instead of silently dropped
+
+The premise recorded in the tracker was wrong and the reality is worse. `parseFrontmatterText` (`src/core/vault.ts:78`) is a line-based `key: value` scanner, not a YAML parser. It **cannot throw**. Its documented contract (`vault.ts:58`) is "lines that don't match are silently skipped" - the drop is at `vault.ts:113`, `if (!kv) continue`. A note is therefore never dropped from the index; instead individual frontmatter fields vanish, leaving the page untyped, unaliased, or undated with zero trace in `IndexStats` (`src/core/search/types.ts:264`, which has no `scanned` and no `skipped` field).
+
+Commit 426d06f8 was exactly this class of bug found in the field: block-style YAML lists were silently dropped and produced spurious "missing field" errors in `o2b brain doctor`. The fix added a grammar branch but no diagnostic channel, so the next unsupported grammar fails the same silent way.
+
+About fifteen call sites additionally swallow the reader with bare `catch { continue }` (`query.ts:330`, `context-pack.ts:269`, `heal-run.ts:86`, `claim-graph.ts:124`, `procedural-graph.ts:189`, `source-cleanup.ts:250`, `idea-discovery.ts:180`, and others), several with comments deferring to "the doctor's concern". Two sites do it right and are the precedent: `dead-ends.ts:183` (pushes a warning with the path) and `dream.ts:974` (accumulates `corrupted` entries and emits a `skip-corrupted-frontmatter` log event).
+
+One malformed case is already reported: an unterminated block yields a chunker warning (`src/core/search/chunker.ts:137`) forwarded into `IndexStats.errors` (`indexer.ts:397`).
+
+Reporting surfaces are split: `runDoctor`/`DoctorIssue` (`src/core/brain/doctor.ts:206`, `src/core/brain/types.ts:1665`) is CLI-only and already has an `uncertain: DoctorUncertainEntry[]` extension point for "attempted but cannot claim completed cleanly"; `vault_health`/`CheckResult` (`src/mcp/tools.ts:176`, `src/core/types.ts:17`) is a different core entry point for install and manifest checks.
+
+## G. Vault-wide broken-link ratchet gate
+
+The premise here was also wrong: **no vault-wide broken or dangling link count exists anywhere in the codebase.** The tracker's anchors point at graph-degree filter machinery. The ratchet needs both a counter and a ceiling.
+
+Primitives that exist: `links.target_document_id INTEGER REFERENCES documents(id) ON DELETE SET NULL` (`src/core/search/schema.ts:164`) - a dangling link is exactly `target_document_id IS NULL AND target_path IS NOT NULL`; two resolution passes run per index run (`store.ts:1088`, `store.ts:1141`); `extractWikilinks` (`src/core/vault.ts:297`). A Brain-scoped, deliberately narrow counter exists in the doctor (`checkBrokenBacklinks`, `doctor.ts:1016`), which skips anything not matching `^(pref|ret|sig)-` because "wikilinks pointing outside the Brain layer are user prose and not our concern".
+
+Definition hazard: read-time link resolution applies a further conservative ladder (materialized id, then `<target>.md` exact, then unambiguous basename suffix) at `store.ts:1193` and siblings. A link can be `target_document_id IS NULL` in SQL yet resolvable at read time. The design must pick one definition and state it. Second hazard: `resolveAliasTargets` only populates aliases for documents changed in that run, so a count taken after an incremental run can differ from one taken after a forced full run.
+
+The precedent to copy exactly is `scripts/sync-version.ts`: a committed invariant plus a `--check` form that is the same code path with writing disabled (`updateFile(rel, regex, version, !check)`), returning 1 on drift, wired into CI as a named npm script (`sync-version:check`) in both `ci.yml` and `release.yml`. There is no committed baseline or ceiling data file in this repository yet, so this unit establishes that convention.
+
+## H. Injection-size meter for the SessionStart eager layer
+
+`hooks/active-inject.ts` composes the eager layer in `assembleActiveContext` (`:161`) from exactly two parts: rendered runtime notices, and an active body that is itself `Brain/active.md` plus `Brain/lessons.md`, each budgeted separately against the same `inject_budget_chars` value (so the effective ceiling is twice the configured one - itself a finding). The three sub-bodies exist as separate strings only inside that function; `parts.join("\n\n")` at `:172` discards the split.
+
+Nothing measures the emitted string. No `estimateTokens` call and no length accounting exists anywhere in `hooks/`. The canonical estimator already exists (`estimateTokens`, `src/core/brain/text/tokenizer.ts:35`), as do `computeTokenFootprint` (per-category token attribution over the vault) and `computeActiveBudgetPressure` (per-section byte breakdown of active.md, currently a doctor probe only).
+
+The natural sink is `emitContextReceipt` (`src/core/brain/context-receipts.ts:85`), but its trigger enum is `"context_pack" | "pre_compress"` and its only two callers are the two pack builders - no hook emits a receipt today.
+
+Hard constraint: the hook path is fail-soft by absolute contract (the wrapper script always exits 0) and runs under a process ceiling. `emitContextReceipt` writes to the continuity store under `acquireLockSync`, so a lock contention throw would be new failure surface on the SessionStart path. Also `active-inject` fires on PostCompact too, so it will record two events per compacted session.
+
+Two triage claims were verified false and must not be carried into the design: `inject-governor.ts` is the belief-lifecycle recall governor and is not on the injection path at all; and pinned context is not part of the eager layer (it rides only the `brain_context` pull path).
+
+## I. Session-scoped retrieval receipt
+
+Reconnaissance verdict: REDUCE. All primitives exist and are durable - `context_receipt` records carry per-item id, path, tokens, tier, trimmed, safety_filtered, epistemic, evidence refs and text hashes; `recall_telemetry` carries `topArtifacts` with scores; `recall_observed_use` carries per-artifact USED/IGNORED/CONTRADICTED with a lifetime `observedReuseRates` fold. What is missing is only the fold: nothing joins receipts across a session, `listContextReceipts` has four callers and all of them map one summary per record, and `observedReuseRates` takes no session or time filter. Receipt emission is also opt-in (`receipt: true`), so a session where no caller asked for one produces nothing.
+
+## J. Guard against writes to an unexpected memory-store location
+
+Verdict: BUILD. `resolveVault` (`src/core/config.ts:161`) has five branches; four return a path with zero existence validation (env `VAULT_DIR`, active profile, config `vault:` key), and the fifth (the pointer file) stats but fails soft. No vault-identity marker exists anywhere. Every Brain write funnels through `brainDirs(vault)` (`src/core/brain/paths.ts:161`, containment check only) and lands in `withTempFile`, which calls `mkdirSync(dir, {recursive: true})` (`src/core/fs-atomic.ts:156`) - so a mis-resolved root is materialized by the first write.
+
+The diagnostic that should catch this actively masks it: `runDoctor` returns `{errors: [], trust_verdict: "clean"}` when `Brain/` is absent (`src/core/brain/doctor.ts:210-222`). `vault_health` catches only a missing root and stops catching anything once the first write creates it. `brain_switch_vault` can activate a profile pointing at a non-existent directory (`profiles.ts:109`), failing in a later process. The OpenClaw entry point silently defaults to the current working directory (`src/openclaw/index.ts:31`).
+
+The desired shape already exists in the codebase and has simply never been applied to the vault root: `json-source.ts:139` throws `noDefaultDirMessage` rather than guessing.
+
+# Project context
+
+Open Second Brain - TypeScript on the Bun runtime, an agent-owned second brain over an Obsidian-compatible Markdown vault, exposed as a CLI (`o2b`) and an MCP server (108 tools). The kernel is deterministic and calls no LLM. Current version 1.38.0; this wave targets 1.39.0.
+
+Recent commits:
+
+```
+c31a2574 feat: semantic-health baseline watermark (v1.38.0) (#148)
+b0c37977 feat: retrieval quality and context delivery (v1.37.0) (#146)
+842d690f feat: knowledge intake and consolidation (v1.36.0) (#145)
+95dc8577 feat: trusted recall and memory write surface (v1.35.0) (#144)
+426d06f8 fix(vault): parse block-style YAML lists in frontmatter (not just inline arrays) (#142)
+4b8100ca feat: source pipeline integrity and operator tooling (v1.34.0) (#143)
+77513f2b feat: belief lifecycle and decision memory (v1.33.0) (#141)
+61e93d24 fix(config): derive vault store reference from a keyed installation secret (#140)
+9a649dd6 feat: memory write-path integrity and store safety wave (v1.32.0) (#139)
+f2a037eb feat: today operator surface - dashboard, open loops, marker write-back (v1.31.0) (#138)
+13bde6c3 refactor: remove all import cycles, decompose search.ts (v1.30.1) (#137)
+fd5661f9 feat: governance visibility - vitals scorecard + batch-inflation lint (v1.30.0) (#136)
+```
+
+The house release shape is a multi-unit wave: 1.37.0 shipped nine units, 1.36.0 shipped eight, each with one or two shared seams named explicitly in the changelog as carrying the wave.
+
+Related files: as cited inline above.
+
+Conventions (all verified against the codebase):
+
+- Exit codes: 0 success or fail-soft skip, 1 operational failure, 2 usage error. `okJson` emits `{ok: true, ...payload}`; the failure idiom is `okJson({ok: false, message})` then return 1.
+- Config: `_brain.yaml` parsed by a hand-written subset parser (max two levels of nesting). An invalid value must raise `BrainConfigError` at load; the file states "clamping silently would mask the operator's intent". New optional blocks use the `DEFAULTS` constant plus a `resolve*()` twin rather than parse-time merging.
+- Writes: `withFileLock(target, {staleMs: 30_000, retries: 3}, cb)` around a read-modify-write, then `atomicWriteText(path, text, {validate: candidate => reparse(candidate)})` so an unparseable file can never land.
+- MCP: an additive field on an existing tool's response changes no pinned count, provided the tool declares no `outputSchema`. Convention is a conditional spread (key absent, never null, when inapplicable) and camelCase core to snake_case wire.
+- Every new surface must be byte-identical to the previous release when its flag, parameter, or config key is absent. This contract is stated in module docblocks throughout and enforced by tests.
+- The repository draws a deliberate line: capture and injection paths swallow all errors, while serving gates fail closed.
+
+Constraints:
+
+- No stub implementations and no do-nothing fallbacks. A fallback that silently returns an empty or default result where an error occurred is the specific anti-pattern this wave exists to remove; do not introduce new instances of it.
+- No hardcoded natural-language word lists in any language. Classification and gating must be structural (explicit frontmatter fields, corpus frequency, typed vocabulary), never keyword matching against a fixed set of words.
+- No new external dependencies.
+- The kernel calls no LLM. Everything here must be deterministic.
+- SOLID, KISS, DRY. Extract shared logic rather than repeating a predicate across ten call sites.
+- Implementation proceeds unit by unit under test-driven development on one branch, shipped as one pull request and one release.
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants for how to structure this wave as a whole - how the ten units decompose, what shared seams (if any) carry them, what lands in this release versus what is deliberately deferred, and how the fail-closed and fail-soft boundary is drawn. Variants must differ in structure, not merely in ordering.
+
+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/context-integrity-gates/design.md b/docs/brainstorm/context-integrity-gates/design.md
new file mode 100644
index 00000000..d7d6efec
--- /dev/null
+++ b/docs/brainstorm/context-integrity-gates/design.md
@@ -0,0 +1,108 @@
+# Context integrity gates - every silent failure becomes a named one
+
+**Status:** draft
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Ten defects in Open Second Brain's read and delivery path degrade quietly. Owner-scoped isolation is enforced on one surface out of thirteen. A context pack carries no record of the vault state it was built from, so a stale pack is indistinguishable from a fresh one. Session continuation resolves ambiguity by picking the most recent candidate instead of abstaining. The lineage ledger loses history on compaction and has no writer lock. An embedding store written against a different model, dimension, or sqlite-vec ABI returns zero or garbage neighbours on the read path with no check at all. A frontmatter line the parser does not understand is dropped without a trace. Nothing counts broken links vault-wide. Nothing measures the SessionStart injection. Nothing joins retrieval receipts across a session. A mis-resolved vault root is materialized by the first write, and the doctor reports it clean.
+
+In every one of these cases the agent cannot distinguish a genuine miss from a broken mechanism, which is precisely the failure mode this project's design posture exists to prevent.
+
+## Scope
+
+Ten units, carried by two shared seams.
+
+**Seam 1 - typed degradation channel.** One closed-vocabulary notice record (`code`, `site`, `path?`, `detail`) plus the helper that emits it, carried by the report types that already exist: `IndexStats` for index runs, `DoctorUncertainEntry` for the doctor, and conditional-spread additive fields for MCP responses.
+
+**Seam 2 - stamp and compare.** One module owning the "record what you were derived from, verify on read" pattern: a stamp comparison over a token map, a typed mismatch, and the three-mode gate resolution (`off` / `warn` / `fail`) that lets the operator choose where refusal begins.
+
+Units:
+
+- **A. Owner-scope isolation across every context-delivery surface.** A shared preference collector replaces the ten independent `readdirSync(dirs.preferences)` loops and becomes the single place the owner predicate attaches. Search-backed surfaces thread `agentScope` into the existing `SearchOptions`. `expandHit` gains a per-hit owner check. A table-driven regression test asserts the rule on every content-returning surface.
+- **B. Context packs bound to a source generation and a validity window.** Packs carry a provenance stamp and an expiry; the anticipatory cache refuses a stamp mismatch instead of silently rebuilding.
+- **C. Fail-closed session continuation.** The crutch resolver returns a named outcome instead of a bare `null`, abstains on ambiguity rather than picking the most recent, and records repo, branch, and commit evidence with credential-free remote normalization.
+- **D. Session-lineage ledger hardening.** Sequence numbers, a hash chain, a writer lock, lossless compaction, and a verification pass that reports rather than refuses.
+- **E. Embedding-store ABI and dimension mismatch.** The sqlite-vec version joins the model and dimension already stamped in `index_state`; the comparison moves onto the read path, where today there is none.
+- **F. Malformed frontmatter reported instead of silently dropped.** The line scanner gains a diagnostic channel; the index run, the doctor, and the fifteen swallowing call sites surface what they discarded.
+- **G. Vault-wide broken-link ratchet gate.** A deterministic dangling-link counter, a committed ceiling file, and a `--check` form wired into CI, copying `scripts/sync-version.ts` exactly.
+- **H. Injection-size meter for the SessionStart eager layer.** Per-source bytes and tokens measured where the sub-bodies still exist as separate strings, emitted into the receipt surface.
+- **I. Session-scoped retrieval receipt.** A read-only fold over records that already exist, exposed as a new operation on an existing tool.
+- **J. Guard against writes to an unexpected memory-store location.** A vault identity marker, a write-path assertion, validation in `brain_switch_vault`, and removal of the doctor early return that masks the condition.
+
+## Out of scope
+
+- **Durable cross-session work identity with execution lanes** (kanban `t_e6be4f6b`). The timing crutch stays; C makes its failures visible and abstains where it cannot tell, which is the prerequisite for replacing it. The replacement is architectural and needs its own design record.
+- **A `--fix` consumer for the diagnostics this wave produces** (kanban `t_f35e184a`). This wave establishes the finding contract; a deterministic applier over it is a separate unit of work.
+- **Shrinking the SessionStart eager layer.** H lands the meter only. Source-aware injection, spawn merge, hint dedupe, and listing collapse are optimizations that must be attributable to a measurement that does not exist yet.
+- **A writer surface for `owner`.** `writePreference` already accepts `input.owner`; no MCP handler or CLI verb passes it. A adds enforcement and leaves the write plumbing as it is, so the gate defaults to `off` and no existing vault narrows.
+- **Making the lineage ledger a security boundary.** D hardens integrity and concurrency; the read path stays fail-soft by contract, because continuity is best-effort and a ledger that refuses to start would break resolution rather than degrade.
+- **Routing an embedding mismatch into `openReadOrSelfHeal`.** That path calls `reindexVault(config)` with no options, so the rebuild is keyword-only and would not touch the vectors. E reports; it does not pretend to heal.
+
+## Chosen approach
+
+Two horizontal seams, ten thin adapters (consultant Variant 1), with graded gate modes grafted from Variant 3 for the two units where the environment - not the release - should decide when refusal begins.
+
+The seams are chosen because they land on this wave's actual duplication. Seam 1 removes fifteen bare `catch { continue }` sites and one structural line-drop by giving them one place to report to. Seam 2 removes three independent "compare a recorded token against a live token" implementations that B, E, and J would otherwise each invent. The shared preference collector that A needs is a third, smaller consequence of the same principle: ten copies of the same directory walk become one, and the owner predicate attaches to it once.
+
+Graded modes apply to exactly two units. **E** because `vec_version()` is not stable across environments: two peers on different sqlite-vec builds would each see a mismatch, and a hard gate could produce a rebuild loop across a synced vault. **A** because every module in that path documents a "null scope is byte-identical" contract, and defaulting a scope from the resolved agent name would silently narrow existing vaults. Everywhere else the gate is binary, because the condition is unambiguous: a pack whose stamp no longer matches is stale, a vault whose recorded identity does not match the resolved root is the wrong vault.
+
+The fail-closed and fail-soft boundary follows the line this repository already draws and states in module docblocks: capture and injection paths swallow errors and now name what they dropped; serving gates refuse. Concretely, E's read-path check, A's delivery filter, B's cache rejection, and J's write guard fail closed; C's abstention, D's verification, F's diagnostics, and H's meter are fail-soft and report.
+
+## Design decisions
+
+- **The degradation vocabulary is a closed union, not a free string.** The consultant's own critique of Variant 1 is that a typed channel becomes a dumping ground. A closed `DegradationCode` union reviewed per unit is the mitigation: adding a code is a deliberate edit, and an exhaustive switch makes an unhandled code a type error.
+- **`parseFrontmatterText` keeps its exact signature.** A sibling returning `[map, body, notices]` carries the diagnostics; the existing two-tuple function delegates and discards. Every one of its callers stays byte-identical until it opts in. This is why F can convert fifteen call sites without a single behavioural regression in the ones not yet converted.
+- **The pack stamp pairs `corpusGeneration()` with a Brain-tree stamp.** `corpusGeneration()` alone is a lagging proxy: `packContext` walks the filesystem and never reads the index, so a hand-edited note changes the pack without bumping `index_revision`. The Brain-tree stamp is a digest over path, mtime, and size for the directories the pack actually walks - cheap, unlike `buildManifest`, which sha256-hashes every file per call.
+- **The anticipatory cache schema version bumps.** Pre-existing cache files then read as misses rather than as un-stamped hits, reusing the rejection branch `readCacheFile` already has for a schema mismatch. No migration, no ambiguity.
+- **E stamps and compares; it never silently rebuilds.** The precedent is the embedding prefix pair, which stamps a compat token at build time and surfaces a reindex-required warning. E follows it exactly, adds `vec_version` to the same `index_state` block with the same delete-on-change semantics, and moves the comparison to the read-mode open where today nothing checks.
+- **C captures git evidence and uses it; it does not replace the timing window.** Repo, branch, and commit become additional required-match predicates alongside the existing `cwd` and freshness rules. The 15-minute window stays as the freshness bound. The change that matters more is the tie-break: two surviving candidates now abstain with `ambiguous` instead of resolving by recency.
+- **The credential normalizer is a canonicalizer, not a redactor.** `BASIC_AUTH_URL_RE` rewrites credentials to a placeholder, which is correct for logs and useless as an identity key: two clones with different tokens would produce the same redacted string but a different one from a credential-free clone. C needs `scheme://host/org/repo` with userinfo, port, `.git` suffix, and trailing slash normalized away, so the same repository compares equal regardless of how it was cloned.
+- **D's verification reports; it never refuses to start.** `readLineageLedger`'s catch-to-empty-map is load-bearing for both the anticipatory cache and the session-lifecycle hook. Verification is a separate exported function whose findings reach the doctor.
+- **D's compaction stops summarizing.** The lossy fold to one line per session is replaced by retention of the most recent lines verbatim, so `firstSeenMs`, event history, and any field added later survive. The re-serializer that hard-codes its field list disappears with it, which removes the silent-field-loss trap rather than documenting it.
+- **G counts links unresolved after the read-time ladder.** ~~The counter uses the SQL definition (`target_document_id IS NULL`) because it is the one that is stable, index-backed, and reproducible.~~ Superseded by measurement: the SQL predicate reported 55 dangling out of 55 link rows on `templates/brain-starter`, because that vault is written in basename wikilinks the ladder resolves and the column does not β€” so the count rose on healthy edits as much as on broken ones. The counter now shares the ladder's SQL with `resolvedDocLinkPairs` and counts what it leaves unresolved. Every rung is still index-backed and deterministic. The ceiling file records the definition token alongside the count so a change of definition cannot be mistaken for link rot; the `--check` form refuses a foreign token and the write form re-measures under the new one. The count is taken after a full resolution pass, never from a partial incremental state.
+- **G's ceiling is JSON at the repository root.** Every machine-read committed invariant here is JSON at the root, and JSON gets free coverage from `fmt:check` and the release-time JSON validation step. The file carries `schema_version`, matching the convention in `schemas/brain/`.
+- **H measures at emission, not at assembly.** The measurement is taken after the fail-open loader returns, so it reflects what is actually written to stdout, and it records the loader's `source` so a degraded-to-cache injection is distinguishable from a genuinely small one.
+- **I adds an operation, not a tool.** The MCP tool count stays 108. The fold is read-only over `context_receipt` records that already carry every field the report needs.
+- **J distinguishes "unmarked" from "mismatched".** An absent marker cannot tell an old vault from a wrong root, so it warns. A marker that is present and does not match the expectation is unambiguous, so it refuses. The init path writes the marker; the write guard is the only new assertion, and it hangs off the function every Brain writer already funnels through.
+- **No new dependency, no LLM call, no natural-language word list.** Every predicate in this wave is structural: a frontmatter field, a SQL null, a hash comparison, a token count, a directory identity.
+
+## File changes
+
+New modules:
+
+- `src/core/integrity/degradation.ts` - the notice record, the closed code union, the emit helper.
+- `src/core/integrity/stamp.ts` - stamp comparison, typed mismatch, gate-mode resolution.
+- `src/core/brain/preferences-collect.ts` - the shared preference collector with the owner predicate.
+- `src/core/brain/lineage/verify.ts` - ledger chain verification.
+- `src/core/brain/vault-identity.ts` - marker read, write, and comparison.
+- `src/core/search/link-ratchet.ts` - the dangling-link counter and ceiling comparison.
+- `scripts/link-ratchet.ts` - the write and `--check` forms.
+- `link-ratchet.json` - the committed ceiling, repository root.
+
+Modified, by unit:
+
+- **Seam 1 / F**: `src/core/vault.ts`, `src/core/search/indexer.ts`, `src/core/search/types.ts`, `src/core/brain/doctor.ts`, and the fifteen swallowing call sites.
+- **Seam 2 / config**: `src/core/brain/types.ts`, `src/core/brain/policy.ts`, `src/core/brain/index.ts`.
+- **A**: `src/core/brain/context-pack.ts`, `pre-compress-pack.ts`, `morning-brief.ts`, `digest.ts`, `active.ts`, `file-recall.ts`, `deep-synthesis.ts`, `src/core/search/cards.ts`, `src/cli/search.ts`, `src/cli/brain/verbs/sgrep.ts`, `src/mcp/tool-contract.ts`, `src/mcp/brain/pack-tools.ts`, `brief-tools.ts`, `context-tools.ts`, `src/mcp/search-tools.ts`.
+- **B**: `src/core/brain/context-pack.ts`, `anticipatory-cache.ts`, `src/mcp/brain/pack-tools.ts`.
+- **C**: `src/core/brain/lineage/crutch.ts`, `resolve.ts`, `ledger.ts`, `types.ts`, `src/core/brain/session-lifecycle.ts`, `src/core/brain/git/reader.ts`, `src/core/redactor.ts`.
+- **D**: `src/core/brain/lineage/ledger.ts`.
+- **E**: `src/core/search/store.ts`, `indexer.ts`, `types.ts`, `src/cli/search.ts`.
+- **G**: `src/core/search/store.ts`, `src/mcp/brain/hygiene-tools.ts`, `package.json`, `.github/workflows/ci.yml`, `.github/workflows/release.yml`.
+- **H**: `hooks/active-inject.ts`, `src/core/brain/context-receipts.ts`.
+- **I**: `src/core/brain/context-receipts.ts`, `observed-use.ts`, `src/mcp/brain/pack-tools.ts`.
+- **J**: `src/core/brain/paths.ts`, `init.ts`, `doctor.ts`, `src/core/brain/portability/profiles.ts`, `src/mcp/brain/entity-tools.ts`.
+
+Docs: `CHANGELOG.md`, `README.md`, `docs/cli-reference.md`, `docs/mcp.md`, `docs/how-it-works.md`.
+
+## Risks and open questions
+
+- **Byte-identical regression surface.** Ten units each need an assertion that output is unchanged when the new field, flag, or config key is absent. This is the largest single share of the test budget and is non-negotiable: the contract is stated in module docblocks throughout the repository.
+- **A touches ten preference-reading call sites at once.** The mitigation is that the collector is introduced first with identical behaviour and no predicate, so the refactor and the enforcement are separately reviewable and separately revertable.
+- **`vec_version()` instability across peers** is the reason E defaults to `warn`. If the observed value proves stable enough in practice, the default can tighten in a later release; tightening it in this one would risk a rebuild loop on a synced vault.
+- **G's first ceiling is a measurement, not a target.** It is generated from the current vault state, which means the initial value encodes whatever link rot exists today. That is the point of a ratchet, but the changelog must say so plainly rather than implying the vault is clean.
+- **D's writer lock has no retry in its synchronous form.** An `ELOCKED` throw lands in the existing outer catch and drops the observation - which the new sequence numbers would then correctly flag as a gap. The implementation must decide between a bounded retry and recording the gap explicitly; recording it is preferred, since a named gap is exactly what this wave is for.
+- **H fires on PostCompact as well as SessionStart**, so two measurements per compacted session are expected. The record carries the hook event name so the two are distinguishable rather than double-counted.
+- **The `gates` vocabulary must not grow past the two units that need it.** Every additional mode multiplies the test matrix; units whose condition is unambiguous stay binary.
diff --git a/docs/brainstorm/context-integrity-gates/plan.md b/docs/brainstorm/context-integrity-gates/plan.md
new file mode 100644
index 00000000..0877cab7
--- /dev/null
+++ b/docs/brainstorm/context-integrity-gates/plan.md
@@ -0,0 +1,96 @@
+# Context integrity gates - implementation plan
+
+Fourteen atomic units on one branch, `feat/context-integrity-gates`, each a separate conventional commit. Test-driven: every unit writes its failing tests first and runs them to confirm they fail for the expected reason before any implementation.
+
+Gates before every commit, all in the foreground: `bun run fmt`, `bun run lint` (baseline is exactly 134 warnings and 0 errors), `bun run typecheck`, the full `bun test`, and `bun run scripts/sync-version.ts --check`.
+
+Every unit carries a byte-identical assertion: with its new field, flag, or config key absent, the affected output must equal the previous release's output exactly.
+
+## Tasks
+
+### Task 1: Degradation notice seam
+- **Files**: `src/core/integrity/degradation.ts` (new), `tests/core/integrity/degradation.test.ts` (new)
+- **What**: the notice record (`code`, `site`, `path?`, `detail`), a closed `DegradationCode` union, and the emit helper. Codes are added deliberately per consuming unit; an unhandled code must be a type error at the consumer, not a runtime string.
+- **Acceptance**: the union is exhaustive-switchable; a notice renders to a single-line English string with the path when known; no natural-language classification anywhere in the module.
+- **Depends on**: none
+
+### Task 2: Frontmatter diagnostic channel
+- **Files**: `src/core/vault.ts`, `tests/core/vault.test.ts`
+- **What**: a sibling of `parseFrontmatterText` returning `[map, body, notices]`, where every line the `key: value` scanner drops and every unreadable read produces a notice. `parseFrontmatterText` and `parseFrontmatter` keep their exact current signatures and delegate, discarding notices.
+- **Acceptance**: the existing tests at `tests/core/vault.test.ts:34-70` pass unchanged; a new test asserts that `-foo` (the case currently pinned as "silently ignored") produces exactly one notice naming the line; the block-list regression from commit 426d06f8 still parses and produces no notice.
+- **Depends on**: Task 1
+
+### Task 3: Frontmatter diagnostics surfaced
+- **Files**: `src/core/search/indexer.ts`, `src/core/search/types.ts`, `src/core/brain/doctor.ts`, `src/cli/search.ts`, and the swallowing call sites: `src/core/brain/query.ts`, `context-pack.ts`, `heal-run.ts`, `source-cleanup.ts`, `claim-graph.ts`, `procedural-graph.ts`, `idea-discovery.ts`, `attention-flows.ts`, `src/core/vault.ts` (the `walk` catch), plus tests
+- **What**: the index run reports per-file frontmatter notices through `IndexStats`; the doctor reports them through its `uncertain` extension point; each bare `catch { continue }` on a frontmatter read is replaced by a named notice plus the same control flow. Behaviour is unchanged - only the trace is new.
+- **Acceptance**: a vault containing a note with an unsupported frontmatter grammar produces a named diagnostic in the index-run output and in `o2b brain doctor`, and the note still indexes; the doctor still never throws; a vault with no malformed frontmatter produces output byte-identical to before.
+- **Depends on**: Task 2
+
+### Task 4: Stamp-and-compare seam and the `integrity` config block
+- **Files**: `src/core/integrity/stamp.ts` (new), `src/core/brain/types.ts`, `src/core/brain/policy.ts`, `src/core/brain/index.ts`, `tests/core/integrity/stamp.test.ts` (new), `tests/core/brain/policy-integrity.test.ts` (new)
+- **What**: stamp comparison over a token map, a typed mismatch carrying field, expected, and actual, and the `off | warn | fail` gate resolution. The `integrity` block adds `owner_scope_delivery` (default `off`), `embedding_abi` (default `warn`), and `pack_validity_seconds` (positive integer). Follow the defaults-plus-resolver strategy, not parse-time merging, and register the keys in `warnUnknownKeys`.
+- **Acceptance**: an invalid mode string and a non-positive `pack_validity_seconds` each raise `BrainConfigError` naming the dotted field; an absent block resolves to the documented defaults; a fully-known config emits no warnings (this is what `tests/core/brain.policy.test.ts:416` pins).
+- **Depends on**: none
+
+### Task 5: Shared preference collector, behaviour-preserving
+- **Files**: `src/core/brain/preferences-collect.ts` (new), `src/core/brain/active.ts`, `context-pack.ts`, `pre-compress-pack.ts`, `morning-brief.ts`, `digest.ts`, plus tests
+- **What**: one collector replacing the independent `readdirSync(dirs.preferences)` loops on the delivery path. No predicate yet - this task is a pure refactor whose only job is to prove the collector is a faithful replacement.
+- **Acceptance**: every existing test over these five surfaces passes unchanged; the collector is the only `readdirSync` of the preferences directory on the delivery path.
+- **Depends on**: none
+
+### Task 6: Owner scope on preference-backed delivery surfaces
+- **Files**: `src/core/brain/preferences-collect.ts`, `context-pack.ts` (owner on `ContextPackOptions`), `pre-compress-pack.ts`, `morning-brief.ts`, `digest.ts`, `active.ts`, `src/core/brain/anticipatory-cache.ts` (owner in the cache key), plus tests
+- **What**: the owner predicate attaches to the collector, gated by `integrity.owner_scope_delivery`. The anticipatory cache path includes the scope, so a cache built under one scope can never be served under another.
+- **Acceptance**: with the gate `off`, output is byte-identical to Task 5; with it `fail`, an owner-tagged preference is absent from every one of these surfaces for a different scope and present for its own; an ownerless preference is always visible; the cache file for scope A is a distinct path from scope B.
+- **Depends on**: Task 4, Task 5
+
+### Task 7: Owner scope on search-backed surfaces and the drill-down
+- **Files**: `src/core/brain/file-recall.ts`, `src/core/brain/deep-synthesis.ts`, `src/cli/brain/verbs/sgrep.ts`, `src/cli/search.ts`, `src/core/search/cards.ts`, plus tests
+- **What**: thread `agentScope` into the existing `SearchOptions` for each search-backed caller, add the `--agent-scope` flag beside `--visibility`, and give `expandHit` an owner check on the resolved path that returns the existing not-found error rather than a distinguishable refusal.
+- **Acceptance**: a scoped call to each surface excludes another owner's page; an unscoped call is byte-identical; `expandHit` on another owner's chunk id is indistinguishable from a missing chunk.
+- **Depends on**: Task 4
+
+### Task 8: MCP scope arguments and the isolation regression matrix
+- **Files**: `src/mcp/tool-contract.ts`, `src/mcp/brain/pack-tools.ts`, `brief-tools.ts`, `context-tools.ts`, `src/mcp/search-tools.ts`, `tests/mcp/agent-scope-matrix.test.ts` (new)
+- **What**: an `agent_scope` argument on every content-returning tool that lacks one, an agent identity on `ServerContext` resolved through `resolveAgentName` for the no-argument `brain_context` surface, and a table-driven test asserting the rule once per surface.
+- **Acceptance**: the matrix test enumerates every content-returning tool and fails if a new one is added without an entry; the MCP tool count stays 108; every tool that declares an `outputSchema` with `additionalProperties: false` is left untouched or has its schema extended deliberately.
+- **Depends on**: Task 6, Task 7
+
+### Task 9: Pack provenance stamp and validity window
+- **Files**: `src/core/brain/context-pack.ts`, `src/core/brain/anticipatory-cache.ts`, `src/mcp/brain/pack-tools.ts`, plus tests
+- **What**: a stamp pairing `corpusGeneration()` with a Brain-tree digest over path, mtime, and size for the directories the pack walks, plus an expiry from `integrity.pack_validity_seconds`. The anticipatory cache stores both and rejects a mismatch or an expiry as a miss; its schema version bumps so pre-existing files read as misses.
+- **Acceptance**: editing a Brain note invalidates a warm cache entry; an expired entry is refused rather than served; a rebuilt entry is served; the refusal names the reason; with the cache absent, `brain_context_pack` output is byte-identical.
+- **Depends on**: Task 4
+
+### Task 10: Embedding ABI stamp and read-path comparison
+- **Files**: `src/core/search/store.ts`, `src/core/search/indexer.ts`, `src/core/search/types.ts`, `src/cli/search.ts`, plus tests
+- **What**: capture the already-executed `vec_version()` result and stamp it into `index_state` beside `embedding_model` and `embedding_dimension`, with the same delete-on-change semantics. Compare all three on the read-mode open, gated by `integrity.embedding_abi`. Add the field to `IndexCheckReport`, its JSON projection, its human renderer, and a recommendation branch. Do not route into `openReadOrSelfHeal` - that path rebuilds keyword-only and would not touch the vectors.
+- **Acceptance**: a store whose recorded dimension differs from the configured one produces a named error on a read-mode open under `fail` and a named warning under `warn`; a legacy store with no recorded `vec_version` warns once rather than erroring; `o2b search check` reports the mismatch with a copy-pasteable fix; a matching store produces byte-identical output.
+- **Depends on**: Task 4
+
+### Task 11: Fail-closed session continuation
+- **Files**: `src/core/brain/lineage/crutch.ts`, `resolve.ts`, `types.ts`, `ledger.ts`, `src/core/brain/session-lifecycle.ts`, `src/core/brain/git/reader.ts`, `src/core/redactor.ts`, plus tests
+- **What**: the crutch resolver returns a discriminated outcome (`linked` or an abstention naming `no-candidate`, `self-known`, `no-workspace`, `ambiguous`, `stale`, or `evidence-missing`) instead of a bare `null`. Two surviving candidates abstain. Repo, branch, and commit are captured onto the lineage observation through the existing hardened `runGit` argv pattern, with a bounded timeout, and become required-match predicates. A pure canonicalizer normalizes a git remote to `scheme://host/org/repo` with userinfo, port, `.git`, and trailing slash removed - a comparable identity, distinct from the redactor's placeholder rewrite.
+- **Acceptance**: two concurrent sessions in one directory inside the window both abstain with `ambiguous` where today one is stitched; a session in a different branch or commit does not link; the abstention reason reaches the caller; a remote carrying credentials canonicalizes to the same identity as the same remote cloned without them, and the credential never appears in any recorded field; the git probe cannot exceed its timeout budget; all lineage capture stays fail-soft and never throws into the hook.
+- **Depends on**: Task 1
+
+### Task 12: Lineage ledger integrity
+- **Files**: `src/core/brain/lineage/ledger.ts`, `src/core/brain/lineage/verify.ts` (new), `src/core/brain/doctor.ts`, plus tests
+- **What**: sequence numbers and a hash chain over the canonical line, a synchronous writer lock around the read-modify-write following the continuity-store precedent, lossless compaction that retains recent lines verbatim instead of folding one summary line per session, and a verification function whose findings reach the doctor. The read path stays fail-soft and the verification never refuses to start. A dropped observation caused by lock contention is recorded as a named gap rather than vanishing.
+- **Acceptance**: compaction preserves `firstSeenMs`, per-session event history, and any field the writer emits; a tampered line is reported by verification with its sequence number and does not prevent resolution; two concurrent writers crossing the cap both land their observations or the loser is recorded as a named gap; `readLineageLedger` still returns an empty map rather than throwing on a corrupt file.
+- **Depends on**: Task 1, Task 11
+
+### Task 13: Broken-link ratchet
+- **Files**: `src/core/search/link-ratchet.ts` (new), `src/core/search/store.ts`, `scripts/link-ratchet.ts` (new), `link-ratchet.json` (new), `package.json`, `.github/workflows/ci.yml`, `.github/workflows/release.yml`, `src/mcp/brain/hygiene-tools.ts`, plus tests
+- **What**: a deterministic vault-wide broken-link count, taken only after a full resolution pass. ~~Using the SQL definition (`target_document_id IS NULL AND target_path IS NOT NULL`).~~ Corrected after measurement: the count is the link rows the read-time resolution ladder leaves unresolved, sharing that ladder's SQL with `resolvedDocLinkPairs` rather than reimplementing it. A committed ceiling file at the repository root carrying `schema_version`, the count, and the definition token. The script mirrors `scripts/sync-version.ts` exactly: one code path, `--check` disabling writes, exit 1 on a rise, a named fix command on failure, and `link-ratchet` / `link-ratchet:check` npm scripts wired into both workflows. `brain_hygiene` gains an additive top-level key.
+- **Acceptance**: two runs over an unchanged vault produce the same count; a new broken link fails `--check` with exit 1 and names the fix; fixing links and rerunning the write form lowers the ceiling; the detection code path is provably identical between the write and check forms; `brain_hygiene`'s existing keys are unchanged and its detector enum is untouched.
+- **Depends on**: none
+
+### Task 14: Injection meter, session receipt fold, and vault identity guard
+- **Files**: `hooks/active-inject.ts`, `src/core/brain/context-receipts.ts`, `src/core/brain/observed-use.ts`, `src/mcp/brain/pack-tools.ts`, `src/core/brain/vault-identity.ts` (new), `src/core/brain/paths.ts`, `src/core/brain/init.ts`, `src/core/brain/doctor.ts`, `src/core/brain/portability/profiles.ts`, `src/mcp/brain/entity-tools.ts`, plus tests
+- **What**: three small units sharing no code but each too small to carry a commit alone if split further - keep them as three separate commits.
+ - **H**: measure bytes and tokens per source (notices, active body, lessons body) where the sub-bodies are still separate strings, take the measurement after the fail-open loader returns so it reflects what is emitted, record the loader source and the hook event name, and emit through the receipt surface with a widened trigger. The whole meter sits inside its own try/catch and cannot extend the hook's process ceiling.
+ - **I**: a session-scoped fold over existing `context_receipt` records - receipt count, total items, distinct items, per-item injection frequency and token cost - plus a session filter on the observed-reuse fold, exposed as a `summary` operation on `brain_context_receipts`. Bound the scan the way the token-impact summary already does. A vault with no receipts reports "no receipts recorded", never zeros presented as a finding.
+ - **J**: a vault identity marker written by the bootstrap path, an assertion on the write path hanging off the function every Brain writer funnels through, an `isDirectory` check in profile switching, and removal of the doctor early return that reports a `Brain`-less root as clean.
+- **Acceptance**: **H** - the meter records one record per injection with per-source attribution, a hook failure in the meter never changes the hook's exit code or its emitted context, and PostCompact records are distinguishable from SessionStart ones. **I** - the fold matches a hand-computed expectation over a seeded set of receipts, redacted payloads are not resurrected, and the MCP tool count stays 108. **J** - a marker mismatch refuses the write with a named error, an absent marker warns rather than refusing, `o2b brain init` still bootstraps a fresh vault without tripping the guard, switching to a profile pointing at a non-existent directory fails at switch time rather than in a later process, and the doctor reports a `Brain`-less root as a named condition instead of `clean`.
+- **Depends on**: Task 1, Task 4
diff --git a/docs/brainstorm/context-integrity-gates/variants.md b/docs/brainstorm/context-integrity-gates/variants.md
new file mode 100644
index 00000000..37be9c89
--- /dev/null
+++ b/docs/brainstorm/context-integrity-gates/variants.md
@@ -0,0 +1,84 @@
+# Context integrity gates - variant audit trail
+
+Consultant: Claude Code (`claude -p`), primary. Exit 0, three parseable variants and one recommendation returned on the first invocation, so the Codex fallback was not run. The prompt is at `cli-output/prompt.md`; the raw response is at `cli-output/claude.md` and is reproduced verbatim below.
+
+Reconnaissance preceding the consultation was carried out by three parallel read-only agents against the live codebase. It corrected three premises carried in the tracker, and those corrections are reflected in the prompt rather than the tracker:
+
+1. A note with malformed frontmatter is not dropped from the index. `parseFrontmatterText` is a line-based `key: value` scanner that cannot throw; it silently discards the lines it does not understand, so individual fields vanish while the note still indexes.
+2. The "frontmatter is not valid YAML" branch in `claude-memory-parser.ts` is unreachable dead code - the function it guards contains no `throw`.
+3. No vault-wide broken or dangling link count exists anywhere in the codebase. The tracker's anchors pointed at graph-degree filter machinery, so the ratchet needs a counter as well as a ceiling.
+
+---
+
+## Consultant response, verbatim
+
+### Variant 1: Two seams, ten adapters
+
+- **Approach**: Build exactly two horizontal shared modules and reduce each of the ten units to a thin adapter onto one or both. Seam 1 is a **typed degradation channel** β€” a non-throwing, named outcome record (`{code, site, path, detail}`) with three carriers already present in the repo: `IndexStats` (new `scanned`/`skipped` fields), `DoctorUncertainEntry`/`CheckResult` for diagnostics, and the conditional-spread MCP field for serving time. Seam 2 is a **stamp-and-verify provenance record**, generalized from the existing `computeSourceStamp` idiom (`freshness.ts:89`) with its `missing`/`unreadable` sentinels, carrying `{corpusGeneration, brainStamp, embeddingAbi, vaultIdentity}` written at build time and compared on read. A third, smaller piece falls out of both: one shared preference collector replacing the ten `readdirSync(dirs.preferences)` loops, which is the single place owner filtering and read diagnostics attach.
+ - Seam 1 carries **F** (all ~15 bare `catch { continue }` sites and the `vault.ts:113` line-drop, following the `dream.ts:974` precedent), **C** (the four null causes become a `LineageOutcome` discriminated union), **D** (compaction records what it discarded instead of dropping `firstSeenMs` silently), **G** (the dangling-link count is a degradation aggregate over `target_document_id IS NULL AND target_path IS NOT NULL`, with the read-time-resolvable ladder recorded as a second, separately-named code), and **A**'s legibility half (an owner-hidden count so a thin pack is distinguishable from an empty vault).
+ - Seam 2 carries **B** (pack stamp plus validity window; `corpusGeneration` alone is a lagging proxy because `packContext` walks the filesystem, so the pack stamp pairs it with a Brain-tree mtime/size stamp rather than a full sha256 manifest), **E** (a `vec_version` + model + dimension ABI token compared on read-mode open, surfaced as a reindex-required warning exactly like `EMBEDDING_PREFIX_QUERY_STATE_KEY`, never routed into `openReadOrSelfHeal` since that path rebuilds keyword-only), **J** (a vault-identity marker file, with `resolveVault` refusing rather than materializing an unmarked root), **H** and **I** (both are the stamp plus a token count riding `emitContextReceipt`, whose trigger enum widens to include a hook-layer value).
+ - Fail boundary follows the line the repo already declares: serving gates fail closed (E's read-mode ABI check, J's write guard, A's filter), capture and injection stay fail-soft but now name what they dropped. **A**'s enforcement half rides an explicit flag so a null scope stays byte-identical; **C** ships abstain-on-ambiguity plus git repo/branch/commit **capture only** (recorded on the lineage event, not yet used for matching); **D** ships sequence numbers, non-lossy compaction, and a `withFileLock` around the read-modify-write, but verification reports rather than refuses to start.
+- **Trade-offs**:
+ - Matches the house release shape exactly: a multi-unit wave with one or two shared seams named in the changelog as carrying it (1.37.0, 1.36.0).
+ - Satisfies the DRY constraint at its sharpest point β€” the ten-loop duplication and the fifteen swallowing catch sites are removed once, not patched per site.
+ - Each unit stays independently testable and independently revertable, so unit-by-unit TDD on one branch works without a big-bang integration step.
+ - The degradation channel risks becoming a dumping ground: without a closed enum reviewed per unit, "named" degrades back into "generic warning".
+ - Seam-first work delays the first visibly shipped unit; the two seams must be designed against all ten consumers before any adapter lands.
+ - Large test surface: every one of the ten units needs a byte-identical-when-absent test in addition to its behavior test.
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 2: One delivery envelope
+
+- **Approach**: Collapse the read path into a single mandatory chokepoint. Every content-returning surface β€” the nine that bypass `isOwnerVisible` plus `search()` β€” builds its payload, then hands it to one `deliverContext(request, payload)` pass that resolves caller identity from a new `agent` field on `ServerContext` (via `resolveAgentName`), applies the isolation rule, attaches the provenance stamp and validity window, meters the emitted token count, and optionally emits a receipt. **A**, **B**, **H**, and **I** stop being four units and become four responsibilities of one function; **E**, **F**, **G**, and **J** become preconditions asserted at the envelope's entry (store ABI verified before any semantic hit is admitted, parse diagnostics riding the payload, vault identity checked at open); **C** and **D** shrink to the single job of producing a trustworthy session key the anticipatory cache path is derived from. **G**'s CI ratchet and **D**'s compaction rewrite are deliberately deferred to 1.40.0 as the two pieces that do not touch the envelope.
+- **Trade-offs**:
+ - The fail-closed boundary becomes a single line anyone can point at: inside the envelope closed, outside it soft. No per-unit judgment calls, no policy sprawl.
+ - Structurally forecloses the whole defect class rather than the ten instances β€” a future eleventh delivery surface cannot bypass isolation, because bypassing the envelope means returning nothing.
+ - Fixes `brain_search_expand`'s `chunk_id` enumeration surface as a consequence rather than a special case, since `expandHit` results must also transit the envelope.
+ - Highest threat to the byte-identical contract: nine surfaces change shape in one PR, and `brain_context` takes no arguments at all, so identity must be injected rather than passed.
+ - Fights the stated implementation model β€” unit-by-unit TDD is hard when eight of ten units are facets of one function that is only correct once all eight land.
+ - Blast radius is total: an envelope bug is a simultaneous outage of every context-delivery surface across a 108-tool MCP server.
+ - Deferring **D** and **G** leaves the ledger's clobbering read-modify-write and the absent link counter shipping nothing in this wave.
+- **Complexity**: large
+- **Risk**: high
+
+### Variant 3: Evidence plane now, enforcement by policy
+
+- **Approach**: Split the wave along the axis of *does it refuse*. Plane one is evidence and ships complete for all ten units: every defect gets a detector that names it β€” F's parse diagnostics, G's dangling-link counter, H's injection meter, I's session receipt fold, B's stamp recorded, C's outcome union, D's sequence numbers, E's ABI token stamped and surfaced, A's owner-hidden count, J's identity marker written β€” all additive, all fail-soft, all byte-identical when unread. Plane two is a single new `gates:` config block with per-gate `off | warn | fail` modes (invalid value raises `BrainConfigError` at load, per the config contract), where only three gates gain a working `fail` mode in 1.39.0: **E** on read-mode dimension mismatch, **J** on vault-identity mismatch at write, **A** on delivery-surface owner scope. **G** additionally ships the committed baseline plus a `--check` npm script wired into `ci.yml` and `release.yml`, copying `scripts/sync-version.ts` exactly and establishing that convention. **C**'s git repo/branch/commit identity and **D**'s hash chain are explicitly deferred to 1.40.0 and named as deferred in the changelog; **C** ships only the abstain-on-ambiguity tie-break, **D** only non-lossy compaction plus a writer lock.
+- **Trade-offs**:
+ - Lowest-risk path to the wave's thesis: a silent failure becomes a named one on day one even where nobody is ready to refuse on it yet.
+ - The `gates:` block gives the operator, not the release, authority over the fail-closed line β€” which is the honest position for **E**, where `vec_version()` instability across Syncthing peers could otherwise produce a rebuild loop.
+ - Detection-first ordering means the counters and diagnostics exist before any gate is tuned against them, so **G**'s ceiling is derived from a measured baseline rather than guessed.
+ - Half-realizes the thesis in default installs: warn-by-default means the agent still cannot tell a genuine miss from a broken mechanism unless the operator opts in.
+ - A policy plane is itself an untested seam, and gate-mode combinatorics multiply the test matrix faster than the per-unit tests it replaces.
+ - Deferring two of ten units under-delivers against a wave framed as ten units, and **D**'s deferred hash chain leaves the ledger's silent-loss-at-compaction contract only partly closed.
+- **Complexity**: medium
+- **Risk**: low
+
+### Recommended: Variant 1
+
+**Rationale**: It is the only variant that ships all ten units while matching the house release shape β€” a multi-unit wave carried by one or two shared seams named in the changelog β€” and its two seams land precisely on the wave's actual duplication (the ten preference loops, the fifteen swallowing catches), which is what the DRY constraint demands and what Variant 3's per-unit detectors would leave in place. Variant 2's chokepoint is the structurally cleanest end state but puts nine delivery surfaces and the byte-identical contract at risk in a single pull request, and it contradicts the stated unit-by-unit TDD model. Variant 1 should absorb Variant 3's one genuinely better idea: give **E** and **A** graded modes rather than a binary gate, since `vec_version()` instability across peers and the "null scope is byte-identical" contract are both cases where the operator, not the release, should choose when refusal begins.
+
+---
+
+## Orchestrator decision
+
+**Accepted: Variant 1, with the consultant's own recommended graft from Variant 3.**
+
+The recommendation is adopted rather than overridden. Variant 1 is the only option that ships all ten units, and its two seams land on this wave's real duplication - the ten independent preference-directory walks and the fifteen bare `catch { continue }` sites - which is exactly what the DRY constraint targets and what Variant 3's per-unit detectors would have left in place. Variant 2's single delivery envelope is the cleanest end state on paper, but it puts nine delivery surfaces and the byte-identical contract into one pull request and makes eight of the ten units correct only once all eight land, which contradicts the unit-by-unit test-driven model this wave is committed to.
+
+The graft is applied as the consultant proposed: graded `off | warn | fail` modes for the two units where the environment rather than the release should decide when refusal begins. Unit E because `vec_version()` is not stable across environments and a hard gate could produce a rebuild loop across a synced vault; unit A because every module in that path documents a "null scope is byte-identical" contract, so enabling enforcement by default would silently narrow existing vaults.
+
+Four decisions go beyond what the consultant proposed, each forced by a reconnaissance finding the consultant was given but did not resolve:
+
+- **The pack stamp is not `corpusGeneration()` alone.** `packContext` walks the filesystem and never reads the search index, so the index generation is a lagging proxy: a hand-edited note changes the pack without bumping `index_revision`. The stamp pairs it with a cheap Brain-tree digest over path, mtime, and size for the directories the pack actually walks. `buildManifest` was rejected for this role because it sha256-hashes every file on every call.
+- **Unit E reports and never routes into the existing self-heal.** `openReadOrSelfHeal` calls `reindexVault(config)` with no options, so the rebuild is keyword-only and would leave the stale vectors in place. Routing a vector mismatch there would have produced a heal that does not heal - the exact anti-pattern this wave exists to remove.
+- **The credential normalizer is a canonicalizer, not a redactor.** The existing `BASIC_AUTH_URL_RE` rewrites credentials to a placeholder, which is correct for logs and useless as an identity key: two clones carrying different tokens would compare equal to each other and unequal to a credential-free clone of the same repository. Unit C needs a comparable identity, so userinfo, port, `.git` suffix, and trailing slash are normalized away instead.
+- **The degradation vocabulary is a closed union.** The consultant identified the risk that a typed channel becomes a dumping ground and named no mitigation. A closed code union makes adding a code a deliberate edit and an unhandled code a type error at the consumer.
+
+Two units are trimmed against their tracker descriptions, both on reconnaissance evidence rather than on effort grounds:
+
+- **The retrieval receipt** is reduced to a read-only fold plus one new operation on an existing tool. Every primitive it needs - per-item identity, tokens, tier, evidence refs, text hashes, and a per-artifact reliance score - already exists and is durable; only the session-scoped join is missing. Building a new record kind would have duplicated three existing ones.
+- **The injection meter** lands the measurement only. Source-aware injection, spawn merge, hint dedupe, and listing collapse are optimizations that cannot be attributed without a measurement that does not exist yet, and the tracker note itself says to land the meter first.
+
+One unit named in the same tracker cluster is deliberately excluded from this wave: durable cross-session work identity with explicit execution lanes. Replacing the fifteen-minute timing crutch is architectural and needs its own design record. Unit C makes the crutch's failures visible and abstains where it cannot tell, which is the prerequisite for that replacement rather than a substitute for it.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 98fab07c..5fbaf7a5 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -398,6 +398,58 @@ additive `suppressed` object with per-detector counts; nothing is ever
hidden silently. An invalid config value is an explicit error at load,
and with no watermark set every output is byte-identical to v1.37.0.
+### Context integrity gates (since v1.39.0)
+
+```text
+o2b search query --agent-scope <name> restrict results to pages that are ownerless or owned by <name>
+o2b search expand --agent-scope <name> same rule on the chunk drill-down; a withheld chunk is indistinguishable from an absent one
+o2b brain sgrep --agent-scope <name> same rule on the structured grep surface
+bun run link-ratchet measure the vault-wide broken-link count and record it as the new ceiling
+bun run link-ratchet:check fail with exit 1 when the count has risen above the committed ceiling
+```
+
+Three gates live in an optional `integrity:` block in `_brain.yaml`:
+`owner_scope_delivery` (default `off`), `embedding_abi` (default
+`warn`), and `pack_validity_seconds` (default 900). The two gate keys
+take `off`, `warn`, or `fail`; an unrecognised mode or a non-positive
+validity is an explicit config error at load, never a clamped default.
+
+`owner_scope_delivery` governs the preference-backed delivery surfaces -
+the context pack, the pre-compress pack, the morning brief, the digest,
+and `active.md`. The search-backed surfaces above filter whenever a
+scope is passed and are not gated. Ownership fails closed: a page whose
+frontmatter cannot be read, and a page whose `owner:` is present but not
+a plain string, are withheld from a scoped caller rather than treated as
+shared. Retiring a memory keeps its owner.
+
+`embedding_abi` compares the recorded embedding model, dimension, and
+sqlite-vec version against the running ones on every read-mode open.
+`o2b search check` reports a drift with a copy-pasteable fix regardless
+of the gate, because it is a diagnostic the operator ran deliberately
+and refuses nothing; `o2b search status` reports it under `warn`; under
+`fail` the read-mode open raises a named error. A store predating the
+stamp is reported, never refused, and nothing is rebuilt automatically -
+the self-heal path rebuilds keyword data only and would leave stale
+vectors in place.
+
+The broken-link ratchet counts link rows the read-time resolution ladder
+cannot resolve and compares them against `link-ratchet.json` at the
+repository root. `--check` is the same code path with writing disabled,
+so detection is identical between the two forms; it exits 1 on a rise
+and names the write form as the fix. A subject that measures nothing -
+empty, missing, or fully excluded - is an explicit unmeasurable state,
+not a ceiling of zero, and the count is refused unless the index's last
+run was a forced full pass.
+
+`o2b brain doctor` gains an `uncertain` stream for conditions it
+attempted but cannot claim completed cleanly: frontmatter lines the
+parser dropped, lineage-ledger findings, stale lock files, and a missing
+vault identity marker. These render as `[UNSURE]` lines and appear in
+`--json` under `uncertain`; they do not affect the exit code. A vault
+with no `Brain/` layer is now reported as a named `brain-root-absent`
+warning instead of `clean`, which means `o2b brain doctor --strict`
+exits 2 on an un-initialized vault where it previously exited 0.
+
## Stability and trust (since v1.0.0)
```text
diff --git a/docs/mcp.md b/docs/mcp.md
index d9baed4b..952a14ba 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -571,3 +571,39 @@ Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default
baseline date; the verdict is computed from the surfaced findings, the
key is absent whenever nothing is hidden, and with no watermark set
the output is byte-identical to v1.37.0.
+- Since v1.39.0 eleven content-returning tools accept an optional
+ `agent_scope` argument (`brain_context_pack`, `brain_pre_compress_pack`,
+ `brain_anticipatory_context`, `brain_brief`, `brain_retrieval_plan`,
+ `brain_file_context`, `brain_search_expand`, `brain_deep_synthesis`,
+ `brain_search_by_source`, `brain_agent_query`, `second_brain_query`),
+ joining `brain_search` and `brain_query` which already had one. A page
+ that is ownerless matches every scope; an owner-tagged page matches
+ only its owner; a page whose ownership cannot be read is withheld. The
+ preference-backed surfaces additionally require
+ `integrity.owner_scope_delivery` to be `warn` or `fail`; the
+ search-backed ones filter whenever a scope is passed. Five `brain_brief`
+ views that cannot honour a scope (`daily`, `weekly`, `monthly`,
+ `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.39.0 `brain_context_receipts` accepts a third `summary`
+ operation, plus `since`, `until`, and `max_receipts`. The summary folds
+ existing receipt records for one session into counts, distinct items,
+ and per-item injection frequency and token cost. Receipt emission is
+ opt-in, so a window with no receipts returns `recorded: false` carrying
+ no counters at all - a consumer must branch before it can read a
+ number, so "nobody enabled receipts" can never be read as "retrieval
+ injected nothing". An uncomparable `since`/`until` value is rejected
+ with `INVALID_PARAMS` rather than filtered into an empty result.
+- Since v1.39.0 `brain_doctor` additively carries an `uncertain` array
+ for conditions the doctor attempted but cannot claim completed
+ cleanly - dropped frontmatter lines, lineage-ledger findings, stale
+ lock files, and a missing vault identity marker. The key is absent
+ when there is nothing to report. `brain_hygiene` likewise gains an
+ additive top-level `link_integrity` key, which reports
+ `measured: false` with a reason rather than a misleading zero when the
+ index's last run was not a forced full pass.
+- Since v1.39.0 `brain_anticipatory_context` reports a `cache_refusal`
+ reason when a cached pack is refused because the vault state it was
+ built from has moved or its validity window has expired, instead of
+ silently serving or silently rebuilding.
diff --git a/hooks/active-inject.ts b/hooks/active-inject.ts
index 9db80c6d..a6a9c9a1 100644
--- a/hooks/active-inject.ts
+++ b/hooks/active-inject.ts
@@ -43,6 +43,9 @@ import { loadInjectContextFailOpen } from "../src/core/brain/inject-failopen.ts"
import { collectRuntimeNotices, renderRuntimeNotices } from "../src/core/brain/runtime-notices.ts";
import { asHookPayload, readHookInput } from "./lib/stdin.ts";
import { isContextEventName } from "./lib/context-events.ts";
+import { emitContextReceipt } from "../src/core/brain/context-receipts.ts";
+import { estimateTokens } from "../src/core/brain/text/tokenizer.ts";
+import type { InjectContextSource } from "../src/core/brain/inject-failopen.ts";
/**
* Best-effort hook audit line. Never throws: a failure to record must never
@@ -132,12 +135,16 @@ async function main(): Promise<void> {
// degrades to the last-good cache (or empty) on any error, never emitting
// a partial or poisoned payload. A successful non-empty body refreshes the
// last-good snapshot.
- const { context } = await loadInjectContextFailOpen({
+ const meter: InjectionMeter = { sources: [], budgetChars: null };
+ const { context, source } = await loadInjectContextFailOpen({
vault,
key: "active",
- assemble: () => assembleActiveContext(vault),
- audit: (source) =>
- auditHook(vault, "inject_failopen_degraded", { hook: "active-inject", source }),
+ assemble: () => assembleActiveContext(vault, meter),
+ audit: (degradedSource) =>
+ auditHook(vault, "inject_failopen_degraded", {
+ hook: "active-inject",
+ source: degradedSource,
+ }),
});
if (context.length === 0) return;
@@ -148,26 +155,147 @@ async function main(): Promise<void> {
},
};
process.stdout.write(JSON.stringify(out) + "\n");
+
+ // Measure LAST, so the injected context is already on stdout before the
+ // meter can spend a millisecond of the ceiling. See recordInjectionSize.
+ recordInjectionSize(vault, { hookEventName, loaderSource: source, context, meter });
} finally {
disarm();
}
}
+// ----- injection-size meter (context-integrity-gates, Unit H) --------------
+
+/**
+ * One injected sub-body, captured while it is still a separate string.
+ *
+ * `assembleActiveContext` joins its parts and returns one string, so this
+ * is the only point at which per-source attribution exists at all. The
+ * name is a stable structural identifier, never derived from content.
+ */
+interface InjectionSource {
+ readonly name: string;
+ readonly text: string;
+}
+
+/** Mutable accumulator threaded through the assembly, read after it returns. */
+interface InjectionMeter {
+ readonly sources: InjectionSource[];
+ /** The `inject_budget_chars` the budgeted sub-bodies were charged against. */
+ budgetChars: number | null;
+}
+
+/** Sub-body identifiers recorded per injection. Structural, not content-derived. */
+const SOURCE_RUNTIME_NOTICES = "runtime-notices";
+const SOURCE_ACTIVE_BODY = "active-body";
+const SOURCE_LESSONS_BODY = "lessons-body";
+
+const UTF8 = new TextEncoder();
+
+function byteLength(text: string): number {
+ return UTF8.encode(text).length;
+}
+
+interface RecordInjectionSizeInput {
+ readonly hookEventName: string;
+ readonly loaderSource: InjectContextSource;
+ readonly context: string;
+ readonly meter: InjectionMeter;
+}
+
+/**
+ * Record what this hook actually injected: total bytes and tokens, plus
+ * per-source attribution when the assembly is what got emitted.
+ *
+ * SCOPE. This measures THIS hook only. `gap-agenda`, `recall-inject`, and
+ * `nav-inject` are separate processes with their own `additionalContext`,
+ * so the session preamble as a whole is larger than any figure recorded
+ * here and cannot be assembled from inside this process.
+ *
+ * ATTRIBUTION. The measurement is taken after the fail-open loader
+ * returns, so it describes the emitted bytes rather than the attempted
+ * ones. When the loader degraded to its last-good cache the sub-bodies in
+ * `meter` were never emitted (assembly threw), so the record says
+ * `sources_measured: false` and carries no items - a per-source breakdown
+ * of zeros would be a finding that never happened.
+ *
+ * FAIL-SOFT. The whole body sits in one try/catch. The receipt sink takes
+ * a continuity-store lock and writes to disk; contention, a read-only
+ * vault, or a directory that is really a file must not become a new
+ * failure surface on the SessionStart path. Nothing here can change the
+ * hook's exit code, and the injected context is already on stdout by the
+ * time this runs.
+ */
+function recordInjectionSize(vault: string, input: RecordInjectionSizeInput): void {
+ try {
+ const measured = input.loaderSource === "fresh";
+ const totalBytes = byteLength(input.context);
+ emitContextReceipt(vault, {
+ options: { host: "hook", trigger: "session_inject" },
+ items: measured
+ ? input.meter.sources.map((source) => ({
+ id: source.name,
+ bytes: byteLength(source.text),
+ tokens: estimateTokens(source.text),
+ }))
+ : [],
+ finalText: input.context,
+ ...(input.meter.budgetChars !== null && measured
+ ? {
+ budget: {
+ inject_budget_chars: input.meter.budgetChars,
+ // Both budgeted sub-bodies are charged against the SAME
+ // configured ceiling, so the effective ceiling is this
+ // count times `inject_budget_chars`. Recorded as two
+ // numbers rather than implied by one.
+ budgeted_source_count: budgetedSourceCount(input.meter),
+ },
+ }
+ : {}),
+ extra: {
+ injection: {
+ hook_event: input.hookEventName,
+ loader_source: input.loaderSource,
+ sources_measured: measured,
+ total_bytes: totalBytes,
+ total_tokens: estimateTokens(input.context),
+ },
+ },
+ });
+ } catch {
+ // The meter is diagnostics. A failure to record must never disturb an
+ // injection that already succeeded.
+ }
+}
+
+/** How many recorded sources were charged against `inject_budget_chars`. */
+function budgetedSourceCount(meter: InjectionMeter): number {
+ return meter.sources.filter(
+ (source) => source.name === SOURCE_ACTIVE_BODY || source.name === SOURCE_LESSONS_BODY,
+ ).length;
+}
+
/**
* Assemble the injected context body. Returns an empty string when there is
* legitimately nothing to inject (no active.md, empty body); throws on a
* genuine read error so the fail-open loader degrades to the last-good cache.
+ *
+ * Every non-empty sub-body is recorded into `meter` as it is produced -
+ * the join below is where per-source attribution stops existing.
*/
-function assembleActiveContext(vault: string): string {
+function assembleActiveContext(vault: string, meter: InjectionMeter): string {
// Runtime-state notices ride the same injection surface as active.md so the
// agent is proactively aware of a degraded/transient condition (semantic
// search fell back to lexical, index missing/rebuilding, read-only vault)
// without a diagnostic round-trip. Best-effort and computed with no network;
// an empty list keeps the injected body byte-identical to before.
const noticesBlock = renderRuntimeNotices(collectRuntimeNotices(vault));
+ if (noticesBlock.length > 0) {
+ meter.sources.push({ name: SOURCE_RUNTIME_NOTICES, text: noticesBlock });
+ }
const activePath = brainActivePath(vault);
- const activeBody = existsSync(activePath) ? readActiveBody(vault, activePath) : "";
+ const activeBody = existsSync(activePath) ? readActiveBody(vault, activePath, meter) : "";
const parts = [noticesBlock, activeBody].filter((p) => p.length > 0);
return parts.join("\n\n");
@@ -178,7 +306,7 @@ function assembleActiveContext(vault: string): string {
* the body is empty; throws on a genuine read error (permissions, fs stall) so
* the fail-open loader degrades to the last-good cache.
*/
-function readActiveBody(vault: string, activePath: string): string {
+function readActiveBody(vault: string, activePath: string, meter: InjectionMeter): string {
const body = readFileSync(activePath, "utf8");
// Drop the `kind: brain-active / generated_at` frontmatter - it
@@ -199,6 +327,7 @@ function readActiveBody(vault: string, activePath: string): string {
} catch {
// intentional fallback - a corrupted _brain.yaml is doctor's job
}
+ meter.budgetChars = budget;
// Auto-load the lessons digest alongside active.md so the agent gets
// the unified, signed, recency-scored corpus (preferences + dead-ends)
@@ -207,9 +336,13 @@ function readActiveBody(vault: string, activePath: string): string {
// the active-preferences injection above.
const lessonsBody = readLessonsBody(brainLessonsPath(vault), budget);
- return lessonsBody === null
- ? budgetActiveBody(trimmed, budget)
- : `${budgetActiveBody(trimmed, budget)}\n\n${lessonsBody}`;
+ const budgetedActive = budgetActiveBody(trimmed, budget);
+ meter.sources.push({ name: SOURCE_ACTIVE_BODY, text: budgetedActive });
+ if (lessonsBody !== null) {
+ meter.sources.push({ name: SOURCE_LESSONS_BODY, text: lessonsBody });
+ }
+
+ return lessonsBody === null ? budgetedActive : `${budgetedActive}\n\n${lessonsBody}`;
}
/**
diff --git a/link-ratchet.json b/link-ratchet.json
new file mode 100644
index 00000000..5228196e
--- /dev/null
+++ b/link-ratchet.json
@@ -0,0 +1,10 @@
+{
+ "schema_version": 1,
+ "definition": "ladder:links-unresolved-after-read-resolution@2",
+ "subjects": [
+ {
+ "path": "templates/brain-starter",
+ "dangling": 22
+ }
+ ]
+}
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 4ee9ca90..28979c52 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.38.0",
+ "version": "1.39.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 71231c8b..e44bbcbd 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.38.0",
+ "version": "1.39.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
@@ -46,6 +46,8 @@
"validate:fix": "bun run lint:fix && bun run fmt",
"sync-version": "bun run scripts/sync-version.ts",
"sync-version:check": "bun run scripts/sync-version.ts --check",
+ "link-ratchet": "bun run scripts/link-ratchet.ts",
+ "link-ratchet:check": "bun run scripts/link-ratchet.ts --check",
"check:paths": "bun run scripts/check-hardcoded-paths.ts",
"check:paths:strict": "bun run scripts/check-hardcoded-paths.ts --strict",
"hooks:install": "git config core.hooksPath .githooks && echo 'git hooks enabled (core.hooksPath=.githooks)'",
diff --git a/plugin.yaml b/plugin.yaml
index 253db47b..898c21c5 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.38.0"
+version: "1.39.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index e38cea87..46b6a2c5 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.38.0",
+ "version": "1.39.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.yaml
index 253db47b..898c21c5 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.38.0"
+version: "1.39.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index 91fcf403..ccf59457 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.38.0"
+version = "1.39.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/link-ratchet.ts b/scripts/link-ratchet.ts
new file mode 100644
index 00000000..339c7809
--- /dev/null
+++ b/scripts/link-ratchet.ts
@@ -0,0 +1,191 @@
+#!/usr/bin/env bun
+/**
+ * Vault-wide broken-link ratchet gate (context-integrity-gates, unit G).
+ *
+ * Measures every vault root named in `link-ratchet.json` and compares
+ * the broken-link count against the committed ceiling.
+ *
+ * A link is broken when the READ-TIME resolution ladder cannot resolve
+ * it - the same ladder the readers follow, shared from `store.ts`. The
+ * narrower `target_document_id IS NULL` predicate this gate first
+ * shipped with counted every basename wikilink as broken (55 of 55 rows
+ * on `templates/brain-starter`), so it rose on healthy edits; the
+ * definition token in the ceiling file records which rule produced a
+ * number, and a ceiling written under the old one is refused rather
+ * than compared. The write form
+ * records what it measured; the `--check` form is the SAME code path
+ * with writing disabled, so what CI detects and what the write form
+ * records can never diverge - the shape `scripts/sync-version.ts`
+ * establishes, and the reason both forms are gated in both workflows.
+ *
+ * Exit codes:
+ * 0 every subject is at or below its ceiling
+ * 1 a subject rose above its ceiling (`--check` only), a subject
+ * could not be measured (BOTH forms - a gate that passes without a
+ * count is the failure this exists to remove), or the ceiling file
+ * cannot be compared (foreign schema version or definition token).
+ *
+ * The ceiling is a MEASUREMENT, not a target: it encodes whatever link
+ * rot existed when it was last written. Raising it is a deliberate,
+ * reviewable line in a diff - which is why the write form records a
+ * rise instead of refusing it, and why only `--check` fails on one.
+ *
+ * Usage:
+ * bun run link-ratchet # measure and record
+ * bun run link-ratchet:check # exit 1 on a rise, no writes
+ */
+
+import { readFileSync, writeFileSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import {
+ DANGLING_LINK_DEFINITION,
+ LINK_RATCHET_FIX_COMMAND,
+ judgeSubject,
+ measureVault,
+ parseCeiling,
+ serializeCeiling,
+ type LinkRatchetCeiling,
+ type LinkRatchetVerdict,
+} from "../src/core/search/link-ratchet.ts";
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
+
+/** Repository-relative location of the committed ceiling. */
+export const CEILING_FILE = "link-ratchet.json";
+
+const LABEL_WIDTH = 14;
+
+export interface LinkRatchetRunOptions {
+ /** Directory holding `link-ratchet.json`; subjects resolve against it. */
+ readonly root: string;
+ /** When true, nothing is written. Detection is unaffected. */
+ readonly check: boolean;
+ readonly stdout: (text: string) => void;
+ readonly stderr: (text: string) => void;
+}
+
+export interface LinkRatchetRun {
+ readonly exitCode: number;
+ readonly verdicts: ReadonlyArray<LinkRatchetVerdict>;
+}
+
+function label(text: string): string {
+ return ` ${`${text}:`.padEnd(LABEL_WIDTH)}`;
+}
+
+function describe(verdict: LinkRatchetVerdict): string {
+ const m = verdict.measurement;
+ if (!m.measurable) {
+ return `${label("UNMEASURABLE")}${verdict.subject} (${m.reason}: ${m.detail})`;
+ }
+ const status = verdict.status === "level" ? "ok" : verdict.status.toUpperCase();
+ return (
+ `${label(status)}${verdict.subject} ` +
+ `(dangling ${m.dangling} of ${m.links} link row(s), ceiling ${verdict.ceiling})`
+ );
+}
+
+/**
+ * Write the recorded ceiling when `write` is true. The single write
+ * guard in this file: with `write` false the comparison above it has
+ * already run, unchanged.
+ */
+function updateCeilingFile(path: string, next: LinkRatchetCeiling, write: boolean): boolean {
+ const text = readFileSync(path, "utf8");
+ const updated = serializeCeiling(next);
+ if (updated === text) return false;
+ if (write) writeFileSync(path, updated, "utf8");
+ return true;
+}
+
+export async function runLinkRatchet(opts: LinkRatchetRunOptions): Promise<LinkRatchetRun> {
+ const path = join(opts.root, CEILING_FILE);
+ let ceiling: LinkRatchetCeiling;
+ try {
+ // Only the write form may read a ceiling recorded under an older
+ // counting definition - it is the command the refusal names as the
+ // fix, so it has to be able to re-measure and record the new one.
+ ceiling = parseCeiling(readFileSync(path, "utf8"), { allowForeignDefinition: !opts.check });
+ } catch (e) {
+ opts.stderr(`${e instanceof Error ? e.message : String(e)}\n`);
+ return { exitCode: 1, verdicts: [] };
+ }
+
+ opts.stdout(`canonical definition: ${DANGLING_LINK_DEFINITION}\n`);
+ const comparable = ceiling.definition === DANGLING_LINK_DEFINITION;
+ if (!comparable) {
+ opts.stdout(
+ `${label("redefining")}recorded under '${ceiling.definition}'; ` +
+ "every subject is re-measured and the committed counts are replaced\n",
+ );
+ }
+
+ // Each subject is measured in its own temporary workspace, so the
+ // order of resolution cannot affect any result; reporting is in
+ // committed-file order regardless.
+ const verdicts: ReadonlyArray<LinkRatchetVerdict> = await Promise.all(
+ ceiling.subjects.map(async (subject) =>
+ judgeSubject(
+ subject.path,
+ subject.dangling,
+ await measureVault(join(opts.root, subject.path)),
+ { comparable },
+ ),
+ ),
+ );
+ for (const verdict of verdicts) opts.stdout(`${describe(verdict)}\n`);
+
+ const risen = verdicts.filter((v) => v.status === "rise");
+ const unmeasured = verdicts.filter((v) => v.status === "unmeasurable");
+
+ // A partial recording would silently invent a ceiling for a subject
+ // nobody measured, so an unmeasurable subject blocks the write too.
+ if (unmeasured.length === 0) {
+ const next: LinkRatchetCeiling = {
+ ...ceiling,
+ // What is recorded is what THIS build counted, never the token the
+ // file happened to carry.
+ definition: DANGLING_LINK_DEFINITION,
+ subjects: verdicts.map((v) => ({
+ path: v.subject,
+ dangling: v.measurement.measurable ? v.measurement.dangling : v.ceiling,
+ })),
+ };
+ if (updateCeilingFile(path, next, !opts.check) && !opts.check) {
+ opts.stdout(`${label("wrote")}${CEILING_FILE}\n`);
+ }
+ }
+
+ if (unmeasured.length > 0) {
+ opts.stderr(
+ `\n${unmeasured.length} subject(s) could not be measured; the ratchet has no count to ` +
+ "compare and will not pass. Fix the subject path or the index error named above.\n",
+ );
+ return { exitCode: 1, verdicts };
+ }
+ if (opts.check && risen.length > 0) {
+ opts.stderr(
+ `\n${risen.length} subject(s) above ceiling; fix the broken links, or record the new ` +
+ `baseline (a reviewable diff) with: ${LINK_RATCHET_FIX_COMMAND}\n`,
+ );
+ return { exitCode: 1, verdicts };
+ }
+ return { exitCode: 0, verdicts };
+}
+
+async function main(argv: ReadonlyArray<string>): Promise<number> {
+ const check = argv.includes("--check");
+ const run = await runLinkRatchet({
+ root: ROOT,
+ check,
+ stdout: (text) => process.stdout.write(text),
+ stderr: (text) => process.stderr.write(text),
+ });
+ return run.exitCode;
+}
+
+if (import.meta.main) {
+ process.exit(await main(process.argv.slice(2)));
+}
diff --git a/src/cli/brain/verbs/doctor.ts b/src/cli/brain/verbs/doctor.ts
index 61ea17f6..93972714 100644
--- a/src/cli/brain/verbs/doctor.ts
+++ b/src/cli/brain/verbs/doctor.ts
@@ -76,16 +76,37 @@ export async function cmdBrainDoctor(argv: string[]): Promise<number> {
}
}
+ // Unit F. `uncertain` is a third stream beside warnings and errors:
+ // sub-operations the doctor attempted but cannot claim completed
+ // cleanly. It is emitted ONLY when non-empty, so a clean vault's
+ // output - JSON and human alike - is byte-identical to before, and it
+ // deliberately does not feed the exit code: uncertainty is not a
+ // failure, and folding it into `--strict` would turn an unreadable
+ // field into a broken build.
+ const uncertain = result.uncertain ?? [];
+
if (flags["json"]) {
process.stdout.write(
- JSON.stringify({ warnings: result.warnings, errors: result.errors }, null, 2) + "\n",
+ JSON.stringify(
+ {
+ warnings: result.warnings,
+ errors: result.errors,
+ ...(uncertain.length > 0 ? { uncertain } : {}),
+ },
+ null,
+ 2,
+ ) + "\n",
);
} else {
for (const e of result.errors)
process.stdout.write(`[ERROR] ${e.code}: ${e.message}${e.path ? ` (${e.path})` : ""}\n`);
for (const w of result.warnings)
process.stdout.write(`[WARN] ${w.code}: ${w.message}${w.path ? ` (${w.path})` : ""}\n`);
- if (result.errors.length === 0 && result.warnings.length === 0) ok("brain doctor: clean");
+ for (const u of uncertain)
+ process.stdout.write(`[UNSURE] ${u.code}: ${u.message}${u.path ? ` (${u.path})` : ""}\n`);
+ if (result.errors.length === 0 && result.warnings.length === 0 && uncertain.length === 0) {
+ ok("brain doctor: clean");
+ }
}
if (result.errors.length > 0) return 1;
diff --git a/src/cli/brain/verbs/sgrep.ts b/src/cli/brain/verbs/sgrep.ts
index b6a37f56..992ed8f2 100644
--- a/src/cli/brain/verbs/sgrep.ts
+++ b/src/cli/brain/verbs/sgrep.ts
@@ -15,6 +15,7 @@ export async function cmdBrainSgrep(argv: string[]): Promise<number> {
vault: { type: "string" },
limit: { type: "string" },
"keyword-only": { type: "boolean" },
+ "agent-scope": { type: "string" },
json: { type: "boolean" },
});
const config = defaultConfigPath();
@@ -23,7 +24,8 @@ export async function cmdBrainSgrep(argv: string[]): Promise<number> {
const query = positional[0];
if (!query || query.trim() === "") {
return fail(
- "usage: o2b brain sgrep <query> [path-prefix] [--limit N] [--keyword-only] [--json]",
+ "usage: o2b brain sgrep <query> [path-prefix] [--limit N] [--keyword-only]" +
+ " [--agent-scope NAME] [--json]",
);
}
const pathPrefix = positional[1];
@@ -41,6 +43,9 @@ export async function cmdBrainSgrep(argv: string[]): Promise<number> {
limit,
keywordOnly: flags["keyword-only"] === true,
...(pathPrefix !== undefined ? { pathPrefix } : {}),
+ ...(typeof flags["agent-scope"] === "string"
+ ? { agentScope: flags["agent-scope"] as string }
+ : {}),
});
if (json) {
okJson({
diff --git a/src/cli/search.ts b/src/cli/search.ts
index d510a0bc..fe060c91 100644
--- a/src/cli/search.ts
+++ b/src/cli/search.ts
@@ -14,6 +14,8 @@
*/
import { defaultConfigPath, resolveVault } from "../core/config.ts";
+import { formatDegradationNotice } from "../core/integrity/degradation.ts";
+import { formatStampMismatch } from "../core/integrity/stamp.ts";
import {
createSafeguard,
resolveSafeguardTimeoutMs,
@@ -53,6 +55,7 @@ import {
serializeEvidencePack,
serializeSearchCard,
serializeIndexStatus,
+ serializeStampMismatches,
SEARCH_LIMIT_MIN,
SEARCH_LIMIT_MAX,
} from "../core/search/index.ts";
@@ -679,6 +682,7 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
property: { type: "string-array" },
degree: { type: "string-array" },
visibility: { type: "string-array" },
+ "agent-scope": { type: "string" },
"query-doc": { type: "string" },
expand: { type: "boolean" },
disclosure: { type: "string" },
@@ -750,6 +754,12 @@ async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {
...(properties !== undefined ? { properties } : {}),
...(degreeFilters !== undefined ? { degreeFilters } : {}),
...(visibility !== undefined && visibility.length > 0 ? { visibility } : {}),
+ // Owner-scope isolation (context-integrity-gates, Unit A): an
+ // owner-private page is returned only to its own scope. Omitting the
+ // flag applies no ownership filtering at all.
+ ...(typeof flags["agent-scope"] === "string"
+ ? { agentScope: flags["agent-scope"] as string }
+ : {}),
...(structuredQuery !== undefined ? { structuredQuery } : {}),
...(flags["expand"] === true ? { expand: true } : {}),
...(disclosureRaw === "cards" ? { disclosure: "cards" as const } : {}),
@@ -927,6 +937,7 @@ async function cmdSearchExpand(argv: ReadonlyArray<string>): Promise<number> {
chunk: { type: "string" },
"raw-limit": { type: "string" },
cursor: { type: "string" },
+ "agent-scope": { type: "string" },
json: { type: "boolean" },
});
const chunkId = Number(flags["chunk"]);
@@ -947,6 +958,9 @@ async function cmdSearchExpand(argv: ReadonlyArray<string>): Promise<number> {
chunkId,
...(rawLimit !== undefined ? { rawLimit } : {}),
...(typeof flags["cursor"] === "string" ? { cursor: flags["cursor"] as string } : {}),
+ ...(typeof flags["agent-scope"] === "string"
+ ? { agentScope: flags["agent-scope"] as string }
+ : {}),
});
} catch (e) {
if (e instanceof SearchError) {
@@ -1155,6 +1169,18 @@ function jsonForStats(stats: IndexStats, cfg: ResolvedSearchConfig): unknown {
embeddings_retries: stats.embeddingsRetries,
},
errors: stats.errors.map((e) => ({ path: e.path, message: e.message })),
+ // Unit F. Conditional so a vault with no malformed frontmatter emits
+ // exactly the payload it emitted before this field existed.
+ ...(stats.frontmatterNotices.length > 0
+ ? {
+ frontmatter_notices: stats.frontmatterNotices.map((n) => ({
+ code: n.code,
+ site: n.site,
+ ...(n.path !== undefined ? { path: n.path } : {}),
+ detail: n.detail,
+ })),
+ }
+ : {}),
duration_ms: stats.durationMs,
vault: cfg.vault,
db_path: cfg.dbPath,
@@ -1177,6 +1203,14 @@ function renderStatsHuman(stats: IndexStats, cfg: ResolvedSearchConfig): string
lines.push(` errors:`);
for (const e of stats.errors) lines.push(` - ${e.path}: ${e.message}`);
}
+ // Unit F. Below the errors block and only when non-empty: these files
+ // indexed successfully, they just lost a frontmatter field.
+ if (stats.frontmatterNotices.length > 0) {
+ lines.push(` frontmatter:`);
+ for (const n of stats.frontmatterNotices) {
+ lines.push(` - ${formatDegradationNotice(n)}`);
+ }
+ }
lines.push(`done in ${(stats.durationMs / 1000).toFixed(1)}s`);
return lines.join("\n") + "\n";
}
@@ -1301,6 +1335,11 @@ function jsonForCheck(r: IndexCheckReport): unknown {
embedding_key_resolved: r.embeddingKeyResolved,
provider_reachable: r.providerReachable,
provider_reason: r.providerReason,
+ // Emitted only on drift, so a matching store's JSON is byte-identical
+ // to the pre-gate output (context-integrity-gates, Unit E).
+ ...(r.embeddingAbi.length > 0
+ ? { embedding_abi: serializeStampMismatches(r.embeddingAbi) }
+ : {}),
warnings: r.warnings,
fatal: r.fatal,
recommendations: r.recommendations,
@@ -1316,6 +1355,10 @@ function renderCheckHuman(r: IndexCheckReport): string {
lines.push(`fts5_ok: ${ok(r.fts5Ok)}`);
lines.push(`vec_extension: ${r.vecExtension}`);
lines.push(`embedding_key: ${ok(r.embeddingKeyResolved)}`);
+ // Only on drift: a matching store renders exactly as before.
+ for (const m of r.embeddingAbi) {
+ lines.push(`embedding_abi: ${formatStampMismatch(m)}`);
+ }
if (r.providerReachable !== null) {
lines.push(`provider_reachable: ${r.providerReachable ? "OK" : "FAIL"}`);
if (r.providerReason) lines.push(`provider_reason: ${r.providerReason}`);
diff --git a/src/core/brain/active.ts b/src/core/brain/active.ts
index 8a1b4ad7..5e2c7c44 100644
--- a/src/core/brain/active.ts
+++ b/src/core/brain/active.ts
@@ -43,9 +43,11 @@ import {
loadBrainConfig,
loadGuardrailsConfigSafe,
} from "./policy.ts";
-import { parsePreference, parseRetired } from "./preference.ts";
+import { isPreferenceVisible } from "./owner-scoped-facts.ts";
+import { parseRetired } from "./preference.ts";
+import { collectPreferences, resolveOwnerScopeDelivery } from "./preferences-collect.ts";
import { BRAIN_TOMBSTONE_STATUS } from "./types.ts";
-import { brainActivePath, brainDirs } from "./paths.ts";
+import { brainActivePath, brainDirsForWrite } from "./paths.ts";
import { isoSecond } from "./time.ts";
import { sortByProvenanceTrust } from "./provenance/trust-order.ts";
import { BRAIN_PREFERENCE_STATUS, type BrainPreference, type BrainRetired } from "./types.ts";
@@ -59,6 +61,44 @@ export interface RegenerateActiveOptions {
readonly now?: Date;
}
+/**
+ * Options for the RENDER, which β€” unlike the write β€” may be narrowed to a
+ * single agent's view.
+ */
+export interface RenderActiveOptions extends RegenerateActiveOptions {
+ /**
+ * Owner scope for delivery isolation (context-integrity-gates, Unit
+ * A). Enforced only when `integrity.owner_scope_delivery` is `fail`;
+ * omitted, or under the default `off`, nothing is filtered and the
+ * output is byte-identical to a vault without the gate.
+ *
+ * Deliberately absent from {@link RegenerateActiveOptions}: `active.md`
+ * is ONE file shared by every agent on the vault, injected into every
+ * SessionStart by `hooks/active-inject.ts` and regenerated unscoped by
+ * the `osb://preferences/active` MCP resource. A per-request visibility
+ * filter that reached the write would make the file thrash between
+ * narrowed and complete, and an agent could lose its OWN memories from
+ * session start because another agent read the vault last.
+ */
+ readonly agentScope?: string;
+ /**
+ * `generated_at` stamp for the rendered frontmatter. Defaults to
+ * {@link isoSecond} of `now`. A read-time render passes the stamp
+ * already on disk so its document describes the same generation the
+ * shared file does.
+ */
+ readonly generatedAt?: string;
+}
+
+/** A rendered digest that has NOT been written anywhere. */
+export interface ActiveRender {
+ /** Body only, no frontmatter β€” what the idempotency check compares. */
+ readonly body: string;
+ /** Frontmatter + body: exactly the bytes a write would store. */
+ readonly document: string;
+ readonly counts: RegenerateActiveResult["counts"];
+}
+
export interface RegenerateActiveResult {
/** Absolute path of the written file. */
readonly path: string;
@@ -81,26 +121,25 @@ export interface RegenerateActiveResult {
}
/**
- * Regenerate `<vault>/Brain/active.md`. Returns whether the body
- * actually changed (callers don't need to skip the call themselves β€”
- * the function makes the right decision internally).
+ * Render the active digest WITHOUT writing it.
+ *
+ * The read-time half of this module. `active.md` is a single file shared
+ * by every agent on the vault, so a scope-narrowed view has to be
+ * produced here and delivered to the one caller that asked for it β€”
+ * never persisted. {@link regenerateActive} is the write, and it never
+ * takes a scope.
*
* Errors thrown by individual preference / retired parsers are caught
- * and the offending file is omitted from the render. The function
- * does not raise on parse failures because a single corrupted
- * frontmatter must not break the agent's view of every healthy rule.
- * Corruption is the domain of `brain_doctor`; this writer's job is to
- * surface what is currently knowable.
+ * and the offending file is omitted from the render. This does not raise
+ * on parse failures because a single corrupted frontmatter must not break
+ * the agent's view of every healthy rule. Corruption is the domain of
+ * `brain_doctor`; this render's job is to surface what is knowable.
*/
-export function regenerateActive(
- vault: string,
- opts: RegenerateActiveOptions = {},
-): RegenerateActiveResult {
+export function renderActive(vault: string, opts: RenderActiveOptions = {}): ActiveRender {
const now = opts.now ?? new Date();
- const path = brainActivePath(vault);
- const preferences = readActivePreferences(vault);
- const retiredRecent = readRecentlyRetired(vault, RECENTLY_RETIRED_COUNT);
+ const preferences = readActivePreferences(vault, opts.agentScope);
+ const retiredRecent = readRecentlyRetired(vault, RECENTLY_RETIRED_COUNT, opts.agentScope);
// Confirmed prefs sort by confidence then id. When provenance trust
// ordering is on, re-rank stated > deduced > inferred as the primary key
@@ -149,19 +188,9 @@ export function regenerateActive(
windowDays,
});
- // `readExistingBody` returns the trimmed body (parseFrontmatter
- // trims internally), so compare against the trimmed render for an
- // apples-to-apples byte check.
- const existingBody = readExistingBody(path);
- const changed = existingBody === null || existingBody !== body.trim();
- if (changed) {
- const document = renderDocument(body, isoSecond(now));
- atomicWriteFileSync(path, document);
- }
-
return {
- path,
- changed,
+ body,
+ document: renderDocument(body, opts.generatedAt ?? isoSecond(now)),
counts: {
confirmed: confirmed.length,
quarantine: quarantine.length,
@@ -171,6 +200,34 @@ export function regenerateActive(
};
}
+/**
+ * Regenerate `<vault>/Brain/active.md`. Returns whether the body
+ * actually changed (callers don't need to skip the call themselves β€”
+ * the function makes the right decision internally).
+ *
+ * The write is ALWAYS unscoped: see {@link RenderActiveOptions.agentScope}
+ * for why a per-request visibility filter must not reach this file.
+ */
+export function regenerateActive(
+ vault: string,
+ opts: RegenerateActiveOptions = {},
+): RegenerateActiveResult {
+ const now = opts.now ?? new Date();
+ const path = brainActivePath(vault);
+ const rendered = renderActive(vault, { now });
+
+ // `readExistingBody` returns the trimmed body (parseFrontmatter
+ // trims internally), so compare against the trimmed render for an
+ // apples-to-apples byte check.
+ const existingBody = readExistingBody(path);
+ const changed = existingBody === null || existingBody !== rendered.body.trim();
+ if (changed) {
+ atomicWriteFileSync(path, rendered.document);
+ }
+
+ return { path, changed, counts: rendered.counts };
+}
+
/**
* Wrapper around {@link regenerateActive} that swallows failures with a
* stderr warning. Used by `dream` and `setPinned` β€” both treat the
@@ -192,38 +249,48 @@ export function regenerateActiveQuiet(vault: string, opts: RegenerateActiveOptio
// ----- Scan helpers --------------------------------------------------------
-function readActivePreferences(vault: string): BrainPreference[] {
- const dirs = brainDirs(vault);
- if (!existsSync(dirs.preferences)) return [];
+function readActivePreferences(vault: string, agentScope: string | undefined): BrainPreference[] {
+ const dirs = brainDirsForWrite(vault);
+ // The shared delivery-path walk (context-integrity-gates, Unit A) owns
+ // the listing and the parse; a corrupted or status/folder-mismatched
+ // file is omitted there, and `brain_doctor` is the surface that flags
+ // it. See the module docblock for the rationale.
const out: BrainPreference[] = [];
- for (const name of readdirSync(dirs.preferences)) {
- if (!name.endsWith(".md")) continue;
- const full = join(dirs.preferences, name);
- try {
- const pref = parsePreference(full);
- // Belief lifecycle suite (t_7d5a3589): a tombstoned (incl.
- // superseded-non-tip) preference remains on disk for audit but
- // never appears in the active-preferences digest.
- if ((pref.status as string) === BRAIN_TOMBSTONE_STATUS) continue;
- out.push(pref);
- } catch {
- // Corrupted or status/folder-mismatched file β€” silently omit
- // here. `brain_doctor` is the surface that flags it. See the
- // module docblock for the rationale.
- }
+ for (const { pref } of collectPreferences(dirs.preferences, {
+ ownerScope: resolveOwnerScopeDelivery(vault, agentScope),
+ }).entries) {
+ // Belief lifecycle suite (t_7d5a3589): a tombstoned (incl.
+ // superseded-non-tip) preference remains on disk for audit but
+ // never appears in the active-preferences digest.
+ if ((pref.status as string) === BRAIN_TOMBSTONE_STATUS) continue;
+ out.push(pref);
}
return out;
}
-function readRecentlyRetired(vault: string, limit: number): BrainRetired[] {
- const dirs = brainDirs(vault);
+/**
+ * Retirement KEEPS ownership (context-integrity-gates, A7): a retired
+ * memory is withdrawn from the active set, never published. The gate
+ * verdict is resolved exactly as it is for the active preferences, so a
+ * vault with the gate off - or a caller with no scope - sees the same
+ * list it always did.
+ */
+function readRecentlyRetired(
+ vault: string,
+ limit: number,
+ agentScope: string | undefined,
+): BrainRetired[] {
+ const dirs = brainDirsForWrite(vault);
if (!existsSync(dirs.retired)) return [];
+ const scope = resolveOwnerScopeDelivery(vault, agentScope).enforcedScope;
const out: BrainRetired[] = [];
for (const name of readdirSync(dirs.retired)) {
if (!name.endsWith(".md")) continue;
const full = join(dirs.retired, name);
try {
- out.push(parseRetired(full));
+ const retired = parseRetired(full);
+ if (scope !== null && !isPreferenceVisible(retired, scope)) continue;
+ out.push(retired);
} catch {
// Same rationale as readActivePreferences.
}
diff --git a/src/core/brain/agent-source/query.ts b/src/core/brain/agent-source/query.ts
index 2e3ea3a6..6b20b84d 100644
--- a/src/core/brain/agent-source/query.ts
+++ b/src/core/brain/agent-source/query.ts
@@ -1,4 +1,5 @@
-import { collectAgentSourceContributions, listAgentSources } from "./registry.ts";
+import { isOwnerVisible, normalizeAgentScope } from "../../graph/agent-scope.ts";
+import { collectAgentSourceContributions, summarizeAgentSources } from "./registry.ts";
import { summarizeAgentContributions } from "./summary.ts";
import type {
AgentSourceContribution,
@@ -12,6 +13,14 @@ export interface AgentSourceQueryOptions {
readonly query?: string;
readonly kind?: AgentSourceContributionKind;
readonly limit?: number;
+ /**
+ * Owner scope of the caller (context-integrity-gates, Unit A). A
+ * contribution whose page declares a different owner is withheld;
+ * ownerless contributions - including every log event, which has no
+ * page to own it - always match. Absent filters nothing, so an
+ * unscoped call is byte-identical to before.
+ */
+ readonly ownerScope?: string;
}
export interface AgentSourceQueryFilters {
@@ -39,7 +48,18 @@ export function queryAgentSources(
vault: string,
opts: AgentSourceQueryOptions = {},
): AgentSourceQueryResult {
- const availableAgents = listAgentSources(vault);
+ const ownerScope = normalizeAgentScope(opts.ownerScope);
+
+ // The ownership filter runs FIRST, and the roster is folded from what
+ // survives it. Listing the agents independently of the filter reported
+ // the withheld contributions' topics verbatim and counted them, so a
+ // correct `total_matched` sat next to a roster that named exactly what
+ // it withheld (context-integrity-gates, A5). An unscoped call filters
+ // nothing, so the roster is the same array it always was.
+ const visible = collectAgentSourceContributions(vault).filter(
+ (contribution) => ownerScope === null || isOwnerVisible(contribution.owner ?? null, ownerScope),
+ );
+ const availableAgents = summarizeAgentSources(visible);
const availableIds = new Set(availableAgents.map((a) => a.id));
const selectedAgents = normalizeAgents(
opts.agents,
@@ -51,7 +71,7 @@ export function queryAgentSources(
const query = normalizeTextFilter(opts.query);
const limit = normalizeLimit(opts.limit);
- const matched = collectAgentSourceContributions(vault).filter((contribution) => {
+ const matched = visible.filter((contribution) => {
if (!contribution.agents.some((agent) => selectedSet.has(agent))) return false;
if (opts.kind !== undefined && contribution.kind !== opts.kind) return false;
if (topic !== null && contribution.topic !== topic) return false;
diff --git a/src/core/brain/agent-source/registry.ts b/src/core/brain/agent-source/registry.ts
index fc2cb7ba..89588909 100644
--- a/src/core/brain/agent-source/registry.ts
+++ b/src/core/brain/agent-source/registry.ts
@@ -23,6 +23,22 @@ export function collectAgentSourceContributions(
}
export function listAgentSources(vault: string): ReadonlyArray<AgentSourceSummary> {
+ return summarizeAgentSources(collectAgentSourceContributions(vault));
+}
+
+/**
+ * Fold a contribution set into the per-agent roster.
+ *
+ * Takes the set rather than the vault so a caller that has already
+ * filtered - `queryAgentSources` under an owner scope - summarizes what
+ * it may actually see. Building the roster from the vault independently
+ * of the filter published the withheld contributions' topics verbatim and
+ * counted them (context-integrity-gates, A5), which is the existence leak
+ * the ownership boundary exists to prevent.
+ */
+export function summarizeAgentSources(
+ contributions: ReadonlyArray<AgentSourceContribution>,
+): ReadonlyArray<AgentSourceSummary> {
const byAgent = new Map<
string,
{
@@ -33,7 +49,7 @@ export function listAgentSources(vault: string): ReadonlyArray<AgentSourceSummar
}
>();
- for (const contribution of collectAgentSourceContributions(vault)) {
+ for (const contribution of contributions) {
for (const agent of contribution.agents) {
const current = byAgent.get(agent) ?? {
providerIds: new Set<string>(),
diff --git a/src/core/brain/agent-source/types.ts b/src/core/brain/agent-source/types.ts
index 6f584f81..ed4f0bbc 100644
--- a/src/core/brain/agent-source/types.ts
+++ b/src/core/brain/agent-source/types.ts
@@ -11,6 +11,13 @@ export interface AgentSourceContribution {
readonly title: string;
readonly text: string;
readonly path?: string;
+ /**
+ * Owner token the underlying page declares, when it can declare one
+ * (context-integrity-gates, Unit A). Absent means shared: either the
+ * page carries no `owner:`, or the contribution has no page behind it
+ * at all (a log event), which is not owner-taggable by construction.
+ */
+ readonly owner?: string;
readonly data: Readonly<Record<string, unknown>>;
}
diff --git a/src/core/brain/agent-source/vault-provider.ts b/src/core/brain/agent-source/vault-provider.ts
index db5010ba..9d3f3c98 100644
--- a/src/core/brain/agent-source/vault-provider.ts
+++ b/src/core/brain/agent-source/vault-provider.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
import type { BrainLogEntry } from "../log.ts";
import { readAllLogEntries } from "../query.ts";
import { brainDirs } from "../paths.ts";
+import { preferenceOwner } from "../owner-scoped-facts.ts";
import { parsePreference, parseRetired } from "../preference.ts";
import { parseSignal } from "../signal.ts";
import type { BrainPreference, BrainRetired, BrainSignal } from "../types.ts";
@@ -30,8 +31,8 @@ function collectVaultContributions(vault: string): ReadonlyArray<AgentSourceCont
for (const signal of signals) {
contributions.push(signalContribution(signal));
}
- for (const preference of collectPreferences(dirs.preferences, dirs.retired)) {
- contributions.push(preferenceContribution(preference, signalAgentById));
+ for (const owned of collectPreferences(dirs.preferences, dirs.retired)) {
+ contributions.push(preferenceContribution(owned, signalAgentById));
}
for (const entry of readAllLogEntries(vault)) {
const contribution = logContribution(entry);
@@ -68,22 +69,28 @@ function collectSignals(...dirs: string[]): BrainSignal[] {
return signals;
}
-function collectPreferences(
- preferencesDir: string,
- retiredDir: string,
-): Array<BrainPreference | BrainRetired> {
+/**
+ * A parsed preference or retired record with the owner token its page
+ * declares (context-integrity-gates, Unit A). Both kinds carry `owner`
+ * since A7 made retirement KEEP ownership, so the token is read from the
+ * parsed record and resolved through the one shared rule - no second
+ * frontmatter read, and no way for the two kinds to disagree.
+ */
+interface OwnedRecord {
+ readonly record: BrainPreference | BrainRetired;
+ readonly owner: string | null;
+}
+
+function collectPreferences(preferencesDir: string, retiredDir: string): OwnedRecord[] {
return [
...collectPreferenceDir(preferencesDir, "pref-"),
...collectPreferenceDir(retiredDir, "ret-"),
];
}
-function collectPreferenceDir(
- dir: string,
- prefix: "pref-" | "ret-",
-): Array<BrainPreference | BrainRetired> {
+function collectPreferenceDir(dir: string, prefix: "pref-" | "ret-"): OwnedRecord[] {
if (!existsSync(dir)) return [];
- const out: Array<BrainPreference | BrainRetired> = [];
+ const out: OwnedRecord[] = [];
const entries = readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>
a.name.localeCompare(b.name),
);
@@ -93,7 +100,8 @@ function collectPreferenceDir(
}
const path = join(dir, entry.name);
try {
- out.push(prefix === "pref-" ? parsePreference(path) : parseRetired(path));
+ const record = prefix === "pref-" ? parsePreference(path) : parseRetired(path);
+ out.push({ record, owner: preferenceOwner(record) });
} catch {
continue;
}
@@ -123,9 +131,10 @@ function signalContribution(signal: BrainSignal): AgentSourceContribution {
}
function preferenceContribution(
- preference: BrainPreference | BrainRetired,
+ owned: OwnedRecord,
signalAgentById: ReadonlyMap<string, string>,
): AgentSourceContribution {
+ const preference = owned.record;
const agents = new Set<string>();
for (const evidence of preference.evidenced_by) {
const id = normaliseWikilinkTarget(evidence);
@@ -141,6 +150,7 @@ function preferenceContribution(
timestamp: preference.kind === "brain-retired" ? preference.retired_at : preference.created_at,
topic: preference.topic,
...(preference.scope !== undefined ? { scope: preference.scope } : {}),
+ ...(owned.owner !== null ? { owner: owned.owner } : {}),
title: preference.topic,
text: [preference.topic, preference.status, preference.principle].join("\n"),
data: {
diff --git a/src/core/brain/anticipatory-cache.ts b/src/core/brain/anticipatory-cache.ts
index fb991448..030fb4bf 100644
--- a/src/core/brain/anticipatory-cache.ts
+++ b/src/core/brain/anticipatory-cache.ts
@@ -22,13 +22,26 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { join, posix } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
+import type { StampTokens } from "../integrity/stamp.ts";
import { packContext, type ContextPackItem } from "./context-pack.ts";
import { readLineageLedger } from "./lineage/ledger.ts";
+import { packStampRefusal, packStampTokens, type ContextPackStamp } from "./pack-stamp.ts";
+import { resolveOwnerScopeDelivery } from "./preferences-collect.ts";
import { resolveSessionLineage } from "./lineage/resolve.ts";
import { BRAIN_ROOT_REL, ensureInsideVault } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { searchSessionRecall, type SessionRecallHit } from "./session-recall.ts";
-export const ANTICIPATORY_SCHEMA_VERSION = "o2b.anticipatory.v1";
+/**
+ * Cache-file schema token. Bumped to `v2` by context-integrity-gates
+ * (Unit B) because a `v1` file carries no provenance stamp: reusing the
+ * version would leave those entries readable as UNSTAMPED hits, which is
+ * exactly the "trusted forever" state the stamp exists to remove.
+ * `readCacheFile` already rejects a schema mismatch, so the bump needs no
+ * migration - every pre-existing file simply reads as a miss and is
+ * rebuilt on the next refresh.
+ */
+export const ANTICIPATORY_SCHEMA_VERSION = "o2b.anticipatory.v2";
/** Default debounce/freshness window. */
export const DEFAULT_ANTICIPATORY_TTL_SECONDS = 120;
@@ -51,6 +64,14 @@ export interface RefreshAnticipatoryCacheInput {
readonly now: Date;
readonly ttlSeconds?: number;
readonly maxTokens?: number;
+ /**
+ * Owner scope for delivery isolation (context-integrity-gates, Unit
+ * A). Part of the cache IDENTITY, not just the pack build: a bundle
+ * assembled under one scope must never be served under another, which
+ * a path keyed only on the lineage root would allow between two agents
+ * sharing one conversation lineage.
+ */
+ readonly agentScope?: string;
}
export interface RefreshAnticipatoryCacheResult {
@@ -66,6 +87,14 @@ export interface ReadAnticipatoryContextInput {
readonly now: Date;
readonly ttlSeconds?: number;
readonly maxTokens?: number;
+ /**
+ * Owner scope for delivery isolation (context-integrity-gates, Unit
+ * A). Part of the cache IDENTITY, not just the pack build: a bundle
+ * assembled under one scope must never be served under another, which
+ * a path keyed only on the lineage root would allow between two agents
+ * sharing one conversation lineage.
+ */
+ readonly agentScope?: string;
}
export interface ReadAnticipatoryContextResult {
@@ -73,9 +102,25 @@ export interface ReadAnticipatoryContextResult {
readonly root_session_id: string;
/** Stamp of the cache that answered (warm reads only). */
readonly generated_at?: string;
+ /**
+ * Why an otherwise-fresh cache entry was REFUSED rather than served
+ * (context-integrity-gates, Unit B): its provenance stamp drifted from
+ * the vault, or its validity window closed. Present only on a refusal,
+ * so an ordinary miss or a TTL-stale read stays byte-identical. The
+ * refusal is named rather than silent precisely so a stale bundle and
+ * a broken mechanism stay distinguishable.
+ */
+ readonly cache_refusal?: string;
readonly context: AnticipatoryContext;
}
+/** On-disk form of {@link ContextPackStamp} (snake_case, like its siblings). */
+interface CacheStamp {
+ readonly tokens: Record<string, string | null>;
+ readonly generated_at: string;
+ readonly expires_at: string;
+}
+
interface CacheFile {
readonly schema: string;
readonly root_session_id: string;
@@ -84,9 +129,27 @@ interface CacheFile {
/** Token budget the cached pack was built under (variant field). */
readonly max_tokens: number;
readonly signal?: string;
+ /** What the cached pack was derived from, and when it stops being servable. */
+ readonly stamp: CacheStamp;
readonly context: AnticipatoryContext;
}
+function toCacheStamp(stamp: ContextPackStamp): CacheStamp {
+ return {
+ tokens: { ...stamp.tokens },
+ generated_at: stamp.generatedAt,
+ expires_at: stamp.expiresAt,
+ };
+}
+
+function fromCacheStamp(stamp: CacheStamp): ContextPackStamp {
+ return {
+ tokens: stamp.tokens as StampTokens,
+ generatedAt: stamp.generated_at,
+ expiresAt: stamp.expires_at,
+ };
+}
+
/**
* Collision-resistant flat filename for any root id: a readable
* sanitized prefix plus a content digest, so distinct roots that
@@ -99,11 +162,41 @@ function safeCacheKey(rootId: string): string {
return `${prefix}-${digest}`;
}
-export function anticipatoryCachePath(vault: string, rootSessionId: string): string {
- return ensureInsideVault(
- join(vault, CACHE_DIR_REL, `${safeCacheKey(rootSessionId)}.json`),
- vault,
- );
+/**
+ * Cache file for a lineage root under an owner scope.
+ *
+ * The scope is part of the KEY, not merely of the payload. The cache
+ * persists a context pack to disk, so a path keyed only on the lineage
+ * root would let one agent's refresh materialize its memories into the
+ * exact file another scope reads back - a disk-persisted leak that
+ * outlives the process that caused it.
+ *
+ * The key uses the ENFORCED scope, resolved here rather than by the
+ * caller, so no call site can key on a scope that does not actually
+ * narrow the payload. That distinction is load-bearing:
+ * `coerceAgentScope(ctx, args, true)` falls back to `resolveAgentName`,
+ * which ALWAYS returns a string (the literal `"agent"` when nothing is
+ * configured), so `brain_anticipatory_context` passes a scope on every
+ * call regardless of the gate - while the two writers that warm the
+ * cache (the session-lifecycle hook and `o2b brain anticipate --refresh`)
+ * pass none. Keying on the REQUESTED scope therefore made the MCP read a
+ * permanent miss on a default vault, rebuilding a full `packContext` on
+ * every call. Under `off` and `warn` the pack is not narrowed either, so
+ * one file is the correct answer as well as the pre-gate one; only `fail`
+ * splits the cache, which is exactly when the payloads genuinely differ.
+ *
+ * An absent or non-enforcing scope keeps the legacy filename
+ * byte-for-byte, so warm caches written before the gate existed are still
+ * found.
+ */
+export function anticipatoryCachePath(
+ vault: string,
+ rootSessionId: string,
+ agentScope?: string | null,
+): string {
+ const scope = resolveOwnerScopeDelivery(vault, agentScope ?? undefined).enforcedScope;
+ const key = safeCacheKey(scope === null ? rootSessionId : `${rootSessionId}\u0000${scope}`);
+ return ensureInsideVault(join(vault, CACHE_DIR_REL, `${key}.json`), vault);
}
function resolveRootId(vault: string, sessionId: string): string {
@@ -127,37 +220,89 @@ function readCacheFile(path: string): CacheFile | null {
if (!Array.isArray(cache.context.items) || !Array.isArray(cache.context.session_hits)) {
return null;
}
+ // An entry that carries no readable stamp is a miss, never an
+ // unstamped hit: the whole point of the stamp is that a persisted
+ // pack is verified rather than trusted, and a file that cannot be
+ // verified has nothing to offer over rebuilding.
+ if (!isCacheStamp(cache.stamp)) return null;
return cache;
} catch {
return null; // corrupt cache reads as a miss by contract
}
}
-function buildContext(
- vault: string,
- sessionId: string,
- signalText: string | undefined,
- maxTokens: number,
-): AnticipatoryContext {
- const pack = packContext(vault, { maxTokens });
- const signal = signalText?.trim() ?? "";
+function isCacheStamp(value: unknown): value is CacheStamp {
+ if (value === null || typeof value !== "object") return false;
+ const stamp = value as CacheStamp;
+ if (typeof stamp.generated_at !== "string" || typeof stamp.expires_at !== "string") return false;
+ return stamp.tokens !== null && typeof stamp.tokens === "object" && !Array.isArray(stamp.tokens);
+}
+
+interface BuildBundleInput {
+ readonly sessionId: string;
+ readonly signalText: string | undefined;
+ readonly maxTokens: number;
+ readonly agentScope: string | undefined;
+ /** Injected clock; the stamp's window is anchored to it. */
+ readonly now: Date;
+}
+
+interface BuiltBundle {
+ readonly context: AnticipatoryContext;
+ readonly stamp: ContextPackStamp;
+}
+
+function buildBundle(vault: string, input: BuildBundleInput): BuiltBundle {
+ const pack = packContext(vault, {
+ maxTokens: input.maxTokens,
+ ...(input.agentScope !== undefined ? { agentScope: input.agentScope } : {}),
+ stamp: { now: input.now },
+ });
+ const signal = input.signalText?.trim() ?? "";
const hits =
signal.length > 0
- ? searchSessionRecall(vault, { query: signal, sessionId, limit: DEFAULT_SESSION_HITS }).hits
+ ? searchSessionRecall(vault, {
+ query: signal,
+ sessionId: input.sessionId,
+ limit: DEFAULT_SESSION_HITS,
+ }).hits
: Object.freeze([] as SessionRecallHit[]);
- return Object.freeze({ items: pack.items, session_hits: hits });
+ return {
+ context: Object.freeze({ items: pack.items, session_hits: hits }),
+ stamp: pack.stamp,
+ };
+}
+
+/**
+ * Why a cached entry must not be served, or `null` when it may be.
+ * Shared by the refresh debounce and the read so the two can never
+ * disagree about what "still valid" means - a warm-but-drifted entry
+ * that survived the debounce would be refused on every read and never
+ * rebuilt until its TTL lapsed.
+ */
+function cacheRefusal(vault: string, cached: CacheFile, now: Date): string | null {
+ return packStampRefusal(fromCacheStamp(cached.stamp), packStampTokens(vault), now);
}
/**
* Refresh the cache for the session's lineage root unless a fresh copy
- * already exists (TTL debounce). Never throws.
+ * already exists (TTL debounce).
+ *
+ * Fail-soft by design: every cache-building error is swallowed and
+ * reported as `refreshed: false`. The ONE exception is the vault-identity
+ * refusal, which is raised ahead of the try so it cannot be mistaken for
+ * an ordinary cache miss - the only caller (the session-lifecycle hook)
+ * already catches, so the hook still fails open, but it fails open
+ * WITHOUT having written the cache into the wrong store.
*/
export function refreshAnticipatoryCache(
vault: string,
input: RefreshAnticipatoryCacheInput,
): RefreshAnticipatoryCacheResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const rootId = resolveRootId(vault, input.sessionId);
- const path = anticipatoryCachePath(vault, rootId);
+ const path = anticipatoryCachePath(vault, rootId, input.agentScope);
const ttlMs = (input.ttlSeconds ?? DEFAULT_ANTICIPATORY_TTL_SECONDS) * 1_000;
const maxTokens = input.maxTokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS;
try {
@@ -167,13 +312,30 @@ export function refreshAnticipatoryCache(
// deliberately NOT part of the cache identity - it changes every
// prompt, and invalidating on it would defeat the debounce that
// makes hook-driven refresh affordable.
+ //
+ // The stamp overrides the debounce (context-integrity-gates, Unit
+ // B): a drifted or expired entry rebuilds even inside the TTL,
+ // because the stamp - not the clock - is the primary invalidator.
+ // Without this the read side would refuse the same drifted entry on
+ // every turn and never get a replacement until the TTL lapsed.
if (existing !== null && existing.max_tokens === maxTokens) {
const age = input.now.getTime() - Date.parse(existing.generated_at);
- if (Number.isFinite(age) && age >= 0 && age < ttlMs) {
+ if (
+ Number.isFinite(age) &&
+ age >= 0 &&
+ age < ttlMs &&
+ cacheRefusal(vault, existing, input.now) === null
+ ) {
return Object.freeze({ refreshed: false, rootSessionId: rootId, path });
}
}
- const context = buildContext(vault, input.sessionId, input.signalText, maxTokens);
+ const bundle = buildBundle(vault, {
+ sessionId: input.sessionId,
+ signalText: input.signalText,
+ maxTokens,
+ agentScope: input.agentScope,
+ now: input.now,
+ });
const signal = input.signalText?.trim();
const cache: CacheFile = {
schema: ANTICIPATORY_SCHEMA_VERSION,
@@ -182,7 +344,8 @@ export function refreshAnticipatoryCache(
generated_at: input.now.toISOString(),
max_tokens: maxTokens,
...(signal !== undefined && signal.length > 0 ? { signal } : {}),
- context,
+ stamp: toCacheStamp(bundle.stamp),
+ context: bundle.context,
};
mkdirSync(join(vault, CACHE_DIR_REL), { recursive: true });
atomicWriteFileSync(path, `${JSON.stringify(cache, null, 2)}\n`);
@@ -201,39 +364,60 @@ export function readAnticipatoryContext(
input: ReadAnticipatoryContextInput,
): ReadAnticipatoryContextResult {
const rootId = resolveRootId(vault, input.sessionId);
- const path = anticipatoryCachePath(vault, rootId);
+ const path = anticipatoryCachePath(vault, rootId, input.agentScope);
const ttlMs = (input.ttlSeconds ?? DEFAULT_ANTICIPATORY_TTL_SECONDS) * 1_000;
const requestedTokens = input.maxTokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS;
const cached = readCacheFile(path);
if (cached !== null) {
const age = input.now.getTime() - Date.parse(cached.generated_at);
if (cached.max_tokens === requestedTokens && Number.isFinite(age) && age >= 0 && age < ttlMs) {
+ // Fresh by the clock is not the same as valid. The stamp decides
+ // whether the persisted bundle still describes this vault, and an
+ // expired window decides when a bundle stops being servable even
+ // if nothing observable drifted.
+ const refusal = cacheRefusal(vault, cached, input.now);
+ if (refusal === null) {
+ return Object.freeze({
+ cache_state: "warm" as const,
+ root_session_id: rootId,
+ generated_at: cached.generated_at,
+ context: cached.context,
+ });
+ }
return Object.freeze({
- cache_state: "warm" as const,
+ cache_state: "miss" as const,
root_session_id: rootId,
- generated_at: cached.generated_at,
- context: cached.context,
+ cache_refusal: refusal,
+ context: buildBundle(vault, {
+ sessionId: input.sessionId,
+ signalText: cached.signal,
+ maxTokens: requestedTokens,
+ agentScope: input.agentScope,
+ now: input.now,
+ }).context,
});
}
return Object.freeze({
cache_state: "stale" as const,
root_session_id: rootId,
- context: buildContext(
- vault,
- input.sessionId,
- cached.signal,
- input.maxTokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS,
- ),
+ context: buildBundle(vault, {
+ sessionId: input.sessionId,
+ signalText: cached.signal,
+ maxTokens: requestedTokens,
+ agentScope: input.agentScope,
+ now: input.now,
+ }).context,
});
}
return Object.freeze({
cache_state: "miss" as const,
root_session_id: rootId,
- context: buildContext(
- vault,
- input.sessionId,
- undefined,
- input.maxTokens ?? DEFAULT_ANTICIPATORY_MAX_TOKENS,
- ),
+ context: buildBundle(vault, {
+ sessionId: input.sessionId,
+ signalText: undefined,
+ maxTokens: requestedTokens,
+ agentScope: input.agentScope,
+ now: input.now,
+ }).context,
});
}
diff --git a/src/core/brain/architect/generate.ts b/src/core/brain/architect/generate.ts
index fa001f14..e007ba91 100644
--- a/src/core/brain/architect/generate.ts
+++ b/src/core/brain/architect/generate.ts
@@ -27,6 +27,7 @@ import { buildRegionDocument, mergeRegions } from "../regions.ts";
import type { Region } from "../regions.ts";
import { scanProject } from "./scan.ts";
import type { ModuleFact, ProjectFacts } from "./scan.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export interface GenerateArchDocsResult {
readonly repoKey: string;
@@ -128,6 +129,8 @@ function upsertNote(
/** Generate or refresh architecture notes for one project tree. */
export function generateArchDocs(vault: string, projectRoot: string): GenerateArchDocsResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const facts = scanProject(projectRoot);
const key = deriveRepoKey(facts.root);
const dir = join(vault, "Brain", "projects", "arch", key);
diff --git a/src/core/brain/attention-flows.ts b/src/core/brain/attention-flows.ts
index 73051cd7..08b271a9 100644
--- a/src/core/brain/attention-flows.ts
+++ b/src/core/brain/attention-flows.ts
@@ -3,6 +3,7 @@ import { join } from "node:path";
import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
import { attentionFlowsDir, brainDirs } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { listProceduralMemory } from "./procedural-memory.ts";
import { listPendingSkillProposals } from "./skill-proposals.ts";
import { listRecurrenceEntries } from "./recurrence.ts";
@@ -41,6 +42,8 @@ export interface AttentionFlowEvaluation {
}
export function ensureDefaultAttentionFlows(vault: string): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const dir = attentionFlowsDir(vault);
mkdirSync(dir, { recursive: true });
const defaultPath = join(dir, "open-loops.md");
@@ -78,20 +81,23 @@ export function listAttentionFlows(vault: string): ReadonlyArray<AttentionFlowRe
for (const name of readdirSync(dir).toSorted()) {
if (!name.endsWith(".md")) continue;
const path = join(dir, name);
- try {
- const [fm] = parseFrontmatter(path);
- if (fm["kind"] !== "brain-attention-flow") continue;
- const actions = normalizeActions(fm["actions"]);
- out.push({
- id: typeof fm["id"] === "string" ? fm["id"] : name.replace(/\.md$/, ""),
- title: typeof fm["title"] === "string" ? fm["title"] : name.replace(/\.md$/, ""),
- actions,
- standingQueryScopes: normalizeStandingQueryScopes(fm["standing_queries"]),
- sourcePath: path,
- });
- } catch {
- continue;
- }
+ // Unit F: unreachable `catch { continue }` removed - nothing in this
+ // body throws (`parseFrontmatter` reads inside its own try, and both
+ // normalizers are total over `unknown`). A recipe whose frontmatter
+ // could not be read yields an empty map, fails the `kind` check on
+ // the next line, and is skipped exactly as the dead branch intended.
+ // See the "Why most readers keep the two-tuple form" section in
+ // src/core/vault.ts for where the condition IS reported.
+ const [fm] = parseFrontmatter(path);
+ if (fm["kind"] !== "brain-attention-flow") continue;
+ const actions = normalizeActions(fm["actions"]);
+ out.push({
+ id: typeof fm["id"] === "string" ? fm["id"] : name.replace(/\.md$/, ""),
+ title: typeof fm["title"] === "string" ? fm["title"] : name.replace(/\.md$/, ""),
+ actions,
+ standingQueryScopes: normalizeStandingQueryScopes(fm["standing_queries"]),
+ sourcePath: path,
+ });
}
return Object.freeze(out);
}
diff --git a/src/core/brain/attributes.ts b/src/core/brain/attributes.ts
index 391103ec..5c254b7d 100644
--- a/src/core/brain/attributes.ts
+++ b/src/core/brain/attributes.ts
@@ -17,6 +17,7 @@ import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
import { resolveNotePath } from "./note-path.ts";
import { normalizeSchemaToken } from "./schema-vocab.ts";
import type { SchemaPack } from "./schema-pack.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export class AttributeVocabularyError extends Error {
readonly type: string;
@@ -131,6 +132,8 @@ export function assignNoteAttribute(
relPath: string,
opts: AssignNoteAttributeOptions,
): NoteAttributeResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = resolveNotePath(vault, relPath);
const [metadata, body] = parseFrontmatter(path);
const rawType = metadata["type"];
@@ -156,6 +159,8 @@ export function removeNoteAttribute(
relPath: string,
opts: RemoveNoteAttributeOptions,
): RemoveNoteAttributeResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const field = normalizeSchemaToken(opts.field);
const path = resolveNotePath(vault, relPath);
const [metadata, body] = parseFrontmatter(path);
diff --git a/src/core/brain/authored-at-backfill.ts b/src/core/brain/authored-at-backfill.ts
index cabd5256..39a2b46e 100644
--- a/src/core/brain/authored-at-backfill.ts
+++ b/src/core/brain/authored-at-backfill.ts
@@ -32,6 +32,7 @@ import { join } from "node:path";
import { BRAIN_INBOX_REL } from "./paths.ts";
import { BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** One signal that carries a preserved turn instant but no `authored_at`. */
export interface AuthoredAtBackfillCandidate {
@@ -103,6 +104,9 @@ export function planAuthoredAtBackfill(
opts: AuthoredAtBackfillOptions = {},
): AuthoredAtBackfillResult {
const apply = opts.apply === true;
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ // Planning without `apply` writes nothing, so it stays ungated.
+ if (apply) assertVaultIdentityForWrite(vault);
const inbox = join(vault, BRAIN_INBOX_REL);
const candidates: AuthoredAtBackfillCandidate[] = [];
let scanned = 0;
diff --git a/src/core/brain/capture/capture-note.ts b/src/core/brain/capture/capture-note.ts
index 8a2e29ec..65bf4b88 100644
Binary files a/src/core/brain/capture/capture-note.ts and b/src/core/brain/capture/capture-note.ts differ
diff --git a/src/core/brain/capture/inbox-drain.ts b/src/core/brain/capture/inbox-drain.ts
index b7628f1c..b53cb5e3 100644
--- a/src/core/brain/capture/inbox-drain.ts
+++ b/src/core/brain/capture/inbox-drain.ts
@@ -30,6 +30,7 @@ import { addObligation, obligationExists, parseCadence, ObligationError } from "
import { ingestSource } from "../ingest/ingest.ts";
import { isoSecond } from "../time.ts";
import { archiveCapture, listStagedCaptures, type CaptureNote } from "./capture-note.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Explicit leading token that classifies a capture as an obligation. */
export const CAPTURE_OBLIGATION_MARKER = "@obligation";
@@ -223,6 +224,8 @@ function dirOf(abs: string): string {
/** Classify and (in apply mode) route every staged capture. */
export function drainInbox(vault: string, opts: DrainOptions): DrainReport {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const items: DrainItem[] = [];
let routed = 0;
let unroutable = 0;
diff --git a/src/core/brain/capture/telegram-capture.ts b/src/core/brain/capture/telegram-capture.ts
index 3ccc0c91..82c69ab5 100644
--- a/src/core/brain/capture/telegram-capture.ts
+++ b/src/core/brain/capture/telegram-capture.ts
@@ -32,6 +32,7 @@ import {
writeCatchupWatermark,
type CaptureNote,
} from "./capture-note.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Telegram command that triggers a catchup reply. */
export const CATCHUP_COMMAND = "/catchup";
@@ -239,6 +240,8 @@ export function handleCaptureUpdate(
update: TelegramUpdate,
opts: HandleUpdateOptions,
): HandleUpdateResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const now = opts.now();
const at = isoSecond(now);
const updateId = typeof update.update_id === "number" ? update.update_id : -1;
diff --git a/src/core/brain/claim-graph.ts b/src/core/brain/claim-graph.ts
index ecb39bf9..941af74b 100644
--- a/src/core/brain/claim-graph.ts
+++ b/src/core/brain/claim-graph.ts
@@ -33,6 +33,7 @@ import { parseFrontmatter } from "../vault.ts";
import { brainDirs, claimGraphPath } from "./paths.ts";
import { isTombstoned, normalizeChainLink, resolveChainTip } from "./lifecycle/tombstone.ts";
import { isValidAt } from "./lifecycle/temporal-replace.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
// ----- Constants ------------------------------------------------------------
@@ -118,12 +119,14 @@ function normalizedList(meta: FrontmatterMap, key: string): string[] {
}
function toNode(vault: string, absPath: string): ClaimNode | null {
- let meta: FrontmatterMap;
- try {
- [meta] = parseFrontmatter(absPath);
- } catch {
- return null;
- }
+ // Unit F: `parseFrontmatter` cannot throw (it reads inside its own try;
+ // everything after is string work), so the `catch { return null }` that
+ // stood here was unreachable - and redundant, because a failed read
+ // yields an empty map and the very next line already returns null for
+ // it. Dropped lines are reported centrally; see the "Why most readers
+ // keep the two-tuple form" section in src/core/vault.ts. A claim node
+ // is a graph vertex with no report field, so it opens no channel here.
+ const [meta] = parseFrontmatter(absPath);
if (Object.keys(meta).length === 0) return null;
const rel = relative(vault, absPath).split("\\").join("/");
const id = normalizeChainLink(absPath);
@@ -193,6 +196,8 @@ export function buildClaimGraph(vault: string, opts: BuildClaimGraphOptions = {}
/** Persist a projection to `Brain/claim-graph.json`. */
export function writeClaimGraph(vault: string, graph: ClaimGraph): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
atomicWriteFileSync(claimGraphPath(vault), `${JSON.stringify(graph, null, 2)}\n`);
}
diff --git a/src/core/brain/claude-memory-manifest.ts b/src/core/brain/claude-memory-manifest.ts
index 2f401909..6f643de1 100644
--- a/src/core/brain/claude-memory-manifest.ts
+++ b/src/core/brain/claude-memory-manifest.ts
@@ -3,6 +3,7 @@ import { dirname, join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { BRAIN_ROOT_REL } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export interface ClaudeMemoryManifestEntry {
readonly pref_id: string;
@@ -51,6 +52,8 @@ export function loadManifest(vault: string): ClaudeMemoryManifest {
}
export function saveManifest(vault: string, m: ClaudeMemoryManifest): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const p = manifestPath(vault);
mkdirSync(dirname(p), { recursive: true });
atomicWriteFileSync(p, JSON.stringify(m, null, 2) + "\n");
diff --git a/src/core/brain/claude-memory-parser.ts b/src/core/brain/claude-memory-parser.ts
index d16b806c..d566e6dc 100644
--- a/src/core/brain/claude-memory-parser.ts
+++ b/src/core/brain/claude-memory-parser.ts
@@ -105,12 +105,16 @@ export function parseClaudeMemoryFile(text: string): ClaudeMemoryParseResult {
if (!m) {
return { kind: "skip", skipReason: "missing or malformed frontmatter" };
}
- let fm: Record<string, unknown>;
- try {
- fm = parseFrontmatterBlock(m[1]!);
- } catch {
- return { kind: "skip", skipReason: "frontmatter is not valid YAML" };
- }
+ // Unit F: the `catch` that stood here returned a
+ // "frontmatter is not valid YAML" skip. `parseFrontmatterBlock` is a
+ // line scanner with no `throw` anywhere in it or in the two pure string
+ // helpers it calls, so that arm was unreachable and the skip reason it
+ // named could never be produced - a diagnostic that reads as coverage
+ // and provides none. Unsupported grammar is dropped line-by-line by
+ // that scanner, exactly as in `parseFrontmatterText`, and the shapes it
+ // cannot express fall out of the `type` / `name` / `description` checks
+ // below with a skip reason that is actually reachable.
+ const fm = parseFrontmatterBlock(m[1]!);
const name = typeof fm["name"] === "string" ? fm["name"].trim() : "";
const description = typeof fm["description"] === "string" ? fm["description"].trim() : "";
// Claude Code Memory uses two frontmatter shapes for the `type` field:
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index d25105e2..0513cc42 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -13,10 +13,9 @@
* are reported in `pagesSkipped` with their estimated cost.
*/
-import { existsSync, readdirSync, statSync } from "node:fs";
+import { statSync } from "node:fs";
import { join, relative } from "node:path";
-import { parseFrontmatter } from "../vault.ts";
import { canonicalNotePath } from "../path-safety.ts";
import { loadGuardrailsConfigSafe } from "./policy.ts";
import {
@@ -25,6 +24,12 @@ import {
type ContextSafetyReport,
} from "./safety/context-guard.ts";
import { brainDirs } from "./paths.ts";
+import {
+ collectPreferencePages,
+ formatOwnerScopeWarning,
+ resolveOwnerScopeDelivery,
+ type OwnerScopeDelivery,
+} from "./preferences-collect.ts";
import { isTombstoned } from "./lifecycle/tombstone.ts";
import { preferChainTips } from "./inject-governor.ts";
import { tensionWarningsForContextItems } from "./tensions.ts";
@@ -63,6 +68,7 @@ import {
type ContextLanesReport,
} from "./context-lanes.ts";
import { buildAttentionContextBlock } from "./attention-flows.ts";
+import { buildPackStamp, type ContextPackStamp } from "./pack-stamp.ts";
import { scoreSessionFocusTarget, sessionFocusIsActive } from "../search/session-focus.ts";
import type { SearchSessionFocus } from "../search/types.ts";
@@ -131,6 +137,32 @@ export interface ContextPackReport {
* keeps the report byte-identical.
*/
readonly warnings?: ReadonlyArray<string>;
+ /**
+ * Provenance stamp and validity window (context-integrity-gates, Unit
+ * B). Present ONLY when the caller passed
+ * {@link ContextPackOptions.stamp}, so a pack that never asked to be
+ * persisted stays byte-identical - the same conditional shape `lanes`
+ * and `density` use.
+ */
+ readonly stamp?: ContextPackStamp;
+}
+
+/**
+ * Opt into a provenance stamp on the report. The clock is INJECTED
+ * rather than read here: the persisting caller (the anticipatory cache)
+ * already owns an event time, and the stamp's window must agree with the
+ * timestamps that caller records rather than with a second wall-clock
+ * reading taken microseconds later.
+ */
+export interface PackStampOptions {
+ readonly now: Date;
+ /**
+ * Config file the stamp resolves the search-index location through.
+ * Threaded rather than defaulted at the leaf so a caller that already
+ * knows its config path stamps against the database `search()` would
+ * actually read for it, not the one the process default names.
+ */
+ readonly configPath?: string;
}
export interface ContextPackOptions {
@@ -201,6 +233,13 @@ export interface ContextPackOptions {
* on the `density_ranking_context_pack` config key.
*/
readonly densityRanking?: boolean;
+ /**
+ * Owner scope for delivery isolation (context-integrity-gates, Unit
+ * A). Enforced only when `integrity.owner_scope_delivery` is `fail`;
+ * omitted, or under the default `off`, no candidate is filtered and
+ * the pack is byte-identical to a vault without the gate.
+ */
+ readonly agentScope?: string;
/**
* Belief lifecycle suite (A4, t_d9365884): keep superseded ancestors in
* the pack instead of collapsing each supersedes-chain to its live tip.
@@ -208,6 +247,13 @@ export interface ContextPackOptions {
* the query. Omitted/false injects only chain tips.
*/
readonly includeHistorical?: boolean;
+ /**
+ * Opt-in provenance stamp (context-integrity-gates, Unit B). Required
+ * by any caller that PERSISTS a pack, so the persisted copy can be
+ * verified against the vault on read instead of being trusted forever.
+ * Omitted keeps the report byte-identical.
+ */
+ readonly stamp?: PackStampOptions;
}
interface Candidate {
@@ -254,21 +300,30 @@ function withOptionalLanes(
};
}
-function collectCandidates(vault: string, delimitUntrusted: boolean): Candidate[] {
+function collectCandidates(
+ vault: string,
+ delimitUntrusted: boolean,
+ ownerScope: OwnerScopeDelivery,
+): { readonly candidates: Candidate[]; readonly hiddenByOwnerScope: number } {
const dirs = brainDirs(vault);
const out: Candidate[] = [];
+ let hiddenByOwnerScope = 0;
for (const dir of [dirs.preferences, dirs.retired]) {
- if (!existsSync(dir)) continue;
- for (const name of readdirSync(dir)) {
- if (!name.endsWith(".md")) continue;
- const full = join(dir, name);
- let meta: Record<string, unknown>;
- let body: string;
- try {
- [meta, body] = parseFrontmatter(full);
- } catch {
- continue;
- }
+ // Shared delivery-path walk (context-integrity-gates, Unit A). This
+ // surface reads raw frontmatter rather than the preference schema:
+ // it injects the BODY, and it walks the retired directory alongside
+ // the preferences one, where the preference schema does not apply.
+ //
+ // Unit F: `parseFrontmatter` cannot throw (it reads inside its own
+ // try; everything after is string work), so the `catch { continue }`
+ // that stood here was unreachable and reported nothing. Dropped
+ // lines and unreadable reads are reported centrally instead - see
+ // the "Why most readers keep the two-tuple form" section in
+ // src/core/vault.ts. A pack returns injected content and carries no
+ // per-candidate report, so it opens no channel of its own.
+ const collected = collectPreferencePages(dir, { ownerScope });
+ hiddenByOwnerScope += collected.hiddenByOwnerScope;
+ for (const { name, path: full, meta, body } of collected.entries) {
// Belief lifecycle suite (t_7d5a3589): a tombstoned (incl.
// superseded-non-tip) memory stays on disk for audit but is never
// injected into a context pack.
@@ -325,9 +380,20 @@ function collectCandidates(vault: string, delimitUntrusted: boolean): Candidate[
});
}
}
- return out;
+ return { candidates: out, hiddenByOwnerScope };
}
+/**
+ * A stamped call is statically known to return a stamped report, so a
+ * persisting caller never has to handle an "impossible" absent stamp -
+ * the case that would otherwise invite exactly the silent fallback this
+ * wave removes.
+ */
+export function packContext(
+ vault: string,
+ opts: ContextPackOptions & { readonly stamp: PackStampOptions },
+): ContextPackReport & { readonly stamp: ContextPackStamp };
+export function packContext(vault: string, opts: ContextPackOptions): ContextPackReport;
export function packContext(vault: string, opts: ContextPackOptions): ContextPackReport {
const startedAtMs = Date.now();
if (!Number.isFinite(opts.maxTokens) || opts.maxTokens <= 0) {
@@ -354,9 +420,15 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
// of replacements injects only the current belief; `includeHistorical`
// keeps the whole chain (explicit flag, never inferred). A vault with no
// supersession chains passes through byte-identically.
- const candidates = preferChainTips(collectCandidates(vault, delimitUntrusted), {
+ const ownerScope = resolveOwnerScopeDelivery(vault, opts.agentScope);
+ const collected = collectCandidates(vault, delimitUntrusted, ownerScope);
+ const candidates = preferChainTips(collected.candidates, {
historical: opts.includeHistorical === true,
}).kept;
+ // Reported only under `warn`, where nothing was withheld - see
+ // `formatOwnerScopeWarning` for why `fail` stays silent.
+ const ownerScopeWarning = formatOwnerScopeWarning(ownerScope, collected.hiddenByOwnerScope);
+ const ownerScopeWarnings = ownerScopeWarning === null ? [] : [ownerScopeWarning];
// Focus boost (within-tier only): computed once per candidate, 0 for
// every candidate when no active focus is supplied, so the default
@@ -560,6 +632,7 @@ export function packContext(vault: string, opts: ContextPackOptions): ContextPac
...withOptionalLanes(opts, finalItems),
},
startedAtMs,
+ ownerScopeWarnings,
);
}
@@ -568,6 +641,13 @@ function finalizeContextPackReport(
opts: ContextPackOptions,
report: ContextPackReport,
startedAtMs: number,
+ /**
+ * Gate reports that are not per-item tension warnings, currently the
+ * owner-scope observation. Empty on every path that has no candidates
+ * to observe, so the `warnings` key stays absent and the pack stays
+ * byte-identical.
+ */
+ extraWarnings: ReadonlyArray<string> = [],
): ContextPackReport {
let enriched = report;
// Belief lifecycle suite (S2, t_0e3f2bee): flag any injected memory that
@@ -578,8 +658,18 @@ function finalizeContextPackReport(
vault,
report.items.map((item) => item.id),
);
- if (tensionWarnings.length > 0) {
- enriched = { ...enriched, warnings: tensionWarnings };
+ const warnings = [...extraWarnings, ...tensionWarnings];
+ if (warnings.length > 0) {
+ enriched = { ...enriched, warnings };
+ }
+ // Provenance stamp (context-integrity-gates, Unit B). Attached in the
+ // one funnel every return path already passes through, so the
+ // zero-budget early return is stamped exactly like the full pack and
+ // no future exit can forget it. Absent option β†’ absent key.
+ if (opts.stamp !== undefined) {
+ const stampSource =
+ opts.stamp.configPath !== undefined ? { configPath: opts.stamp.configPath } : {};
+ enriched = { ...enriched, stamp: buildPackStamp(vault, opts.stamp.now, stampSource) };
}
// Gated emissions route through the lazy emit kernel (t_5d7aa7c5):
// with the option absent the thunk never runs, and a broken
diff --git a/src/core/brain/context-receipts.ts b/src/core/brain/context-receipts.ts
index 8c103bf8..9ac6497d 100644
--- a/src/core/brain/context-receipts.ts
+++ b/src/core/brain/context-receipts.ts
@@ -1,10 +1,23 @@
import { createHash } from "node:crypto";
-import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
+import {
+ appendContinuityRecord,
+ isCanonicalUtcTimestamp,
+ listContinuityRecords,
+} from "./continuity/store.ts";
import type { ContinuityRecord } from "./continuity/types.ts";
import type { RecallAdequacyVerdict } from "./recall-adequacy.ts";
-export type ContextReceiptTrigger = "context_pack" | "pre_compress";
+/**
+ * What produced the injected context a receipt accounts for.
+ *
+ * `context_pack` and `pre_compress` are the two pack builders. Unit H of
+ * the context-integrity-gates wave adds `session_inject`: the SessionStart
+ * eager layer, which until now emitted context that nothing measured. The
+ * vocabulary is closed - a reader switching over it can enumerate every
+ * injection surface that exists.
+ */
+export type ContextReceiptTrigger = "context_pack" | "pre_compress" | "session_inject";
export interface ContextReceiptOptions {
readonly host: string;
@@ -19,6 +32,13 @@ export interface ContextReceiptItemInput {
readonly path?: string;
readonly text?: string;
readonly tokens?: number;
+ /**
+ * UTF-8 byte size of the item. Tokens are an estimate derived from
+ * bytes; recording both keeps the estimate auditable against the exact
+ * measurement it came from. Optional, so a caller that has no byte
+ * figure records exactly what it knows.
+ */
+ readonly bytes?: number;
readonly tier?: string;
readonly trimmed?: boolean;
readonly safetyFiltered?: boolean;
@@ -92,6 +112,7 @@ export function emitContextReceipt(
original_rank: index + 1,
...(item.path ? { path: item.path } : {}),
...(item.tokens !== undefined ? { tokens: item.tokens } : {}),
+ ...(item.bytes !== undefined ? { bytes: item.bytes } : {}),
...(item.tier ? { tier: item.tier } : {}),
...(item.trimmed !== undefined ? { trimmed: item.trimmed } : {}),
...(item.safetyFiltered !== undefined ? { safety_filtered: item.safetyFiltered } : {}),
@@ -152,6 +173,249 @@ export function listContextReceipts(
return Object.freeze(receipts);
}
+// ----- session-scoped fold (context-integrity-gates, Unit I) --------------
+
+/**
+ * Default ceiling on how many receipts one fold AGGREGATES.
+ *
+ * It is a fold bound, not a scan bound, and the docblock said otherwise
+ * for exactly as long as nobody measured it. Every receipt matching the
+ * window is read into memory first and the bound is applied afterwards,
+ * so the read cost is set by `since` / `until` (which do skip whole
+ * month shards) and by nothing else. Two consequences worth stating:
+ * lowering `maxReceipts` makes the REPORT smaller, never the read; and
+ * the observed-use join the MCP surface performs alongside this fold
+ * walks the same window again through `observedReuseRates`.
+ *
+ * A real scan bound was considered and rejected. It would mean reading
+ * shards newest-first with an early exit, which changes
+ * `listContinuityRecords` for every caller and changes what `truncated`
+ * asserts - from "more receipts matched than were folded" to "the read
+ * stopped early", which cannot report a total at all. The bound that
+ * exists is honest about what it does: exceeding it is REPORTED
+ * (`truncated`) rather than silently returning a prefix as if it were
+ * the complete answer.
+ */
+export const CONTEXT_RECEIPT_FOLD_MAX_RECEIPTS = 500;
+
+export interface ContextReceiptFoldFilter {
+ readonly trigger?: ContextReceiptTrigger;
+ readonly host?: string;
+ readonly sessionId?: string;
+ /** Inclusive lower bound on `createdAt` (canonical UTC ISO-8601). */
+ readonly since?: string;
+ /** Inclusive upper bound on `createdAt` (canonical UTC ISO-8601). */
+ readonly until?: string;
+ /** Fold bound; defaults to {@link CONTEXT_RECEIPT_FOLD_MAX_RECEIPTS}. */
+ readonly maxReceipts?: number;
+}
+
+/**
+ * A window bound was not a canonical UTC timestamp.
+ *
+ * `since` and `until` are compared LEXICALLY against stored `createdAt`
+ * strings, which is correct for the canonical form and meaningless for
+ * anything else: `"yesterday"` sorts after every `2026-…` timestamp, so
+ * it filters the window down to nothing and the fold reports "no
+ * receipts recorded for this filter". Reporting "nothing happened" for
+ * malformed input is precisely the failure this wave exists to remove,
+ * so a bound that cannot mean what it says is refused instead.
+ */
+export class ContextReceiptWindowError extends Error {
+ /** `since` or `until`. */
+ readonly field: string;
+
+ constructor(field: string, value: string) {
+ super(
+ `context receipt window: ${field} must be a canonical UTC ISO-8601 timestamp ` +
+ `(YYYY-MM-DDTHH:MM:SS[.sss]Z with a real calendar date), got ${JSON.stringify(value)}`,
+ );
+ this.name = "ContextReceiptWindowError";
+ this.field = field;
+ }
+}
+
+/** Throw {@link ContextReceiptWindowError} unless `value` can be compared. */
+export function assertContextReceiptWindowBound(field: string, value: string | undefined): void {
+ if (value === undefined) return;
+ if (!isCanonicalUtcTimestamp(value)) throw new ContextReceiptWindowError(field, value);
+}
+
+/** One artifact's injection history across the folded receipts. */
+export interface ContextReceiptItemUsage {
+ readonly id: string;
+ /** Vault-relative path, when the receipts recorded one. */
+ readonly path?: string;
+ /** How many of the folded receipts injected this artifact. */
+ readonly injections: number;
+ /** Summed recorded token cost across those injections. */
+ readonly tokens: number;
+}
+
+/**
+ * The filtered window held no receipts at all.
+ *
+ * This is a DIFFERENT statement from "every counter is zero", and the
+ * difference is the point: receipt emission is opt-in, so a vault where
+ * nobody asked for receipts has recorded nothing, and reporting counts
+ * of zero would present the absence of a mechanism as a finding about
+ * retrieval. The shape carries no counters, so a consumer cannot read
+ * one without first branching on `recorded`.
+ */
+export interface ContextReceiptFoldEmpty {
+ readonly recorded: false;
+ readonly max_receipts: number;
+}
+
+/** The fold over a non-empty window. */
+export interface ContextReceiptFoldResult {
+ readonly recorded: true;
+ /** Receipts folded, including any withheld from item aggregation. */
+ readonly receipt_count: number;
+ /** Total item occurrences across the aggregated receipts. */
+ readonly item_total: number;
+ /** Distinct artifacts behind those occurrences. */
+ readonly distinct_items: number;
+ /** Per-artifact frequency and token cost, most-injected first. */
+ readonly items: ReadonlyArray<ContextReceiptItemUsage>;
+ /**
+ * Receipts the redactor flagged private or redacted. They are counted
+ * but never unfolded, so redacted content cannot re-enter the vault
+ * through an aggregate. The three item figures above describe the
+ * remaining receipts only.
+ */
+ readonly withheld_receipts: number;
+ /**
+ * Folded receipts that recorded an EMPTY item array.
+ *
+ * A real and expected shape, not a defect: the SessionStart meter
+ * writes `items: []` whenever the injection loader degraded to its
+ * last-good cache, because the sub-bodies it would have attributed
+ * were never emitted. They inflate `receipt_count` while contributing
+ * nothing to the item figures, so they are counted here rather than
+ * disappearing into the difference between two other numbers.
+ */
+ readonly empty_receipts: number;
+ /**
+ * Folded receipts whose `items` field is absent or not an array. A
+ * receipt that cannot be unfolded at all - distinct from one that
+ * deliberately carried nothing.
+ */
+ readonly malformed_receipts: number;
+ /** True when the fold bound cut the input; the figures are a prefix. */
+ readonly truncated: boolean;
+ readonly max_receipts: number;
+}
+
+export type ContextReceiptFold = ContextReceiptFoldEmpty | ContextReceiptFoldResult;
+
+/**
+ * Join `context_receipt` records across a window into one retrieval
+ * picture: how many injections happened, how many distinct artifacts
+ * they carried, and how often and how expensively each one was injected.
+ *
+ * Read-only. Every field folded here was already durable on the record;
+ * what did not exist was the join - `listContextReceipts` has only ever
+ * mapped one summary per record, so nothing could answer "what did this
+ * session actually keep re-injecting?".
+ */
+export function summarizeContextReceiptSession(
+ vault: string,
+ filter: ContextReceiptFoldFilter = {},
+): ContextReceiptFold {
+ assertContextReceiptWindowBound("since", filter.since);
+ assertContextReceiptWindowBound("until", filter.until);
+ const maxReceipts = Math.max(
+ 1,
+ Math.floor(filter.maxReceipts ?? CONTEXT_RECEIPT_FOLD_MAX_RECEIPTS),
+ );
+ const matched = listContinuityRecords(vault, {
+ kind: "context_receipt",
+ ...(filter.since !== undefined ? { since: filter.since } : {}),
+ ...(filter.until !== undefined ? { until: filter.until } : {}),
+ })
+ .filter((record) =>
+ matchesReceiptFilter(record, {
+ ...(filter.trigger !== undefined ? { trigger: filter.trigger } : {}),
+ ...(filter.host !== undefined ? { host: filter.host } : {}),
+ ...(filter.sessionId !== undefined ? { sessionId: filter.sessionId } : {}),
+ }),
+ )
+ .toReversed();
+
+ if (matched.length === 0) {
+ return Object.freeze({ recorded: false as const, max_receipts: maxReceipts });
+ }
+
+ const folded = matched.slice(0, maxReceipts);
+ const usage = new Map<string, { path?: string; injections: number; tokens: number }>();
+ let itemTotal = 0;
+ let withheld = 0;
+ let emptyReceipts = 0;
+ let malformedReceipts = 0;
+
+ for (const record of folded) {
+ if (record.private || record.redacted) {
+ withheld += 1;
+ continue;
+ }
+ const items = record.payload["items"];
+ if (!Array.isArray(items)) {
+ malformedReceipts += 1;
+ continue;
+ }
+ if (items.length === 0) emptyReceipts += 1;
+ for (const raw of items) {
+ if (raw === null || typeof raw !== "object") continue;
+ const item = raw as Record<string, unknown>;
+ const id = item["id"];
+ if (typeof id !== "string" || id.length === 0) continue;
+ itemTotal += 1;
+ const path = typeof item["path"] === "string" ? item["path"] : undefined;
+ const tokens = typeof item["tokens"] === "number" ? item["tokens"] : 0;
+ const current = usage.get(id) ?? { injections: 0, tokens: 0 };
+ current.injections += 1;
+ current.tokens += tokens;
+ if (current.path === undefined && path !== undefined) current.path = path;
+ usage.set(id, current);
+ }
+ }
+
+ const items = [...usage.entries()]
+ .map(([id, entry]) =>
+ Object.freeze({
+ id,
+ ...(entry.path !== undefined ? { path: entry.path } : {}),
+ injections: entry.injections,
+ tokens: entry.tokens,
+ }),
+ )
+ // Codepoint order for the id tiebreak, not `localeCompare`: the
+ // comparison must be reproducible across hosts, and ICU collation
+ // varies with the runtime locale, so the same receipts could fold to a
+ // different item order on two machines. Matches `stamp.ts` and
+ // `link-ratchet.ts`, which take the same decision for the same reason.
+ .toSorted(
+ (a, b) =>
+ b.injections - a.injections ||
+ b.tokens - a.tokens ||
+ (a.id < b.id ? -1 : a.id > b.id ? 1 : 0),
+ );
+
+ return Object.freeze({
+ recorded: true as const,
+ receipt_count: folded.length,
+ item_total: itemTotal,
+ distinct_items: usage.size,
+ items: Object.freeze(items),
+ withheld_receipts: withheld,
+ empty_receipts: emptyReceipts,
+ malformed_receipts: malformedReceipts,
+ truncated: matched.length > folded.length,
+ max_receipts: maxReceipts,
+ });
+}
+
export function getContextReceipt(vault: string, id: string): ContinuityRecord | null {
return (
listContinuityRecords(vault, { kind: "context_receipt" }).find((record) => record.id === id) ??
@@ -188,9 +452,16 @@ function adequacySummary(
}
export function isContextReceiptTrigger(value: unknown): value is ContextReceiptTrigger {
- return value === "context_pack" || value === "pre_compress";
+ return value === "context_pack" || value === "pre_compress" || value === "session_inject";
}
+/** Every trigger, in declaration order, for schemas and error messages. */
+export const CONTEXT_RECEIPT_TRIGGERS: ReadonlyArray<ContextReceiptTrigger> = Object.freeze([
+ "context_pack",
+ "pre_compress",
+ "session_inject",
+]);
+
function sha256(text: string): string {
return createHash("sha256").update(text, "utf8").digest("hex");
}
diff --git a/src/core/brain/continuity/store.ts b/src/core/brain/continuity/store.ts
index 0defe6ab..99043a95 100644
--- a/src/core/brain/continuity/store.ts
+++ b/src/core/brain/continuity/store.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { BRAIN_LOG_REL, ensureInsideVault } from "../paths.ts";
import { acquireLockSync } from "../sync-lockfile.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { safeContinuityPayload } from "./redaction.ts";
import { CLIP_PROTECTED_PAYLOAD_KEYS, CONTINUITY_SCHEMA_VERSION } from "./types.ts";
import type {
@@ -138,6 +139,11 @@ export function appendContinuityRecords(
throw new Error("appendContinuityRecords: inputs must be a non-empty array");
}
+ // Vault-identity write guard (context-integrity-gates, Unit J),
+ // ahead of the phase-3 shard appends. Backs `brain_session_checkpoint`
+ // and every telemetry writer that funnels through the continuity log.
+ assertVaultIdentityForWrite(vault);
+
// Phase 1 β€” build + validate ALL records before any disk mutation.
// buildRecord sanitises payloads; continuityLogPath validates the month
// prefix and throws on a malformed createdAt. Any throw here aborts the
@@ -276,6 +282,10 @@ function buildRecord(
}
function appendRecord(vault: string, record: ContinuityRecord): ContinuityRecord {
+ // Vault-identity write guard (context-integrity-gates, Unit J). The
+ // single-record funnel: guarding here covers every public entry point
+ // that appends one record rather than a batch.
+ assertVaultIdentityForWrite(vault);
const path = continuityLogPath(vault, record.createdAt.slice(0, 7));
mkdirSync(join(vault, CONTINUITY_REL), { recursive: true });
const handle = acquireLockSync(path);
diff --git a/src/core/brain/dead-ends.ts b/src/core/brain/dead-ends.ts
index b136a412..285f7385 100644
--- a/src/core/brain/dead-ends.ts
+++ b/src/core/brain/dead-ends.ts
@@ -18,6 +18,7 @@ import { parseFrontmatterText, slugify, writeFrontmatterAtomic } from "../vault.
import type { FrontmatterMap } from "../types.ts";
import { allocateSlug } from "./paths.ts";
import { isoDate, isoSecond } from "./time.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** Active dead-ends kept before overflow archives the oldest. */
export const DEAD_END_MAX_ACTIVE = 100;
@@ -82,6 +83,8 @@ function renderBody(approach: string, reason: string, context: string | null): s
* suffixes, matching the signal naming discipline.
*/
export function recordDeadEnd(vault: string, input: RecordDeadEndInput): RecordDeadEndResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const approach = sanitiseTextField(input.approach, {
maxLen: APPROACH_MAX_LEN,
singleLine: true,
diff --git a/src/core/brain/decisions/receipts.ts b/src/core/brain/decisions/receipts.ts
index 45c42073..1559e206 100644
--- a/src/core/brain/decisions/receipts.ts
+++ b/src/core/brain/decisions/receipts.ts
@@ -30,6 +30,7 @@ import { join } from "node:path";
import { resolveDeviceId } from "../../config.ts";
import { appendLogEvent } from "../log.ts";
import { BRAIN_LOG_EVENT_KIND } from "../types.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Schema tag stamped on every receipt line. */
export const DECISION_CHANGE_SCHEMA_VERSION = "decision_change.v1";
@@ -217,6 +218,8 @@ export function appendDecisionChangeReceipt(
vault: string,
input: AppendReceiptInput,
): AppendReceiptResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
// Closed-schema gate: reject any unexpected field before doing anything.
for (const key of Object.keys(input)) {
if (!ALLOWED_INPUT_KEYS.has(key)) {
diff --git a/src/core/brain/decisions/record.ts b/src/core/brain/decisions/record.ts
index 93617979..c8fd7f95 100644
--- a/src/core/brain/decisions/record.ts
+++ b/src/core/brain/decisions/record.ts
@@ -32,6 +32,7 @@ import { parseFrontmatter, slugify } from "../../vault.ts";
import { appendLogEvent } from "../log.ts";
import { addObligation } from "../obligations.ts";
import { decisionPath, decisionsDir, obligationPath, validateIsoDate } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { jaccard, tokenise } from "../similarity.ts";
import { isoSecond } from "../time.ts";
import { BRAIN_LOG_EVENT_KIND, type BrainCommitmentTier } from "../types.ts";
@@ -348,6 +349,8 @@ export function ensureReviewObligation(
vault: string,
input: { title: string; reviewDate: string; agent: string; now?: Date },
): { slug: string; created: boolean } {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const obligationTitle = reviewObligationTitle(input.title);
const slug = slugify(obligationTitle);
if (existsSync(obligationPath(vault, slug))) {
@@ -371,6 +374,8 @@ export function ensureReviewObligation(
* existing decision slug (an update is a distinct, later operation).
*/
export function recordDecision(vault: string, input: RecordDecisionInput): RecordDecisionResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const title = requireField(input.title, "title");
const chosen = requireField(input.chosen, "chosen");
const assumption = requireField(input.assumption, "assumption");
@@ -456,6 +461,8 @@ export function recordDecision(vault: string, input: RecordDecisionInput): Recor
* an empty outcome with a typed error.
*/
export function backfillOutcome(vault: string, input: BackfillOutcomeInput): DecisionRecord {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const slug = slugify(input.slug);
const prior = parsePage(vault, slug);
if (prior === null) throw new DecisionError(`no decision: ${slug}`);
@@ -506,6 +513,8 @@ export function backfillOutcome(vault: string, input: BackfillOutcomeInput): Dec
* Rejects an unknown slug or an out-of-range rating with a typed error.
*/
export function updateRating(vault: string, input: UpdateRatingInput): DecisionRecord {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const slug = slugify(input.slug);
const prior = parsePage(vault, slug);
if (prior === null) throw new DecisionError(`no decision: ${slug}`);
diff --git a/src/core/brain/deep-synthesis.ts b/src/core/brain/deep-synthesis.ts
index f3b07d44..54a51efe 100644
--- a/src/core/brain/deep-synthesis.ts
+++ b/src/core/brain/deep-synthesis.ts
@@ -222,6 +222,14 @@ export interface DeepSynthesisOptions {
readonly limit?: number;
/** A matched note older than this counts as a stale claim. Default 90. */
readonly staleAgeDays?: number;
+ /**
+ * Owner-scope isolation (context-integrity-gates, Unit A). Threaded
+ * straight into `SearchOptions.agentScope`, so an owner-private page
+ * is returned only to its own scope and an ownerless page always is.
+ * Omitted / blank applies no ownership filtering, which keeps an
+ * unscoped call byte-identical.
+ */
+ readonly agentScope?: string;
}
const CHECKED = Object.freeze([
@@ -358,7 +366,12 @@ export async function deepSynthesis(
// can produce many chunks, and capping before the per-document
// dedupe would let it crowd every other note out of the dossier.
const rawLimit = Math.min(100, Math.max(limit * 3, limit));
- const outcome = await search(config, { query: topic, limit: rawLimit, keywordOnly: true });
+ const outcome = await search(config, {
+ query: topic,
+ limit: rawLimit,
+ keywordOnly: true,
+ ...(opts.agentScope !== undefined ? { agentScope: opts.agentScope } : {}),
+ });
// Dedupe chunk hits into per-document notes (best score wins), THEN
// apply the note limit.
diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.ts
index 35d1b99c..9b549560 100644
--- a/src/core/brain/diagnostics.ts
+++ b/src/core/brain/diagnostics.ts
@@ -54,6 +54,7 @@ import { acquireLockSync } from "./sync-lockfile.ts";
import { isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
import { normaliseWikilinkTarget } from "./wikilink.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
// ----- Diagnostics-signal model --------------------------------------------
@@ -561,6 +562,9 @@ export interface ApplyRepairOptions {
* changed disk. Idempotent: a second non-dry-run call finds nothing to do.
*/
export function applyRepair(vault: string, opts: ApplyRepairOptions): RepairOutcome {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ // A dry run previews and writes nothing, so it stays ungated.
+ 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);
diff --git a/src/core/brain/digest.ts b/src/core/brain/digest.ts
index fbce4c2d..4d57ee7c 100644
--- a/src/core/brain/digest.ts
+++ b/src/core/brain/digest.ts
@@ -51,7 +51,13 @@ import {
loadBrainConfig,
} from "./policy.ts";
import { normaliseWikilinkTarget, renderPrefLink, type LinkOutputFormat } from "./wikilink.ts";
-import { parsePreference, parseRetired } from "./preference.ts";
+import { parseRetired } from "./preference.ts";
+import {
+ collectPreferences,
+ PREFERENCE_ID_PREFIX,
+ resolveOwnerScopeDelivery,
+} from "./preferences-collect.ts";
+import { isPreferenceVisible } from "./owner-scoped-facts.ts";
import type { BrainLogEntry } from "./log.ts";
import { listLogDates, readLogDay } from "./log-jsonl.ts";
import {
@@ -93,6 +99,13 @@ export interface RenderDigestOptions {
* counterparts on the summary instead of defaulting to zero.
*/
readonly dreamSummary?: import("./dream.ts").DreamRunSummary;
+ /**
+ * Owner scope for delivery isolation (context-integrity-gates, Unit
+ * A). Enforced only when `integrity.owner_scope_delivery` is `fail`;
+ * omitted, or under the default `off`, nothing is filtered and the
+ * output is byte-identical to a vault without the gate.
+ */
+ readonly agentScope?: string;
}
export interface RenderDigestResult {
@@ -327,7 +340,7 @@ export function renderDigest(vault: string, opts: RenderDigestOptions = {}): Ren
);
}
- const data = collectDigestData(vault, since, until);
+ const data = collectDigestData(vault, since, until, opts.agentScope);
const empty = isEmpty(data);
if (format === "json") {
@@ -419,7 +432,12 @@ interface DigestData {
readonly actions: ReadonlyArray<ActionItem>;
}
-function collectDigestData(vault: string, since: Date, until: Date): DigestData {
+function collectDigestData(
+ vault: string,
+ since: Date,
+ until: Date,
+ agentScope: string | undefined,
+): DigestData {
const sinceMs = since.getTime();
const untilMs = until.getTime();
const inWindow = (iso: string | null): boolean => {
@@ -431,7 +449,7 @@ function collectDigestData(vault: string, since: Date, until: Date): DigestData
// 1. Iterate preferences/ for unconfirmed (created_at in window) and
// confirmed (confirmed_at in window).
- const preferences = readAllPreferences(vault);
+ const preferences = readAllPreferences(vault, agentScope);
const new_unconfirmed: DigestJsonNewUnconfirmed[] = [];
const confirmed: DigestJsonConfirmed[] = [];
@@ -461,7 +479,7 @@ function collectDigestData(vault: string, since: Date, until: Date): DigestData
// 2. Iterate retired/ for entries retired in window.
const retiredEntries: DigestJsonRetired[] = [];
- const retiredAll = readAllRetired(vault);
+ const retiredAll = readAllRetired(vault, agentScope);
for (const { ret, path } of retiredAll) {
void path;
if (inWindow(ret.retired_at)) {
@@ -696,21 +714,21 @@ interface PreferenceWithPath {
readonly path: string;
}
-function readAllPreferences(vault: string): ReadonlyArray<PreferenceWithPath> {
+function readAllPreferences(
+ vault: string,
+ agentScope: string | undefined,
+): ReadonlyArray<PreferenceWithPath> {
const dirs = brainDirs(vault);
- if (!existsSync(dirs.preferences)) return [];
- const out: PreferenceWithPath[] = [];
- for (const entry of readdirSync(dirs.preferences, { withFileTypes: true })) {
- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
- if (!entry.name.startsWith("pref-")) continue;
- const path = join(dirs.preferences, entry.name);
- try {
- out.push({ pref: parsePreference(path), path });
- } catch {
- // The doctor reports corruption; digest skips silently.
- }
- }
- return out;
+ // Shared delivery-path walk (context-integrity-gates, Unit A). This
+ // surface's listing is the strictest of the five - regular files only,
+ // and only `pref-*` names - so both rules are passed as options rather
+ // than unified away. The doctor reports corruption; digest skips
+ // silently, which is what the collector's parse already does.
+ return collectPreferences(dirs.preferences, {
+ namePrefix: PREFERENCE_ID_PREFIX,
+ regularFilesOnly: true,
+ ownerScope: resolveOwnerScopeDelivery(vault, agentScope),
+ }).entries.map(({ pref, path }) => ({ pref, path }));
}
interface RetiredWithPath {
@@ -718,16 +736,28 @@ interface RetiredWithPath {
readonly path: string;
}
-function readAllRetired(vault: string): ReadonlyArray<RetiredWithPath> {
+/**
+ * Retirement KEEPS ownership (context-integrity-gates, A7): a retired
+ * memory is withdrawn from the active set, never published to every
+ * agent. Same gate resolution as {@link readAllPreferences}, so an
+ * unscoped digest is byte-identical.
+ */
+function readAllRetired(
+ vault: string,
+ agentScope: string | undefined,
+): ReadonlyArray<RetiredWithPath> {
const dirs = brainDirs(vault);
if (!existsSync(dirs.retired)) return [];
+ const scope = resolveOwnerScopeDelivery(vault, agentScope).enforcedScope;
const out: RetiredWithPath[] = [];
for (const entry of readdirSync(dirs.retired, { withFileTypes: true })) {
if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
if (!entry.name.startsWith("ret-")) continue;
const path = join(dirs.retired, entry.name);
try {
- out.push({ ret: parseRetired(path), path });
+ const ret = parseRetired(path);
+ if (scope !== null && !isPreferenceVisible(ret, scope)) continue;
+ out.push({ ret, path });
} catch {
// ditto
}
diff --git a/src/core/brain/distill/distill-source.ts b/src/core/brain/distill/distill-source.ts
index a0fee166..e55c766e 100644
--- a/src/core/brain/distill/distill-source.ts
+++ b/src/core/brain/distill/distill-source.ts
@@ -27,6 +27,7 @@ import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { canonicalNotePath } from "../../path-safety.ts";
import { formatFrontmatter, parseFrontmatter, slugify } from "../../vault.ts";
import { distillationPagePath } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import {
renderProvenanceSection,
sourceIdentityHash,
@@ -129,6 +130,8 @@ export function distillSource(
input: DistillSourceInput,
opts: DistillSourceOptions,
): DistillSourceResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
validate(input);
const canonicalSource = canonicalNotePath(input.sourcePath);
diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.ts
index 83fa811f..f306bac2 100644
--- a/src/core/brain/doctor.ts
+++ b/src/core/brain/doctor.ts
@@ -41,7 +41,13 @@ import { join, relative } from "node:path";
import { realpathInsideVault, vaultRelative } from "../path-safety.ts";
import { REMOVED_TOOLS } from "../removed-surfaces.ts";
-import { extractWikilinks, listVaultBasenames, parseFrontmatter } from "../vault.ts";
+import type { DegradationNotice } from "../integrity/degradation.ts";
+import {
+ extractWikilinks,
+ listVaultBasenames,
+ listVaultPages,
+ parseFrontmatter,
+} from "../vault.ts";
import { computeActiveBudgetPressure } from "./active-budget-pressure.ts";
import { resolveVaultScope } from "../vault-scope/index.ts";
import { buildBacklinkIndex } from "./backlinks.ts";
@@ -52,6 +58,7 @@ import {
} from "./entities/semantic-dedup.ts";
import { findMalformedEntityLabels } from "./entities/label-hygiene.ts";
import { buildCaptureBoundary } from "./capture-boundary.ts";
+import { verifyLineageLedger } from "./lineage/verify.ts";
import { verifyContentHash } from "./content-hash.ts";
import { readTierDriftCount } from "./frontmatter-tiers.ts";
import { scanDanglingWorkruns } from "./dream-workrun.ts";
@@ -96,6 +103,8 @@ import {
type ResolvedBrainHealthConfig,
type TrustVerdict,
} from "./types.ts";
+import { scanStaleLocks } from "./sync-lockfile.ts";
+import { vaultMarkerAbsentNotice } from "./vault-identity.ts";
import { normaliseWikilinkTarget, parseArtifactRef } from "./wikilink.ts";
// ----- Public types ---------------------------------------------------------
@@ -203,21 +212,44 @@ export interface RunDoctorResult {
// ----- Entry point ----------------------------------------------------------
+/** Issue code for a resolved root that carries no Brain layer. */
+const BRAIN_ROOT_ABSENT_CODE = "brain-root-absent";
+
export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctorResult {
const issues: DoctorIssue[] = [];
const dirs = brainDirs(vault);
if (!existsSync(dirs.brain)) {
- // No Brain layer present is not an error here β€” `o2b brain init`
- // is the right command, but a vault without Brain is allowed in
- // v0.9. Return clean. v0.10.16: emit the new trust-layer fields
- // with their clean / empty defaults for shape symmetry with the
- // normal-return path.
+ // A root with no Brain layer is NOT clean (context-integrity-gates,
+ // Unit J). It is exactly the shape a mis-resolved vault takes, and
+ // reporting it as clean is what let a wrong root pass the one
+ // command an operator runs to check the store. It is still not an
+ // error - an un-initialized vault is legitimate - so it is reported
+ // as a named warning plus an `uncertain` entry: every check below
+ // was skipped, so nothing about this root has actually been
+ // verified.
+ const message =
+ `no Brain layer at ${dirs.brain}; run \`o2b brain init\` if this is the ` +
+ "intended vault, otherwise the resolved vault root is wrong";
return Object.freeze({
- warnings: Object.freeze([]),
+ warnings: Object.freeze([
+ {
+ severity: "warning",
+ code: BRAIN_ROOT_ABSENT_CODE,
+ path: dirs.brain,
+ message,
+ } satisfies DoctorIssue,
+ ]),
errors: Object.freeze([]),
- trust_verdict: "clean" as TrustVerdict,
+ trust_verdict: "watch" as TrustVerdict,
instruction_file_warnings: Object.freeze([]),
+ uncertain: Object.freeze([
+ {
+ code: BRAIN_ROOT_ABSENT_CODE,
+ path: dirs.brain,
+ message: "every Brain check was skipped: the layer is absent",
+ },
+ ]),
});
}
@@ -410,6 +442,54 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor
/* doctor never throws */
}
+ // Unit F: frontmatter lines the scanner dropped anywhere under
+ // Brain/. Reported as UNCERTAINTY, not as a warning or an error: the
+ // note is still on disk and still indexes, but the doctor cannot
+ // claim it verified every field it declared, because a field it
+ // could not read is indistinguishable from a field that is absent.
+ // (That ambiguity is exactly what produced the spurious
+ // `missing field: tags` errors fixed in 426d06f8.)
+ const uncertain: DoctorUncertainEntry[] = [];
+ try {
+ collectFrontmatterUncertainty(vault, uncertain);
+ } catch {
+ /* doctor never throws */
+ }
+
+ // Unit D: session-lineage ledger integrity - a line edited after it
+ // was written, a line removed from the middle, or an observation the
+ // writer could not append. Uncertainty rather than an error for the
+ // same reason as above: continuity still resolves from this ledger,
+ // but the doctor cannot claim the history it read is the history that
+ // was written.
+ try {
+ collectLineageLedgerUncertainty(vault, uncertain);
+ } catch {
+ /* doctor never throws */
+ }
+
+ // Unit J: a resolved root with no identity marker. An absent marker
+ // cannot tell an old vault from a wrong one, so it is uncertainty
+ // rather than a warning - but it is the exact shape a mis-resolved
+ // root takes, and the doctor reporting such a root clean is what let
+ // one pass the single command an operator runs to check the store.
+ try {
+ collectVaultMarkerUncertainty(vault, uncertain);
+ } catch {
+ /* doctor never throws */
+ }
+
+ // Lock files left behind by a crashed writer. `scanStaleLocks` has
+ // documented itself as "the brain doctor surfaces these" since it was
+ // written and had no caller: a SIGKILLed process leaves a `.lock` that
+ // no breaker may safely remove, so the ONLY recovery is an operator
+ // deleting it, and the only way that happens is if something names it.
+ try {
+ collectStaleLockUncertainty(vault, uncertain);
+ } catch {
+ /* doctor never throws */
+ }
+
// v0.14.0 semantic-health pass. Best-effort like every other lint:
// a failure here must not poison the structural warning / error
// stream. The report is attached to the result even on a clean run
@@ -468,10 +548,107 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor
trust_verdict: trustVerdict,
...(verificationCounts !== undefined ? { verification_delta_summary: verificationCounts } : {}),
instruction_file_warnings: instructionWarnings,
+ // Conditional so a clean vault's result - and therefore the CLI's
+ // `--json` payload - is byte-identical to the shape it had before
+ // this field had a producer.
+ ...(uncertain.length > 0 ? { uncertain: Object.freeze(uncertain) } : {}),
...(semanticReport !== undefined ? { semantic_health: semanticReport } : {}),
});
}
+/** Site recorded on the notices the doctor's Brain-tree sweep collects. */
+const DOCTOR_FRONTMATTER_SITE = "brain.doctor";
+
+/**
+ * Sweep every Markdown file under `Brain/` for frontmatter the line
+ * scanner could not express, and fold each notice into the doctor's
+ * `uncertain` stream.
+ *
+ * One walk, through the same shared helper every other converted site
+ * uses ({@link listVaultPages} with its opt-in notice sink), so there is
+ * no second definition of "what counts as a dropped line".
+ *
+ * Unlike an index run - which reads only the files whose mtime or size
+ * moved - this sweep is unconditional, which is what makes the doctor
+ * the complete view of the condition.
+ */
+function collectFrontmatterUncertainty(vault: string, out: DoctorUncertainEntry[]): void {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.brain)) return;
+ const notices: DegradationNotice[] = [];
+ listVaultPages(dirs.brain, { notices, site: DOCTOR_FRONTMATTER_SITE });
+ for (const notice of notices) {
+ out.push({
+ code: notice.code,
+ ...(notice.path !== undefined ? { path: notice.path } : {}),
+ message: notice.detail,
+ });
+ }
+}
+
+/**
+ * Fold every session-lineage ledger finding into the doctor's
+ * `uncertain` stream. The verifier is read-only and never throws, so
+ * this needs no guard of its own beyond the doctor's blanket one.
+ */
+function collectLineageLedgerUncertainty(vault: string, out: DoctorUncertainEntry[]): void {
+ const report = verifyLineageLedger(vault);
+ for (const notice of report.notices) {
+ out.push({
+ code: notice.code,
+ path: notice.path ?? report.path,
+ message: notice.detail,
+ });
+ }
+}
+
+/**
+ * Report a resolved root that carries no vault identity marker.
+ *
+ * The producer is pure, throws nothing, and treats a corrupt marker as
+ * absent - the same collapse `readVaultIdentity` performs, because a
+ * truncated sync must not be reported as a wrong vault.
+ */
+function collectVaultMarkerUncertainty(vault: string, out: DoctorUncertainEntry[]): void {
+ const notice = vaultMarkerAbsentNotice(vault);
+ if (notice === null) return;
+ out.push({
+ code: notice.code,
+ ...(notice.path !== undefined ? { path: notice.path } : {}),
+ message: notice.detail,
+ });
+}
+
+/** Code for a `.lock` file the doctor found under the Brain tree. */
+const STALE_LOCK_CODE = "stale-lock";
+
+/**
+ * Report every `.lock` file under `Brain/`.
+ *
+ * Deliberately NOT age-filtered and deliberately not removed. The lock
+ * primitive is a single-attempt exclusive create with no breaker, by
+ * design: no timeout can distinguish a crashed writer from a slow live
+ * one, and killing a live writer's lock corrupts what it protects. So
+ * this reports the condition and leaves the judgment to the operator -
+ * which is the whole reason a lock a crash left behind must be nameable
+ * at all. A lock held by a healthy concurrent writer shows up here too,
+ * and is uncertainty rather than a warning for exactly that reason.
+ */
+function collectStaleLockUncertainty(vault: string, out: DoctorUncertainEntry[]): void {
+ const dirs = brainDirs(vault);
+ if (!existsSync(dirs.brain)) return;
+ for (const lockPath of scanStaleLocks(dirs.brain)) {
+ out.push({
+ code: STALE_LOCK_CODE,
+ path: lockPath,
+ message:
+ "a writer lock is present; while it is held every write it guards is refused. " +
+ "If no process owns it (a crash leaves one behind) remove the file by hand - " +
+ "nothing breaks it automatically, because a live writer cannot be told from a dead one",
+ });
+ }
+}
+
// ----- Semantic health (v0.14.0) --------------------------------------------
/**
diff --git a/src/core/brain/dream-stage.ts b/src/core/brain/dream-stage.ts
index 8a775071..14299e6a 100644
--- a/src/core/brain/dream-stage.ts
+++ b/src/core/brain/dream-stage.ts
@@ -38,6 +38,7 @@ import { appendMetric } from "./metrics.ts";
import { brainDirs } from "./paths.ts";
import { dream, type DreamOptions, type DreamRunSummary } from "./dream.ts";
import { isoSecond } from "./time.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export const DREAM_STAGE_SCHEMA_VERSION = "o2b.dream-stage.v1";
@@ -239,6 +240,8 @@ function renderReport(runId: string, stagedAt: string, plan: DreamStagePlan): st
* Read-only against live Brain state.
*/
export function stageDream(vault: string, opts: DreamStageOptions): DreamStageBundle {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const summary = dream(vault, {
now: opts.now,
dryRun: true,
@@ -387,6 +390,8 @@ export function applyDreamBundle(
runId: string,
opts: DreamStageOptions,
): DreamStageApplyOutcome {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const validation = validateDreamBundle(vault, runId, opts);
if (!validation.valid) {
return Object.freeze({ applied: false, validation });
@@ -431,6 +436,8 @@ export function applyDreamBundle(
/** Remove one staged bundle. True when it existed. */
export function discardDreamBundle(vault: string, runId: string): boolean {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
if (!isValidRunId(runId)) return false;
const dir = join(stagedRoot(vault), runId);
if (!existsSync(dir)) return false;
diff --git a/src/core/brain/dream-workrun.ts b/src/core/brain/dream-workrun.ts
index 195e0ca6..adcf24b2 100644
--- a/src/core/brain/dream-workrun.ts
+++ b/src/core/brain/dream-workrun.ts
@@ -33,6 +33,7 @@ import {
import { dirname, join } from "node:path";
import { dreamRunsDir, dreamWorkrunPath } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/**
* Canonical phase identifiers. Five forward-progress phases plus the
@@ -73,6 +74,8 @@ export interface WorkrunHandle {
* phase. Creates the workrun directory on demand.
*/
export function openWorkrun(vault: string, runId: string): WorkrunHandle {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = dreamWorkrunPath(vault, runId);
mkdirSync(dirname(path), { recursive: true });
let closed = false;
diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.ts
index aad031fd..683eb7ea 100644
--- a/src/core/brain/dream.ts
+++ b/src/core/brain/dream.ts
@@ -70,6 +70,7 @@ import { loadBrainConfig, resolveGuardrails } from "./policy.ts";
import { applySelfApprovalGuardrail } from "./trust/self-approval-guardrail.ts";
import {
brainDirs,
+ brainDirsForWrite,
dreamWorkrunPath,
preferencePath,
processedSignalPath,
@@ -942,7 +943,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {
...(snapshotPathStr ? { snapshot_path: snapshotPathStr } : {}),
...(dryRun
? { dry_run: true }
- : { log_path: join(brainDirs(vault).log, `${isoDate(now)}.md`) }),
+ : { log_path: join(brainDirsForWrite(vault).log, `${isoDate(now)}.md`) }),
} satisfies DreamRunSummary);
}
diff --git a/src/core/brain/entities/label-hygiene.ts b/src/core/brain/entities/label-hygiene.ts
index 54cab210..cd867941 100644
--- a/src/core/brain/entities/label-hygiene.ts
+++ b/src/core/brain/entities/label-hygiene.ts
@@ -26,6 +26,7 @@ import {
} from "./canonical.ts";
import { buildEntityIndex, type EntityIndex } from "./index-builder.ts";
import type { BrainEntity } from "./types.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Snapshot run-id label for a confirmed entity-label prune. */
export const ENTITY_PRUNE_SNAPSHOT_LABEL = "entity-prune";
@@ -198,6 +199,9 @@ export function pruneEntityLabels(
vault: string,
opts: PruneEntityLabelsOptions = {},
): PruneEntityLabelsResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ // Unconfirmed runs only list candidates, so they stay ungated.
+ if (opts.confirm === true) assertVaultIdentityForWrite(vault);
const denylist = opts.denylist ?? resolveEntityLabelDenylist(opts.configPath);
const candidates = findMalformedEntityLabels(vault, { denylist });
diff --git a/src/core/brain/entities/registry.ts b/src/core/brain/entities/registry.ts
index 602c7b52..bbeedcd3 100644
--- a/src/core/brain/entities/registry.ts
+++ b/src/core/brain/entities/registry.ts
@@ -20,6 +20,7 @@ import { isKnownRelation, normalizeRelation } from "../../graph/relation-vocab.t
import { normalizeRelationTarget } from "../../graph/frontmatter-relations.ts";
import { isoSecond } from "../time.ts";
import { entityPath } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import {
assertValidEntityLabel,
entityIdentityKey,
@@ -219,6 +220,8 @@ function allocateEntityId(index: EntityIndex, category: string, name: string): s
// ----- Operations ------------------------------------------------------------
export function upsertEntity(vault: string, input: UpsertEntityInput): UpsertEntityResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const category = validateEntityCategory(input.category);
// Label quality gate (A1): strip Markdown/punctuation decoration BEFORE
// normalisation and reject structurally-junk or denylisted names with a
@@ -314,6 +317,8 @@ export function upsertEntity(vault: string, input: UpsertEntityInput): UpsertEnt
}
export function relateEntities(vault: string, input: RelateEntitiesInput): BrainEntity {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const relation = normalizeRelation(input.relation);
if (!isKnownRelation(relation)) {
throw new Error(
@@ -362,6 +367,8 @@ export function archiveEntity(
ref: EntityRef,
opts: ArchiveEntityOptions,
): BrainEntity {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const index = buildEntityIndex(vault);
let target: BrainEntity | null;
if (opts.restore) {
diff --git a/src/core/brain/exact-state.ts b/src/core/brain/exact-state.ts
index 02f78b07..dd99ec26 100644
--- a/src/core/brain/exact-state.ts
+++ b/src/core/brain/exact-state.ts
@@ -23,6 +23,7 @@ import { atomicWriteFileSync } from "../fs-atomic.ts";
import { sanitiseTextField } from "../redactor.ts";
import { parseFrontmatterText } from "../vault.ts";
import { brainStateDir, exactStatePath, validateSlug } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** Frontmatter `kind` marking a page as an exact-state lane artifact. */
export const EXACT_STATE_KIND = "exact-state";
@@ -96,6 +97,8 @@ export function writeExactState(
value: unknown,
now: number = Date.now(),
): ExactStateEntry {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const slug = validateAspect(aspect);
const normalised = normaliseValue(value);
if (normalised.length > MAX_EXACT_STATE_VALUE_LEN) {
@@ -152,6 +155,8 @@ export function listExactState(vault: string): ExactStateEntry[] {
/** Remove an aspect. Returns whether it existed before the call. */
export function clearExactState(vault: string, aspect: string): boolean {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = exactStatePath(vault, validateAspect(aspect));
if (!existsSync(path)) return false;
rmSync(path, { force: true });
diff --git a/src/core/brain/fact-extract.ts b/src/core/brain/fact-extract.ts
index d25a9d9c..6f7f8114 100644
--- a/src/core/brain/fact-extract.ts
+++ b/src/core/brain/fact-extract.ts
@@ -32,7 +32,7 @@ import { BRAIN_LOG_EVENT_KIND, BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";
import { sanitiseTextField } from "../redactor.ts";
import { classifyDurability, resolveDurabilityDenylist } from "./gates/durability.ts";
import { resolveWriteApprovalEnabled } from "./pending.ts";
-import { brainDirs } from "./paths.ts";
+import { brainDirsForWrite } from "./paths.ts";
import type { DedupIndexEntry } from "./dedup-hash.ts";
import { buildEntityIndex } from "./entities/index-builder.ts";
import {
@@ -346,7 +346,7 @@ export function routeExtractedFacts(vault: string, input: RouteFactsInput): Rout
writeApprovalEnabled = false;
}
}
- const targetDir = writeApprovalEnabled ? brainDirs(vault).pending : undefined;
+ const targetDir = writeApprovalEnabled ? brainDirsForWrite(vault).pending : undefined;
for (const fact of input.facts) {
const hash = factDedupHash(fact);
diff --git a/src/core/brain/file-recall.ts b/src/core/brain/file-recall.ts
index f4d1d5a8..94e7daa0 100644
--- a/src/core/brain/file-recall.ts
+++ b/src/core/brain/file-recall.ts
@@ -29,6 +29,14 @@ export interface FileContextOptions {
readonly limit?: number;
/** Skip files smaller than this many bytes. Default 1500. */
readonly minBytes?: number;
+ /**
+ * Owner-scope isolation (context-integrity-gates, Unit A). Threaded
+ * straight into `SearchOptions.agentScope`, so an owner-private page
+ * is returned only to its own scope and an ownerless page always is.
+ * Omitted / blank applies no ownership filtering, which keeps an
+ * unscoped call byte-identical.
+ */
+ readonly agentScope?: string;
}
export interface FileContextResult {
@@ -90,7 +98,11 @@ export async function fileContextRecall(
return frozenResult(opts.filePath, true, "below_size_gate", query, []);
}
- const outcome = await search(config, { query, limit });
+ const outcome = await search(config, {
+ query,
+ limit,
+ ...(opts.agentScope !== undefined ? { agentScope: opts.agentScope } : {}),
+ });
return frozenResult(opts.filePath, false, null, query, outcome.results);
}
diff --git a/src/core/brain/gaps/gap-loop.ts b/src/core/brain/gaps/gap-loop.ts
index 66b9fb5a..2970c601 100644
--- a/src/core/brain/gaps/gap-loop.ts
+++ b/src/core/brain/gaps/gap-loop.ts
@@ -23,6 +23,7 @@ import { existsSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { brainGapTasksDir, BRAIN_GAP_TASKS_REL } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { summarizeRecallTelemetry } from "../recall-telemetry.ts";
import { renderActivityTimeline, type ActivityItem } from "../render/activity-line.ts";
import type { RecallRetriever } from "../recall-inject.ts";
@@ -94,6 +95,8 @@ export function promoteGapsToTasks(
vault: string,
opts: { threshold?: number; now: Date },
): GapPromotionResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const dir = brainGapTasksDir(vault);
const created: string[] = [];
const skipped: string[] = [];
@@ -213,6 +216,10 @@ export async function autoCloseRecalledGaps(
retriever: RecallRetriever,
opts: { confidenceFloor?: number; now: Date },
): Promise<GapAutoCloseResult> {
+ // Vault-identity write guard (context-integrity-gates, Unit J), like
+ // its sibling `promoteGapsToTasks`: closing a task rewrites the note's
+ // frontmatter, so it is a write path, not a read.
+ assertVaultIdentityForWrite(vault);
const floor = opts.confidenceFloor ?? GAP_LOOP_AUTO_CLOSE_FLOOR;
const closed: string[] = [];
const kept: string[] = [];
diff --git a/src/core/brain/git/decisions.ts b/src/core/brain/git/decisions.ts
index 4f323b6c..2a8adb25 100644
--- a/src/core/brain/git/decisions.ts
+++ b/src/core/brain/git/decisions.ts
@@ -21,6 +21,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { listGitCommits } from "./store.ts";
import type { GitCommitRecord } from "./store.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
const CONVENTIONAL_BREAKING_RE = /^[a-z]+(\([^)]*\))?!:/;
const REVERT_RE = /^revert\b/i;
@@ -108,6 +109,8 @@ export interface MineCommitDecisionsResult {
/** Mine one repo's ingested commits into ADR candidate notes. */
export function mineCommitDecisions(vault: string, repoKey: string): MineCommitDecisionsResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const commits = listGitCommits(vault, repoKey);
const dir = join(vault, "Brain", "decisions", "candidates");
let created = 0;
diff --git a/src/core/brain/git/ingest.ts b/src/core/brain/git/ingest.ts
index 33da3796..84f8db69 100644
--- a/src/core/brain/git/ingest.ts
+++ b/src/core/brain/git/ingest.ts
@@ -39,6 +39,7 @@ import {
writeGitState,
} from "./store.ts";
import type { GitCommitRecord, GitRecord, GitTagRecord } from "./store.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const DEFAULT_MAX_COUNT = 1000;
@@ -110,6 +111,8 @@ export function ingestGitHistory(
repoPath: string,
opts: IngestGitHistoryOptions = {},
): IngestGitHistoryResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const repo = resolve(repoPath);
const key = deriveRepoKey(repo);
const maxCount = opts.maxCount ?? DEFAULT_MAX_COUNT;
diff --git a/src/core/brain/git/reader.ts b/src/core/brain/git/reader.ts
index 160b8d14..1f9b41eb 100644
--- a/src/core/brain/git/reader.ts
+++ b/src/core/brain/git/reader.ts
@@ -83,11 +83,34 @@ function isGitRepo(repoPath: string): boolean {
return existsSync(join(resolve(repoPath), ".git"));
}
-function runGit(repoPath: string, args: ReadonlyArray<string>): string | null {
+interface RunGitOptions {
+ /**
+ * Hard wall-clock bound for this invocation. Absent means "no bound",
+ * which is the historical behaviour every pre-existing caller keeps.
+ * A bounded caller (the workspace probe below, which runs inside a
+ * hook's process ceiling) passes the remaining slice of its budget.
+ */
+ readonly timeoutMs?: number;
+ /** Discard git's stderr instead of inheriting the parent's. */
+ readonly quiet?: boolean;
+}
+
+function runGit(
+ repoPath: string,
+ args: ReadonlyArray<string>,
+ opts: RunGitOptions = {},
+): string | null {
try {
return execFileSync("git", ["-C", resolve(repoPath), ...args], {
encoding: "utf8",
maxBuffer: 64 * 1024 * 1024,
+ // SIGKILL rather than SIGTERM: a git process wedged on a stalled
+ // network filesystem is exactly the case the bound exists for, and
+ // it is the case least likely to honour a polite signal.
+ ...(opts.timeoutMs !== undefined
+ ? { timeout: opts.timeoutMs, killSignal: "SIGKILL" as const }
+ : {}),
+ ...(opts.quiet === true ? { stdio: ["ignore", "pipe", "ignore"] as const } : {}),
});
} catch {
// Fail-soft: a broken repo / missing git binary reads as "no
@@ -210,6 +233,144 @@ export function revListRange(
return Object.freeze(raw.split("\n").filter((line) => isFullSha(line.trim())));
}
+// ----- Workspace identity (context-integrity-gates, Unit C) ----------------
+//
+// Session continuation needs to know whether two lifecycle observations
+// happened in the SAME working state, not merely under the same `cwd`
+// string. Repo, branch and commit are that state.
+
+/**
+ * What a working directory can attest about itself. Every field is
+ * explicitly `null` when git could not report it (no remote, detached
+ * HEAD, unborn branch), never absent - a caller comparing two
+ * identities must be able to distinguish "not attested" from "attested
+ * differently" without probing for key presence.
+ */
+export interface GitWorkspaceIdentity {
+ /** Canonical remote identity - see {@link canonicalizeGitRemote}. */
+ readonly repo: string | null;
+ /** Short branch name; `null` on a detached HEAD. */
+ readonly branch: string | null;
+ /** Full 40-hex commit sha; `null` on an unborn branch. */
+ readonly commit: string | null;
+}
+
+/** Default wall-clock bound for the whole workspace probe. */
+export const GIT_PROBE_TIMEOUT_MS = 2_000;
+
+/** `HEAD` is what `--abbrev-ref` prints for a detached checkout. */
+const DETACHED_HEAD_REF = "HEAD";
+
+/** `user@host:path` - the scp-like remote syntax, which is not a URL. */
+const SCP_REMOTE_RE = /^(?<user>[^\s/@]+)@(?<host>[^\s/:]+):(?<path>(?!\/).+)$/;
+
+/** A trailing `.git`, with or without trailing slashes already stripped. */
+const DOT_GIT_SUFFIX_RE = /\.git$/;
+
+/**
+ * Reduce a git remote URL to a COMPARABLE repository identity of the
+ * form `scheme://host/org/repo`, or `null` when the input names no
+ * repository.
+ *
+ * This is a canonicalizer, NOT a redactor. `redactor.ts` rewrites
+ * embedded credentials to a placeholder, which is right for a log and
+ * useless as an identity key: two clones carrying different tokens
+ * would produce the same placeholder string but a different one from a
+ * credential-free clone of the same repository. Here userinfo, port, a
+ * `.git` suffix and trailing slashes are normalized AWAY, so all three
+ * clones compare equal - and, as a direct consequence, the credential
+ * cannot survive into any recorded field.
+ *
+ * Host case is normalized (DNS is case-insensitive); path case is not
+ * (many forges are case-sensitive, and folding it would merge two
+ * genuinely distinct repositories).
+ */
+export function canonicalizeGitRemote(raw: unknown): string | null {
+ if (typeof raw !== "string") return null;
+ const trimmed = raw.trim();
+ if (trimmed.length === 0) return null;
+
+ const url = parseRemote(trimmed);
+ if (url === null) return null;
+ // A URL-shaped string with no authority is not a remote - except for
+ // `file:`, whose authority is empty by construction.
+ const isFile = url.protocol === "file:";
+ if (!isFile && url.hostname.length === 0) return null;
+
+ const path = canonicalRemotePath(url.pathname);
+ if (path === null) return null;
+ return `${url.protocol}//${url.hostname}${path}`;
+}
+
+function parseRemote(value: string): URL | null {
+ const scp = SCP_REMOTE_RE.exec(value);
+ if (scp?.groups !== undefined) {
+ return safeUrl(`ssh://${scp.groups["host"]}/${scp.groups["path"]}`);
+ }
+ // An absolute filesystem path is a legitimate git remote and is not a
+ // URL; give it the `file:` scheme so it lands in the same shape.
+ if (value.startsWith("/")) return safeUrl(`file://${value}`);
+ return safeUrl(value);
+}
+
+function safeUrl(value: string): URL | null {
+ try {
+ return new URL(value);
+ } catch {
+ return null;
+ }
+}
+
+function canonicalRemotePath(pathname: string): string | null {
+ let path = pathname;
+ while (path.endsWith("/")) path = path.slice(0, -1);
+ path = path.replace(DOT_GIT_SUFFIX_RE, "");
+ while (path.endsWith("/")) path = path.slice(0, -1);
+ // `https://host` alone identifies a forge, not a repository.
+ return path.length === 0 || path === "/" ? null : path;
+}
+
+/**
+ * Probe `repoPath` for its workspace identity, or `null` when it is not
+ * inside a git repository (or the probe's budget ran out).
+ *
+ * TWO git invocations, both through the hardened fixed-argv {@link
+ * runGit}: `rev-parse HEAD --abbrev-ref HEAD` yields the commit and the
+ * branch together, and `remote get-url origin` yields the remote. The
+ * whole probe shares ONE wall-clock budget - each invocation gets only
+ * what is left of it - because this runs inside a lifecycle hook whose
+ * own process ceiling it must never consume.
+ *
+ * Deliberately NOT gated on {@link isGitRepo}: that helper looks for a
+ * `.git` entry in the directory itself, so it reports `false` for every
+ * SUBDIRECTORY of a repository, which is where a session's `cwd`
+ * usually sits. git's own resolution walks upward and is the authority.
+ */
+export function readGitWorkspaceIdentity(
+ repoPath: string,
+ opts: { readonly timeoutMs?: number } = {},
+): GitWorkspaceIdentity | null {
+ const budgetMs =
+ typeof opts.timeoutMs === "number" && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
+ ? Math.floor(opts.timeoutMs)
+ : GIT_PROBE_TIMEOUT_MS;
+ const deadline = Date.now() + budgetMs;
+ const probe = (args: ReadonlyArray<string>): string => {
+ const remaining = deadline - Date.now();
+ if (remaining <= 0) return "";
+ return runGit(repoPath, args, { timeoutMs: remaining, quiet: true })?.trim() ?? "";
+ };
+
+ const [shaLine, refLine] = probe(["rev-parse", "HEAD", "--abbrev-ref", "HEAD"]).split("\n");
+ const commit = isFullSha(shaLine?.trim()) ? shaLine!.trim() : null;
+ const ref = refLine?.trim() ?? "";
+ const branch = ref.length > 0 && ref !== DETACHED_HEAD_REF ? ref : null;
+ const repo = canonicalizeGitRemote(probe(["remote", "get-url", "origin"]));
+
+ if (repo === null && branch === null && commit === null) return null;
+ return Object.freeze({ repo, branch, commit });
+}
+
/** True when the (validated) sha resolves to a commit in this repo. */
export function shaExists(repoPath: string, sha: string): boolean {
if (!isFullSha(sha)) return false;
diff --git a/src/core/brain/git/store.ts b/src/core/brain/git/store.ts
index e7a37a10..3410e038 100644
--- a/src/core/brain/git/store.ts
+++ b/src/core/brain/git/store.ts
@@ -27,6 +27,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { isFullSha } from "./reader.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export interface GitCommitRecord {
readonly kind: "commit";
@@ -179,6 +180,8 @@ export function appendGitRecords(
repoKey: string,
records: ReadonlyArray<GitRecord>,
): AppendGitRecordsResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const existing = readRecords(vault, repoKey);
const seenShas = new Set<string>();
// Tag identity is (name, target): a RETARGETED tag (same name, new
@@ -270,6 +273,8 @@ export function listGitTags(vault: string, repoKey: string): ReadonlyArray<GitTa
/** Watermark write; the sha grammar is enforced before anything lands. */
export function writeGitState(vault: string, repoKey: string, state: GitState): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
if (!isFullSha(state.lastSha)) {
throw new Error(`git state lastSha must be a full 40-hex git sha, got: ${state.lastSha}`);
}
diff --git a/src/core/brain/handoff.ts b/src/core/brain/handoff.ts
index a7ee8c4c..5655aaca 100644
--- a/src/core/brain/handoff.ts
+++ b/src/core/brain/handoff.ts
@@ -15,6 +15,7 @@ import { join } from "node:path";
import { computeSourceStamp, formatSourceStampFrontmatter } from "./freshness.ts";
import { isoDate, isoSecond } from "./time.ts";
import { resolveSessionScope } from "./session-scope.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import type { SessionTurn } from "./sessions/types.ts";
export interface HandoffNoteOptions {
@@ -137,6 +138,8 @@ export function buildHandoffNote(
/** Build and persist the note at `Brain/handoffs/<date>-<scope>.md`. */
export function writeHandoffNote(vault: string, input: WriteHandoffNoteInput): HandoffNoteResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const now = input.now ?? new Date();
const scope = resolveSessionScope(input.sessionId);
const dir = join(vault, "Brain", "handoffs");
diff --git a/src/core/brain/heal-run.ts b/src/core/brain/heal-run.ts
index 4eb4ef66..cfefdad6 100644
--- a/src/core/brain/heal-run.ts
+++ b/src/core/brain/heal-run.ts
@@ -25,6 +25,7 @@ import {
} from "../vault.ts";
import { BRAIN_ROOT_REL } from "./paths.ts";
import { planHealEnrichmentPrepared, prepareHealPhrases } from "./heal-enrich.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export interface HealRunResult {
/** Pages scanned (outside the Brain root). */
@@ -40,6 +41,8 @@ export interface HealRunResult {
* scan/enrich counts. Writes only changed pages.
*/
export function runHealEnrichment(vault: string): HealRunResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
// BRAIN_ROOT_REL is the Brain dir name relative to the vault (its
// first path segment is the dir to skip). The skipDirs option REPLACES
// the default exclusions, so the Brain root is added to the standard
@@ -79,14 +82,15 @@ export function runHealEnrichment(vault: string): HealRunResult {
const changed: string[] = [];
for (const p of pages) {
- let meta;
- let body;
- try {
- [meta, body] = parseFrontmatter(p.path);
- } catch {
- // A page we cannot parse is skipped, not aborted - heal is hygiene.
- continue;
- }
+ // Unit F: `parseFrontmatter` cannot throw (it reads inside its own
+ // try; everything after is string work), so the `catch { continue }`
+ // that stood here was unreachable - a page was never actually
+ // skipped by it. Dropped lines and unreadable reads are reported
+ // centrally instead; see the "Why most readers keep the two-tuple
+ // form" section in src/core/vault.ts. An unreadable page still
+ // yields an empty map here and plans no change, so heal stays
+ // hygiene: it never rewrites what it could not read.
+ const [meta, body] = parseFrontmatter(p.path);
// Never link a page to its own title or aliases.
const own = ownTokens.get(p.path) ?? new Set<string>();
const plan = planHealEnrichmentPrepared({ frontmatter: meta, body }, prepared, own);
diff --git a/src/core/brain/health-baseline.ts b/src/core/brain/health-baseline.ts
index 3434df4a..9126755b 100644
--- a/src/core/brain/health-baseline.ts
+++ b/src/core/brain/health-baseline.ts
@@ -20,6 +20,7 @@ import { withFileLock } from "../reliability/lock.ts";
import { brainConfigPath } from "./paths.ts";
import { loadBrainConfig, resolveHealth } from "./policy.ts";
import { isValidIsoInstant } from "./health/iso-time.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** Operational failure surfacing a bad value or an unwritable config. */
export class HealthBaselineError extends Error {
@@ -46,6 +47,8 @@ export function readHealthBaseline(vault: string): string | null {
* update to a last-writer-wins overwrite.
*/
export async function writeHealthBaseline(vault: string, value: string | null): Promise<void> {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
if (value !== null && !isValidIsoInstant(value)) {
throw new HealthBaselineError(
`not an ISO-8601 date (YYYY-MM-DD) or timestamp: ${JSON.stringify(value)}`,
diff --git a/src/core/brain/health/edit-history.ts b/src/core/brain/health/edit-history.ts
index feaab49a..7b4c03b5 100644
--- a/src/core/brain/health/edit-history.ts
+++ b/src/core/brain/health/edit-history.ts
@@ -15,6 +15,7 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname } from "node:path";
import { preferenceHistoryPath } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export interface EditHistoryEntry {
/** ISO timestamp of the mutation. */
@@ -76,6 +77,8 @@ export function appendEditHistory(
slug: string,
entries: ReadonlyArray<EditHistoryEntry>,
): number {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
if (entries.length === 0) return 0;
const path = preferenceHistoryPath(vault, slug);
const seen = new Set(readEditHistory(vault, slug).map(dedupKey));
diff --git a/src/core/brain/health/remediation.ts b/src/core/brain/health/remediation.ts
index 844c25cf..d8fc92f6 100644
--- a/src/core/brain/health/remediation.ts
+++ b/src/core/brain/health/remediation.ts
@@ -25,6 +25,7 @@ import { ensureInsideVault, vaultRelative } from "../../path-safety.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../../vault.ts";
import { computeContentHash, verifyContentHash } from "../content-hash.ts";
import { brainDirs, preferencePath } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { parsePreference } from "../preference.ts";
import { acquireLockSync } from "../sync-lockfile.ts";
import { BRAIN_PREFERENCE_STATUS } from "../types.ts";
@@ -337,6 +338,8 @@ export function applyRemediation(
plan: RemediationPlan,
opts: ApplyRemediationOptions,
): RemediationOutcome {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const applied: RemediationStep[] = [];
const skipped: RemediationStep[] = [];
let budget = plan.stepCap;
diff --git a/src/core/brain/health/thesis.ts b/src/core/brain/health/thesis.ts
index 56ee3724..831a4bbd 100644
--- a/src/core/brain/health/thesis.ts
+++ b/src/core/brain/health/thesis.ts
@@ -45,6 +45,7 @@ import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { parseFrontmatter, slugify } from "../../vault.ts";
import { nextDueDate, parseCadence, type ObligationCadence } from "../obligations.ts";
import { thesesDir, thesisPath, validateIsoDate } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { isoDate, isoSecond } from "../time.ts";
import { type BrainSignalSign, type BrainCommitmentTier } from "../types.ts";
import { readCommitmentTier, validateCommitmentTier } from "../commitment.ts";
@@ -241,6 +242,8 @@ function parsePage(vault: string, slug: string): ThesisPage | null {
/** Create a declared-thesis page. Refuses to clobber an existing slug. */
export function recordThesis(vault: string, input: RecordThesisInput): ThesisPage {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const statement = input.statement.trim();
if (statement.length === 0) throw new ThesisError("thesis statement must not be empty");
const cadence = parseCadence(input.cadence ?? "monthly");
@@ -272,6 +275,8 @@ export function recordThesis(vault: string, input: RecordThesisInput): ThesisPag
/** Revise a thesis; bumps `last_updated` to now (or the injected clock). */
export function updateThesis(vault: string, input: UpdateThesisInput): ThesisPage {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const slug = slugify(input.slug);
const prior = parsePage(vault, slug);
if (prior === null) throw new ThesisError(`no thesis: ${slug}`);
@@ -310,6 +315,8 @@ export function recordThesisSupport(
slug: string,
opts: { date?: string; now?: Date } = {},
): ThesisPage {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const normalized = slugify(slug);
const prior = parsePage(vault, normalized);
if (prior === null) throw new ThesisError(`no thesis: ${normalized}`);
@@ -323,6 +330,8 @@ export function recordThesisSupport(
/** Formally close a thesis (the graveyard's recommended action). */
export function closeThesis(vault: string, slug: string): ThesisPage {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const normalized = slugify(slug);
const prior = parsePage(vault, normalized);
if (prior === null) throw new ThesisError(`no thesis: ${normalized}`);
diff --git a/src/core/brain/hygiene/apply.ts b/src/core/brain/hygiene/apply.ts
index 5f32f96d..eaf52bce 100644
--- a/src/core/brain/hygiene/apply.ts
+++ b/src/core/brain/hygiene/apply.ts
@@ -21,9 +21,10 @@ import { join } from "node:path";
import { appendAuditRecord } from "../../reliability/audit.ts";
import { mergePreferences } from "../merge.ts";
-import { brainDirs } from "../paths.ts";
+import { brainDirsForWrite } from "../paths.ts";
import { archivePage, executeRecompile, planRecompile } from "../recompile.ts";
import { appendClaimEvent } from "../truth/store.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import type { HygienePlan } from "./plan.ts";
import type { HygieneFinding } from "./types.ts";
@@ -148,6 +149,12 @@ export async function applyHygienePlan(
});
}
+ // Vault-identity write guard (context-integrity-gates, Unit J), after
+ // the dry-run early return and before the first executor. The per-
+ // finding loop is fail-soft, so an assertion reached only from inside
+ // an executor would be filed as a finding error instead of refusing.
+ assertVaultIdentityForWrite(vault);
+
const applied: HygieneAppliedAction[] = [];
const errors: { finding_id: string; message: string }[] = [];
for (const finding of plan.selected) {
@@ -162,7 +169,7 @@ export async function applyHygienePlan(
}
if (applied.length > 0 || errors.length > 0) {
- appendAuditRecord(join(brainDirs(vault).log, "hygiene"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, "hygiene"), {
timestamp: opts.now.toISOString(),
actor: opts.agent,
action: "hygiene_apply",
diff --git a/src/core/brain/idea-discovery.ts b/src/core/brain/idea-discovery.ts
index 910170f9..a35e0367 100644
--- a/src/core/brain/idea-discovery.ts
+++ b/src/core/brain/idea-discovery.ts
@@ -15,7 +15,7 @@ import { join } from "node:path";
import { buildMorningBrief, type MorningBriefOpenQuestion } from "./morning-brief.ts";
import { extractWikilinkRichBodies, parseWikilinkRich } from "./link-graph/parse-wikilink.ts";
-import { parseFrontmatterText } from "../vault.ts";
+import { parseFrontmatter } from "../vault.ts";
import type { InsightCandidate, TriggerKind } from "./triggers/types.ts";
const DAY_MS = 24 * 3600 * 1000;
@@ -174,12 +174,18 @@ export function discoverIdeas(
const age = ageDays(absPath, opts.now);
if (age < agingSignalDays) continue;
let topic = name.slice(0, -".md".length);
- try {
- const [meta] = parseFrontmatterText(readFileSync(absPath, "utf8"));
- if (typeof meta["topic"] === "string" && meta["topic"] !== "") topic = meta["topic"];
- } catch {
- // keep the filename-derived topic
- }
+ // Unit F: this site used to do its own `readFileSync` inside a
+ // `catch {}` that silently kept the filename-derived topic - the one
+ // genuinely reachable swallow among the frontmatter readers, since
+ // the read is outside the parser. `parseFrontmatter` owns the read
+ // now, so a failure is named at the source (a
+ // `frontmatter-unreadable` notice) instead of here, and still
+ // returns an empty map - which leaves the filename-derived topic in
+ // place, exactly as before. A ranked candidate list has no report
+ // field; see the "Why most readers keep the two-tuple form" section
+ // in src/core/vault.ts for where the condition IS reported.
+ const [meta] = parseFrontmatter(absPath);
+ if (typeof meta["topic"] === "string" && meta["topic"] !== "") topic = meta["topic"];
candidates.push(
Object.freeze({
kind: "idea_direction" as const,
diff --git a/src/core/brain/idempotency-ledger.ts b/src/core/brain/idempotency-ledger.ts
index d7b69069..bc3c6c69 100644
--- a/src/core/brain/idempotency-ledger.ts
+++ b/src/core/brain/idempotency-ledger.ts
@@ -39,6 +39,7 @@ import { join } from "node:path";
import { BRAIN_ROOT_REL, ensureInsideVault } from "./paths.ts";
import { acquireLockSync } from "./sync-lockfile.ts";
import { isoSecond } from "./time.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** Month-sharded JSONL root, distinct from `Brain/log/` (the human trail). */
const IDEMPOTENCY_REL = `${BRAIN_ROOT_REL}/logs/idempotency`;
@@ -155,6 +156,8 @@ export function lookupKey(vault: string, key: string): IdempotencyRecord | null
* `payload_mismatch` write nothing.
*/
export function rememberKey(vault: string, input: RememberKeyInput): RememberKeyResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const key = normaliseKey(input.key);
const contentHash = requireHash(input.contentHash);
const createdAt = input.createdAt ?? isoSecond(new Date());
diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.ts
index 89346c4d..c142b82e 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 { assertVaultIdentityForWrite } from "./vault-identity.ts";
export interface ImportClaudeMemoryOpts {
readonly vault: string;
@@ -78,6 +79,11 @@ function mergePreservingEvidence(existingBody: string, freshBody: string): strin
}
export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMemoryResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J). The
+ // dry-run form writes nothing, so it stays a read and is not gated -
+ // guarding a preview would refuse the very inspection an operator
+ // runs to decide whether the resolved vault is the intended one.
+ if (opts.mode === "apply") assertVaultIdentityForWrite(opts.vault);
const backend = opts.backend ?? claudeMemoryBackend;
assertSafeMemoryPath(opts.memoryDir, opts.allowArbitraryMemoryPath ?? false);
if (!existsSync(opts.memoryDir)) {
diff --git a/src/core/brain/index.ts b/src/core/brain/index.ts
index dabf244f..854c2697 100644
--- a/src/core/brain/index.ts
+++ b/src/core/brain/index.ts
@@ -36,6 +36,8 @@ export type {
BrainRetireConfig,
BrainConfidenceConfig,
BrainSnapshotsConfig,
+ BrainIntegrityConfig,
+ ResolvedBrainIntegrityConfig,
} from "./types.ts";
export {
@@ -114,6 +116,10 @@ export {
loadBrainConfigDetailed,
validateBrainConfig,
validateBrainConfigDetailed,
+ BRAIN_INTEGRITY_DEFAULTS,
+ PACK_VALIDITY_SECONDS_DEFAULT,
+ resolveIntegrity,
+ loadIntegrityConfigSafe,
} from "./policy.ts";
export { parseBrainYaml } from "./yaml-parse.ts";
diff --git a/src/core/brain/ingest/checkpoint.ts b/src/core/brain/ingest/checkpoint.ts
index 648b406e..94b71086 100644
--- a/src/core/brain/ingest/checkpoint.ts
+++ b/src/core/brain/ingest/checkpoint.ts
@@ -30,6 +30,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { canonicalNotePath } from "../../path-safety.ts";
import { isoSecond } from "../time.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Only schema version currently understood. Unknown versions are refused. */
const SCHEMA_VERSION = 1 as const;
@@ -174,6 +175,8 @@ export function recordCompleted(
now: Date,
): boolean {
if (!checkpointingEnabled()) return false;
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const prev = readCheckpoint(vault, planId);
const merged = new Set<string>(prev?.completed ?? []);
for (const p of paths) merged.add(canonicalNotePath(p));
@@ -196,6 +199,8 @@ export function recordCompleted(
* existed.
*/
export function clearCheckpoint(vault: string, planId: string): boolean {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = checkpointPath(vault, planId);
if (!existsSync(path)) return false;
rmSync(path);
diff --git a/src/core/brain/ingest/content-manifest.ts b/src/core/brain/ingest/content-manifest.ts
index 7b8bb87f..70d46073 100644
--- a/src/core/brain/ingest/content-manifest.ts
+++ b/src/core/brain/ingest/content-manifest.ts
@@ -34,6 +34,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { canonicalNotePath } from "../../path-safety.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Only schema version currently understood. Unknown versions are refused. */
const SCHEMA_VERSION = 1 as const;
@@ -169,6 +170,8 @@ function serializeManifest(entries: Record<string, string>): string {
* nothing (and leaves the file's mtime alone).
*/
export function writeManifestAtomic(vault: string, entries: Record<string, string>): boolean {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = manifestPath(vault);
const next = serializeManifest(entries);
if (existsSync(path) && readFileSync(path, "utf8") === next) {
diff --git a/src/core/brain/ingest/ingest.ts b/src/core/brain/ingest/ingest.ts
index 62ce91c7..ec2cbffd 100644
--- a/src/core/brain/ingest/ingest.ts
+++ b/src/core/brain/ingest/ingest.ts
@@ -32,6 +32,7 @@ import {
} from "../../vault.ts";
import { isoSecond } from "../time.ts";
import { sourcePagePath } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { intakeExtraction, type ExtractionIntake } from "../intake/extract-intake.ts";
import {
renderProvenanceSection,
@@ -110,6 +111,8 @@ export function ingestSource(
input: IngestSourceInput,
opts: IngestSourceOptions,
): IngestSourceResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const canonicalSource = canonicalNotePath(input.sourcePath);
const preExtract = opts.preExtract === true ? runPreExtract(vault, canonicalSource) : undefined;
const sourceLink = `[[${canonicalSource}]]`;
diff --git a/src/core/brain/ingest/sources-registry.ts b/src/core/brain/ingest/sources-registry.ts
index dd1a8d7d..c992e26b 100644
--- a/src/core/brain/ingest/sources-registry.ts
+++ b/src/core/brain/ingest/sources-registry.ts
@@ -22,6 +22,7 @@ import { ensureInsideVault } from "../../path-safety.ts";
import { parseFrontmatter } from "../../vault.ts";
import { BRAIN_SOURCES_REL } from "../paths.ts";
import { BRAIN_SOURCE_KIND } from "./ingest.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export interface IngestedSource {
/** Vault-relative POSIX path of the summary page - the id for get/delete. */
@@ -129,6 +130,8 @@ export function getIngestedSource(vault: string, id: string): IngestedSourceDeta
* outside `Brain/sources` or a non-source page is never deleted.
*/
export function deleteIngestedSource(vault: string, id: string): boolean {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const abs = resolveSourceAbs(vault, id);
if (abs === null || !existsSync(abs)) return false;
let meta: FrontmatterMap;
diff --git a/src/core/brain/init.ts b/src/core/brain/init.ts
index 1b673ba2..e47f5aa7 100644
--- a/src/core/brain/init.ts
+++ b/src/core/brain/init.ts
@@ -34,6 +34,7 @@ import {
brainManualPath,
vaultRelative,
} from "./paths.ts";
+import { vaultIdentityPath, writeVaultIdentity } from "./vault-identity.ts";
import { DEFAULT_BRAIN_CONFIG_YAML, formatPrimaryAgentYamlValue } from "./policy.ts";
import { BASE_TEMPLATE_FILES, BASES_TEMPLATE_DIR, renderBrainManual } from "./templates.ts";
@@ -241,6 +242,16 @@ export function bootstrapBrain(
mkdirSync(dir, { recursive: true });
}
+ // 1b. `Brain/vault-id.json` β€” the vault identity marker (Unit J). The
+ // bootstrap path is what legitimately creates a Brain tree, so it
+ // stamps the marker rather than being gated on it. Idempotent: a
+ // vault that already has an identity keeps it, since rotating the
+ // id would make every synced peer look like a different store.
+ const identityPath = vaultIdentityPath(vault);
+ const identityExisted = existsSync(identityPath);
+ writeVaultIdentity(vault);
+ if (!identityExisted) created.push(vaultRelative(identityPath, vault));
+
// 2. `_brain.yaml` β€” default config (with optional primary_agent).
const brainYamlPath = brainConfigPath(vault);
const brainYamlRel = vaultRelative(brainYamlPath, vault);
diff --git a/src/core/brain/intentions.ts b/src/core/brain/intentions.ts
index f9eb511b..c4199988 100644
--- a/src/core/brain/intentions.ts
+++ b/src/core/brain/intentions.ts
@@ -17,6 +17,7 @@ import { atomicWriteFileSync } from "../fs-atomic.ts";
import { parseFrontmatter } from "../vault.ts";
import { resolveSessionScope } from "./session-scope.ts";
import { isoDate, isoSecond } from "./time.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export interface IntentionChain {
readonly scope: string;
@@ -113,6 +114,8 @@ function parseChain(vault: string, scope: string): IntentionChain | null {
/** Create or update the scoped intention; prior text lands in history. */
export function setIntention(vault: string, input: SetIntentionInput): IntentionChain {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const scope = resolveSessionScope(input.scope);
const now = input.now ?? new Date();
const text = input.text.trim();
@@ -162,6 +165,8 @@ export function moveIntentionToHistory(
vault: string,
input: MoveIntentionInput,
): MoveIntentionResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const scope = resolveSessionScope(input.scope);
const now = input.now ?? new Date();
const activePath = intentionPath(vault, scope);
diff --git a/src/core/brain/labels.ts b/src/core/brain/labels.ts
index 01b3ce6b..bfacf4ef 100644
--- a/src/core/brain/labels.ts
+++ b/src/core/brain/labels.ts
@@ -16,6 +16,7 @@ import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
import { resolveNotePath } from "./note-path.ts";
import { normalizeSchemaToken } from "./schema-vocab.ts";
import { upsertEntity } from "./entities/registry.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import type { SchemaPack } from "./schema-pack.ts";
export const LABEL_ENTITY_CATEGORY = "label";
@@ -127,6 +128,8 @@ export function assignNoteLabel(
relPath: string,
opts: AssignNoteLabelOptions,
): NoteLabelResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const assignment = validateLabelAssignment(opts.pack, opts.dimension, opts.value);
const path = resolveNotePath(vault, relPath);
const [metadata, body] = parseFrontmatter(path);
@@ -157,6 +160,8 @@ export function removeNoteLabel(
relPath: string,
opts: RemoveNoteLabelOptions,
): RemoveNoteLabelResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const dimension = normalizeSchemaToken(opts.dimension);
const path = resolveNotePath(vault, relPath);
const [metadata, body] = parseFrontmatter(path);
diff --git a/src/core/brain/lessons.ts b/src/core/brain/lessons.ts
index 7866949b..8d25418b 100644
--- a/src/core/brain/lessons.ts
+++ b/src/core/brain/lessons.ts
@@ -39,7 +39,7 @@ import { parseFrontmatter } from "../vault.ts";
import { decayWeight } from "./continuity/usage-signal.ts";
import { listDeadEnds, type DeadEndEntry } from "./dead-ends.ts";
import { listLogDates, readLogDay } from "./log-jsonl.ts";
-import { brainDirs, brainLessonsPath } from "./paths.ts";
+import { brainDirs, brainDirsForWrite, brainLessonsPath } from "./paths.ts";
import { parsePreference } from "./preference.ts";
import {
LESSONS_CORROBORATION_MIN_DEFAULT,
@@ -437,7 +437,8 @@ export function regenerateLessonsQuiet(vault: string, opts: RegenerateLessonsOpt
// ----- Scan helpers --------------------------------------------------------
function readActivePreferences(vault: string): BrainPreference[] {
- const dirs = brainDirs(vault);
+ // Only reached from `regenerateLessons`, which writes `Brain/lessons.md`.
+ const dirs = brainDirsForWrite(vault);
if (!existsSync(dirs.preferences)) return [];
const out: BrainPreference[] = [];
for (const name of readdirSync(dirs.preferences)) {
diff --git a/src/core/brain/lifecycle/temporal-replace.ts b/src/core/brain/lifecycle/temporal-replace.ts
index 6caf2a52..a863005b 100644
--- a/src/core/brain/lifecycle/temporal-replace.ts
+++ b/src/core/brain/lifecycle/temporal-replace.ts
@@ -37,6 +37,7 @@ import { resolveNotePath } from "../note-path.ts";
import { isoSecond } from "../time.ts";
import { BRAIN_LOG_EVENT_KIND } from "../types.ts";
import { normalizeChainLink, SUPERSEDED_BY_KEY } from "./tombstone.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
// ----- Constants ------------------------------------------------------------
@@ -157,6 +158,8 @@ function relForVault(vault: string, absPath: string): string {
* `temporal-replace` event.
*/
export function temporalReplace(input: TemporalReplaceInput): TemporalReplaceResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(input.vault);
let absPred: string;
let absSucc: string;
try {
diff --git a/src/core/brain/lifecycle/tombstone.ts b/src/core/brain/lifecycle/tombstone.ts
index d731613b..f67c8cdc 100644
--- a/src/core/brain/lifecycle/tombstone.ts
+++ b/src/core/brain/lifecycle/tombstone.ts
@@ -36,6 +36,7 @@ import { BRAIN_ROOT_REL } from "../paths.ts";
import { resolveNotePath } from "../note-path.ts";
import { isoSecond } from "../time.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_TOMBSTONE_STATUS } from "../types.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
// ----- Constants ------------------------------------------------------------
@@ -182,6 +183,8 @@ function relForVault(vault: string, absPath: string): string {
* existing state is returned with `changed: false`.
*/
export function tombstone(input: TombstoneInput): TombstoneResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(input.vault);
const reason = sanitiseTextField(input.reason, {
maxLen: REASON_MAX_LEN,
singleLine: true,
diff --git a/src/core/brain/lineage/crutch.ts b/src/core/brain/lineage/crutch.ts
index c8a16d91..76704719 100644
--- a/src/core/brain/lineage/crutch.ts
+++ b/src/core/brain/lineage/crutch.ts
@@ -11,21 +11,58 @@
* unrelated conversations merged) is strictly worse than a missed
* stitch (status quo). A link happens only when ALL hold:
*
- * 1. the new session has NO ledger history of its own (a session
- * seen before without a link is a parallel session);
- * 2. a predecessor exists in the SAME cwd;
- * 3. the predecessor's LATEST event evidences a compression
+ * 1. the new session has NO history of its own - neither a ledger
+ * line NOR a recorded gap (a session seen before without a link is
+ * a parallel session, and a dropped observation is still a session
+ * that spoke);
+ * 2. a predecessor exists in the SAME cwd, and no other session has
+ * already continued from it;
+ * 3. that predecessor's git working state - repo, branch, commit -
+ * matches this session's, and both sides attested one;
+ * 4. the predecessor's LATEST event evidences a compression
* boundary (PostCompact / PreCompact / SessionStart:compact);
- * 4. the predecessor's last activity falls within
- * `CRUTCH_LINK_WINDOW_MS` before now.
+ * 5. the predecessor's last activity falls within
+ * `CRUTCH_LINK_WINDOW_MS` before now;
+ * 6. EXACTLY ONE predecessor survives 2-5.
*
- * Time proximity alone NEVER links. Removal plan (kanban
- * t_1459706f): once the upstream PR merges and the deployed Hermes
- * emits `parent_session_id`, delete this file and every call site
- * carrying the CRUTCH(t_1459706f) marker; the native payload path in
- * `resolve.ts` already takes precedence.
+ * Time proximity alone NEVER links.
+ *
+ * ## Fail-closed (context-integrity-gates, Unit C)
+ *
+ * Rule 6 is the correction that matters most. This resolver used to
+ * break a multi-candidate tie by taking the largest `lastSeenMs`, so
+ * two concurrent sessions in one directory - both inside the window,
+ * both showing compression evidence - silently stitched to whichever
+ * had spoken more recently. A wrong-but-plausible resume injects
+ * another branch's continuity as fact, and downstream the anticipatory
+ * cache path derives from the lineage root, so a mis-stitch redirects
+ * one conversation's cache into another's file. Ambiguity now ABSTAINS.
+ *
+ * Rule 3 is the second: `cwd` is a string, and one string names many
+ * working states. The same directory on a different branch, or after a
+ * commit, is a different context, and a session resumed across that
+ * boundary is not the same work. Identity that only ONE side attested
+ * is refused too - an unverifiable claim is not evidence.
+ *
+ * Every refusal is NAMED. The old signature returned a bare `null` into
+ * which four distinct causes collapsed - no candidate, self already
+ * known, no cwd, several candidates - leaving every caller unable to
+ * tell a genuine absence of history from a mechanism that declined. The
+ * abstention is a returned value, never a throw: this path is fail-soft
+ * by contract and must not raise into a lifecycle hook.
+ *
+ * The 900-second window stays as the freshness bound. Replacing the
+ * timing crutch with durable work identity is a separate architectural
+ * unit (kanban t_e6be4f6b); this makes its failures visible and abstains
+ * where it cannot tell, which is that replacement's prerequisite.
+ *
+ * Removal plan (kanban t_1459706f): once the upstream PR merges and the
+ * deployed Hermes emits `parent_session_id`, delete this file and every
+ * call site carrying the CRUTCH(t_1459706f) marker; the native payload
+ * path in `resolve.ts` already takes precedence.
*/
+import type { GitWorkspaceIdentity } from "../git/reader.ts";
import {
CRUTCH_LINK_WINDOW_MS,
type LineageLedgerEntry,
@@ -34,44 +71,273 @@ import {
import type { SessionLineage } from "./types.ts";
/**
- * Infer lineage for `sessionId` from the ledger, or return `null`
- * when no conservative link exists. CRUTCH(t_1459706f).
+ * Closed vocabulary of continuation refusals. Every member names a
+ * DIFFERENT cause, which is the whole point: `no-candidate` (nothing to
+ * link to) and `ambiguous` (too much to link to) are opposite
+ * conditions that the previous `null` return made indistinguishable.
*/
-export function resolveCrutchLineage(
- sessionId: string,
- cwd: string | undefined,
- ledger: LineageLedgerState,
- nowMs: number,
-): SessionLineage | null {
+export const CRUTCH_ABSTENTION = Object.freeze({
+ /** Nothing in the ledger reached the freshness or evidence gates. */
+ noCandidate: "no-candidate",
+ /** This session already has ledger history of its own: parallel, not a continuation. */
+ selfKnown: "self-known",
+ /** The host reported no working directory, so no candidate set can be formed. */
+ noWorkspace: "no-workspace",
+ /** Several candidates survived every predicate. Refused rather than resolved by recency. */
+ ambiguous: "ambiguous",
+ /** Candidates existed in this workspace but all fell outside the freshness window. */
+ stale: "stale",
+ /** Candidates were fresh but showed no compression boundary, or their git state was unattested. */
+ evidenceMissing: "evidence-missing",
+} as const);
+
+export type CrutchAbstentionReason = (typeof CRUTCH_ABSTENTION)[keyof typeof CRUTCH_ABSTENTION];
+
+/** A link was inferred. */
+export interface CrutchLinked {
+ readonly kind: "linked";
+ readonly lineage: SessionLineage;
+}
+
+/** No link was inferred, and this is why. */
+export interface CrutchAbstained {
+ readonly kind: "abstained";
+ readonly reason: CrutchAbstentionReason;
+ /** One English line stating the counts behind the refusal. */
+ readonly detail: string;
+ /** Predecessors in this workspace that were examined. */
+ readonly considered: number;
+}
+
+export type CrutchOutcome = CrutchLinked | CrutchAbstained;
+
+export interface CrutchResolveInput {
+ readonly sessionId: string;
+ /** Working directory the host reported, if any. */
+ readonly cwd?: string;
+ readonly ledger: LineageLedgerState;
+ /** Injected clock (epoch ms). */
+ readonly nowMs: number;
+ /** Git working state of THIS session, when its `cwd` attested one. */
+ readonly workspace?: GitWorkspaceIdentity;
+ /**
+ * Sessions the ledger's gap sidecar records as having spoken without
+ * being appended (`lineageGapSessionIds`). Membership is evidence of
+ * own history exactly as a ledger line is - see Rule 1 above. Omitted
+ * means "no gap evidence available", which is the pre-existing
+ * behaviour and the only reason the field is optional.
+ */
+ readonly gapSessionIds?: ReadonlySet<string>;
+}
+
+/**
+ * How two attestations relate. `unattested` is neither agreement nor
+ * disagreement: exactly one side made a claim (or neither did while the
+ * other could have), so the working state is unverified rather than
+ * different - a distinction the caller reports as missing evidence
+ * instead of as a mismatch.
+ */
+type AttestationMatch = "match" | "mismatch" | "unattested";
+
+/** Which predicate turned a candidate away. Ordered by how far it got. */
+type RejectionKind = "claimed" | "workspace" | "stale" | "evidence";
+
+/**
+ * Infer lineage for a session from the ledger, or abstain with a named
+ * reason. CRUTCH(t_1459706f). Never throws.
+ */
+export function resolveCrutchLineage(input: CrutchResolveInput): CrutchOutcome {
+ const { sessionId, ledger, nowMs } = input;
+
const own = ledger.get(sessionId);
// A previously persisted link (from an earlier crutch or payload
// resolution) is authoritative for the rest of the session.
if (own?.lineage !== undefined && own.lineage.source !== "flat") {
- return own.lineage;
+ return Object.freeze({ kind: "linked" as const, lineage: own.lineage });
}
// Rule 1: known session without a link = parallel session, not a
// continuation. Never re-guess.
- if (own !== undefined) return null;
- if (cwd === undefined || cwd.length === 0) return null;
+ if (own !== undefined) {
+ return abstain(
+ CRUTCH_ABSTENTION.selfKnown,
+ "the session already has ledger history without a link",
+ 0,
+ );
+ }
+ // Rule 1, second half. A ledger LINE is only one of the two records
+ // that a session already spoke; a writer-lock drop leaves the other -
+ // a gap in the sidecar. Reading the ledger alone makes a session whose
+ // observation was dropped indistinguishable from one that never
+ // spoke, which turns this fail-closed rule into a FALSE STITCH onto an
+ // unrelated parallel session. Absent evidence is evidence, once it is
+ // recorded that it was lost.
+ if (input.gapSessionIds?.has(sessionId) === true) {
+ return abstain(
+ CRUTCH_ABSTENTION.selfKnown,
+ "the session has a recorded ledger gap: it spoke, and the observation was dropped",
+ 0,
+ );
+ }
+ const cwd = input.cwd;
+ if (cwd === undefined || cwd.length === 0) {
+ return abstain(CRUTCH_ABSTENTION.noWorkspace, "the host reported no working directory", 0);
+ }
+
+ const survivors: LineageLedgerEntry[] = [];
+ const rejected: Record<RejectionKind, number> = {
+ claimed: 0,
+ workspace: 0,
+ stale: 0,
+ evidence: 0,
+ };
+ let considered = 0;
+ const claimed = claimedPredecessors(ledger, sessionId);
- let predecessor: LineageLedgerEntry | null = null;
for (const entry of ledger.values()) {
if (entry.sessionId === sessionId) continue;
- if (entry.cwd !== cwd) continue; // Rule 2
- if (!entry.compressionEvidence) continue; // Rule 3
+ // Rule 2. A different directory is a different piece of work, not a
+ // near miss, so it never enters the candidate count.
+ if (entry.cwd !== cwd) continue;
+ considered++;
+
+ // A compaction boundary has exactly one successor, so a
+ // predecessor another session already continued from is spoken for.
+ // Without this, an A -> B -> C chain looks ambiguous from C: both A
+ // and B are fresh, evidenced and in the same directory, and only B
+ // is actually available.
+ if (claimed.has(entry.sessionId)) {
+ rejected.claimed++;
+ continue;
+ }
+
+ // Rule 3, part one: an attested disagreement about repo, branch or
+ // commit is decisive - this is a different working state.
+ const attestation = compareWorkspace(entry.workspace, input.workspace);
+ if (attestation === "mismatch") {
+ rejected.workspace++;
+ continue;
+ }
+ // Rule 5.
const age = nowMs - entry.lastSeenMs;
- if (age < 0 || age > CRUTCH_LINK_WINDOW_MS) continue; // Rule 4
- if (predecessor === null || entry.lastSeenMs > predecessor.lastSeenMs) {
- predecessor = entry;
+ if (age < 0 || age > CRUTCH_LINK_WINDOW_MS) {
+ rejected.stale++;
+ continue;
+ }
+ // Rule 4.
+ if (!entry.compressionEvidence) {
+ rejected.evidence++;
+ continue;
}
+ // Rule 3, part two: one-sided attestation is an unverifiable claim.
+ if (attestation === "unattested") {
+ rejected.evidence++;
+ continue;
+ }
+ survivors.push(entry);
+ }
+
+ // Rule 6.
+ if (survivors.length > 1) {
+ return abstain(
+ CRUTCH_ABSTENTION.ambiguous,
+ `${survivors.length} predecessors survived every predicate in the same working state; ` +
+ "refused rather than resolved by recency",
+ considered,
+ );
+ }
+ const predecessor = survivors[0];
+ if (predecessor === undefined) {
+ return abstain(nearestMiss(rejected), summarize(considered, rejected), considered);
}
- if (predecessor === null) return null;
const parentLineage = predecessor.lineage;
return Object.freeze({
- rootId: parentLineage !== undefined ? parentLineage.rootId : predecessor.sessionId,
- parentId: predecessor.sessionId,
- depth: (parentLineage !== undefined ? parentLineage.depth : 0) + 1,
- source: "crutch" as const,
+ kind: "linked" as const,
+ lineage: Object.freeze({
+ rootId: parentLineage !== undefined ? parentLineage.rootId : predecessor.sessionId,
+ parentId: predecessor.sessionId,
+ depth: (parentLineage !== undefined ? parentLineage.depth : 0) + 1,
+ source: "crutch" as const,
+ }),
});
}
+
+function abstain(
+ reason: CrutchAbstentionReason,
+ detail: string,
+ considered: number,
+): CrutchAbstained {
+ return Object.freeze({ kind: "abstained" as const, reason, detail, considered });
+}
+
+/**
+ * Report the NEAREST MISS. A candidate rejected on evidence got further
+ * through the predicate chain than one rejected on freshness, which got
+ * further than one whose working state disagreed - so naming the
+ * furthest tells the operator what actually stood between two sessions.
+ */
+function nearestMiss(rejected: Record<RejectionKind, number>): CrutchAbstentionReason {
+ if (rejected.evidence > 0) return CRUTCH_ABSTENTION.evidenceMissing;
+ if (rejected.stale > 0) return CRUTCH_ABSTENTION.stale;
+ return CRUTCH_ABSTENTION.noCandidate;
+}
+
+function summarize(considered: number, rejected: Record<RejectionKind, number>): string {
+ if (considered === 0) return "no predecessor was recorded in this working directory";
+ return (
+ `no predecessor survived: ${considered} examined ` +
+ `(${rejected.claimed} already continued, ${rejected.workspace} in another working state, ` +
+ `${rejected.stale} outside the freshness window, ` +
+ `${rejected.evidence} without usable evidence)`
+ );
+}
+
+/**
+ * Session ids that some OTHER ledger entry already names as its parent.
+ * Membership means the compaction boundary out of that session has been
+ * taken; a second successor would be a fork, which the crutch has no
+ * evidence to justify.
+ */
+function claimedPredecessors(ledger: LineageLedgerState, sessionId: string): ReadonlySet<string> {
+ const claimed = new Set<string>();
+ for (const entry of ledger.values()) {
+ if (entry.sessionId === sessionId) continue;
+ const parentId = entry.lineage?.parentId;
+ if (typeof parentId === "string" && parentId.length > 0) claimed.add(parentId);
+ }
+ return claimed;
+}
+
+/**
+ * Compare the git working state of a candidate against this session's.
+ *
+ * Both sides silent is a MATCH: a workspace outside any repository can
+ * attest nothing, and refusing every non-git directory would disable
+ * continuation there rather than harden it. One side silent is
+ * `unattested` - including the migration case where the predecessor was
+ * recorded before this evidence existed, which self-heals within one
+ * freshness window as new observations land.
+ */
+function compareWorkspace(
+ candidate: GitWorkspaceIdentity | undefined,
+ session: GitWorkspaceIdentity | undefined,
+): AttestationMatch {
+ if (candidate === undefined && session === undefined) return "match";
+ if (candidate === undefined || session === undefined) return "unattested";
+
+ let agreed = 0;
+ let oneSided = false;
+ for (const field of ["repo", "branch", "commit"] as const) {
+ const a = candidate[field];
+ const b = session[field];
+ if (a === null && b === null) continue;
+ if (a === null || b === null) {
+ oneSided = true;
+ continue;
+ }
+ if (a !== b) return "mismatch";
+ agreed++;
+ }
+ if (oneSided || agreed === 0) return "unattested";
+ return "match";
+}
diff --git a/src/core/brain/lineage/ledger.ts b/src/core/brain/lineage/ledger.ts
index 15547f5b..69d720e6 100644
--- a/src/core/brain/lineage/ledger.ts
+++ b/src/core/brain/lineage/ledger.ts
@@ -19,14 +19,54 @@
*
* Everything here is fail-soft: a missing ledger reads as empty,
* corrupt lines are skipped, and the file is compacted in place
- * (atomic rewrite) once it grows past the line cap.
+ * (atomic rewrite) once it grows past the line cap. Skipped lines are
+ * COUNTED and returned ({@link scanLineageLedger}) rather than merely
+ * dropped - fail-soft for the resolver, reportable for the verifier.
+ *
+ * ## Integrity (context-integrity-gates, Unit D)
+ *
+ * Every line carries a SEQUENCE NUMBER and a HASH CHAIN link, so a line
+ * that was edited, removed, or never written is detectable after the
+ * fact - by {@link import('./verify.ts').verifyLineageLedger}, which
+ * REPORTS and never refuses. The read path below deliberately does not
+ * consult the chain: `readLineageLedger`'s catch-to-empty-map is
+ * load-bearing for both the anticipatory cache and the lifecycle hook,
+ * and a ledger that refused to load would break resolution rather than
+ * degrade it. Integrity here is an audit property, not a gate.
+ *
+ * The whole read-modify-write runs under a SYNCHRONOUS writer lock
+ * (`acquireLockSync`, the same primitive the continuity store and the
+ * idempotency ledger use, re-reading under the lock exactly as they
+ * do). Before it, two hooks crossing the compaction cap could both read
+ * the file and the second rewrite could clobber the first's
+ * observation. `acquireLockSync` has no retry by design; a busy lock
+ * therefore DROPS the observation, and the drop is written to a gap
+ * sidecar and returned as a named notice rather than vanishing.
+ *
+ * Compaction retains the most recent lines VERBATIM. It used to fold
+ * the file to one summary line per session, which destroyed per-session
+ * event history, dropped `firstSeenMs` (the summary was stamped at
+ * `lastSeenMs`, so a reread saw first === last), deleted every session
+ * past the retention rank, and - through a re-serializer that hard-
+ * coded its field list - silently dropped any field a later writer
+ * added. Verbatim retention removes all four at once, including the
+ * last as a class of bug rather than an instance.
*/
-import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
+import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, unlinkSync } from "node:fs";
import { dirname, join, posix } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
+import {
+ DEGRADATION_CODE,
+ type DegradationNotice,
+ degradationNotice,
+} from "../../integrity/degradation.ts";
+import type { GitWorkspaceIdentity } from "../git/reader.ts";
+import { computePayloadHash } from "../idempotency-ledger.ts";
import { BRAIN_ROOT_REL, ensureInsideVault } from "../paths.ts";
+import { acquireLockSync, type LockHandle } from "../sync-lockfile.ts";
+import { assertVaultIdentityForWrite, VaultIdentityMismatchError } from "../vault-identity.ts";
import type { SessionLineage } from "./types.ts";
/** Crutch link window: a continuation must start this close to the
@@ -35,11 +75,98 @@ export const CRUTCH_LINK_WINDOW_MS = 900_000;
/** Compact the ledger once it holds more lines than this. */
const MAX_LEDGER_LINES = 512;
-/** Sessions retained (most recent first) by a compaction rewrite. */
-const RETAIN_SESSIONS = 256;
+/**
+ * LINES retained verbatim by a compaction rewrite - not sessions. The
+ * unit changed with the fold: a summary kept one line per session and
+ * lost that session's history, whereas keeping raw lines keeps history
+ * and loses only the oldest of it.
+ */
+const RETAIN_LEDGER_LINES = 256;
+/** Gap records retained; the sidecar must not grow without bound either. */
+const MAX_GAP_LINES = 256;
+/**
+ * How long a recorded gap keeps being reported.
+ *
+ * Without an aging policy one burst of writer contention makes
+ * `verifyLineageLedger().ok` false forever and re-emits the same notices
+ * on every doctor run, which trains an operator to ignore the stream the
+ * whole unit exists to populate. A gap is a point-in-time observation,
+ * not a standing defect, so it expires.
+ */
+const GAP_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
+/**
+ * Age at which the SIDECAR's OWN trim lock is treated as abandoned.
+ *
+ * This is a breaker for one lock and one operation, and it is scoped
+ * that narrowly on purpose. The ledger's writer lock never gets one: no
+ * timeout can distinguish a crashed writer from a slow live one, and
+ * killing a live writer's lock corrupts the file it protects. The trim
+ * is different in kind - it is idempotent (keep the newest N records),
+ * it protects diagnostics rather than the ledger, and the alternative is
+ * that one crash inside the trim window disables the bound permanently.
+ */
+const GAP_LOCK_STALE_MS = 60_000;
const STATE_DIR_REL = posix.join(BRAIN_ROOT_REL, ".state");
const LEDGER_FILE = "session-lineage.jsonl";
+const GAPS_FILE = "session-lineage-gaps.jsonl";
+
+/** Site recorded on every notice this module emits. */
+const LEDGER_SITE = "brain.lineage.ledger";
+
+/** Why an observation never reached the ledger. Structural, closed. */
+export const LINEAGE_GAP_REASON = Object.freeze({
+ /** Another writer held the lock; `acquireLockSync` has no retry. */
+ lockBusy: "writer-lock-busy",
+ /** The lock could not be taken for any other reason (permissions, io). */
+ lockFailed: "writer-lock-failed",
+ /** The lock was held but the read-modify-write itself failed. */
+ writeFailed: "write-failed",
+} as const);
+
+export type LineageGapReason = (typeof LINEAGE_GAP_REASON)[keyof typeof LINEAGE_GAP_REASON];
+
+export const LINEAGE_RECORD_STATUS = Object.freeze({
+ appended: "appended",
+ dropped: "dropped",
+} as const);
+
+export type LineageRecordStatus =
+ (typeof LINEAGE_RECORD_STATUS)[keyof typeof LINEAGE_RECORD_STATUS];
+
+/**
+ * Outcome of one {@link recordLineageObservation}. The function used to
+ * return `void`, so a swallowed failure and a successful append were
+ * indistinguishable to its caller; they no longer are.
+ */
+export interface LineageRecordResult {
+ readonly status: LineageRecordStatus;
+ /** Sequence number allocated to the appended line. */
+ readonly seq?: number;
+ /** True when this write also compacted the file. */
+ readonly compacted?: boolean;
+ /** Present only on `dropped`: the named gap. */
+ readonly notice?: DegradationNotice;
+}
+
+/** One recorded gap: an observation that was never appended. */
+export interface LineageGapRecord {
+ readonly sessionId: string;
+ /** The OBSERVATION's timestamp, as the caller reported it. */
+ readonly at: string;
+ /**
+ * When the gap itself was written, on the recording process's clock.
+ *
+ * Distinct from {@link at} on purpose: `at` is host-supplied and can
+ * name any instant (an imported transcript backfills months-old
+ * events), so aging on it would expire a gap recorded seconds ago.
+ * Empty only for a record written before this field existed, which
+ * then ages on `at` as the best available evidence.
+ */
+ readonly recordedAt: string;
+ readonly event: string;
+ readonly reason: string;
+}
export interface LineageObservation {
readonly sessionId: string;
@@ -51,6 +178,14 @@ export interface LineageObservation {
readonly compressionEvidence?: boolean;
/** Resolved lineage to persist alongside the observation. */
readonly lineage?: SessionLineage;
+ /**
+ * Git working state the observation was made in
+ * (context-integrity-gates, Unit C). Absent when the session's `cwd`
+ * is not inside a repository or the bounded probe found nothing; the
+ * remote is already canonicalized, so no credential reaches this
+ * record.
+ */
+ readonly workspace?: GitWorkspaceIdentity;
}
export interface LineageLedgerEntry {
@@ -63,6 +198,13 @@ export interface LineageLedgerEntry {
readonly compressionEvidence: boolean;
/** Last persisted lineage for the session, if any. */
readonly lineage?: SessionLineage;
+ /**
+ * Last attested git working state for the session, if any. Carried
+ * forward from the newest observation that reported one, exactly as
+ * `cwd` is - a probe that came back empty on one event does not erase
+ * what the session already attested.
+ */
+ readonly workspace?: GitWorkspaceIdentity;
}
export type LineageLedgerState = ReadonlyMap<string, LineageLedgerEntry>;
@@ -71,7 +213,16 @@ export function sessionLineageLedgerPath(vault: string): string {
return ensureInsideVault(join(vault, STATE_DIR_REL, LEDGER_FILE), vault);
}
-interface LedgerLine {
+/**
+ * Sidecar holding observations that were never appended. Lives beside
+ * the ledger under the same dot-directory, which is excluded from vault
+ * walking and search indexing - a diagnostic must not become a note.
+ */
+export function sessionLineageGapsPath(vault: string): string {
+ return ensureInsideVault(join(vault, STATE_DIR_REL, GAPS_FILE), vault);
+}
+
+export interface LedgerLine {
readonly sid: string;
readonly at: string;
readonly cwd?: string;
@@ -81,6 +232,86 @@ interface LedgerLine {
readonly root?: string;
readonly depth?: number;
readonly src?: SessionLineage["source"];
+ /** Canonical remote identity (Unit C). Never carries a credential. */
+ readonly repo?: string;
+ readonly branch?: string;
+ readonly commit?: string;
+ /** Monotonic sequence number (Unit D). Absent on pre-chain lines. */
+ readonly seq?: number;
+ /** Chain hash of the preceding line; `null` at a chain anchor. */
+ readonly prev?: string | null;
+ /** This line's chain hash. Absent on pre-chain lines. */
+ readonly h?: string;
+}
+
+/** A parsed line together with the exact text it came from. */
+export interface LineageLedgerLine {
+ /** Verbatim source text - what compaction retains, unchanged. */
+ readonly raw: string;
+ readonly line: LedgerLine;
+}
+
+/** The chain-carrying fields, excluded from the body that is hashed. */
+const CHAIN_FIELDS = ["seq", "prev", "h"] as const;
+
+/**
+ * The hashed body of a line: everything EXCEPT the chain fields. Built
+ * by removal rather than by an allow-list, so a field a future writer
+ * adds is covered by the hash automatically - the same reason
+ * compaction retains raw text instead of re-serializing.
+ */
+function lineBody(line: LedgerLine): Record<string, unknown> {
+ const body: Record<string, unknown> = { ...(line as unknown as Record<string, unknown>) };
+ for (const field of CHAIN_FIELDS) delete body[field];
+ return body;
+}
+
+function chainHash(prev: string | null, seq: number, body: Record<string, unknown>): string {
+ return computePayloadHash({ prev, seq, body });
+}
+
+/**
+ * Recompute the chain hash a stored line SHOULD carry. A line whose
+ * recorded `h` differs from this was edited after it was written.
+ */
+export function lineageChainHash(line: LedgerLine): string {
+ return chainHash(line.prev ?? null, typeof line.seq === "number" ? line.seq : 0, lineBody(line));
+}
+
+/** True when a line carries a usable chain link. */
+export function isChainedLine(line: LedgerLine): boolean {
+ return (
+ typeof line.h === "string" &&
+ line.h.length > 0 &&
+ typeof line.seq === "number" &&
+ Number.isInteger(line.seq) &&
+ line.seq > 0
+ );
+}
+
+/**
+ * Project a workspace identity onto its line fields, omitting the ones
+ * git could not attest. A key that is absent means "not attested" - the
+ * distinction the fail-closed match predicate turns on.
+ */
+function workspaceFields(
+ workspace: GitWorkspaceIdentity | undefined,
+): Pick<LedgerLine, "repo" | "branch" | "commit"> {
+ if (workspace === undefined) return {};
+ return {
+ ...(workspace.repo !== null ? { repo: workspace.repo } : {}),
+ ...(workspace.branch !== null ? { branch: workspace.branch } : {}),
+ ...(workspace.commit !== null ? { commit: workspace.commit } : {}),
+ };
+}
+
+/** Inverse of {@link workspaceFields}; `undefined` when nothing was attested. */
+function readWorkspace(line: LedgerLine): GitWorkspaceIdentity | undefined {
+ const repo = typeof line.repo === "string" ? line.repo : null;
+ const branch = typeof line.branch === "string" ? line.branch : null;
+ const commit = typeof line.commit === "string" ? line.commit : null;
+ if (repo === null && branch === null && commit === null) return undefined;
+ return Object.freeze({ repo, branch, commit });
}
function toLine(obs: LineageObservation): LedgerLine {
@@ -98,25 +329,279 @@ function toLine(obs: LineageObservation): LedgerLine {
src: obs.lineage.source,
}
: {}),
+ ...workspaceFields(obs.workspace),
};
}
-function parseLines(raw: string): LedgerLine[] {
- const out: LedgerLine[] = [];
- for (const line of raw.split("\n")) {
- const trimmed = line.trim();
+/** What one parse of the ledger text found, including what it could not use. */
+interface ParsedLedger {
+ readonly lines: LineageLedgerLine[];
+ /**
+ * 1-based file positions of the non-blank lines that are not a usable
+ * ledger record. Recorded rather than discarded: dropping them
+ * silently is what let a wholly destroyed ledger verify as clean, and
+ * the position is what makes one addressable.
+ */
+ readonly skippedLineNumbers: number[];
+}
+
+/**
+ * Parse the file into lines, KEEPING the source text of each. The raw
+ * text is what compaction writes back, which is how a field this
+ * version does not know about survives a rewrite.
+ */
+function readLedgerLines(raw: string): ParsedLedger {
+ const lines: LineageLedgerLine[] = [];
+ const skippedLineNumbers: number[] = [];
+ const source = raw.split("\n");
+ for (let index = 0; index < source.length; index++) {
+ const trimmed = source[index]!.trim();
if (trimmed.length === 0) continue;
+ const lineNumber = index + 1;
try {
const parsed = JSON.parse(trimmed) as unknown;
- if (parsed === null || typeof parsed !== "object") continue;
+ if (parsed === null || typeof parsed !== "object") {
+ skippedLineNumbers.push(lineNumber);
+ continue;
+ }
const candidate = parsed as LedgerLine;
- if (typeof candidate.sid !== "string" || typeof candidate.at !== "string") continue;
- out.push(candidate);
+ if (typeof candidate.sid !== "string" || typeof candidate.at !== "string") {
+ skippedLineNumbers.push(lineNumber);
+ continue;
+ }
+ lines.push({ raw: trimmed, line: candidate });
+ } catch {
+ // Fail-soft for the READ path, recorded for the VERIFIER: a corrupt
+ // line never poisons resolution, and never passes unreported.
+ skippedLineNumbers.push(lineNumber);
+ }
+ }
+ return { lines, skippedLineNumbers };
+}
+
+/**
+ * One read of the ledger file, with the three states the old
+ * `LineageLedgerLine[]` return collapsed into an empty array: the file
+ * is absent, the file is present but could not be read, or the file was
+ * read and some of it was not usable.
+ */
+export interface LineageLedgerScan {
+ /** The ledger file exists on disk. */
+ readonly exists: boolean;
+ /** The file's bytes were obtained. False for an absent or unreadable file. */
+ readonly readable: boolean;
+ /** Usable records, in file order. */
+ readonly lines: ReadonlyArray<LineageLedgerLine>;
+ /** 1-based positions of the non-blank lines that could not be read. */
+ readonly skippedLineNumbers: ReadonlyArray<number>;
+}
+
+/**
+ * Read the ledger as parsed lines in file order, reporting what it could
+ * not use. Fail-soft like every other read here - it never throws, and
+ * an unreadable file yields no lines - but the caller can now tell an
+ * absent ledger from a destroyed one. Exposed for `verify.ts`, which
+ * needs line order and the chain fields that per-session state folds
+ * away.
+ */
+export function scanLineageLedger(vault: string): LineageLedgerScan {
+ const absent = Object.freeze({
+ exists: false,
+ readable: false,
+ lines: Object.freeze([]),
+ skippedLineNumbers: Object.freeze([]),
+ });
+ let path: string;
+ try {
+ path = sessionLineageLedgerPath(vault);
+ } catch {
+ return absent;
+ }
+ if (!existsSync(path)) return absent;
+ let raw: string;
+ try {
+ raw = readFileSync(path, "utf8");
+ } catch {
+ return Object.freeze({
+ exists: true,
+ readable: false,
+ lines: Object.freeze([]),
+ skippedLineNumbers: Object.freeze([]),
+ });
+ }
+ const parsed = readLedgerLines(raw);
+ return Object.freeze({
+ exists: true,
+ readable: true,
+ lines: Object.freeze(parsed.lines),
+ skippedLineNumbers: Object.freeze(parsed.skippedLineNumbers),
+ });
+}
+
+/** The sidecar as a whole: what it still lists, and what it no longer can. */
+export interface LineageGapReport {
+ /** The sidecar file exists on disk. */
+ readonly exists: boolean;
+ /** Gap records still within the retention window, oldest first. */
+ readonly records: ReadonlyArray<LineageGapRecord>;
+ /**
+ * Records the sidecar's bound discarded. They are COUNTED, never
+ * listed, so a capped listing is never mistaken for a complete one.
+ */
+ readonly discarded: number;
+ /** True when `discarded > 0`: {@link records} is a suffix, not the whole. */
+ readonly truncated: boolean;
+ /** Dropped observations still on the record: listed plus discarded. */
+ readonly total: number;
+}
+
+export interface ReadLineageGapsOptions {
+ /** Injected clock (epoch ms) for the retention window. */
+ readonly nowMs?: number;
+}
+
+/** One line of the sidecar: either a gap record or the truncation marker. */
+interface ParsedGapFile {
+ readonly records: LineageGapRecord[];
+ /** Records earlier trims discarded, from the accumulator line. */
+ readonly discarded: number;
+ /** When the accumulator was last written; `null` when there is none. */
+ readonly discardedAt: string | null;
+ /** Records this parse dropped because they fell outside retention. */
+ readonly aged: number;
+}
+
+/** Key that distinguishes the accumulator line from a gap record. */
+const GAP_DISCARDED_KEY = "discarded";
+/** Key carrying {@link LineageGapRecord.recordedAt} on the wire. */
+const GAP_RECORDED_AT_KEY = "rat";
+
+function parseGapFile(raw: string, nowMs: number): ParsedGapFile {
+ const records: LineageGapRecord[] = [];
+ let discarded = 0;
+ let discardedAt: string | null = null;
+ let aged = 0;
+ for (const line of raw.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.length === 0) continue;
+ let parsed: Record<string, unknown>;
+ try {
+ parsed = JSON.parse(trimmed) as Record<string, unknown>;
} catch {
- // Fail-soft: a corrupt line never poisons the ledger.
+ // A corrupt gap line is itself a gap we cannot name; skip it.
+ continue;
+ }
+ const count = parsed[GAP_DISCARDED_KEY];
+ if (typeof count === "number" && Number.isFinite(count)) {
+ const at = typeof parsed["at"] === "string" ? parsed["at"] : "";
+ if (!isExpired(at, nowMs)) {
+ discarded += Math.max(0, Math.trunc(count));
+ discardedAt = at;
+ }
+ continue;
}
+ if (typeof parsed["sid"] !== "string") continue;
+ const at = typeof parsed["at"] === "string" ? parsed["at"] : "";
+ const recordedAt = typeof parsed[GAP_RECORDED_AT_KEY] === "string" ? parsed["rat"] : "";
+ if (isExpired(recordedAt.length > 0 ? recordedAt : at, nowMs)) {
+ aged++;
+ continue;
+ }
+ records.push({
+ sessionId: parsed["sid"],
+ at,
+ recordedAt,
+ event: typeof parsed["event"] === "string" ? parsed["event"] : "unknown",
+ reason: typeof parsed["reason"] === "string" ? parsed["reason"] : "unknown",
+ });
}
- return out;
+ return { records, discarded, discardedAt, aged };
+}
+
+/**
+ * The on-disk form of one gap record. Written by the append AND by the
+ * trim's rewrite, so a trimmed sidecar is byte-comparable with a
+ * freshly appended one and no field is lost in the round trip.
+ */
+function gapLine(record: LineageGapRecord): Record<string, unknown> {
+ return {
+ sid: record.sessionId,
+ at: record.at,
+ ...(record.recordedAt.length > 0 ? { [GAP_RECORDED_AT_KEY]: record.recordedAt } : {}),
+ event: record.event,
+ reason: record.reason,
+ };
+}
+
+/**
+ * True when a recorded instant is older than the retention window. An
+ * undatable record never expires: aging out something whose age is
+ * unknown would be a guess, and this module reports rather than guesses.
+ */
+function isExpired(at: string, nowMs: number): boolean {
+ const ms = Date.parse(at);
+ if (!Number.isFinite(ms)) return false;
+ return nowMs - ms > GAP_RETENTION_MS;
+}
+
+/**
+ * Read the sidecar. Fail-soft; a missing sidecar reads as none.
+ * Records older than {@link GAP_RETENTION_MS} are omitted here as well as
+ * pruned on the next trim, so a vault that has stopped dropping
+ * observations stops reporting them even if nothing writes again.
+ */
+export function readLineageGapReport(
+ vault: string,
+ opts: ReadLineageGapsOptions = {},
+): LineageGapReport {
+ const nowMs = opts.nowMs ?? Date.now();
+ const empty = Object.freeze({
+ exists: false,
+ records: Object.freeze([]),
+ discarded: 0,
+ truncated: false,
+ total: 0,
+ });
+ let raw: string;
+ try {
+ const path = sessionLineageGapsPath(vault);
+ if (!existsSync(path)) return empty;
+ raw = readFileSync(path, "utf8");
+ } catch {
+ return empty;
+ }
+ const parsed = parseGapFile(raw, nowMs);
+ return Object.freeze({
+ exists: true,
+ records: Object.freeze(parsed.records),
+ discarded: parsed.discarded,
+ truncated: parsed.discarded > 0,
+ total: parsed.records.length + parsed.discarded,
+ });
+}
+
+/** The listed gap records. See {@link readLineageGapReport} for the rest. */
+export function readLineageGaps(
+ vault: string,
+ opts: ReadLineageGapsOptions = {},
+): ReadonlyArray<LineageGapRecord> {
+ return readLineageGapReport(vault, opts).records;
+}
+
+/**
+ * Session ids that spoke but whose observation never reached the ledger.
+ *
+ * This is the OTHER half of "does this session have history of its own".
+ * The crutch's Rule 1 reads the ledger for the session's own line and
+ * treats its absence as proof of a brand-new session; a writer-lock drop
+ * removes exactly that line, so without this set a session that DID
+ * speak looks new and can be stitched onto an unrelated parallel one.
+ * Fail-soft like every read here.
+ */
+export function lineageGapSessionIds(vault: string): ReadonlySet<string> {
+ const ids = new Set<string>();
+ for (const gap of readLineageGaps(vault)) ids.add(gap.sessionId);
+ return ids;
}
function buildState(lines: ReadonlyArray<LedgerLine>): Map<string, LineageLedgerEntry> {
@@ -134,6 +619,7 @@ function buildState(lines: ReadonlyArray<LedgerLine>): Map<string, LineageLedger
source: line.src,
})
: prev?.lineage;
+ const workspace = readWorkspace(line) ?? prev?.workspace;
state.set(line.sid, {
sessionId: line.sid,
firstSeenMs: prev === undefined ? atMs : Math.min(prev.firstSeenMs, atMs),
@@ -146,70 +632,238 @@ function buildState(lines: ReadonlyArray<LedgerLine>): Map<string, LineageLedger
lastEvent: line.event ?? prev?.lastEvent ?? "unknown",
compressionEvidence: line.ce === true,
...(lineage !== undefined ? { lineage } : {}),
+ ...(workspace !== undefined ? { workspace } : {}),
});
}
return state;
}
-/** Read the ledger into per-session state. Missing file reads empty. */
+/**
+ * Read the ledger into per-session state. Missing file reads empty.
+ *
+ * Deliberately does NOT verify the chain. The catch-to-empty-map below
+ * is load-bearing for `resolveRootId` in the anticipatory cache and for
+ * the lifecycle hook, both of which treat "no lineage" as a normal
+ * state and neither of which can handle a throw. Integrity findings
+ * belong to `verify.ts`, which reports them to the doctor.
+ */
export function readLineageLedger(vault: string): LineageLedgerState {
- const path = sessionLineageLedgerPath(vault);
- if (!existsSync(path)) return new Map();
- let raw: string;
+ return buildState(scanLineageLedger(vault).lines.map((entry) => entry.line));
+}
+
+/**
+ * Append one observation under the writer lock, compacting the file
+ * (atomic rewrite keeping the most recent lines verbatim) once it
+ * crosses the line cap.
+ *
+ * Fail-soft by contract: nothing here throws into a lifecycle hook. But
+ * a failure is no longer SILENT - a dropped observation is written to
+ * the gap sidecar and returned as a named notice, so the absence is
+ * attributable instead of being indistinguishable from a session that
+ * simply never spoke.
+ */
+export function recordLineageObservation(
+ vault: string,
+ obs: LineageObservation,
+): LineageRecordResult {
+ // Vault-identity write guard (Unit J), AHEAD OF THE FIRST BYTE: the
+ // `mkdirSync` below materializes `Brain/.state/` under whatever root
+ // it is handed, so asserting after it would refuse a store this
+ // function had already created. A refusal is returned as a named drop,
+ // never thrown, and deliberately does NOT reach the gap sidecar -
+ // writing the diagnostic into the wrong vault is the very thing the
+ // guard just refused.
try {
- raw = readFileSync(path, "utf8");
+ assertVaultIdentityForWrite(vault);
+ } catch (err) {
+ return {
+ status: LINEAGE_RECORD_STATUS.dropped,
+ notice:
+ err instanceof VaultIdentityMismatchError
+ ? err.notice
+ : degradationNotice({
+ code: DEGRADATION_CODE.vaultMarkerMismatch,
+ site: LEDGER_SITE,
+ detail:
+ `observation for session ${obs.sessionId} (event ${obs.event}) ` +
+ "was not appended: the vault write guard refused this root",
+ }),
+ };
+ }
+
+ let handle: LockHandle | undefined;
+ try {
+ const path = sessionLineageLedgerPath(vault);
+ mkdirSync(dirname(path), { recursive: true });
+ try {
+ handle = acquireLockSync(path);
+ } catch (err) {
+ // No retry, by the lock's design: a loud named gap beats a silent
+ // retry loop that still fails. The gap is exactly what the
+ // sequence numbers above would otherwise leave unexplained. The
+ // lock file is NAMED on the notice: a lock left behind by a
+ // SIGKILLed writer disables capture for the life of the vault, and
+ // an operator cannot remove a file the diagnostic never mentions.
+ const errno = err as NodeJS.ErrnoException;
+ return recordGap(
+ vault,
+ obs,
+ errno.code === "ELOCKED" ? LINEAGE_GAP_REASON.lockBusy : LINEAGE_GAP_REASON.lockFailed,
+ typeof errno.path === "string" ? errno.path : undefined,
+ );
+ }
+
+ // Re-read UNDER the lock, exactly as the idempotency ledger does:
+ // the chain head and the next sequence number must come from the
+ // file as it is now, not as it was before the lock was taken.
+ const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
+ const entries = readLedgerLines(existing).lines;
+ const body = toLine(obs);
+ const { seq, prev } = nextChainPosition(entries);
+ const line: LedgerLine = {
+ ...body,
+ seq,
+ prev,
+ h: chainHash(prev, seq, body as unknown as Record<string, unknown>),
+ };
+ const serialized = JSON.stringify(line);
+
+ if (entries.length + 1 > MAX_LEDGER_LINES) {
+ // Verbatim retention: raw source text, never a re-serialization.
+ // Retained lines keep their own sequence numbers and chain links,
+ // so the chain stays contiguous across the truncation.
+ const retained = entries.slice(-RETAIN_LEDGER_LINES).map((entry) => entry.raw);
+ retained.push(serialized);
+ atomicWriteFileSync(path, `${retained.join("\n")}\n`);
+ return { status: LINEAGE_RECORD_STATUS.appended, seq, compacted: true };
+ }
+ appendFileSync(path, `${serialized}\n`, "utf8");
+ return { status: LINEAGE_RECORD_STATUS.appended, seq };
} catch {
- return new Map();
+ return recordGap(vault, obs, LINEAGE_GAP_REASON.writeFailed);
+ } finally {
+ handle?.release();
}
- return buildState(parseLines(raw));
}
/**
- * Append one observation; compact the file (atomic rewrite keeping the
- * most recent sessions) once it crosses the line cap. Fail-soft: any
- * filesystem error is swallowed - lineage is an enhancement, never a
- * capture blocker.
+ * Sequence number and chain link for the next line. Sequence numbers
+ * continue from the last CHAINED line, so a compacted file keeps
+ * counting from where its retained head left off, and a pre-chain
+ * ledger starts a fresh chain at 1 with a null anchor.
*/
-export function recordLineageObservation(vault: string, obs: LineageObservation): void {
+function nextChainPosition(entries: ReadonlyArray<LineageLedgerLine>): {
+ seq: number;
+ prev: string | null;
+} {
+ for (let index = entries.length - 1; index >= 0; index--) {
+ const line = entries[index]!.line;
+ if (!isChainedLine(line)) continue;
+ return { seq: line.seq! + 1, prev: line.h! };
+ }
+ return { seq: 1, prev: null };
+}
+
+/**
+ * Record an observation that never reached the ledger. Best-effort and
+ * itself fail-soft: if even the sidecar cannot be written, the returned
+ * notice is the only trace, which is still strictly more than the
+ * nothing this path used to leave.
+ */
+function recordGap(
+ vault: string,
+ obs: LineageObservation,
+ reason: LineageGapReason,
+ lockPath?: string,
+): LineageRecordResult {
+ const notice = degradationNotice({
+ code: DEGRADATION_CODE.lineageObservationDropped,
+ site: LEDGER_SITE,
+ ...(lockPath !== undefined ? { path: lockPath } : {}),
+ detail:
+ `observation for session ${obs.sessionId} (event ${obs.event}) ` +
+ `was not appended: ${reason}` +
+ (lockPath !== undefined ? `; the lock is held at ${lockPath}` : ""),
+ });
try {
- const path = sessionLineageLedgerPath(vault);
+ const path = sessionLineageGapsPath(vault);
mkdirSync(dirname(path), { recursive: true });
- const serialized = `${JSON.stringify(toLine(obs))}\n`;
- const existing = existsSync(path) ? readFileSync(path, "utf8") : "";
- const lines = parseLines(existing);
- if (lines.length + 1 > MAX_LEDGER_LINES) {
- lines.push(toLine(obs));
- const state = buildState(lines);
- const retained = [...state.values()]
- .toSorted((a, b) => b.lastSeenMs - a.lastSeenMs)
- .slice(0, RETAIN_SESSIONS);
- // One summary line per retained session, oldest first so a
- // future append keeps chronological order readable.
- retained.reverse();
- const compacted = retained
- .map((entry) =>
- JSON.stringify({
- sid: entry.sessionId,
- at: new Date(entry.lastSeenMs).toISOString(),
- ...(entry.cwd !== undefined ? { cwd: entry.cwd } : {}),
- event: entry.lastEvent,
- ...(entry.compressionEvidence ? { ce: true } : {}),
- ...(entry.lineage !== undefined
- ? {
- parent: entry.lineage.parentId,
- root: entry.lineage.rootId,
- depth: entry.lineage.depth,
- src: entry.lineage.source,
- }
- : {}),
- }),
- )
- .join("\n");
- atomicWriteFileSync(path, `${compacted}\n`);
- return;
+ const nowMs = Date.now();
+ // O_APPEND: concurrent gap writers cannot interleave a short line.
+ appendFileSync(
+ path,
+ `${JSON.stringify(gapLine({ sessionId: obs.sessionId, at: obs.at, recordedAt: new Date(nowMs).toISOString(), event: obs.event, reason }))}\n`,
+ "utf8",
+ );
+ boundGapSidecar(path, nowMs);
+ } catch {
+ // The gap could not be persisted; the notice still names it.
+ }
+ return { status: LINEAGE_RECORD_STATUS.dropped, notice };
+}
+
+/**
+ * Keep the gap sidecar bounded, aged, and HONEST about the difference.
+ *
+ * Three properties, each of which was previously absent:
+ *
+ * - the bound always applies. The trim takes the sidecar's OWN lock
+ * (never the ledger's, so it cannot deadlock against the writer that
+ * called it) and reclaims that lock once it is older than
+ * {@link GAP_LOCK_STALE_MS} - otherwise one crash inside the trim
+ * window leaves a lock nothing ever removes and the bound stops
+ * existing for the life of the vault;
+ * - records past {@link GAP_RETENTION_MS} are pruned, so a burst of
+ * contention stops being reported instead of pinning the verifier's
+ * verdict to `false` permanently;
+ * - every record the bound removes is ADDED TO AN ACCUMULATOR, so 400
+ * drops are never presented as the 256 that happen to still be
+ * listed.
+ */
+function boundGapSidecar(path: string, nowMs: number): void {
+ let handle: LockHandle | undefined;
+ try {
+ const before = parseGapFile(readFileSync(path, "utf8"), nowMs);
+ if (before.records.length <= MAX_GAP_LINES && before.aged === 0) return;
+ handle = acquireGapLock(path, nowMs);
+ // Re-read under the lock: another writer may have appended, and the
+ // count that decides the trim must be the current one.
+ const current = parseGapFile(readFileSync(path, "utf8"), nowMs);
+ const kept = current.records.slice(-MAX_GAP_LINES);
+ const discarded = current.discarded + (current.records.length - kept.length);
+ const lines: string[] = [];
+ if (discarded > 0) {
+ lines.push(
+ JSON.stringify({ [GAP_DISCARDED_KEY]: discarded, at: new Date(nowMs).toISOString() }),
+ );
}
- appendFileSync(path, serialized, "utf8");
+ for (const record of kept) lines.push(JSON.stringify(gapLine(record)));
+ atomicWriteFileSync(path, lines.length === 0 ? "" : `${lines.join("\n")}\n`);
} catch {
- // Fail-soft by contract.
+ // Best-effort: the sidecar is diagnostics, and a failed trim must
+ // never propagate into the capture path that recorded the gap.
+ } finally {
+ handle?.release();
+ }
+}
+
+/**
+ * Take the sidecar's trim lock, reclaiming it once when it is provably
+ * abandoned. Scoped to this one lock and this one idempotent operation -
+ * see {@link GAP_LOCK_STALE_MS} for why the ledger's writer lock gets no
+ * such treatment.
+ */
+function acquireGapLock(path: string, nowMs: number): LockHandle {
+ try {
+ return acquireLockSync(path);
+ } catch (err) {
+ const errno = err as NodeJS.ErrnoException;
+ if (errno.code !== "ELOCKED") throw err;
+ const lockPath = typeof errno.path === "string" ? errno.path : `${path}.lock`;
+ if (nowMs - statSync(lockPath).mtimeMs <= GAP_LOCK_STALE_MS) throw err;
+ unlinkSync(lockPath);
+ // Exactly one retry. A second ELOCKED means a live writer took the
+ // lock in between, which is contention rather than abandonment.
+ return acquireLockSync(path);
}
}
diff --git a/src/core/brain/lineage/resolve.ts b/src/core/brain/lineage/resolve.ts
index 09c6e812..b22fc763 100644
--- a/src/core/brain/lineage/resolve.ts
+++ b/src/core/brain/lineage/resolve.ts
@@ -5,28 +5,96 @@
* belong to". Precedence: native payload fields, then the interim
* ledger crutch, then flat. See `types.ts` for the contract and
* `crutch.ts` for the conservative inference rules.
+ *
+ * Two entry points, following the sibling pattern this repository uses
+ * wherever a diagnostic channel is grafted onto an established
+ * signature: {@link resolveSessionLineageDetailed} carries the crutch's
+ * named outcome, and {@link resolveSessionLineage} delegates to it and
+ * discards everything but the lineage, so every pre-existing caller
+ * stays byte-identical.
*/
-import { resolveCrutchLineage } from "./crutch.ts";
+import { CRUTCH_ABSTENTION, type CrutchOutcome, resolveCrutchLineage } from "./crutch.ts";
import type { LineageLedgerState } from "./ledger.ts";
import type { LineageHints, SessionLineage } from "./types.ts";
+import {
+ DEGRADATION_CODE,
+ type DegradationNotice,
+ emitDegradationNotice,
+} from "../../integrity/degradation.ts";
export interface ResolveLineageOptions {
/** Ledger state for the crutch path; omit to disable the crutch. */
readonly ledger?: LineageLedgerState;
+ /**
+ * Sessions the ledger's gap sidecar records as dropped
+ * (`lineageGapSessionIds`). Threaded straight into the crutch, where
+ * it completes Rule 1: a session whose observation the writer lock
+ * refused still has history, and without this it would be stitched
+ * onto an unrelated parallel session.
+ */
+ readonly gapSessionIds?: ReadonlySet<string>;
/** Clock injected by the caller (epoch ms). Required for the crutch. */
readonly nowMs?: number;
+ /**
+ * Opt-in sink for degradation notices (context-integrity-gates).
+ * Absent means no diagnostics are produced at all, which is why
+ * adding the channel changed no existing caller.
+ */
+ readonly notices?: DegradationNotice[];
+}
+
+/** Lineage plus the evidence behind it. */
+export interface SessionLineageResolution {
+ readonly lineage: SessionLineage;
+ /**
+ * The crutch's named outcome, present only when the crutch actually
+ * ran (a ledger was supplied and the native payload did not already
+ * decide). A `linked` outcome IS the lineage; an `abstained` one is
+ * why continuation was refused.
+ */
+ readonly crutch?: CrutchOutcome;
}
+/** Site recorded on the notices this module emits. */
+const RESOLVE_SITE = "brain.lineage.resolve";
+
+/**
+ * Abstentions worth reporting. `no-candidate`, `self-known` and
+ * `no-workspace` are the ORDINARY flat path - a first session, a
+ * parallel session, a host that reports no directory - and emitting a
+ * notice for them would bury the three that mean a continuation was
+ * available and refused.
+ */
+const REPORTABLE_ABSTENTIONS: ReadonlySet<string> = new Set([
+ CRUTCH_ABSTENTION.ambiguous,
+ CRUTCH_ABSTENTION.stale,
+ CRUTCH_ABSTENTION.evidenceMissing,
+]);
+
function readId(value: string | null | undefined): string | null {
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
+const FLAT_SOURCE = "flat";
+
/** Resolve the lineage of one session id. Never throws. */
export function resolveSessionLineage(
hints: LineageHints,
opts: ResolveLineageOptions = {},
): SessionLineage {
+ return resolveSessionLineageDetailed(hints, opts).lineage;
+}
+
+/**
+ * Resolve the lineage of one session id AND report how it was decided.
+ * Never throws: a refusal is a returned value, because this runs inside
+ * capture paths that are fail-soft by contract.
+ */
+export function resolveSessionLineageDetailed(
+ hints: LineageHints,
+ opts: ResolveLineageOptions = {},
+): SessionLineageResolution {
const sessionId = hints.sessionId;
// Native path: any genuine lineage field on the payload wins. A
@@ -44,30 +112,60 @@ export function resolveSessionLineage(
// lineage, inherit its root (and continue its depth count).
const parentLineage = parentId !== null ? opts.ledger?.get(parentId)?.lineage : undefined;
const inheritedRoot =
- parentLineage !== undefined && parentLineage.source !== "flat" ? parentLineage.rootId : null;
+ parentLineage !== undefined && parentLineage.source !== FLAT_SOURCE
+ ? parentLineage.rootId
+ : null;
const depthRaw = hints.compressionDepth;
const depth =
typeof depthRaw === "number" && Number.isInteger(depthRaw) && depthRaw >= 0
? depthRaw
: parentId !== null
- ? (parentLineage !== undefined && parentLineage.source !== "flat"
+ ? (parentLineage !== undefined && parentLineage.source !== FLAT_SOURCE
? parentLineage.depth
: 0) + 1
: 0;
- return Object.freeze({
- rootId: rootFromPayload ?? inheritedRoot ?? parentId ?? sessionId,
- parentId,
- depth,
- source: "payload" as const,
- });
+ return {
+ lineage: Object.freeze({
+ rootId: rootFromPayload ?? inheritedRoot ?? parentId ?? sessionId,
+ parentId,
+ depth,
+ source: "payload" as const,
+ }),
+ };
}
// Interim inference for hosts without native lineage fields.
// CRUTCH(t_1459706f).
if (opts.ledger !== undefined) {
- const inferred = resolveCrutchLineage(sessionId, hints.cwd, opts.ledger, opts.nowMs ?? 0);
- if (inferred !== null) return inferred;
+ const outcome = resolveCrutchLineage({
+ sessionId,
+ ...(hints.cwd !== undefined ? { cwd: hints.cwd } : {}),
+ ledger: opts.ledger,
+ nowMs: opts.nowMs ?? 0,
+ ...(hints.workspace !== undefined ? { workspace: hints.workspace } : {}),
+ ...(opts.gapSessionIds !== undefined ? { gapSessionIds: opts.gapSessionIds } : {}),
+ });
+ if (outcome.kind === "linked") {
+ return { lineage: outcome.lineage, crutch: outcome };
+ }
+ if (opts.notices !== undefined && REPORTABLE_ABSTENTIONS.has(outcome.reason)) {
+ emitDegradationNotice(opts.notices, {
+ code: DEGRADATION_CODE.sessionLinkAbstained,
+ site: RESOLVE_SITE,
+ detail: `${outcome.reason}: ${outcome.detail} (session ${sessionId})`,
+ });
+ }
+ return { lineage: flat(sessionId), crutch: outcome };
}
- return Object.freeze({ rootId: sessionId, parentId: null, depth: 0, source: "flat" as const });
+ return { lineage: flat(sessionId) };
+}
+
+function flat(sessionId: string): SessionLineage {
+ return Object.freeze({
+ rootId: sessionId,
+ parentId: null,
+ depth: 0,
+ source: FLAT_SOURCE,
+ });
}
diff --git a/src/core/brain/lineage/types.ts b/src/core/brain/lineage/types.ts
index 8118ede2..1cf4ca71 100644
--- a/src/core/brain/lineage/types.ts
+++ b/src/core/brain/lineage/types.ts
@@ -17,6 +17,8 @@
* every ambiguous case.
*/
+import type { GitWorkspaceIdentity } from "../git/reader.ts";
+
export type SessionLineageSource = "payload" | "crutch" | "flat";
export interface SessionLineage {
@@ -41,6 +43,14 @@ export interface LineageHints {
readonly compressionDepth?: number | null;
/** Working directory the host reported for the session, if any. */
readonly cwd?: string;
+ /**
+ * Git working state observed at `cwd` (context-integrity-gates, Unit
+ * C): repo, branch and commit, which join `cwd` as required-match
+ * predicates for the interim crutch. Passed IN rather than probed
+ * here so lineage resolution stays a pure function of its inputs -
+ * the shell-out lives at the capture boundary, once per hook.
+ */
+ readonly workspace?: GitWorkspaceIdentity;
}
/**
diff --git a/src/core/brain/lineage/verify.ts b/src/core/brain/lineage/verify.ts
new file mode 100644
index 00000000..1662aa11
--- /dev/null
+++ b/src/core/brain/lineage/verify.ts
@@ -0,0 +1,285 @@
+/**
+ * Lineage ledger verification (context-integrity-gates, Unit D).
+ *
+ * The ledger is append-only JSONL whose read path is fail-soft BY
+ * CONTRACT: `readLineageLedger` returns an empty map rather than
+ * throwing, because both `resolveRootId` in the anticipatory cache and
+ * the session-lifecycle hook depend on it never raising. That contract
+ * is exactly why verification lives HERE and not there.
+ *
+ * This module REPORTS. It never refuses to start, never mutates the
+ * ledger, and never changes what resolution returns - a ledger with a
+ * broken chain still resolves lineage, and the break is surfaced as a
+ * doctor finding instead of as an outage. Making the ledger a security
+ * boundary is explicitly out of scope; the property being defended is
+ * that an edited, truncated or never-written line is DETECTABLE, not
+ * that it is impossible.
+ *
+ * Three conditions are checked over the chained lines, in file order:
+ *
+ * - a line whose recomputed hash differs from its recorded one was
+ * edited after it was written;
+ * - a line whose `prev` does not match the preceding chained line's
+ * hash means a line between them was removed or reordered;
+ * - a sequence number that does not follow its predecessor's is the
+ * same condition seen from the other side.
+ *
+ * The FIRST chained line in the file is an anchor and is not checked
+ * against a predecessor: compaction drops the head of the file by
+ * design, so its `prev` legitimately names a line that no longer
+ * exists.
+ *
+ * Three more conditions concern lines the chain checks never see, and
+ * each of them used to verify as CLEAN:
+ *
+ * - a non-blank line that is not a usable record. The reader drops it
+ * so that resolution survives; the verifier counts it, because a
+ * file of pure garbage reporting `ok: true` is the exact silent
+ * failure this wave exists to remove;
+ * - a ledger that exists but cannot be read. Nothing in it was
+ * verified, and "not verified" is not "verified clean";
+ * - a line with NO chain fields appearing after a chained one. Lines
+ * predating the chain are legitimate and sit at the head of the
+ * file, so they stay uncounted as findings - but the same shape in
+ * the middle is a line whose links were stripped, and because a
+ * legacy line resets the anchor it also silences the `prev` check on
+ * its successor. That is how a tampered middle line used to pass.
+ *
+ * Recorded gaps - observations the writer could not append, usually
+ * because another process held the lock - are surfaced too. A gap is
+ * the one failure the chain cannot show by itself: an observation that
+ * never got a sequence number leaves no hole to find.
+ */
+
+import {
+ DEGRADATION_CODE,
+ type DegradationNotice,
+ emitDegradationNotice,
+} from "../../integrity/degradation.ts";
+import {
+ isChainedLine,
+ type LedgerLine,
+ lineageChainHash,
+ readLineageGapReport,
+ scanLineageLedger,
+ sessionLineageLedgerPath,
+} from "./ledger.ts";
+
+/** Site recorded on every notice this module emits. */
+const VERIFY_SITE = "brain.lineage.verify";
+
+/**
+ * Findings of one kind listed individually before the rest are folded
+ * into a single counted notice.
+ *
+ * A destroyed ledger or a contention burst produces hundreds of
+ * identical findings, and pouring all of them into the doctor's
+ * `uncertain` stream buries every other diagnostic beside them. The
+ * remainder is never dropped: it is reported as an explicit count, so a
+ * capped listing is never mistaken for the whole finding.
+ */
+const MAX_ITEMIZED_FINDINGS = 20;
+
+export interface LineageLedgerVerification {
+ /** The ledger that was verified, whether or not it exists. */
+ readonly path: string;
+ /** The ledger file is on disk. Distinguishes "no ledger" from "empty ledger". */
+ readonly exists: boolean;
+ /** The file's bytes were obtained. False for an absent OR unreadable ledger. */
+ readonly readable: boolean;
+ /** Parseable lines found. */
+ readonly lines: number;
+ /** Non-blank lines that could not be read as a record. Each is a finding. */
+ readonly skipped: number;
+ /** Lines carrying a sequence number and a chain hash. */
+ readonly chained: number;
+ /** Lines carrying no chain fields. A finding only AFTER a chained line. */
+ readonly legacy: number;
+ /** Observations recorded as never-appended gaps, listed plus discarded. */
+ readonly droppedObservations: number;
+ /** True when the gap sidecar's bound discarded records it can no longer list. */
+ readonly gapsTruncated: boolean;
+ /** Every finding, in file order. Empty on a clean ledger. */
+ readonly notices: ReadonlyArray<DegradationNotice>;
+ /** True when nothing was found. */
+ readonly ok: boolean;
+}
+
+export interface VerifyLineageLedgerOptions {
+ /** Injected clock (epoch ms) for the gap retention window. */
+ readonly nowMs?: number;
+}
+
+/**
+ * Verify the ledger's sequence and hash chain and collect recorded
+ * gaps. Never throws: an unreadable or unparseable ledger reports what
+ * it could read, because a verifier that fails on the file it exists to
+ * inspect reproduces the silent failure it is meant to remove.
+ *
+ * It does not, however, report such a ledger as CLEAN. `ok` used to be
+ * true for a file of pure garbage, for a wholly truncated one, and for
+ * one the process could not open, because the reader dropped every
+ * unusable line before the verifier could count it. Those three are now
+ * findings; the read path that resolution depends on is unchanged.
+ */
+export function verifyLineageLedger(
+ vault: string,
+ opts: VerifyLineageLedgerOptions = {},
+): LineageLedgerVerification {
+ const notices: DegradationNotice[] = [];
+ const path = safeLedgerPath(vault);
+ let chained = 0;
+ let legacy = 0;
+
+ const scan = scanLineageLedger(vault);
+ if (scan.exists && !scan.readable) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageChainBroken,
+ site: VERIFY_SITE,
+ path,
+ detail:
+ "the ledger exists but could not be read, so no line in it was verified - " +
+ "an unverifiable history is not a clean one",
+ });
+ }
+ const skipped = scan.skippedLineNumbers;
+ for (const lineNumber of skipped.slice(0, MAX_ITEMIZED_FINDINGS)) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageChainBroken,
+ site: VERIFY_SITE,
+ path,
+ detail:
+ `line ${lineNumber} could not be read as a ledger record; the observation it ` +
+ "carried is lost, which is not the same as never having been made",
+ });
+ }
+ if (skipped.length > MAX_ITEMIZED_FINDINGS) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageChainBroken,
+ site: VERIFY_SITE,
+ path,
+ detail:
+ `${skipped.length - MAX_ITEMIZED_FINDINGS} further lines could not be read as a ` +
+ `ledger record and are not itemized (${skipped.length} of ` +
+ `${skipped.length + scan.lines.length} non-blank lines in total)`,
+ });
+ }
+
+ let previous: LedgerLine | undefined;
+ let sawChained = false;
+ let legacyReported = 0;
+ for (const entry of scan.lines) {
+ const line = entry.line;
+ if (!isChainedLine(line)) {
+ legacy++;
+ // Lines predating the chain are legitimate and sit at the HEAD of
+ // the file. One appearing after a chained line is not history: it
+ // is a line whose chain fields were removed, and because it resets
+ // the anchor below it also leaves its successor's `prev`
+ // unchecked - which is how a tampered middle line used to pass.
+ if (sawChained && legacyReported < MAX_ITEMIZED_FINDINGS) {
+ legacyReported++;
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageChainBroken,
+ site: VERIFY_SITE,
+ path,
+ detail:
+ `session ${line.sid} at ${line.at}: a line with no chain fields follows a chained ` +
+ "one - its links were stripped, and the next line's is no longer checkable",
+ });
+ }
+ // A legacy line breaks the adjacency the checks below rely on;
+ // the next chained line becomes a fresh anchor.
+ previous = undefined;
+ continue;
+ }
+ chained++;
+ sawChained = true;
+ checkChainedLine(line, previous, notices);
+ previous = line;
+ }
+
+ const gaps = readLineageGapReport(vault, opts.nowMs !== undefined ? { nowMs: opts.nowMs } : {});
+ for (const gap of gaps.records.slice(0, MAX_ITEMIZED_FINDINGS)) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageObservationDropped,
+ site: VERIFY_SITE,
+ detail:
+ `observation for session ${gap.sessionId} (event ${gap.event}) ` +
+ `was never appended: ${gap.reason}`,
+ });
+ }
+ const unlisted = gaps.total - Math.min(gaps.records.length, MAX_ITEMIZED_FINDINGS);
+ if (unlisted > 0) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageObservationDropped,
+ site: VERIFY_SITE,
+ detail:
+ `${unlisted} further observations were never appended and are not itemized` +
+ (gaps.truncated ? ` (${gaps.discarded} beyond the sidecar's retained records)` : ""),
+ });
+ }
+
+ return Object.freeze({
+ path,
+ exists: scan.exists,
+ readable: scan.readable,
+ lines: scan.lines.length,
+ skipped: skipped.length,
+ chained,
+ legacy,
+ droppedObservations: gaps.total,
+ gapsTruncated: gaps.truncated,
+ notices: Object.freeze(notices),
+ ok: notices.length === 0,
+ });
+}
+
+/**
+ * Check one chained line. At most ONE finding per line: a tampered line
+ * would otherwise also fail its successor's `prev` check and report the
+ * same damage twice.
+ */
+function checkChainedLine(
+ line: LedgerLine,
+ previous: LedgerLine | undefined,
+ notices: DegradationNotice[],
+): void {
+ const seq = line.seq!;
+ if (lineageChainHash(line) !== line.h) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageChainBroken,
+ site: VERIFY_SITE,
+ detail:
+ `sequence ${seq} (session ${line.sid}): content does not match its ` +
+ "recorded hash - the line was edited after it was written",
+ });
+ return;
+ }
+ if (previous === undefined) return; // chain anchor
+ if ((line.prev ?? null) !== previous.h) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageChainBroken,
+ site: VERIFY_SITE,
+ detail:
+ `sequence ${seq} (session ${line.sid}): does not link to sequence ` +
+ `${previous.seq} - a line between them was removed or reordered`,
+ });
+ return;
+ }
+ if (seq !== previous.seq! + 1) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.lineageChainBroken,
+ site: VERIFY_SITE,
+ detail: `sequence ${seq} (session ${line.sid}): follows sequence ${previous.seq}`,
+ });
+ }
+}
+
+function safeLedgerPath(vault: string): string {
+ try {
+ return sessionLineageLedgerPath(vault);
+ } catch {
+ return vault;
+ }
+}
diff --git a/src/core/brain/link-graph/bridge-discovery.ts b/src/core/brain/link-graph/bridge-discovery.ts
index 39760d16..506cc0cd 100644
--- a/src/core/brain/link-graph/bridge-discovery.ts
+++ b/src/core/brain/link-graph/bridge-discovery.ts
@@ -36,6 +36,7 @@ import {
} from "../../vault.ts";
import { resolveNotePath } from "../note-path.ts";
import type { SchemaPack } from "../schema-pack.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const BRIDGE_DEFAULT_MIN_SIMILARITY = 0.8;
export const BRIDGE_DEFAULT_MAX_PROPOSALS = 10;
@@ -196,6 +197,8 @@ export function writeBridgeProposals(
report: BridgeDiscoveryReport,
opts: { readonly now: Date },
): string {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = proposalsPath(vault);
const lines: string[] = [
"# Bridge proposals",
@@ -250,6 +253,8 @@ export function readDismissedBridges(vault: string): Set<string> {
/** Persist one dismissal; returns true when it was new. */
export function dismissBridge(vault: string, source: string, target: string): boolean {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const key = bridgePairKey(source, target);
const dismissed = readDismissedBridges(vault);
if (dismissed.has(key)) return false;
diff --git a/src/core/brain/link-graph/co-occurrence.ts b/src/core/brain/link-graph/co-occurrence.ts
index e3fbe9d1..a1d06027 100644
--- a/src/core/brain/link-graph/co-occurrence.ts
+++ b/src/core/brain/link-graph/co-occurrence.ts
@@ -28,6 +28,7 @@ import {
} from "../../graph/frontmatter-relations.ts";
import type { FrontmatterMap } from "../../types.ts";
import { BRAIN_ROOT_REL } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const CO_OCCURRENCE_SCHEMA_VERSION = "o2b.cooccurrence.v1";
@@ -156,6 +157,8 @@ export function writeCoOccurrenceSuggestions(
result: CoOccurrenceResult,
opts: { readonly generatedAt: string },
): string {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = join(vault, ARTIFACT_REL);
mkdirSync(dirname(path), { recursive: true });
writeFileSync(
diff --git a/src/core/brain/link-graph/communities.ts b/src/core/brain/link-graph/communities.ts
index 0bb4bc06..a07418d8 100644
--- a/src/core/brain/link-graph/communities.ts
+++ b/src/core/brain/link-graph/communities.ts
@@ -31,6 +31,7 @@ import { getGraphSnapshot } from "./graph-index.ts";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { isoSecond } from "../time.ts";
import { formatFrontmatter, parseFrontmatter } from "../../vault.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const COMMUNITY_DEFAULT_MIN_SIZE = 4;
export const COMMUNITY_MAX_ITERATIONS = 20;
@@ -239,6 +240,8 @@ export function materializeClusterNotes(
communities: ReadonlyArray<Community>,
opts: MaterializeClusterNotesOptions,
): MaterializeClusterNotesResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const dir = clustersDir(vault);
mkdirSync(dir, { recursive: true });
const writeNote = opts.writeNote ?? atomicWriteFileSync;
diff --git a/src/core/brain/link-graph/repair-lane.ts b/src/core/brain/link-graph/repair-lane.ts
index 0f1c0e23..d8287d7d 100644
--- a/src/core/brain/link-graph/repair-lane.ts
+++ b/src/core/brain/link-graph/repair-lane.ts
@@ -35,6 +35,7 @@ import {
} from "../../vault.ts";
import { listContinuityRecords } from "../continuity/store.ts";
import { canonicalCoOccurrenceKey, computeCoOccurrenceSuggestions } from "./co-occurrence.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Identity-strength tiers, strongest first. `inferred` is opt-in. */
export const IDENTITY_STRENGTH = Object.freeze({
@@ -188,6 +189,9 @@ export function runRepairLane(
if (apply && opts.confirm !== REPAIR_CONFIRM_PHRASE) {
throw new RepairConfirmationError();
}
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ // A non-apply run reports decisions and writes nothing.
+ if (apply) assertVaultIdentityForWrite(vault);
const threshold = opts.confidenceThreshold ?? REPAIR_CONFIDENCE_THRESHOLD;
const writeCap = Math.max(0, Math.floor(opts.writeCap ?? REPAIR_WRITE_CAP));
@@ -302,7 +306,7 @@ function clampConfidence(value: number): number {
}
function pairId(source: string, target: string): string {
- return `${source}${target}`;
+ return `${source}\0${target}`;
}
/** Mask wikilink and code spans so a mention inside them is not counted. */
diff --git a/src/core/brain/lint-consolidate.ts b/src/core/brain/lint-consolidate.ts
index 20dd396b..e21c507b 100644
--- a/src/core/brain/lint-consolidate.ts
+++ b/src/core/brain/lint-consolidate.ts
@@ -32,6 +32,7 @@ import {
readLifecycle,
} from "./page-meta/lifecycle.ts";
import { readMergedInto } from "./page-meta/page-id.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export interface LintFix {
readonly kind: "fix-merged-link";
@@ -167,6 +168,8 @@ function applyDemotion(path: string): boolean {
}
export function lintConsolidate(vault: string, opts: LintOptions): LintReport {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const now = opts.now ?? new Date();
const staleDays = opts.staleDays ?? PAGE_STALE_DAYS_DEFAULT;
const merge = buildMergeMap(vault);
diff --git a/src/core/brain/log.ts b/src/core/brain/log.ts
index 9ce17bcf..7d523eac 100644
--- a/src/core/brain/log.ts
+++ b/src/core/brain/log.ts
@@ -30,7 +30,13 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import lockfile from "proper-lockfile";
import { atomicWriteFileSync } from "../fs-atomic.ts";
-import { brainDirs, logPath, logShardJsonlPath, logShardPath, validateIsoDate } from "./paths.ts";
+import {
+ brainDirsForWrite,
+ logPath,
+ logShardJsonlPath,
+ logShardPath,
+ validateIsoDate,
+} from "./paths.ts";
import { isValidDeviceId, resolveDeviceId } from "../config.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "./types.ts";
@@ -291,7 +297,7 @@ export function appendLogEvent(
const ts = parseIsoUtc(event.timestamp);
const path = logShardPath(vault, ts.date, deviceId);
const jsonlPath = logShardJsonlPath(vault, ts.date, deviceId);
- const logDir = brainDirs(vault).log;
+ const logDir = brainDirsForWrite(vault).log;
const topLevelAgent = (event as { agent?: unknown }).agent;
const eventBody =
typeof topLevelAgent === "string" && typeof event.body["agent"] !== "string"
diff --git a/src/core/brain/maintenance/journal.ts b/src/core/brain/maintenance/journal.ts
index 93204d03..22210fa4 100644
--- a/src/core/brain/maintenance/journal.ts
+++ b/src/core/brain/maintenance/journal.ts
@@ -10,6 +10,7 @@
import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const MAINTENANCE_JOURNAL_CAP = 500;
@@ -31,6 +32,8 @@ function journalPath(vault: string): string {
}
export function appendJournal(vault: string, entry: MaintenanceJournalEntry): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = journalPath(vault);
mkdirSync(dirname(path), { recursive: true });
// O_APPEND, one line per call: concurrent gate-refusal writers
@@ -43,6 +46,8 @@ export function appendJournal(vault: string, entry: MaintenanceJournalEntry): vo
/** Trim the journal to the newest `cap` lines. Lease-holder only. */
export function sweepJournal(vault: string, cap: number = MAINTENANCE_JOURNAL_CAP): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = journalPath(vault);
const lines = readLines(path);
if (lines.length <= cap) return;
diff --git a/src/core/brain/manifest.ts b/src/core/brain/manifest.ts
index 245e419e..6cb66764 100644
--- a/src/core/brain/manifest.ts
+++ b/src/core/brain/manifest.ts
@@ -14,6 +14,7 @@ import { join, relative } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { BRAIN_ROOT_REL, brainDirs } from "./paths.ts";
import { isoSecond } from "./time.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export const BRAIN_MANIFEST_SCHEMA_VERSION = 1 as const;
@@ -298,6 +299,8 @@ export function readManifestSidecar(vault: string, runId: string): BrainManifest
* indent so a manual `cat` or `git diff` stays readable.
*/
export function writeManifestSidecar(vault: string, runId: string, manifest: BrainManifest): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = manifestSidecarPath(vault, runId);
atomicWriteFileSync(path, JSON.stringify(manifest, null, 2) + "\n");
}
diff --git a/src/core/brain/marker-writeback.ts b/src/core/brain/marker-writeback.ts
index c5b1afcf..c70a2529 100644
--- a/src/core/brain/marker-writeback.ts
+++ b/src/core/brain/marker-writeback.ts
@@ -56,6 +56,7 @@ import { NoteTitleResolutionError, resolveNoteTarget } from "./notes/note-title-
import { loadGuardrailsConfigSafe } from "./policy.ts";
import { loadSchemaPack } from "./schema-pack.ts";
import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** The `marker_writeback` guardrail flag name, surfaced in refusals. */
export const MARKER_WRITEBACK_GUARDRAIL = "marker_writeback";
@@ -192,6 +193,11 @@ export async function applyMarkerWritebacks(
vault: string,
opts: MarkerWritebackOptions,
): Promise<MarkerWritebackReport> {
+ // Vault-identity write guard (context-integrity-gates, Unit J). Apply
+ // mode writes attributes, an audit event, and consumes markers through
+ // `rewriteMarkers`, which takes an absolute path and no vault of its
+ // own; this is the entry point that has one.
+ if (opts.apply) assertVaultIdentityForWrite(vault);
const guardrailEnabled = loadGuardrailsConfigSafe(vault).marker_writeback;
if (opts.apply && !guardrailEnabled) {
throw new MarkerWritebackGuardrailError(
diff --git a/src/core/brain/metrics.ts b/src/core/brain/metrics.ts
index 11bfe222..86178e61 100644
--- a/src/core/brain/metrics.ts
+++ b/src/core/brain/metrics.ts
@@ -21,6 +21,7 @@
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** On-disk schema version stamped on every metric record. */
export const METRICS_SCHEMA_VERSION = "o2b.metrics.v1";
@@ -81,6 +82,8 @@ function assertSurface(surface: string): void {
* Creates `Brain/metrics/` on first write.
*/
export function appendMetric(vault: string, input: AppendMetricInput): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
assertSurface(input.surface);
if (!ISO_RE.test(input.runAt)) {
throw new MetricSurfaceError(
diff --git a/src/core/brain/morning-brief.ts b/src/core/brain/morning-brief.ts
index 693dbfbb..a324bcb9 100644
--- a/src/core/brain/morning-brief.ts
+++ b/src/core/brain/morning-brief.ts
@@ -13,11 +13,8 @@
* recall-budget primitive so one oversized entry cannot dominate.
*/
-import { existsSync, readdirSync } from "node:fs";
-import { join } from "node:path";
-
import { brainDirs } from "./paths.ts";
-import { parsePreference } from "./preference.ts";
+import { collectPreferences, resolveOwnerScopeDelivery } from "./preferences-collect.ts";
import { applyCharBudget } from "./recall-budget.ts";
import { readLogDay } from "./log-jsonl.ts";
import { renderActivityTimeline, type ActivityItem } from "./render/activity-line.ts";
@@ -58,6 +55,13 @@ export interface MorningBriefOptions {
readonly maxCharsPerMemory?: number;
/** Total character cap across the brief; <= 0 / undefined disables. */
readonly maxTotalChars?: number;
+ /**
+ * Owner scope for delivery isolation (context-integrity-gates, Unit
+ * A). Enforced only when `integrity.owner_scope_delivery` is `fail`;
+ * omitted, or under the default `off`, nothing is filtered and the
+ * output is byte-identical to a vault without the gate.
+ */
+ readonly agentScope?: string;
}
interface ConfirmedPref {
@@ -67,18 +71,15 @@ interface ConfirmedPref {
readonly createdAt: string;
}
-function collectConfirmed(vault: string): ConfirmedPref[] {
+function collectConfirmed(vault: string, agentScope: string | undefined): ConfirmedPref[] {
const dir = brainDirs(vault).preferences;
- if (!existsSync(dir)) return [];
const out: ConfirmedPref[] = [];
- for (const name of readdirSync(dir)) {
- if (!name.endsWith(".md")) continue;
- let pref;
- try {
- pref = parsePreference(join(dir, name));
- } catch {
- continue;
- }
+ // Listing and parse come from the shared delivery-path walk
+ // (context-integrity-gates, Unit A); the confirmed-status filter is
+ // this surface's own and stays here.
+ for (const { pref } of collectPreferences(dir, {
+ ownerScope: resolveOwnerScopeDelivery(vault, agentScope),
+ }).entries) {
if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;
out.push({
id: pref.id,
@@ -156,7 +157,7 @@ const TIMELINE_HEADER = "## Recent activity";
export function buildMorningBrief(vault: string, opts: MorningBriefOptions): MorningBrief {
const lookbackDays = opts.lookbackDays ?? 7;
- const ranked = collectConfirmed(vault).toSorted((a, b) => {
+ const ranked = collectConfirmed(vault, opts.agentScope).toSorted((a, b) => {
if (b.confidence !== a.confidence) return b.confidence - a.confidence;
if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
diff --git a/src/core/brain/notes/create-note.ts b/src/core/brain/notes/create-note.ts
index 01d2c9d1..fcb151e4 100644
--- a/src/core/brain/notes/create-note.ts
+++ b/src/core/brain/notes/create-note.ts
@@ -19,6 +19,7 @@ import { ensureInsideVault } from "../../path-safety.ts";
import { writeFrontmatterAtomic } from "../../vault.ts";
import { inspectPath, resolveVaultScope } from "../../vault-scope/index.ts";
import { BRAIN_ROOT_REL } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Machine-readable reason a {@link createNote} call was refused. */
export type CreateNoteErrorCode = "invalid_path" | "excluded" | "exists" | "outside_vault";
@@ -121,6 +122,10 @@ export function resolveNoteTarget(vault: string, path: string): ResolvedNoteTarg
* vault-relative path; throws {@link CreateNoteError} on any refusal.
*/
export function createNote(vault: string, input: CreateNoteInput): CreateNoteResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J). This
+ // backs `brain_create_note`, `brain_append_note`, and
+ // `brain_update_note` - the headline note writers.
+ assertVaultIdentityForWrite(vault);
const { relPath, abs } = resolveNoteTarget(vault, input.path);
mkdirSync(dirname(abs), { recursive: true });
diff --git a/src/core/brain/obligations.ts b/src/core/brain/obligations.ts
index c9dfbbb9..08a64782 100644
--- a/src/core/brain/obligations.ts
+++ b/src/core/brain/obligations.ts
@@ -26,6 +26,7 @@ import { atomicWriteFileSync } from "../fs-atomic.ts";
import { slugify } from "../vault.ts";
import { parseFrontmatter } from "../vault.ts";
import { obligationPath, obligationsArchiveDir, obligationsDir, validateIsoDate } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { isoDate, isoSecond } from "./time.ts";
/**
@@ -243,6 +244,8 @@ function parsePage(vault: string, slug: string): ObligationPage | null {
/** Create a recurring obligation page. */
export function addObligation(vault: string, input: AddObligationInput): ObligationPage {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const title = input.title.trim();
if (title.length === 0) throw new ObligationError("obligation title must not be empty");
const cadence = parseCadence(input.cadence);
@@ -274,6 +277,8 @@ export function addObligation(vault: string, input: AddObligationInput): Obligat
/** Record a completion and advance next-due by one cadence interval. */
export function completeObligation(vault: string, input: CompleteObligationInput): ObligationPage {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const slug = slugify(input.slug);
const prior = parsePage(vault, slug);
if (prior === null) throw new ObligationError(`no obligation: ${slug}`);
@@ -346,6 +351,8 @@ export function listObligations(
/** Retire an obligation into Brain/obligations/archive/. */
export function removeObligation(vault: string, slug: string): RemoveObligationResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const normalized = slugify(slug);
const activePath = obligationPath(vault, normalized);
if (!existsSync(activePath)) throw new ObligationError(`no obligation: ${normalized}`);
diff --git a/src/core/brain/observed-use.ts b/src/core/brain/observed-use.ts
index 4c66c59b..979f3127 100644
--- a/src/core/brain/observed-use.ts
+++ b/src/core/brain/observed-use.ts
@@ -142,12 +142,42 @@ export interface ObservedReuse {
}
/**
- * Fold every `recall_observed_use` record into a per-artifact reuse map,
+ * Narrows {@link observedReuseRates} from its lifetime default to one
+ * session or one window. Every field is optional and an empty filter is
+ * byte-identical to the unfiltered lifetime fold, so no existing caller
+ * changes behaviour.
+ */
+export interface ObservedReuseFilter {
+ /** Only records carrying this `session_id`. */
+ readonly sessionId?: string;
+ /** Inclusive lower bound on `createdAt` (canonical UTC ISO-8601). */
+ readonly since?: string;
+ /** Inclusive upper bound on `createdAt` (canonical UTC ISO-8601). */
+ readonly until?: string;
+}
+
+/**
+ * Fold `recall_observed_use` records into a per-artifact reuse map,
* keyed by `path` when present else `id`. Order-insensitive.
+ *
+ * Unfiltered this is the lifetime rate ranking consumes. A filter makes
+ * the same fold answerable for one session or one window, which is what
+ * a session-scoped retrieval report needs: a lifetime rate cannot say
+ * whether the material injected THIS session was used.
*/
-export function observedReuseRates(vault: string): Map<string, ObservedReuse> {
+export function observedReuseRates(
+ vault: string,
+ filter: ObservedReuseFilter = {},
+): Map<string, ObservedReuse> {
const acc = new Map<string, { used: number; ignored: number; contradicted: number }>();
- for (const record of listContinuityRecords(vault, { kind: "recall_observed_use" })) {
+ for (const record of listContinuityRecords(vault, {
+ kind: "recall_observed_use",
+ ...(filter.since !== undefined ? { since: filter.since } : {}),
+ ...(filter.until !== undefined ? { until: filter.until } : {}),
+ })) {
+ if (filter.sessionId !== undefined && record.payload["session_id"] !== filter.sessionId) {
+ continue;
+ }
const entries = record.payload["entries"];
if (!Array.isArray(entries)) continue;
for (const raw of entries) {
diff --git a/src/core/brain/owner-scoped-facts.ts b/src/core/brain/owner-scoped-facts.ts
index 019ac54c..d645e9a4 100644
--- a/src/core/brain/owner-scoped-facts.ts
+++ b/src/core/brain/owner-scoped-facts.ts
@@ -14,12 +14,20 @@
* is visible exactly as today.
*/
-import { isOwnerVisible, pageOwner } from "../graph/agent-scope.ts";
+import { isOwnerVisible, ownerToken } from "../graph/agent-scope.ts";
import type { BrainPreference } from "./types.ts";
-/** The normalized owner token of a preference, or null when ownerless. */
+/**
+ * The normalized owner token of a preference, or null when ownerless.
+ *
+ * Resolves through {@link ownerToken}, the same function `pageOwner` uses,
+ * so a preference whose page declared an unresolvable `owner:` (a YAML
+ * list, a nested mapping) carries the same `OWNER_UNRESOLVED` verdict here
+ * as the page does on the search path β€” never `null`, which would publish
+ * it to every scope.
+ */
export function preferenceOwner(pref: Pick<BrainPreference, "owner">): string | null {
- return pageOwner({ owner: pref.owner ?? "" });
+ return ownerToken(pref.owner);
}
/**
diff --git a/src/core/brain/pack-stamp.ts b/src/core/brain/pack-stamp.ts
new file mode 100644
index 00000000..ac70ae23
--- /dev/null
+++ b/src/core/brain/pack-stamp.ts
@@ -0,0 +1,239 @@
+/**
+ * Provenance stamp and validity window for a context pack
+ * (context-integrity-gates, Unit B).
+ *
+ * A context pack is computed fresh per call and, until now, recorded
+ * nothing about the vault state it was derived from. The moment one is
+ * PERSISTED - which the anticipatory cache does - a stale pack becomes
+ * indistinguishable from a fresh one, and the agent cannot tell a
+ * genuine miss from a broken mechanism. This module is the pack's answer
+ * to "what was I built from", expressed in the shared vocabulary of
+ * `integrity/stamp.ts`.
+ *
+ * ## Why two tokens, not one
+ *
+ * `corpus_generation` alone is a LAGGING proxy. `packContext` never
+ * reads the search index - it walks the filesystem directly - so a
+ * hand-edited memory changes the pack without bumping `index_revision`,
+ * and the generation string would still compare equal. Pairing it with a
+ * digest over the directories the pack actually walks closes that gap:
+ *
+ * - `corpus_generation` observes the index identity that ranking and
+ * semantic recall depend on (model, dimension, schema, revision);
+ * - `brain_tree` observes the bytes the pack itself reads, via path,
+ * mtime and size.
+ *
+ * `brain_tree` covers the preference and retired directories AND
+ * `Brain/_brain.yaml`. The config is not a memory, but `packContext`
+ * reads it and its `untrusted_source_delimiting` flag changes the bodies
+ * the pack emits - so a pack built before that flag flipped would
+ * otherwise compare equal to the vault state after it, which is exactly
+ * the staleness this stamp exists to name.
+ *
+ * `buildManifest` was considered for the second role and rejected: it
+ * sha256-hashes every file on every call, which is not affordable on a
+ * hook-driven path. Path + mtime + size is.
+ *
+ * ## A vault with no search index
+ *
+ * `corpus_generation` is `null` there, and `null` means UNRECORDED - not
+ * "matches anything". Two unrecorded sides are not a finding (that is
+ * `stamp.ts`'s contract, and it is what lets an index-less vault work at
+ * all), so on such a vault `brain_tree` carries the whole load. The
+ * moment an index appears or disappears the token moves between `null`
+ * and a string, and the comparison names `corpus_generation` explicitly
+ * rather than silently agreeing.
+ */
+
+import { createHash } from "node:crypto";
+import { statSync } from "node:fs";
+
+import { compareStamps, formatStampMismatch, type StampTokens } from "../integrity/stamp.ts";
+import { vaultRelative } from "../path-safety.ts";
+import { resolveSearchConfig } from "../search/index.ts";
+import { peekCorpusGenerationSync } from "../search/store.ts";
+import { defaultConfigPath } from "../config.ts";
+import { brainConfigPath, brainDirs } from "./paths.ts";
+import { loadIntegrityConfigSafe } from "./policy.ts";
+import { listPreferenceFiles } from "./preferences-collect.ts";
+
+/**
+ * The stamp's field names. Caller-owned by `stamp.ts`'s contract, so
+ * they are named once here and reused by every consumer rather than
+ * respelled at each comparison site.
+ */
+export const PACK_STAMP_FIELD = Object.freeze({
+ /** Index identity: embedding model, dimension, schema, revision. */
+ corpusGeneration: "corpus_generation",
+ /** Digest over the Brain files the pack walks. */
+ brainTree: "brain_tree",
+} as const);
+
+/** Bytes of the digest kept, in hex characters. */
+const BRAIN_TREE_DIGEST_CHARS = 16;
+
+/** Field separator inside one digested line; never valid in a path. */
+const DIGEST_FIELD_SEP = "\0";
+
+/**
+ * Recorded for a file whose `stat` failed. A distinct RECORDED value,
+ * not an omission: a memory that becomes unreadable is a change to the
+ * tree the pack walks, and must move the digest.
+ */
+const UNSTATTABLE = "-1";
+
+/** What a pack was derived from, and how long it stays servable. */
+export interface ContextPackStamp {
+ /** Tokens identifying the vault state at build time. */
+ readonly tokens: StampTokens;
+ /** ISO instant the pack was built. */
+ readonly generatedAt: string;
+ /** ISO instant past which the pack is refused regardless of drift. */
+ readonly expiresAt: string;
+}
+
+/**
+ * Digest over the Brain files a pack walks: `collectCandidates` reads
+ * the preferences and retired directories, and this reuses the very same
+ * listing helper, so the digest can never cover a different file set
+ * than the pack does.
+ *
+ * Lines are sorted before hashing because `readdirSync` order is not
+ * guaranteed stable across filesystems, and an unstable digest would
+ * invalidate every cache entry at random.
+ */
+function brainTreeToken(vault: string): string {
+ const dirs = brainDirs(vault);
+ const lines: string[] = [];
+ for (const dir of [dirs.preferences, dirs.retired]) {
+ for (const file of listPreferenceFiles(dir)) {
+ lines.push(digestLine(vault, file.path));
+ }
+ }
+ // The config the pack reads. Always digested, present or not: an
+ // ABSENT config is a state, and creating one must move the token.
+ lines.push(digestLine(vault, brainConfigPath(vault)));
+ lines.sort();
+ return createHash("sha256")
+ .update(lines.join("\n"))
+ .digest("hex")
+ .slice(0, BRAIN_TREE_DIGEST_CHARS);
+}
+
+/**
+ * One digested line: vault-relative path, mtime, size. A path that
+ * cannot be stat'ed - absent, or unreadable - records {@link UNSTATTABLE}
+ * for both, which is a value and not an omission, so the file appearing
+ * or disappearing moves the digest.
+ */
+function digestLine(vault: string, path: string): string {
+ let mtime = UNSTATTABLE;
+ let size = UNSTATTABLE;
+ try {
+ const stat = statSync(path);
+ mtime = String(Math.trunc(stat.mtimeMs));
+ size = String(stat.size);
+ } catch {
+ /* recorded as UNSTATTABLE above - a state, not an omission */
+ }
+ return [vaultRelative(path, vault), mtime, size].join(DIGEST_FIELD_SEP);
+}
+
+/**
+ * Recorded when the index file EXISTS but cannot be opened or queried.
+ *
+ * A distinct recorded value, not `null`. `null` means unrecorded, and
+ * two unrecorded sides are not a finding by `stamp.ts`'s contract - so
+ * folding a corrupt index onto "no index" would make a pack stamped
+ * before the corruption compare EQUAL to one validated after it. The
+ * sentinel keeps the two states apart and makes the repair itself a
+ * named drift.
+ */
+export const CORPUS_GENERATION_UNREADABLE = "index-unreadable";
+
+export interface PackStampSourceOptions {
+ /**
+ * Config file to resolve the index location through. Defaults to the
+ * process's own config path; passed explicitly by callers that have
+ * one, and by tests, which must not read the operator's.
+ */
+ readonly configPath?: string;
+}
+
+/**
+ * Index path as the search layer itself resolves it, so the stamp
+ * observes the database `search()` would read.
+ *
+ * This goes through `resolveSearchConfig`, not the env variable alone.
+ * The env-only form missed the config-file `search_db_path` key, so on a
+ * vault configured that way the stamp peeked at a database that was not
+ * there: `corpus_generation` read `null` on both the stamping and the
+ * validating side, "two unrecorded sides are not a finding" applied, and
+ * half the pack stamp was permanently inert while claiming otherwise.
+ */
+function packIndexPath(vault: string, configPath: string | undefined): string {
+ return resolveSearchConfig({ vault, configPath: configPath ?? defaultConfigPath() }).dbPath;
+}
+
+/** The live tokens for `vault`, right now. */
+export function packStampTokens(vault: string, opts: PackStampSourceOptions = {}): StampTokens {
+ const peek = peekCorpusGenerationSync(packIndexPath(vault, opts.configPath));
+ const corpusGeneration =
+ peek.kind === "read"
+ ? peek.value
+ : peek.kind === "unreadable"
+ ? CORPUS_GENERATION_UNREADABLE
+ : null;
+ return Object.freeze({
+ [PACK_STAMP_FIELD.corpusGeneration]: corpusGeneration,
+ [PACK_STAMP_FIELD.brainTree]: brainTreeToken(vault),
+ });
+}
+
+/**
+ * Stamp a pack built at `now`, with the validity window from
+ * `integrity.pack_validity_seconds`.
+ *
+ * The config load is the SAFE form for the same reason every other
+ * delivery-path read uses it: a pack must keep working on a vault that
+ * has never run `o2b brain init`, and an unreadable config is not a
+ * reason to change what the pack returns.
+ */
+export function buildPackStamp(
+ vault: string,
+ now: Date,
+ opts: PackStampSourceOptions = {},
+): ContextPackStamp {
+ const validitySeconds = loadIntegrityConfigSafe(vault).pack_validity_seconds;
+ return Object.freeze({
+ tokens: packStampTokens(vault, opts),
+ generatedAt: now.toISOString(),
+ expiresAt: new Date(now.getTime() + validitySeconds * 1_000).toISOString(),
+ });
+}
+
+/**
+ * Why a stamped pack must not be served, or `null` when it may be.
+ *
+ * The window is checked first and unconditionally: it is the backstop
+ * for the changes a token cannot observe, so an expired pack is refused
+ * even when every token still matches. An unparseable expiry is refused
+ * too - a validity window that cannot be read is not a valid one.
+ *
+ * The gate is binary here, with no `off` mode, and deliberately: a pack
+ * whose stamp no longer matches IS stale, which is unambiguous. Only the
+ * two units whose condition is environment-dependent take a mode.
+ */
+export function packStampRefusal(
+ recorded: ContextPackStamp,
+ live: StampTokens,
+ now: Date,
+): string | null {
+ const expiresMs = Date.parse(recorded.expiresAt);
+ if (!Number.isFinite(expiresMs) || now.getTime() >= expiresMs) {
+ return `pack validity window expired at ${recorded.expiresAt} (now ${now.toISOString()})`;
+ }
+ const drift = compareStamps(recorded.tokens, live);
+ if (drift.length === 0) return null;
+ return `source stamp drifted: ${drift.map(formatStampMismatch).join("; ")}`;
+}
diff --git a/src/core/brain/page-dedup.ts b/src/core/brain/page-dedup.ts
index 64cc4899..2fb0313b 100644
Binary files a/src/core/brain/page-dedup.ts and b/src/core/brain/page-dedup.ts differ
diff --git a/src/core/brain/page-meta/page-id.ts b/src/core/brain/page-meta/page-id.ts
index b2aabae0..2c21d0fc 100644
--- a/src/core/brain/page-meta/page-id.ts
+++ b/src/core/brain/page-meta/page-id.ts
@@ -17,6 +17,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { parseFrontmatter } from "../../vault.ts";
import { brainDirs } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const MERGE_CHAIN_MAX_DEPTH = 5;
@@ -120,6 +121,8 @@ export function resolveCanonicalId(vault: string, startId: string): string {
* and which is the secondary; this function only writes the pointer.
*/
export function setMergedInto(vault: string, secondaryId: string, canonicalId: string): string {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
if (!isValidPageId(secondaryId)) {
throw new MergeChainError(
"MALFORMED",
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index 331b5874..92685acc 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -27,6 +27,8 @@ import { existsSync } from "node:fs";
import { join, posix } from "node:path";
import { ensureInsideVault, vaultRelative } from "../path-safety.ts";
+import type { DegradationNotice } from "../integrity/degradation.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export { ensureInsideVault, vaultRelative } from "../path-safety.ts";
@@ -173,6 +175,48 @@ export function brainDirs(vault: string): BrainDirs {
};
}
+/**
+ * {@link brainDirs} for a caller that is about to WRITE.
+ *
+ * Identical directories, plus the vault-identity assertion in front of
+ * them (context-integrity-gates, Unit J). The write-intent variant
+ * exists because the guard belongs on the write side only: read paths
+ * must stay unaffected, and a blanket assertion inside `brainDirs`
+ * would fire on every listing, every doctor pass, and every fail-soft
+ * hook that merely inspects the tree.
+ *
+ * An unmarked root emits a `vault-marker-absent` notice into `notices`
+ * and proceeds; a root whose marker differs from the one this process
+ * pinned raises `VaultIdentityMismatchError`. The bootstrap path
+ * deliberately uses plain {@link brainDirs}: it is what legitimately
+ * creates the tree, so it must not be gated on the marker it is about
+ * to write.
+ *
+ * ## Which call sites use this one
+ *
+ * A site is write-intent when EITHER the `BrainDirs` value it produces
+ * forms a path the same flow creates, moves, or deletes (even
+ * conditionally), OR the site is reached only from flows that mutate
+ * the Brain tree. Everything else stays on {@link brainDirs}:
+ *
+ * - read, query, report, and analysis flows - widening the guard onto
+ * them would break `src/openclaw/index.ts`, which silently defaults
+ * to the process working directory, and the hooks, which fail open
+ * by contract;
+ * - sites reached from BOTH a mutating flow and a read-only or
+ * dry-run preview of it, where the guard would fire on a preview;
+ * - the path builders in this module. They are intent-neutral by
+ * construction - `preferencePath` serves `parsePreference` and
+ * `writePreference` alike - so a writer that reaches the tree
+ * through one of them is guarded at its own entry point, not here.
+ * Those writers call `assertVaultIdentityForWrite` directly; see
+ * its docblock for the two call surfaces and why they differ.
+ */
+export function brainDirsForWrite(vault: string, notices?: DegradationNotice[]): BrainDirs {
+ assertVaultIdentityForWrite(vault, notices);
+ return brainDirs(vault);
+}
+
/** Path of `Brain/_brain.yaml`. */
export function brainConfigPath(vault: string): string {
return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_CONFIG_FILE), vault);
diff --git a/src/core/brain/payload-registry.ts b/src/core/brain/payload-registry.ts
index ef8b3fe2..08d2087f 100644
--- a/src/core/brain/payload-registry.ts
+++ b/src/core/brain/payload-registry.ts
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { ensureInsideVault } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export interface PayloadRegistryOptions {
readonly vault: string;
@@ -72,6 +73,10 @@ export class PayloadRegistry {
}
private put(text: string): ExternalizedPayload {
+ // Vault-identity write guard (context-integrity-gates, Unit J). The
+ // registry externalizes oversized payloads into `Brain/.payloads/`,
+ // so this is the class's only byte-producing path.
+ assertVaultIdentityForWrite(this.vault);
const sha256 = createHash("sha256").update(text, "utf8").digest("hex");
const ref = `${PAYLOAD_REF_PREFIX}${sha256}`;
const placeholder = `[payload: ${ref} chars=${text.length}]`;
diff --git a/src/core/brain/pending.ts b/src/core/brain/pending.ts
index 98f0f759..2be36d3e 100644
--- a/src/core/brain/pending.ts
+++ b/src/core/brain/pending.ts
@@ -28,7 +28,7 @@ import { atomicCreateFileSyncExclusive } from "../fs-atomic.ts";
import { discoverConfig } from "../config.ts";
import type { FrontmatterMap } from "../types.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
-import { brainDirs, ensureInsideVault } from "./paths.ts";
+import { brainDirs, brainDirsForWrite, ensureInsideVault } from "./paths.ts";
import { parseSignal, writeSignal, type WriteSignalInput } from "./signal.ts";
import type { BrainSignal } from "./types.ts";
@@ -91,14 +91,14 @@ export interface StageResult {
* identical to what the inbox would have received.
*/
export function stagePendingSignal(vault: string, input: WriteSignalInput): StageResult {
- const res = writeSignal(vault, input, { targetDir: brainDirs(vault).pending });
+ const res = writeSignal(vault, input, { targetDir: brainDirsForWrite(vault).pending });
return { id: res.id, path: res.path };
}
/** Validate a pending id and resolve its absolute path inside `Brain/pending/`. */
function pendingFilePath(vault: string, id: string): string {
if (!SIGNAL_ID_RE.test(id)) throw new InvalidPendingIdError(id);
- return ensureInsideVault(join(brainDirs(vault).pending, `${id}.md`), vault);
+ return ensureInsideVault(join(brainDirsForWrite(vault).pending, `${id}.md`), vault);
}
/** List the staged signals in `Brain/pending/`, sorted by id. */
@@ -127,7 +127,7 @@ export function applyPending(vault: string, id: string): StageResult {
const src = pendingFilePath(vault, id);
if (!existsSync(src)) throw new PendingSignalNotFoundError(id);
const contents = readFileSync(src, "utf8");
- const dest = ensureInsideVault(join(brainDirs(vault).inbox, `${id}.md`), vault);
+ const dest = ensureInsideVault(join(brainDirsForWrite(vault).inbox, `${id}.md`), vault);
// Exclusive create: never clobber an existing inbox file with the same id.
atomicCreateFileSyncExclusive(dest, contents);
unlinkSync(src);
@@ -171,7 +171,7 @@ export function rejectPending(
nextMeta["retired_at"] = now.toISOString();
nextMeta["retired_reason"] = reason;
- const dest = ensureInsideVault(join(brainDirs(vault).retired, `${id}.md`), vault);
+ const dest = ensureInsideVault(join(brainDirsForWrite(vault).retired, `${id}.md`), vault);
writeFrontmatterAtomic(dest, nextMeta, body, {
overwrite: false,
vaultForRelativePath: vault,
diff --git a/src/core/brain/pin.ts b/src/core/brain/pin.ts
index f454add6..9b30f100 100644
--- a/src/core/brain/pin.ts
+++ b/src/core/brain/pin.ts
@@ -34,6 +34,7 @@ import { regenerateActiveQuiet } from "./active.ts";
import { appendLogEvent, type BrainLogEntry } from "./log.ts";
import { parsePreference } from "./preference.ts";
import { preferencePath, validateSlug } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND, type BrainPreference } from "./types.ts";
import { renderPrefLink } from "./wikilink.ts";
@@ -77,6 +78,8 @@ export function setPinned(
value: boolean,
opts: SetPinnedOptions = {},
): SetPinnedResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
if (typeof prefId !== "string" || !prefId.trim()) {
throw new Error("setPinned missing field: pref_id");
}
diff --git a/src/core/brain/pinned.ts b/src/core/brain/pinned.ts
index edaa82a7..22899c57 100644
--- a/src/core/brain/pinned.ts
+++ b/src/core/brain/pinned.ts
@@ -3,6 +3,7 @@ import { existsSync, readFileSync } from "node:fs";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { sanitiseTextField } from "../redactor.ts";
import { brainPinnedPath } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export const MAX_PINNED_CONTEXT_LEN = 20_000;
@@ -51,6 +52,8 @@ function commitPinnedContent(
normalised: string,
operation: "write" | "append",
): PinnedContext {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
assertWithinPinnedBudget(normalised, operation);
const path = brainPinnedPath(vault);
atomicWriteFileSync(path, normalised.length > 0 ? `${normalised}\n` : "");
@@ -58,6 +61,8 @@ function commitPinnedContent(
}
export function clearPinnedContext(vault: string): PinnedContext {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = brainPinnedPath(vault);
atomicWriteFileSync(path, "");
return { path, present: true, content: "" };
@@ -166,11 +171,18 @@ export interface PinnedBatchResult extends PinnedContext {
* absent `replace` target, or an over-budget final projection throws
* {@link PinnedBatchError} and leaves `Brain/pinned.md` byte-for-byte
* unchanged.
+ *
+ * Carries the same vault-identity guard as the single-operation surface.
+ * Both modes are the one `brain_pinned_context` tool writing the one
+ * file, so a batch that wrote where a single `write` refused would make
+ * the guard a property of the argument shape rather than of the vault.
*/
export function applyPinnedOperations(
vault: string,
operations: ReadonlyArray<PinnedOperation>,
): PinnedBatchResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
if (!Array.isArray(operations) || operations.length === 0) {
throw new PinnedBatchError("invalid_operation", -1, "operations must be a non-empty array");
}
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index 9430337f..fab6faf9 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -32,6 +32,7 @@ import type {
BrainRollupConfig,
BrainHealthConfig,
BrainHygieneConfig,
+ BrainIntegrityConfig,
BrainLessonsConfig,
BrainRecallConfig,
BrainLinkGraphConfig,
@@ -44,6 +45,7 @@ import type {
DisciplineReportConfig,
ResolvedBrainGuardrailConfig,
ResolvedBrainHealthConfig,
+ ResolvedBrainIntegrityConfig,
ResolvedBrainLinkGraphConfig,
ResolvedBrainNotesConfig,
ResolvedBrainSessionsConfig,
@@ -55,6 +57,7 @@ import {
validateSchemaDeclarations,
} from "./schema-vocab.ts";
import { SCOPE_MAX_LEN } from "./signal.ts";
+import { GATE_MODE, GATE_MODES, isGateMode } from "../integrity/stamp.ts";
// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to
// break the module-init cycle: the resolver lives in `index.ts` and
// itself imports `loadBrainConfig` from this file. See the
@@ -297,6 +300,73 @@ export function resolveHealth(cfg: BrainConfig): ResolvedBrainHealthConfig {
};
}
+/**
+ * Sub-keys of the `integrity:` block whose value is a gate mode. Named
+ * once and reused by the validator, the unknown-key list, and the
+ * resolver so the three can never disagree about what the block holds.
+ */
+const INTEGRITY_GATE_KEYS = ["owner_scope_delivery", "embedding_abi"] as const;
+
+/**
+ * How long a context pack stays servable after it was built, when
+ * `_brain.yaml` omits `integrity.pack_validity_seconds`.
+ *
+ * 900 seconds (15 minutes) is the same bound `CRUTCH_LINK_WINDOW_MS`
+ * already uses for "still the same working session", so the pack's outer
+ * staleness bound and the session-continuity bound agree on what a
+ * session is rather than inventing a second, conflicting answer.
+ *
+ * It is deliberately much longer than the anticipatory cache's 120 s TTL:
+ * the provenance stamp is the PRIMARY invalidator (it observes the vault
+ * edits that matter), and this window is the backstop for the changes a
+ * stamp cannot observe. A short window here would duplicate the TTL and
+ * mask which mechanism actually did the invalidating.
+ *
+ * The value is unbounded above on purpose - unlike the instruction-file
+ * ceiling, a large window does not silently disable anything, because
+ * the stamp still refuses a drifted pack.
+ */
+export const PACK_VALIDITY_SECONDS_DEFAULT = 900;
+
+/**
+ * Default `integrity:` block (context-integrity-gates). Absent block (or
+ * absent individual keys) falls back here via `resolveIntegrity`.
+ *
+ * Both gate defaults are the modes that leave every existing vault
+ * byte-identical:
+ * - `owner_scope_delivery: off` - the delivery path documents a "null
+ * scope is byte-identical" contract throughout, so defaulting a
+ * scope would silently narrow vaults that never opted in. There is
+ * no writer surface for `owner` yet, so nothing would be gained.
+ * - `embedding_abi: warn` - `vec_version()` is not stable across
+ * environments, so two peers on different sqlite-vec builds would
+ * each see a mismatch. Refusing by default risks a rebuild loop on a
+ * synced vault; reporting cannot.
+ */
+export const BRAIN_INTEGRITY_DEFAULTS: ResolvedBrainIntegrityConfig = Object.freeze({
+ owner_scope_delivery: GATE_MODE.off,
+ embedding_abi: GATE_MODE.warn,
+ pack_validity_seconds: PACK_VALIDITY_SECONDS_DEFAULT,
+}) as ResolvedBrainIntegrityConfig;
+
+/**
+ * Merge a parsed `integrity` block (or `undefined`) with
+ * `BRAIN_INTEGRITY_DEFAULTS`. Resolution happens on the READ side, not
+ * at parse time, so `cfg.integrity` keeps recording exactly what the
+ * operator wrote and "absent" stays distinguishable from "explicitly set
+ * to the default".
+ */
+export function resolveIntegrity(cfg: BrainConfig): ResolvedBrainIntegrityConfig {
+ const it = cfg.integrity;
+ if (it === undefined) return BRAIN_INTEGRITY_DEFAULTS;
+ return {
+ owner_scope_delivery: it.owner_scope_delivery ?? BRAIN_INTEGRITY_DEFAULTS.owner_scope_delivery,
+ embedding_abi: it.embedding_abi ?? BRAIN_INTEGRITY_DEFAULTS.embedding_abi,
+ pack_validity_seconds:
+ it.pack_validity_seconds ?? BRAIN_INTEGRITY_DEFAULTS.pack_validity_seconds,
+ };
+}
+
/**
* Default `notes:` block (v0.11.0). Empty `read_paths` list means
* the agent does not scan any user-authored notes. The operator
@@ -395,6 +465,71 @@ export const loadTemporalConfigSafe = makeSafeLoader(resolveTemporal, BRAIN_TEMP
*/
export const loadGuardrailsConfigSafe = makeSafeLoader(resolveGuardrails, BRAIN_GUARDRAIL_DEFAULTS);
+/**
+ * Gate modes used when `_brain.yaml` EXISTS but cannot be read.
+ *
+ * Not the defaults: the defaults encode "this operator has said nothing",
+ * and an unreadable file is the opposite - the operator said something
+ * and we cannot tell what. Collapsing that to the defaults turns
+ * `owner_scope_delivery: fail` into `off`, which disables an isolation
+ * boundary because of a typo somewhere else in the file, with no signal
+ * on any surface. Erring to the strictest mode makes the same typo loud
+ * and reversible instead of quiet and permanent.
+ *
+ * `pack_validity_seconds` is not a gate and has no strict direction, so
+ * it keeps the default window.
+ */
+export const BRAIN_INTEGRITY_STRICT_FALLBACK: ResolvedBrainIntegrityConfig = Object.freeze({
+ owner_scope_delivery: GATE_MODE.fail,
+ embedding_abi: GATE_MODE.fail,
+ pack_validity_seconds: PACK_VALIDITY_SECONDS_DEFAULT,
+}) as ResolvedBrainIntegrityConfig;
+
+/**
+ * Why `_brain.yaml` could not be read, or `null` when it reads fine or
+ * does not exist.
+ *
+ * Exists so the unreadable-config condition is NAMEABLE on a surface
+ * rather than only inferable from a gate that suddenly refuses. The
+ * runtime-notice channel reports it; `loadIntegrityConfigSafe` uses the
+ * same distinction to choose its fallback.
+ */
+export function brainConfigReadFailure(vault: string): string | null {
+ if (!existsSync(brainConfigPath(vault))) return null;
+ try {
+ loadBrainConfig(vault);
+ return null;
+ } catch (err) {
+ return err instanceof Error ? err.message : String(err);
+ }
+}
+
+/**
+ * Load + resolve the `integrity:` block.
+ *
+ * Two failure modes, deliberately NOT collapsed into one:
+ *
+ * - CONFIG ABSENT - a vault that has never run `o2b brain init`. The
+ * search layer reads its gate on a store open and must keep working
+ * there, so the gates land on `BRAIN_INTEGRITY_DEFAULTS`. This is the
+ * case the safe-loader pattern legitimately defends.
+ * - CONFIG PRESENT BUT UNREADABLE - a bad gate token, or any unrelated
+ * syntax error anywhere else in the file. Falling back to the
+ * defaults here would silently turn an operator's
+ * `owner_scope_delivery: fail` into `off`. It resolves to
+ * {@link BRAIN_INTEGRITY_STRICT_FALLBACK} instead, and
+ * {@link brainConfigReadFailure} names the cause.
+ */
+export function loadIntegrityConfigSafe(vault: string): ResolvedBrainIntegrityConfig {
+ try {
+ return resolveIntegrity(loadBrainConfig(vault));
+ } catch {
+ return existsSync(brainConfigPath(vault))
+ ? BRAIN_INTEGRITY_STRICT_FALLBACK
+ : BRAIN_INTEGRITY_DEFAULTS;
+ }
+}
+
/**
* Load the configured `feedback.default_scope`, or `undefined` when the
* config file is missing, malformed, or carries no feedback block. Used
@@ -1402,6 +1537,52 @@ export function validateBrainConfigDetailed(
health = Object.keys(partialH).length > 0 ? (partialH as BrainHealthConfig) : {};
}
+ // Optional `integrity:` block (context-integrity-gates). Shape:
+ // integrity:
+ // owner_scope_delivery: off | warn | fail # default off
+ // embedding_abi: off | warn | fail # default warn
+ // pack_validity_seconds: 900 # positive integer
+ // Every value is a hard error when out of range. A gate that clamped
+ // an unrecognised mode to `off`, or a validity window that silently
+ // reverted to the default, would be indistinguishable from the
+ // operator's intent - which is the exact class of silent degradation
+ // this block exists to gate. Absent block β†’ `cfg.integrity` undefined;
+ // `resolveIntegrity` returns the bit-identical defaults.
+ let integrity: BrainIntegrityConfig | undefined;
+ if (hasBlock(obj, "integrity", knownBlockKeys)) {
+ const itObj = requireMapBlock(obj["integrity"], "integrity", source);
+ const partialIt: Record<string, unknown> = {};
+ for (const key of INTEGRITY_GATE_KEYS) {
+ if (key in itObj) {
+ const v = itObj[key];
+ if (!isGateMode(v)) {
+ throw new BrainConfigError(
+ `must be one of ${GATE_MODES.join(", ")}; got ${describe(v)}`,
+ `integrity.${key}`,
+ source,
+ );
+ }
+ partialIt[key] = v;
+ }
+ }
+ if ("pack_validity_seconds" in itObj) {
+ requirePositiveInteger(
+ "integrity.pack_validity_seconds",
+ itObj["pack_validity_seconds"],
+ source,
+ );
+ partialIt["pack_validity_seconds"] = itObj["pack_validity_seconds"] as number;
+ }
+ warnUnknownKeys(
+ itObj,
+ [...INTEGRITY_GATE_KEYS, "pack_validity_seconds"],
+ "integrity",
+ source,
+ warnings,
+ );
+ integrity = Object.keys(partialIt).length > 0 ? (partialIt as BrainIntegrityConfig) : {};
+ }
+
// Optional `notes:` block (v0.11.0). Shape:
// notes:
// read_paths:
@@ -1766,6 +1947,7 @@ export function validateBrainConfigDetailed(
...(notes !== undefined ? { notes } : {}),
...(sessions !== undefined ? { sessions } : {}),
...(health !== undefined ? { health } : {}),
+ ...(integrity !== undefined ? { integrity } : {}),
...(schema !== undefined ? { schema } : {}),
...(hygiene !== undefined ? { hygiene } : {}),
...(anticipatory !== undefined ? { anticipatory } : {}),
diff --git a/src/core/brain/portability/graph.ts b/src/core/brain/portability/graph.ts
index a3a16adb..e52f76d7 100644
--- a/src/core/brain/portability/graph.ts
+++ b/src/core/brain/portability/graph.ts
@@ -28,6 +28,7 @@ import {
} from "../../graph/frontmatter-relations.ts";
import { BRAIN_ROOT_REL, ensureInsideVault } from "../paths.ts";
import { loadVaultMap, resolveTokens } from "./role-tokens.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const GRAPH_VERSION = "1";
@@ -201,6 +202,8 @@ export function importVaultGraph(
graph: { nodes?: ReadonlyArray<unknown> },
opts: { mode?: GraphImportMode } = {},
): GraphImportResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const mode: GraphImportMode = opts.mode ?? "skip";
const result: GraphImportResult = {
created: [],
diff --git a/src/core/brain/portability/okf.ts b/src/core/brain/portability/okf.ts
index 651b8231..64718f35 100644
--- a/src/core/brain/portability/okf.ts
+++ b/src/core/brain/portability/okf.ts
@@ -65,6 +65,7 @@ import {
} from "../paths.ts";
import { isoSecond } from "../time.ts";
import { vaultDisplayName } from "../templates.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const OKF_SCHEMA_VERSION = "1";
export const OKF_PRODUCER = "open-second-brain";
@@ -630,6 +631,8 @@ export function importOkfBundle(
bundle: ParsedOkfBundle,
opts: OkfImportOptions = {},
): OkfImportResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const trusted = opts.trusted === true;
const nowIso = isoSecond(opts.now ?? new Date());
const written: string[] = [];
diff --git a/src/core/brain/portability/profiles.ts b/src/core/brain/portability/profiles.ts
index cd2c28e1..9c911be5 100644
--- a/src/core/brain/portability/profiles.ts
+++ b/src/core/brain/portability/profiles.ts
@@ -12,7 +12,7 @@
* depend on it without a cycle.
*/
-import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
@@ -105,16 +105,40 @@ export function createProfile(configPath: string, name: string, vault: string):
save(configPath, data);
}
-/** Activate a named profile. Throws if the profile does not exist. */
+/**
+ * Activate a named profile. Throws if the profile does not exist, or if
+ * its recorded vault path is not an existing directory.
+ *
+ * The directory check exists because activation used to succeed against
+ * a path that was never there, and the failure surfaced in a LATER
+ * process - as a Brain tree materialized under the mis-resolved root by
+ * the first write, which is indistinguishable from a vault where
+ * nothing has been recorded yet (context-integrity-gates, Unit J). The
+ * check is on the MUTATING call only; `resolveActiveProfileVault` stays
+ * read-only and never throws.
+ */
export function switchProfile(configPath: string, name: string): void {
const data = load(configPath);
- if (!data.profiles[name]) {
+ const profile = data.profiles[name];
+ if (!profile) {
throw new Error(`unknown profile '${name}'`);
}
+ if (!isDirectory(profile.vault)) {
+ throw new Error(`profile '${name}' points at a path that is not a directory: ${profile.vault}`);
+ }
data.active = name;
save(configPath, data);
}
+/** True when `path` exists and is a directory. Never throws. */
+function isDirectory(path: string): boolean {
+ try {
+ return statSync(path).isDirectory();
+ } catch {
+ return false;
+ }
+}
+
/**
* Vault path of the active profile, or `null` when no profile is active
* (or the active pointer dangles). Read-only; never throws.
diff --git a/src/core/brain/pre-compress-pack.ts b/src/core/brain/pre-compress-pack.ts
index e8bab053..f67d329b 100644
--- a/src/core/brain/pre-compress-pack.ts
+++ b/src/core/brain/pre-compress-pack.ts
@@ -15,11 +15,11 @@
* the only ordering inputs are confidence, creation time, and id.
*/
-import { existsSync, readFileSync, readdirSync } from "node:fs";
-import { join } from "node:path";
+import { existsSync, readFileSync } from "node:fs";
+import { renderActive } from "./active.ts";
import { brainActivePath, brainDirs } from "./paths.ts";
-import { parsePreference } from "./preference.ts";
+import { collectPreferences, resolveOwnerScopeDelivery } from "./preferences-collect.ts";
import { applyCharBudget, type CharBudgetDegradationMode } from "./recall-budget.ts";
import { emitContextReceipt, type ContextReceiptOptions } from "./context-receipts.ts";
import { emitGatedTelemetry } from "./continuity/emit.ts";
@@ -72,6 +72,13 @@ export interface PreCompressOptions {
readonly receipt?: ContextReceiptOptions;
/** Opt-in telemetry for recall coverage and gap diagnostics. */
readonly telemetry?: RecallTelemetryOptions;
+ /**
+ * Owner scope for delivery isolation (context-integrity-gates, Unit
+ * A). Enforced only when `integrity.owner_scope_delivery` is `fail`;
+ * omitted, or under the default `off`, nothing is filtered and the
+ * output is byte-identical to a vault without the gate.
+ */
+ readonly agentScope?: string;
}
interface ConfirmedPref {
@@ -81,18 +88,15 @@ interface ConfirmedPref {
readonly createdAt: string;
}
-function collectConfirmed(vault: string): ConfirmedPref[] {
+function collectConfirmed(vault: string, agentScope: string | undefined): ConfirmedPref[] {
const dir = brainDirs(vault).preferences;
- if (!existsSync(dir)) return [];
const out: ConfirmedPref[] = [];
- for (const name of readdirSync(dir)) {
- if (!name.endsWith(".md")) continue;
- let pref;
- try {
- pref = parsePreference(join(dir, name));
- } catch {
- continue;
- }
+ // Listing and parse come from the shared delivery-path walk
+ // (context-integrity-gates, Unit A); the confirmed-status filter is
+ // this surface's own and stays here.
+ for (const { pref } of collectPreferences(dir, {
+ ownerScope: resolveOwnerScopeDelivery(vault, agentScope),
+ }).entries) {
if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;
out.push({
id: pref.id,
@@ -104,7 +108,25 @@ function collectConfirmed(vault: string): ConfirmedPref[] {
return out;
}
-function readActiveHead(vault: string): string | null {
+/**
+ * The active-digest head this caller may see.
+ *
+ * `active.md` is ONE file shared by every agent, so under an enforcing
+ * owner-scope gate the file's own bytes are the wrong answer: they carry
+ * every owner's memories. The scoped caller gets an in-memory
+ * {@link renderActive} instead, which is where the ownership predicate
+ * already attaches. Narrowing the FILE to make this read correct is what
+ * `brain_context` used to do, and it made a shared write follow a
+ * per-request filter (context-integrity-gates, A3).
+ *
+ * With no enforced scope - the shipped `off` default - the file is read
+ * verbatim exactly as before, stamp and all.
+ */
+function readActiveHead(vault: string, enforcedScope: string | null): string | null {
+ if (enforcedScope !== null) {
+ const text = renderActive(vault, { agentScope: enforcedScope }).document.trim();
+ return text.length > 0 ? text : null;
+ }
const path = brainActivePath(vault);
if (!existsSync(path)) return null;
try {
@@ -122,14 +144,17 @@ function readActiveHead(vault: string): string | null {
*/
export function buildPreCompressPack(vault: string, opts: PreCompressOptions): PreCompressPack {
const startedAtMs = Date.now();
- const ranked = collectConfirmed(vault).toSorted((a, b) => {
+ const ranked = collectConfirmed(vault, opts.agentScope).toSorted((a, b) => {
if (b.confidence !== a.confidence) return b.confidence - a.confidence;
if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
});
const top = ranked.slice(0, Math.max(0, opts.topK));
- const activeHead = readActiveHead(vault);
+ const activeHead = readActiveHead(
+ vault,
+ resolveOwnerScopeDelivery(vault, opts.agentScope).enforcedScope,
+ );
const safetyById = new Map<string, ContextSafetyReport>();
const entries: Array<{ item: string; text: string }> = [];
if (activeHead !== null) {
diff --git a/src/core/brain/pref-audit.ts b/src/core/brain/pref-audit.ts
index e708b93a..f54b2833 100644
--- a/src/core/brain/pref-audit.ts
+++ b/src/core/brain/pref-audit.ts
@@ -27,6 +27,7 @@ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname } from "node:path";
import { prefAuditPath } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { isoSecond } from "./time.ts";
import { PREF_AUDIT_OP, type PrefAuditOp, type PrefAuditRecord } from "./types.ts";
@@ -99,6 +100,8 @@ export function appendPrefAudit(
input: AppendPrefAuditInput,
opts: { now?: Date } = {},
): boolean {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
// No-op when an `update` did not change the preference content. Both
// hashes present and equal => counter-only churn, nothing meaningful
// to record. Lifecycle ops always record (see module docstring).
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index 1785ebd0..02a57e76 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -46,7 +46,9 @@ import {
validateSchemaToken,
type BrainSchemaVocabulary,
} from "./schema-vocab.ts";
-import { brainDirs, preferencePath, retiredPath, validateSlug } from "./paths.ts";
+import { brainDirsForWrite, preferencePath, retiredPath, validateSlug } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+import { OWNER_UNRESOLVED } from "../graph/agent-scope.ts";
import { asProvenanceLevel, type ProvenanceLevel } from "./provenance/provenance.ts";
import { sanitisePrinciple } from "./text/sanitize-principle.ts";
import {
@@ -311,6 +313,11 @@ export function writePreference(
input: WritePreferenceInput,
options: WritePreferenceOptions = {},
): WritePreferenceResult {
+ // Vault-identity guard (context-integrity-gates, Unit J). This writer
+ // reaches the tree through `preferencePath`, not `brainDirs`, so
+ // `brainDirsForWrite` cannot cover it - the assertion has to sit at
+ // the entry point, ahead of the field validation and every write.
+ assertVaultIdentityForWrite(vault);
if (!input.slug?.trim()) throw new Error("preference missing field: slug");
if (!input.topic?.trim()) throw new Error("preference missing field: topic");
if (!input.principle?.trim()) {
@@ -799,9 +806,7 @@ export function parsePreference(
...(optionalScalarString(meta, "scope") !== undefined
? { scope: optionalScalarString(meta, "scope") }
: {}),
- ...(optionalScalarString(meta, "owner") !== undefined
- ? { owner: optionalScalarString(meta, "owner") }
- : {}),
+ ...(optionalOwnerField(meta) !== undefined ? { owner: optionalOwnerField(meta) } : {}),
...(provenance !== null ? { provenance } : {}),
...(optionalScalarString(meta, "freshness_trend") !== undefined
? { freshness_trend: optionalScalarString(meta, "freshness_trend") }
@@ -985,6 +990,8 @@ export function parseRetired(path: string, options: ParsePreferenceOptions = {})
...(optionalScalarString(meta, "scope") !== undefined
? { scope: optionalScalarString(meta, "scope") }
: {}),
+ // Retirement KEEPS ownership - see `BrainRetired.owner`.
+ ...(optionalOwnerField(meta) !== undefined ? { owner: optionalOwnerField(meta) } : {}),
...(optionalScalarString(meta, "superseded_by") !== undefined
? { superseded_by: optionalScalarString(meta, "superseded_by") }
: {}),
@@ -1034,7 +1041,7 @@ export function moveToRetired(
// canonical `preferences/` folder. Doing this check *before* any I/O
// means a buggy caller cannot trick us into deleting an unrelated
// file: a misrouted call fails fast with no destructive side effect.
- const dirs = brainDirs(vault);
+ const dirs = brainDirsForWrite(vault);
if (dirname(prefPath) !== dirs.preferences) {
throw new Error(`moveToRetired: source path was not under preferences/: ${prefPath}`);
}
@@ -1366,6 +1373,26 @@ function optionalNumber(meta: Record<string, unknown>, field: string, fallback:
throw new Error(`preference field '${field}' must be a number`);
}
+/**
+ * Read the `owner:` frontmatter field (context-integrity-gates, Unit A).
+ *
+ * Distinct from {@link optionalScalarString} because a present-but-
+ * non-string value must NOT read as absent here: Obsidian Properties
+ * writes any list-shaped field as a YAML sequence, and `owner:` parsed as
+ * an array would otherwise make an owner-private memory ownerless β€” that
+ * is, shared with every agent. Such a claim resolves to
+ * {@link OWNER_UNRESOLVED}, which no requested scope can equal, so the
+ * memory reads as somebody else's. A usable string is stored VERBATIM,
+ * exactly as before; normalization for comparison stays in
+ * `preferenceOwner`.
+ */
+function optionalOwnerField(meta: Record<string, unknown>): string | undefined {
+ const raw = meta["owner"];
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw !== "string") return OWNER_UNRESOLVED;
+ return raw.trim() === "" ? undefined : raw;
+}
+
function optionalScalarString(meta: Record<string, unknown>, field: string): string | undefined {
const v = meta[field];
if (v === undefined || v === null) return undefined;
diff --git a/src/core/brain/preferences-collect.ts b/src/core/brain/preferences-collect.ts
new file mode 100644
index 00000000..bf1e7faf
--- /dev/null
+++ b/src/core/brain/preferences-collect.ts
@@ -0,0 +1,334 @@
+/**
+ * The one directory walk behind every preference-backed context-DELIVERY
+ * surface (context-integrity-gates, Unit A).
+ *
+ * Five surfaces on the delivery path - `active.ts`, `context-pack.ts`,
+ * `pre-compress-pack.ts`, `morning-brief.ts` and `digest.ts` - each grew
+ * its own `readdirSync(dirs.preferences)` loop. Five copies of one walk
+ * is five places an isolation predicate would have to be added, and five
+ * places it could be forgotten. This module is that walk, once, so the
+ * owner predicate has exactly one place to attach.
+ *
+ * ## The ownership predicate lives here, once
+ *
+ * {@link isOwnerVisible} is the vault's single isolation rule; this
+ * module is where the delivery path consults it. The predicate never
+ * engages on its own: a caller must pass the verdict of
+ * {@link resolveOwnerScopeDelivery}, which reads
+ * `integrity.owner_scope_delivery` and only grants narrowing under
+ * `fail`. With the gate on its shipped `off` default every surface here
+ * is byte-for-byte what it was before the gate existed, which is the
+ * contract `agent-scope.ts`, `search/types.ts` and `result-filters.ts`
+ * all state: a null scope is byte-identical to today.
+ *
+ * ## What belongs here, and what does not
+ *
+ * Here: locating candidate files, turning each into a parsed value, and
+ * the ownership predicate.
+ *
+ * NOT here: every DOMAIN filter the surfaces apply after the walk -
+ * tombstone exclusion, `status === confirmed`, recency windows. Those
+ * differ per surface by design and folding them in would make the
+ * collector a switch over its callers rather than a shared walk.
+ *
+ * ## Two parse modes, one walk
+ *
+ * The surfaces split on how they read a file, and the split is real
+ * rather than incidental: four want a validated {@link BrainPreference}
+ * and skip whatever fails to parse, while the context pack wants raw
+ * frontmatter plus the body (it injects the body, and it walks the
+ * retired directory alongside the preferences directory, where the
+ * preference schema does not apply). Both modes share
+ * {@link listPreferenceFiles}; neither reimplements the listing.
+ *
+ * ## Listing differences are parameters, not erasures
+ *
+ * The digest scan lists with `withFileTypes` and keeps only regular
+ * files, and only those named `pref-*`; the other four list bare names.
+ * Those are pre-existing, observable differences (a symlinked
+ * preference file is visible to four surfaces and not to the digest), so
+ * they are expressed as options rather than unified away - unifying them
+ * would be a behaviour change wearing a refactor's clothes.
+ *
+ * Entries are returned in `readdirSync` order, never re-sorted: each
+ * caller owns its own ordering, and imposing one here would change
+ * output the callers currently derive from disk order.
+ */
+
+import { existsSync, readdirSync } from "node:fs";
+import { join } from "node:path";
+
+import { isOwnerVisible, normalizeAgentScope, pageOwner } from "../graph/agent-scope.ts";
+import { DEGRADATION_CODE } from "../integrity/degradation.ts";
+import { GATE_MODE, type GateMode } from "../integrity/stamp.ts";
+import type { FrontmatterMap } from "../types.ts";
+import { parseFrontmatterWithNotices } from "../vault.ts";
+import { isPreferenceVisible } from "./owner-scoped-facts.ts";
+import { loadIntegrityConfigSafe } from "./policy.ts";
+import { parsePreference } from "./preference.ts";
+import type { BrainPreference } from "./types.ts";
+
+/** Attribution recorded on the notices this module's reads produce. */
+const COLLECT_SITE = "brain.preferences-collect";
+
+/** Extension every Brain memory file on the delivery path carries. */
+export const PREFERENCE_FILE_EXT = ".md";
+
+/**
+ * Filename prefix of a preference note. The digest scan requires it so a
+ * hand-dropped file in the preferences directory is not mistaken for a
+ * preference; named here so the literal is not respelled per surface.
+ */
+export const PREFERENCE_ID_PREFIX = "pref-";
+
+/** A candidate file the walk found, before any parse. */
+export interface PreferenceFile {
+ /** Basename, including {@link PREFERENCE_FILE_EXT}. */
+ readonly name: string;
+ /** Absolute path, `join(dir, name)`. */
+ readonly path: string;
+}
+
+/** Per-caller listing rules; both default to the loosest form. */
+export interface PreferenceScanOptions {
+ /**
+ * Required filename prefix. Omitted accepts every `.md` name, which is
+ * what four of the five delivery surfaces do.
+ */
+ readonly namePrefix?: string;
+ /**
+ * Keep only regular files (`Dirent.isFile()`). Omitted lists bare
+ * names, so a directory or symlink whose name ends in `.md` is a
+ * candidate and is rejected later by the parse, exactly as before.
+ */
+ readonly regularFilesOnly?: boolean;
+ /**
+ * The gate's verdict on ownership isolation, from
+ * {@link resolveOwnerScopeDelivery}. Omitted / `null` applies no
+ * ownership filtering at all, which is the shipped default and the
+ * reason an existing vault stays byte-identical.
+ *
+ * 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.
+ *
+ * The rule itself is {@link isOwnerVisible}, reused rather than
+ * restated: an ownerless memory is shared and always kept, an owned
+ * one is kept only for its own scope, and a memory whose owner cannot
+ * be determined is DROPPED - see {@link CollectedPage.unreadable}.
+ */
+ readonly ownerScope?: OwnerScopeDelivery | null;
+}
+
+/**
+ * What a collect call returned, plus the evidence that the ownership
+ * predicate fired.
+ *
+ * The count is what keeps `warn` from being a mode that does nothing:
+ * under `warn` the predicate is still evaluated and the count is still
+ * reported, but nothing is withheld, so an operator can watch the gate
+ * take effect before tightening it to `fail`.
+ */
+export interface PreferenceCollection<T> {
+ readonly entries: ReadonlyArray<T>;
+ /**
+ * How many entries the ownership predicate rejected. Non-zero only
+ * when a scope was requested under `warn` or `fail`; under `fail`
+ * those entries are absent from {@link entries}, under `warn` they are
+ * still present and the count is the only trace.
+ */
+ readonly hiddenByOwnerScope: number;
+}
+
+/**
+ * The delivery path's reading of `integrity.owner_scope_delivery`.
+ *
+ * `enforcedScope` and `requestedScope` are deliberately separate: the
+ * gate decides whether a requested scope may NARROW delivery, and only
+ * `fail` grants that. Under `warn` the caller still knows what was asked
+ * for, so it can report; under `off` it knows nothing at all, so a
+ * consumer wired to this struct structurally cannot emit a new field or
+ * warning while the gate is off - the same property
+ * {@link checkStamp} gives the stamp consumers.
+ */
+export interface OwnerScopeDelivery {
+ /** The operator-chosen mode, echoed so a report can name it. */
+ readonly mode: GateMode;
+ /** Scope that narrows the result. Non-null only under `fail`. */
+ readonly enforcedScope: string | null;
+ /** Scope the caller asked for. Null under `off`, and when none was asked. */
+ readonly requestedScope: string | null;
+}
+
+/**
+ * Resolve a caller-requested agent scope against the vault's
+ * `integrity.owner_scope_delivery` gate.
+ *
+ * The config load is the SAFE form: these surfaces must keep working on
+ * a vault that has never run `o2b brain init`, and an unreadable config
+ * is not a reason to change what a delivery surface returns.
+ */
+export function resolveOwnerScopeDelivery(
+ vault: string,
+ requested: string | undefined,
+): OwnerScopeDelivery {
+ const mode = loadIntegrityConfigSafe(vault).owner_scope_delivery;
+ if (mode === GATE_MODE.off) {
+ return Object.freeze({ mode, enforcedScope: null, requestedScope: null });
+ }
+ const requestedScope = normalizeAgentScope(requested);
+ return Object.freeze({
+ mode,
+ enforcedScope: mode === GATE_MODE.fail ? requestedScope : null,
+ requestedScope,
+ });
+}
+
+/** A preference file parsed through the preference schema. */
+export interface CollectedPreference extends PreferenceFile {
+ readonly pref: BrainPreference;
+}
+
+/** A memory file read as raw frontmatter plus body. */
+export interface CollectedPage extends PreferenceFile {
+ readonly meta: FrontmatterMap;
+ readonly body: string;
+ /**
+ * True when the file could not be read at all, so nothing about it -
+ * including its owner - is known. `parseFrontmatter` resolves an
+ * unreadable file to empty metadata, which is indistinguishable from a
+ * genuinely ownerless page; this flag keeps the two apart so a caller
+ * enforcing isolation can fail closed instead of leaking.
+ */
+ readonly unreadable: boolean;
+}
+
+/**
+ * List the candidate memory files in `dir`, or nothing when the
+ * directory is absent. The only `readdirSync` of a preferences directory
+ * on the delivery path.
+ */
+export function listPreferenceFiles(
+ dir: string,
+ opts: PreferenceScanOptions = {},
+): ReadonlyArray<PreferenceFile> {
+ if (!existsSync(dir)) return [];
+ const out: PreferenceFile[] = [];
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ if (opts.regularFilesOnly === true && !entry.isFile()) continue;
+ const name = entry.name;
+ if (!name.endsWith(PREFERENCE_FILE_EXT)) continue;
+ if (opts.namePrefix !== undefined && !name.startsWith(opts.namePrefix)) continue;
+ out.push({ name, path: join(dir, name) });
+ }
+ return out;
+}
+
+/**
+ * Parse every candidate through the preference schema, omitting the ones
+ * that fail. A corrupt or mis-filed note is the doctor's finding to
+ * report, not the delivery path's to raise - see each caller's docblock.
+ */
+export function collectPreferences(
+ dir: string,
+ opts: PreferenceScanOptions = {},
+): PreferenceCollection<CollectedPreference> {
+ const gate = ownerGate(opts);
+ const entries: CollectedPreference[] = [];
+ let hiddenByOwnerScope = 0;
+ for (const file of listPreferenceFiles(dir, opts)) {
+ let pref: BrainPreference;
+ try {
+ // An unparseable file is already fail-closed: it is omitted under
+ // every scope, so its unknowable owner can never leak.
+ pref = parsePreference(file.path);
+ } catch {
+ continue;
+ }
+ if (gate !== null && !isPreferenceVisible(pref, gate.scope)) {
+ hiddenByOwnerScope += 1;
+ if (gate.enforce) continue;
+ }
+ entries.push({ ...file, pref });
+ }
+ return { entries, hiddenByOwnerScope };
+}
+
+/**
+ * Read every candidate as raw frontmatter plus body. Never throws and
+ * never skips: `parseFrontmatterWithNotices` resolves an unreadable file
+ * to empty metadata, and the entry records that fact in
+ * {@link CollectedPage.unreadable} rather than dropping it, so the
+ * caller decides.
+ */
+export function collectPreferencePages(
+ dir: string,
+ opts: PreferenceScanOptions = {},
+): PreferenceCollection<CollectedPage> {
+ const gate = ownerGate(opts);
+ const entries: CollectedPage[] = [];
+ let hiddenByOwnerScope = 0;
+ for (const file of listPreferenceFiles(dir, opts)) {
+ const [meta, body, notices] = parseFrontmatterWithNotices(file.path, { site: COLLECT_SITE });
+ const unreadable = notices.some((n) => n.code === DEGRADATION_CODE.frontmatterUnreadable);
+ if (gate !== null) {
+ // Fail CLOSED on an unreadable page, matching `applyAgentScope` on
+ // the search side. `parseFrontmatter` resolves an unreadable file
+ // to empty metadata, which reads as "ownerless" and would leak an
+ // owner-private body under an active scope; an unknowable owner is
+ // treated as somebody else's instead.
+ const visible = !unreadable && isOwnerVisible(pageOwner(meta), gate.scope);
+ if (!visible) {
+ hiddenByOwnerScope += 1;
+ if (gate.enforce) continue;
+ }
+ }
+ entries.push({ ...file, meta, body, unreadable });
+ }
+ return { entries, hiddenByOwnerScope };
+}
+
+/**
+ * The one-line report a delivery surface emits when the ownership gate
+ * observed something, or `null` when there is nothing to say.
+ *
+ * Reported ONLY under `warn`, and deliberately so. `warn` withholds
+ * nothing, so naming a count reveals no more than the delivered content
+ * already does, and it is the whole point of the mode: an operator can
+ * watch what `fail` would remove before tightening the gate. Under
+ * `fail` the memories ARE withheld, and 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. So `fail` says nothing at all.
+ *
+ * A surface with no report channel simply does not call this; it is the
+ * mode's meaning that differs, never the delivered bytes.
+ */
+export function formatOwnerScopeWarning(
+ delivery: OwnerScopeDelivery,
+ hiddenByOwnerScope: number,
+): string | null {
+ if (delivery.mode !== GATE_MODE.warn) return null;
+ if (delivery.requestedScope === null || hiddenByOwnerScope <= 0) return null;
+ return (
+ `owner scope ${JSON.stringify(delivery.requestedScope)}: ${hiddenByOwnerScope} ` +
+ `memory item(s) owned by another agent were delivered; set ` +
+ `integrity.owner_scope_delivery to ${GATE_MODE.fail} to withhold them`
+ );
+}
+
+/**
+ * Reduce the gate verdict to what the walk needs: the scope to evaluate
+ * against, and whether a rejection actually withholds the entry.
+ * `null` means "do not evaluate at all", which is the `off` default and
+ * the no-scope-requested case.
+ */
+function ownerGate(
+ opts: PreferenceScanOptions,
+): { readonly scope: string; readonly enforce: boolean } | null {
+ const delivery = opts.ownerScope;
+ if (delivery === undefined || delivery === null) return null;
+ const scope = delivery.requestedScope;
+ if (scope === null) return null;
+ return { scope, enforce: delivery.enforcedScope !== null };
+}
diff --git a/src/core/brain/procedural-graph.ts b/src/core/brain/procedural-graph.ts
index 8ac7d5b1..7a5ace36 100644
--- a/src/core/brain/procedural-graph.ts
+++ b/src/core/brain/procedural-graph.ts
@@ -12,6 +12,7 @@ import {
skillProposalRejectedPath,
} from "./paths.ts";
import type { ProceduralMemoryEntry } from "./types.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export type ProceduralGraphNodeKind = "procedure" | "skill" | "runbook" | "proposal" | "entity";
export type ProceduralGraphEdgeKind =
@@ -50,6 +51,8 @@ export function rebuildProceduralGraph(
vault: string,
opts: ProceduralGraphBuildOptions = {},
): ProceduralGraphProjection {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const now = opts.now ?? new Date();
const nodes: ProceduralGraphNode[] = [];
const edges: ProceduralGraphEdge[] = [];
@@ -180,15 +183,17 @@ function detectProcedureSourceProposal(vault: string, sourcePath: string): strin
return null;
}
if (!existsSync(absPath)) return null;
- try {
- const [fm] = parseFrontmatter(absPath);
- if (typeof fm["source_proposal"] === "string" && fm["source_proposal"].trim()) {
- return fm["source_proposal"].trim();
- }
- return null;
- } catch {
- return null;
+ // Unit F: `parseFrontmatter` cannot throw (it reads inside its own try;
+ // everything after is string work), so the `catch { return null }` that
+ // stood here was unreachable - and redundant, since a failed read
+ // yields an empty map and falls through to the same `return null`.
+ // Dropped lines are reported centrally; see the "Why most readers keep
+ // the two-tuple form" section in src/core/vault.ts.
+ const [fm] = parseFrontmatter(absPath);
+ if (typeof fm["source_proposal"] === "string" && fm["source_proposal"].trim()) {
+ return fm["source_proposal"].trim();
}
+ return null;
}
function listProposals(vault: string): ProceduralGraphNode[] {
@@ -204,26 +209,29 @@ function listProposals(vault: string): ProceduralGraphNode[] {
for (const name of readDirSorted(dir)) {
if (!name.endsWith(".md")) continue;
const absPath = `${dir}/${name}`;
- try {
- const [fm] = parseFrontmatter(absPath);
- if (fm["kind"] !== "brain-skill-proposal") continue;
- const id = typeof fm["id"] === "string" ? fm["id"] : `proposal-${basename(name, ".md")}`;
- out.push({
- id,
- kind: "proposal",
- title:
- typeof fm["slug"] === "string"
- ? `Proposal: ${fm["slug"]}`
- : `Proposal: ${basename(name, ".md")}`,
- sourcePath: `Brain/skill-proposals/${status}/${name}`,
- metadata: {
- status,
- pattern_kind: fm["pattern_kind"] ?? null,
- },
- });
- } catch {
- continue;
- }
+ // Unit F: unreachable `catch { continue }` removed - nothing in this
+ // body throws (`parseFrontmatter` reads inside its own try, and the
+ // rest is property reads and `basename`). A file whose frontmatter
+ // could not be read yields an empty map, fails the `kind` check on
+ // the next line, and is skipped exactly as the dead branch intended.
+ // See the "Why most readers keep the two-tuple form" section in
+ // src/core/vault.ts for where the condition IS reported.
+ const [fm] = parseFrontmatter(absPath);
+ if (fm["kind"] !== "brain-skill-proposal") continue;
+ const id = typeof fm["id"] === "string" ? fm["id"] : `proposal-${basename(name, ".md")}`;
+ out.push({
+ id,
+ kind: "proposal",
+ title:
+ typeof fm["slug"] === "string"
+ ? `Proposal: ${fm["slug"]}`
+ : `Proposal: ${basename(name, ".md")}`,
+ sourcePath: `Brain/skill-proposals/${status}/${name}`,
+ metadata: {
+ status,
+ pattern_kind: fm["pattern_kind"] ?? null,
+ },
+ });
}
}
return out;
diff --git a/src/core/brain/procedural-hints.ts b/src/core/brain/procedural-hints.ts
index a329fb98..8fa7fd2d 100644
--- a/src/core/brain/procedural-hints.ts
+++ b/src/core/brain/procedural-hints.ts
@@ -4,6 +4,7 @@ import { dirname } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { proceduralHintsPath } from "./paths.ts";
import { readProceduralGraph, type ProceduralGraphProjection } from "./procedural-graph.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export interface ProceduralHintEntry {
readonly node_id: string;
@@ -20,6 +21,8 @@ export function rebuildProceduralHints(
vault: string,
opts: { now?: Date; graph?: ProceduralGraphProjection } = {},
): ProceduralHintsProjection {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const graph = opts.graph ?? readProceduralGraph(vault);
const now = opts.now ?? new Date();
const entries: ProceduralHintEntry[] = [];
diff --git a/src/core/brain/procedural-memory.ts b/src/core/brain/procedural-memory.ts
index 3d092cfd..b82ffab8 100644
--- a/src/core/brain/procedural-memory.ts
+++ b/src/core/brain/procedural-memory.ts
@@ -9,6 +9,7 @@ import { rebuildProceduralHints } from "./procedural-hints.ts";
import { rebuildProceduralGraph } from "./procedural-graph.ts";
import { proceduralMemoryIndexPath, proceduralMemoryUsagePath } from "./paths.ts";
import type { ProceduralEntryKind, ProceduralMemoryEntry, ProceduralOutcome } from "./types.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
interface UsageRecord {
readonly usedCount: number;
@@ -312,6 +313,8 @@ function asStringOrNull(value: unknown): string | null {
}
function writeIndex(vault: string, entries: ReadonlyArray<ProceduralMemoryEntry>): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = proceduralMemoryIndexPath(vault);
mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
const payload = JSON.stringify(
diff --git a/src/core/brain/profile-doc.ts b/src/core/brain/profile-doc.ts
index 62de9509..79408a87 100644
--- a/src/core/brain/profile-doc.ts
+++ b/src/core/brain/profile-doc.ts
@@ -18,6 +18,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { buildMorningBrief } from "./morning-brief.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export const PROFILE_DOC_REL = join("Brain", "profile.md");
export const O2BFS_MARKER_FILE = ".o2bfs";
@@ -97,6 +98,8 @@ export interface WriteProfileResult {
/** Materialize `Brain/profile.md` and the `.o2bfs` root marker. */
export function writeProfileDoc(vault: string, opts: ProfileDocOptions): WriteProfileResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const doc = buildProfileDoc(vault, opts);
const path = join(vault, PROFILE_DOC_REL);
atomicWriteFileSync(path, doc.text);
diff --git a/src/core/brain/protect.ts b/src/core/brain/protect.ts
index 4ae0d7dd..253dcc8d 100644
--- a/src/core/brain/protect.ts
+++ b/src/core/brain/protect.ts
@@ -34,6 +34,7 @@ import { join } from "node:path";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import { escapeRegex } from "../strings.ts";
import { BRAIN_ROOT_REL, brainConfigPath, brainDirs } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** Bumped on any structural change to manifest / fence layout. */
export const PROTECT_SCHEMA_VERSION = 1;
@@ -319,6 +320,8 @@ export function readManifest(vault: string, target: ProtectTarget): ManifestReco
}
export function writeManifest(vault: string, entry: ManifestRecord): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = manifestPath(vault);
mkdirSync(join(vault, MANIFEST_DIR), { recursive: true });
const file: ManifestFile = existsSync(path)
@@ -360,6 +363,8 @@ function readFileOrEmpty(path: string): string {
}
export function removeManifestEntry(vault: string, target: ProtectTarget): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = manifestPath(vault);
if (!existsSync(path)) return;
const file = parseManifestFile(readFileSync(path, "utf8"), path);
diff --git a/src/core/brain/query-demand.ts b/src/core/brain/query-demand.ts
index 8902a0dc..3ce7ef6b 100644
--- a/src/core/brain/query-demand.ts
+++ b/src/core/brain/query-demand.ts
@@ -39,6 +39,7 @@ import {
significantTerms,
} from "../search/coverage.ts";
import type { CompletenessVerdict } from "../search/types.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** Longest single normalized term kept; longer tokens are dropped as a
* privacy guard (a 40+ char alnum run is far likelier a secret/id than a
@@ -205,6 +206,8 @@ export function recordQueryDemand(
? { coverage: clamp01(input.coverage) }
: {}),
};
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = queryDemandLogPath(vault);
mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
const handle = acquireLockSync(path);
diff --git a/src/core/brain/query.ts b/src/core/brain/query.ts
index 3cc048dd..d4d12c81 100644
--- a/src/core/brain/query.ts
+++ b/src/core/brain/query.ts
@@ -328,7 +328,14 @@ function collectSignals(dir: string, topic: string, out: BrainSignal[]): void {
try {
sig = parseSignal(path);
} catch {
- // Corrupted frontmatter is the doctor's concern; queries skip.
+ // Unit F, deliberately NOT converted: this catch does not swallow a
+ // frontmatter read. `parseSignal` is the typed validator and its
+ // throw is a real, reachable signal (missing required field, bad
+ // status/folder pairing) that `o2b brain doctor` already reports as
+ // an ERROR against this exact path. Emitting a degradation notice
+ // here would duplicate an existing finding at a lower severity.
+ // The line-level drops underneath it are reported by the doctor's
+ // Brain sweep - see src/core/vault.ts.
continue;
}
if (sig.topic === topic) out.push(sig);
@@ -363,7 +370,10 @@ function findPreferenceForTopic(
const parsed = kind === "preference" ? parsePreference(path) : parseRetired(path);
if (parsed.topic === topic) return parsed;
} catch {
- // Doctor's job, not query's.
+ // Unit F, deliberately NOT converted - same reasoning as
+ // collectSignals above: `parsePreference` / `parseRetired` throw on
+ // typed validation, which the doctor already reports as an error
+ // against this path. Not a swallowed frontmatter read.
continue;
}
}
diff --git a/src/core/brain/recompile.ts b/src/core/brain/recompile.ts
index e109bb90..9768c321 100644
--- a/src/core/brain/recompile.ts
+++ b/src/core/brain/recompile.ts
@@ -18,7 +18,8 @@ import { basename, isAbsolute, join } from "node:path";
import { appendAuditRecord } from "../reliability/audit.ts";
import { scanFreshness } from "./freshness.ts";
import { writeHandoffNote } from "./handoff.ts";
-import { brainDirs, BRAIN_SNAPSHOTS_REL } from "./paths.ts";
+import { brainDirsForWrite, BRAIN_SNAPSHOTS_REL } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { detectAdapter } from "./sessions/registry.ts";
import type { SessionTurn } from "./sessions/types.ts";
import { isoDate } from "./time.ts";
@@ -130,6 +131,11 @@ async function readTranscriptTurns(transcript: string): Promise<SessionTurn[] |
* hygiene `archive` / `forget` actions.
*/
export function archivePage(vault: string, page: string, now: Date): string {
+ // Vault-identity write guard (context-integrity-gates, Unit J). This is
+ // a public export reached from hygiene `archive`/`forget` as well as
+ // from the recompile executor, so it carries its own assertion ahead of
+ // the `mkdirSync` + `renameSync` pair rather than relying on a caller.
+ assertVaultIdentityForWrite(vault);
const dir = join(vault, BRAIN_SNAPSHOTS_REL, `hygiene-${isoDate(now)}`);
mkdirSync(dir, { recursive: true });
let target = join(dir, basename(page));
@@ -152,6 +158,11 @@ export async function executeRecompile(
opts: ExecuteRecompileOptions,
): Promise<RecompileResult> {
const dryRun = opts.dryRun === true;
+ // Vault-identity write guard (context-integrity-gates, Unit J). The
+ // per-entry loop is fail-soft, so a guard reached only from inside it
+ // would be recorded as an ordinary entry error instead of refusing the
+ // run; a dry run previews and writes nothing, so it stays ungated.
+ if (!dryRun) assertVaultIdentityForWrite(vault);
const rederived: string[] = [];
const archived: string[] = [];
const manual: string[] = [];
@@ -194,7 +205,7 @@ export async function executeRecompile(
!dryRun &&
(rederived.length > 0 || archived.length > 0 || manual.length > 0 || errors.length > 0)
) {
- appendAuditRecord(join(brainDirs(vault).log, "hygiene"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, "hygiene"), {
timestamp: opts.now.toISOString(),
actor: opts.agent,
action: "targeted_recompile",
diff --git a/src/core/brain/recurrence.ts b/src/core/brain/recurrence.ts
index c14c913b..b4e02613 100644
--- a/src/core/brain/recurrence.ts
+++ b/src/core/brain/recurrence.ts
@@ -3,6 +3,7 @@ import { dirname } from "node:path";
import { ensureInsideVault } from "../path-safety.ts";
import { proceduralRecurrencePath } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export type RecurrenceCommitment = "exploring" | "leaning" | "decided" | "locked";
export type RecurrenceAction = "learn" | "forget";
@@ -231,6 +232,8 @@ function commitmentForSupport(
}
function appendEvent(vault: string, event: RecurrenceEvent): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = proceduralRecurrencePath(vault);
mkdirSync(ensureInsideVault(dirname(path), vault), { recursive: true });
appendFileSync(path, `${JSON.stringify(event)}\n`, { encoding: "utf8" });
diff --git a/src/core/brain/report-snapshot.ts b/src/core/brain/report-snapshot.ts
index 84858fb7..e280a912 100644
--- a/src/core/brain/report-snapshot.ts
+++ b/src/core/brain/report-snapshot.ts
@@ -27,6 +27,7 @@ import { join } from "node:path";
import { discoverConfig } from "../config.ts";
import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
export const REPORT_SNAPSHOT_SCHEMA_VERSION = "o2b.report-snapshot.v1";
@@ -160,6 +161,8 @@ export function writeReportSnapshot(
date: string,
payload: unknown,
): string {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const dir = reportsDir(vault, surface);
mkdirSync(dir, { recursive: true });
const path = join(dir, `${date}.json`);
diff --git a/src/core/brain/research/research.ts b/src/core/brain/research/research.ts
index 8abfdd6a..ed2b99c6 100644
--- a/src/core/brain/research/research.ts
+++ b/src/core/brain/research/research.ts
@@ -25,6 +25,7 @@ import { canonicalNotePath } from "../../path-safety.ts";
import { slugify, writeFrontmatterAtomic } from "../../vault.ts";
import { isoDate, isoSecond } from "../time.ts";
import { reportPagePath } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { renderProvenanceSection, type Provenance } from "../provenance/provenance.ts";
import {
ExternalFetchError,
@@ -128,6 +129,8 @@ export function writeResearchReport(
input: ResearchReportInput,
opts: ResearchReportOptions,
): ResearchReportResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
validate(input);
const date = isoDate(opts.now);
diff --git a/src/core/brain/retrieval-plan.ts b/src/core/brain/retrieval-plan.ts
index ea98b67f..57f90222 100644
--- a/src/core/brain/retrieval-plan.ts
+++ b/src/core/brain/retrieval-plan.ts
@@ -108,7 +108,11 @@ export interface RetrievalPlanAdvice {
export interface RetrievalPlanDeps {
/** Context pack producer; defaults to a read-only {@link packContext}. */
- readonly pack?: (vault: string, budget: number) => ContextPackReport;
+ readonly pack?: (
+ vault: string,
+ budget: number,
+ agentScope: string | undefined,
+ ) => ContextPackReport;
/** Token-impact summary; defaults to {@link summarizeTokenImpact}. */
readonly tokenImpact?: (vault: string) => TokenImpactSummary;
/** Route latency summary; defaults to {@link summarizeMcpRouteLatency}. */
@@ -117,6 +121,15 @@ export interface RetrievalPlanDeps {
readonly surfaceVocabulary?: ReadonlySet<string>;
/** Context-pack token budget; defaults to {@link DEFAULT_PLAN_TOKEN_BUDGET}. */
readonly tokenBudget?: number;
+ /**
+ * Owner scope for the pack the advice is computed over
+ * (context-integrity-gates, Unit A). The plan returns no memory
+ * bodies, but its item count and density curve are derived from them,
+ * so advice built over memories the caller may not see would describe
+ * a pack it can never receive. Gated like every other
+ * preference-backed surface; omitted filters nothing.
+ */
+ readonly agentScope?: string;
}
// ----- Composition ----------------------------------------------------------
@@ -130,8 +143,16 @@ function summarySurfaceVocabulary(vault: string): ReadonlySet<string> {
}
/** Read-only default pack: no receipt, telemetry, or metric, so nothing is written. */
-function defaultPack(vault: string, budget: number): ContextPackReport {
- return packContext(vault, { maxTokens: budget, densityRanking: true });
+function defaultPack(
+ vault: string,
+ budget: number,
+ agentScope: string | undefined,
+): ContextPackReport {
+ return packContext(vault, {
+ maxTokens: budget,
+ densityRanking: true,
+ ...(agentScope !== undefined ? { agentScope } : {}),
+ });
}
function graphExpansionFor(intent: QueryIntent): RetrievalPlanGraphExpansion {
@@ -215,7 +236,7 @@ export function buildRetrievalPlan(
const vocab = deps.surfaceVocabulary ?? summarySurfaceVocabulary(vault);
const queryPlan = buildQueryPlan(question, [], null, vocab);
- const pack = (deps.pack ?? defaultPack)(vault, budget);
+ const pack = (deps.pack ?? defaultPack)(vault, budget, deps.agentScope);
const items = pack.items;
const densityCurve = items.map((i) => i.density ?? 0);
const tokens = items.map((i) => i.tokens);
diff --git a/src/core/brain/rollup-ladder.ts b/src/core/brain/rollup-ladder.ts
index a2fcd761..42cb82e2 100644
--- a/src/core/brain/rollup-ladder.ts
+++ b/src/core/brain/rollup-ladder.ts
@@ -24,6 +24,7 @@ import { existsSync, readFileSync } from "node:fs";
import { atomicWriteFileSync } from "../fs-atomic.ts";
import type { BrainConfig } from "./types.ts";
import { rollupLedgerPath } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** New facts since the last rollup that trigger a fact -> rollup step. */
export const DEFAULT_FACT_ROLLUP_THRESHOLD = 20;
@@ -127,6 +128,8 @@ export function readRollupLedger(vault: string): RollupLedger | null {
/** Persist the ledger. Called only when a rung fired. */
export function writeRollupLedger(vault: string, ledger: RollupLedger): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
atomicWriteFileSync(rollupLedgerPath(vault), `${JSON.stringify(ledger, null, 2)}\n`);
}
diff --git a/src/core/brain/runtime-notices.ts b/src/core/brain/runtime-notices.ts
index c7cf94fa..2309f234 100644
--- a/src/core/brain/runtime-notices.ts
+++ b/src/core/brain/runtime-notices.ts
@@ -17,11 +17,15 @@
*/
import { existsSync } from "node:fs";
+import { join } from "node:path";
import lockfile from "proper-lockfile";
import { resolveSearchConfig } from "../search/index.ts";
import { checkVaultWriteable } from "../doctor.ts";
+import { BRAIN_ROOT_REL } from "./paths.ts";
+import { brainConfigReadFailure } from "./policy.ts";
+import { vaultMarkerAbsentNotice } from "./vault-identity.ts";
export type RuntimeNoticeSeverity = "info" | "warning";
@@ -66,6 +70,45 @@ export function collectRuntimeNotices(
// best-effort
}
+ // Vault identity: a Brain tree with no identity marker cannot tell an
+ // old vault from a mis-resolved root, and the write guard can only warn
+ // about it (context-integrity-gates, Unit J). Gated on the tree already
+ // existing, because a root nothing has written to yet is not a wrong
+ // store - it is a vault waiting for `o2b brain init`, and nagging before
+ // that command runs would make the notice noise instead of signal.
+ try {
+ if (existsSync(join(vault, BRAIN_ROOT_REL))) {
+ const absent = vaultMarkerAbsentNotice(vault);
+ if (absent !== null) {
+ notices.push({
+ code: "vault_marker_absent",
+ severity: "warning",
+ message: `${absent.detail} (${absent.path})`,
+ });
+ }
+ }
+ } catch {
+ // best-effort
+ }
+
+ // An unreadable `_brain.yaml`: every `load*ConfigSafe` reader falls
+ // back, and for the integrity gates that fallback is now the STRICT
+ // one rather than the defaults. Either way the operator's settings are
+ // not the ones in force, so the condition has to be visible instead of
+ // inferable from a gate that suddenly refuses.
+ try {
+ const failure = brainConfigReadFailure(vault);
+ if (failure !== null) {
+ notices.push({
+ code: "brain_config_unreadable",
+ severity: "warning",
+ message: `Brain/_brain.yaml could not be read, so configured settings are not in force and the integrity gates fall back to their strictest mode (${failure}). Fix the file, then re-run.`,
+ });
+ }
+ } catch {
+ // best-effort
+ }
+
// Search index availability + semantic degradation.
try {
const config = resolveSearchConfig({ vault, configPath: opts.configPath });
diff --git a/src/core/brain/schema-mutate.ts b/src/core/brain/schema-mutate.ts
index 1531b27d..ff2d4815 100644
--- a/src/core/brain/schema-mutate.ts
+++ b/src/core/brain/schema-mutate.ts
@@ -4,7 +4,8 @@ import { join } from "node:path";
import { appendAuditRecord } from "../reliability/audit.ts";
import { atomicWriteText } from "../fs-atomic.ts";
import { withFileLock } from "../reliability/lock.ts";
-import { brainConfigPath, brainDirs } from "./paths.ts";
+import { brainConfigPath, brainDirsForWrite } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import {
parseSchemaPack,
renderSchemaBlock,
@@ -126,6 +127,10 @@ export async function applySchemaMutations(
mutations: ReadonlyArray<SchemaMutation>,
opts: ApplySchemaMutationsOptions,
): Promise<ApplySchemaMutationsResult> {
+ // Vault-identity write guard (context-integrity-gates, Unit J), ahead
+ // of the `_brain.yaml` rewrite - the trailing audit append is far too
+ // late to stop a schema landing in the wrong store.
+ assertVaultIdentityForWrite(vault);
const configPath = brainConfigPath(vault);
const now = opts.now ?? new Date();
return await withFileLock(configPath, { staleMs: opts.lockStaleMs ?? 30_000, retries: 3 }, () => {
@@ -139,7 +144,7 @@ export async function applySchemaMutations(
parseSchemaPack(candidate);
},
});
- const auditPath = appendAuditRecord(join(brainDirs(vault).log, "schema-mutations"), {
+ const auditPath = appendAuditRecord(join(brainDirsForWrite(vault).log, "schema-mutations"), {
timestamp: now.toISOString(),
actor: opts.actor,
action: "schema_apply_mutations",
diff --git a/src/core/brain/secrets/exec.ts b/src/core/brain/secrets/exec.ts
index 49765815..de446416 100644
--- a/src/core/brain/secrets/exec.ts
+++ b/src/core/brain/secrets/exec.ts
@@ -12,7 +12,7 @@
import { redactRawOutput } from "../../redactor.ts";
import { appendAuditRecord } from "../../reliability/audit.ts";
import { escapeRegex } from "../../strings.ts";
-import { brainDirs } from "../paths.ts";
+import { brainDirsForWrite } from "../paths.ts";
import { join } from "node:path";
import { resolveSecretForExec, type SecretAuditContext } from "./store.ts";
@@ -99,7 +99,7 @@ export async function runWithSecret(
});
const resolved = resolveSecretForExec(vault, name, ctx);
if (!matchesAllowlist(resolved.allow, command)) {
- appendAuditRecord(join(brainDirs(vault).log, "secret-custody"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, "secret-custody"), {
timestamp: ctx.now.toISOString(),
actor: ctx.agent,
action: "secret_exec_denied",
@@ -110,7 +110,7 @@ export async function runWithSecret(
throw new SecretExecDeniedError(resolved.name, command, resolved.allow);
}
- appendAuditRecord(join(brainDirs(vault).log, "secret-custody"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, "secret-custody"), {
timestamp: ctx.now.toISOString(),
actor: ctx.agent,
action: "secret_exec_started",
diff --git a/src/core/brain/secrets/store.ts b/src/core/brain/secrets/store.ts
index 7f050f1a..67485dae 100644
--- a/src/core/brain/secrets/store.ts
+++ b/src/core/brain/secrets/store.ts
@@ -17,7 +17,8 @@ import { join } from "node:path";
import lockfile from "proper-lockfile";
import { appendAuditRecord } from "../../reliability/audit.ts";
-import { brainDirs } from "../paths.ts";
+import { brainDirsForWrite } from "../paths.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { decryptValue, encryptValue, loadOrCreateKey, type EncryptedValue } from "./crypto.ts";
export const SECRETS_SCHEMA_VERSION = 1;
@@ -110,6 +111,11 @@ function withSecretsLock<T>(vault: string, fn: () => T): T {
}
export function setSecret(vault: string, input: SetSecretInput): SecretMetadata {
+ // Vault-identity write guard (context-integrity-gates, Unit J), AHEAD
+ // of `loadOrCreateKey`: that call mints a keyfile and creates the 0700
+ // state directory, so a guard sitting on the trailing audit append
+ // would have already put key material in the wrong vault.
+ assertVaultIdentityForWrite(vault);
const name = input.name.trim().toLowerCase();
if (!NAME_RE.test(name)) {
throw new Error(
@@ -165,6 +171,8 @@ export function listSecrets(vault: string): SecretMetadata[] {
}
export function removeSecret(vault: string, name: string, ctx: SecretAuditContext): boolean {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const normalized = name.trim().toLowerCase();
const removed = withSecretsLock(vault, () => {
const file = readStore(vault);
@@ -190,12 +198,19 @@ export interface ResolvedSecret {
* Decrypt one secret for the exec path. THE ONLY reader of secret
* material; everything it returns must go straight into a subprocess
* env and nowhere else. Audited as `secret_resolved_for_exec`.
+ *
+ * READ-SHAPED BUT A WRITER. It stamps `last_used_at` through
+ * {@link touchLastUsed} and appends a custody record, so it carries the
+ * vault-identity guard like any other writer. The guard is at the top,
+ * ahead of `loadOrCreateKey`, which would otherwise mint a keyfile in
+ * the wrong store before the refusal.
*/
export function resolveSecretForExec(
vault: string,
name: string,
ctx: SecretAuditContext = { agent: "cli", now: new Date() },
): ResolvedSecret {
+ assertVaultIdentityForWrite(vault);
const file = readStore(vault);
const normalized = name.trim().toLowerCase();
const stored = file.secrets[normalized];
@@ -254,6 +269,12 @@ function writeStore(vault: string, file: SecretsFile): void {
renameSync(tmp, path);
}
+/**
+ * Stamp `last_used_at`. Private, and reached only from
+ * {@link resolveSecretForExec}, which carries the vault-identity guard
+ * at its entry point - the assertion is not repeated here so there stays
+ * exactly one guard per public entry point.
+ */
function touchLastUsed(vault: string, name: string, now: Date): void {
// Re-read under the lock: the snapshot the resolver decrypted from
// may be stale by the time the usage stamp lands.
@@ -275,7 +296,7 @@ function audit(
name: string,
details: Record<string, unknown>,
): void {
- appendAuditRecord(join(brainDirs(vault).log, "secret-custody"), {
+ appendAuditRecord(join(brainDirsForWrite(vault).log, "secret-custody"), {
timestamp: ctx.now.toISOString(),
actor: ctx.agent,
action,
diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.ts
index d0fa7a7a..e7e2ce1a 100644
--- a/src/core/brain/session-lifecycle.ts
+++ b/src/core/brain/session-lifecycle.ts
@@ -3,7 +3,7 @@ import { basename, join } from "node:path";
import { appendAuditRecord } from "../reliability/audit.ts";
import { appendLogEvent } from "./log.ts";
-import { brainDirs } from "./paths.ts";
+import { brainDirsForWrite } from "./paths.ts";
import { buildCaptureBoundary, type SessionCaptureDecision } from "./capture-boundary.ts";
import { extractFacts, routeExtractedFacts } from "./fact-extract.ts";
import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";
@@ -18,8 +18,14 @@ import { resolveSessionHandoff } from "../config.ts";
import { writeHandoffNote, type HandoffNoteResult } from "./handoff.ts";
import { detectAdapter } from "./sessions/registry.ts";
import type { SessionTurn } from "./sessions/types.ts";
-import { readLineageLedger, recordLineageObservation } from "./lineage/ledger.ts";
-import { resolveSessionLineage } from "./lineage/resolve.ts";
+import {
+ lineageGapSessionIds,
+ readLineageLedger,
+ recordLineageObservation,
+} from "./lineage/ledger.ts";
+import { resolveSessionLineageDetailed } from "./lineage/resolve.ts";
+import { readGitWorkspaceIdentity } from "./git/reader.ts";
+import { type DegradationNotice, formatDegradationNotice } from "../integrity/degradation.ts";
import { isCompressionEvidenceEvent, type SessionLineage } from "./lineage/types.ts";
import { refreshAnticipatoryCache } from "./anticipatory-cache.ts";
@@ -126,9 +132,25 @@ export async function captureSessionLifecycleEvent(
// Read-only resolution runs for every session; the ledger only
// grows for captured, non-dry runs. Fail-soft throughout.
let lineage: SessionLineage | undefined;
+ /** Continuations that were available and REFUSED. */
+ const lineageNotices: DegradationNotice[] = [];
+ /**
+ * Observations that were made and NOT APPENDED. Kept apart from the
+ * abstentions above because they are opposite findings: one says the
+ * resolver declined to link, the other says the history the resolver
+ * will read next time is missing a line.
+ */
+ const lineageDrops: DegradationNotice[] = [];
if (normalized.sessionId !== undefined) {
try {
- lineage = resolveSessionLineage(
+ // Unit C: probe the working state ONCE per lifecycle event, at
+ // the capture boundary, so the resolver below stays a pure
+ // function of its inputs. Two bounded git invocations; a
+ // directory outside any repository attests nothing and costs one
+ // failed spawn.
+ const workspace =
+ normalized.cwd !== undefined ? readGitWorkspaceIdentity(normalized.cwd) : null;
+ const resolution = resolveSessionLineageDetailed(
{
sessionId: normalized.sessionId,
...(normalized.parentSessionId !== undefined
@@ -141,11 +163,28 @@ export async function captureSessionLifecycleEvent(
? { compressionDepth: normalized.compressionDepth }
: {}),
...(normalized.cwd !== undefined ? { cwd: normalized.cwd } : {}),
+ ...(workspace !== null ? { workspace } : {}),
+ },
+ {
+ ledger: readLineageLedger(vault),
+ // Unit C / block C: a session whose observation the writer
+ // lock refused has history the ledger cannot show. Without
+ // this the crutch reads it as brand new and stitches it onto
+ // an unrelated parallel session in the same directory.
+ gapSessionIds: lineageGapSessionIds(vault),
+ nowMs: now.getTime(),
+ notices: lineageNotices,
},
- { ledger: readLineageLedger(vault), nowMs: now.getTime() },
);
+ lineage = resolution.lineage;
if (mayWrite && !opts.dryRun) {
- recordLineageObservation(vault, {
+ // The return value carries a NAMED gap when the observation was
+ // not appended. Discarding it - which this call site did, as a
+ // bare statement - restored the silent failure the widened
+ // return type exists to remove: the same audit record that
+ // reports a refused continuation can report a lost observation,
+ // and the two are the same class of finding.
+ const recorded = recordLineageObservation(vault, {
sessionId: normalized.sessionId,
at: now.toISOString(),
...(normalized.cwd !== undefined ? { cwd: normalized.cwd } : {}),
@@ -154,7 +193,9 @@ export async function captureSessionLifecycleEvent(
? { compressionEvidence: true }
: {}),
...(lineage.source !== "flat" ? { lineage } : {}),
+ ...(workspace !== null ? { workspace } : {}),
});
+ if (recorded.notice !== undefined) lineageDrops.push(recorded.notice);
}
} catch {
lineage = undefined; // lineage is an enhancement, never a blocker
@@ -304,7 +345,7 @@ export async function captureSessionLifecycleEvent(
logPath = appendLifecycleLog(vault, normalized, opts.agent, now, counters);
}
- const auditPath = appendAuditRecord(join(brainDirs(vault).log, "session-lifecycle"), {
+ const auditPath = appendAuditRecord(join(brainDirsForWrite(vault).log, "session-lifecycle"), {
timestamp: now.toISOString(),
actor: opts.agent,
action: "session_lifecycle_capture",
@@ -325,6 +366,18 @@ export async function captureSessionLifecycleEvent(
lineage_source: chainLineage.source,
}
: {}),
+ // Unit C: a continuation that was AVAILABLE and refused. Absent
+ // on the ordinary flat path, so a session with nothing to link to
+ // keeps its previous audit shape exactly.
+ ...(lineageNotices.length > 0
+ ? { lineage_abstained: lineageNotices.map(formatDegradationNotice) }
+ : {}),
+ // Block C: the observation this event tried to record and could
+ // not. Absent on every successful append, so the ordinary audit
+ // shape is unchanged.
+ ...(lineageDrops.length > 0
+ ? { lineage_dropped: lineageDrops.map(formatDegradationNotice) }
+ : {}),
...counters,
},
});
diff --git a/src/core/brain/set-primary.ts b/src/core/brain/set-primary.ts
index f78338ba..74a24aeb 100644
--- a/src/core/brain/set-primary.ts
+++ b/src/core/brain/set-primary.ts
@@ -31,6 +31,7 @@ import { atomicWriteFileSync } from "../fs-atomic.ts";
import { brainConfigPath } from "./paths.ts";
import { parseBrainYaml } from "./yaml-parse.ts";
import { BrainConfigError, formatPrimaryAgentYamlValue, validateBrainConfig } from "./policy.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/**
* Result of {@link setPrimaryAgent}. `previous` is the value on disk
@@ -57,6 +58,8 @@ const LINE_RE = /^primary_agent:.*$/m;
* the loader will reject on the next read.
*/
export function setPrimaryAgent(vault: string, name: string | null): SetPrimaryAgentResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const path = brainConfigPath(vault);
if (!existsSync(path)) {
throw new BrainConfigError(
diff --git a/src/core/brain/signal-retire.ts b/src/core/brain/signal-retire.ts
index 7adb97aa..1b5d3949 100644
--- a/src/core/brain/signal-retire.ts
+++ b/src/core/brain/signal-retire.ts
@@ -30,7 +30,7 @@ import { existsSync, unlinkSync } from "node:fs";
import { join } from "node:path";
import { appendLogEvent } from "./log.ts";
-import { brainDirs, ensureInsideVault } from "./paths.ts";
+import { brainDirsForWrite, ensureInsideVault } from "./paths.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";
import { isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
@@ -113,7 +113,7 @@ export function retireSignal(
throw new InvalidSignalIdError(trimmed);
}
- const dirs = brainDirs(vault);
+ const dirs = brainDirsForWrite(vault);
const srcPath = ensureInsideVault(join(dirs.inbox, `${trimmed}.md`), vault);
const destPath = ensureInsideVault(join(dirs.retired, `${trimmed}.md`), vault);
diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.ts
index d385b726..14408965 100644
--- a/src/core/brain/signal.ts
+++ b/src/core/brain/signal.ts
@@ -38,7 +38,7 @@ import { sanitisePrinciple } from "./text/sanitize-principle.ts";
import { normalizeExpirationDate } from "./expiration.ts";
import { writeFrontmatterAtomic, parseFrontmatter } from "../vault.ts";
import { compress, expand, CODEC_VERSION } from "./portability/codec.ts";
-import { allocateSlug, brainDirs, validateIsoDate } from "./paths.ts";
+import { allocateSlug, brainDirsForWrite, validateIsoDate } from "./paths.ts";
import {
isKnownSchemaToken,
validateSchemaToken,
@@ -295,7 +295,10 @@ export function writeSignal(
}
}
- const dirs = brainDirs(vault);
+ // Write-intent variant (Unit J): a signal write is the path that
+ // materializes a mis-resolved root, so it asserts the vault identity
+ // before allocating a filename under it.
+ const dirs = brainDirsForWrite(vault);
const allocated = allocateSlug({
vault,
targetDir: options.targetDir ?? dirs.inbox,
diff --git a/src/core/brain/skill-proposals.ts b/src/core/brain/skill-proposals.ts
index 7eb235e8..9cc8c084 100644
--- a/src/core/brain/skill-proposals.ts
+++ b/src/core/brain/skill-proposals.ts
@@ -24,6 +24,7 @@ import {
skillProposalPendingPath,
skillProposalRejectedPath,
} from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { listContinuityRecords, type ContinuityRecord } from "./continuity/store.ts";
export type SkillProposalPatternKind =
@@ -90,6 +91,8 @@ export function learnSkillProposals(
vault: string,
opts: SkillProposalLearnOptions = {},
): SkillProposalLearnResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const now = opts.now ?? new Date();
const minSupport = Math.max(2, opts.minSupport ?? DEFAULT_MIN_SUPPORT);
@@ -271,6 +274,8 @@ export function acceptSkillProposal(
slug: string,
opts: { now?: Date; note?: string } = {},
): SkillProposalReviewResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const now = (opts.now ?? new Date()).toISOString();
const pendingPath = skillProposalPendingPath(vault, slug);
if (!existsSync(pendingPath)) {
@@ -350,6 +355,8 @@ export function rejectSkillProposal(
slug: string,
opts: { now?: Date; note: string },
): SkillProposalReviewResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
if (!opts.note.trim()) {
throw new Error("rejecting skill proposal requires a non-empty note");
}
diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.ts
index 1a9c5d80..02441eaa 100644
--- a/src/core/brain/snapshot.ts
+++ b/src/core/brain/snapshot.ts
@@ -50,7 +50,14 @@ import { tmpdir } from "node:os";
import { basename, join } from "node:path";
import { buildManifest, manifestSidecarPath, writeManifestSidecar } from "./manifest.ts";
-import { BRAIN_ROOT_REL, brainDirs, snapshotPath, validateRunId } from "./paths.ts";
+import {
+ BRAIN_ROOT_REL,
+ brainDirs,
+ brainDirsForWrite,
+ snapshotPath,
+ validateRunId,
+} from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
// ----- Errors ---------------------------------------------------------------
@@ -174,7 +181,7 @@ function detectTooling(): ToolAvailability {
*/
export function createSnapshot(vault: string, runId: string): CreateSnapshotResult {
validateRunId(runId);
- const dirs = brainDirs(vault);
+ const dirs = brainDirsForWrite(vault);
mkdirSync(dirs.snapshots, { recursive: true });
const outPath = snapshotPath(vault, runId);
@@ -395,6 +402,11 @@ export function listSnapshots(vault: string): SnapshotInfo[] {
* on the same dir returns `deleted: []`.
*/
export function pruneSnapshots(vault: string, retentionCount: number): PruneSnapshotsResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J). This is
+ // the most destructive operation in the module - an `rmSync` over
+ // archives - and it was the only one of the three without the guard
+ // its `createSnapshot` and `restoreSnapshot` siblings carry.
+ assertVaultIdentityForWrite(vault);
if (!Number.isInteger(retentionCount) || retentionCount < 0) {
throw new Error(
`pruneSnapshots: retentionCount must be a non-negative integer; got ${retentionCount}`,
@@ -566,7 +578,7 @@ export function restoreSnapshot(
// eslint-disable-next-line @typescript-eslint/no-unused-vars -- reserved for future log emission
_opts: { now?: Date } = {},
): RestoreSnapshotResult {
- const dirs = brainDirs(vault);
+ const dirs = brainDirsForWrite(vault);
const ext = extractSnapshotToTemp(vault, runId);
try {
// Replace every top-level entry under Brain/, EXCEPT `.snapshots/`.
diff --git a/src/core/brain/source-cleanup.ts b/src/core/brain/source-cleanup.ts
index 9b513dd4..5d999157 100644
--- a/src/core/brain/source-cleanup.ts
+++ b/src/core/brain/source-cleanup.ts
@@ -59,6 +59,7 @@ import { manifestPath, readManifest, writeManifestAtomic } from "./ingest/conten
import { appendContinuitySourceInvalidation } from "./continuity/store.ts";
import { isoSecond } from "./time.ts";
import { withDestructiveSnapshot } from "./snapshot-gate.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
/** Run-id label for the snapshot taken before a confirmed source cleanup. */
const DELETE_BY_SOURCE_SNAPSHOT_LABEL = "delete-by-source";
@@ -244,13 +245,14 @@ function directMatch(
} catch {
return null;
}
- let meta: FrontmatterMap = {};
- try {
- [meta] = parseFrontmatter(absPath);
- } catch {
- // A page we cannot parse is scanned as raw text only.
- meta = {};
- }
+ // Unit F: `parseFrontmatter` cannot throw (it reads inside its own try;
+ // everything after is string work), so the `catch { meta = {} }` that
+ // stood here was unreachable - and its intent is what the parser
+ // already does, returning an empty map for a failed read, so a page
+ // whose frontmatter is unavailable is still scanned as raw text.
+ // Dropped lines are reported centrally; see the "Why most readers keep
+ // the two-tuple form" section in src/core/vault.ts.
+ const [meta] = parseFrontmatter(absPath);
const kind = classifyKind(vault, absPath);
const sourceLinks = stringArrayField(meta, "source");
@@ -333,12 +335,11 @@ function traceReferences(vault: string, sourceFile: string): Traced {
if (alreadyMatched.has(absPath)) continue;
const kind = classifyKind(vault, absPath);
if (kind !== "preference") continue;
- let meta: FrontmatterMap;
- try {
- [meta] = parseFrontmatter(absPath);
- } catch {
- continue;
- }
+ // Unit F: unreachable `catch { continue }` removed - see directMatch
+ // above. An unreadable page yields an empty map, so it has no
+ // `_evidenced_by` links and falls out on the next line exactly as
+ // the dead branch intended.
+ const [meta] = parseFrontmatter(absPath);
const evidencedBy = evidencedByLinks(meta);
const targets = evidencedBy.map((link) => wikilinkTarget(link));
if (targets.length === 0) continue;
@@ -492,6 +493,9 @@ export function deleteBySource(
const canonical = canonicalNotePath(sourceFile);
const confirm = opts.confirm === true;
const includeOriginals = opts.includeOriginals === true;
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ // Dry-run (the default) plans and writes nothing, so it stays ungated.
+ if (confirm) assertVaultIdentityForWrite(vault);
const { derived, mentions } = traceReferences(vault, sourceFile);
const originals = findOriginals(vault, canonical);
diff --git a/src/core/brain/tensions.ts b/src/core/brain/tensions.ts
index 62b20d56..b778a7e7 100644
--- a/src/core/brain/tensions.ts
+++ b/src/core/brain/tensions.ts
@@ -43,6 +43,7 @@ import {
import { appendLogEvent } from "./log.ts";
import { buildNoteWalkRules, resolveNoteRoots, walkMarkdownFiles } from "./notes/note-walk.ts";
import { tensionPath, tensionsDir } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { BRAIN_HEALTH_DEFAULTS } from "./policy.ts";
import { isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND, type BrainSignalSign } from "./types.ts";
@@ -398,6 +399,8 @@ export function persistTension(
finding: NoteContradictionFinding,
opts: PersistTensionOptions = {},
): PersistTensionResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const { idLow, idHigh, signLow, signHigh, quoteLow, quoteHigh } = canonicalPair(finding);
const slug = tensionSlug(finding);
const dedupKey = tensionDedupKey(finding);
@@ -583,6 +586,11 @@ function transition(
verb: TensionTransition,
opts: TransitionOptions,
): TensionRecord {
+ // Vault-identity write guard (context-integrity-gates, Unit J). The
+ // page rewrite below precedes `appendLogEvent`, so leaning on that
+ // call's guard would land the new status in the wrong store first -
+ // the same defect `persistTension` was fixed for.
+ assertVaultIdentityForWrite(vault);
const prior = parsePage(vault, slug);
if (prior === null) throw new TensionError(`no tension: ${slug}`);
const rule = TRANSITIONS[verb];
diff --git a/src/core/brain/triggers/store.ts b/src/core/brain/triggers/store.ts
index 26e26e38..8f96a94e 100644
--- a/src/core/brain/triggers/store.ts
+++ b/src/core/brain/triggers/store.ts
@@ -28,6 +28,7 @@ import lockfile from "proper-lockfile";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
import { parseFrontmatterText } from "../../vault.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import {
isTriggerKind,
isTriggerStatus,
@@ -242,6 +243,8 @@ export function createTriggers(
candidates: ReadonlyArray<InsightCandidate>,
opts: CreateTriggersOptions,
): CreateTriggersResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
// Serialize the check-then-write against concurrent scans (CLI and
// MCP can both reach this): without the lock two callers could each
// observe "no twin" and persist duplicates for one cooldown key.
@@ -349,6 +352,8 @@ export function transitionTrigger(
action: TriggerAction,
opts: TransitionOptions,
): TriggerRecord {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const record = listTriggers(vault, { now: opts.now }).find((r) => r.id === id);
if (record === undefined) throw new Error(`unknown trigger: ${id}`);
if (!OPEN_STATUSES.has(record.effectiveStatus)) {
@@ -375,6 +380,8 @@ export function markTriggersDelivered(
opts: TransitionOptions,
): void {
if (ids.length === 0) return;
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const wanted = new Set(ids);
const nowIso = opts.now.toISOString();
for (const record of listTriggers(vault, { now: opts.now })) {
diff --git a/src/core/brain/truth/store.ts b/src/core/brain/truth/store.ts
index 0962ed26..676bd0c2 100644
--- a/src/core/brain/truth/store.ts
+++ b/src/core/brain/truth/store.ts
@@ -39,6 +39,7 @@ import type {
TruthState,
} from "./types.ts";
import { TRUTH_SCHEMA_VERSION } from "./types.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
/** Default cap on retained claim events (explicit sweep only). */
export const CLAIM_EVENT_MAX_COUNT = 10000;
@@ -91,6 +92,8 @@ export function appendClaimEvent(
input: AppendClaimInput,
opts: { readonly configPath?: string } = {},
): AppendClaimResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const entity = normalizeEntityName(input.entity);
const aspect = normalizeEntityName(input.aspect);
if (entity === "") throw new Error("claim entity must not be empty");
@@ -264,6 +267,8 @@ function coerceClaim(
}
export function writeTruthState(vault: string, state: TruthState): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
mkdirSync(truthDir(vault), { recursive: true });
writeFileSync(truthStatePath(vault), JSON.stringify(state, null, 2) + "\n");
}
@@ -348,6 +353,8 @@ export interface ClaimSweepOptions {
* history.
*/
export function sweepClaimEvents(vault: string, opts: ClaimSweepOptions): ClaimSweepOutcome {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const maxEvents = opts.maxEvents ?? CLAIM_EVENT_MAX_COUNT;
const dir = truthDir(vault);
let names: string[];
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index a26ffa43..a90011f6 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -11,6 +11,14 @@
* sections 5 (file formats) and 10 (configuration).
*/
+// The one import this module carries, and it is TYPE-ONLY: `GateMode`
+// is owned by the integrity seam that acts on it, so the `_brain.yaml`
+// shape cannot drift from the vocabulary the gate actually understands.
+// `verbatimModuleSyntax` erases this entirely, and `stamp.ts` imports
+// nothing itself, so the "plain-data leaf with no runtime dependency"
+// property this module relies on is unchanged.
+import type { GateMode } from "../integrity/stamp.ts";
+
// ----- Status & retire-reason enums -----------------------------------------
//
// We use `as const` objects with derived union types instead of TypeScript
@@ -768,6 +776,21 @@ export interface BrainRetired {
readonly tags: ReadonlyArray<string>;
readonly topic: string;
readonly scope?: string;
+ /**
+ * Owner token, inherited verbatim from the preference
+ * (context-integrity-gates, A7).
+ *
+ * RETIREMENT KEEPS OWNERSHIP. This is the wave's single answer to
+ * "does retirement strip ownership?", and it is `no`: retiring a
+ * memory withdraws it from the active set, it does not PUBLISH it to
+ * every agent on the vault. `moveToRetired` already copied the field
+ * to disk; the field's absence from this type was what made
+ * `isPreferenceVisible` trivially true for a retired record, so the
+ * recently-retired list, the digest's retired section and
+ * `brain_query` each independently treated retired memories as shared
+ * while the agent-source provider did not.
+ */
+ readonly owner?: string;
readonly principle: string;
readonly evidenced_by: ReadonlyArray<string>;
readonly applied_count: number;
@@ -1414,6 +1437,14 @@ export interface BrainConfig {
* to `BRAIN_HEALTH_DEFAULTS` via `resolveHealth`.
*/
readonly health?: BrainHealthConfig;
+ /**
+ * Optional `integrity:` block (context-integrity-gates). Chooses where
+ * refusal begins for the owner-scoped delivery filter and the
+ * embedding-store ABI check, and bounds how long a context pack stays
+ * valid. Absent: callers fall back to `BRAIN_INTEGRITY_DEFAULTS` via
+ * `resolveIntegrity`, which leaves every existing vault unchanged.
+ */
+ readonly integrity?: BrainIntegrityConfig;
/**
* Optional runtime schema vocabulary declarations. Absent by default;
* consumers resolve built-ins through `resolveSchemaVocabulary`.
@@ -1648,6 +1679,53 @@ export interface ResolvedBrainHealthConfig {
readonly silence_before: string | null;
}
+/**
+ * Optional `integrity:` block (context-integrity-gates). Chooses where
+ * refusal begins for the two gates whose correct strictness the
+ * ENVIRONMENT decides rather than the release, and bounds how long a
+ * context pack stays valid. Absent: callers fall back to
+ * `BRAIN_INTEGRITY_DEFAULTS` via `resolveIntegrity`.
+ *
+ * Every field is an operator knob, so an out-of-range value is a hard
+ * error at load time and never clamps: a gate that silently reverted to
+ * a laxer mode would be the exact silent degradation this block exists
+ * to remove.
+ */
+export interface BrainIntegrityConfig {
+ /**
+ * Where owner-scoped isolation begins on the context-delivery
+ * surfaces. Defaults to `off` because every module on that path
+ * documents a "null scope is byte-identical" contract, so enabling it
+ * by default would silently narrow existing vaults.
+ */
+ readonly owner_scope_delivery?: GateMode;
+ /**
+ * Where the embedding-store ABI/model/dimension check begins on the
+ * read path. Defaults to `warn` because the sqlite-vec version is not
+ * stable across environments: two peers on different builds would each
+ * see a mismatch, and a hard gate could produce a rebuild loop across
+ * a synced vault.
+ */
+ readonly embedding_abi?: GateMode;
+ /**
+ * How long a context pack stays servable after it was built, in
+ * seconds. Positive integer. The provenance stamp is the primary
+ * invalidator; this window is the backstop for changes a stamp cannot
+ * observe.
+ */
+ readonly pack_validity_seconds?: number;
+}
+
+/**
+ * Concrete (fully-resolved) integrity config. Returned by
+ * `resolveIntegrity(cfg)` so consumers do not branch on optionals.
+ */
+export interface ResolvedBrainIntegrityConfig {
+ readonly owner_scope_delivery: GateMode;
+ readonly embedding_abi: GateMode;
+ readonly pack_validity_seconds: number;
+}
+
// ----- Doctor / trust-layer shapes -------------------------------------------
//
// Shared between `doctor.ts` and the `trust/` helpers it calls
diff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.ts
index 5deddac4..4e008fb2 100644
--- a/src/core/brain/upgrade.ts
+++ b/src/core/brain/upgrade.ts
@@ -29,6 +29,7 @@ import { createSnapshot } from "./snapshot.ts";
import { renderBrainManual } from "./templates.ts";
import { isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
// ----- Public types --------------------------------------------------------
@@ -132,6 +133,8 @@ export function applyUpgrade(
vault: string,
opts: { agent?: string; now?: Date } = {},
): UpgradeApplyResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const plan = planUpgrade(vault);
if (plan.errors > 0) {
const messages = plan.files
diff --git a/src/core/brain/vault-identity.ts b/src/core/brain/vault-identity.ts
new file mode 100644
index 00000000..55727f4c
--- /dev/null
+++ b/src/core/brain/vault-identity.ts
@@ -0,0 +1,387 @@
+/**
+ * Unit J - vault identity marker, read, write, and comparison.
+ *
+ * `resolveVault` has five branches and four of them return a path with
+ * ZERO existence validation: the `VAULT_DIR` env var, the active
+ * profile, and the config `vault:` key are taken at face value, and the
+ * pointer branch stats but fails soft. Every Brain write then funnels
+ * through `brainDirs` - a containment check only - into `withTempFile`,
+ * which calls `mkdirSync(dir, {recursive: true})`. The consequence is
+ * that the FIRST WRITE materializes a mis-resolved root: a typo in
+ * `VAULT_DIR` does not fail, it creates a second, empty memory store
+ * that looks exactly like a vault where nothing has been recorded yet.
+ *
+ * This module supplies the identity that makes such a root nameable.
+ *
+ * ## Absent WARNS, present-and-different REFUSES
+ *
+ * The two conditions are not symmetric and must not be treated alike.
+ *
+ * - An ABSENT marker is ambiguous by construction. A fresh directory,
+ * a vault predating markers, and a completely wrong root all look
+ * identical, and refusing would break `o2b brain init` on the very
+ * path it exists to serve. So absence is reported as a
+ * `vault-marker-absent` notice and the write proceeds.
+ * - A marker that is PRESENT and does not match what this process has
+ * already been writing to is unambiguous: the store under this path
+ * is not the store the process started with. That refuses.
+ *
+ * Because the condition is binary, no gate mode is involved. Units whose
+ * condition is genuinely environment-dependent (the embedding ABI, the
+ * owner-scope delivery filter) carry modes; this one does not.
+ *
+ * ## The marker carries NO absolute path
+ *
+ * A vault is Syncthing-shared across devices, so any machine-local
+ * absolute path stored inside it is stale on every peer. A marker
+ * recording where it was written would therefore refuse every write on
+ * the second device - the exact class of defect this repository already
+ * names for index keys. The marker records only an opaque random id, so
+ * it is identical on every peer and survives a `mv` of the vault.
+ *
+ * The comparison is consequently against the identity THIS PROCESS
+ * pinned on its first write, not against an external expectation.
+ *
+ * ## Exactly what the guard can and cannot catch
+ *
+ * Stated precisely, because the previous wording implied more.
+ *
+ * The ONLY condition that raises {@link VaultIdentityMismatchError} is:
+ * a root this process has already written to, whose marker is present
+ * and now holds a DIFFERENT id than the one pinned on that first write.
+ * That is the store changing underneath a live process - a profile
+ * switch, a remount, a restored backup of a different vault.
+ *
+ * Everything else passes, by construction and not by oversight:
+ *
+ * - A COLD-START MIS-RESOLUTION passes. A typo in `VAULT_DIR` yields a
+ * root with no marker, the first write pins nothing, and the write
+ * proceeds. Nothing durable records which vault the process meant,
+ * so there is no expectation to compare against; inventing one from
+ * a machine-local path would refuse every write on a synced peer.
+ * What this case gets instead is a `vault-marker-absent` notice -
+ * see {@link vaultMarkerAbsentNotice}, which the runtime-notice
+ * channel reports on any Brain tree lacking a marker.
+ * - A DELETED marker passes. Absence is indistinguishable from a fresh
+ * vault and refusing would break `o2b brain init`.
+ * - A CORRUPT marker passes, as absence, for the same reason.
+ * - TWO DISTINCT VAULTS in one process both pass. Pins are keyed by
+ * resolved root, deliberately: a CLI or MCP server legitimately
+ * serves more than one vault.
+ *
+ * The mechanism is therefore a same-path, same-process consistency
+ * check plus a standing report on unmarked roots. It is not, and does
+ * not claim to be, proof that the resolved root is the intended one.
+ */
+
+import { randomBytes } from "node:crypto";
+import { existsSync, readFileSync, statSync } from "node:fs";
+import { join, resolve } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { ensureInsideVault } from "../path-safety.ts";
+import {
+ DEGRADATION_CODE,
+ degradationNotice,
+ emitDegradationNotice,
+ formatDegradationNotice,
+ type DegradationNotice,
+} from "../integrity/degradation.ts";
+import { compareStamps, formatStampMismatch, type StampMismatch } from "../integrity/stamp.ts";
+import { BRAIN_ROOT_REL } from "./paths.ts";
+
+/** Marker schema version. Bumped only on an incompatible field change. */
+export const VAULT_IDENTITY_SCHEMA_VERSION = 1;
+
+/** Marker filename inside `Brain/`. */
+export const VAULT_IDENTITY_FILE = "vault-id.json";
+
+/** Site name carried by every notice this module emits. */
+const SITE = "vault-identity";
+
+/** Stamp field name shared by the notice and the mismatch record. */
+const VAULT_ID_FIELD = "vault_id";
+
+/** Bytes of entropy behind a vault id (rendered as 32 hex characters). */
+const VAULT_ID_BYTES = 16;
+
+/**
+ * A vault's durable identity. Deliberately minimal: an opaque id and
+ * when it was minted. Nothing here is machine-local, so the record is
+ * byte-identical on every synced peer.
+ */
+export interface VaultIdentity {
+ readonly schema_version: number;
+ readonly vault_id: string;
+ readonly created_at: string;
+}
+
+/** Path of the identity marker: `<vault>/Brain/vault-id.json`. */
+export function vaultIdentityPath(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_ROOT_REL, VAULT_IDENTITY_FILE), vault);
+}
+
+/**
+ * Read the marker, or `null` when there is none.
+ *
+ * An unreadable or malformed marker also reads as `null` - that is, as
+ * ABSENT rather than as a mismatch. Treating corruption as a mismatch
+ * would refuse writes on a truncated sync, which is the failure mode a
+ * warn-on-absence design exists to avoid.
+ */
+export function readVaultIdentity(vault: string): VaultIdentity | null {
+ const path = vaultIdentityPath(vault);
+ if (!existsSync(path)) return null;
+ try {
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as Partial<VaultIdentity>;
+ if (typeof parsed.vault_id !== "string" || parsed.vault_id.length === 0) return null;
+ return Object.freeze({
+ schema_version:
+ typeof parsed.schema_version === "number"
+ ? parsed.schema_version
+ : VAULT_IDENTITY_SCHEMA_VERSION,
+ vault_id: parsed.vault_id,
+ created_at: typeof parsed.created_at === "string" ? parsed.created_at : "",
+ });
+ } catch {
+ return null;
+ }
+}
+
+export interface WriteVaultIdentityOptions {
+ /** Clock for `created_at`; injected so a test can pin the stamp. */
+ readonly now?: Date;
+}
+
+/**
+ * Stamp the marker, or return the one already there.
+ *
+ * IDEMPOTENT BY CONTRACT. Re-running the bootstrap path must never mint
+ * a new id: the id is what makes a synced peer's vault recognisable as
+ * the same store, and rotating it on every `o2b brain init` would make
+ * the identity meaningless.
+ */
+export function writeVaultIdentity(
+ vault: string,
+ opts: WriteVaultIdentityOptions = {},
+): VaultIdentity {
+ const existing = readVaultIdentity(vault);
+ if (existing !== null) return existing;
+ const identity: VaultIdentity = Object.freeze({
+ schema_version: VAULT_IDENTITY_SCHEMA_VERSION,
+ vault_id: randomBytes(VAULT_ID_BYTES).toString("hex"),
+ created_at: (opts.now ?? new Date()).toISOString(),
+ });
+ atomicWriteFileSync(vaultIdentityPath(vault), `${JSON.stringify(identity, null, 2)}\n`);
+ return identity;
+}
+
+/**
+ * A write was attempted against a root whose recorded identity is not
+ * the one this process has been writing to. Carries the structured
+ * notice and the stamp mismatch behind the message so a caller can
+ * report the evidence rather than re-parse the string.
+ */
+export class VaultIdentityMismatchError extends Error {
+ readonly notice: DegradationNotice;
+ readonly mismatch: StampMismatch;
+
+ constructor(notice: DegradationNotice, mismatch: StampMismatch) {
+ super(formatDegradationNotice(notice));
+ this.name = "VaultIdentityMismatchError";
+ this.notice = notice;
+ this.mismatch = mismatch;
+ }
+}
+
+/**
+ * Identity this process pinned per resolved root, on its first write.
+ *
+ * Module state is the right scope: the question the guard answers is
+ * "is this still the store I have been writing to?", which is a
+ * property of the running process and of nothing durable. Keying by the
+ * resolved path keeps two roots in one process independent.
+ */
+const PINNED_IDENTITIES = new Map<string, string>();
+
+/**
+ * Inode identity of the marker file the last assertion parsed, per
+ * resolved root.
+ *
+ * The guard sits on EVERY write, including append-heavy telemetry loops
+ * that record tens of thousands of rows in one run, so the per-call cost
+ * has to be one syscall rather than an open-read-parse. `writeVaultIdentity`
+ * goes through `atomicWriteFileSync` - a temp file plus a rename - so a
+ * replaced marker always arrives with a new inode. Matching on
+ * (inode, size, mtime) therefore proves the bytes are the ones already
+ * parsed; anything else falls through to a full re-read.
+ */
+interface MarkerStamp {
+ readonly ino: number;
+ readonly size: number;
+ readonly mtimeMs: number;
+ readonly vaultId: string;
+}
+const MARKER_STAMPS = new Map<string, MarkerStamp>();
+
+/** Resolved marker path per root; see {@link currentVaultId}. */
+const MARKER_PATHS = new Map<string, string>();
+
+/**
+ * Drop every pin. Exported for tests, which run many vaults in one
+ * process; production code has no reason to call it.
+ */
+export function resetVaultIdentityPins(): void {
+ PINNED_IDENTITIES.clear();
+ MARKER_STAMPS.clear();
+ MARKER_PATHS.clear();
+}
+
+/**
+ * The marker's `vault_id`, re-read only when the file on disk is not
+ * byte-for-byte the one the last call parsed. `null` for absent,
+ * unreadable, or malformed - the same collapse {@link readVaultIdentity}
+ * performs, for the same reason.
+ */
+function currentVaultId(root: string): string | null {
+ // `vaultIdentityPath` runs the full containment check (lexical plus a
+ // realpath walk of the deepest existing ancestor). That is the right
+ // price once per root and the wrong price once per appended row, so
+ // the resolved path is memoized alongside the marker stamp.
+ let path = MARKER_PATHS.get(root);
+ if (path === undefined) {
+ path = vaultIdentityPath(root);
+ MARKER_PATHS.set(root, path);
+ }
+ // `throwIfNoEntry: false` matters for cost, not for semantics. An
+ // ABSENT marker is the steady state of every unmarked root, and this
+ // function runs once per written row - so the throwing form built and
+ // discarded one Error, with its stack, per append. Measured over 20k
+ // guarded writes (median of 5): 159ms -> 76ms on an unmarked root,
+ // unchanged on a marked one, where the stat simply succeeds and
+ // nothing ever threw.
+ //
+ // The `catch` stays. The option suppresses ENOENT only, and every
+ // other stat failure (EACCES, ELOOP) must still collapse to "absent"
+ // exactly as before, rather than propagate out of a write guard.
+ let stat;
+ try {
+ stat = statSync(path, { throwIfNoEntry: false });
+ } catch {
+ stat = undefined;
+ }
+ if (stat === undefined) {
+ MARKER_STAMPS.delete(root);
+ return null;
+ }
+ const cached = MARKER_STAMPS.get(root);
+ if (
+ cached !== undefined &&
+ cached.ino === stat.ino &&
+ cached.size === stat.size &&
+ cached.mtimeMs === stat.mtimeMs
+ ) {
+ return cached.vaultId;
+ }
+ const identity = readVaultIdentity(root);
+ if (identity === null) {
+ MARKER_STAMPS.delete(root);
+ return null;
+ }
+ MARKER_STAMPS.set(root, {
+ ino: stat.ino,
+ size: stat.size,
+ mtimeMs: stat.mtimeMs,
+ vaultId: identity.vault_id,
+ });
+ return identity.vault_id;
+}
+
+/**
+ * The `vault-marker-absent` notice for `vault`, or `null` when the
+ * resolved root carries a readable marker.
+ *
+ * This is the READ-SIDE half of the unit, and the only place the absent
+ * branch is described. Two callers exist and they need the same record
+ * for different reasons: {@link assertVaultIdentityForWrite} emits it
+ * into a write-path sink, and the diagnostic surfaces report it as a
+ * standing condition of the root.
+ *
+ * A corrupt or unparseable marker reads as ABSENT here, exactly as it
+ * does in {@link readVaultIdentity}: the two cannot be distinguished
+ * without guessing, and guessing wrong turns a truncated sync into a
+ * refusal.
+ */
+export function vaultMarkerAbsentNotice(vault: string): DegradationNotice | null {
+ const root = resolve(vault);
+ if (currentVaultId(root) !== null) return null;
+ return degradationNotice({
+ code: DEGRADATION_CODE.vaultMarkerAbsent,
+ site: SITE,
+ path: root,
+ detail:
+ "resolved vault root carries no identity marker; " +
+ "run `o2b brain init` on this root if it is the intended vault",
+ });
+}
+
+/**
+ * Assert that a write may proceed against `vault`.
+ *
+ * Emits a `vault-marker-absent` notice into `sink` (when one is given)
+ * for an unmarked root and returns; throws
+ * {@link VaultIdentityMismatchError} when the root's marker differs from
+ * the one this process pinned. Never throws for an absent, unreadable,
+ * or malformed marker.
+ *
+ * ## Two call surfaces, one assertion
+ *
+ * Brain writers reach the vault tree two ways, and both funnel here.
+ *
+ * - Writers that resolve a whole directory set call
+ * `brainDirsForWrite`, which is a thin wrapper over this function.
+ * - Writers that build a single path with one of the `paths.ts`
+ * builders (`preferencePath`, `entityPath`, `decisionPath`, …) call
+ * this function DIRECTLY, at their own entry point.
+ *
+ * The second surface exists because the builders are intent-neutral by
+ * construction: `preferencePath` serves `parsePreference` and
+ * `writePreference` alike, so asserting inside the builder would refuse
+ * reads. The assertion therefore belongs to the writer, and it belongs
+ * BEFORE the writer's first byte - a refusal that arrives after the page
+ * is on disk has already materialized the wrong store.
+ */
+export function assertVaultIdentityForWrite(vault: string, sink?: DegradationNotice[]): void {
+ const root = resolve(vault);
+ const vaultId = currentVaultId(root);
+ if (vaultId === null) {
+ if (sink !== undefined) {
+ const absent = vaultMarkerAbsentNotice(root);
+ // `currentVaultId` just reported no readable marker, so the notice
+ // is non-null; the check keeps the types honest rather than casting.
+ if (absent !== null) emitDegradationNotice(sink, absent);
+ }
+ return;
+ }
+
+ const pinned = PINNED_IDENTITIES.get(root);
+ if (pinned === undefined) {
+ PINNED_IDENTITIES.set(root, vaultId);
+ return;
+ }
+ if (pinned === vaultId) return;
+
+ const mismatch = compareStamps({ [VAULT_ID_FIELD]: pinned }, { [VAULT_ID_FIELD]: vaultId })[0];
+ // compareStamps reports every differing field and the two ids differ,
+ // so exactly one mismatch is guaranteed here.
+ const evidence = mismatch as StampMismatch;
+ throw new VaultIdentityMismatchError(
+ degradationNotice({
+ code: DEGRADATION_CODE.vaultMarkerMismatch,
+ site: SITE,
+ path: root,
+ detail: `refusing to write: the store at this root is not the one this process opened (${formatStampMismatch(evidence)})`,
+ }),
+ evidence,
+ );
+}
diff --git a/src/core/brain/watchdog.ts b/src/core/brain/watchdog.ts
index 3437d82b..440ccc25 100644
--- a/src/core/brain/watchdog.ts
+++ b/src/core/brain/watchdog.ts
@@ -13,6 +13,7 @@ import {
BRAIN_RETIRED_REL,
brainConfigPath,
brainDirs,
+ brainDirsForWrite,
} from "./paths.ts";
export interface WatchdogOptions {
@@ -72,7 +73,10 @@ export function runBrainWatchdog(vault: string, opts: WatchdogOptions = {}): Bra
const checks: ProbeCheck[] = [];
const remediationPlan: WatchdogRemediation[] = [];
const applied: WatchdogRemediation[] = [];
- const dirs = brainDirs(vault);
+ // Write-intent unconditionally (context-integrity-gates, Unit J): a
+ // remediating run creates or replaces the directories below, and EVERY
+ // run - probe included - appends its audit record into `dirs.log`.
+ const dirs = brainDirsForWrite(vault);
const configPath = brainConfigPath(vault);
const configKind = pathKind(configPath);
diff --git a/src/core/brain/write-batch.ts b/src/core/brain/write-batch.ts
index 929a2f2b..99418414 100644
--- a/src/core/brain/write-batch.ts
+++ b/src/core/brain/write-batch.ts
@@ -40,6 +40,7 @@ import {
} from "./apply-evidence.ts";
import { appendBrainNote, type AppendBrainNoteInput } from "./note.ts";
import { preferencePath, validateSlug } from "./paths.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
import { BRAIN_APPLY_RESULT } from "./types.ts";
/** Separator inserted between the existing body and appended text. */
@@ -182,6 +183,8 @@ export function applyWriteBatch(
vault: string,
operations: ReadonlyArray<WriteOperation>,
): WriteBatchResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
if (!Array.isArray(operations) || operations.length === 0) {
throw new WriteBatchError("invalid_operation", -1, "operations must be a non-empty array");
}
diff --git a/src/core/brain/write-session/engine.ts b/src/core/brain/write-session/engine.ts
index 5196ecdd..03c5738a 100644
--- a/src/core/brain/write-session/engine.ts
+++ b/src/core/brain/write-session/engine.ts
@@ -45,6 +45,7 @@ import {
type WriteSessionIntent,
type WriteSessionRecord,
} from "./types.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
export const DEFAULT_RETRY_CAP = 3;
export const DEFAULT_TTL_MS = 24 * 3600 * 1000;
@@ -338,6 +339,9 @@ export function commitArtifact(
artifact: string,
now: string,
): WriteSessionEnvelope {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+
// Last-line-of-defense containment: `validateTargetPath` runs at open
// time and is purely lexical (it rejects `..`/backslashes/NUL but is
// blind to symlinked ancestors), and the persisted session record is
diff --git a/src/core/brain/write-session/store.ts b/src/core/brain/write-session/store.ts
index 45034536..70eab083 100644
--- a/src/core/brain/write-session/store.ts
+++ b/src/core/brain/write-session/store.ts
@@ -20,6 +20,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:f
import { join } from "node:path";
import { atomicCreateFileSyncExclusive, atomicWriteFileSync } from "../../fs-atomic.ts";
+import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import {
isTerminalWriteSessionStatus,
type WriteSessionError,
@@ -229,6 +230,8 @@ function applyTtl(record: WriteSessionRecord, nowIso: string): WriteSessionRecor
/** Persist a session record atomically (updates an EXISTING session). */
export function saveWriteSession(vault: string, record: WriteSessionRecord): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
mkdirSync(writeSessionDir(vault), { recursive: true });
atomicWriteFileSync(writeSessionPath(vault, record.id), serializeRecord(record));
}
@@ -245,6 +248,8 @@ export function createWriteSession(
nowIso: string,
build: (id: string) => WriteSessionRecord,
): WriteSessionRecord {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
mkdirSync(writeSessionDir(vault), { recursive: true });
for (let attempt = 0; attempt < 10_000; attempt++) {
const id = allocateWriteSessionId(vault, nowIso);
@@ -320,6 +325,8 @@ export function listWriteSessions(
/** Remove one session file (idempotent). */
export function deleteWriteSession(vault: string, id: string): void {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
rmSync(writeSessionPath(vault, id), { force: true });
}
@@ -333,6 +340,8 @@ export interface SweepWriteSessionsResult {
* files are also removed - they can never transition anywhere.
*/
export function sweepWriteSessions(vault: string, nowIso: string): SweepWriteSessionsResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
const dir = writeSessionDir(vault);
if (!existsSync(dir)) return Object.freeze({ removed: 0, kept: 0 });
let removed = 0;
diff --git a/src/core/graph/agent-scope.ts b/src/core/graph/agent-scope.ts
index e1286d23..495d4fc6 100644
--- a/src/core/graph/agent-scope.ts
+++ b/src/core/graph/agent-scope.ts
@@ -9,6 +9,9 @@
* behaviour change for vaults that never set the field).
* - A page that declares an owner is owner-private: reachable only when
* the caller requests that owner's scope.
+ * - A page that declares an owner this parser cannot resolve to one
+ * token is treated as SOMEBODY ELSE'S ({@link OWNER_UNRESOLVED}),
+ * never as shared. An unreadable ownership claim is still a claim.
* - When no scope is requested (the default), NO ownership filtering
* happens at all - every page is reachable, so a recall that opts
* into nothing is byte-identical to today.
@@ -28,15 +31,57 @@ function normToken(raw: string): string {
return raw.normalize("NFC").trim().toLowerCase();
}
+/**
+ * The owner of a page that CLAIMS ownership in a shape this vault cannot
+ * resolve to a single token.
+ *
+ * The shapes are routine rather than exotic: Obsidian Properties writes
+ * any list-shaped field as a YAML block sequence, and `parseFrontmatterText`
+ * parses both block and inline sequences into arrays; a nested mapping
+ * under `owner:` leaves the key with an empty value and hoists the child
+ * keys. Reading any of those as "no owner" would publish an owner-private
+ * page to every scope - the exact inversion of an isolation boundary - so
+ * they resolve to this token instead, which no requested scope can ever
+ * equal and which therefore reads as "somebody else's".
+ *
+ * Unreachable by construction: {@link normalizeAgentScope} lower-cases
+ * every requested scope, so no caller can request a scope containing an
+ * upper-case letter. A page that literally declares
+ * `owner: OWNER_UNRESOLVED` is therefore hidden from every scope, which
+ * is the fail-closed direction.
+ */
+export const OWNER_UNRESOLVED = "OWNER_UNRESOLVED";
+
+/**
+ * Resolve any raw `owner` value - a frontmatter field, a parsed record's
+ * `owner` slot - to the token the visibility rule compares.
+ *
+ * - absent (`undefined` / `null`): SHARED, returns `null`.
+ * - a usable string: its normalized token.
+ * - present but unusable (empty/blank string, array, object, number):
+ * {@link OWNER_UNRESOLVED}.
+ *
+ * Idempotent: feeding {@link OWNER_UNRESOLVED} back in returns it
+ * unchanged, so a record that already carries the token (a preference
+ * parsed from a list-shaped `owner:`) resolves the same way as the page
+ * it came from.
+ */
+export function ownerToken(raw: unknown): string | null {
+ if (raw === undefined || raw === null) return null;
+ if (raw === OWNER_UNRESOLVED) return OWNER_UNRESOLVED;
+ if (typeof raw !== "string") return OWNER_UNRESOLVED;
+ const token = normToken(raw);
+ return token.length > 0 ? token : OWNER_UNRESOLVED;
+}
+
/**
* The owner a page declares, or `null` for a shared (ownerless) page.
- * A non-string `owner:` value is treated as absent.
+ * A present-but-unresolvable `owner:` yields {@link OWNER_UNRESOLVED} β€”
+ * never `null`, because an ownership claim that cannot be read is not
+ * an absence of one.
*/
export function pageOwner(meta: FrontmatterMap): string | null {
- const raw = meta["owner"];
- if (typeof raw !== "string") return null;
- const token = normToken(raw);
- return token.length > 0 ? token : null;
+ return ownerToken(meta["owner"]);
}
/**
diff --git a/src/core/integrity/degradation.ts b/src/core/integrity/degradation.ts
new file mode 100644
index 00000000..bcac8388
--- /dev/null
+++ b/src/core/integrity/degradation.ts
@@ -0,0 +1,221 @@
+/**
+ * Seam 1 - the typed degradation notice channel.
+ *
+ * Across the read and delivery path this repository swallows failures in
+ * bare `catch { continue }` arms and drops frontmatter lines the scanner
+ * does not understand. The information is not merely unlogged: the agent
+ * cannot tell a genuine miss from a broken mechanism. This module is the
+ * one place those sites report to. It records WHAT degraded (`code`),
+ * WHERE (`site`), on which artifact (`path`, when one is known), and the
+ * concrete observation (`detail`).
+ *
+ * The channel carries diagnostics only. It never changes control flow: a
+ * fail-soft caller emits a notice and continues exactly as before, so
+ * conversion of a swallowing call site is behaviour-preserving and only
+ * the trace is new.
+ *
+ * ## The code vocabulary is CLOSED by design
+ *
+ * `DegradationCode` is a union over a frozen table, not a free string.
+ * The failure mode a typed diagnostic channel invites is becoming a
+ * dumping ground - every call site inventing its own token until the
+ * vocabulary is unreviewable and no consumer can switch on it. Two
+ * properties prevent that here:
+ *
+ * 1. Adding a code is a deliberate edit of this file, reviewed against
+ * the unit that needs it. A caller cannot mint one in passing.
+ * 2. A consumer switching over `DegradationCode` with a `never`-typed
+ * `default` arm gets a COMPILE error for an unhandled member, so a
+ * new code cannot silently fall through an existing renderer.
+ *
+ * Every member below is therefore annotated with the unit that owns it.
+ * The seeded set covers exactly the units whose plan entries declare a
+ * dependency on this seam (F, C, D, J). Units whose gate is a stamp
+ * comparison rather than a swallowed failure (B, E) report through
+ * `stamp.ts` instead and add nothing here.
+ *
+ * Nothing in this module inspects natural language. `detail` is operator
+ * -supplied text passed through verbatim; the formatter templates it and
+ * normalizes whitespace, and that is the whole of its processing.
+ */
+
+/**
+ * Closed vocabulary of degradation conditions. Keys are camelCase for
+ * call sites; values are the kebab-case tokens that appear in reports,
+ * receipts, and MCP payloads.
+ */
+export const DEGRADATION_CODE = Object.freeze({
+ /**
+ * Unit F. The frontmatter scanner reached a line it cannot express as
+ * a `key: value` pair (or a block-style list continuation) and dropped
+ * it. Today this is structurally silent: the field simply never
+ * reaches the parsed map.
+ */
+ frontmatterLineDropped: "frontmatter-line-dropped",
+ /**
+ * Unit F. A note's frontmatter could not be obtained at all because
+ * the read failed. This is the condition behind the bare
+ * `catch { continue }` arms on every frontmatter-reading walker.
+ */
+ frontmatterUnreadable: "frontmatter-unreadable",
+ /**
+ * Unit F. A vault walk could not descend into or stat an entry, so a
+ * subtree is missing from the result. Distinct from
+ * `frontmatterUnreadable`: nothing was parsed, an entire branch was
+ * skipped.
+ */
+ vaultWalkEntrySkipped: "vault-walk-entry-skipped",
+ /**
+ * Unit C. Session continuation declined to link rather than guessing -
+ * no candidate, an ambiguous set, or missing evidence. The abstention
+ * is the correct outcome; the notice is what makes it visible instead
+ * of indistinguishable from "nothing to link".
+ */
+ sessionLinkAbstained: "session-link-abstained",
+ /**
+ * Unit D. A lineage observation was not appended (writer-lock
+ * contention or a failed read-modify-write) and is recorded as a named
+ * gap rather than vanishing.
+ */
+ lineageObservationDropped: "lineage-observation-dropped",
+ /**
+ * Unit D. Ledger verification found a sequence gap or a hash-chain
+ * break. Reported, never fatal: the read path stays fail-soft.
+ */
+ lineageChainBroken: "lineage-chain-broken",
+ /**
+ * Unit J. The resolved vault root carries no identity marker. An
+ * absent marker cannot distinguish an old vault from a wrong root, so
+ * this warns rather than refusing.
+ */
+ vaultMarkerAbsent: "vault-marker-absent",
+ /**
+ * Unit J. The resolved vault root carries a marker that does not match
+ * the expected identity. Unambiguous, and therefore a refusal at the
+ * write path rather than a warning.
+ */
+ vaultMarkerMismatch: "vault-marker-mismatch",
+} as const);
+
+/**
+ * The closed union. A consumer that switches over this type with a
+ * `never`-typed `default` arm fails to compile when a member is added
+ * without a corresponding arm - which is the point of the closure.
+ */
+export type DegradationCode = (typeof DEGRADATION_CODE)[keyof typeof DEGRADATION_CODE];
+
+/**
+ * One named degradation. `path` is present only when the condition is
+ * attributable to a concrete file or directory; the key is OMITTED (not
+ * set to `undefined`) when it is not, so a serialized notice from a
+ * path-less site carries no empty field.
+ */
+export interface DegradationNotice {
+ /** What degraded, from the closed vocabulary. */
+ readonly code: DegradationCode;
+ /** Where it was observed - a function, verb, or subsystem name. */
+ readonly site: string;
+ /** The artifact it happened to, when one is known. */
+ readonly path?: string;
+ /** The concrete observation, in English, passed through verbatim. */
+ readonly detail: string;
+}
+
+/** Construction input for {@link degradationNotice}. */
+export interface DegradationNoticeInput {
+ readonly code: DegradationCode;
+ readonly site: string;
+ readonly path?: string;
+ readonly detail: string;
+}
+
+/**
+ * A notice was constructed that could not name its own condition. This
+ * throws rather than returning a placeholder record: a diagnostic
+ * channel that emits blank diagnostics reproduces exactly the silent
+ * failure it exists to remove.
+ */
+export class DegradationNoticeError extends Error {
+ /** The offending field (`site`, `detail`, or `path`). */
+ readonly field: string;
+
+ constructor(field: string, message: string) {
+ super(`degradation notice: ${field}: ${message}`);
+ this.name = "DegradationNoticeError";
+ this.field = field;
+ }
+}
+
+/** Runs of any whitespace, including the newlines a single line cannot carry. */
+const WHITESPACE_RUN_RE = /\s+/g;
+
+/** Rendered in place of a path only when one is known - see `formatDegradationNotice`. */
+const PATH_OPEN = " (";
+const PATH_CLOSE = ")";
+
+function requireNonBlank(field: string, value: string): string {
+ if (value.trim().length === 0) {
+ throw new DegradationNoticeError(field, "must be a non-blank string");
+ }
+ return value;
+}
+
+/**
+ * Build one frozen {@link DegradationNotice}, rejecting an input that
+ * cannot name its condition. Use this at sites that RETURN a notice;
+ * sites that accumulate into a collector should use
+ * {@link emitDegradationNotice}.
+ */
+export function degradationNotice(input: DegradationNoticeInput): DegradationNotice {
+ const site = requireNonBlank("site", input.site);
+ const detail = requireNonBlank("detail", input.detail);
+ // `path` is optional, so absence is legal - but a present-and-blank
+ // path is a caller bug that would render as an empty `()` suffix.
+ const path = input.path === undefined ? undefined : requireNonBlank("path", input.path);
+ return Object.freeze({
+ code: input.code,
+ site,
+ ...(path !== undefined ? { path } : {}),
+ detail,
+ });
+}
+
+/**
+ * Build a notice and append it to `sink`, returning the same record.
+ * This is the emit form used by the report types that already exist
+ * (`IndexStats`, the doctor's `uncertain` list, MCP response fields):
+ * the caller keeps one array and never repeats the push.
+ *
+ * A malformed input throws before anything is appended, so a sink never
+ * holds a notice that cannot name its condition.
+ */
+export function emitDegradationNotice(
+ sink: DegradationNotice[],
+ input: DegradationNoticeInput,
+): DegradationNotice {
+ const notice = degradationNotice(input);
+ sink.push(notice);
+ return notice;
+}
+
+/**
+ * Render a notice as exactly ONE English line:
+ *
+ * `<code> at <site>: <detail>`
+ * `<code> at <site> (<path>): <detail>`
+ *
+ * Whitespace runs inside `site`, `path`, and `detail` collapse to single
+ * spaces so a multi-line error message cannot break the one-line
+ * contract that log, receipt, and doctor renderers depend on.
+ */
+export function formatDegradationNotice(notice: DegradationNotice): string {
+ const site = collapse(notice.site);
+ const detail = collapse(notice.detail);
+ const where =
+ notice.path === undefined ? "" : `${PATH_OPEN}${collapse(notice.path)}${PATH_CLOSE}`;
+ return `${notice.code} at ${site}${where}: ${detail}`;
+}
+
+function collapse(value: string): string {
+ return value.replace(WHITESPACE_RUN_RE, " ").trim();
+}
diff --git a/src/core/integrity/stamp.ts b/src/core/integrity/stamp.ts
new file mode 100644
index 00000000..20b4ca3d
--- /dev/null
+++ b/src/core/integrity/stamp.ts
@@ -0,0 +1,208 @@
+/**
+ * Seam 2 - "record what you were derived from, verify on read".
+ *
+ * Three units of the context-integrity-gates wave need the same
+ * mechanism and would otherwise each invent it: a context pack must
+ * verify the vault state it was built from (B), an embedding store must
+ * verify the model, dimension, and sqlite-vec ABI it was written against
+ * (E), and a vault root must verify the identity marker it was
+ * bootstrapped with (J).
+ *
+ * The mechanism is: a caller records a map of opaque string tokens at
+ * write time, presents the live tokens at read time, and this module
+ * reports which fields drifted. It is deliberately DOMAIN-AGNOSTIC -
+ * every field name is supplied by the caller, so nothing here mentions a
+ * generation counter, an embedding dimension, or a vault id. A token is
+ * an opaque string; this module never parses, orders, or interprets one,
+ * and never inspects natural language.
+ *
+ * ## `null` means "not recorded"
+ *
+ * A token map is `Record<string, string | null>`. An absent key and an
+ * explicit `null` are the SAME condition - the side did not record that
+ * field - so a legacy artifact written before a field existed compares
+ * as unrecorded rather than as a spurious drift against the empty
+ * string. Two unrecorded sides are not a finding. An empty string, by
+ * contrast, IS a recorded value and is distinct from `null`.
+ *
+ * ## The gate decides where refusal begins, and `off` really is off
+ *
+ * {@link compareStamps} is the pure comparison and always reports what
+ * it finds. {@link checkStamp} is the gated form: under
+ * {@link GATE_MODE.off} it does not compare at all and returns no
+ * evidence, so a caller wired to the gate structurally CANNOT emit a new
+ * field, warning, or refusal while the gate is off. That is what makes
+ * the byte-identical-when-absent contract mechanical rather than a
+ * discipline every consumer has to re-implement. A caller that wants a
+ * diagnostic irrespective of the operator's gate calls
+ * {@link compareStamps} directly and says so.
+ */
+
+/**
+ * The three-mode gate. `off` disables the check, `warn` reports drift
+ * without refusing, `fail` refuses. Closed by design: every additional
+ * mode multiplies the consuming test matrix, and units whose condition
+ * is unambiguous are expected to stay binary rather than grow a fourth.
+ */
+export const GATE_MODE = Object.freeze({
+ off: "off",
+ warn: "warn",
+ fail: "fail",
+} as const);
+
+/**
+ * Gate-mode union. A consumer switching over it with a `never`-typed
+ * `default` arm fails to compile if a mode is ever added.
+ */
+export type GateMode = (typeof GATE_MODE)[keyof typeof GATE_MODE];
+
+/**
+ * The modes in increasing order of strictness. Ordered (not a `Set`) so
+ * config-error messages list them the same way every time.
+ */
+export const GATE_MODES: ReadonlyArray<GateMode> = Object.freeze([
+ GATE_MODE.off,
+ GATE_MODE.warn,
+ GATE_MODE.fail,
+]);
+
+/** Narrow an unvalidated config or argument value to a {@link GateMode}. */
+export function isGateMode(value: unknown): value is GateMode {
+ return typeof value === "string" && (GATE_MODES as ReadonlyArray<string>).includes(value);
+}
+
+/**
+ * The tokens one side of a comparison recorded. Keys are caller-owned
+ * field names; values are opaque strings, or `null` for "this side did
+ * not record that field".
+ */
+export type StampTokens = Readonly<Record<string, string | null>>;
+
+/** One field whose recorded token no longer matches the live one. */
+export interface StampMismatch {
+ /** The caller-supplied field name that drifted. */
+ readonly field: string;
+ /** What was recorded when the artifact was derived. */
+ readonly expected: string | null;
+ /** What is live now. */
+ readonly actual: string | null;
+}
+
+/** Outcome of a gated comparison. */
+export const STAMP_VERDICT = Object.freeze({
+ /** Nothing to report: the stamps matched, or the gate is off. */
+ pass: "pass",
+ /** Drift found; the gate reports it and the caller proceeds. */
+ warn: "warn",
+ /** Drift found; the gate refuses. */
+ fail: "fail",
+} as const);
+
+export type StampVerdict = (typeof STAMP_VERDICT)[keyof typeof STAMP_VERDICT];
+
+/** Result of {@link checkStamp}: the verdict plus the evidence behind it. */
+export interface StampCheck {
+ /** The mode the check ran under, echoed so a report can name it. */
+ readonly mode: GateMode;
+ readonly verdict: StampVerdict;
+ /** Empty whenever the verdict is `pass` - including under `off`. */
+ readonly mismatches: ReadonlyArray<StampMismatch>;
+}
+
+/** Rendered for a side that recorded nothing, so a gap is never blank. */
+const UNRECORDED_TOKEN = "<unrecorded>";
+
+/** Runs of any whitespace; collapsed so a rendered mismatch is one line. */
+const WHITESPACE_RUN_RE = /\s+/g;
+
+/** An absent key and an explicit `null` are the same condition. */
+function tokenOf(tokens: StampTokens, field: string): string | null {
+ const value = tokens[field];
+ return value === undefined ? null : value;
+}
+
+/**
+ * Compare two token maps and report every field that drifted.
+ *
+ * The compared field set is the union of both maps' keys, sorted by code
+ * unit so the result is byte-identical across runs, engines, and locales
+ * regardless of the order the caller built either map in.
+ *
+ * This is the ungated form: it always compares and always reports.
+ */
+export function compareStamps(
+ expected: StampTokens,
+ actual: StampTokens,
+): ReadonlyArray<StampMismatch> {
+ const fields = [...new Set([...Object.keys(expected), ...Object.keys(actual)])].toSorted();
+ const mismatches: StampMismatch[] = [];
+ for (const field of fields) {
+ const before = tokenOf(expected, field);
+ const now = tokenOf(actual, field);
+ if (before === now) continue;
+ mismatches.push(Object.freeze({ field, expected: before, actual: now }));
+ }
+ return Object.freeze(mismatches);
+}
+
+/**
+ * Compare under an operator-chosen gate.
+ *
+ * Under {@link GATE_MODE.off} no comparison is performed and no evidence
+ * is returned, so a gated caller emits nothing at all - see the module
+ * docblock. Otherwise the drift is reported and the mode decides whether
+ * the verdict is a warning or a refusal; the caller owns what it does
+ * with each.
+ *
+ * A mode outside the closed vocabulary THROWS. The types stop most of
+ * them, but a value crossing a `JSON.parse` or an `as` cast does not
+ * meet the compiler, and the previous `mode === fail ? fail : warn`
+ * shape resolved every such value to the SOFTEST verdict - an
+ * unrecognised token silently becoming a warning is indistinguishable
+ * from an operator who asked for one.
+ */
+export function checkStamp(expected: StampTokens, actual: StampTokens, mode: GateMode): StampCheck {
+ if (!isGateMode(mode)) {
+ throw new Error(
+ `unknown gate mode ${JSON.stringify(mode)}; expected one of ${GATE_MODES.join(", ")}`,
+ );
+ }
+ if (mode === GATE_MODE.off) {
+ return Object.freeze({
+ mode,
+ verdict: STAMP_VERDICT.pass,
+ mismatches: Object.freeze([]) as ReadonlyArray<StampMismatch>,
+ });
+ }
+ const mismatches = compareStamps(expected, actual);
+ const verdict =
+ mismatches.length === 0
+ ? STAMP_VERDICT.pass
+ : mode === GATE_MODE.fail
+ ? STAMP_VERDICT.fail
+ : STAMP_VERDICT.warn;
+ return Object.freeze({ mode, verdict, mismatches });
+}
+
+/**
+ * Render one mismatch as a single English line:
+ *
+ * `<field>: expected "<recorded>", actual <unrecorded>`
+ *
+ * Values are quoted so an empty recorded value is visible, and an
+ * unrecorded side is named explicitly rather than rendered as a gap.
+ * Shared by every consuming unit so three gates cannot grow three
+ * spellings of the same refusal.
+ */
+export function formatStampMismatch(mismatch: StampMismatch): string {
+ const field = collapse(mismatch.field);
+ return `${field}: expected ${renderToken(mismatch.expected)}, actual ${renderToken(mismatch.actual)}`;
+}
+
+function renderToken(value: string | null): string {
+ return value === null ? UNRECORDED_TOKEN : JSON.stringify(collapse(value));
+}
+
+function collapse(value: string): string {
+ return value.replace(WHITESPACE_RUN_RE, " ").trim();
+}
diff --git a/src/core/search/cards.ts b/src/core/search/cards.ts
index 9d0692f0..0c21ca36 100644
--- a/src/core/search/cards.ts
+++ b/src/core/search/cards.ts
@@ -4,7 +4,9 @@
* into its fuller note (layer 2) and paginated raw chunks (layer 3).
*/
+import { normalizeAgentScope } from "../graph/agent-scope.ts";
import { formatLinePointer } from "./line-numbering.ts";
+import { isPathOwnerVisible } from "./result-filters.ts";
import { Store } from "./store.ts";
import { SearchError } from "./types.ts";
import type {
@@ -63,6 +65,21 @@ export function cardSnippet(content: string): string {
* self-heals β€” a card can only exist because a prior search built the
* index, and a rebuild would WRITE it. The layer-2/3 data is pure store
* reads (`hydrateChunks` + `getChunksByDocument`), never a new index.
+ *
+ * ## Ownership (context-integrity-gates, Unit A)
+ *
+ * `chunkId` is a SEQUENTIAL INTEGER, so without a check this is an
+ * enumeration surface for whole note bodies: walking the integers
+ * returns every document in the vault, ranking and query filters
+ * bypassed entirely. Under an `agentScope` the resolved path's owner is
+ * checked with the same {@link isPathOwnerVisible} rule the ranked filter
+ * uses, and a refusal is {@link notFound} β€” byte-for-byte the error an
+ * absent chunk produces. A distinguishable refusal would still leak: it
+ * would confirm that the chunk exists and belongs to someone else,
+ * which is exactly what enumeration is looking for.
+ *
+ * An omitted or blank scope filters nothing, so an unscoped call is
+ * byte-identical.
*/
export async function expandHit(
config: ResolvedSearchConfig,
@@ -71,11 +88,15 @@ export async function expandHit(
if (!Number.isInteger(input.chunkId) || input.chunkId < 1) {
throw new SearchError("INVALID_INPUT", "chunkId must be a positive integer");
}
+ const agentScope = normalizeAgentScope(input.agentScope);
const store = await Store.open(config, { mode: "read" });
try {
const hit = store.hydrateChunks([input.chunkId]).get(input.chunkId);
if (hit === undefined) {
- throw new SearchError("INVALID_INPUT", `chunk not found: ${input.chunkId}`);
+ throw notFound(input.chunkId);
+ }
+ if (agentScope !== null && !ownerVisible(config, hit.path, agentScope)) {
+ throw notFound(input.chunkId);
}
// Document chunks in `chunkIndex` order: the fuller note (layer 2) is
// their concatenation; the raw transcript (layer 3) is the same rows.
@@ -115,3 +136,30 @@ export async function expandHit(
await store.close();
}
}
+
+/**
+ * The single construction of the drill-down's not-found error. Both the
+ * absent-chunk branch and the ownership refusal call it, so the two
+ * cannot drift into distinguishable messages.
+ */
+function notFound(chunkId: number): SearchError {
+ return new SearchError("INVALID_INPUT", `chunk not found: ${chunkId}`);
+}
+
+/**
+ * Is the note at `path` reachable under `scope`? Fails CLOSED on an
+ * unreadable page, matching `applyAgentScope` on the ranked path: an
+ * owner that cannot be determined is treated as somebody else's rather
+ * than as shared.
+ *
+ * Delegates to {@link isPathOwnerVisible} rather than restating the rule,
+ * so the drill-down and the ranked filter cannot drift on what "closed"
+ * means β€” including the unreadable-file verdict, which an empty
+ * frontmatter map cannot express.
+ */
+function ownerVisible(config: ResolvedSearchConfig, path: string, scope: string): boolean {
+ // One hit, so the cache is a formality β€” it exists because the shared
+ // reader takes one, and reusing it keeps this check on exactly the
+ // same parse semantics as the ranked filter.
+ return isPathOwnerVisible(config.vault, path, scope, new Map());
+}
diff --git a/src/core/search/index.ts b/src/core/search/index.ts
index 398488df..959b7fb0 100644
--- a/src/core/search/index.ts
+++ b/src/core/search/index.ts
@@ -75,7 +75,11 @@ export {
} from "./session-focus.ts";
export { evaluateSurfacingGate, type SurfacingGateDecision } from "./surfacing-gate.ts";
export { buildEvidencePack, serializeEvidencePack } from "./evidence-pack.ts";
-export { serializeSearchCard, serializeIndexStatus } from "./serialize.ts";
+export {
+ serializeSearchCard,
+ serializeIndexStatus,
+ serializeStampMismatches,
+} from "./serialize.ts";
export {
loadProviderRegistry,
addProviderProfile,
diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.ts
index 70513f49..7db42d69 100644
--- a/src/core/search/indexer.ts
+++ b/src/core/search/indexer.ts
@@ -42,15 +42,24 @@ import { extractFrontmatterRelations } from "../graph/frontmatter-relations.ts";
import { loadSchemaPack, type SchemaPack } from "../brain/schema-pack.ts";
import { tieredFieldsForKind } from "../brain/frontmatter-tiers.ts";
import { normalizeSchemaToken } from "../brain/schema-vocab.ts";
-import { parseFrontmatterText } from "../vault.ts";
+import type { DegradationNotice } from "../integrity/degradation.ts";
+import { parseFrontmatterTextWithNotices } from "../vault.ts";
import { appendMetric } from "../brain/metrics.ts";
import { throwIfAborted } from "../brain/safeguard.ts";
import { extractEntities } from "./entities.ts";
+import { compareStamps, formatStampMismatch, type StampMismatch } from "../integrity/stamp.ts";
+
import {
acquireWriterLock,
+ EMBEDDING_ABI_FIX_COMMAND,
+ formatEmbeddingAbiDrift,
+ readEmbeddingAbiSync,
+ runtimeEmbeddingAbi,
Store,
EMBEDDING_PREFIX_QUERY_STATE_KEY,
EMBEDDING_PREFIX_PASSAGE_STATE_KEY,
+ LAST_FULL_INDEX_AT_STATE_KEY,
+ LAST_INDEXED_AT_STATE_KEY,
} from "./store.ts";
import { LATEST_SCHEMA_VERSION } from "./schema.ts";
import { SearchError } from "./types.ts";
@@ -94,6 +103,9 @@ export interface IndexVaultOptions {
readonly signal?: AbortSignal;
}
+/** Site recorded on the frontmatter notices an index run collects. */
+const INDEX_FRONTMATTER_SITE = "search.indexVault";
+
interface MutableStats {
added: number;
updated: number;
@@ -103,6 +115,7 @@ interface MutableStats {
embeddingsComputed: number;
embeddingsRetries: number;
errors: Array<{ readonly path: string; readonly message: string }>;
+ frontmatterNotices: DegradationNotice[];
relationViolations: IndexStats["relationViolations"];
tierDrift: IndexStats["tierDrift"];
aliasResolved: number;
@@ -120,6 +133,7 @@ function newStats(): MutableStats {
embeddingsComputed: 0,
embeddingsRetries: 0,
errors: [],
+ frontmatterNotices: [],
relationViolations: [],
tierDrift: [],
aliasResolved: 0,
@@ -140,6 +154,7 @@ function freezeStats(s: MutableStats, durationMs: number): IndexStats {
embeddingsComputed: s.embeddingsComputed,
embeddingsRetries: s.embeddingsRetries,
errors: Object.freeze([...s.errors]),
+ frontmatterNotices: Object.freeze([...s.frontmatterNotices]),
relationViolations: Object.freeze([...s.relationViolations]),
tierDrift: Object.freeze([...s.tierDrift]),
aliasResolved: s.aliasResolved,
@@ -320,7 +335,15 @@ async function indexInto(
// The document's declared frontmatter `type` is persisted so
// the link-constraint post-pass can join endpoint types
// without re-reading files (v6).
- const [frontmatter] = parseFrontmatterText(content);
+ // Unit F: the scanner drops a line it cannot express instead of
+ // failing, so a note keeps indexing while a field silently
+ // vanishes. Collect what it dropped; the run reports it and
+ // nothing about the indexing changes.
+ const [frontmatter, , fmNotices] = parseFrontmatterTextWithNotices(content, {
+ site: INDEX_FRONTMATTER_SITE,
+ path: file.relPath,
+ });
+ for (const n of fmNotices) stats.frontmatterNotices.push(n);
const docId = store.upsertDocument({
path: file.relPath,
title: chunkResult.title,
@@ -500,8 +523,11 @@ async function indexInto(
}
const now = new Date().toISOString();
- store.setState("last_indexed_at", now);
- if (opts?.force) store.setState("last_full_index_at", now);
+ store.setState(LAST_INDEXED_AT_STATE_KEY, now);
+ // The SAME instant on a forced run: their equality is the
+ // "this index resolved the whole vault" predicate the broken-link
+ // ratchet verifies before it trusts a count (unit G).
+ if (opts?.force) store.setState(LAST_FULL_INDEX_AT_STATE_KEY, now);
// Bump the corpus-generation revision whenever the index actually
// changed, so the persistent query cache (v0.20.0) is invalidated
@@ -826,6 +852,7 @@ export async function indexStatus(config: ResolvedSearchConfig): Promise<IndexSt
embeddingKeyPresent: !!config.semantic.apiKey,
lastIndexedAt: null,
lastFullIndexAt: null,
+ embeddingAbi: Object.freeze([]),
warnings: Object.freeze([]),
});
}
@@ -836,8 +863,8 @@ export async function indexStatus(config: ResolvedSearchConfig): Promise<IndexSt
const model = store.getState("embedding_model");
const dimRaw = store.getState("embedding_dimension");
const dim = dimRaw ? Number(dimRaw) : null;
- const last = store.getState("last_indexed_at");
- const full = store.getState("last_full_index_at");
+ const last = store.getState(LAST_INDEXED_AT_STATE_KEY);
+ const full = store.getState(LAST_FULL_INDEX_AT_STATE_KEY);
const warnings: string[] = [];
if (config.semantic.enabled && !store.vecLoaded()) {
@@ -870,6 +897,25 @@ export async function indexStatus(config: ResolvedSearchConfig): Promise<IndexSt
}
}
+ // Embedding-ABI drift (context-integrity-gates, Unit E). The read
+ // open already ran the gated comparison, so this only surfaces what
+ // it found: empty when the stamps agree AND whenever the operator
+ // has `integrity.embedding_abi` off. Gated on stored vectors for the
+ // same reason the prefix warning above is - an index with no
+ // embeddings has nothing that could be incomparable.
+ //
+ // Reported twice, deliberately: as one operator-facing line here and
+ // as the structured `embeddingAbi` field below. The MCP status block
+ // carries both, so an agent can branch on the field instead of
+ // matching on message text.
+ const abiDrift =
+ config.semantic.enabled && counts.embeddings > 0
+ ? store.embeddingAbiMismatches()
+ : Object.freeze([] as ReadonlyArray<StampMismatch>);
+ if (abiDrift.length > 0) {
+ warnings.push(formatEmbeddingAbiDrift(abiDrift));
+ }
+
// Best-effort spend estimate to bring stale/missing embeddings current.
// Only scan chunk content when the active model is actually priced.
const activeModel =
@@ -902,6 +948,7 @@ export async function indexStatus(config: ResolvedSearchConfig): Promise<IndexSt
embeddingKeyPresent: !!config.semantic.apiKey,
lastIndexedAt: last,
lastFullIndexAt: full,
+ embeddingAbi: abiDrift,
warnings: Object.freeze(warnings),
});
} finally {
@@ -946,6 +993,8 @@ export async function indexCheck(config: ResolvedSearchConfig): Promise<IndexChe
let sqliteOk = false;
let fts5Ok = false;
let vecExtension: "loaded" | "unavailable" | "not-attempted" = "not-attempted";
+ /** Runtime ABI token; captured from the probe rather than re-queried. */
+ let vecVersion: string | null = null;
try {
// Use an in-memory DB so the check never touches the real index.
const { Database } = await import("bun:sqlite");
@@ -965,7 +1014,8 @@ export async function indexCheck(config: ResolvedSearchConfig): Promise<IndexChe
// eslint-disable-next-line @typescript-eslint/no-require-imports
const vec = require("sqlite-vec") as { getLoadablePath(): string };
db.loadExtension(vec.getLoadablePath());
- db.query("SELECT vec_version()").get();
+ const row = db.query<{ v: string }, []>("SELECT vec_version() AS v").get();
+ vecVersion = typeof row?.v === "string" ? row.v : null;
vecExtension = "loaded";
} catch (e) {
vecExtension = "unavailable";
@@ -1002,6 +1052,21 @@ export async function indexCheck(config: ResolvedSearchConfig): Promise<IndexChe
}
}
+ // Stored-versus-runtime embedding ABI (context-integrity-gates, Unit
+ // E). The probe above deliberately runs in memory and never touches
+ // the real index, so the stored side is read explicitly here - without
+ // it there is nothing to compare against.
+ //
+ // This is the DIAGNOSTIC surface, so it compares ungated: an operator
+ // who ran `search check` asked to be told. The gate governs the read
+ // path, which is where a comparison can refuse; a report cannot.
+ const recordedAbi = config.semantic.enabled ? readEmbeddingAbiSync(config.dbPath) : null;
+ const embeddingAbi =
+ recordedAbi === null
+ ? Object.freeze([] as ReadonlyArray<StampMismatch>)
+ : compareStamps(recordedAbi, runtimeEmbeddingAbi(config, vecVersion));
+ if (embeddingAbi.length > 0) warnings.push(formatEmbeddingAbiDrift(embeddingAbi));
+
// Β§E.2 β€” Actionable hints derived from the check state.
// Rules match the design doc table; agents and operators read the
// list to know what command to run next without learning the
@@ -1011,6 +1076,7 @@ export async function indexCheck(config: ResolvedSearchConfig): Promise<IndexChe
embeddingKeyResolved,
vecExtension,
providerReachable,
+ embeddingAbi,
});
return Object.freeze({
@@ -1018,6 +1084,7 @@ export async function indexCheck(config: ResolvedSearchConfig): Promise<IndexChe
indexDirWritable,
sqliteOk,
fts5Ok,
+ embeddingAbi,
vecExtension,
embeddingKeyResolved,
providerReachable,
@@ -1033,11 +1100,22 @@ interface BuildRecommendationsInput {
readonly embeddingKeyResolved: boolean;
readonly vecExtension: "loaded" | "unavailable" | "not-attempted";
readonly providerReachable: boolean | null;
+ readonly embeddingAbi: ReadonlyArray<StampMismatch>;
}
function buildRecommendations(input: BuildRecommendationsInput): string[] {
const recs: string[] = [];
+ // Embedding-ABI drift is the one condition here whose remediation is a
+ // single command, so it is named verbatim and copy-pasteable.
+ if (input.embeddingAbi.length > 0) {
+ recs.push(
+ `Stored vectors were written under a different embedding ABI ` +
+ `(${input.embeddingAbi.map(formatStampMismatch).join("; ")}). Run: ` +
+ `${EMBEDDING_ABI_FIX_COMMAND}`,
+ );
+ }
+
if (input.config.semantic.enabled && !input.embeddingKeyResolved) {
recs.push(
"Set OPEN_SECOND_BRAIN_EMBEDDING_KEY in ~/.hermes/.env (or the configured env file).",
diff --git a/src/core/search/link-ratchet.ts b/src/core/search/link-ratchet.ts
new file mode 100644
index 00000000..7adbe6c1
--- /dev/null
+++ b/src/core/search/link-ratchet.ts
@@ -0,0 +1,446 @@
+/**
+ * Vault-wide broken-link ratchet: the counter and the ceiling
+ * comparison (context-integrity-gates, unit G).
+ *
+ * Nothing in this repository counted broken links vault-wide before
+ * this module. `doctor.ts:checkBrokenBacklinks` answers a deliberately
+ * narrower question (Brain-layer `pref-`/`ret-`/`sig-` targets only)
+ * and is untouched; the graph-degree machinery in `link-graph/` counts
+ * RESOLVED edges and never the unresolved ones.
+ *
+ * ## What "dangling" means here
+ *
+ * A link row that carries a target path and that the READ-TIME
+ * resolution ladder cannot resolve to any document. The ladder is the
+ * one every reader already follows - `store.resolvedDocLinkPairs()` and
+ * its siblings - and it lives in exactly one place,
+ * `RESOLVED_LINK_TARGET_SQL` in `store.ts`: a materialized id, then a
+ * `<target>.md` exact match, then an unambiguous basename. Tags carry
+ * no target path and are excluded.
+ *
+ * ## Why not the narrower SQL predicate
+ *
+ * The first cut of this gate counted `target_document_id IS NULL AND
+ * target_path IS NOT NULL`, chosen for stability and index-backing.
+ * Measurement refuted it: `templates/brain-starter` reported 55
+ * dangling out of 55 link rows - every row in the vault - because that
+ * vault is written in basename wikilinks (`[[pref-x]]`), which the
+ * ladder resolves and the raw predicate does not. Under that
+ * definition, adding a healthy basename link raises the count exactly
+ * as adding a broken one does, so the gate fires on correct edits and
+ * gets routinely bumped. A gate nobody believes is the misleading
+ * signal this wave exists to remove, so the definition follows the
+ * reader instead: {@link DANGLING_LINK_DEFINITION} names the rule that
+ * produced a number, and a ceiling recorded under a different one is
+ * refused at parse time rather than being read as link rot.
+ *
+ * Determinism survives the move. Every rung is index-backed
+ * (`idx_links_target_path`, the UNIQUE `documents.path`,
+ * `idx_documents_basename`), the ambiguous-basename rung resolves to
+ * nothing rather than guessing, alias collisions resolve first-wins by
+ * sorted document path, and `walkVault` sorts every listing - so two
+ * runs over an unchanged subject agree, which the tests assert.
+ *
+ * ## The full-resolution precondition
+ *
+ * `resolveLinkTargets` and `resolveAliasTargets` run as global
+ * post-passes, but `replaceDocAliases` runs only for the documents a
+ * run actually read, so a count taken after an incremental pass can
+ * differ from one taken after a forced full pass. The precondition is
+ * therefore VERIFIED, not documented: `measureFromIndex` refuses to
+ * return a number unless the index itself records that its last run was
+ * a forced one (`last_full_index_at === last_indexed_at`, both stamped
+ * from the same instant by `indexVault`). {@link measureVault} verifies
+ * more: it indexes a hermetic copy from an empty database and checks
+ * that every walked file materialized a document row.
+ *
+ * An unmeasurable subject is a distinct outcome from a clean one at
+ * every layer - there is no fallback that reports zero.
+ */
+
+import { cpSync, mkdtempSync, rmSync, statSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { resolveSearchConfig } from "./index.ts";
+import { indexVault } from "./indexer.ts";
+import { LAST_FULL_INDEX_AT_STATE_KEY, LAST_INDEXED_AT_STATE_KEY, Store } from "./store.ts";
+import { SearchError, type ResolvedSearchConfig } from "./types.ts";
+import { walkVault } from "./walker.ts";
+
+/**
+ * The counting rule that produced a number, recorded beside it. Bump
+ * the `@n` suffix whenever the predicate changes, so a redefinition
+ * fails the comparison loudly instead of reading as link rot.
+ */
+export const DANGLING_LINK_DEFINITION = "ladder:links-unresolved-after-read-resolution@2";
+
+/** Schema version of `link-ratchet.json`, per `schemas/brain/` convention. */
+export const LINK_RATCHET_SCHEMA_VERSION = 1;
+
+/** The single remediation, named once and quoted by every failure path. */
+export const LINK_RATCHET_FIX_COMMAND = "bun run link-ratchet";
+
+/** Chunking pinned for the gate: chunk boundaries decide how many link
+ * rows a document produces (extraction dedupes per chunk), so the
+ * measurement must not inherit an operator's `search_chunk_*` override. */
+const RATCHET_CHUNK_SIZE = 800;
+const RATCHET_CHUNK_OVERLAP = 100;
+const RATCHET_CHUNK_MIN_SIZE = 100;
+
+/** Why a count could not be obtained. Never folded into a zero. */
+export type LinkRatchetUnmeasurableReason =
+ /** The subject directory does not exist or is not a directory. */
+ | "subject-missing"
+ /** No index database at the configured path. */
+ | "index-missing"
+ /** The index exists but could not be opened or queried. */
+ | "index-unreadable"
+ /** The last index run was not a forced full pass. */
+ | "partial-resolution"
+ /** The index does not cover every markdown file under the subject. */
+ | "index-incomplete"
+ /**
+ * The subject exists but holds no indexable markdown at all - emptied,
+ * renamed, sparse-checked-out, or fully excluded by its own ignore
+ * rules. A count over nothing satisfies every completeness guard and
+ * reads as `dangling: 0`, which is a clean bill of health for a
+ * subject nobody measured; the write form would then commit that zero
+ * as a permanent ceiling.
+ */
+ | "subject-empty";
+
+export type LinkRatchetMeasurement =
+ | {
+ readonly measurable: true;
+ readonly definition: string;
+ /**
+ * Link rows matching {@link DANGLING_LINK_DEFINITION}: those the
+ * read-time ladder leaves unresolved.
+ */
+ readonly dangling: number;
+ /** Link rows carrying a target path (the denominator). */
+ readonly links: number;
+ readonly documents: number;
+ }
+ | {
+ readonly measurable: false;
+ readonly definition: string;
+ readonly reason: LinkRatchetUnmeasurableReason;
+ readonly detail: string;
+ };
+
+/** One committed ceiling entry: a repo-relative vault root and its count. */
+export interface LinkRatchetSubject {
+ readonly path: string;
+ readonly dangling: number;
+}
+
+/** The committed `link-ratchet.json` document. */
+export interface LinkRatchetCeiling {
+ readonly schema_version: number;
+ readonly definition: string;
+ readonly subjects: ReadonlyArray<LinkRatchetSubject>;
+}
+
+export type LinkRatchetStatus =
+ | "level"
+ | "drop"
+ | "rise"
+ | "unmeasurable"
+ /** Measured, but under a rule the recorded ceiling did not use. */
+ | "redefined";
+
+export interface LinkRatchetVerdict {
+ readonly subject: string;
+ readonly ceiling: number;
+ readonly status: LinkRatchetStatus;
+ readonly measurement: LinkRatchetMeasurement;
+}
+
+/** A malformed or incomparable ceiling file. */
+export class LinkRatchetError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "LinkRatchetError";
+ }
+}
+
+function errorMessage(e: unknown): string {
+ return e instanceof Error ? e.message : String(e);
+}
+
+function unmeasurable(
+ reason: LinkRatchetUnmeasurableReason,
+ detail: string,
+): LinkRatchetMeasurement {
+ return Object.freeze({
+ measurable: false as const,
+ definition: DANGLING_LINK_DEFINITION,
+ reason,
+ detail,
+ });
+}
+
+/**
+ * The search config the gate measures under: the operator's resolved
+ * config with the determinism-relevant fields pinned - the database
+ * location (so the subject tree is never written into), the chunk
+ * geometry, and the embedding lane (a link census needs no vectors).
+ * Ignore rules still come from the subject's own `Brain/_brain.yaml`,
+ * which is part of the subject and therefore part of the measurement.
+ */
+export function ratchetSearchConfig(vault: string, dbPath: string): ResolvedSearchConfig {
+ const base = resolveSearchConfig({ vault });
+ return Object.freeze({
+ ...base,
+ dbPath,
+ chunkSize: RATCHET_CHUNK_SIZE,
+ chunkOverlap: RATCHET_CHUNK_OVERLAP,
+ chunkMinSize: RATCHET_CHUNK_MIN_SIZE,
+ semantic: Object.freeze({ ...base.semantic, enabled: false }),
+ });
+}
+
+/**
+ * Count dangling links in an EXISTING index, refusing unless that index
+ * records a full resolution pass as its most recent run.
+ *
+ * Read-only: opens the store in read mode, never indexes, never writes.
+ */
+export async function measureFromIndex(
+ config: ResolvedSearchConfig,
+): Promise<LinkRatchetMeasurement> {
+ let store: Store;
+ try {
+ store = await Store.open(config, { mode: "read" });
+ } catch (e) {
+ if (e instanceof SearchError && e.code === "INDEX_MISSING") {
+ return unmeasurable("index-missing", `no search index at ${config.dbPath}`);
+ }
+ return unmeasurable("index-unreadable", errorMessage(e));
+ }
+ try {
+ const full = store.getState(LAST_FULL_INDEX_AT_STATE_KEY);
+ const last = store.getState(LAST_INDEXED_AT_STATE_KEY);
+ if (full === null || last === null || full !== last) {
+ return unmeasurable(
+ "partial-resolution",
+ `last full index ${full ?? "(never)"} is not the last index run ${last ?? "(never)"}; ` +
+ "a dangling count is only reproducible after a forced full pass",
+ );
+ }
+ const links = store.linkResolutionCounts();
+ return Object.freeze({
+ measurable: true as const,
+ definition: DANGLING_LINK_DEFINITION,
+ dangling: links.unresolved,
+ links: links.total,
+ documents: store.counts().documents,
+ });
+ } catch (e) {
+ return unmeasurable("index-unreadable", errorMessage(e));
+ } finally {
+ await store.close();
+ }
+}
+
+/**
+ * Markdown files the walker admits under `config.vault`. Materialized
+ * rather than streamed: a completeness check needs the whole set, and
+ * the walker has already applied the ignore rules and the index
+ * admission predicate, so this is exactly the population the indexer
+ * saw.
+ */
+function countWalkedFiles(config: ResolvedSearchConfig): number {
+ return [...walkVault(config)].length;
+}
+
+/**
+ * Measure one vault root from scratch: copy it, index the copy from an
+ * empty database with `force`, and count.
+ *
+ * The copy is not paranoia - `indexVault` appends a run record under
+ * `<vault>/Brain/metrics/`, so measuring a subject in place would
+ * mutate the tree being measured. The copy also removes any prior index
+ * state from the comparison, which is what makes two runs over an
+ * unchanged subject agree.
+ */
+export async function measureVault(vaultDir: string): Promise<LinkRatchetMeasurement> {
+ try {
+ if (!statSync(vaultDir).isDirectory()) {
+ return unmeasurable("subject-missing", `not a directory: ${vaultDir}`);
+ }
+ } catch {
+ return unmeasurable("subject-missing", `no such directory: ${vaultDir}`);
+ }
+
+ const work = mkdtempSync(join(tmpdir(), "o2b-link-ratchet-"));
+ try {
+ const copy = join(work, "vault");
+ cpSync(vaultDir, copy, { recursive: true });
+ const config = ratchetSearchConfig(copy, join(work, "index.sqlite"));
+ const stats = await indexVault(config, { force: true });
+ if (stats.unchanged !== 0 || stats.deleted !== 0) {
+ return unmeasurable(
+ "index-incomplete",
+ `forced run reported ${stats.unchanged} unchanged and ${stats.deleted} deleted file(s)`,
+ );
+ }
+ const walked = countWalkedFiles(config);
+ if (walked === 0) {
+ return unmeasurable(
+ "subject-empty",
+ `no indexable markdown under ${vaultDir}; a count over an empty subject ` +
+ "would read as zero dangling and pass every completeness guard",
+ );
+ }
+ const measurement = await measureFromIndex(config);
+ if (measurement.measurable && measurement.documents !== walked) {
+ return unmeasurable(
+ "index-incomplete",
+ `indexed ${measurement.documents} of ${walked} markdown file(s) under ${vaultDir}`,
+ );
+ }
+ return measurement;
+ } catch (e) {
+ return unmeasurable("index-unreadable", errorMessage(e));
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ }
+}
+
+export interface JudgeSubjectOptions {
+ /**
+ * Whether the recorded ceiling was produced by the rule this build
+ * counts with. False makes the comparison meaningless, so the verdict
+ * reports `redefined` instead of inventing a rise or a drop.
+ * Defaults to true.
+ */
+ readonly comparable?: boolean;
+}
+
+/** Compare one measurement against its committed ceiling. */
+export function judgeSubject(
+ subject: string,
+ ceiling: number,
+ measurement: LinkRatchetMeasurement,
+ options: JudgeSubjectOptions = {},
+): LinkRatchetVerdict {
+ const status: LinkRatchetStatus = !measurement.measurable
+ ? "unmeasurable"
+ : options.comparable === false
+ ? "redefined"
+ : measurement.dangling > ceiling
+ ? "rise"
+ : measurement.dangling < ceiling
+ ? "drop"
+ : "level";
+ return Object.freeze({ subject, ceiling, status, measurement });
+}
+
+function asRecord(value: unknown, what: string): Record<string, unknown> {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ throw new LinkRatchetError(`${what} must be a JSON object`);
+ }
+ return value as Record<string, unknown>;
+}
+
+export interface ParseCeilingOptions {
+ /**
+ * Accept a ceiling recorded under a different counting definition,
+ * returning it with that definition preserved so the caller can see
+ * the numbers are incomparable.
+ *
+ * Only the WRITE form passes this. The refusal names
+ * {@link LINK_RATCHET_FIX_COMMAND} as the remedy, so that command has
+ * to be able to read the very file the comparison rejects - otherwise
+ * a definition change could never be adopted. `--check` keeps the
+ * refusal, which is what makes a redefinition a reviewable diff
+ * rather than a silent reinterpretation of the gate.
+ */
+ readonly allowForeignDefinition?: boolean;
+}
+
+/**
+ * Parse a committed ceiling file, refusing anything that cannot be
+ * compared: a foreign schema version, a foreign counting definition
+ * (unless {@link ParseCeilingOptions.allowForeignDefinition}), a
+ * non-integer count, a duplicate subject, or an empty subject list (a
+ * gate with nothing to measure is not a gate).
+ */
+export function parseCeiling(text: string, options: ParseCeilingOptions = {}): LinkRatchetCeiling {
+ let raw: unknown;
+ try {
+ raw = JSON.parse(text);
+ } catch (e) {
+ throw new LinkRatchetError(`ceiling file is not valid JSON: ${errorMessage(e)}`);
+ }
+ const doc = asRecord(raw, "ceiling file");
+
+ if (doc["schema_version"] !== LINK_RATCHET_SCHEMA_VERSION) {
+ throw new LinkRatchetError(
+ `ceiling schema_version ${String(doc["schema_version"])} is not the supported ` +
+ `${LINK_RATCHET_SCHEMA_VERSION}`,
+ );
+ }
+ const rawDefinition = doc["definition"];
+ if (typeof rawDefinition !== "string" || rawDefinition.length === 0) {
+ throw new LinkRatchetError("ceiling 'definition' must be a non-empty string");
+ }
+ if (rawDefinition !== DANGLING_LINK_DEFINITION && options.allowForeignDefinition !== true) {
+ throw new LinkRatchetError(
+ `ceiling definition '${rawDefinition}' is not the current ` +
+ `'${DANGLING_LINK_DEFINITION}': the counts are not comparable, ` +
+ `re-measure with: ${LINK_RATCHET_FIX_COMMAND}`,
+ );
+ }
+ const rawSubjects = doc["subjects"];
+ if (!Array.isArray(rawSubjects) || rawSubjects.length === 0) {
+ throw new LinkRatchetError("ceiling 'subjects' must be a non-empty array");
+ }
+
+ const seen = new Set<string>();
+ const subjects: LinkRatchetSubject[] = [];
+ for (const entry of rawSubjects) {
+ const subject = asRecord(entry, "ceiling subject");
+ const path = subject["path"];
+ const dangling = subject["dangling"];
+ if (typeof path !== "string" || path.length === 0) {
+ throw new LinkRatchetError("every ceiling subject needs a non-empty 'path'");
+ }
+ if (typeof dangling !== "number" || !Number.isInteger(dangling) || dangling < 0) {
+ throw new LinkRatchetError(`subject '${path}': 'dangling' must be a non-negative integer`);
+ }
+ if (seen.has(path)) throw new LinkRatchetError(`duplicate ceiling subject '${path}'`);
+ seen.add(path);
+ subjects.push(Object.freeze({ path, dangling }));
+ }
+ return Object.freeze({
+ schema_version: LINK_RATCHET_SCHEMA_VERSION,
+ definition: rawDefinition,
+ subjects: Object.freeze(subjects),
+ });
+}
+
+/**
+ * Render a ceiling file: subjects sorted by path, two-space indent,
+ * trailing newline - the shape `fmt:check` already enforces for every
+ * other JSON file at the repository root.
+ */
+export function serializeCeiling(ceiling: LinkRatchetCeiling): string {
+ const subjects = ceiling.subjects
+ .toSorted((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
+ .map((s) => ({ path: s.path, dangling: s.dangling }));
+ return (
+ JSON.stringify(
+ {
+ schema_version: ceiling.schema_version,
+ definition: ceiling.definition,
+ subjects,
+ },
+ null,
+ 2,
+ ) + "\n"
+ );
+}
diff --git a/src/core/search/result-filters.ts b/src/core/search/result-filters.ts
index e17ea0a3..d19c9370 100644
--- a/src/core/search/result-filters.ts
+++ b/src/core/search/result-filters.ts
@@ -8,8 +8,9 @@
import { statSync } from "node:fs";
import { join } from "node:path";
-import { parseFrontmatter } from "../vault.ts";
+import { parseFrontmatterWithNotices } from "../vault.ts";
import { BRAIN_STATE_REL } from "../brain/paths.ts";
+import { DEGRADATION_CODE } from "../integrity/degradation.ts";
import type { FrontmatterMap } from "../types.ts";
import { isVisible, pageVisibility } from "../graph/visibility.ts";
import { isOwnerVisible, pageOwner } from "../graph/agent-scope.ts";
@@ -29,23 +30,62 @@ import {
} from "./rank-adjust.ts";
import type { BrainSearchResult } from "./types.ts";
+/**
+ * A cached frontmatter read, plus whether the file could be read at all.
+ *
+ * The two are inseparable because `parseFrontmatter` resolves an
+ * unreadable file to EMPTY metadata, which is byte-indistinguishable from
+ * a genuinely field-less page. Every fail-open filter is right to ignore
+ * the difference; the ownership boundary is not, and would leak an
+ * owner-private page the moment its file is deleted, renamed, or made
+ * unreadable after the last index run.
+ */
+export interface CachedFrontmatter {
+ readonly meta: FrontmatterMap;
+ /** True when the file itself could not be READ, so nothing is known. */
+ readonly unreadable: boolean;
+}
+
+/** Per-`search()`-call frontmatter read cache, keyed by vault-relative path. */
+export type FrontmatterCache = Map<string, CachedFrontmatter>;
+
/**
* One frontmatter read per (vault, path) pair, shared across every filter
- * stage of a single `search()` call. `parseFrontmatter` never throws (a
- * read failure resolves to empty metadata internally), so caching the raw
- * result changes no call site's fallback behaviour - it only stops the
- * same file being read and parsed once per stage instead of once total.
+ * stage of a single `search()` call, carrying the read verdict alongside
+ * the parsed map β€” see {@link CachedFrontmatter}.
*/
-export function readCachedFrontmatter(
- cache: Map<string, FrontmatterMap>,
+export function readCachedFrontmatterEntry(
+ cache: FrontmatterCache,
vault: string,
path: string,
-): FrontmatterMap {
+): CachedFrontmatter {
const cached = cache.get(path);
if (cached !== undefined) return cached;
- const [meta] = parseFrontmatter(join(vault, path));
- cache.set(path, meta);
- return meta;
+ const [meta, , notices] = parseFrontmatterWithNotices(join(vault, path), {
+ site: FRONTMATTER_CACHE_SITE,
+ });
+ const entry: CachedFrontmatter = Object.freeze({
+ meta,
+ unreadable: notices.some((n) => n.code === DEGRADATION_CODE.frontmatterUnreadable),
+ });
+ cache.set(path, entry);
+ return entry;
+}
+
+/** Attribution recorded on the notices this cache's reads produce. */
+const FRONTMATTER_CACHE_SITE = "search.result-filters";
+
+/**
+ * The parsed map alone, for the filters that treat an unreadable page and
+ * a field-less page identically (every fail-open one). The ownership
+ * boundary must use {@link readCachedFrontmatterEntry} instead.
+ */
+export function readCachedFrontmatter(
+ cache: FrontmatterCache,
+ vault: string,
+ path: string,
+): FrontmatterMap {
+ return readCachedFrontmatterEntry(cache, vault, path).meta;
}
const EXACT_STATE_LANE_PREFIX = `${BRAIN_STATE_REL}/`;
@@ -79,7 +119,7 @@ export function applyExactStateBarrier(
export function buildTerminalPaths(
vault: string,
results: ReadonlyArray<BrainSearchResult>,
- frontmatterCache: Map<string, FrontmatterMap>,
+ frontmatterCache: FrontmatterCache,
): ReadonlySet<string> {
const terminal = new Set<string>();
const seen = new Set<string>();
@@ -106,7 +146,7 @@ export function buildTerminalPaths(
export function applyStatusFilter(
ranked: ReadonlyArray<BrainSearchResult>,
vault: string,
- frontmatterCache: Map<string, FrontmatterMap>,
+ frontmatterCache: FrontmatterCache,
): ReadonlyArray<BrainSearchResult> {
return ranked.filter((r) => {
try {
@@ -122,7 +162,7 @@ export function applyPropertyFilter(
ranked: ReadonlyArray<BrainSearchResult>,
filters: ReadonlyMap<string, ReadonlyArray<string>>,
vault: string,
- frontmatterCache: Map<string, FrontmatterMap>,
+ frontmatterCache: FrontmatterCache,
): ReadonlyArray<BrainSearchResult> {
const reader = (path: string): Record<string, unknown> | null => {
try {
@@ -210,7 +250,7 @@ export function applyVisibilityScope(
ranked: ReadonlyArray<BrainSearchResult>,
scope: ReadonlySet<string>,
vault: string,
- frontmatterCache: Map<string, FrontmatterMap>,
+ frontmatterCache: FrontmatterCache,
): ReadonlyArray<BrainSearchResult> {
const tagsFor = (path: string): string[] => {
try {
@@ -234,7 +274,7 @@ export function applyScopeFilter(
ranked: ReadonlyArray<BrainSearchResult>,
requested: CompositeScope,
vault: string,
- frontmatterCache: Map<string, FrontmatterMap>,
+ frontmatterCache: FrontmatterCache,
): ReadonlyArray<BrainSearchResult> {
return ranked.filter((r) => {
let pageScope: CompositeScope;
@@ -250,27 +290,38 @@ export function applyScopeFilter(
});
}
+/**
+ * May a caller scoped to `scope` see the page at this vault-relative
+ * path? The one place the ownership rule meets the filesystem, so every
+ * surface that owns a path - ranked search results, source-derived
+ * pages, any future one - resolves ownership identically.
+ *
+ * FAILS CLOSED: a page whose file cannot be READ has an unknowable owner
+ * and is hidden under an active scope rather than leaked - the routine
+ * trigger being a document still in the index whose file was deleted,
+ * renamed, or made unreadable since the last index run. The verdict comes
+ * from {@link readCachedFrontmatterEntry} rather than from an empty
+ * metadata map, because the parser resolves an unreadable file to `{}`
+ * and never throws, so a `catch` arm here would be dead code. This is
+ * stricter than visibility scoping's fail-open default - deliberate,
+ * because agent-scope is an isolation boundary.
+ */
+export function isPathOwnerVisible(
+ vault: string,
+ path: string,
+ scope: string,
+ frontmatterCache: FrontmatterCache,
+): boolean {
+ const entry = readCachedFrontmatterEntry(frontmatterCache, vault, path);
+ if (entry.unreadable) return false;
+ return isOwnerVisible(pageOwner(entry.meta), scope);
+}
+
export function applyAgentScope(
ranked: ReadonlyArray<BrainSearchResult>,
scope: string,
vault: string,
- frontmatterCache: Map<string, FrontmatterMap>,
+ frontmatterCache: FrontmatterCache,
): ReadonlyArray<BrainSearchResult> {
- // Fail-closed sentinel: a page whose frontmatter cannot be parsed has
- // an unknowable owner, so under an active scope it is dropped rather
- // than leaked. This is stricter than visibility scoping's fail-open
- // default - deliberate, because agent-scope is an isolation boundary.
- const UNPARSEABLE = " unparseable-owner";
- const ownerFor = (path: string): string => {
- try {
- return pageOwner(readCachedFrontmatter(frontmatterCache, vault, path)) ?? "";
- } catch {
- return UNPARSEABLE;
- }
- };
- return ranked.filter((r) => {
- const owner = ownerFor(r.path);
- if (owner === UNPARSEABLE) return false; // fail closed
- return isOwnerVisible(owner === "" ? null : owner, scope);
- });
+ return ranked.filter((r) => isPathOwnerVisible(vault, r.path, scope, frontmatterCache));
}
diff --git a/src/core/search/search.ts b/src/core/search/search.ts
index 7c11871a..0c7e8b33 100644
--- a/src/core/search/search.ts
+++ b/src/core/search/search.ts
@@ -12,7 +12,6 @@
import { statSync } from "node:fs";
import { join } from "node:path";
-import type { FrontmatterMap } from "../types.ts";
import { normalizeVisibilityScope } from "../graph/visibility.ts";
import { normalizeAgentScope } from "../graph/agent-scope.ts";
import { canonicalSourceSetKey, normalizeScopeFilter, rrfKey } from "../scope-key.ts";
@@ -65,7 +64,7 @@ import { readActiveSessionFocus } from "./session-focus.ts";
import { applyTemporalBridge } from "./temporal-bridge.ts";
import { resolveTimeRange } from "./time-range.ts";
import { eventTimeInRange, parseValidityWindow, type ValidityWindow } from "./validity.ts";
-import { Store } from "./store.ts";
+import { contradictedAbiFields, formatEmbeddingAbiDrift, Store } from "./store.ts";
import { SearchError } from "./types.ts";
import type {
BrainSearchResult,
@@ -98,6 +97,7 @@ import {
buildTerminalPaths,
readCachedFrontmatter,
supersedeFadeAdjuster,
+ type FrontmatterCache,
} from "./result-filters.ts";
import { applyRelationPolarityPhase, applyTraversal } from "./graph-phases.ts";
import { buildEvidenceVerification, coverageOverChunks } from "./evidence-verification.ts";
@@ -242,7 +242,7 @@ export async function search(
// Shared across every frontmatter-reading filter stage below (Plan 1,
// 1.3) so a candidate path already read by one stage is not re-read
// and re-parsed by the next.
- const frontmatterCache = new Map<string, FrontmatterMap>();
+ const frontmatterCache: FrontmatterCache = new Map();
// Opt-in local expansion (t_2fa95db1): an explicit structured
// document always wins; expansion only fills the gap. The lex lane's
@@ -433,6 +433,24 @@ export async function search(
semanticAttempted = semOutcome.attempted;
semHits = semOutcome.hits;
for (const w of semOutcome.warnings) warnings.push(w);
+ // Embedding-ABI drift on the QUERY path (context-integrity-gates,
+ // Unit E). The read open already ran the gated comparison; until
+ // now nothing on this path looked at the result, so under the
+ // shipped `warn` default a caller was served neighbours out of a
+ // vector table written by another build with nothing to observe.
+ //
+ // Attached to the queries it actually describes: only when the
+ // semantic lane RAN, so a keyword-only query stays byte-identical,
+ // and only for fields the index CONTRADICTS. An unrecorded token
+ // is a store predating the stamp - true of every index built
+ // before this release - and repeating it on every query would
+ // make the warning worthless; it stays on `search status`,
+ // `second_brain_status` and `search check`, which is where an
+ // operator goes looking.
+ if (semanticAttempted) {
+ const contradicted = contradictedAbiFields(store.embeddingAbiMismatches());
+ if (contradicted.length > 0) warnings.push(formatEmbeddingAbiDrift(contradicted));
+ }
}
// Hybrid-degrade signal (Search & Recall Quality Suite): one
diff --git a/src/core/search/serialize.ts b/src/core/search/serialize.ts
index 34d25d38..62bd21a2 100644
--- a/src/core/search/serialize.ts
+++ b/src/core/search/serialize.ts
@@ -4,8 +4,26 @@
* field-by-field the way independently hand-written copies do.
*/
+import type { StampMismatch } from "../integrity/stamp.ts";
import type { IndexStatusSnapshot, SearchCard } from "./types.ts";
+/**
+ * Wire shape for a stamp comparison. `recorded` is what the index
+ * wrote, `runtime` what this build would write; a `recorded` of `null`
+ * is a field the index never stamped. Shared by `o2b search check`,
+ * `o2b search status --json` and the MCP `search.*` status block, so
+ * one drift cannot be described three ways.
+ */
+export function serializeStampMismatches(
+ mismatches: ReadonlyArray<StampMismatch>,
+): Array<Record<string, unknown>> {
+ return mismatches.map((m) => ({
+ field: m.field,
+ recorded: m.expected,
+ runtime: m.actual,
+ }));
+}
+
/** Layer-1 card projection - identical shape on both the CLI and MCP surfaces. */
export function serializeSearchCard(c: SearchCard): Record<string, unknown> {
return {
@@ -44,6 +62,11 @@ export function serializeIndexStatus(s: IndexStatusSnapshot): Record<string, unk
embedding_key_present: s.embeddingKeyPresent,
last_indexed_at: s.lastIndexedAt,
last_full_index_at: s.lastFullIndexAt,
+ // Emitted only on drift, so a matching store's JSON is byte-identical
+ // to the pre-gate output (context-integrity-gates, Unit E).
+ ...(s.embeddingAbi.length > 0
+ ? { embedding_abi: serializeStampMismatches(s.embeddingAbi) }
+ : {}),
warnings: s.warnings,
};
}
diff --git a/src/core/search/store.ts b/src/core/search/store.ts
index 8633ffce..8c278113 100644
--- a/src/core/search/store.ts
+++ b/src/core/search/store.ts
@@ -20,6 +20,16 @@ import lockfile from "proper-lockfile";
import { registerWriterDb, unregisterWriterDb } from "./store-exit.ts";
+import { loadIntegrityConfigSafe } from "../brain/policy.ts";
+import {
+ checkStamp,
+ compareStamps,
+ formatStampMismatch,
+ STAMP_VERDICT,
+ type StampMismatch,
+ type StampTokens,
+} from "../integrity/stamp.ts";
+
import { computeCorpusGeneration } from "./corpus-generation.ts";
import { SearchError } from "./types.ts";
import type { ResolvedSearchConfig } from "./types.ts";
@@ -47,6 +57,82 @@ import {
export const EMBEDDING_PREFIX_QUERY_STATE_KEY = "embedding_prefix_query";
export const EMBEDDING_PREFIX_PASSAGE_STATE_KEY = "embedding_prefix_passage";
+/**
+ * `index_state` keys behind the corpus-generation fingerprint. Named so
+ * the class accessors and {@link readCorpusGenerationSync} cannot drift
+ * into two spellings of the same key.
+ */
+export const EMBEDDING_MODEL_STATE_KEY = "embedding_model";
+export const EMBEDDING_DIMENSION_STATE_KEY = "embedding_dimension";
+export const INDEX_REVISION_STATE_KEY = "index_revision";
+
+/**
+ * sqlite-vec version the stored vectors were written against
+ * (context-integrity-gates, Unit E). `SELECT vec_version()` was already
+ * executed on every extension load and the row discarded every time;
+ * this key is where it now lands, so the ABI the vectors were produced
+ * under can be compared later instead of assumed.
+ */
+export const EMBEDDING_VEC_VERSION_STATE_KEY = "embedding_vec_version";
+
+/**
+ * The single remediation for embedding-ABI drift, named once so the
+ * store's refusal, the status warning and the `search check`
+ * recommendation cannot grow three spellings of the same instruction.
+ */
+export const EMBEDDING_ABI_FIX_COMMAND = "o2b search reindex --embeddings";
+
+/**
+ * `index_state` keys stamped by every index run (`last_indexed_at`) and
+ * by a FORCED one only (`last_full_index_at`). Both carry the same ISO
+ * instant when the run was forced, which is what makes their equality a
+ * usable "the last run resolved the whole vault" predicate - the
+ * precondition the broken-link ratchet verifies before it trusts a
+ * dangling count (context-integrity-gates, unit G).
+ */
+export const LAST_INDEXED_AT_STATE_KEY = "last_indexed_at";
+export const LAST_FULL_INDEX_AT_STATE_KEY = "last_full_index_at";
+
+/** Vault-wide link-resolution census (see {@link Store.linkResolutionCounts}). */
+export interface LinkResolutionCounts {
+ /**
+ * Link rows carrying a target path. Tag rows have `target_path IS
+ * NULL` and are excluded - a tag has nothing to resolve to.
+ */
+ readonly total: number;
+ /**
+ * Rows the read-time resolution ladder cannot resolve to any
+ * document - broken links as a reader experiences them.
+ */
+ readonly unresolved: number;
+}
+
+/**
+ * The READ-TIME link-resolution ladder, as one SQL expression over a
+ * `links` row aliased `l`, yielding the resolved document id or NULL.
+ *
+ * Three rungs, in order: the materialized `target_document_id` that
+ * `resolveLinkTargets` / `resolveAliasTargets` wrote, then a
+ * `<target>.md` exact path match, then an UNAMBIGUOUS nested-basename
+ * match (`basename = target` with exactly one such nested document -
+ * a top-level `target.md` has no leading slash and belongs to the exact
+ * rung above).
+ *
+ * Defined once and shared by {@link Store.resolvedDocLinkPairs} (which
+ * follows it) and {@link Store.linkResolutionCounts} (which counts what
+ * it leaves over), so "resolvable" and "broken" can never drift apart
+ * into two different opinions of the same vault.
+ */
+const RESOLVED_LINK_TARGET_SQL =
+ "COALESCE(" +
+ " l.target_document_id, " +
+ " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +
+ " (SELECT d.id FROM documents d " +
+ " WHERE d.basename = l.target_path AND instr(d.path, '/') > 0 " +
+ " AND 1 = (SELECT COUNT(*) FROM documents d2 " +
+ " WHERE d2.basename = l.target_path AND instr(d2.path, '/') > 0))" +
+ ")";
+
/** The query/passage instruction prefixes active for an index run. */
export interface EmbeddingPrefixPair {
readonly query: string;
@@ -209,7 +295,18 @@ function ensureFts5(db: Database): void {
}
}
-function tryLoadVecExtension(db: Database): boolean {
+/**
+ * Load sqlite-vec and return the version it reports, or `null` when the
+ * extension is unavailable.
+ *
+ * The `vec_version()` probe was always executed and its row always
+ * discarded; returning it costs nothing and is what lets the ABI the
+ * vectors were written against be stamped rather than assumed
+ * (context-integrity-gates, Unit E). `null` doubles as the
+ * "not loaded" signal, so there is exactly one source of truth for both
+ * facts.
+ */
+function tryLoadVecExtension(db: Database): string | null {
try {
// sqlite-vec is an optional dependency. Wrap the import + load so
// a missing platform package degrades to "extension unavailable"
@@ -218,11 +315,196 @@ function tryLoadVecExtension(db: Database): boolean {
const vec = require("sqlite-vec") as { getLoadablePath(): string };
db.loadExtension(vec.getLoadablePath());
// Confirm by calling vec_version() β€” guards against partial loads.
- db.query("SELECT vec_version()").get();
- return true;
+ const row = db.query<{ v: string }, []>("SELECT vec_version() AS v").get();
+ return typeof row?.v === "string" ? row.v : null;
} catch {
- return false;
+ return null;
+ }
+}
+
+/**
+ * Corpus-generation fingerprint read WITHOUT opening a {@link Store}.
+ *
+ * `Store.open` is async (the write path acquires a lock) and a read open
+ * refuses a schema mismatch, so neither form is usable from a
+ * synchronous caller that only wants to observe the index's identity and
+ * must keep working when there is no index at all. The context pack's
+ * provenance stamp (context-integrity-gates, Unit B) is exactly that
+ * caller. It lives here rather than beside the caller because this
+ * module is the single SQL boundary for the index.
+ *
+ * Returns `null` - "unrecorded", per `integrity/stamp.ts` - when the
+ * index file is absent or cannot be read. That is DISTINCT from a
+ * recorded generation string: a vault that gains or loses its index
+ * drifts from `null` to a value (or back) and the stamp comparison names
+ * it, rather than treating "nothing to compare" as agreement.
+ *
+ * The schema version comes from the file itself, not from
+ * {@link LATEST_SCHEMA_VERSION}: an index still at an older schema is a
+ * different corpus state, and folding it onto the current constant would
+ * hide precisely that.
+ */
+export function readCorpusGenerationSync(dbPath: string): string | null {
+ const peek = peekCorpusGenerationSync(dbPath);
+ return peek.kind === "read" ? peek.value : null;
+}
+
+/**
+ * {@link readCorpusGenerationSync} with the three outcomes kept apart, so
+ * a caller that must not treat a corrupt index as "no index" can tell.
+ */
+export function peekCorpusGenerationSync(dbPath: string): IndexPeek<string | null> {
+ return peekReadonlyIndex(dbPath, (read, db) => {
+ const dimRaw = read(EMBEDDING_DIMENSION_STATE_KEY);
+ const dim = dimRaw === null ? null : Number(dimRaw);
+ const revRaw = read(INDEX_REVISION_STATE_KEY);
+ const rev = revRaw === null ? 0 : Number(revRaw);
+ return computeCorpusGeneration({
+ embeddingModel: read(EMBEDDING_MODEL_STATE_KEY),
+ embeddingDimension: dim !== null && Number.isFinite(dim) ? dim : null,
+ schemaVersion: readSchemaVersion(db),
+ indexRevision: Number.isFinite(rev) && rev >= 0 ? Math.floor(rev) : 0,
+ });
+ });
+}
+
+/**
+ * Embedding-ABI tokens recorded in an index, without opening a
+ * {@link Store}.
+ *
+ * `indexCheck` needs these and cannot get them from its own probe: it
+ * deliberately runs against an IN-MEMORY database and never touches the
+ * real index, so a stored-versus-runtime comparison there has no stored
+ * side unless one is read explicitly.
+ *
+ * `null` means the index is absent or unreadable - not that its ABI
+ * matches.
+ */
+export function readEmbeddingAbiSync(dbPath: string): StampTokens | null {
+ return withReadonlyIndex(dbPath, (read) => recordedEmbeddingAbi(read));
+}
+
+/**
+ * Outcome of a synchronous peek at the index.
+ *
+ * ABSENT and UNREADABLE used to collapse to one `null`, which is wrong
+ * for a stamp: "no index here" and "an index that exists and is corrupt"
+ * are different states of the world, and a caller that records both as
+ * unrecorded makes two such sides compare EQUAL - "two unrecorded sides
+ * are not a finding" - so a corrupt index silently agrees with a missing
+ * one. They are now separate arms and the caller chooses.
+ */
+export type IndexPeek<T> =
+ | { readonly kind: "read"; readonly value: T }
+ | { readonly kind: "absent" }
+ | { readonly kind: "unreadable"; readonly detail: string };
+
+/**
+ * Run `read` against a read-only handle on the index, naming which of
+ * the three outcomes occurred. Shared by the synchronous peeks so the
+ * classification lives in one place rather than once per caller.
+ */
+function peekReadonlyIndex<T>(
+ dbPath: string,
+ read: (state: (key: string) => string | null, db: Database) => T,
+): IndexPeek<T> {
+ if (!existsSync(dbPath)) return { kind: "absent" };
+ let db: Database;
+ try {
+ db = new Database(dbPath, { readonly: true });
+ } catch (e) {
+ return { kind: "unreadable", detail: e instanceof Error ? e.message : String(e) };
}
+ try {
+ return {
+ kind: "read",
+ value: read(
+ (key: string): string | null =>
+ db
+ .query<{ value: string }, [string]>("SELECT value FROM index_state WHERE key = ?")
+ .get(key)?.value ?? null,
+ db,
+ ),
+ };
+ } catch (e) {
+ return { kind: "unreadable", detail: e instanceof Error ? e.message : String(e) };
+ } finally {
+ try {
+ db.close();
+ } catch {
+ /* a close failure cannot change what was already read */
+ }
+ }
+}
+
+/**
+ * {@link peekReadonlyIndex} collapsed to `T | null` for the callers that
+ * genuinely cannot act on the distinction.
+ */
+function withReadonlyIndex<T>(
+ dbPath: string,
+ read: (state: (key: string) => string | null, db: Database) => T,
+): T | null {
+ const peek = peekReadonlyIndex(dbPath, read);
+ return peek.kind === "read" ? peek.value : null;
+}
+
+/** The ABI tokens an index recorded, read through any state accessor. */
+function recordedEmbeddingAbi(state: (key: string) => string | null): StampTokens {
+ return {
+ [EMBEDDING_MODEL_STATE_KEY]: state(EMBEDDING_MODEL_STATE_KEY),
+ [EMBEDDING_DIMENSION_STATE_KEY]: state(EMBEDDING_DIMENSION_STATE_KEY),
+ [EMBEDDING_VEC_VERSION_STATE_KEY]: state(EMBEDDING_VEC_VERSION_STATE_KEY),
+ };
+}
+
+/**
+ * The ABI tokens the CURRENT build and configuration would produce. The
+ * counterpart of {@link recordedEmbeddingAbi}, kept beside it so the two
+ * sides of the comparison can never cover different fields.
+ */
+export function runtimeEmbeddingAbi(
+ config: ResolvedSearchConfig,
+ vecVersion: string | null,
+): StampTokens {
+ return {
+ [EMBEDDING_MODEL_STATE_KEY]: config.semantic.model,
+ [EMBEDDING_DIMENSION_STATE_KEY]:
+ config.semantic.dimension === null ? null : String(config.semantic.dimension),
+ [EMBEDDING_VEC_VERSION_STATE_KEY]: vecVersion,
+ };
+}
+
+/**
+ * The subset of an ABI comparison the index actually CONTRADICTS: it
+ * recorded a token and that token disagrees with this build.
+ *
+ * A mismatch whose recorded side is `null` is an UNRECORDED field - a
+ * store written before that token was stamped. An absent marker cannot
+ * tell an old store from a wrong one, so it is reported on the
+ * diagnostic surfaces and never drives a refusal or a per-read warning.
+ * Both consumers of that distinction (the `fail` verdict's refusal and
+ * the query path's warning) route through here rather than restating
+ * the predicate, so they cannot drift on what counts as contradicted.
+ */
+export function contradictedAbiFields(
+ mismatches: ReadonlyArray<StampMismatch>,
+): ReadonlyArray<StampMismatch> {
+ return mismatches.filter((m) => m.expected !== null);
+}
+
+/**
+ * One operator-facing line for embedding-ABI drift. Shared by the read
+ * open's refusal, the status warning and the `search check`
+ * recommendation, so the three cannot describe the same condition
+ * differently or name different fixes.
+ */
+export function formatEmbeddingAbiDrift(mismatches: ReadonlyArray<StampMismatch>): string {
+ return (
+ `embedding ABI drift between the stored index and this build ` +
+ `(${mismatches.map(formatStampMismatch).join("; ")}); stored vectors are not ` +
+ `comparable to queries embedded now. Run: ${EMBEDDING_ABI_FIX_COMMAND}`
+ );
}
/** Parse a JSON-encoded drift value; a corrupt cell surfaces as-is. */
@@ -371,19 +653,25 @@ function vecToBuffer(values: ReadonlyArray<number> | Float32Array): Buffer {
export class Store {
private db: Database;
private readonly config: ResolvedSearchConfig;
+ private readonly loadedVecVersion: string | null;
private readonly _vecLoaded: boolean;
private readonly release: (() => Promise<void>) | null;
private closed = false;
+ /** Empty unless a gated read-mode open found ABI drift; see {@link embeddingAbiMismatches}. */
+ private abiDrift: ReadonlyArray<StampMismatch> = Object.freeze([]);
private constructor(
db: Database,
config: ResolvedSearchConfig,
- vecLoaded: boolean,
+ vecVersion: string | null,
release: (() => Promise<void>) | null,
) {
this.db = db;
this.config = config;
- this._vecLoaded = vecLoaded;
+ this.loadedVecVersion = vecVersion;
+ // One source of truth: the version is present exactly when the
+ // extension loaded, so "loaded" is derived rather than tracked twice.
+ this._vecLoaded = vecVersion !== null;
this.release = release;
}
@@ -435,8 +723,14 @@ export class Store {
`index schema version ${version} != ${LATEST_SCHEMA_VERSION}. Run: o2b search reindex`,
);
}
- const vecLoaded = loadVec && tryLoadVecExtension(db);
- return new Store(db, config, vecLoaded, null);
+ const vecVersion = loadVec ? tryLoadVecExtension(db) : null;
+ const store = new Store(db, config, vecVersion, null);
+ // The read path is where the silent-garbage window actually is:
+ // `ensureEmbeddingModel` runs only on a write open, so every MCP
+ // query reached `semanticTopK` - and a `chunk_vec` of unknown
+ // declared width - with nothing having compared anything.
+ store.resolveEmbeddingAbi();
+ return store;
} catch (e) {
db.close();
throw e;
@@ -465,8 +759,8 @@ export class Store {
applyPragmas(db);
applyMigrations(db, { ftsTokenize: config.ftsTokenize });
ensureFts5(db);
- const vecLoaded = loadVec && tryLoadVecExtension(db);
- const store = new Store(db, config, vecLoaded, release);
+ const vecVersion = loadVec ? tryLoadVecExtension(db) : null;
+ const store = new Store(db, config, vecVersion, release);
store.ensureEmbeddingModel(config.semantic.model, config.semantic.dimension, {
query: config.semantic.queryPrefix ?? "",
passage: config.semantic.passagePrefix ?? "",
@@ -490,6 +784,63 @@ export class Store {
return this._vecLoaded;
}
+ /** sqlite-vec version this connection loaded, or null when unavailable. */
+ vecVersion(): string | null {
+ return this.loadedVecVersion;
+ }
+
+ /**
+ * Embedding-ABI fields whose recorded token no longer matches this
+ * build (context-integrity-gates, Unit E).
+ *
+ * Empty when the stamps agree, when semantic search is disabled, and -
+ * structurally - whenever `integrity.embedding_abi` is `off`, so a
+ * consumer wired to this accessor cannot report anything while the
+ * operator has the gate off. A mismatch whose recorded side is `null`
+ * is an UNRECORDED field (a store predating the stamp), which is
+ * reported but never refused: an absent marker cannot tell an old
+ * store from a wrong one.
+ */
+ embeddingAbiMismatches(): ReadonlyArray<StampMismatch> {
+ return this.abiDrift;
+ }
+
+ /**
+ * Compare the recorded embedding ABI against this build's, under the
+ * operator's gate. Called on the READ open, which is where nothing
+ * checked before.
+ *
+ * Runs only when semantic search is enabled, because that is the only
+ * configuration that can reach `semanticTopK`; with it disabled the
+ * configured model and dimension are null and every comparison would
+ * be against nothing.
+ *
+ * The pure comparison runs FIRST and short-circuits, so the
+ * overwhelmingly common no-drift open never pays for a config read.
+ * When there is drift, {@link checkStamp} re-runs it under the
+ * resolved mode and remains the single authority on what `off`, `warn`
+ * and `fail` mean.
+ *
+ * It reports and refuses; it never rebuilds. `vec_version()` is not
+ * stable across environments, so two peers on different sqlite-vec
+ * builds each see a mismatch - an automatic rebuild here would loop
+ * across a synced vault, which is why the default is `warn` and why
+ * the remediation is a command the operator runs.
+ */
+ private resolveEmbeddingAbi(): void {
+ if (!this.config.semantic.enabled) return;
+ const recorded = recordedEmbeddingAbi((key) => this.getState(key));
+ const runtime = runtimeEmbeddingAbi(this.config, this.loadedVecVersion);
+ if (compareStamps(recorded, runtime).length === 0) return;
+ const mode = loadIntegrityConfigSafe(this.config.vault).embedding_abi;
+ const check = checkStamp(recorded, runtime, mode);
+ this.abiDrift = check.mismatches;
+ if (check.verdict !== STAMP_VERDICT.fail) return;
+ const drifted = contradictedAbiFields(check.mismatches);
+ if (drifted.length === 0) return;
+ throw new SearchError("EMBEDDING_DIMENSION_MISMATCH", formatEmbeddingAbiDrift(drifted));
+ }
+
schemaVersion(): number {
return readSchemaVersion(this.db);
}
@@ -549,14 +900,14 @@ export class Store {
/** Monotonic counter bumped on every index mutation; 0 if never set. */
indexRevision(): number {
- const raw = this.getState("index_revision");
+ const raw = this.getState(INDEX_REVISION_STATE_KEY);
const n = raw === null ? 0 : Number(raw);
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
}
/** Increment the index revision. Called after a mutating index run. */
bumpIndexRevision(): void {
- this.setState("index_revision", String(this.indexRevision() + 1));
+ this.setState(INDEX_REVISION_STATE_KEY, String(this.indexRevision() + 1));
}
/**
@@ -565,10 +916,10 @@ export class Store {
* embedding change or content reindex invalidates cached results.
*/
corpusGeneration(): string {
- const dimRaw = this.getState("embedding_dimension");
+ const dimRaw = this.getState(EMBEDDING_DIMENSION_STATE_KEY);
const dim = dimRaw === null ? null : Number(dimRaw);
return computeCorpusGeneration({
- embeddingModel: this.getState("embedding_model"),
+ embeddingModel: this.getState(EMBEDDING_MODEL_STATE_KEY),
embeddingDimension: dim !== null && Number.isFinite(dim) ? dim : null,
schemaVersion: LATEST_SCHEMA_VERSION,
indexRevision: this.indexRevision(),
@@ -986,8 +1337,8 @@ export class Store {
dimension: number | null,
prefixes?: EmbeddingPrefixPair,
): ModelChangeOutcome {
- const prevModel = this.getState("embedding_model");
- const prevDimRaw = this.getState("embedding_dimension");
+ const prevModel = this.getState(EMBEDDING_MODEL_STATE_KEY);
+ const prevDimRaw = this.getState(EMBEDDING_DIMENSION_STATE_KEY);
const prevDim = prevDimRaw === null ? null : Number(prevDimRaw);
const modelChanged = prevModel !== null && model !== null && prevModel !== model;
@@ -1018,8 +1369,12 @@ export class Store {
console.error(
`embedding model changed from ${prevModel}/${prevDim} to ${model}/${dimension}, embeddings cleared`,
);
- this.deleteState("embedding_model");
- this.deleteState("embedding_dimension");
+ this.deleteState(EMBEDDING_MODEL_STATE_KEY);
+ this.deleteState(EMBEDDING_DIMENSION_STATE_KEY);
+ // The recorded sqlite-vec version described the vectors that were
+ // just cleared, so it must not outlive them: leaving it would
+ // claim an ABI for storage that no longer holds any.
+ this.deleteState(EMBEDDING_VEC_VERSION_STATE_KEY);
} else if (prefixChanged) {
// Model/dimension unchanged: the prefix change alone triggers the clear.
this.clearEmbeddings();
@@ -1030,8 +1385,15 @@ export class Store {
);
}
- if (model !== null) this.setState("embedding_model", model);
- if (dimension !== null) this.setState("embedding_dimension", String(dimension));
+ if (model !== null) this.setState(EMBEDDING_MODEL_STATE_KEY, model);
+ if (dimension !== null) this.setState(EMBEDDING_DIMENSION_STATE_KEY, String(dimension));
+ // Same shape as the model and dimension above: recorded only when
+ // this build actually has a value. With the extension unavailable
+ // there is nothing to record, and writing a placeholder would be a
+ // claim about storage this process never touched.
+ if (this.loadedVecVersion !== null) {
+ this.setState(EMBEDDING_VEC_VERSION_STATE_KEY, this.loadedVecVersion);
+ }
if (prefixes !== undefined) {
this.setState(EMBEDDING_PREFIX_QUERY_STATE_KEY, prefixes.query);
this.setState(EMBEDDING_PREFIX_PASSAGE_STATE_KEY, prefixes.passage);
@@ -1092,6 +1454,38 @@ export class Store {
);
}
+ /**
+ * Vault-wide link-resolution census (context-integrity-gates, unit G).
+ *
+ * `unresolved` counts the link rows that carry a target path and that
+ * {@link RESOLVED_LINK_TARGET_SQL} - the SAME ladder
+ * {@link resolvedDocLinkPairs} follows - cannot resolve to any
+ * document. That is what "broken" means to a reader: a materialized
+ * id, a `<target>.md` exact match, and an unambiguous basename all
+ * count as resolved, and only what survives all three rungs is
+ * reported.
+ *
+ * The narrower `target_document_id IS NULL` predicate is NOT used
+ * here. It also fires on every basename-style `[[note]]`, which the
+ * ladder resolves perfectly well and which an Obsidian-shaped vault
+ * is written in - a count that rises on a healthy edit is a gate that
+ * gets bumped rather than obeyed.
+ *
+ * Index-backed on every rung: `idx_links_target_path` bounds the
+ * scan, `documents.path` is UNIQUE, and the basename rungs
+ * equality-join `idx_documents_basename`.
+ */
+ linkResolutionCounts(): LinkResolutionCounts {
+ const row = this.db
+ .query<{ total: number; unresolved: number | null }, []>(
+ "SELECT count(*) AS total, " +
+ `sum(CASE WHEN ${RESOLVED_LINK_TARGET_SQL} IS NULL THEN 1 ELSE 0 END) AS unresolved ` +
+ "FROM links l WHERE l.target_path IS NOT NULL",
+ )
+ .get();
+ return Object.freeze({ total: row?.total ?? 0, unresolved: row?.unresolved ?? 0 });
+ }
+
// ── doc aliases (v7, link-recall-intelligence) ─────────────────────────────
/**
@@ -1200,22 +1594,11 @@ export class Store {
resolvedDocLinkPairs(): Array<{ readonly source: number; readonly target: number }> {
const rows = this.db
.query<{ source: number; target: number | null }, []>(
- // Resolution ladder: materialized id, then `<target>.md` exact
- // (path is UNIQUE + indexed), then an UNAMBIGUOUS nested-basename
- // match. The basename branch equality-joins idx_documents_basename
- // and mirrors the old `SUBSTR(path) = '/'||target||'.md'` scan
- // exactly: a `/`-aligned basename suffix is precisely
- // `basename = target AND path is nested` (top-level `target.md`
- // has no leading slash and is owned by the exact branch above).
+ // The ladder itself lives in RESOLVED_LINK_TARGET_SQL, shared
+ // with `linkResolutionCounts` so the edges this yields and the
+ // rows that gate counts as broken are two views of one rule.
"SELECT DISTINCT l.source_document_id AS source, " +
- " COALESCE(" +
- " l.target_document_id, " +
- " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +
- " (SELECT d.id FROM documents d " +
- " WHERE d.basename = l.target_path AND instr(d.path, '/') > 0 " +
- " AND 1 = (SELECT COUNT(*) FROM documents d2 " +
- " WHERE d2.basename = l.target_path AND instr(d2.path, '/') > 0))" +
- " ) AS target " +
+ ` ${RESOLVED_LINK_TARGET_SQL} AS target ` +
"FROM links l WHERE l.target_path IS NOT NULL",
)
.all();
diff --git a/src/core/search/types.ts b/src/core/search/types.ts
index 5ab6516f..ec7115d7 100644
--- a/src/core/search/types.ts
+++ b/src/core/search/types.ts
@@ -4,6 +4,8 @@
* Anchored in docs/plans/2026-05-16-brain-search-design.md Β§12, Β§14.
*/
+import type { DegradationNotice } from "../integrity/degradation.ts";
+import type { StampMismatch } from "../integrity/stamp.ts";
import type { VaultIgnoreRule } from "../vault-scope/defaults.ts";
import type { DegreePredicate } from "./property-filter.ts";
import type {
@@ -273,6 +275,26 @@ export interface IndexStats {
readonly path: string;
readonly message: string;
}>;
+ /**
+ * Frontmatter lines this run's scanner could not express as a
+ * `key: value` pair or a block-list item, and therefore dropped
+ * (unit F). The `path` on each notice is vault-relative.
+ *
+ * A separate field rather than an entry in `errors` on purpose:
+ * `errors` means "this file did not index", drives the `N error(s)`
+ * count in the watch summary, and is rendered under an `errors:`
+ * heading by `o2b search index`. A dropped frontmatter line is none
+ * of those - the file indexes fine, it just lost a field. Folding it
+ * into `errors` would change the meaning of an existing field and the
+ * reported error count for vaults that index cleanly today.
+ *
+ * Scoped to the files this run actually read: the mtime/size fastpath
+ * skips unchanged documents, so an unchanged malformed file is
+ * reported by the run that last read it, not by every run. Use
+ * `--force` (or `o2b brain doctor`, which scans the Brain tree
+ * unconditionally) for a full sweep.
+ */
+ readonly frontmatterNotices: ReadonlyArray<DegradationNotice>;
/**
* Typed edges blocked by the schema pack's `link_constraints` during
* this run's materialization post-pass
@@ -360,6 +382,21 @@ export interface IndexStatusSnapshot {
readonly embeddingKeyPresent: boolean;
readonly lastIndexedAt: string | null;
readonly lastFullIndexAt: string | null;
+ /**
+ * Embedding-ABI fields whose recorded token no longer matches this
+ * build, as the GATED read open found them (context-integrity-gates,
+ * Unit E). Structurally empty whenever `integrity.embedding_abi` is
+ * `off`, which is what distinguishes this from the ungated
+ * {@link IndexCheckReport.embeddingAbi}: `search check` is a
+ * diagnostic the operator explicitly ran and refuses nothing, while
+ * status reports what the serving path actually enforced.
+ *
+ * The same condition also appears in {@link warnings} as one
+ * operator-facing line. This field is the machine-readable side of
+ * it, so an agent does not have to match on message text; both are
+ * emitted only when there is drift.
+ */
+ readonly embeddingAbi: ReadonlyArray<StampMismatch>;
readonly warnings: ReadonlyArray<string>;
}
@@ -372,6 +409,19 @@ export interface IndexCheckReport {
readonly embeddingKeyResolved: boolean;
readonly providerReachable: boolean | null;
readonly providerReason: string | null;
+ /**
+ * Embedding-ABI fields whose token recorded in the index no longer
+ * matches this build - model, dimension, or sqlite-vec version
+ * (context-integrity-gates, Unit E). Empty when they agree, when
+ * there is no index to read, or when semantic search is disabled;
+ * the CLI emits the field only when non-empty, so a matching store's
+ * output is byte-identical.
+ *
+ * `expected` is what the index recorded and `actual` what this build
+ * would produce; an `expected` of `null` is a store written before the
+ * field was stamped, which is reported and never treated as wrong.
+ */
+ readonly embeddingAbi: ReadonlyArray<StampMismatch>;
readonly warnings: ReadonlyArray<string>;
readonly fatal: ReadonlyArray<string>;
/**
@@ -424,6 +474,14 @@ export interface ExpandHitInput {
readonly rawLimit?: number;
/** Opaque pagination cursor returned as `next_cursor` by a prior call. */
readonly cursor?: string;
+ /**
+ * Owner-scope isolation (context-integrity-gates, Unit A). `chunkId`
+ * is a sequential integer, so an unchecked drill-down enumerates whole
+ * note bodies. Under a scope, another owner's chunk is refused with
+ * the SAME error an absent chunk produces - a distinguishable refusal
+ * would confirm the chunk exists. Omitted / blank filters nothing.
+ */
+ readonly agentScope?: string;
}
/**
diff --git a/src/core/vault.ts b/src/core/vault.ts
index e8694978..3dcb4951 100644
--- a/src/core/vault.ts
+++ b/src/core/vault.ts
@@ -5,6 +5,45 @@
* Mirrors `src/open_second_brain/vault.py`. Designed dependency-free; the small
* YAML-like emitter handles only the scalar/inline-array shapes that round-trip
* through Obsidian and the simple parser.
+ *
+ * ## Frontmatter diagnostics (unit F)
+ *
+ * The frontmatter reader is a line scanner, not a YAML parser, so it cannot
+ * fail β€” it drops what it does not understand, and the field simply never
+ * reaches the parsed map. That is how commit 426d06f8 (block-style lists
+ * dropped, producing spurious "missing field" errors in the doctor) stayed
+ * invisible until a human noticed the symptom.
+ *
+ * {@link parseFrontmatterTextWithNotices} is the diagnostic-carrying sibling:
+ * same map, same body, plus the notices. The rule for what counts as a
+ * dropped line β€” and what is legitimately skipped content that must stay
+ * silent β€” is stated on that function and is the authority for it.
+ * {@link parseFrontmatter} and {@link parseFrontmatterText} delegate to the
+ * siblings and discard the notices, so every call site not yet converted is
+ * byte-identical.
+ *
+ * ### Why most readers keep the two-tuple form
+ *
+ * Two consequences follow from the parser being a scanner rather than a
+ * YAML parser, and they are the reason the conversion is deliberately
+ * partial:
+ *
+ * 1. `parseFrontmatter` CANNOT throw. It reads inside its own `try` and
+ * everything after that is string work. Every `catch { … }` wrapped
+ * around nothing but a `parseFrontmatter` call is therefore
+ * unreachable, and the arm that "handles" the failure has never run.
+ * Those arms are removed where the `try` guards nothing else; the
+ * control flow is provably identical because the branch was dead.
+ * 2. A reader that returns a plain value - a list of recipes, a graph
+ * node, a ranked candidate set - has nowhere to put a notice.
+ * Widening its return type would create a channel with no consumer,
+ * which is the same silence in a new shape.
+ *
+ * The condition itself is not lost, because it is observable centrally:
+ * {@link listVaultPages}'s opt-in sink feeds `o2b brain doctor`, which
+ * sweeps the whole `Brain/` tree unconditionally, and the search indexer
+ * reports per-file notices through `IndexStats.frontmatterNotices`. A
+ * per-call channel at every reader would duplicate that, not add to it.
*/
import { createHash } from "node:crypto";
@@ -14,6 +53,11 @@ import { dirname, join, relative } from "node:path";
import { WIKILINK_TARGET_RE } from "./brain/wikilink.ts";
import { atomicCreateFileSyncExclusive, atomicWriteFileSync } from "./fs-atomic.ts";
import { stem } from "./fs-utils.ts";
+import {
+ DEGRADATION_CODE,
+ type DegradationNotice,
+ emitDegradationNotice,
+} from "./integrity/degradation.ts";
import type { FrontmatterMap, FrontmatterValue, VaultPage } from "./types.ts";
const FRONTMATTER_RE = /^---\s*\n([\s\S]*?)\n---\s*\n?/;
@@ -59,26 +103,132 @@ const DEFAULT_SKIP_FILES = ["index.md", "log.md"] as const;
* Only simple `key: value` lines are recognized β€” values are returned as strings,
* with surrounding quotes stripped. Inline arrays `[a, b]` are parsed into arrays
* of strings. Lines that don't match are silently skipped.
+ *
+ * Delegates to {@link parseFrontmatterWithNotices} and DISCARDS its
+ * diagnostics, so this signature and its output stay exactly as they were.
+ * Prefer the `WithNotices` sibling at any call site that has a report to
+ * carry the trace.
*/
export function parseFrontmatter(path: string): readonly [FrontmatterMap, string] {
- let text: string;
- try {
- text = readFileSync(path, "utf8");
- } catch {
- return [{}, ""];
- }
- return parseFrontmatterText(text);
+ const [metadata, body] = parseFrontmatterWithNotices(path);
+ return [metadata, body];
}
/**
* Same parse as {@link parseFrontmatter} but over an in-memory string,
* so a caller that already holds the file content (e.g. the search
* indexer) does not pay a second `readFileSync`.
+ *
+ * Delegates to {@link parseFrontmatterTextWithNotices} and discards its
+ * diagnostics β€” see {@link parseFrontmatter}.
*/
export function parseFrontmatterText(text: string): readonly [FrontmatterMap, string] {
+ const [metadata, body] = parseFrontmatterTextWithNotices(text);
+ return [metadata, body];
+}
+
+/** Site recorded on a notice when the caller names none. */
+const FRONTMATTER_SITE = "vault.parseFrontmatter";
+
+/**
+ * Longest run of a dropped source line reproduced in a notice `detail`.
+ * A notice renders as ONE line in doctor / index output, so an unbounded
+ * frontmatter line (a pasted blob, a minified payload) must not be able
+ * to dominate a report.
+ */
+const NOTICE_LINE_MAX = 120;
+const NOTICE_LINE_ELLIPSIS = "…";
+
+/** Attribution for the notices a frontmatter parse emits. */
+export interface FrontmatterNoticeOptions {
+ /**
+ * The subsystem to record as the notice `site`. Defaults to the parser
+ * itself; a converted call site passes its own name so a reader can
+ * tell WHICH walker hit the condition.
+ */
+ readonly site?: string;
+ /**
+ * The file the text came from, when the caller knows it. The path form
+ * ({@link parseFrontmatterWithNotices}) supplies this itself.
+ */
+ readonly path?: string;
+}
+
+/** `[metadata, body, notices]` β€” the diagnostic-carrying parse result. */
+export type FrontmatterParseWithNotices = readonly [
+ FrontmatterMap,
+ string,
+ ReadonlyArray<DegradationNotice>,
+];
+
+/**
+ * {@link parseFrontmatter} plus the diagnostics it would otherwise drop.
+ *
+ * An unreadable file yields one `frontmatter-unreadable` notice naming
+ * the path, and the same `[{}, ""]` result the two-tuple form has always
+ * returned β€” the read failure is reported, never raised.
+ */
+export function parseFrontmatterWithNotices(
+ path: string,
+ opts: FrontmatterNoticeOptions = {},
+): FrontmatterParseWithNotices {
+ const site = opts.site ?? FRONTMATTER_SITE;
+ let text: string;
+ try {
+ text = readFileSync(path, "utf8");
+ } catch (err) {
+ const notices: DegradationNotice[] = [];
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.frontmatterUnreadable,
+ site,
+ path,
+ detail: `frontmatter read failed: ${err instanceof Error ? err.message : String(err)}`,
+ });
+ return [{}, "", notices];
+ }
+ return parseFrontmatterTextWithNotices(text, { site, path });
+}
+
+/**
+ * {@link parseFrontmatterText} plus the diagnostics it would otherwise
+ * drop. The map and body are byte-identical to the two-tuple form; the
+ * third element is the new trace.
+ *
+ * ## What counts as a DROPPED line
+ *
+ * The scanner is line-based, not a YAML parser, so "unsupported grammar"
+ * has to be defined structurally. A line inside the `---` block is
+ * CONSUMED when it is one of:
+ *
+ * - a `key: value` pair (`KEY_VALUE_RE`), including the empty-value
+ * form that opens a block sequence or records a null scalar;
+ * - a dash item (`DASH_ITEM_RE`) while a block sequence is open.
+ *
+ * It is legitimately SKIPPED, with no notice, when it is:
+ *
+ * - blank, or whitespace-only β€” structural separation the format
+ * expects, and a notice per blank line would be noise, not signal;
+ * - a `#` comment β€” content the format explicitly discards.
+ *
+ * Everything else is a DROP and emits exactly one
+ * `frontmatter-line-dropped` notice carrying the 1-based line number
+ * within the block and the offending text. That covers the two shapes
+ * seen in the field: grammar the scanner has no branch for (a folded or
+ * literal block scalar, an indented nested mapping, a `-foo` string that
+ * is not a list item) and a dash item with no open key to land in.
+ *
+ * Emitting a notice never changes the parse. A dropped line is still
+ * dropped, exactly as before; only the trace is new.
+ */
+export function parseFrontmatterTextWithNotices(
+ text: string,
+ opts: FrontmatterNoticeOptions = {},
+): FrontmatterParseWithNotices {
+ const notices: DegradationNotice[] = [];
+ const site = opts.site ?? FRONTMATTER_SITE;
const match = FRONTMATTER_RE.exec(text);
if (!match) {
- return [{}, text.trim()];
+ return [{}, text.trim(), notices];
}
const fmBlock = match[1]!;
@@ -110,7 +260,15 @@ export function parseFrontmatterText(text: string): readonly [FrontmatterMap, st
blockKey = null;
const kv = KEY_VALUE_RE.exec(line);
- if (!kv) continue;
+ if (!kv) {
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.frontmatterLineDropped,
+ site,
+ ...(opts.path !== undefined ? { path: opts.path } : {}),
+ detail: `frontmatter line ${i + 1} is not a supported key/value or list item: ${clipNoticeLine(line)}`,
+ });
+ continue;
+ }
const key = kv[1]!;
let value = kv[2]!.trim();
@@ -146,7 +304,14 @@ export function parseFrontmatterText(text: string): readonly [FrontmatterMap, st
metadata[key] = stripQuotes(value);
}
- return [metadata, body];
+ return [metadata, body, notices];
+}
+
+/** Bound one source line to {@link NOTICE_LINE_MAX} for a one-line notice. */
+function clipNoticeLine(line: string): string {
+ return line.length <= NOTICE_LINE_MAX
+ ? line
+ : line.slice(0, NOTICE_LINE_MAX) + NOTICE_LINE_ELLIPSIS;
}
/**
@@ -314,23 +479,51 @@ export function extractWikilinks(content: string): string[] {
export interface ListVaultPagesOptions {
readonly skipDirs?: ReadonlyArray<string>;
readonly skipFiles?: ReadonlyArray<string>;
+ /**
+ * Opt-in diagnostic sink (unit F). When supplied, the walk appends a
+ * notice for every directory it could not read and every frontmatter
+ * line it dropped, each carrying the absolute path it happened to.
+ *
+ * The sink is OPT-IN rather than a widened return type so a caller
+ * that has nowhere to report stays byte-identical and pays nothing.
+ * The walk's control flow does not depend on it: an unreadable
+ * subtree is skipped and a page with a dropped line is still listed,
+ * exactly as before.
+ */
+ readonly notices?: DegradationNotice[];
+ /** Site recorded on the notices; defaults to `vault.listVaultPages`. */
+ readonly site?: string;
}
+const LIST_VAULT_PAGES_SITE = "vault.listVaultPages";
+
/**
* Walk the vault and return every Markdown page with parsed frontmatter
* metadata. Pages are sorted by title (case-insensitive). Excluded dirs/files
* mirror the Python defaults.
+ *
+ * Pass `opts.notices` to collect what the walk discarded β€” see
+ * {@link ListVaultPagesOptions}.
*/
export function listVaultPages(vaultDir: string, opts: ListVaultPagesOptions = {}): VaultPage[] {
const skipDirs = new Set(opts.skipDirs ?? DEFAULT_SKIP_DIRS);
const skipFiles = new Set((opts.skipFiles ?? DEFAULT_SKIP_FILES).map((f) => f.toLowerCase()));
const pages: VaultPage[] = [];
- walk(vaultDir, vaultDir, skipDirs, skipFiles, pages);
+ walk(vaultDir, vaultDir, skipDirs, skipFiles, pages, {
+ sink: opts.notices,
+ site: opts.site ?? LIST_VAULT_PAGES_SITE,
+ });
pages.sort((a, b) => a.title.toLowerCase().localeCompare(b.title.toLowerCase()));
return pages;
}
+/** Where {@link walk} reports what it discarded, and under which name. */
+interface WalkNoticeSink {
+ readonly sink: DegradationNotice[] | undefined;
+ readonly site: string;
+}
+
/**
* Cheap basename-only walker over a vault directory. Returns the set
* of `.md` basenames (without extension) β€” no frontmatter parsing.
@@ -386,18 +579,30 @@ function walk(
skipDirs: Set<string>,
skipFiles: Set<string>,
out: VaultPage[],
+ notices: WalkNoticeSink,
): void {
let entries;
try {
entries = readdirSync(dir, { withFileTypes: true });
- } catch {
+ } catch (err) {
+ // Unit F: an unreadable directory used to make an entire subtree
+ // vanish from the listing with no trace. The walk still returns
+ // (fail-soft, as before); the branch is now named.
+ if (notices.sink !== undefined) {
+ emitDegradationNotice(notices.sink, {
+ code: DEGRADATION_CODE.vaultWalkEntrySkipped,
+ site: notices.site,
+ path: dir,
+ detail: `directory listing failed: ${err instanceof Error ? err.message : String(err)}`,
+ });
+ }
return;
}
for (const entry of entries) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name)) continue;
- walk(root, full, skipDirs, skipFiles, out);
+ walk(root, full, skipDirs, skipFiles, out, notices);
continue;
}
if (!entry.isFile()) continue;
@@ -406,12 +611,13 @@ function walk(
const rel = relative(root, full);
const parts = rel.split(/[\\/]/);
if (parts.some((p) => skipDirs.has(p))) continue;
- let meta: FrontmatterMap;
- try {
- [meta] = parseFrontmatter(full);
- } catch {
- continue;
- }
+ // The former `catch { continue }` here was unreachable: the parser
+ // is a line scanner over a string it read inside its own try, so it
+ // cannot throw. What it CAN do is drop a line or fail the read, and
+ // both now reach the sink instead of vanishing. The page is still
+ // listed either way - identical control flow.
+ const [meta, , pageNotices] = parseFrontmatterWithNotices(full, { site: notices.site });
+ if (notices.sink !== undefined) notices.sink.push(...pageNotices);
const titleVal = meta["title"];
const title = typeof titleVal === "string" && titleVal ? titleVal : stem(entry.name);
out.push({ title, path: full, metadata: meta });
diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.ts
index 327786c6..22f121cb 100644
--- a/src/mcp/brain/brief-tools.ts
+++ b/src/mcp/brain/brief-tools.ts
@@ -29,7 +29,13 @@ import { captureReportDelta } from "../../core/brain/report-snapshot.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
-import { coerceIsoDate, coerceFormat } from "../coerce.ts";
+import {
+ AGENT_SCOPE_ARG_NAME,
+ AGENT_SCOPE_SCHEMA,
+ coerceAgentScope,
+ coerceIsoDate,
+ coerceFormat,
+} from "../coerce.ts";
import {
coerceIsoTimestampOrDate,
coerceNonNegativeInteger,
@@ -56,9 +62,11 @@ async function toolBrainMorningBrief(
args["max_total_chars"],
);
const now = new Date();
+ const agentScope = coerceAgentScope(ctx, args, true);
const brief = buildMorningBrief(ctx.vault, {
now,
topK,
+ ...(agentScope !== undefined ? { agentScope } : {}),
lookbackDays,
...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
@@ -112,11 +120,13 @@ async function toolBrainDigest(
// snapshot render, and the snapshot date key all describe the same
// window even when the caller omitted `until`.
const effectiveUntil = until ?? new Date();
+ const agentScope = coerceAgentScope(ctx, args, true);
const result = renderDigest(ctx.vault, {
...(since ? { since } : {}),
until: effectiveUntil,
format,
linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
+ ...(agentScope !== undefined ? { agentScope } : {}),
});
const envelope: Record<string, unknown> = {
@@ -136,6 +146,7 @@ async function toolBrainDigest(
until: effectiveUntil,
format: "json",
linkOutputFormat: resolveLinkOutputFormat(ctx.configPath ?? undefined),
+ ...(agentScope !== undefined ? { agentScope } : {}),
}).content;
let parsedSnapshot: unknown = null;
try {
@@ -404,7 +415,40 @@ const BRIEF_VIEW_HANDLERS: Readonly<
today: toolBrainToday,
});
+/**
+ * The views whose builders thread `agent_scope` through to the ownership
+ * predicate. `agent_scope` is declared once for the whole tool, so the
+ * other five would ACCEPT the argument and discard it - handing a caller
+ * who asked to be isolated another owner's preference ids
+ * (`weekly.retired[].prefId`, `weekly.statusTransitions[].prefId`,
+ * `operator`'s ranked actions) while believing it was scoped. Silently
+ * ignoring an argument a tool accepts is this wave's anti-pattern, so the
+ * views that cannot honour it REFUSE it instead
+ * (context-integrity-gates, A6).
+ *
+ * Threading it through the remaining five is the better end state; it
+ * needs an ownership predicate inside `weekly-brief`, `monthly-review`,
+ * `daily-brief`, `operator-summary` and `today-dashboard`, which is a
+ * change to those builders rather than to this dispatcher.
+ */
+const AGENT_SCOPE_VIEWS: ReadonlySet<string> = new Set(["morning", "digest"]);
+
async function toolBrainBrief(ctx: ServerContext, args: Record<string, unknown>): Promise<unknown> {
+ const view = typeof args["view"] === "string" ? args["view"] : "";
+ const scopeSupplied =
+ AGENT_SCOPE_ARG_NAME in args &&
+ args[AGENT_SCOPE_ARG_NAME] !== undefined &&
+ args[AGENT_SCOPE_ARG_NAME] !== null;
+ // Only an EXPLICIT argument is refused: the gated surfaces default their
+ // scope from `ServerContext.agentName`, and refusing that would make the
+ // tool unusable for every client that never passes the argument.
+ if (scopeSupplied && view in BRIEF_VIEW_HANDLERS && !AGENT_SCOPE_VIEWS.has(view)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_brief view=${view} cannot honour '${AGENT_SCOPE_ARG_NAME}'; ` +
+ `owner scoping is supported by view=${[...AGENT_SCOPE_VIEWS].join(", view=")}`,
+ );
+ }
return localizeEnvelope(ctx, await dispatchByView(BRIEF_VIEW_HANDLERS, ctx, args));
}
@@ -484,6 +528,16 @@ export const BRIEF_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
minimum: 0,
description: "view=operator: cap on ranked actions (default 5).",
},
+ // The one place this argument's shared description is overridden,
+ // and only to name WHICH views honour it - a caller cannot learn
+ // that from a tool-wide declaration, and learning it from a
+ // rejection after the fact is worse. Kept inside the registry
+ // guard's 160-character property-description cap.
+ agent_scope: {
+ ...AGENT_SCOPE_SCHEMA,
+ description:
+ "Optional agent-ownership scope; ownerless memories always match. Accepted by view=morning and view=digest only; other views reject it, never ignore it.",
+ },
},
required: ["view"],
additionalProperties: false,
diff --git a/src/mcp/brain/context-tools.ts b/src/mcp/brain/context-tools.ts
index 988eefd1..f5eae8fc 100644
--- a/src/mcp/brain/context-tools.ts
+++ b/src/mcp/brain/context-tools.ts
@@ -9,7 +9,12 @@
import { existsSync, readFileSync } from "node:fs";
import { resolveAgentName } from "../../core/config.ts";
import { brainActivePath, brainDirs } from "../../core/brain/paths.ts";
-import { regenerateActive, type RegenerateActiveResult } from "../../core/brain/active.ts";
+import {
+ regenerateActive,
+ renderActive,
+ type RegenerateActiveResult,
+} from "../../core/brain/active.ts";
+import { resolveOwnerScopeDelivery } from "../../core/brain/preferences-collect.ts";
import { parseFrontmatter } from "../../core/vault.ts";
import { readVaultInstructionFile } from "../../core/brain/vault-instruction-file.ts";
import { normalizeAgentArgument } from "../../core/agent-identity.ts";
@@ -320,6 +325,12 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unkn
let counts: BrainContextCounts = EMPTY_CONTEXT_COUNTS;
let error: string | undefined;
try {
+ // The SHARED file is regenerated unscoped, always. `active.md` is one
+ // file for the whole vault - injected into every agent's SessionStart
+ // by `hooks/active-inject.ts` and regenerated unscoped by the
+ // `osb://preferences/active` resource - so narrowing the WRITE to this
+ // caller would make it thrash and could drop an agent's own memories
+ // from its session start (context-integrity-gates, A3).
counts = regenerateActive(ctx.vault).counts;
} catch (err) {
error = (err as Error)?.message ?? String(err);
@@ -346,6 +357,26 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unkn
generatedAt = null;
}
}
+ // Owner-scope isolation (context-integrity-gates, Unit A) applies to
+ // what this ONE caller is handed, not to what is on disk. This surface
+ // takes no arguments, so `ServerContext.agentName` is its only source of
+ // identity, and the gate decides whether it narrows: `enforcedScope` is
+ // non-null only under `fail`, so the branch is dead on a default vault
+ // and the delivered bytes stay the file's own. The re-render reuses the
+ // stamp already on disk so the scoped view names the same generation the
+ // shared file does.
+ if (!error) {
+ const delivery = resolveOwnerScopeDelivery(ctx.vault, ctx.agentName);
+ if (delivery.enforcedScope !== null) {
+ const scoped = renderActive(ctx.vault, {
+ agentScope: delivery.enforcedScope,
+ ...(generatedAt !== null ? { generatedAt } : {}),
+ });
+ content = scoped.document;
+ counts = scoped.counts;
+ }
+ }
+
content = appendPinnedToContextContent(content, pinned.content);
// Optional vault-root instruction file (v0.10.17). Absent file =
diff --git a/src/mcp/brain/health-tools.ts b/src/mcp/brain/health-tools.ts
index ff5172de..f84457fb 100644
--- a/src/mcp/brain/health-tools.ts
+++ b/src/mcp/brain/health-tools.ts
@@ -92,6 +92,26 @@ async function toolBrainDoctor(
lines: w.lines,
ceiling: w.ceiling,
})),
+ // context-integrity-gates: the third diagnostic stream. Frontmatter
+ // lines the scanner dropped, lineage-ledger findings, an unmarked
+ // vault root and stale writer locks all land in `uncertain`, and
+ // until now the CLI was its only reader - so an agent driving the
+ // doctor over MCP could not see any of them. A named failure no
+ // consumer reads is still a silent failure.
+ //
+ // Omitted when empty, mirroring the CLI and `runDoctor` itself, so a
+ // 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: result.uncertain.map((u) => ({
+ code: u.code,
+ ...(u.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, u.path) } : {}),
+ message: u.message,
+ })),
+ }
+ : {}),
};
}
diff --git a/src/mcp/brain/hygiene-tools.ts b/src/mcp/brain/hygiene-tools.ts
index d9fec466..96041af7 100644
--- a/src/mcp/brain/hygiene-tools.ts
+++ b/src/mcp/brain/hygiene-tools.ts
@@ -30,6 +30,12 @@ import {
type HygieneScanReport,
} from "../../core/brain/hygiene/types.ts";
import { executeRecompile, planRecompile } from "../../core/brain/recompile.ts";
+import { resolveSearchConfig } from "../../core/search/index.ts";
+import {
+ DANGLING_LINK_DEFINITION,
+ measureFromIndex,
+ type LinkRatchetMeasurement,
+} from "../../core/search/link-ratchet.ts";
import { coerceBool } from "../coerce.ts";
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
@@ -84,6 +90,59 @@ function findingView(vault: string, finding: HygieneFinding): Record<string, unk
};
}
+/**
+ * Vault-wide link integrity, reported beside the detector findings
+ * (context-integrity-gates, unit G).
+ *
+ * An ADDITIVE top-level key, not a fifth detector: `HYGIENE_DETECTOR_IDS`
+ * is a closed tuple validated in three places including this tool's own
+ * input-schema enum, so extending it would change the tool contract.
+ *
+ * `dangling` counts the link rows the READ-TIME resolution ladder
+ * leaves unresolved - broken as the reader of this vault experiences
+ * it, not as the raw `target_document_id` column reports it. The
+ * `definition` key names the rule that produced the number.
+ *
+ * Read-only over the index the operator's searches already use, and
+ * refused unless that index records a full resolution pass - so
+ * `measured: false` with a reason is a real outcome here, never
+ * flattened into a zero.
+ */
+async function linkIntegrityView(ctx: ServerContext): Promise<Record<string, unknown>> {
+ let measurement: LinkRatchetMeasurement;
+ try {
+ measurement = await measureFromIndex(
+ resolveSearchConfig({
+ vault: ctx.vault,
+ ...(ctx.configPath ? { configPath: ctx.configPath } : {}),
+ }),
+ );
+ } catch (e) {
+ // A read-only scan is never failed by the reporting layer.
+ return {
+ definition: DANGLING_LINK_DEFINITION,
+ measured: false,
+ reason: "index-unreadable",
+ detail: e instanceof Error ? e.message : String(e),
+ };
+ }
+ if (!measurement.measurable) {
+ return {
+ definition: measurement.definition,
+ measured: false,
+ reason: measurement.reason,
+ detail: measurement.detail,
+ };
+ }
+ return {
+ definition: measurement.definition,
+ measured: true,
+ dangling: measurement.dangling,
+ links: measurement.links,
+ documents: measurement.documents,
+ };
+}
+
async function toolBrainHygiene(
ctx: ServerContext,
args: Record<string, unknown>,
@@ -135,6 +194,7 @@ async function toolBrainHygiene(
counts: report.counts,
findings: report.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.ts
index 401c8594..1833df75 100644
--- a/src/mcp/brain/ingest-tools.ts
+++ b/src/mcp/brain/ingest-tools.ts
@@ -21,6 +21,8 @@ import {
type SourceCleanupPlan,
} from "../../core/brain/source-cleanup.ts";
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 { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
@@ -124,10 +126,22 @@ async function toolBrainSearchBySource(
): Promise<Record<string, unknown>> {
const sourceFile = coerceStr(args, "source_file", true)!;
const hits = searchBySourceFile(ctx.vault, sourceFile);
+ // Owner-scope isolation (context-integrity-gates, Unit A). Every entry
+ // names a Brain page, so the ownership rule applies through the same
+ // path-based resolver the ranked search path uses - including its
+ // 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 cache: FrontmatterCache = new Map();
+ const visible =
+ scope === null
+ ? hits
+ : hits.filter((entry) => isPathOwnerVisible(ctx.vault, entry.path, scope, cache));
return {
source_file: sourceFile,
- total: hits.length,
- entries: hits.map(serializeEntry),
+ total: visible.length,
+ entries: visible.map(serializeEntry),
};
}
@@ -322,6 +336,11 @@ export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
type: "string",
description: "Exact source identity to trace: a vault-relative path or a URL.",
},
+ agent_scope: {
+ type: "string",
+ description:
+ "Optional owner scope: a derived page declaring an `owner:` is returned only to its own scope; ownerless pages always match. Absent = no filtering.",
+ },
},
required: ["source_file"],
additionalProperties: false,
diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.ts
index 98ea511c..dd8768c7 100644
--- a/src/mcp/brain/knowledge-tools.ts
+++ b/src/mcp/brain/knowledge-tools.ts
@@ -61,7 +61,7 @@ import {
import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
-import { coerceStr, coerceBool } from "../coerce.ts";
+import { AGENT_SCOPE_SCHEMA, coerceAgentScope, coerceStr, coerceBool } from "../coerce.ts";
import { coercePositiveInteger } from "./shared.ts";
/** Forward-looking projection envelope; read-only fold. */
@@ -347,7 +347,12 @@ async function toolBrainDeepSynthesis(
vault: ctx.vault,
configPath: ctx.configPath ?? undefined,
});
- const report = await deepSynthesis(searchConfig, topic, { now, limit });
+ const agentScope = coerceAgentScope(ctx, args, false);
+ const report = await deepSynthesis(searchConfig, topic, {
+ now,
+ limit,
+ ...(agentScope !== undefined ? { agentScope } : {}),
+ });
let triggersCreated: number | undefined;
if (enqueue) {
const result = createTriggers(ctx.vault, synthesisCandidates(report), {
@@ -831,6 +836,7 @@ export const KNOWLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
type: "boolean",
description: "Enqueue contradiction/gap findings into the trigger queue.",
},
+ agent_scope: AGENT_SCOPE_SCHEMA,
},
required: ["topic"],
additionalProperties: false,
diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.ts
index fde66a23..aa87a472 100644
--- a/src/mcp/brain/pack-tools.ts
+++ b/src/mcp/brain/pack-tools.ts
@@ -24,12 +24,16 @@ import {
import { loadBrainConfig } from "../../core/brain/policy.ts";
import { buildPreCompressPack } from "../../core/brain/pre-compress-pack.ts";
import {
+ assertContextReceiptWindowBound,
+ CONTEXT_RECEIPT_TRIGGERS,
getContextReceipt,
isContextReceiptTrigger,
listContextReceipts,
summarizeContextReceipt,
+ summarizeContextReceiptSession,
type ContextReceiptOptions,
} from "../../core/brain/context-receipts.ts";
+import { observedReuseRates } from "../../core/brain/observed-use.ts";
import {
diffContextPreset,
getContextPreset,
@@ -43,7 +47,13 @@ import { BRAIN_LOG_EVENT_KIND_SET, type BrainLogEventKind } from "../../core/bra
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
-import { coerceStr, coerceStrList, coerceBool } from "../coerce.ts";
+import {
+ AGENT_SCOPE_SCHEMA,
+ coerceAgentScope,
+ coerceStr,
+ coerceStrList,
+ coerceBool,
+} from "../coerce.ts";
import {
coercePositiveInteger,
optionalStringArg,
@@ -115,8 +125,10 @@ async function toolBrainContextPack(
// gated on the density_ranking_context_pack config key (default off)
// so the default pack stays byte-identical to the tier β†’ recency order.
const densityRanking = resolveDensityRankingContextPack(ctx.configPath ?? undefined);
+ const agentScope = coerceAgentScope(ctx, args, true);
const report = packContext(ctx.vault, {
maxTokens,
+ ...(agentScope !== undefined ? { agentScope } : {}),
...(densityRanking ? { densityRanking: true } : {}),
...(sessionFocus !== null ? { sessionFocus } : {}),
...(query ? { query } : {}),
@@ -225,7 +237,7 @@ async function toolBrainContextReceipts(
if (trigger !== undefined && !isContextReceiptTrigger(trigger)) {
throw new MCPError(
INVALID_PARAMS,
- "brain_context_receipts: trigger must be context_pack or pre_compress",
+ `brain_context_receipts: trigger must be one of ${CONTEXT_RECEIPT_TRIGGERS.join(", ")}`,
);
}
const host = optionalStringArg("brain_context_receipts", args, "host");
@@ -265,7 +277,129 @@ async function toolBrainContextReceipts(
};
}
- throw new MCPError(INVALID_PARAMS, "brain_context_receipts: operation must be list or show");
+ if (operation === "summary") return summarizeReceipts(ctx, args);
+
+ throw new MCPError(
+ INVALID_PARAMS,
+ "brain_context_receipts: operation must be list, show, or summary",
+ );
+}
+
+/**
+ * Session-scoped retrieval report (context-integrity-gates, Unit I): a
+ * read-only fold over receipts that already exist, joined to the
+ * observed-use verdicts for the same window.
+ *
+ * A window with no receipts reports exactly that. Receipt emission is
+ * opt-in, so counters of zero would describe a mechanism nobody enabled
+ * rather than a retrieval finding.
+ */
+async function summarizeReceipts(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const trigger = optionalStringArg("brain_context_receipts", args, "trigger");
+ if (trigger !== undefined && !isContextReceiptTrigger(trigger)) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_context_receipts: trigger must be one of ${CONTEXT_RECEIPT_TRIGGERS.join(", ")}`,
+ );
+ }
+ const host = optionalStringArg("brain_context_receipts", args, "host");
+ const sessionId = optionalStringArg("brain_context_receipts", args, "session_id");
+ const since = optionalStringArg("brain_context_receipts", args, "since");
+ const until = optionalStringArg("brain_context_receipts", args, "until");
+ // Both bounds are compared LEXICALLY against stored `createdAt`
+ // strings. An uncomparable value (`"yesterday"`, a local-time stamp,
+ // `2026-13-01`) silently filters the window to empty and the fold
+ // reports "no receipts recorded for this filter" - "nothing happened"
+ // for what is really malformed input. Refuse it instead.
+ for (const [field, value] of [
+ ["since", since],
+ ["until", until],
+ ] as const) {
+ try {
+ assertContextReceiptWindowBound(field, value);
+ } catch (err) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_context_receipts: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ }
+ }
+ const maxReceipts = coercePositiveInteger(
+ "brain_context_receipts",
+ "max_receipts",
+ args["max_receipts"],
+ );
+ const limit = coercePositiveInteger("brain_context_receipts", "limit", args["limit"]);
+
+ const window = {
+ ...(trigger !== undefined ? { trigger } : {}),
+ ...(host !== undefined ? { host } : {}),
+ ...(sessionId !== undefined ? { sessionId } : {}),
+ ...(since !== undefined ? { since } : {}),
+ ...(until !== undefined ? { until } : {}),
+ };
+ const fold = summarizeContextReceiptSession(ctx.vault, {
+ ...window,
+ ...(maxReceipts !== undefined ? { maxReceipts } : {}),
+ });
+ if (!fold.recorded) {
+ return {
+ vault_path: ctx.vault,
+ recorded: false,
+ max_receipts: fold.max_receipts,
+ note: "no receipts recorded for this filter; receipt emission is opt-in per call",
+ };
+ }
+
+ // Observed use is folded over the SAME window, so a per-item verdict
+ // describes this session rather than the artifact's lifetime rate.
+ const reuse = observedReuseRates(ctx.vault, {
+ ...(sessionId !== undefined ? { sessionId } : {}),
+ ...(since !== undefined ? { since } : {}),
+ ...(until !== undefined ? { until } : {}),
+ });
+ const items = limit === undefined ? fold.items : fold.items.slice(0, limit);
+
+ return {
+ vault_path: ctx.vault,
+ recorded: true,
+ receipt_count: fold.receipt_count,
+ item_total: fold.item_total,
+ distinct_items: fold.distinct_items,
+ withheld_receipts: fold.withheld_receipts,
+ // Receipts that inflate `receipt_count` and contribute no items: an
+ // injection that degraded to cache records `items: []` by design,
+ // and a receipt with no item array at all cannot be unfolded. Both
+ // used to vanish into the gap between `receipt_count` and
+ // `item_total`.
+ empty_receipts: fold.empty_receipts,
+ malformed_receipts: fold.malformed_receipts,
+ truncated: fold.truncated,
+ max_receipts: fold.max_receipts,
+ items: items.map((item) => {
+ const observed = reuse.get(item.path ?? item.id);
+ return {
+ id: item.id,
+ ...(item.path !== undefined ? { path: item.path } : {}),
+ injections: item.injections,
+ tokens: item.tokens,
+ ...(observed !== undefined
+ ? {
+ observed: {
+ used: observed.used,
+ ignored: observed.ignored,
+ contradicted: observed.contradicted,
+ total: observed.total,
+ score: observed.score,
+ },
+ }
+ : {}),
+ };
+ }),
+ };
}
// ----- brain_event_trace ---------------------------------------------------
@@ -407,8 +541,10 @@ async function toolBrainPreCompressPack(
);
const receipt = receiptOptionsFromArgs("brain_pre_compress_pack", args, "pre_compress", "mcp");
const telemetry = telemetryOptionsFromArgs("brain_pre_compress_pack", args, "mcp");
+ const agentScope = coerceAgentScope(ctx, args, true);
const pack = buildPreCompressPack(ctx.vault, {
topK,
+ ...(agentScope !== undefined ? { agentScope } : {}),
...(maxCharsPerMemory !== undefined ? { maxCharsPerMemory } : {}),
...(maxTotalChars !== undefined ? { maxTotalChars } : {}),
...(configuredDegradation(ctx.vault) !== undefined
@@ -490,11 +626,13 @@ async function toolBrainAnticipatoryContext(
} catch {
// defaults apply; a broken config never blocks a read
}
+ const anticipatoryScope = coerceAgentScope(ctx, args, true);
const now = new Date();
if (coerceBool(args, "refresh") === true) {
const signal = coerceStr(args, "signal_text");
refreshAnticipatoryCache(ctx.vault, {
sessionId,
+ ...(anticipatoryScope !== undefined ? { agentScope: anticipatoryScope } : {}),
...(typeof signal === "string" && signal.trim() !== "" ? { signalText: signal } : {}),
now,
...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
@@ -504,6 +642,7 @@ async function toolBrainAnticipatoryContext(
const result = readAnticipatoryContext(ctx.vault, {
sessionId,
now,
+ ...(anticipatoryScope !== undefined ? { agentScope: anticipatoryScope } : {}),
...(ttlSeconds !== undefined ? { ttlSeconds } : {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
});
@@ -511,6 +650,10 @@ async function toolBrainAnticipatoryContext(
cache_state: result.cache_state,
root_session_id: result.root_session_id,
...(result.generated_at !== undefined ? { generated_at: result.generated_at } : {}),
+ // Present only when a fresh-by-the-clock entry was refused on its
+ // provenance stamp or validity window, so an ordinary miss stays
+ // byte-identical (context-integrity-gates, Unit B).
+ ...(result.cache_refusal !== undefined ? { cache_refusal: result.cache_refusal } : {}),
items: result.context.items.map((item) => ({
id: item.id,
tier: item.tier,
@@ -612,6 +755,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
type: "string",
description: "Optional turn id recorded on emitted telemetry.",
},
+ agent_scope: AGENT_SCOPE_SCHEMA,
},
required: ["max_tokens"],
additionalProperties: false,
@@ -621,14 +765,15 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
{
name: "brain_context_receipts",
description:
- "List context receipt summaries or show one full receipt by id. Receipts are append-only continuity records emitted by opt-in context injection callers. Read-only.",
+ "List context receipt summaries, show one full receipt by id, or fold a window into a retrieval summary (distinct items, per-item injection frequency, token cost, observed use). Receipts are append-only continuity records emitted by opt-in injection callers. Read-only.",
inputSchema: {
type: "object",
properties: {
operation: {
type: "string",
- enum: ["list", "show"],
- description: "Use list for summaries, show for one full receipt by id.",
+ enum: ["list", "show", "summary"],
+ description:
+ "list returns summaries, show returns one full receipt by id, summary folds a window into a retrieval report.",
},
id: {
type: "string",
@@ -636,7 +781,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
trigger: {
type: "string",
- enum: ["context_pack", "pre_compress"],
+ enum: [...CONTEXT_RECEIPT_TRIGGERS],
description: "Optional list filter by injection trigger.",
},
host: {
@@ -645,12 +790,29 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
session_id: {
type: "string",
- description: "Optional list filter by recorded session id.",
+ description: "Optional list/summary filter by recorded session id.",
+ },
+ since: {
+ type: "string",
+ description:
+ "Summary only: inclusive lower bound on receipt createdAt. Canonical UTC only (YYYY-MM-DDTHH:MM:SS[.sss]Z); anything else is rejected, not filtered to empty.",
+ },
+ until: {
+ type: "string",
+ description:
+ "Summary only: inclusive upper bound on receipt createdAt. Canonical UTC only (YYYY-MM-DDTHH:MM:SS[.sss]Z); anything else is rejected, not filtered to empty.",
+ },
+ max_receipts: {
+ type: "integer",
+ minimum: 1,
+ description:
+ "Summary only: how many matching receipts are AGGREGATED (a fold bound, not a read bound - narrow the read with since/until). Exceeding it sets `truncated`.",
},
limit: {
type: "integer",
minimum: 1,
- description: "Optional maximum number of summaries to return.",
+ description:
+ "Maximum summaries to return (list) or item rows to return (summary; `distinct_items` still reports the full count).",
},
},
required: ["operation"],
@@ -787,6 +949,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
type: "string",
description: "Optional turn id recorded on emitted telemetry.",
},
+ agent_scope: AGENT_SCOPE_SCHEMA,
},
additionalProperties: false,
},
@@ -857,6 +1020,7 @@ export const PACK_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
type: "string",
description: "Latest prompt/signal text steering the refreshed bundle.",
},
+ agent_scope: AGENT_SCOPE_SCHEMA,
},
required: ["session_id"],
additionalProperties: false,
diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.ts
index 77b12ae1..390d7829 100644
--- a/src/mcp/brain/query-tools.ts
+++ b/src/mcp/brain/query-tools.ts
@@ -114,9 +114,10 @@ async function toolBrainQuery(
const res = queryByPreference(ctx.vault, preference);
// Fail closed: an owner-private fact outside the requested scope is
// indistinguishable from absent, so it cannot leak across owners.
- // Only active preferences carry an owner; a retired record is shared.
- const prefOwner =
- res.preference.kind === "brain-preference" ? res.preference.owner : undefined;
+ // Retirement KEEPS ownership (context-integrity-gates, A7), so a
+ // retired record is read through the same predicate as an active
+ // one - retiring a memory must not publish it.
+ const prefOwner = res.preference.owner;
if (ownerScope !== null && !isPreferenceVisible({ owner: prefOwner }, ownerScope)) {
throw new BrainNotFoundError(`preference not found: ${preference}`);
}
@@ -141,10 +142,7 @@ async function toolBrainQuery(
const res = queryByTopic(ctx.vault, topic, { showExpired });
const resultCount = res.signals.length + res.all_log_events.length;
emitQueryTelemetry(resultCount > 0 ? "ok" : "empty", resultCount);
- const topicPrefOwner =
- res.preference && res.preference.kind === "brain-preference"
- ? res.preference.owner
- : undefined;
+ const topicPrefOwner = res.preference?.owner;
const topicPrefVisible =
res.preference !== null &&
res.preference !== undefined &&
@@ -181,11 +179,16 @@ async function toolBrainAgentQuery(
const topic = coerceStr(args, "topic", false);
const query = coerceStr(args, "query", false);
const kind = coerceAgentContributionKind(args, "kind");
+ // 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);
return queryAgentSources(ctx.vault, {
agents: coerceStrList(args, "agents"),
...(topic !== null ? { topic } : {}),
...(query !== null ? { query } : {}),
...(kind !== null ? { kind } : {}),
+ ...(ownerScope !== null ? { ownerScope } : {}),
limit: coerceInt(args, "limit", 50, 1, 500),
}) as unknown as Record<string, unknown>;
}
@@ -551,6 +554,11 @@ export const QUERY_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
maximum: 500,
description: "Maximum contributions returned. Defaults to 50.",
},
+ agent_scope: {
+ type: "string",
+ description:
+ "Optional owner scope: a contribution whose page declares an `owner:` returns only to its own scope; ownerless ones always match. Absent = no filtering.",
+ },
},
additionalProperties: false,
},
diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.ts
index 76054d47..76eaf072 100644
--- a/src/mcp/brain/recall-tools.ts
+++ b/src/mcp/brain/recall-tools.ts
@@ -65,6 +65,7 @@ import { INVALID_PARAMS, MCPError } from "../protocol.ts";
import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import { coercePositiveInteger, optionalStringArg, requiredStringArg } from "./shared.ts";
+import { AGENT_SCOPE_SCHEMA, coerceAgentScope } from "../coerce.ts";
/** Recall-quality benchmark over an inline dataset. */
async function toolBrainBenchmark(
@@ -347,11 +348,11 @@ async function toolBrainRetrievalPlan(
"token_budget",
args["token_budget"],
);
- const plan = buildRetrievalPlan(
- ctx.vault,
- question,
- tokenBudget !== undefined ? { tokenBudget } : {},
- );
+ const agentScope = coerceAgentScope(ctx, args, true);
+ const plan = buildRetrievalPlan(ctx.vault, question, {
+ ...(tokenBudget !== undefined ? { tokenBudget } : {}),
+ ...(agentScope !== undefined ? { agentScope } : {}),
+ });
return { vault_path: ctx.vault, ...serializeRetrievalPlan(plan) };
}
@@ -1033,6 +1034,7 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
minimum: 1,
description: "Optional context-pack token budget to model (default 2000).",
},
+ agent_scope: AGENT_SCOPE_SCHEMA,
},
required: ["question"],
additionalProperties: false,
diff --git a/src/mcp/coerce.ts b/src/mcp/coerce.ts
index c2f376b6..2549d103 100644
--- a/src/mcp/coerce.ts
+++ b/src/mcp/coerce.ts
@@ -85,6 +85,43 @@ export function coerceStringOptional(
return v;
}
+/**
+ * Input-schema fragment for the owner-scope argument
+ * (context-integrity-gates, Unit A). Declared once so eleven tools
+ * cannot grow eleven descriptions of the same argument.
+ */
+export const AGENT_SCOPE_ARG_NAME = "agent_scope";
+
+/** Longest accepted owner token; an agent name, not a document. */
+const AGENT_SCOPE_MAX_LEN = 128;
+
+export const AGENT_SCOPE_SCHEMA = Object.freeze({
+ type: "string",
+ description:
+ "Optional agent-ownership scope; shared (ownerless) memories always match, owner-tagged memories only their owner. Absent = no ownership filtering.",
+});
+
+/**
+ * Read the owner scope a content-returning tool was called with.
+ *
+ * `fallbackToServerIdentity` is for the GATED preference-backed
+ * surfaces: with no explicit argument they scope to the process's own
+ * agent identity, which is what makes `owner_scope_delivery: fail`
+ * effective for clients that never pass the argument. It is safe there
+ * 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.
+ */
+export function coerceAgentScope(
+ ctx: { 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;
+}
+
export function coerceIsoDate(args: Record<string, unknown>, key: string): Date | null {
const raw = coerceStr(args, key, false);
if (raw === null) return null;
diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.ts
index 48d0a570..7d1e7af2 100644
--- a/src/mcp/search-tools.ts
+++ b/src/mcp/search-tools.ts
@@ -38,7 +38,13 @@ import {
import { assessRecallAdequacy } from "../core/brain/recall-adequacy.ts";
import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";
import type { ServerContext, ToolDefinition } from "./tool-contract.ts";
-import { coerceBoolOptional, coerceStr, coerceStringOptional } from "./coerce.ts";
+import {
+ AGENT_SCOPE_SCHEMA,
+ coerceAgentScope,
+ coerceBoolOptional,
+ coerceStr,
+ coerceStringOptional,
+} from "./coerce.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
import { deriveRecallHint } from "../core/search/recall-hint.ts";
import { projectScoreBreakdown } from "../core/search/enrich.ts";
@@ -1002,6 +1008,7 @@ const FILE_CONTEXT_INPUT_SCHEMA: Record<string, unknown> = {
file_path: { type: "string", minLength: 1, maxLength: 1024 },
limit: { type: "integer", minimum: 1, maximum: MCP_LIMIT_MAX },
min_bytes: { type: "integer", minimum: 0, maximum: 10_000_000 },
+ agent_scope: AGENT_SCOPE_SCHEMA,
},
required: ["file_path"],
additionalProperties: false,
@@ -1051,7 +1058,9 @@ async function toolBrainFileContext(
});
try {
+ const agentScope = coerceAgentScope(ctx, args, false);
const outcome = await fileContextRecall(config, {
+ ...(agentScope !== undefined ? { agentScope } : {}),
filePath,
...(limit !== undefined ? { limit } : {}),
...(minBytes !== undefined ? { minBytes } : {}),
@@ -1110,6 +1119,7 @@ const SEARCH_EXPAND_INPUT_SCHEMA: Record<string, unknown> = {
maxLength: 32,
description: "Pagination cursor returned as next_cursor by a prior expand call.",
},
+ agent_scope: AGENT_SCOPE_SCHEMA,
},
required: ["chunk_id"],
additionalProperties: false,
@@ -1171,6 +1181,7 @@ async function toolBrainSearchExpand(
}
const rawLimit = coerceIntInRange(args, "raw_limit", 1, MCP_LIMIT_MAX);
const cursor = coerceStringOptional(args, "cursor", 32);
+ const expandScope = coerceAgentScope(ctx, args, false);
const config = resolveSearchConfig({
vault: ctx.vault,
configPath: ctx.configPath ?? undefined,
@@ -1180,6 +1191,7 @@ async function toolBrainSearchExpand(
result = await withTimeout(
expandHit(config, {
chunkId: rawChunk,
+ ...(expandScope !== undefined ? { agentScope: expandScope } : {}),
...(rawLimit !== undefined ? { rawLimit } : {}),
...(cursor !== undefined ? { cursor } : {}),
}),
@@ -1289,13 +1301,25 @@ export async function buildSearchStatusBlock(ctx: ServerContext): Promise<Record
}
// Token-budget conscious: pick the MCP subset out of the shared
// serializer's full field set rather than re-declaring the mapping.
+ //
+ // `warnings` used to be dropped with the rest, which is how an
+ // agent driving the vault entirely over MCP could not observe
+ // embedding-ABI drift at any setting short of `fail`
+ // (context-integrity-gates, Unit E): the drift line, the
+ // instruction-prefix line and the "sqlite-vec unavailable" line all
+ // died here. It is now spread back in only when non-empty, so a
+ // healthy vault's block is byte-identical and the token cost lands
+ // exactly on the vaults that have something to say. The structured
+ // `embedding_abi` field rides through in `rest` on the same
+ // condition, so an agent can branch instead of matching text.
const {
embedding_signature: _embeddingSignature,
estimated_refresh_cost_usd: _estimatedRefreshCostUsd,
- warnings: _warnings,
+ warnings,
...rest
} = serializeIndexStatus(snap);
- return rest;
+ const reportable = Array.isArray(warnings) ? warnings : [];
+ return reportable.length > 0 ? { ...rest, warnings: reportable } : rest;
} catch (e) {
return { exists: false, error: e instanceof Error ? e.message : String(e) };
}
diff --git a/src/mcp/server.ts b/src/mcp/server.ts
index 6df27a4f..a19a2a5f 100644
--- a/src/mcp/server.ts
+++ b/src/mcp/server.ts
@@ -115,6 +115,11 @@ export class MCPServer {
repoRoot: this.repoRoot,
capabilityReport: this.capabilityReport,
artifactStore: this.artifactStore,
+ // Owner-scope isolation (context-integrity-gates, Unit A): the
+ // only source of identity for `brain_context`, which takes no
+ // arguments. Resolved per access, like `resolveAgentName`'s other
+ // callers, so a config edit takes effect without a restart.
+ agentName: resolveAgentName(this.configPath ?? undefined),
};
}
diff --git a/src/mcp/tool-contract.ts b/src/mcp/tool-contract.ts
index 1bc56f0d..b1fa26bb 100644
--- a/src/mcp/tool-contract.ts
+++ b/src/mcp/tool-contract.ts
@@ -42,6 +42,22 @@ export interface ServerContext {
* back through it. Optional so manually-built contexts stay valid.
*/
readonly artifactStore?: ArtifactStore;
+ /**
+ * Resolved agent identity for this server process
+ * (context-integrity-gates, Unit A), from `resolveAgentName`.
+ *
+ * It exists because `brain_context` β€” the documented session-bootstrap
+ * surface β€” takes NO arguments at all (`{properties:{},
+ * additionalProperties:false}`), so it has no other way to learn who
+ * is asking. It is the fallback scope for the GATED preference-backed
+ * surfaces only: those cannot narrow anything unless the operator has
+ * set `integrity.owner_scope_delivery` to `fail`. The ungated
+ * search-backed surfaces deliberately do NOT fall back to it, because
+ * defaulting a scope there would narrow every search in every vault.
+ *
+ * Optional so a manually-built context stays valid and unscoped.
+ */
+ readonly agentName?: string;
}
export interface ToolDefinition {
diff --git a/src/mcp/tools.ts b/src/mcp/tools.ts
index 62823f58..bd25490b 100644
--- a/src/mcp/tools.ts
+++ b/src/mcp/tools.ts
@@ -41,9 +41,11 @@ import { SKILL_TOOLS } from "./skill-tools.ts";
import { buildHydrateTool, TOOL_HYDRATE_NAME } from "./hydrate-tool.ts";
import { normalizeAgentArgument, PLACEHOLDER_AGENT_VALUES } from "../core/agent-identity.ts";
import { vaultRelative } from "../core/path-safety.ts";
+import { isOwnerVisible, normalizeAgentScope, pageOwner } from "../core/graph/agent-scope.ts";
import { listVaultPages } from "../core/vault.ts";
+import { DEGRADATION_CODE, type DegradationNotice } from "../core/integrity/degradation.ts";
import { INVALID_PARAMS, METHOD_NOT_FOUND, MCPError } from "./protocol.ts";
-import { coerceStr, coerceInt } from "./coerce.ts";
+import { AGENT_SCOPE_SCHEMA, coerceAgentScope, coerceStr, coerceInt } from "./coerce.ts";
import type { OutputSchema } from "./output-contract.ts";
import { MCP_PREVIEW_BUDGET } from "./preview-budget.ts";
import { CAPABILITY_DIAGNOSTIC_TOOL } from "./capabilities.ts";
@@ -150,8 +152,35 @@ async function toolQuery(
}
const pattern = coerceStr(args, "pattern", false);
const limit = coerceInt(args, "limit", 50, 1, 500);
+ // Owner-scope isolation (context-integrity-gates, Unit A). This
+ // surface lists pages straight off the filesystem rather than through
+ // search, so it applies the rule itself - over the frontmatter
+ // `listVaultPages` has already parsed, so an unscoped call does no
+ // extra work and returns exactly what it always did.
+ //
+ // FAILS CLOSED, matching `isPathOwnerVisible` on the search path: the
+ // walk's diagnostic sink names every page whose file it could not read,
+ // and an unreadable page has an unknowable owner. Without the sink an
+ // unreadable page parses to empty metadata, reads as ownerless, and is
+ // shared with every scope. The sink is collected only under an active
+ // scope, so an unscoped call allocates nothing extra.
+ const scope = normalizeAgentScope(coerceAgentScope(ctx, args, false));
- const pages = listVaultPages(ctx.vault);
+ const notices: DegradationNotice[] = [];
+ const listed =
+ scope === null ? listVaultPages(ctx.vault) : listVaultPages(ctx.vault, { notices });
+ const unreadable = new Set(
+ notices
+ .filter((n) => n.code === DEGRADATION_CODE.frontmatterUnreadable)
+ .map((n) => n.path)
+ .filter((path): path is string => path !== undefined),
+ );
+ const pages =
+ scope === null
+ ? listed
+ : listed.filter(
+ (p) => !unreadable.has(p.path) && isOwnerVisible(pageOwner(p.metadata), scope),
+ );
const needle = pattern ? pattern.toLowerCase() : null;
const matched: Array<Record<string, unknown>> = [];
for (const p of pages) {
@@ -363,6 +392,7 @@ export function buildToolTable(scope: ToolScope = "full"): ToolDefinition[] {
maximum: 500,
description: "Maximum number of matched pages to return (default 50).",
},
+ agent_scope: AGENT_SCOPE_SCHEMA,
},
additionalProperties: false,
},
diff --git a/tests/cli/agent-scope-flags.test.ts b/tests/cli/agent-scope-flags.test.ts
new file mode 100644
index 00000000..9fc628fe
--- /dev/null
+++ b/tests/cli/agent-scope-flags.test.ts
@@ -0,0 +1,207 @@
+/**
+ * CLI `--agent-scope` flags (context-integrity-gates, Unit A).
+ *
+ * Owner-scope isolation is well covered at the library level, and the
+ * MCP `agent_scope` argument has its own regression matrix. The three
+ * CLI flags that reach the same rule - `o2b search query`,
+ * `o2b search expand` and `o2b brain sgrep` - had none: nothing
+ * exercised the argument parsing or the flag-to-`SearchOptions.agentScope`
+ * wiring, so the release would have claimed a user-facing capability
+ * nobody had run.
+ *
+ * Every case here proves the flag NARROWS - a scoped invocation must
+ * drop another owner's page while an unscoped one keeps it - rather than
+ * merely parsing without error.
+ */
+
+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 { runCli } from "../helpers/run-cli.ts";
+
+const OWNER_A = "agent-a";
+const OWNER_B = "agent-b";
+const QUERY = "lattice widgets";
+const OWNED_A = "notes/owned-a.md";
+const OWNED_B = "notes/owned-b.md";
+const SHARED = "notes/shared.md";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+
+beforeEach(async () => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-agent-scope-cli-"));
+ vault = join(tmp, "vault");
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, OWNED_A),
+ `---\nowner: ${OWNER_A}\n---\n\n# A\n\n${QUERY} owned by a\n`,
+ );
+ writeFileSync(
+ join(vault, OWNED_B),
+ `---\nowner: ${OWNER_B}\n---\n\n# B\n\n${QUERY} owned by b\n`,
+ );
+ writeFileSync(join(vault, SHARED), `# Shared\n\n${QUERY} shared with everyone\n`);
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(configPath, `vault: ${vault}\nagent_name: ${OWNER_A}\n`);
+
+ const indexed = await runCli(["search", "index"], { env: env() });
+ expect(indexed.returncode).toBe(0);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+interface QueryJson {
+ readonly results: ReadonlyArray<{ readonly path: string; readonly chunk_id: number }>;
+}
+
+/** `o2b search query --json`, with whatever extra flags the case needs. */
+async function query(extra: ReadonlyArray<string> = []): Promise<QueryJson> {
+ const r = await runCli(["search", "query", QUERY, "--json", "--limit", "20", ...extra], {
+ env: env(),
+ });
+ expect(r.returncode).toBe(0);
+ return JSON.parse(r.stdout) as QueryJson;
+}
+
+async function queryPaths(extra: ReadonlyArray<string> = []): Promise<string[]> {
+ return (await query(extra)).results.map((x) => x.path);
+}
+
+async function chunkIdFor(path: string): Promise<number> {
+ const hit = (await query()).results.find((r) => r.path === path);
+ expect(hit).toBeDefined();
+ return hit!.chunk_id;
+}
+
+// ─── o2b search query ────────────────────────────────────────────────────────
+
+test("`search query --agent-scope` drops another owner's page and keeps the shared one", async () => {
+ const unscoped = await queryPaths();
+ expect(unscoped).toContain(OWNED_A);
+ expect(unscoped).toContain(OWNED_B);
+
+ const scoped = await queryPaths(["--agent-scope", OWNER_A]);
+ expect(scoped).not.toContain(OWNED_B);
+ expect(scoped).toContain(OWNED_A);
+ expect(scoped).toContain(SHARED);
+});
+
+test("`search query --agent-scope` reads the same page from the other side", async () => {
+ const scoped = await queryPaths(["--agent-scope", OWNER_B]);
+ expect(scoped).toContain(OWNED_B);
+ expect(scoped).not.toContain(OWNED_A);
+});
+
+test("`search query --agent-scope` normalizes the token it was given", async () => {
+ // The flag value goes through the same NFC + trim + lower-case
+ // normalization as the frontmatter token, so an operator typing the
+ // agent name with capitals is not silently isolated from their own
+ // pages.
+ const scoped = await queryPaths(["--agent-scope", " Agent-A "]);
+ expect(scoped).toContain(OWNED_A);
+ expect(scoped).not.toContain(OWNED_B);
+});
+
+test("`search query --agent-scope=` (blank) requests no scope and filters nothing", async () => {
+ // Blank is "no scope requested", not "the empty owner": the documented
+ // `normalizeAgentScope` contract, shared with every other surface. A
+ // blank value that narrowed to nothing would be a far worse surprise.
+ const scoped = await queryPaths(["--agent-scope="]);
+ expect(scoped).toContain(OWNED_A);
+ expect(scoped).toContain(OWNED_B);
+});
+
+test("`search query --agent-scope` with no value is a usage error", async () => {
+ const r = await runCli(["search", "query", QUERY, "--json", "--agent-scope"], { env: env() });
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toContain("--agent-scope requires a value");
+});
+
+// ─── o2b search expand ───────────────────────────────────────────────────────
+
+test("`search expand --agent-scope` refuses another owner's chunk indistinguishably", async () => {
+ const chunkId = await chunkIdFor(OWNED_B);
+
+ const unscoped = await runCli(["search", "expand", "--chunk", String(chunkId), "--json"], {
+ env: env(),
+ });
+ expect(unscoped.returncode).toBe(0);
+ expect(unscoped.stdout).toContain(OWNED_B);
+
+ const scoped = await runCli(
+ ["search", "expand", "--chunk", String(chunkId), "--json", "--agent-scope", OWNER_A],
+ { env: env() },
+ );
+ expect(scoped.returncode).toBe(2);
+ // Byte-identical to the absent-chunk error: a distinguishable refusal
+ // would confirm the chunk exists and belongs to someone else, which is
+ // exactly what walking the sequential ids is looking for.
+ expect(scoped.stderr).toContain(`chunk not found: ${chunkId}`);
+ expect(scoped.stdout).toBe("");
+});
+
+test("`search expand --agent-scope` still serves the owner their own chunk", async () => {
+ const chunkId = await chunkIdFor(OWNED_A);
+ const scoped = await runCli(
+ ["search", "expand", "--chunk", String(chunkId), "--json", "--agent-scope", OWNER_A],
+ { env: env() },
+ );
+ expect(scoped.returncode).toBe(0);
+ expect(scoped.stdout).toContain(OWNED_A);
+});
+
+test("`search expand --agent-scope` leaves a shared chunk reachable", async () => {
+ const chunkId = await chunkIdFor(SHARED);
+ const scoped = await runCli(
+ ["search", "expand", "--chunk", String(chunkId), "--json", "--agent-scope", OWNER_B],
+ { env: env() },
+ );
+ expect(scoped.returncode).toBe(0);
+ expect(scoped.stdout).toContain(SHARED);
+});
+
+// ─── o2b brain sgrep ─────────────────────────────────────────────────────────
+
+interface SgrepJson {
+ readonly results: ReadonlyArray<{ readonly path: string }>;
+}
+
+async function sgrepPaths(extra: ReadonlyArray<string> = []): Promise<string[]> {
+ const r = await runCli(["brain", "sgrep", QUERY, "--json", "--limit", "20", ...extra], {
+ env: env(),
+ });
+ // Grep-like contract: 0 with matches, 1 without. Either way the JSON
+ // body is what the assertion reads.
+ expect([0, 1]).toContain(r.returncode);
+ return (JSON.parse(r.stdout) as SgrepJson).results.map((x) => x.path);
+}
+
+test("`brain sgrep --agent-scope` drops another owner's page and keeps the shared one", async () => {
+ const unscoped = await sgrepPaths();
+ expect(unscoped).toContain(OWNED_A);
+ expect(unscoped).toContain(OWNED_B);
+
+ const scoped = await sgrepPaths(["--agent-scope", OWNER_A]);
+ expect(scoped).not.toContain(OWNED_B);
+ expect(scoped).toContain(OWNED_A);
+ expect(scoped).toContain(SHARED);
+});
+
+test("`brain sgrep --agent-scope` with no value is a usage error", async () => {
+ const r = await runCli(["brain", "sgrep", QUERY, "--json", "--agent-scope"], { env: env() });
+ // 1, not the 2 the `search` group returns: the `brain` dispatcher owns
+ // its own CliError catch and has always mapped usage errors to 1. That
+ // divergence predates this flag and belongs to the dispatcher, not to
+ // `--agent-scope`; pinned here so the flag's behaviour is recorded as
+ // it actually is.
+ expect(r.returncode).toBe(1);
+ expect(r.stderr).toContain("--agent-scope requires a value");
+});
diff --git a/tests/cli/frontmatter-notices.test.ts b/tests/cli/frontmatter-notices.test.ts
new file mode 100644
index 00000000..dd2616f5
--- /dev/null
+++ b/tests/cli/frontmatter-notices.test.ts
@@ -0,0 +1,122 @@
+/**
+ * Unit F, CLI surface: a frontmatter line the scanner dropped is visible
+ * to an operator through `o2b search index` and `o2b brain doctor`, and a
+ * vault with no malformed frontmatter produces output byte-identical to
+ * the previous release (the new keys are conditional, never empty).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { writeVaultIdentity } from "../../src/core/brain/vault-identity.ts";
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+
+const CLEAN_NOTE =
+ "---\ntitle: Clean\ntype: note\ntags:\n - a\n - b\n---\n\nA body with enough words to chunk.\n";
+const ODD_NOTE = "---\ntitle: Odd\n-foo\ntype: note\n---\n\nA body with enough words to chunk.\n";
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-fm-notices-cli-"));
+ vault = join(tmp, "vault");
+ for (const d of ["preferences", "retired", "inbox", "processed", "log"]) {
+ mkdirSync(join(vault, "Brain", d), { recursive: true });
+ }
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+ // Unit J: an unmarked root is itself reported through `uncertain`, so
+ // the "clean tree emits no uncertain key" assertion needs the marker
+ // `o2b brain init` would have stamped on a real vault.
+ writeVaultIdentity(vault);
+ configPath = join(tmp, "config.yaml");
+ writeFileSync(
+ configPath,
+ `vault: ${vault}\nagent_name: test\ndb_path: ${join(tmp, "b.sqlite")}\n`,
+ );
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });
+
+describe("o2b search index frontmatter notices", () => {
+ test("a clean vault emits no frontmatter_notices key at all", async () => {
+ writeFileSync(join(vault, "clean.md"), CLEAN_NOTE);
+ const r = await runCli(["search", "index", "--json"], { env: env() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).not.toContain("frontmatter_notices");
+ expect(JSON.parse(r.stdout)).not.toHaveProperty("frontmatter_notices");
+ });
+
+ test("a dropped line is named in the JSON payload", async () => {
+ writeFileSync(join(vault, "odd.md"), ODD_NOTE);
+ const r = await runCli(["search", "index", "--json"], { env: env() });
+ expect(r.returncode).toBe(0);
+ const payload = JSON.parse(r.stdout) as {
+ frontmatter_notices?: Array<{ code: string; path?: string; detail: string }>;
+ errors: unknown[];
+ };
+ expect(payload.errors).toEqual([]);
+ expect(payload.frontmatter_notices).toHaveLength(1);
+ expect(payload.frontmatter_notices![0]!.code).toBe("frontmatter-line-dropped");
+ expect(payload.frontmatter_notices![0]!.path).toBe("odd.md");
+ expect(payload.frontmatter_notices![0]!.detail).toContain("-foo");
+ });
+
+ test("a dropped line is named in the human render, and a clean run is unchanged", async () => {
+ writeFileSync(join(vault, "clean.md"), CLEAN_NOTE);
+ const clean = await runCli(["search", "index"], { env: env() });
+ expect(clean.returncode).toBe(0);
+ expect(clean.stdout).not.toContain("frontmatter");
+
+ writeFileSync(join(vault, "odd.md"), ODD_NOTE);
+ const odd = await runCli(["search", "index"], { env: env() });
+ expect(odd.returncode).toBe(0);
+ expect(odd.stdout).toContain("frontmatter-line-dropped");
+ expect(odd.stdout).toContain("odd.md");
+ });
+});
+
+describe("o2b brain doctor frontmatter notices", () => {
+ test("a clean Brain tree emits no uncertain key", async () => {
+ const r = await runCli(["brain", "doctor", "--json"], { env: env() });
+ expect(JSON.parse(r.stdout)).not.toHaveProperty("uncertain");
+ expect(r.stdout).not.toContain("uncertain");
+ });
+
+ test("a dropped line reaches the doctor JSON and the human render", async () => {
+ writeFileSync(
+ join(vault, "Brain", "notes", "odd.md"),
+ "---\ntitle: Odd\ntopic: odd\n-foo\n---\n\nBody.\n",
+ );
+ const asJson = await runCli(["brain", "doctor", "--json"], { env: env() });
+ const payload = JSON.parse(asJson.stdout) as {
+ uncertain?: Array<{ code: string; path?: string; message: string }>;
+ };
+ expect(payload.uncertain).toBeDefined();
+ const hit = payload.uncertain!.find((e) => (e.path ?? "").endsWith("odd.md"));
+ expect(hit).toBeDefined();
+ expect(hit!.code).toBe("frontmatter-line-dropped");
+
+ const human = await runCli(["brain", "doctor"], { env: env() });
+ expect(human.stdout).toContain("frontmatter-line-dropped");
+ });
+
+ test("a dropped line alone does not change the doctor exit code", async () => {
+ writeFileSync(
+ join(vault, "Brain", "notes", "odd.md"),
+ "---\ntitle: Odd\ntopic: odd\n-foo\n---\n\nBody.\n",
+ );
+ // Uncertainty is neither a warning nor an error, so even --strict
+ // must stay at 0 when nothing else is wrong.
+ const r = await runCli(["brain", "doctor", "--strict"], { env: env() });
+ expect(r.returncode).toBe(0);
+ });
+});
diff --git a/tests/cli/vault-portability-cli.test.ts b/tests/cli/vault-portability-cli.test.ts
index c0951e25..beaa2d6b 100644
--- a/tests/cli/vault-portability-cli.test.ts
+++ b/tests/cli/vault-portability-cli.test.ts
@@ -6,7 +6,7 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -92,8 +92,13 @@ describe("o2b vault profile / map", () => {
test("profile create / switch / list", async () => {
await bootstrap();
const env = { OPEN_SECOND_BRAIN_CONFIG: config };
+ // The profile target must be a real directory: activation validates
+ // it at switch time (context-integrity-gates, Unit J), where before
+ // it deferred the failure to whichever later process wrote first.
+ const workVault = join(tmp, "work-vault");
+ mkdirSync(workVault, { recursive: true });
expect(
- (await runCli(["vault", "profile", "create", "work", "/srv/v/work"], { env })).returncode,
+ (await runCli(["vault", "profile", "create", "work", workVault], { env })).returncode,
).toBe(0);
expect((await runCli(["vault", "profile", "switch", "work"], { env })).returncode).toBe(0);
const list = await runCli(["vault", "profile", "list", "--json"], { env });
diff --git a/tests/core/brain.doctor-trust-atoms.test.ts b/tests/core/brain.doctor-trust-atoms.test.ts
index 213733ce..c6a6353b 100644
--- a/tests/core/brain.doctor-trust-atoms.test.ts
+++ b/tests/core/brain.doctor-trust-atoms.test.ts
@@ -13,6 +13,7 @@ import { join } from "node:path";
import { runDoctor } from "../../src/core/brain/doctor.ts";
import { brainConfigPath, brainDirs } from "../../src/core/brain/paths.ts";
import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/policy.ts";
+import { writeVaultIdentity } from "../../src/core/brain/vault-identity.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
let tmp: string;
@@ -32,6 +33,10 @@ beforeEach(() => {
mkdirSync(d, { recursive: true });
}
atomicWriteFileSync(brainConfigPath(tmp), DEFAULT_BRAIN_CONFIG_YAML);
+ // Unit J: an unmarked root is itself an uncertainty finding, so a
+ // fixture that stands for a CLEAN vault has to carry what `o2b brain
+ // init` would have stamped on it.
+ writeVaultIdentity(tmp);
});
afterEach(() => {
diff --git a/tests/core/brain.doctor.test.ts b/tests/core/brain.doctor.test.ts
index a4e52f8d..f1a90adc 100644
--- a/tests/core/brain.doctor.test.ts
+++ b/tests/core/brain.doctor.test.ts
@@ -66,12 +66,20 @@ describe("clean vault", () => {
expect(res.warnings).toEqual([]);
});
- test("a vault without Brain/ at all reports zero issues (no Brain layer present is acceptable)", () => {
+ test("a vault without Brain/ at all is named, not reported clean", () => {
+ // Until context-integrity-gates (Unit J) this asserted zero warnings
+ // AND a `clean` trust verdict. That assertion encoded the defect
+ // rather than the contract: a root with no Brain layer is exactly
+ // the shape a MIS-RESOLVED vault takes, so the one command an
+ // operator runs to check the store certified the wrong root as fine.
+ // An un-initialized vault is still not an ERROR, so `errors` stays
+ // empty; the condition is now a named warning.
const fresh = mkdtempSync(join(tmpdir(), "o2b-doctor-no-brain-"));
try {
const res = runDoctor(fresh);
expect(res.errors).toEqual([]);
- expect(res.warnings).toEqual([]);
+ expect(res.warnings.map((w) => w.code)).toEqual(["brain-root-absent"]);
+ expect(res.trust_verdict).not.toBe("clean");
} finally {
rmSync(fresh, { recursive: true, force: true });
}
diff --git a/tests/core/brain.init.test.ts b/tests/core/brain.init.test.ts
index a9cd6ba7..b86a6486 100644
--- a/tests/core/brain.init.test.ts
+++ b/tests/core/brain.init.test.ts
@@ -62,11 +62,14 @@ describe("bootstrapBrain β€” empty vault", () => {
// in v0.11.0; the operating manual lives at Brain/_BRAIN.md only.)
expect(existsSync(join(vault, "Brain", "_brain.yaml"))).toBe(true);
expect(existsSync(join(vault, "Brain", "_BRAIN.md"))).toBe(true);
-
- // Counts: six created (_brain.yaml, _BRAIN.md, and the four
- // Brain/bases/*.base view definitions stamped at init), none
- // overwritten, none skipped.
- expect(result.created.length).toBe(6);
+ // The vault identity marker is stamped by the bootstrap path
+ // (context-integrity-gates, Unit J).
+ expect(existsSync(join(vault, "Brain", "vault-id.json"))).toBe(true);
+
+ // Counts: seven created (vault-id.json, _brain.yaml, _BRAIN.md, and
+ // the four Brain/bases/*.base view definitions stamped at init),
+ // none overwritten, none skipped.
+ expect(result.created.length).toBe(7);
expect(result.overwritten.length).toBe(0);
expect(result.skipped.length).toBe(0);
diff --git a/tests/core/brain/anticipatory-cache.test.ts b/tests/core/brain/anticipatory-cache.test.ts
index 747e7c39..beb85669 100644
--- a/tests/core/brain/anticipatory-cache.test.ts
+++ b/tests/core/brain/anticipatory-cache.test.ts
@@ -10,7 +10,7 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { tmpdir } from "node:os";
@@ -18,10 +18,12 @@ import { bootstrapBrain } from "../../../src/core/brain/init.ts";
import { captureSessionLifecycleEvent } from "../../../src/core/brain/session-lifecycle.ts";
import { recordLineageObservation } from "../../../src/core/brain/lineage/ledger.ts";
import {
+ ANTICIPATORY_SCHEMA_VERSION,
anticipatoryCachePath,
readAnticipatoryContext,
refreshAnticipatoryCache,
} from "../../../src/core/brain/anticipatory-cache.ts";
+import { PACK_STAMP_FIELD } from "../../../src/core/brain/pack-stamp.ts";
let vault: string;
@@ -55,7 +57,10 @@ describe("refreshAnticipatoryCache", () => {
schema: string;
root_session_id: string;
};
- expect(raw.schema).toBe("o2b.anticipatory.v1");
+ // A literal, not the constant: comparing the constant to itself is a
+ // tautology that can never catch an unintended schema-token change.
+ expect(raw.schema).toBe("o2b.anticipatory.v2");
+ expect(ANTICIPATORY_SCHEMA_VERSION).toBe("o2b.anticipatory.v2");
expect(raw.root_session_id).toBe("root-1");
});
@@ -148,6 +153,147 @@ describe("readAnticipatoryContext", () => {
});
});
+describe("provenance stamp and validity window", () => {
+ function writePref(slug: string, body: string, mtimeSeconds: number): void {
+ const path = join(vault, "Brain", "preferences", `pref-${slug}.md`);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ [
+ "---",
+ `id: pref-${slug}`,
+ `topic: ${slug}`,
+ "principle: p",
+ "tier: core",
+ "---",
+ "",
+ body,
+ ].join("\n"),
+ );
+ utimesSync(path, mtimeSeconds, mtimeSeconds);
+ }
+
+ test("the cache records the pack's stamp", () => {
+ writePref("stamped", "a body", 1_700_000_000);
+ refreshAnticipatoryCache(vault, { sessionId: "s-stamp", now: T0 });
+ const raw = JSON.parse(readFileSync(anticipatoryCachePath(vault, "s-stamp"), "utf8")) as Record<
+ string,
+ unknown
+ >;
+ const stamp = raw["stamp"] as { tokens: Record<string, string | null>; expires_at: string };
+ expect(typeof stamp.tokens[PACK_STAMP_FIELD.brainTree]).toBe("string");
+ expect(typeof stamp.expires_at).toBe("string");
+ });
+
+ test("editing a Brain note invalidates a warm cache entry and names the reason", () => {
+ writePref("edited", "original body", 1_700_000_000);
+ refreshAnticipatoryCache(vault, { sessionId: "s-edit", now: T0 });
+ expect(
+ readAnticipatoryContext(vault, { sessionId: "s-edit", now: new Date(T0.getTime() + 5_000) })
+ .cache_state,
+ ).toBe("warm");
+
+ writePref("edited", "a rewritten body of a different length", 1_700_000_500);
+ const read = readAnticipatoryContext(vault, {
+ sessionId: "s-edit",
+ now: new Date(T0.getTime() + 6_000),
+ });
+ expect(read.cache_state).toBe("miss");
+ expect(read.cache_refusal).toBeDefined();
+ expect(read.cache_refusal!).toContain(PACK_STAMP_FIELD.brainTree);
+ });
+
+ test("a refused entry is served warm again once it is rebuilt", () => {
+ writePref("rebuilt", "original body", 1_700_000_000);
+ refreshAnticipatoryCache(vault, { sessionId: "s-rebuild", now: T0 });
+ writePref("rebuilt", "a rewritten body of a different length", 1_700_000_500);
+ const refused = readAnticipatoryContext(vault, {
+ sessionId: "s-rebuild",
+ now: new Date(T0.getTime() + 6_000),
+ });
+ expect(refused.cache_state).toBe("miss");
+
+ // The drifted entry must not survive the TTL debounce: a refresh
+ // inside the debounce window still rebuilds, because the stamp -
+ // not the clock - is the primary invalidator.
+ const refreshed = refreshAnticipatoryCache(vault, {
+ sessionId: "s-rebuild",
+ now: new Date(T0.getTime() + 7_000),
+ });
+ expect(refreshed.refreshed).toBe(true);
+ const read = readAnticipatoryContext(vault, {
+ sessionId: "s-rebuild",
+ now: new Date(T0.getTime() + 8_000),
+ });
+ expect(read.cache_state).toBe("warm");
+ expect(read.cache_refusal).toBeUndefined();
+ });
+
+ test("an expired validity window is refused rather than served, naming the expiry", () => {
+ writePref("expiring", "a body", 1_700_000_000);
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8") +
+ "\nintegrity:\n pack_validity_seconds: 60\n",
+ );
+ refreshAnticipatoryCache(vault, { sessionId: "s-expire", now: T0, ttlSeconds: 3_600 });
+ const read = readAnticipatoryContext(vault, {
+ sessionId: "s-expire",
+ now: new Date(T0.getTime() + 61_000),
+ ttlSeconds: 3_600,
+ });
+ expect(read.cache_state).toBe("miss");
+ expect(read.cache_refusal).toBeDefined();
+ expect(read.cache_refusal!).toContain("2026-06-10T12:01:00.000Z");
+ });
+
+ test("a cache file written under the previous schema reads as a miss", () => {
+ const path = anticipatoryCachePath(vault, "s-legacy");
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ `${JSON.stringify(
+ {
+ schema: "o2b.anticipatory.v1",
+ root_session_id: "s-legacy",
+ session_id: "s-legacy",
+ generated_at: T0.toISOString(),
+ max_tokens: 2_000,
+ context: { items: [], session_hits: [] },
+ },
+ null,
+ 2,
+ )}\n`,
+ "utf8",
+ );
+ const read = readAnticipatoryContext(vault, { sessionId: "s-legacy", now: T0 });
+ expect(read.cache_state).toBe("miss");
+ });
+
+ test("a cache file with no stamp at all reads as a miss, never as an unstamped hit", () => {
+ const path = anticipatoryCachePath(vault, "s-unstamped");
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(
+ path,
+ `${JSON.stringify(
+ {
+ schema: ANTICIPATORY_SCHEMA_VERSION,
+ root_session_id: "s-unstamped",
+ session_id: "s-unstamped",
+ generated_at: T0.toISOString(),
+ max_tokens: 2_000,
+ context: { items: [], session_hits: [] },
+ },
+ null,
+ 2,
+ )}\n`,
+ "utf8",
+ );
+ const read = readAnticipatoryContext(vault, { sessionId: "s-unstamped", now: T0 });
+ expect(read.cache_state).toBe("miss");
+ });
+});
+
describe("hook integration", () => {
test("a UserPromptSubmit lifecycle event warms the cache fail-soft", async () => {
await captureSessionLifecycleEvent(
@@ -179,3 +325,44 @@ describe("hook integration", () => {
expect(read.cache_state).toBe("miss");
});
});
+
+// ----- A4: the cache keys on the ENFORCED scope, not the requested one ----
+
+describe("owner scope in the cache key", () => {
+ /**
+ * The two writers that warm the cache (the session-lifecycle hook and
+ * `o2b brain anticipate --refresh`) pass no scope; the MCP tool passes
+ * one unconditionally, because `coerceAgentScope(ctx, args, true)` falls
+ * back to `resolveAgentName`, which always returns a string. Keying the
+ * filename on the REQUESTED scope therefore made every MCP read a
+ * permanent miss on a default vault, rebuilding a full `packContext` on
+ * each call - an observable behaviour change with the gate off.
+ */
+ test("a hook-warmed cache is warm for a scoped MCP read under the default gate", () => {
+ const warmed = refreshAnticipatoryCache(vault, { sessionId: "s-scope", now: T0 });
+ expect(warmed.refreshed).toBe(true);
+
+ const read = readAnticipatoryContext(vault, {
+ sessionId: "s-scope",
+ now: T0,
+ agentScope: "agent-a",
+ });
+ expect(read.cache_state).toBe("warm");
+ });
+
+ test("the hook-written path and the scoped read path are the same file", () => {
+ const hookPath = anticipatoryCachePath(vault, "root-1");
+ expect(anticipatoryCachePath(vault, "root-1", "agent-a")).toBe(hookPath);
+ expect(anticipatoryCachePath(vault, "root-1", "agent-b")).toBe(hookPath);
+ });
+
+ test("a second scoped read does not rebuild what the first one already had", () => {
+ refreshAnticipatoryCache(vault, { sessionId: "s-twice", now: T0 });
+ for (const scope of ["agent-a", "agent-b"]) {
+ expect(
+ readAnticipatoryContext(vault, { sessionId: "s-twice", now: T0, agentScope: scope })
+ .cache_state,
+ ).toBe("warm");
+ }
+ });
+});
diff --git a/tests/core/brain/context-receipt-session-summary.test.ts b/tests/core/brain/context-receipt-session-summary.test.ts
new file mode 100644
index 00000000..15047bd9
--- /dev/null
+++ b/tests/core/brain/context-receipt-session-summary.test.ts
@@ -0,0 +1,222 @@
+/**
+ * Unit I - session-scoped retrieval receipt fold.
+ *
+ * Every primitive already existed and was durable; what was missing was
+ * the join across a session. The assertions below are about the join and
+ * about the two ways it could lie: presenting zeros where nothing was
+ * recorded, and presenting a bounded scan as a complete one.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ ContextReceiptWindowError,
+ emitContextReceipt,
+ summarizeContextReceiptSession,
+ type ContextReceiptItemInput,
+} from "../../../src/core/brain/context-receipts.ts";
+import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";
+import { emitObservedUse, observedReuseRates } from "../../../src/core/brain/observed-use.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-receipt-fold-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function seed(
+ createdAt: string,
+ sessionId: string,
+ items: ReadonlyArray<ContextReceiptItemInput>,
+): void {
+ emitContextReceipt(vault, {
+ options: { host: "unit-test", trigger: "context_pack", createdAt, sessionId },
+ items,
+ finalText: items.map((i) => i.id).join("|"),
+ });
+}
+
+describe("summarizeContextReceiptSession", () => {
+ test("reports that nothing was recorded instead of zeros presented as a finding", () => {
+ const summary = summarizeContextReceiptSession(vault, { sessionId: "s1" });
+ expect(summary.recorded).toBe(false);
+ // A caller cannot reach a count at all without first branching on
+ // `recorded` - which is the entire distinction this unit exists for.
+ expect("receipt_count" in summary).toBe(false);
+ });
+
+ test("folds a session into distinct items with injection frequency and token cost", () => {
+ seed("2026-06-01T10:00:00Z", "s1", [
+ { id: "pref-a", path: "Brain/preferences/pref-a.md", tokens: 10 },
+ { id: "pref-b", path: "Brain/preferences/pref-b.md", tokens: 20 },
+ ]);
+ seed("2026-06-01T10:05:00Z", "s1", [
+ { id: "pref-a", path: "Brain/preferences/pref-a.md", tokens: 12 },
+ ]);
+ seed("2026-06-01T10:10:00Z", "s1", [
+ { id: "pref-a", path: "Brain/preferences/pref-a.md", tokens: 8 },
+ { id: "pref-c", tokens: 5 },
+ ]);
+ // A different session must not leak into the fold.
+ seed("2026-06-01T10:11:00Z", "s2", [{ id: "pref-z", tokens: 99 }]);
+
+ const summary = summarizeContextReceiptSession(vault, { sessionId: "s1" });
+ if (!summary.recorded) throw new Error("expected receipts");
+ expect(summary.receipt_count).toBe(3);
+ expect(summary.item_total).toBe(5);
+ expect(summary.distinct_items).toBe(3);
+ expect(summary.truncated).toBe(false);
+ expect(summary.withheld_receipts).toBe(0);
+ expect(summary.items).toEqual([
+ { id: "pref-a", path: "Brain/preferences/pref-a.md", injections: 3, tokens: 30 },
+ { id: "pref-b", path: "Brain/preferences/pref-b.md", injections: 1, tokens: 20 },
+ { id: "pref-c", injections: 1, tokens: 5 },
+ ]);
+ });
+
+ test("counts a redacted receipt without unfolding its payload into the aggregate", () => {
+ seed("2026-06-02T10:00:00Z", "s1", [{ id: "pref-a", tokens: 10 }]);
+ seed("2026-06-02T10:01:00Z", "s1", [{ id: "<private>pref-secret</private>", tokens: 1000 }]);
+
+ const summary = summarizeContextReceiptSession(vault, { sessionId: "s1" });
+ if (!summary.recorded) throw new Error("expected receipts");
+ expect(summary.receipt_count).toBe(2);
+ expect(summary.withheld_receipts).toBe(1);
+ expect(summary.distinct_items).toBe(1);
+ expect(summary.items.map((i) => i.id)).toEqual(["pref-a"]);
+ expect(summary.items[0]!.tokens).toBe(10);
+ });
+
+ test("reports that the scan bound truncated the input", () => {
+ for (let i = 0; i < 5; i++) {
+ seed(`2026-06-03T10:0${i}:00Z`, "s1", [{ id: `pref-${i}`, tokens: 1 }]);
+ }
+ const bounded = summarizeContextReceiptSession(vault, { sessionId: "s1", maxReceipts: 2 });
+ if (!bounded.recorded) throw new Error("expected receipts");
+ expect(bounded.truncated).toBe(true);
+ expect(bounded.max_receipts).toBe(2);
+ expect(bounded.receipt_count).toBe(2);
+
+ const complete = summarizeContextReceiptSession(vault, { sessionId: "s1", maxReceipts: 50 });
+ if (!complete.recorded) throw new Error("expected receipts");
+ expect(complete.truncated).toBe(false);
+ expect(complete.receipt_count).toBe(5);
+ });
+
+ test("a time window bounds the fold", () => {
+ seed("2026-06-04T10:00:00Z", "s1", [{ id: "old", tokens: 1 }]);
+ seed("2026-06-06T10:00:00Z", "s1", [{ id: "new", tokens: 1 }]);
+ const summary = summarizeContextReceiptSession(vault, { since: "2026-06-05T00:00:00Z" });
+ if (!summary.recorded) throw new Error("expected receipts");
+ expect(summary.items.map((i) => i.id)).toEqual(["new"]);
+ });
+});
+
+describe("summarizeContextReceiptSession β€” receipts that carry no items", () => {
+ test("an empty item array is COUNTED, not silently dropped", () => {
+ // This is the shape the SessionStart meter writes when the injection
+ // loader degraded to its last-good cache: a real receipt with
+ // nothing to attribute. It inflates receipt_count and contributes
+ // nothing to item_total, and no counter used to name it.
+ seed("2026-06-01T10:00:00Z", "s1", [{ id: "pref-a", tokens: 5 }]);
+ seed("2026-06-01T10:01:00Z", "s1", []);
+ const summary = summarizeContextReceiptSession(vault, { sessionId: "s1" });
+ if (!summary.recorded) throw new Error("expected receipts");
+ expect(summary.receipt_count).toBe(2);
+ expect(summary.item_total).toBe(1);
+ expect(summary.empty_receipts).toBe(1);
+ expect(summary.malformed_receipts).toBe(0);
+ });
+
+ test("a receipt with no item array at all is counted separately", () => {
+ seed("2026-06-01T10:00:00Z", "s1", [{ id: "pref-a", tokens: 5 }]);
+ appendContinuityRecord(vault, {
+ kind: "context_receipt",
+ createdAt: "2026-06-01T10:02:00Z",
+ sourceRefs: [],
+ payload: { host: "unit-test", trigger: "context_pack", session_id: "s1", item_count: 0 },
+ });
+ const summary = summarizeContextReceiptSession(vault, { sessionId: "s1" });
+ if (!summary.recorded) throw new Error("expected receipts");
+ expect(summary.receipt_count).toBe(2);
+ expect(summary.malformed_receipts).toBe(1);
+ expect(summary.empty_receipts).toBe(0);
+ });
+});
+
+describe("summarizeContextReceiptSession β€” window bounds are validated", () => {
+ test("an uncomparable `since` is REFUSED, not reported as 'nothing happened'", () => {
+ seed("2026-06-01T10:00:00Z", "s1", [{ id: "pref-a", tokens: 5 }]);
+ // "yesterday" sorts after every 2026-… timestamp, so the lexical
+ // filter emptied the window and the fold answered `recorded: false`
+ // - "nothing was recorded for this filter" for malformed input.
+ expect(() => summarizeContextReceiptSession(vault, { since: "yesterday" })).toThrow(
+ ContextReceiptWindowError,
+ );
+ });
+
+ test("a non-UTC offset and an impossible date are refused too", () => {
+ expect(() =>
+ summarizeContextReceiptSession(vault, { until: "2026-06-01T10:00:00+03:00" }),
+ ).toThrow(ContextReceiptWindowError);
+ expect(() => summarizeContextReceiptSession(vault, { since: "2026-02-30T00:00:00Z" })).toThrow(
+ ContextReceiptWindowError,
+ );
+ });
+
+ test("the canonical forms already in use still pass", () => {
+ seed("2026-06-06T10:00:00Z", "s1", [{ id: "pref-a", tokens: 5 }]);
+ expect(
+ summarizeContextReceiptSession(vault, {
+ since: "2026-06-05T00:00:00Z",
+ until: "2026-06-07T00:00:00.000Z",
+ }).recorded,
+ ).toBe(true);
+ });
+});
+
+describe("observedReuseRates filtering", () => {
+ test("a session filter narrows the lifetime fold", () => {
+ emitObservedUse(vault, {
+ createdAt: "2026-06-01T10:00:00Z",
+ host: "unit-test",
+ sessionId: "s1",
+ entries: [{ id: "pref-a", verdict: "USED" }],
+ });
+ emitObservedUse(vault, {
+ createdAt: "2026-06-01T11:00:00Z",
+ host: "unit-test",
+ sessionId: "s2",
+ entries: [{ id: "pref-a", verdict: "IGNORED" }],
+ });
+
+ expect(observedReuseRates(vault).get("pref-a")!.total).toBe(2);
+ const scoped = observedReuseRates(vault, { sessionId: "s1" });
+ expect(scoped.get("pref-a")!.total).toBe(1);
+ expect(scoped.get("pref-a")!.used).toBe(1);
+ });
+
+ test("a time window narrows the lifetime fold", () => {
+ emitObservedUse(vault, {
+ createdAt: "2026-06-01T10:00:00Z",
+ host: "unit-test",
+ entries: [{ id: "pref-a", verdict: "USED" }],
+ });
+ emitObservedUse(vault, {
+ createdAt: "2026-06-09T10:00:00Z",
+ host: "unit-test",
+ entries: [{ id: "pref-a", verdict: "CONTRADICTED" }],
+ });
+ const scoped = observedReuseRates(vault, { since: "2026-06-05T00:00:00Z" });
+ expect(scoped.get("pref-a")!.contradicted).toBe(1);
+ expect(scoped.get("pref-a")!.total).toBe(1);
+ });
+});
diff --git a/tests/core/brain/context-receipts.test.ts b/tests/core/brain/context-receipts.test.ts
index 5ab8c361..937d2dbf 100644
--- a/tests/core/brain/context-receipts.test.ts
+++ b/tests/core/brain/context-receipts.test.ts
@@ -5,7 +5,11 @@ import { join } from "node:path";
import { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";
import { packContext } from "../../../src/core/brain/context-pack.ts";
-import { emitContextReceipt } from "../../../src/core/brain/context-receipts.ts";
+import {
+ CONTEXT_RECEIPT_TRIGGERS,
+ emitContextReceipt,
+ isContextReceiptTrigger,
+} from "../../../src/core/brain/context-receipts.ts";
import { brainActivePath } from "../../../src/core/brain/paths.ts";
import { buildPreCompressPack } from "../../../src/core/brain/pre-compress-pack.ts";
import { writePreference } from "../../../src/core/brain/preference.ts";
@@ -106,6 +110,33 @@ describe("context receipts", () => {
}),
).toThrow("context receipt extra key collides with payload field: host");
});
+
+ test("the trigger vocabulary names the SessionStart eager layer", () => {
+ // Unit H: the eager layer emits receipts too, so a reader can tell a
+ // hook injection from a pack build instead of seeing only pack builds.
+ expect(isContextReceiptTrigger("session_inject")).toBe(true);
+ expect(isContextReceiptTrigger("not_a_trigger")).toBe(false);
+ expect([...CONTEXT_RECEIPT_TRIGGERS]).toEqual([
+ "context_pack",
+ "pre_compress",
+ "session_inject",
+ ]);
+ });
+
+ test("an item records its byte size beside its token estimate", () => {
+ const record = emitContextReceipt(vault, {
+ options: {
+ host: "unit-test",
+ trigger: "session_inject",
+ createdAt: "2026-05-31T12:20:00Z",
+ },
+ items: [{ id: "active-body", bytes: 12, tokens: 3 }],
+ finalText: "body",
+ });
+ const item = (record.payload["items"] as ReadonlyArray<Record<string, unknown>>)[0]!;
+ expect(item["bytes"]).toBe(12);
+ expect(item["tokens"]).toBe(3);
+ });
});
function writePref(slug: string, topic: string, principle: string, body: string): void {
diff --git a/tests/core/brain/doctor-brain-root.test.ts b/tests/core/brain/doctor-brain-root.test.ts
new file mode 100644
index 00000000..969b8214
--- /dev/null
+++ b/tests/core/brain/doctor-brain-root.test.ts
@@ -0,0 +1,48 @@
+/**
+ * Unit J - the doctor must not report a `Brain`-less root as clean.
+ *
+ * The diagnostic that should catch a mis-resolved vault actively masked
+ * it: an absent `Brain/` returned `{errors: [], trust_verdict: "clean"}`,
+ * so the one command an operator runs to check the store said the wrong
+ * root was fine.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-doctor-brain-root-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("runDoctor on a root with no Brain layer", () => {
+ test("names the condition instead of reporting clean", () => {
+ const result = runDoctor(vault);
+ expect(result.trust_verdict).not.toBe("clean");
+ expect(result.warnings.map((w) => w.code)).toContain("brain-root-absent");
+ const warning = result.warnings.find((w) => w.code === "brain-root-absent")!;
+ expect(warning.path).toBe(join(vault, "Brain"));
+ expect(result.uncertain?.map((u) => u.code)).toContain("brain-root-absent");
+ });
+
+ test("still never throws", () => {
+ expect(() => runDoctor(vault)).not.toThrow();
+ });
+
+ test("a root that does have a Brain layer is unaffected", () => {
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+ const result = runDoctor(vault);
+ expect(result.warnings.map((w) => w.code)).not.toContain("brain-root-absent");
+ });
+});
diff --git a/tests/core/brain/doctor-frontmatter-notices.test.ts b/tests/core/brain/doctor-frontmatter-notices.test.ts
new file mode 100644
index 00000000..3b71eebc
--- /dev/null
+++ b/tests/core/brain/doctor-frontmatter-notices.test.ts
@@ -0,0 +1,93 @@
+/**
+ * Unit F: the doctor surfaces frontmatter lines the scanner dropped.
+ *
+ * A note with unsupported frontmatter grammar is never excluded from the
+ * vault - individual fields simply vanish, leaving the page untyped,
+ * unaliased, or undated. `runDoctor` reports the drop through its
+ * `uncertain` extension point ("sub-operations the doctor attempted but
+ * cannot claim completed cleanly") without changing any severity: it is
+ * neither a warning nor an error, because nothing is provably broken -
+ * only unverifiable.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { writeVaultIdentity } from "../../../src/core/brain/vault-identity.ts";
+import { DEGRADATION_CODE } from "../../../src/core/integrity/degradation.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-doctor-fm-notices-"));
+ vault = join(tmp, "vault");
+ for (const d of ["preferences", "retired", "inbox", "processed", "log"]) {
+ mkdirSync(join(vault, "Brain", d), { recursive: true });
+ }
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+ // Unit J: an unmarked root is an uncertainty finding in its own
+ // right, so a fixture standing for a clean vault carries the marker
+ // `o2b brain init` would have stamped.
+ writeVaultIdentity(vault);
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("runDoctor frontmatter notices", () => {
+ test("a clean Brain tree reports no uncertain entries", () => {
+ writeFileSync(
+ join(vault, "Brain", "notes", "ok.md"),
+ "---\ntitle: Fine\ntopic: ok\ntags:\n - brain\n - brain/note\n---\n\nBody.\n",
+ );
+ const result = runDoctor(vault);
+ expect(result.uncertain ?? []).toEqual([]);
+ });
+
+ test("an unsupported frontmatter line is reported as an uncertain entry naming the file", () => {
+ writeFileSync(
+ join(vault, "Brain", "notes", "odd.md"),
+ "---\ntitle: Odd\ntopic: odd\n-foo\n---\n\nBody.\n",
+ );
+ const result = runDoctor(vault);
+ const entries = result.uncertain ?? [];
+ expect(entries.length).toBeGreaterThan(0);
+ const hit = entries.find((e) => (e.path ?? "").endsWith("odd.md"));
+ expect(hit).toBeDefined();
+ expect(hit!.code).toBe(DEGRADATION_CODE.frontmatterLineDropped);
+ expect(hit!.message).toContain("-foo");
+ });
+
+ test("the dropped line does not become a warning or an error", () => {
+ writeFileSync(
+ join(vault, "Brain", "notes", "odd.md"),
+ "---\ntitle: Odd\ntopic: odd\n-foo\n---\n\nBody.\n",
+ );
+ const result = runDoctor(vault);
+ for (const issue of [...result.warnings, ...result.errors]) {
+ expect(issue.code).not.toBe(DEGRADATION_CODE.frontmatterLineDropped);
+ }
+ });
+
+ test("a supported block-style list produces no uncertain entry", () => {
+ writeFileSync(
+ join(vault, "Brain", "notes", "block.md"),
+ "---\ntitle: Block\ntopic: block\ntags:\n - brain\n - brain/signal\n---\n\nBody.\n",
+ );
+ const result = runDoctor(vault);
+ expect(result.uncertain ?? []).toEqual([]);
+ });
+
+ test("the doctor still never throws on an unreadable Brain subtree", () => {
+ // A directory where a Markdown file is expected: the walker cannot
+ // parse it, and the doctor must still return a result.
+ mkdirSync(join(vault, "Brain", "notes", "dir.md"));
+ expect(() => runDoctor(vault)).not.toThrow();
+ });
+});
diff --git a/tests/core/brain/doctor-uncertain-surfaces.test.ts b/tests/core/brain/doctor-uncertain-surfaces.test.ts
new file mode 100644
index 00000000..82be4603
--- /dev/null
+++ b/tests/core/brain/doctor-uncertain-surfaces.test.ts
@@ -0,0 +1,130 @@
+/**
+ * The doctor's `uncertain` stream, and the two producers that were
+ * written for it and never wired to it.
+ *
+ * `vaultMarkerAbsentNotice` shipped pure, throwing, tested - and with no
+ * caller inside `runDoctor`, so the one condition an unmarked root is
+ * diagnostic of (a mis-resolved vault materialized by its first write)
+ * never reached the one command an operator runs to check the store.
+ *
+ * `scanStaleLocks` shipped with a docblock reading "the brain doctor
+ * surfaces these" and `rg scanStaleLocks src/` matching only its own
+ * definition. The lock primitive deliberately has no breaker, so a lock
+ * a SIGKILLed writer left behind is recoverable ONLY by an operator
+ * deleting it - which requires something to name it first.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { DEGRADATION_CODE } from "../../../src/core/integrity/degradation.ts";
+import { acquireLockSync } from "../../../src/core/brain/sync-lockfile.ts";
+import { recordLineageObservation } from "../../../src/core/brain/lineage/ledger.ts";
+import {
+ resetVaultIdentityPins,
+ writeVaultIdentity,
+} from "../../../src/core/brain/vault-identity.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-doctor-uncertain-"));
+ vault = join(tmp, "vault");
+ for (const d of ["preferences", "retired", "inbox", "processed", "log"]) {
+ mkdirSync(join(vault, "Brain", d), { recursive: true });
+ }
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");
+ resetVaultIdentityPins();
+});
+
+afterEach(() => {
+ resetVaultIdentityPins();
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function codes(): string[] {
+ return (runDoctor(vault).uncertain ?? []).map((entry) => entry.code);
+}
+
+describe("runDoctor β€” the vault identity marker", () => {
+ test("an unmarked root is reported as uncertainty, naming the root", () => {
+ const entry = (runDoctor(vault).uncertain ?? []).find(
+ (u) => u.code === DEGRADATION_CODE.vaultMarkerAbsent,
+ );
+ expect(entry).toBeDefined();
+ expect(entry!.path).toBeDefined();
+ expect(entry!.message).toContain("o2b brain init");
+ });
+
+ test("a marked root reports nothing", () => {
+ writeVaultIdentity(vault);
+ expect(codes()).not.toContain(DEGRADATION_CODE.vaultMarkerAbsent);
+ });
+
+ test("a CORRUPT marker reads as absent, never as a mismatch", () => {
+ writeFileSync(join(vault, "Brain", "vault-id.json"), "{ not json", "utf8");
+ expect(codes()).toContain(DEGRADATION_CODE.vaultMarkerAbsent);
+ // And the doctor still completes: a corrupt marker is a warning
+ // condition, not a refusal.
+ expect(runDoctor(vault).errors).toEqual([]);
+ });
+
+ test("it never throws the doctor", () => {
+ rmSync(join(vault, "Brain", "_brain.yaml"));
+ expect(() => runDoctor(vault)).not.toThrow();
+ });
+});
+
+describe("runDoctor β€” writer locks left on disk", () => {
+ test("a held lock under Brain/ is named with its path", () => {
+ writeVaultIdentity(vault);
+ const target = join(vault, "Brain", "log", "continuity", "2026-06.jsonl");
+ mkdirSync(join(vault, "Brain", "log", "continuity"), { recursive: true });
+ const handle = acquireLockSync(target);
+ try {
+ const entry = (runDoctor(vault).uncertain ?? []).find((u) => u.code === "stale-lock");
+ expect(entry).toBeDefined();
+ expect(entry!.path).toBe(handle.path);
+ expect(entry!.message).toContain("remove the file by hand");
+ } finally {
+ handle.release();
+ }
+ });
+
+ test("a vault with no locks reports none", () => {
+ writeVaultIdentity(vault);
+ expect(codes()).not.toContain("stale-lock");
+ });
+});
+
+describe("runDoctor β€” lineage ledger findings reach uncertain", () => {
+ test("a destroyed ledger is uncertainty, not silence", () => {
+ writeVaultIdentity(vault);
+ mkdirSync(join(vault, "Brain", ".state"), { recursive: true });
+ writeFileSync(join(vault, "Brain", ".state", "session-lineage.jsonl"), "garbage\n", "utf8");
+ expect(codes()).toContain(DEGRADATION_CODE.lineageChainBroken);
+ });
+
+ test("a dropped observation is uncertainty too", () => {
+ writeVaultIdentity(vault);
+ recordLineageObservation(vault, { sessionId: "s-1", at: new Date().toISOString(), event: "S" });
+ const ledger = join(vault, "Brain", ".state", "session-lineage.jsonl");
+ const handle = acquireLockSync(ledger);
+ let found: string[];
+ try {
+ recordLineageObservation(vault, {
+ sessionId: "s-2",
+ at: new Date().toISOString(),
+ event: "S",
+ });
+ found = codes();
+ } finally {
+ handle.release();
+ }
+ expect(found).toContain(DEGRADATION_CODE.lineageObservationDropped);
+ });
+});
diff --git a/tests/core/brain/lineage-continuation.test.ts b/tests/core/brain/lineage-continuation.test.ts
new file mode 100644
index 00000000..c3393547
--- /dev/null
+++ b/tests/core/brain/lineage-continuation.test.ts
@@ -0,0 +1,670 @@
+/**
+ * Fail-closed session continuation (context-integrity-gates, Unit C /
+ * Task 11).
+ *
+ * The interim crutch used to resolve a multi-candidate set by picking
+ * the most recent predecessor, and to report every refusal as a bare
+ * `null` that four distinct causes collapsed into. Both are pinned here
+ * as defects: ambiguity must ABSTAIN, and every refusal must name its
+ * own reason. Repo, branch and commit join `cwd` as required-match
+ * predicates, captured through the hardened git argv reader under a
+ * bounded timeout and canonicalized so a credential-bearing clone is
+ * the same identity as a credential-free one - and so the credential
+ * never reaches a recorded field.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ DEGRADATION_CODE,
+ type DegradationNotice,
+} from "../../../src/core/integrity/degradation.ts";
+import {
+ canonicalizeGitRemote,
+ type GitWorkspaceIdentity,
+ readGitWorkspaceIdentity,
+} from "../../../src/core/brain/git/reader.ts";
+import { CRUTCH_ABSTENTION, resolveCrutchLineage } from "../../../src/core/brain/lineage/crutch.ts";
+import {
+ CRUTCH_LINK_WINDOW_MS,
+ LINEAGE_RECORD_STATUS,
+ lineageGapSessionIds,
+ readLineageLedger,
+ recordLineageObservation,
+ sessionLineageLedgerPath,
+} from "../../../src/core/brain/lineage/ledger.ts";
+import { acquireLockSync } from "../../../src/core/brain/sync-lockfile.ts";
+import {
+ resolveSessionLineage,
+ resolveSessionLineageDetailed,
+} from "../../../src/core/brain/lineage/resolve.ts";
+import { captureSessionLifecycleEvent } from "../../../src/core/brain/session-lifecycle.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-continuation-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const T0 = Date.parse("2026-06-10T08:00:00Z");
+
+// ----- git fixture ---------------------------------------------------------
+
+/** A remote whose credentials must never survive canonicalization. */
+const SECRET_REMOTE = "https://alice:[email protected]:8443/org/repo.git/";
+const SECRET_REMOTE_IDENTITY = "https://git.example.invalid/org/repo";
+
+function git(dir: string, args: ReadonlyArray<string>): void {
+ execFileSync("git", ["-C", dir, ...args], { stdio: "ignore" });
+}
+
+function initRepo(dir: string, opts: { remote?: string; branch?: string } = {}): string {
+ mkdirSync(dir, { recursive: true });
+ execFileSync("git", ["init", "--quiet", `--initial-branch=${opts.branch ?? "main"}`, dir], {
+ stdio: "ignore",
+ });
+ git(dir, ["config", "user.email", "[email protected]"]);
+ git(dir, ["config", "user.name", "Fixture"]);
+ git(dir, ["config", "commit.gpgsign", "false"]);
+ if (opts.remote !== undefined) git(dir, ["remote", "add", "origin", opts.remote]);
+ writeFileSync(join(dir, "a.txt"), "one\n", "utf8");
+ git(dir, ["add", "a.txt"]);
+ git(dir, ["commit", "--quiet", "--no-gpg-sign", "-m", "one"]);
+ return dir;
+}
+
+function commitAgain(dir: string, text: string): void {
+ writeFileSync(join(dir, "a.txt"), text, "utf8");
+ git(dir, ["add", "a.txt"]);
+ git(dir, ["commit", "--quiet", "--no-gpg-sign", "-m", text]);
+}
+
+// ----- the canonicalizer ---------------------------------------------------
+
+describe("canonicalizeGitRemote β€” a comparable identity, not a redaction", () => {
+ test("strips userinfo, port, .git suffix and trailing slash", () => {
+ expect(canonicalizeGitRemote(SECRET_REMOTE)).toBe(SECRET_REMOTE_IDENTITY);
+ });
+
+ test("a credential-bearing clone is the SAME identity as a credential-free one", () => {
+ const withCreds = canonicalizeGitRemote("https://u:[email protected]/org/repo.git");
+ const withOther = canonicalizeGitRemote("https://other:[email protected]/org/repo");
+ const without = canonicalizeGitRemote("https://github.com/org/repo");
+ expect(withCreds).toBe(without!);
+ expect(withOther).toBe(without!);
+ });
+
+ test("never carries the credential through", () => {
+ const out = canonicalizeGitRemote(SECRET_REMOTE)!;
+ expect(out.includes("s3cr3t-token")).toBe(false);
+ expect(out.includes("alice")).toBe(false);
+ expect(out.includes("@")).toBe(false);
+ });
+
+ test("scp-style and ssh-url forms normalize to one identity", () => {
+ const scp = canonicalizeGitRemote("[email protected]:org/repo.git");
+ expect(scp).toBe("ssh://github.com/org/repo");
+ expect(canonicalizeGitRemote("ssh://[email protected]:22/org/repo.git/")).toBe(scp!);
+ });
+
+ test("host case is normalized, path case is not", () => {
+ expect(canonicalizeGitRemote("https://GitHub.COM/Org/Repo.git")).toBe(
+ "https://github.com/Org/Repo",
+ );
+ });
+
+ test("a local path remote becomes a file identity", () => {
+ expect(canonicalizeGitRemote("/srv/git/thing.git/")).toBe("file:///srv/git/thing");
+ });
+
+ test("blank or hostless input is null, never a placeholder", () => {
+ expect(canonicalizeGitRemote("")).toBeNull();
+ expect(canonicalizeGitRemote(" ")).toBeNull();
+ expect(canonicalizeGitRemote("https://")).toBeNull();
+ });
+});
+
+// ----- the probe -----------------------------------------------------------
+
+describe("readGitWorkspaceIdentity β€” hardened, bounded probe", () => {
+ test("reads repo, branch and commit from a throwaway repository", () => {
+ const repo = initRepo(join(tmp, "repo"), { remote: SECRET_REMOTE, branch: "trunk" });
+ const identity = readGitWorkspaceIdentity(repo);
+ expect(identity).not.toBeNull();
+ expect(identity!.repo).toBe(SECRET_REMOTE_IDENTITY);
+ expect(identity!.branch).toBe("trunk");
+ expect(identity!.commit).toMatch(/^[0-9a-f]{40}$/);
+ });
+
+ test("the recorded repo identity never carries the clone credential", () => {
+ const repo = initRepo(join(tmp, "repo"), { remote: SECRET_REMOTE });
+ const identity = readGitWorkspaceIdentity(repo)!;
+ expect(JSON.stringify(identity).includes("s3cr3t-token")).toBe(false);
+ });
+
+ test("a SUBDIRECTORY of the repository resolves the same identity", () => {
+ const repo = initRepo(join(tmp, "repo"), { remote: SECRET_REMOTE });
+ const sub = join(repo, "src", "deep");
+ mkdirSync(sub, { recursive: true });
+ expect(readGitWorkspaceIdentity(sub)).toEqual(readGitWorkspaceIdentity(repo)!);
+ });
+
+ test("a new commit changes the identity", () => {
+ const repo = initRepo(join(tmp, "repo"), { remote: SECRET_REMOTE });
+ const before = readGitWorkspaceIdentity(repo)!;
+ commitAgain(repo, "two\n");
+ const after = readGitWorkspaceIdentity(repo)!;
+ expect(after.commit).not.toBe(before.commit!);
+ expect(after.repo).toBe(before.repo!);
+ });
+
+ test("a directory that is not a repository reads as no identity", () => {
+ const plain = join(tmp, "plain");
+ mkdirSync(plain, { recursive: true });
+ expect(readGitWorkspaceIdentity(plain)).toBeNull();
+ expect(readGitWorkspaceIdentity(join(tmp, "does-not-exist"))).toBeNull();
+ });
+
+ test("a repository with no remote still reports branch and commit", () => {
+ const repo = initRepo(join(tmp, "bare-remote"));
+ const identity = readGitWorkspaceIdentity(repo)!;
+ expect(identity.repo).toBeNull();
+ expect(identity.branch).toBe("main");
+ });
+
+ test("the probe is bounded: an exhausted budget yields no identity, never a hang", () => {
+ const repo = initRepo(join(tmp, "repo"), { remote: SECRET_REMOTE });
+ expect(readGitWorkspaceIdentity(repo, { timeoutMs: 1 })).toBeNull();
+ });
+});
+
+// ----- the resolver --------------------------------------------------------
+
+function seed(opts: {
+ sessionId: string;
+ atMs?: number;
+ cwd?: string;
+ evidence?: boolean;
+ workspace?: GitWorkspaceIdentity;
+}): void {
+ recordLineageObservation(tmp, {
+ sessionId: opts.sessionId,
+ at: new Date(opts.atMs ?? T0).toISOString(),
+ cwd: opts.cwd ?? "/work",
+ event: opts.evidence === false ? "Stop" : "PostCompact",
+ ...(opts.evidence === false ? {} : { compressionEvidence: true }),
+ ...(opts.workspace !== undefined ? { workspace: opts.workspace } : {}),
+ });
+}
+
+const WS_MAIN: GitWorkspaceIdentity = {
+ repo: "https://git.example.invalid/org/repo",
+ branch: "main",
+ commit: "a".repeat(40),
+};
+
+function outcome(
+ sessionId: string,
+ over: Partial<Parameters<typeof resolveCrutchLineage>[0]> = {},
+) {
+ return resolveCrutchLineage({
+ sessionId,
+ cwd: "/work",
+ ledger: readLineageLedger(tmp),
+ nowMs: T0 + 30_000,
+ ...over,
+ });
+}
+
+describe("resolveCrutchLineage β€” every refusal names itself", () => {
+ test("links a single surviving candidate", () => {
+ seed({ sessionId: "s-old" });
+ const result = outcome("s-new");
+ expect(result.kind).toBe("linked");
+ if (result.kind !== "linked") throw new Error("unreachable");
+ expect(result.lineage).toEqual({
+ rootId: "s-old",
+ parentId: "s-old",
+ depth: 1,
+ source: "crutch",
+ });
+ });
+
+ test("TWO surviving candidates ABSTAIN instead of taking the most recent", () => {
+ seed({ sessionId: "s-a", atMs: T0 });
+ seed({ sessionId: "s-b", atMs: T0 + 10_000 });
+ const result = outcome("s-new");
+ expect(result.kind).toBe("abstained");
+ if (result.kind !== "abstained") throw new Error("unreachable");
+ expect(result.reason).toBe(CRUTCH_ABSTENTION.ambiguous);
+ expect(result.considered).toBe(2);
+ expect(result.detail.length).toBeGreaterThan(0);
+ });
+
+ test("no ledger at all abstains with no-candidate", () => {
+ const result = outcome("s-new");
+ expect(result).toMatchObject({ kind: "abstained", reason: CRUTCH_ABSTENTION.noCandidate });
+ });
+
+ test("a session with its own unlinked history abstains with self-known", () => {
+ seed({ sessionId: "s-old" });
+ seed({ sessionId: "s-new", atMs: T0 - 120_000, evidence: false });
+ const result = outcome("s-new");
+ expect(result).toMatchObject({ kind: "abstained", reason: CRUTCH_ABSTENTION.selfKnown });
+ });
+
+ test("an absent working directory abstains with no-workspace", () => {
+ seed({ sessionId: "s-old" });
+ expect(outcome("s-new", { cwd: undefined })).toMatchObject({
+ kind: "abstained",
+ reason: CRUTCH_ABSTENTION.noWorkspace,
+ });
+ expect(outcome("s-new", { cwd: "" })).toMatchObject({
+ kind: "abstained",
+ reason: CRUTCH_ABSTENTION.noWorkspace,
+ });
+ });
+
+ test("a candidate outside the freshness window abstains with stale", () => {
+ seed({ sessionId: "s-old" });
+ const result = outcome("s-new", { nowMs: T0 + CRUTCH_LINK_WINDOW_MS + 1 });
+ expect(result).toMatchObject({ kind: "abstained", reason: CRUTCH_ABSTENTION.stale });
+ });
+
+ test("a candidate without compression evidence abstains with evidence-missing", () => {
+ seed({ sessionId: "s-old", evidence: false });
+ const result = outcome("s-new");
+ expect(result).toMatchObject({
+ kind: "abstained",
+ reason: CRUTCH_ABSTENTION.evidenceMissing,
+ });
+ });
+
+ test("a candidate in another working directory is no-candidate, not a near miss", () => {
+ seed({ sessionId: "s-old", cwd: "/elsewhere" });
+ expect(outcome("s-new")).toMatchObject({
+ kind: "abstained",
+ reason: CRUTCH_ABSTENTION.noCandidate,
+ });
+ });
+
+ test("a predecessor another session already continued from is not a candidate", () => {
+ // A -> B is recorded; C must resolve to B alone, not read A and B
+ // as an ambiguous pair. A compaction boundary has one successor.
+ seed({ sessionId: "s-a", atMs: T0 });
+ recordLineageObservation(tmp, {
+ sessionId: "s-b",
+ at: new Date(T0 + 10_000).toISOString(),
+ cwd: "/work",
+ event: "PostCompact",
+ compressionEvidence: true,
+ lineage: { rootId: "s-a", parentId: "s-a", depth: 1, source: "crutch" },
+ });
+ const result = outcome("s-c");
+ expect(result.kind).toBe("linked");
+ if (result.kind !== "linked") throw new Error("unreachable");
+ expect(result.lineage).toEqual({
+ rootId: "s-a",
+ parentId: "s-b",
+ depth: 2,
+ source: "crutch",
+ });
+ });
+
+ test("the nearest miss wins: evidence-missing outranks stale", () => {
+ seed({ sessionId: "s-stale", atMs: T0 - CRUTCH_LINK_WINDOW_MS - 1 });
+ seed({ sessionId: "s-noevidence", evidence: false });
+ expect(outcome("s-new")).toMatchObject({
+ kind: "abstained",
+ reason: CRUTCH_ABSTENTION.evidenceMissing,
+ });
+ });
+});
+
+describe("resolveCrutchLineage β€” repo, branch and commit are match predicates", () => {
+ test("an identical workspace identity links", () => {
+ seed({ sessionId: "s-old", workspace: WS_MAIN });
+ expect(outcome("s-new", { workspace: WS_MAIN }).kind).toBe("linked");
+ });
+
+ test("a different BRANCH does not link", () => {
+ seed({ sessionId: "s-old", workspace: WS_MAIN });
+ const result = outcome("s-new", { workspace: { ...WS_MAIN, branch: "feature" } });
+ expect(result.kind).toBe("abstained");
+ });
+
+ test("a different COMMIT does not link", () => {
+ seed({ sessionId: "s-old", workspace: WS_MAIN });
+ const result = outcome("s-new", { workspace: { ...WS_MAIN, commit: "b".repeat(40) } });
+ expect(result.kind).toBe("abstained");
+ });
+
+ test("a different REPO does not link", () => {
+ seed({ sessionId: "s-old", workspace: WS_MAIN });
+ const result = outcome("s-new", {
+ workspace: { ...WS_MAIN, repo: "https://git.example.invalid/org/other" },
+ });
+ expect(result.kind).toBe("abstained");
+ });
+
+ test("an attested candidate against an unattested session abstains with evidence-missing", () => {
+ seed({ sessionId: "s-old", workspace: WS_MAIN });
+ expect(outcome("s-new")).toMatchObject({
+ kind: "abstained",
+ reason: CRUTCH_ABSTENTION.evidenceMissing,
+ });
+ });
+
+ test("an unattested candidate against an attested session abstains with evidence-missing", () => {
+ seed({ sessionId: "s-old" });
+ expect(outcome("s-new", { workspace: WS_MAIN })).toMatchObject({
+ kind: "abstained",
+ reason: CRUTCH_ABSTENTION.evidenceMissing,
+ });
+ });
+
+ test("two unattested sides still link β€” a non-git workspace is not a refusal", () => {
+ seed({ sessionId: "s-old" });
+ expect(outcome("s-new").kind).toBe("linked");
+ });
+});
+
+// ----- the ledger carries the identity -------------------------------------
+
+describe("lineage ledger β€” workspace identity round-trip", () => {
+ test("records and reads back repo, branch and commit", () => {
+ seed({ sessionId: "s-1", workspace: WS_MAIN });
+ expect(readLineageLedger(tmp).get("s-1")?.workspace).toEqual(WS_MAIN);
+ });
+
+ test("compaction preserves the workspace identity", () => {
+ // Compaction retains the most recent LINES verbatim, so the line
+ // under test has to be inside the retention window when the rewrite
+ // runs - which is the realistic case, the ledger being append-only.
+ const filler = (from: number, count: number): void => {
+ for (let i = from; i < from + count; i++) {
+ recordLineageObservation(tmp, {
+ sessionId: `filler-${i}`,
+ at: new Date(T0 + i * 1_000).toISOString(),
+ event: "Stop",
+ });
+ }
+ };
+ filler(0, 510);
+ seed({ sessionId: "s-keep", atMs: T0 + 510_000, workspace: WS_MAIN });
+ filler(511, 5); // crosses the cap and rewrites the file
+ expect(readLineageLedger(tmp).get("s-keep")?.workspace).toEqual(WS_MAIN);
+ });
+});
+
+// ----- resolution surface --------------------------------------------------
+
+describe("resolveSessionLineageDetailed β€” the abstention reaches the caller", () => {
+ test("carries the crutch outcome alongside the lineage", () => {
+ seed({ sessionId: "s-a", atMs: T0 });
+ seed({ sessionId: "s-b", atMs: T0 + 10_000 });
+ const resolution = resolveSessionLineageDetailed(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 30_000 },
+ );
+ expect(resolution.lineage.source).toBe("flat");
+ expect(resolution.crutch).toMatchObject({
+ kind: "abstained",
+ reason: CRUTCH_ABSTENTION.ambiguous,
+ });
+ });
+
+ test("an ambiguous abstention emits a sessionLinkAbstained notice", () => {
+ seed({ sessionId: "s-a", atMs: T0 });
+ seed({ sessionId: "s-b", atMs: T0 + 10_000 });
+ const notices: DegradationNotice[] = [];
+ resolveSessionLineageDetailed(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 30_000, notices },
+ );
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.code).toBe(DEGRADATION_CODE.sessionLinkAbstained);
+ expect(notices[0]!.detail).toContain(CRUTCH_ABSTENTION.ambiguous);
+ });
+
+ test("the ordinary flat path emits NO notice", () => {
+ const notices: DegradationNotice[] = [];
+ resolveSessionLineageDetailed(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 30_000, notices },
+ );
+ expect(notices).toHaveLength(0);
+ });
+
+ test("a link emits no notice", () => {
+ seed({ sessionId: "s-old" });
+ const notices: DegradationNotice[] = [];
+ const resolution = resolveSessionLineageDetailed(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 30_000, notices },
+ );
+ expect(resolution.lineage.source).toBe("crutch");
+ expect(notices).toHaveLength(0);
+ });
+
+ test("resolveSessionLineage stays flat on an abstention and never throws", () => {
+ seed({ sessionId: "s-a", atMs: T0 });
+ seed({ sessionId: "s-b", atMs: T0 + 10_000 });
+ expect(
+ resolveSessionLineage(
+ { sessionId: "s-new", cwd: "/work" },
+ { ledger: readLineageLedger(tmp), nowMs: T0 + 30_000 },
+ ),
+ ).toEqual({ rootId: "s-new", parentId: null, depth: 0, source: "flat" });
+ });
+});
+
+// ----- a dropped observation is still the session's own history ------------
+
+describe("resolveCrutchLineage β€” a DROPPED observation cannot become a FALSE STITCH", () => {
+ /**
+ * Rule 1 ("a session with its own ledger history is parallel, never a
+ * continuation") is tested by the presence of the session's own ledger
+ * line. A writer-lock drop removes exactly that evidence, so without
+ * the gap sidecar the resolver reads a session that DID speak as one
+ * that never has - and stitches it onto an unrelated parallel session.
+ * A false stitch is strictly worse than a missed one, and the
+ * anticipatory cache derives its file from the lineage root, so this
+ * redirects one conversation's cache into another's.
+ */
+ function dropObservation(sessionId: string, atMs: number): void {
+ const handle = acquireLockSync(sessionLineageLedgerPath(tmp));
+ try {
+ const result = recordLineageObservation(tmp, {
+ sessionId,
+ at: new Date(atMs).toISOString(),
+ cwd: "/work",
+ event: "Stop",
+ });
+ expect(result.status).toBe(LINEAGE_RECORD_STATUS.dropped);
+ } finally {
+ handle.release();
+ }
+ }
+
+ test("a session whose only observation was dropped abstains with self-known", () => {
+ seed({ sessionId: "s-parallel", atMs: T0 });
+ dropObservation("s-spoke", T0 + 5_000);
+ expect(readLineageLedger(tmp).has("s-spoke")).toBe(false);
+
+ const result = outcome("s-spoke", { gapSessionIds: lineageGapSessionIds(tmp) });
+ expect(result).toMatchObject({
+ kind: "abstained",
+ reason: CRUTCH_ABSTENTION.selfKnown,
+ });
+ });
+
+ test("without the gap set the same ledger produces the false stitch", () => {
+ // Pins WHY the observation has to be threaded: the ledger alone
+ // cannot tell "never spoke" from "spoke and was dropped".
+ seed({ sessionId: "s-parallel", atMs: T0 });
+ dropObservation("s-spoke", T0 + 5_000);
+ expect(outcome("s-spoke").kind).toBe("linked");
+ });
+
+ test("a session with no gap and no history still links normally", () => {
+ seed({ sessionId: "s-parallel", atMs: T0 });
+ dropObservation("s-spoke", T0 + 5_000);
+ const result = outcome("s-fresh", { gapSessionIds: lineageGapSessionIds(tmp) });
+ expect(result.kind).toBe("linked");
+ });
+
+ test("resolveSessionLineageDetailed threads the gap set through", () => {
+ seed({ sessionId: "s-parallel", atMs: T0 });
+ dropObservation("s-spoke", T0 + 5_000);
+ const resolution = resolveSessionLineageDetailed(
+ { sessionId: "s-spoke", cwd: "/work" },
+ {
+ ledger: readLineageLedger(tmp),
+ gapSessionIds: lineageGapSessionIds(tmp),
+ nowMs: T0 + 30_000,
+ },
+ );
+ expect(resolution.lineage.source).toBe("flat");
+ expect(resolution.crutch).toMatchObject({ reason: CRUTCH_ABSTENTION.selfKnown });
+ });
+});
+
+// ----- the hook path -------------------------------------------------------
+
+describe("captureSessionLifecycleEvent β€” fail-closed, fail-soft, credential-free", () => {
+ let vault: string;
+ let repo: string;
+
+ beforeEach(() => {
+ vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ bootstrapBrain(vault);
+ repo = initRepo(join(tmp, "repo"), { remote: SECRET_REMOTE });
+ });
+
+ test("stamps the canonical workspace identity onto the ledger observation", async () => {
+ await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "g-1", cwd: repo, prompt: "hi" },
+ { agent: "tester", now: new Date(T0) },
+ );
+ const entry = readLineageLedger(vault).get("g-1");
+ expect(entry?.workspace?.repo).toBe(SECRET_REMOTE_IDENTITY);
+ expect(entry?.workspace?.commit).toMatch(/^[0-9a-f]{40}$/);
+ });
+
+ test("the clone credential never reaches the ledger file", async () => {
+ await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "g-2", cwd: repo, prompt: "hi" },
+ { agent: "tester", now: new Date(T0) },
+ );
+ const raw = readFileSync(sessionLineageLedgerPath(vault), "utf8");
+ expect(raw.includes("s3cr3t-token")).toBe(false);
+ expect(raw.includes("alice")).toBe(false);
+ });
+
+ test("stitches within one repository state and REFUSES after a new commit", async () => {
+ await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "PostCompact", session_id: "g-old", cwd: repo },
+ { agent: "tester", now: new Date(T0) },
+ );
+ const linked = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "g-mid", cwd: repo, prompt: "go" },
+ { agent: "tester", now: new Date(T0 + 60_000) },
+ );
+ expect(linked.lineage?.source).toBe("crutch");
+
+ await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "PostCompact", session_id: "g-mid", cwd: repo },
+ { agent: "tester", now: new Date(T0 + 70_000) },
+ );
+ commitAgain(repo, "moved on\n");
+ const refused = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "g-next", cwd: repo, prompt: "go" },
+ { agent: "tester", now: new Date(T0 + 80_000) },
+ );
+ expect("lineage" in refused).toBe(false);
+ });
+
+ test("two concurrent sessions in one repository state both abstain", async () => {
+ // Two conversations running side by side in one working tree: each
+ // is already known to the ledger before either compacts, so neither
+ // is the other's continuation, and both compact inside the window.
+ // Sequential by construction: the ledger state each call observes is
+ // the state the previous call left behind, so these cannot be
+ // collapsed into a parallel await.
+ const capture = (payload: Record<string, unknown>, atMs: number): Promise<unknown> =>
+ captureSessionLifecycleEvent(vault, payload, {
+ agent: "tester",
+ now: new Date(atMs),
+ });
+ await capture(
+ { hook_event_name: "UserPromptSubmit", session_id: "c-a", cwd: repo, prompt: "work" },
+ T0,
+ );
+ await capture(
+ { hook_event_name: "UserPromptSubmit", session_id: "c-b", cwd: repo, prompt: "work" },
+ T0,
+ );
+ await capture({ hook_event_name: "PostCompact", session_id: "c-a", cwd: repo }, T0 + 10_000);
+ await capture({ hook_event_name: "PostCompact", session_id: "c-b", cwd: repo }, T0 + 10_000);
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "c-new", cwd: repo, prompt: "go" },
+ { agent: "tester", now: new Date(T0 + 60_000) },
+ );
+ expect("lineage" in result).toBe(false);
+ // The refusal is not merely silent-and-flat: it is on the record.
+ const audit = readFileSync(result.audit_path, "utf8");
+ expect(audit).toContain(DEGRADATION_CODE.sessionLinkAbstained);
+ expect(audit).toContain(CRUTCH_ABSTENTION.ambiguous);
+ });
+
+ test("a dropped observation reaches the audit record instead of being discarded", async () => {
+ // `recordLineageObservation` returns a NAMED notice when the writer
+ // lock refuses the append; the call site used to be a bare statement
+ // that threw it away, which is a silent failure with extra steps.
+ const handle = acquireLockSync(sessionLineageLedgerPath(vault));
+ let result;
+ try {
+ result = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "d-1", cwd: repo, prompt: "hi" },
+ { agent: "tester", now: new Date(T0) },
+ );
+ } finally {
+ handle.release();
+ }
+ const audit = JSON.parse(
+ readFileSync(result.audit_path, "utf8").trim().split("\n").at(-1)!,
+ ) as { details: Record<string, unknown> };
+ const dropped = audit.details["lineage_dropped"] as string[];
+ expect(dropped).toBeDefined();
+ expect(dropped[0]).toContain(DEGRADATION_CODE.lineageObservationDropped);
+ expect(dropped[0]).toContain("d-1");
+ });
+
+ test("a successful append leaves the audit shape unchanged", async () => {
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ { hook_event_name: "UserPromptSubmit", session_id: "d-2", cwd: repo, prompt: "hi" },
+ { agent: "tester", now: new Date(T0) },
+ );
+ expect(readFileSync(result.audit_path, "utf8")).not.toContain("lineage_dropped");
+ });
+});
diff --git a/tests/core/brain/lineage-ledger-integrity.test.ts b/tests/core/brain/lineage-ledger-integrity.test.ts
new file mode 100644
index 00000000..11a3df83
--- /dev/null
+++ b/tests/core/brain/lineage-ledger-integrity.test.ts
@@ -0,0 +1,563 @@
+/**
+ * Lineage ledger integrity (context-integrity-gates, Unit D / Task 12).
+ *
+ * The ledger was append-only JSONL with no sequence numbers, no hash
+ * chain, no writer lock and no verification. Four losses are pinned here
+ * as defects:
+ *
+ * - compaction folded the file to ONE SUMMARY LINE PER SESSION,
+ * destroying per-session event history and `firstSeenMs` outright;
+ * - its re-serializer hard-coded its field list, so any field added to
+ * the writer vanished at the next compaction;
+ * - the compaction branch was a read-modify-write with no mutual
+ * exclusion, so a concurrent writer's observation was clobbered;
+ * - a dropped observation left no trace at all.
+ *
+ * The read path stays fail-soft throughout: verification is a separate
+ * function that REPORTS, and `readLineageLedger` still returns an empty
+ * map rather than throwing on a corrupt file, because the anticipatory
+ * cache and the lifecycle hook both depend on that.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ appendFileSync,
+ chmodSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ utimesSync,
+ writeFileSync,
+} from "node:fs";
+import { dirname, join } from "node:path";
+import { tmpdir } from "node:os";
+
+import { DEGRADATION_CODE } from "../../../src/core/integrity/degradation.ts";
+import {
+ LINEAGE_RECORD_STATUS,
+ readLineageGapReport,
+ readLineageLedger,
+ recordLineageObservation,
+ sessionLineageGapsPath,
+ sessionLineageLedgerPath,
+} from "../../../src/core/brain/lineage/ledger.ts";
+import { verifyLineageLedger } from "../../../src/core/brain/lineage/verify.ts";
+import { acquireLockSync } from "../../../src/core/brain/sync-lockfile.ts";
+
+let tmp: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-ledger-"));
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const T0 = Date.parse("2026-06-10T08:00:00Z");
+
+interface RawLine {
+ readonly sid: string;
+ readonly at: string;
+ readonly event: string;
+ readonly seq?: number;
+ readonly prev?: string | null;
+ readonly h?: string;
+ readonly [key: string]: unknown;
+}
+
+function rawLines(vault: string): RawLine[] {
+ const raw = readFileSync(sessionLineageLedgerPath(vault), "utf8");
+ return raw
+ .split("\n")
+ .filter((line) => line.trim().length > 0)
+ .map((line) => JSON.parse(line) as RawLine);
+}
+
+function record(sessionId: string, atMs: number, over: Record<string, unknown> = {}) {
+ return recordLineageObservation(tmp, {
+ sessionId,
+ at: new Date(atMs).toISOString(),
+ event: "Stop",
+ ...over,
+ });
+}
+
+// ----- sequence numbers and the hash chain ---------------------------------
+
+describe("recordLineageObservation β€” sequence numbers and hash chain", () => {
+ test("allocates a contiguous sequence and links each line to the last", () => {
+ record("s-1", T0);
+ record("s-2", T0 + 1_000);
+ record("s-3", T0 + 2_000);
+ const lines = rawLines(tmp);
+ expect(lines.map((line) => line.seq)).toEqual([1, 2, 3]);
+ expect(lines[0]!.prev).toBeNull();
+ expect(lines[1]!.prev).toBe(lines[0]!.h!);
+ expect(lines[2]!.prev).toBe(lines[1]!.h!);
+ expect(lines[2]!.h).toMatch(/^[0-9a-f]{64}$/);
+ });
+
+ test("reports the allocated sequence to the caller", () => {
+ expect(record("s-1", T0)).toMatchObject({
+ status: LINEAGE_RECORD_STATUS.appended,
+ seq: 1,
+ });
+ expect(record("s-2", T0 + 1_000)).toMatchObject({
+ status: LINEAGE_RECORD_STATUS.appended,
+ seq: 2,
+ });
+ });
+
+ test("a clean ledger verifies with no findings", () => {
+ record("s-1", T0);
+ record("s-1", T0 + 1_000, { event: "PostCompact", compressionEvidence: true });
+ const report = verifyLineageLedger(tmp);
+ expect(report.ok).toBe(true);
+ expect(report.notices).toHaveLength(0);
+ expect(report.chained).toBe(2);
+ expect(report.legacy).toBe(0);
+ });
+});
+
+describe("verifyLineageLedger β€” reports, never refuses", () => {
+ test("a tampered line is reported with its sequence number", () => {
+ record("s-1", T0);
+ record("s-2", T0 + 1_000);
+ record("s-3", T0 + 2_000);
+ const path = sessionLineageLedgerPath(tmp);
+ const lines = readFileSync(path, "utf8")
+ .split("\n")
+ .filter((l) => l.trim().length > 0);
+ const tampered = JSON.parse(lines[1]!) as RawLine;
+ lines[1] = JSON.stringify({ ...tampered, cwd: "/somewhere-else" });
+ writeFileSync(path, `${lines.join("\n")}\n`, "utf8");
+
+ const report = verifyLineageLedger(tmp);
+ expect(report.ok).toBe(false);
+ expect(report.notices.some((n) => n.code === DEGRADATION_CODE.lineageChainBroken)).toBe(true);
+ expect(report.notices.some((n) => n.detail.includes("2"))).toBe(true);
+ });
+
+ test("a tampered ledger does NOT prevent resolution", () => {
+ record("s-1", T0, { cwd: "/work" });
+ const path = sessionLineageLedgerPath(tmp);
+ const line = JSON.parse(readFileSync(path, "utf8").trim()) as RawLine;
+ writeFileSync(path, `${JSON.stringify({ ...line, cwd: "/tampered" })}\n`, "utf8");
+ expect(readLineageLedger(tmp).get("s-1")?.cwd).toBe("/tampered");
+ expect(verifyLineageLedger(tmp).ok).toBe(false);
+ });
+
+ test("a removed line is reported as a sequence gap", () => {
+ record("s-1", T0);
+ record("s-2", T0 + 1_000);
+ record("s-3", T0 + 2_000);
+ const path = sessionLineageLedgerPath(tmp);
+ const lines = readFileSync(path, "utf8")
+ .split("\n")
+ .filter((l) => l.trim().length > 0);
+ writeFileSync(path, `${lines[0]!}\n${lines[2]!}\n`, "utf8");
+ const report = verifyLineageLedger(tmp);
+ expect(report.ok).toBe(false);
+ expect(report.notices[0]!.code).toBe(DEGRADATION_CODE.lineageChainBroken);
+ });
+
+ test("a missing ledger verifies clean rather than throwing", () => {
+ const report = verifyLineageLedger(tmp);
+ expect(report.ok).toBe(true);
+ expect(report.lines).toBe(0);
+ });
+
+ test("a wholly corrupt file is reported, and the read path still returns empty", () => {
+ const path = sessionLineageLedgerPath(tmp);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "not-json\n{\n", "utf8");
+ expect(readLineageLedger(tmp).size).toBe(0);
+
+ // The behaviour the name promises: a destroyed ledger is REPORTED,
+ // not silently verified clean. `not.toThrow()` asserted nothing of
+ // the kind - it passed against a verifier that returned ok:true.
+ const report = verifyLineageLedger(tmp);
+ expect(report.ok).toBe(false);
+ expect(report.skipped).toBe(2);
+ expect(report.notices.some((n) => n.code === DEGRADATION_CODE.lineageChainBroken)).toBe(true);
+ });
+
+ test("an all-truncated-JSON ledger is reported, never clean", () => {
+ const path = sessionLineageLedgerPath(tmp);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, '{"sid":"s-1","at":"2026-06-10T08:0\n{"sid":"s-2"\n', "utf8");
+ const report = verifyLineageLedger(tmp);
+ expect(report.lines).toBe(0);
+ expect(report.skipped).toBe(2);
+ expect(report.ok).toBe(false);
+ });
+
+ test("a ledger that exists but holds nothing parseable is not 'no ledger'", () => {
+ const path = sessionLineageLedgerPath(tmp);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, "\n\n", "utf8");
+ const report = verifyLineageLedger(tmp);
+ expect(report.exists).toBe(true);
+ expect(report.lines).toBe(0);
+ // A present-but-empty ledger has no findings of its own; the point
+ // is that a consumer can tell it apart from an absent one.
+ expect(verifyLineageLedger(join(tmp, "elsewhere")).exists).toBe(false);
+ });
+
+ test("an unreadable ledger is reported rather than counted as clean", () => {
+ const path = sessionLineageLedgerPath(tmp);
+ mkdirSync(dirname(path), { recursive: true });
+ writeFileSync(path, `${JSON.stringify({ sid: "s", at: "x", event: "Stop" })}\n`, "utf8");
+ chmodSync(path, 0o000);
+ try {
+ const report = verifyLineageLedger(tmp);
+ // Running as root defeats the mode bits; skip rather than assert
+ // a permission the environment does not enforce.
+ if (report.readable) return;
+ expect(report.ok).toBe(false);
+ expect(report.notices.some((n) => n.detail.includes("could not be read"))).toBe(true);
+ } finally {
+ chmodSync(path, 0o644);
+ }
+ });
+
+ test("a line stripped of its chain fields is reported once chained lines exist", () => {
+ record("s-1", T0);
+ record("s-2", T0 + 1_000);
+ record("s-3", T0 + 2_000);
+ const path = sessionLineageLedgerPath(tmp);
+ const lines = readFileSync(path, "utf8")
+ .split("\n")
+ .filter((l) => l.trim().length > 0);
+ const { seq: _seq, prev: _prev, h: _h, ...stripped } = JSON.parse(lines[1]!) as RawLine;
+ lines[1] = JSON.stringify(stripped);
+ writeFileSync(path, `${lines.join("\n")}\n`, "utf8");
+
+ // Stripping the chain fields made the line `legacy`, which reset
+ // `previous` and left the FOLLOWING line's `prev` unchecked - so a
+ // tampered middle line passed with ok:true.
+ const report = verifyLineageLedger(tmp);
+ expect(report.legacy).toBe(1);
+ expect(report.ok).toBe(false);
+ expect(report.notices.some((n) => n.code === DEGRADATION_CODE.lineageChainBroken)).toBe(true);
+ });
+
+ test("a pre-chain ledger is counted as legacy, not as a break", () => {
+ const path = sessionLineageLedgerPath(tmp);
+ mkdirSync(dirname(path), { recursive: true });
+ appendFileSync(
+ path,
+ `${JSON.stringify({ sid: "old-1", at: new Date(T0).toISOString(), event: "Stop" })}\n`,
+ "utf8",
+ );
+ const report = verifyLineageLedger(tmp);
+ expect(report.legacy).toBe(1);
+ expect(report.ok).toBe(true);
+
+ // A new line appended after legacy content chains from scratch.
+ record("s-1", T0 + 1_000);
+ const after = verifyLineageLedger(tmp);
+ expect(after.ok).toBe(true);
+ expect(after.chained).toBe(1);
+ });
+});
+
+// ----- lossless compaction -------------------------------------------------
+
+describe("recordLineageObservation β€” compaction is lossless", () => {
+ function fill(count: number, sessionId = "chatty"): void {
+ for (let i = 0; i < count; i++) {
+ record(sessionId, T0 + i * 1_000, { event: `E${i}` });
+ }
+ }
+
+ test("preserves firstSeenMs β€” the summary fold dropped it entirely", () => {
+ fill(600);
+ const entry = readLineageLedger(tmp).get("chatty")!;
+ // The old fold rewrote one line per session stamped at lastSeenMs,
+ // so firstSeenMs and lastSeenMs collapsed onto the same instant.
+ expect(entry.firstSeenMs).toBeLessThan(entry.lastSeenMs);
+ });
+
+ test("preserves per-session event history", () => {
+ fill(600);
+ const events = rawLines(tmp).filter((line) => line.sid === "chatty");
+ expect(events.length).toBeGreaterThan(1);
+ expect(new Set(events.map((line) => line.event)).size).toBe(events.length);
+ });
+
+ test("preserves a field the writer emits that no re-serializer knows about", () => {
+ // Stands in for any field a future writer adds. The old compaction
+ // re-serialized from a hard-coded field list and would have dropped
+ // this silently; verbatim retention cannot.
+ fill(510);
+ const path = sessionLineageLedgerPath(tmp);
+ const lines = readFileSync(path, "utf8")
+ .split("\n")
+ .filter((l) => l.trim().length > 0);
+ const last = JSON.parse(lines.at(-1)!) as RawLine;
+ lines[lines.length - 1] = JSON.stringify({ ...last, unknown_future_field: "keep-me" });
+ writeFileSync(path, `${lines.join("\n")}\n`, "utf8");
+
+ // Cross the cap so a compaction rewrite runs while the marked line
+ // is still inside the retention window.
+ fill(3, "tail");
+ expect(rawLines(tmp).length).toBeLessThanOrEqual(512);
+ expect(readFileSync(path, "utf8").includes("keep-me")).toBe(true);
+ });
+
+ test("keeps the file bounded and the chain intact across compaction", () => {
+ fill(600);
+ const lines = rawLines(tmp);
+ expect(lines.length).toBeLessThanOrEqual(512);
+ expect(lines.length).toBeGreaterThan(1);
+ // Retained lines keep their original sequence numbers, so the chain
+ // is still contiguous even though the head was dropped.
+ expect(lines[0]!.seq).toBeGreaterThan(1);
+ expect(verifyLineageLedger(tmp).ok).toBe(true);
+ });
+
+ test("the oldest sessions still age out", () => {
+ for (let i = 0; i < 600; i++) record(`s-${i}`, T0 + i * 1_000);
+ const state = readLineageLedger(tmp);
+ expect(state.has("s-599")).toBe(true);
+ expect(state.has("s-0")).toBe(false);
+ });
+});
+
+// ----- mutual exclusion ----------------------------------------------------
+
+describe("recordLineageObservation β€” writer lock", () => {
+ test("a held lock drops the observation and records a NAMED gap", () => {
+ record("s-1", T0);
+ const handle = acquireLockSync(sessionLineageLedgerPath(tmp));
+ let result;
+ try {
+ result = record("s-2", T0 + 1_000);
+ } finally {
+ handle.release();
+ }
+ expect(result.status).toBe(LINEAGE_RECORD_STATUS.dropped);
+ expect(result.notice?.code).toBe(DEGRADATION_CODE.lineageObservationDropped);
+ // The observation is gone, but its absence is on the record.
+ expect(readLineageLedger(tmp).has("s-2")).toBe(false);
+ expect(readFileSync(sessionLineageGapsPath(tmp), "utf8")).toContain("s-2");
+ });
+
+ test("verification surfaces recorded gaps as dropped observations", () => {
+ record("s-1", T0);
+ const handle = acquireLockSync(sessionLineageLedgerPath(tmp));
+ try {
+ record("s-2", T0 + 1_000);
+ } finally {
+ handle.release();
+ }
+ const report = verifyLineageLedger(tmp);
+ expect(report.droppedObservations).toBe(1);
+ expect(report.notices.some((n) => n.code === DEGRADATION_CODE.lineageObservationDropped)).toBe(
+ true,
+ );
+ expect(report.ok).toBe(false);
+ });
+
+ test("the lock is released after a successful write", () => {
+ record("s-1", T0);
+ // If the previous write leaked its lock this would be dropped.
+ expect(record("s-2", T0 + 1_000).status).toBe(LINEAGE_RECORD_STATUS.appended);
+ });
+});
+
+// ----- the gap sidecar's own failure modes ---------------------------------
+
+describe("the gap sidecar is bounded, aged, and honest about both", () => {
+ const DAY_MS = 24 * 60 * 60 * 1000;
+
+ /** Drop `count` observations by holding the ledger's writer lock. */
+ function dropMany(count: number): void {
+ const handle = acquireLockSync(sessionLineageLedgerPath(tmp));
+ try {
+ for (let i = 0; i < count; i++) {
+ expect(record(`d-${i}`, T0 + i).status).toBe(LINEAGE_RECORD_STATUS.dropped);
+ }
+ } finally {
+ handle.release();
+ }
+ }
+
+ function gapFileLines(): string[] {
+ return readFileSync(sessionLineageGapsPath(tmp), "utf8")
+ .split("\n")
+ .filter((line) => line.trim().length > 0);
+ }
+
+ test("a saturated sidecar reports the TOTAL, not the retained count", () => {
+ dropMany(400);
+ const report = readLineageGapReport(tmp);
+ // 400 drops presented as 256 was the defect: the cap is real, and
+ // what it removed is carried as an explicit count beside it.
+ expect(report.records.length).toBe(256);
+ expect(report.truncated).toBe(true);
+ expect(report.discarded).toBe(400 - 256);
+ expect(report.total).toBe(400);
+ });
+
+ test("verification names the unlisted remainder instead of dropping it", () => {
+ dropMany(400);
+ const report = verifyLineageLedger(tmp);
+ expect(report.droppedObservations).toBe(400);
+ expect(report.gapsTruncated).toBe(true);
+ // Bounded itemization, with the rest counted rather than silently cut.
+ expect(report.notices.length).toBeLessThan(40);
+ expect(report.notices.some((n) => n.detail.includes("not itemized"))).toBe(true);
+ });
+
+ /** An oversized sidecar, as a crash inside the trim window leaves it. */
+ function seedOversizedSidecar(count: number): void {
+ const path = sessionLineageGapsPath(tmp);
+ mkdirSync(dirname(path), { recursive: true });
+ const now = new Date().toISOString();
+ writeFileSync(
+ path,
+ Array.from({ length: count }, (_, i) =>
+ JSON.stringify({
+ sid: `old-${i}`,
+ at: now,
+ rat: now,
+ event: "Stop",
+ reason: "write-failed",
+ }),
+ ).join("\n") + "\n",
+ "utf8",
+ );
+ }
+
+ test("a stale trim lock does not disable the bound", () => {
+ seedOversizedSidecar(300);
+ const gapsLock = `${sessionLineageGapsPath(tmp)}.lock`;
+ writeFileSync(gapsLock, "9999999\n", "utf8");
+ const old = new Date(Date.now() - 10 * 60_000);
+ utimesSync(gapsLock, old, old);
+ try {
+ // Before the reclaim path the trim skipped outright on ELOCKED, so
+ // one crash inside that window left the sidecar growing forever.
+ dropMany(1);
+ expect(readLineageGapReport(tmp).records.length).toBe(256);
+ expect(gapFileLines().length).toBe(257); // 256 records + the marker
+ } finally {
+ rmSync(gapsLock, { force: true });
+ }
+ });
+
+ test("a LIVE trim lock is respected β€” no breaker on a lock in use", () => {
+ seedOversizedSidecar(300);
+ const handle = acquireLockSync(sessionLineageGapsPath(tmp));
+ try {
+ dropMany(1);
+ // Untrimmed: a lock that a live process holds is never taken away.
+ expect(gapFileLines().length).toBe(301);
+ } finally {
+ handle.release();
+ }
+ });
+
+ test("gaps age out, so one contention burst does not pin ok:false forever", () => {
+ dropMany(3);
+ expect(verifyLineageLedger(tmp).ok).toBe(false);
+ const later = Date.now() + 8 * DAY_MS;
+ expect(readLineageGapReport(tmp, { nowMs: later }).total).toBe(0);
+ expect(verifyLineageLedger(tmp, { nowMs: later }).ok).toBe(true);
+ });
+
+ test("aging keys off when the gap was RECORDED, not the observation's own clock", () => {
+ // Every observation here is stamped in the past (T0 is 2026-06-10);
+ // aging on `at` would expire a gap written this instant.
+ dropMany(2);
+ expect(readLineageGapReport(tmp).total).toBe(2);
+ });
+
+ test("the truncation marker expires with the records it counted", () => {
+ dropMany(400);
+ const later = Date.now() + 8 * DAY_MS;
+ const report = readLineageGapReport(tmp, { nowMs: later });
+ expect(report.total).toBe(0);
+ expect(report.truncated).toBe(false);
+ });
+
+ test("the drop notice NAMES the lock file", () => {
+ const lockPath = `${sessionLineageLedgerPath(tmp)}.lock`;
+ const handle = acquireLockSync(sessionLineageLedgerPath(tmp));
+ let result;
+ try {
+ result = record("s-blocked", T0);
+ } finally {
+ handle.release();
+ }
+ expect(result.notice?.path).toBe(lockPath);
+ expect(result.notice?.detail).toContain(lockPath);
+ });
+});
+
+describe("recordLineageObservation β€” genuinely concurrent writers", () => {
+ test("every attempt either lands or is recorded as a gap, and the chain holds", async () => {
+ // Real OS processes, not simulated contention: four `bun` children
+ // hammering one ledger seeded to just under the compaction cap, so
+ // the read-modify-write branch runs while they overlap.
+ for (let i = 0; i < 500; i++) record(`seed-${i}`, T0 + i * 1_000);
+
+ const ledgerModule = join(import.meta.dir, "../../../src/core/brain/lineage/ledger.ts");
+ const script = join(tmp, "writer.ts");
+ writeFileSync(
+ script,
+ [
+ `import { recordLineageObservation } from ${JSON.stringify(ledgerModule)};`,
+ "const [vault, tag, count] = process.argv.slice(2);",
+ "let appended = 0; let dropped = 0;",
+ "for (let i = 0; i < Number(count); i++) {",
+ " const result = recordLineageObservation(vault, {",
+ " sessionId: `${tag}-${i}`,",
+ " at: new Date().toISOString(),",
+ " event: 'Stop',",
+ " });",
+ " if (result.status === 'appended') appended++; else dropped++;",
+ "}",
+ "process.stdout.write(JSON.stringify({ appended, dropped }));",
+ ].join("\n"),
+ "utf8",
+ );
+
+ const writers = 4;
+ const perWriter = 25;
+ const procs = Array.from({ length: writers }, (_, index) =>
+ Bun.spawn(["bun", script, tmp, `w${index}`, String(perWriter)], {
+ stdout: "pipe",
+ stderr: "pipe",
+ }),
+ );
+ const results = await Promise.all(
+ procs.map(async (proc) => {
+ const text = await new Response(proc.stdout).text();
+ await proc.exited;
+ return JSON.parse(text) as { appended: number; dropped: number };
+ }),
+ );
+
+ const appended = results.reduce((sum, r) => sum + r.appended, 0);
+ const dropped = results.reduce((sum, r) => sum + r.dropped, 0);
+ // Conservation: nothing vanishes without a name.
+ expect(appended + dropped).toBe(writers * perWriter);
+
+ const report = verifyLineageLedger(tmp);
+ expect(report.droppedObservations).toBe(dropped);
+ // The only findings, if any, are the named gaps - never a broken chain.
+ expect(report.notices.every((n) => n.code === DEGRADATION_CODE.lineageObservationDropped)).toBe(
+ true,
+ );
+
+ // Every landed observation is readable, and none clobbered another.
+ const state = readLineageLedger(tmp);
+ const landed = [...state.keys()].filter((sid) => sid.startsWith("w")).length;
+ expect(landed).toBe(appended);
+ }, 30_000);
+});
diff --git a/tests/core/brain/owner-scope-delivery.test.ts b/tests/core/brain/owner-scope-delivery.test.ts
new file mode 100644
index 00000000..47f8e818
--- /dev/null
+++ b/tests/core/brain/owner-scope-delivery.test.ts
@@ -0,0 +1,286 @@
+/**
+ * Owner-scope isolation on the preference-backed delivery surfaces
+ * (context-integrity-gates, Unit A / Task 6).
+ *
+ * The load-bearing assertion is the FIRST one: with
+ * `integrity.owner_scope_delivery` absent or `off`, every surface is
+ * byte-identical whether or not a scope is requested. Every module on
+ * this path documents a "a null scope is byte-identical to today"
+ * contract, so a gate that narrowed by default would be a breaking
+ * change disguised as a fix.
+ */
+
+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 { GATE_MODE } from "../../../src/core/integrity/stamp.ts";
+import { renderActive } from "../../../src/core/brain/active.ts";
+import { anticipatoryCachePath } from "../../../src/core/brain/anticipatory-cache.ts";
+import { packContext } from "../../../src/core/brain/context-pack.ts";
+import { renderDigest } from "../../../src/core/brain/digest.ts";
+import { buildMorningBrief } from "../../../src/core/brain/morning-brief.ts";
+import { brainConfigPath, brainDirs } from "../../../src/core/brain/paths.ts";
+import { buildPreCompressPack } from "../../../src/core/brain/pre-compress-pack.ts";
+import { moveToRetired, writePreference } from "../../../src/core/brain/preference.ts";
+import { preferencePath } from "../../../src/core/brain/paths.ts";
+import {
+ collectPreferencePages,
+ collectPreferences,
+ resolveOwnerScopeDelivery,
+ type OwnerScopeDelivery,
+} from "../../../src/core/brain/preferences-collect.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";
+
+const OWNER_A = "agent-a";
+const OWNER_B = "agent-b";
+const NOW = new Date("2026-05-10T00:00:00Z");
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-owner-delivery-"));
+ for (const sub of ["preferences", "retired", "inbox", "log"]) {
+ mkdirSync(join(vault, "Brain", sub), { recursive: true });
+ }
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function setGate(mode: string | null): void {
+ const body = mode === null ? "" : `integrity:\n owner_scope_delivery: ${mode}\n`;
+ writeFileSync(brainConfigPath(vault), `schema_version: 1\n${body}`);
+}
+
+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 } : {}),
+ });
+}
+
+/** Every preference-backed delivery surface, rendered as comparable text. */
+function renderAll(agentScope?: string): Record<string, string> {
+ // The DELIVERY surface for active.md is the render, never the write:
+ // `regenerateActive` writes one shared file for the whole vault.
+ const active = renderActive(vault, { now: NOW, ...scopeArg(agentScope) });
+ return {
+ pack: JSON.stringify(
+ packContext(vault, { maxTokens: 4000, ...scopeArg(agentScope) }).items.map((i) => i.id),
+ ),
+ preCompress: buildPreCompressPack(vault, { topK: 10, ...scopeArg(agentScope) }).text,
+ morningBrief: buildMorningBrief(vault, { now: NOW, topK: 10, ...scopeArg(agentScope) }).text,
+ digest: renderDigest(vault, {
+ now: NOW,
+ until: NOW,
+ format: "json",
+ ...scopeArg(agentScope),
+ }).content,
+ active: JSON.stringify(active.counts),
+ };
+}
+
+/** 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 };
+}
+
+function scopeArg(agentScope?: string): { agentScope?: string } {
+ return agentScope === undefined ? {} : { agentScope };
+}
+
+test("gate absent: a requested scope changes nothing on any surface", () => {
+ setGate(null);
+ makePref("shared");
+ makePref("owned-by-a", OWNER_A);
+
+ const unscoped = renderAll();
+ expect(renderAll(OWNER_B)).toEqual(unscoped);
+ expect(renderAll(OWNER_A)).toEqual(unscoped);
+ // Sanity: the owned preference really is on the surfaces being compared.
+ expect(unscoped["pack"]).toContain("pref-owned-by-a");
+});
+
+test("gate off: explicit off behaves exactly like an absent block", () => {
+ setGate(GATE_MODE.off);
+ makePref("shared");
+ makePref("owned-by-a", OWNER_A);
+
+ expect(renderAll(OWNER_B)).toEqual(renderAll());
+});
+
+test("gate fail: another owner's preference is absent from every surface", () => {
+ setGate(GATE_MODE.fail);
+ makePref("shared");
+ makePref("owned-by-a", OWNER_A);
+
+ const asB = renderAll(OWNER_B);
+ for (const [surface, text] of Object.entries(asB)) {
+ if (surface === "active") continue; // counts only; asserted below
+ expect(text).not.toContain("owned-by-a");
+ expect(text).toContain("shared");
+ }
+ expect(JSON.parse(asB["active"]!).confirmed).toBe(1);
+
+ const asA = renderAll(OWNER_A);
+ expect(asA["pack"]).toContain("pref-owned-by-a");
+ expect(asA["pack"]).toContain("pref-shared");
+ expect(JSON.parse(asA["active"]!).confirmed).toBe(2);
+});
+
+test("gate fail with no scope requested still delivers everything", () => {
+ setGate(GATE_MODE.fail);
+ makePref("shared");
+ makePref("owned-by-a", OWNER_A);
+
+ expect(renderAll()["pack"]).toContain("pref-owned-by-a");
+});
+
+test("gate warn reports the isolation without withholding anything", () => {
+ setGate(GATE_MODE.warn);
+ makePref("shared");
+ makePref("owned-by-a", OWNER_A);
+
+ const warned = packContext(vault, { maxTokens: 4000, agentScope: OWNER_B });
+ expect(warned.items.map((i) => i.id)).toContain("pref-owned-by-a");
+ expect((warned.warnings ?? []).join("\n")).toContain("owner");
+
+ const off = packContext(vault, { maxTokens: 4000 });
+ expect(off.warnings).toBeUndefined();
+});
+
+test("resolveOwnerScopeDelivery narrows only under fail", () => {
+ setGate(GATE_MODE.fail);
+ expect(resolveOwnerScopeDelivery(vault, OWNER_A).enforcedScope).toBe(OWNER_A);
+ expect(resolveOwnerScopeDelivery(vault, undefined).enforcedScope).toBeNull();
+
+ setGate(GATE_MODE.warn);
+ expect(resolveOwnerScopeDelivery(vault, OWNER_A).enforcedScope).toBeNull();
+ expect(resolveOwnerScopeDelivery(vault, OWNER_A).requestedScope).toBe(OWNER_A);
+
+ setGate(GATE_MODE.off);
+ expect(resolveOwnerScopeDelivery(vault, OWNER_A).enforcedScope).toBeNull();
+ expect(resolveOwnerScopeDelivery(vault, OWNER_A).requestedScope).toBeNull();
+});
+
+test("the collector drops an unreadable page under an active scope", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("shared");
+ // A directory named like a note: readable as an entry, unreadable as a file.
+ mkdirSync(join(dir, "pref-unreadable.md"));
+
+ const open = collectPreferencePages(dir);
+ expect(open.entries.map((e) => e.name)).toContain("pref-unreadable.md");
+
+ const closed = collectPreferencePages(dir, { ownerScope: enforcing(OWNER_B) });
+ expect(closed.entries.map((e) => e.name)).not.toContain("pref-unreadable.md");
+ expect(closed.entries.map((e) => e.name)).toContain("pref-shared.md");
+});
+
+test("the collector counts what an active scope removed", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("shared");
+ makePref("owned-by-a", OWNER_A);
+
+ expect(collectPreferences(dir, { ownerScope: enforcing(OWNER_B) }).hiddenByOwnerScope).toBe(1);
+ expect(collectPreferences(dir, { ownerScope: enforcing(OWNER_A) }).hiddenByOwnerScope).toBe(0);
+ expect(collectPreferences(dir).hiddenByOwnerScope).toBe(0);
+});
+
+test("an ownerless preference is visible under every scope", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("shared");
+
+ for (const scope of [null, OWNER_A, OWNER_B]) {
+ const collected = collectPreferences(dir, {
+ ownerScope: scope === null ? null : enforcing(scope),
+ });
+ expect(collected.entries.map((e) => e.pref.id)).toEqual(["pref-shared"]);
+ }
+});
+
+test("the anticipatory cache path is distinct per owner scope under `fail`", () => {
+ setGate(GATE_MODE.fail);
+ const none = anticipatoryCachePath(vault, "root-1");
+ const a = anticipatoryCachePath(vault, "root-1", OWNER_A);
+ const b = anticipatoryCachePath(vault, "root-1", OWNER_B);
+
+ expect(new Set([none, a, b]).size).toBe(3);
+ // An absent scope keeps the legacy path so warm caches are not orphaned.
+ expect(anticipatoryCachePath(vault, "root-1", null)).toBe(none);
+});
+
+/**
+ * The key follows the ENFORCED scope, not the requested one. Under `off`
+ * and `warn` the pack is not narrowed, so a per-scope filename would only
+ * split one identical payload across N files - and, because the MCP tool
+ * always passes a scope while the hook writers never do, would turn every
+ * MCP read into a permanent miss (context-integrity-gates, A4).
+ */
+for (const mode of [null, GATE_MODE.off, GATE_MODE.warn]) {
+ test(`the anticipatory cache path ignores the requested scope under ${mode ?? "an absent gate"}`, () => {
+ setGate(mode);
+ const none = anticipatoryCachePath(vault, "root-1");
+ expect(anticipatoryCachePath(vault, "root-1", OWNER_A)).toBe(none);
+ expect(anticipatoryCachePath(vault, "root-1", OWNER_B)).toBe(none);
+ });
+}
+
+// ----- A7: retirement KEEPS ownership -------------------------------------
+
+/**
+ * Retiring a memory must not PUBLISH it. Before this fix the wave answered
+ * the question three ways: the agent-source provider kept the owner, while
+ * `active.md`'s recently-retired list, the digest's retired section, and
+ * `brain_query` all treated a retired record as shared - because
+ * `BrainRetired` carried no `owner` field, so the visibility predicate was
+ * trivially true for it.
+ */
+test("a retired memory keeps its owner on every delivery surface", () => {
+ setGate(GATE_MODE.fail);
+ makePref("shared");
+ makePref("owned-by-a", OWNER_A);
+ moveToRetired(vault, preferencePath(vault, "owned-by-a"), "stale-no-evidence", {
+ now: NOW,
+ retired_by: "[[Brain/log/2026-05-10]]",
+ });
+
+ const asB = renderActive(vault, { now: NOW, agentScope: OWNER_B });
+ expect(asB.document).not.toContain("owned-by-a");
+ expect(asB.counts.retired_recent).toBe(0);
+ expect(
+ renderDigest(vault, { now: NOW, until: NOW, format: "json", agentScope: OWNER_B }).content,
+ ).not.toContain("owned-by-a");
+
+ // Its own owner still sees it - the memory is withheld, not destroyed.
+ const asA = renderActive(vault, { now: NOW, agentScope: OWNER_A });
+ expect(asA.document).toContain("ret-owned-by-a");
+ expect(asA.counts.retired_recent).toBe(1);
+});
+
+test("with the gate off a retired memory reaches every caller as before", () => {
+ setGate(GATE_MODE.off);
+ makePref("owned-by-a", OWNER_A);
+ moveToRetired(vault, preferencePath(vault, "owned-by-a"), "stale-no-evidence", {
+ now: NOW,
+ retired_by: "[[Brain/log/2026-05-10]]",
+ });
+
+ const asB = renderActive(vault, { now: NOW, agentScope: OWNER_B });
+ expect(asB.document).toContain("ret-owned-by-a");
+ expect(asB.counts.retired_recent).toBe(1);
+});
diff --git a/tests/core/brain/owner-scoped-facts.test.ts b/tests/core/brain/owner-scoped-facts.test.ts
index 9e77094a..aa56ca86 100644
--- a/tests/core/brain/owner-scoped-facts.test.ts
+++ b/tests/core/brain/owner-scoped-facts.test.ts
@@ -19,6 +19,7 @@ import {
isPreferenceVisible,
preferenceOwner,
} from "../../../src/core/brain/owner-scoped-facts.ts";
+import { OWNER_UNRESOLVED } from "../../../src/core/graph/agent-scope.ts";
import { QUERY_TOOLS } from "../../../src/mcp/brain/query-tools.ts";
import type { ServerContext } from "../../../src/mcp/tool-contract.ts";
@@ -63,12 +64,24 @@ function enableOwnerScoping(): void {
const queryHandler = QUERY_TOOLS.find((t) => t.name === "brain_query")!.handler;
describe("owner-visibility filter (pure)", () => {
- test("preferenceOwner normalizes and treats blank as null", () => {
+ test("preferenceOwner normalizes, and only an ABSENT owner is null", () => {
expect(preferenceOwner({ owner: " Agent-A " })).toBe("agent-a");
- expect(preferenceOwner({ owner: "" })).toBeNull();
expect(preferenceOwner({})).toBeNull();
});
+ /**
+ * A blank or list-shaped `owner:` is a claim this parser cannot
+ * resolve; reading it as ownerless would share the memory with every
+ * agent (context-integrity-gates, A2). It resolves to the poison token
+ * instead, which no requested scope can equal.
+ */
+ test("an unresolvable owner is withheld under any scope, shared under none", () => {
+ expect(preferenceOwner({ owner: "" })).toBe(OWNER_UNRESOLVED);
+ expect(isPreferenceVisible({ owner: "" }, "agent-a")).toBe(false);
+ expect(isPreferenceVisible({ owner: OWNER_UNRESOLVED }, "agent-b")).toBe(false);
+ expect(isPreferenceVisible({ owner: OWNER_UNRESOLVED }, null)).toBe(true);
+ });
+
test("no requested scope: everything visible (byte-identical default)", () => {
expect(isPreferenceVisible({ owner: "agent-a" }, null)).toBe(true);
expect(isPreferenceVisible({}, null)).toBe(true);
diff --git a/tests/core/brain/pack-stamp.test.ts b/tests/core/brain/pack-stamp.test.ts
new file mode 100644
index 00000000..1dca6bf6
--- /dev/null
+++ b/tests/core/brain/pack-stamp.test.ts
@@ -0,0 +1,285 @@
+/**
+ * Pack provenance stamp and validity window (context-integrity-gates,
+ * Unit B / Task 9).
+ *
+ * A context pack carries no record of the vault state it was built from,
+ * so a stale pack is indistinguishable from a fresh one. These tests pin
+ * the stamp's two tokens, the "no search index" modelling, and the
+ * byte-identical contract for a pack that never asked for a stamp.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { packContext } from "../../../src/core/brain/context-pack.ts";
+import {
+ CORPUS_GENERATION_UNREADABLE,
+ PACK_STAMP_FIELD,
+ buildPackStamp,
+ packStampRefusal,
+ packStampTokens,
+} from "../../../src/core/brain/pack-stamp.ts";
+import { PACK_VALIDITY_SECONDS_DEFAULT } from "../../../src/core/brain/policy.ts";
+import { compareStamps, formatStampMismatch } from "../../../src/core/integrity/stamp.ts";
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { makeConfig } from "../../helpers/search-fixtures.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-pack-stamp-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+const T0 = new Date("2026-06-10T12:00:00Z");
+
+/** A config path that does not exist, so no operator config leaks in. */
+const ABSENT_CONFIG = join(tmpdir(), "o2b-pack-stamp-no-such-config.yaml");
+
+function writePref(slug: string, body: string, mtimeSeconds: number): string {
+ const path = join(vault, "Brain", "preferences", `pref-${slug}.md`);
+ writeFileSync(
+ path,
+ [
+ "---",
+ `id: pref-${slug}`,
+ `topic: ${slug}`,
+ "principle: p",
+ "tier: core",
+ "---",
+ "",
+ body,
+ ].join("\n"),
+ );
+ utimesSync(path, mtimeSeconds, mtimeSeconds);
+ return path;
+}
+
+describe("packStampTokens", () => {
+ test("records both tokens, and an absent search index is unrecorded rather than matched", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const tokens = packStampTokens(vault);
+ expect(Object.keys(tokens).toSorted()).toEqual(
+ [PACK_STAMP_FIELD.brainTree, PACK_STAMP_FIELD.corpusGeneration].toSorted(),
+ );
+ // No index has ever been built: the corpus token is explicitly
+ // `null` ("this side recorded nothing"), never a stand-in value that
+ // would compare equal to a real generation.
+ expect(tokens[PACK_STAMP_FIELD.corpusGeneration]).toBe(null);
+ expect(typeof tokens[PACK_STAMP_FIELD.brainTree]).toBe("string");
+ expect((tokens[PACK_STAMP_FIELD.brainTree] as string).length).toBeGreaterThan(0);
+ });
+
+ test("the Brain-tree token carries invalidation on a vault with no search index", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const before = packStampTokens(vault);
+ writePref("a", "alpha body rewritten with different length", 1_700_000_500);
+ const after = packStampTokens(vault);
+ const drift = compareStamps(before, after);
+ expect(drift.map((m) => m.field)).toEqual([PACK_STAMP_FIELD.brainTree]);
+ });
+
+ test("adding a memory changes the Brain-tree token", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const before = packStampTokens(vault);
+ writePref("b", "beta body", 1_700_000_000);
+ const after = packStampTokens(vault);
+ expect(after[PACK_STAMP_FIELD.brainTree]).not.toBe(before[PACK_STAMP_FIELD.brainTree]);
+ });
+
+ test("an unchanged vault produces a byte-identical token map", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ expect(JSON.stringify(packStampTokens(vault))).toBe(JSON.stringify(packStampTokens(vault)));
+ });
+
+ test("a search index appearing is a named corpus_generation drift, not a silent match", async () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const before = packStampTokens(vault);
+ expect(before[PACK_STAMP_FIELD.corpusGeneration]).toBe(null);
+
+ await indexVault(
+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),
+ {},
+ );
+
+ const after = packStampTokens(vault);
+ expect(typeof after[PACK_STAMP_FIELD.corpusGeneration]).toBe("string");
+ const drift = compareStamps(before, after);
+ const fields = drift.map((m) => m.field);
+ expect(fields).toContain(PACK_STAMP_FIELD.corpusGeneration);
+ const rendered = drift.map(formatStampMismatch).join("; ");
+ expect(rendered).toContain(PACK_STAMP_FIELD.corpusGeneration);
+ expect(rendered).toContain("<unrecorded>");
+ });
+});
+
+describe("buildPackStamp", () => {
+ test("derives the validity window from integrity.pack_validity_seconds", () => {
+ const stamp = buildPackStamp(vault, T0);
+ expect(stamp.generatedAt).toBe(T0.toISOString());
+ expect(stamp.expiresAt).toBe(
+ new Date(T0.getTime() + PACK_VALIDITY_SECONDS_DEFAULT * 1_000).toISOString(),
+ );
+ });
+
+ test("honours a configured pack_validity_seconds", () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ ["schema_version: 1", "integrity:", " pack_validity_seconds: 60", ""].join("\n"),
+ );
+ const stamp = buildPackStamp(vault, T0);
+ expect(stamp.expiresAt).toBe(new Date(T0.getTime() + 60_000).toISOString());
+ });
+});
+
+describe("packStampRefusal", () => {
+ test("returns null for an unexpired stamp whose tokens still match", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const stamp = buildPackStamp(vault, T0);
+ const reason = packStampRefusal(stamp, packStampTokens(vault), new Date(T0.getTime() + 1_000));
+ expect(reason).toBe(null);
+ });
+
+ test("names the drifted field when the Brain tree changed", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const stamp = buildPackStamp(vault, T0);
+ writePref("a", "alpha body rewritten with different length", 1_700_000_500);
+ const reason = packStampRefusal(stamp, packStampTokens(vault), new Date(T0.getTime() + 1_000));
+ expect(reason).not.toBe(null);
+ expect(reason!).toContain(PACK_STAMP_FIELD.brainTree);
+ });
+
+ test("refuses an expired window even when every token still matches", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const stamp = buildPackStamp(vault, T0);
+ const expired = new Date(T0.getTime() + (PACK_VALIDITY_SECONDS_DEFAULT + 1) * 1_000);
+ const reason = packStampRefusal(stamp, packStampTokens(vault), expired);
+ expect(reason).not.toBe(null);
+ expect(reason!).toContain(stamp.expiresAt);
+ });
+
+ test("a stamp whose recorded tokens are unreadable is refused, never accepted", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const stamp = buildPackStamp(vault, T0);
+ const reason = packStampRefusal(
+ { ...stamp, tokens: {} },
+ packStampTokens(vault),
+ new Date(T0.getTime() + 1_000),
+ );
+ expect(reason).not.toBe(null);
+ });
+});
+
+describe("packContext stamp option", () => {
+ test("a pack that did not ask for a stamp carries no stamp key", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const report = packContext(vault, { maxTokens: 1_000 });
+ expect("stamp" in report).toBe(false);
+ });
+
+ test("the stamp rides the pack when requested", () => {
+ writePref("a", "alpha body", 1_700_000_000);
+ const report = packContext(vault, { maxTokens: 1_000, stamp: { now: T0 } });
+ expect(report.stamp).toBeDefined();
+ expect(report.stamp!.generatedAt).toBe(T0.toISOString());
+ expect(report.stamp!.tokens[PACK_STAMP_FIELD.brainTree]).toBe(
+ packStampTokens(vault)[PACK_STAMP_FIELD.brainTree],
+ );
+ });
+
+ test("a stamped empty-budget pack still carries its stamp", () => {
+ const report = packContext(vault, { maxTokens: 0, stamp: { now: T0 } });
+ expect(report.stamp).toBeDefined();
+ });
+});
+
+/**
+ * `packIndexPath` consulted only `OPEN_SECOND_BRAIN_SEARCH_DB`, while
+ * `resolveSearchConfig` also honours the config-file `search_db_path`.
+ * On a vault configured that way the stamp read a database that was not
+ * there, `corpus_generation` was `null` on both sides, "two unrecorded
+ * sides are not a finding" applied, and half the pack stamp was
+ * permanently inert - while its own docblock claimed it observed the
+ * database `search()` would read.
+ */
+describe("packStampTokens observes the index search() would read", () => {
+ test("a config-file search_db_path is honoured, not just the env var", async () => {
+ const home = mkdtempSync(join(tmpdir(), "o2b-pack-stamp-cfg-"));
+ const dbPath = join(home, "elsewhere.sqlite");
+ const configPath = join(home, "config.yaml");
+ writeFileSync(configPath, `vault: "${vault}"\nsearch_db_path: "${dbPath}"\n`, "utf8");
+ writeFileSync(join(vault, "note.md"), "# Note\n\nbody\n", "utf8");
+ try {
+ await indexVault(makeConfig({ vault, dbPath }), {});
+ const generation = packStampTokens(vault, { configPath })[PACK_STAMP_FIELD.corpusGeneration];
+ expect(generation).not.toBeNull();
+ // The default location holds no database, so the env-only
+ // resolution this replaces still reads as unrecorded.
+ expect(packStampTokens(vault, { configPath: join(home, "absent.yaml") })).toHaveProperty(
+ PACK_STAMP_FIELD.corpusGeneration,
+ null,
+ );
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test("a corrupt index is recorded as unreadable, not as unrecorded", async () => {
+ const home = mkdtempSync(join(tmpdir(), "o2b-pack-stamp-corrupt-"));
+ const dbPath = join(home, "corrupt.sqlite");
+ const configPath = join(home, "config.yaml");
+ writeFileSync(configPath, `vault: "${vault}"\nsearch_db_path: "${dbPath}"\n`, "utf8");
+ writeFileSync(dbPath, "this is not a sqlite database", "utf8");
+ try {
+ const generation = packStampTokens(vault, { configPath })[PACK_STAMP_FIELD.corpusGeneration];
+ // Not null: an index that exists and cannot be read is a state, and
+ // collapsing it onto "no index" makes both sides agree by accident.
+ expect(generation).not.toBeNull();
+ expect(generation).toBe(CORPUS_GENERATION_UNREADABLE);
+ } finally {
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+});
+
+/**
+ * `brain_tree` digested only the preference and retired directories,
+ * while `packContext` also reads `Brain/_brain.yaml` - whose
+ * `untrusted_source_delimiting` flag changes the emitted bodies. A pack
+ * built before the flag flipped therefore compared EQUAL to the vault
+ * state after it, which is exactly the staleness the stamp exists to
+ * name. The digest was extended rather than the docblock narrowed: the
+ * config is one stat, and it changes what the pack returns.
+ */
+describe("brain_tree covers every input packContext reads", () => {
+ test("flipping a config flag moves the digest", () => {
+ const configFile = join(vault, "Brain", "_brain.yaml");
+ writeFileSync(configFile, "schema_version: 1\n", "utf8");
+ const before = packStampTokens(vault, { configPath: ABSENT_CONFIG })[
+ PACK_STAMP_FIELD.brainTree
+ ];
+ writeFileSync(
+ configFile,
+ "schema_version: 1\nguardrails:\n untrusted_source_delimiting: true\n",
+ "utf8",
+ );
+ const after = packStampTokens(vault, { configPath: ABSENT_CONFIG })[PACK_STAMP_FIELD.brainTree];
+ expect(after).not.toBe(before);
+ });
+
+ test("creating the config where there was none moves the digest", () => {
+ const before = packStampTokens(vault, { configPath: ABSENT_CONFIG })[
+ PACK_STAMP_FIELD.brainTree
+ ];
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n", "utf8");
+ const after = packStampTokens(vault, { configPath: ABSENT_CONFIG })[PACK_STAMP_FIELD.brainTree];
+ expect(after).not.toBe(before);
+ });
+});
diff --git a/tests/core/brain/policy-integrity.test.ts b/tests/core/brain/policy-integrity.test.ts
new file mode 100644
index 00000000..fd326639
--- /dev/null
+++ b/tests/core/brain/policy-integrity.test.ts
@@ -0,0 +1,261 @@
+/**
+ * `integrity` block (context-integrity-gates) - the three-mode delivery
+ * and embedding-ABI gates plus the context-pack validity window.
+ *
+ * Same shape as `policy-guardrails.test.ts`: defaults, absent block,
+ * partial block, every out-of-range rejection, non-object block, unknown
+ * sub-key warning. Out-of-range values are hard errors - this block must
+ * never clamp or silently default, because a gate that quietly reverts
+ * to `off` is precisely the silent degradation the wave removes.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { parseBrainYaml } from "../../../src/core/brain/yaml-parse.ts";
+import {
+ BRAIN_INTEGRITY_DEFAULTS,
+ BRAIN_INTEGRITY_STRICT_FALLBACK,
+ BrainConfigError,
+ brainConfigReadFailure,
+ loadIntegrityConfigSafe,
+ PACK_VALIDITY_SECONDS_DEFAULT,
+ resolveIntegrity,
+ validateBrainConfigDetailed,
+} from "../../../src/core/brain/policy.ts";
+import {
+ BRAIN_INTEGRITY_DEFAULTS as BARREL_DEFAULTS,
+ resolveIntegrity as barrelResolveIntegrity,
+} from "../../../src/core/brain/index.ts";
+import { GATE_MODE } from "../../../src/core/integrity/stamp.ts";
+
+function validate(yaml: string) {
+ return validateBrainConfigDetailed(parseBrainYaml(yaml), "<test>");
+}
+
+const HEAD = `schema_version: 1\n`;
+const GATE_KEYS = ["owner_scope_delivery", "embedding_abi"] as const;
+
+describe("BRAIN_INTEGRITY_DEFAULTS", () => {
+ test("owner_scope_delivery defaults to off so no existing vault narrows", () => {
+ expect(BRAIN_INTEGRITY_DEFAULTS.owner_scope_delivery).toBe(GATE_MODE.off);
+ });
+
+ test("embedding_abi defaults to warn (vec_version is not stable across peers)", () => {
+ expect(BRAIN_INTEGRITY_DEFAULTS.embedding_abi).toBe(GATE_MODE.warn);
+ });
+
+ test("pack_validity_seconds defaults to the documented window", () => {
+ expect(BRAIN_INTEGRITY_DEFAULTS.pack_validity_seconds).toBe(PACK_VALIDITY_SECONDS_DEFAULT);
+ expect(Number.isInteger(PACK_VALIDITY_SECONDS_DEFAULT)).toBe(true);
+ expect(PACK_VALIDITY_SECONDS_DEFAULT).toBeGreaterThan(0);
+ });
+
+ test("is frozen", () => {
+ expect(Object.isFrozen(BRAIN_INTEGRITY_DEFAULTS)).toBe(true);
+ });
+
+ test("is reachable through the Brain barrel", () => {
+ expect(BARREL_DEFAULTS).toBe(BRAIN_INTEGRITY_DEFAULTS);
+ expect(barrelResolveIntegrity(validate(HEAD).config)).toEqual(BRAIN_INTEGRITY_DEFAULTS);
+ });
+});
+
+describe("integrity config block", () => {
+ test("absent block β†’ cfg.integrity is undefined; resolveIntegrity returns defaults", () => {
+ const { config, warnings } = validate(HEAD);
+ expect(config.integrity).toBeUndefined();
+ expect(resolveIntegrity(config)).toEqual(BRAIN_INTEGRITY_DEFAULTS);
+ expect(warnings.length).toBe(0);
+ });
+
+ test("`integrity` is a known top-level key (no forward-compat warning)", () => {
+ const { warnings } = validateBrainConfigDetailed(
+ { schema_version: 1, integrity: {} },
+ "<test>",
+ );
+ expect(warnings.length).toBe(0);
+ });
+
+ test("present with all three fields β†’ loaded fully", () => {
+ const { config } = validate(
+ HEAD +
+ `integrity:\n` +
+ ` owner_scope_delivery: fail\n` +
+ ` embedding_abi: off\n` +
+ ` pack_validity_seconds: 60\n`,
+ );
+ expect(config.integrity).toEqual({
+ owner_scope_delivery: "fail",
+ embedding_abi: "off",
+ pack_validity_seconds: 60,
+ });
+ expect(resolveIntegrity(config)).toEqual({
+ owner_scope_delivery: "fail",
+ embedding_abi: "off",
+ pack_validity_seconds: 60,
+ });
+ });
+
+ test("each mode key accepts every gate mode", () => {
+ for (const key of GATE_KEYS) {
+ for (const mode of ["off", "warn", "fail"] as const) {
+ const { config } = validate(HEAD + `integrity:\n ${key}: ${mode}\n`);
+ expect(config.integrity?.[key]).toBe(mode);
+ expect(resolveIntegrity(config)[key]).toBe(mode);
+ }
+ }
+ });
+
+ test("partial block β†’ missing fields fall back to defaults via resolveIntegrity", () => {
+ const { config } = validate(HEAD + `integrity:\n owner_scope_delivery: warn\n`);
+ expect(config.integrity?.owner_scope_delivery).toBe("warn");
+ expect(config.integrity?.embedding_abi).toBeUndefined();
+ const resolved = resolveIntegrity(config);
+ expect(resolved.owner_scope_delivery).toBe("warn");
+ expect(resolved.embedding_abi).toBe(BRAIN_INTEGRITY_DEFAULTS.embedding_abi);
+ expect(resolved.pack_validity_seconds).toBe(BRAIN_INTEGRITY_DEFAULTS.pack_validity_seconds);
+ });
+
+ test("an invalid mode string is rejected, naming the dotted field", () => {
+ for (const key of GATE_KEYS) {
+ for (const bad of ["on", "true", "OFF", "Warn", "refuse"]) {
+ let caught: unknown;
+ try {
+ validate(HEAD + `integrity:\n ${key}: ${bad}\n`);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(BrainConfigError);
+ expect((caught as BrainConfigError).field).toBe(`integrity.${key}`);
+ expect((caught as BrainConfigError).message).toContain(`integrity.${key}`);
+ }
+ }
+ });
+
+ test("a non-string mode value is rejected", () => {
+ for (const key of GATE_KEYS) {
+ for (const bad of ["1", "true", "null", "0.5"]) {
+ expect(() => validate(HEAD + `integrity:\n ${key}: ${bad}\n`)).toThrow(BrainConfigError);
+ }
+ }
+ });
+
+ test("pack_validity_seconds: 0 rejected", () => {
+ let caught: unknown;
+ try {
+ validate(HEAD + `integrity:\n pack_validity_seconds: 0\n`);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(BrainConfigError);
+ expect((caught as BrainConfigError).field).toBe("integrity.pack_validity_seconds");
+ });
+
+ test("pack_validity_seconds: negative rejected", () => {
+ expect(() => validate(HEAD + `integrity:\n pack_validity_seconds: -1\n`)).toThrow(
+ BrainConfigError,
+ );
+ });
+
+ test("pack_validity_seconds: non-integer rejected", () => {
+ expect(() => validate(HEAD + `integrity:\n pack_validity_seconds: 2.5\n`)).toThrow(
+ BrainConfigError,
+ );
+ });
+
+ test("pack_validity_seconds: non-number rejected", () => {
+ expect(() => validate(HEAD + `integrity:\n pack_validity_seconds: soon\n`)).toThrow(
+ BrainConfigError,
+ );
+ });
+
+ test("pack_validity_seconds: 1 accepted (no clamping, no silent default)", () => {
+ const { config } = validate(HEAD + `integrity:\n pack_validity_seconds: 1\n`);
+ expect(config.integrity?.pack_validity_seconds).toBe(1);
+ expect(resolveIntegrity(config).pack_validity_seconds).toBe(1);
+ });
+
+ test("non-object integrity block rejected", () => {
+ expect(() => validate(HEAD + `integrity: "nope"\n`)).toThrow(BrainConfigError);
+ });
+
+ test("unknown sub-key warns but does not throw", () => {
+ const { config, warnings } = validate(
+ HEAD + `integrity:\n embedding_abi: fail\n unknown_field: 1\n`,
+ );
+ expect(config.integrity?.embedding_abi).toBe("fail");
+ expect(warnings.some((w) => w.message.includes("integrity.unknown_field"))).toBe(true);
+ });
+
+ test("a block of only unknown sub-keys still resolves to defaults", () => {
+ const { config, warnings } = validate(HEAD + `integrity:\n unknown_field: 1\n`);
+ expect(config.integrity).toEqual({});
+ expect(resolveIntegrity(config)).toEqual(BRAIN_INTEGRITY_DEFAULTS);
+ expect(warnings.length).toBe(1);
+ });
+
+ test("each known sub-key emits no forward-compat warning", () => {
+ for (const key of [...GATE_KEYS, "pack_validity_seconds"] as const) {
+ const value = key === "pack_validity_seconds" ? "30" : "warn";
+ const { warnings } = validate(HEAD + `integrity:\n ${key}: ${value}\n`);
+ expect(warnings.some((w) => w.message.includes(`integrity.${key}`))).toBe(false);
+ }
+ });
+});
+
+/**
+ * `loadIntegrityConfigSafe` used to be a bare `try { … } catch { return
+ * defaults }`, which made ANY `_brain.yaml` problem - a bad gate token or
+ * an unrelated syntax error a hundred lines away - silently turn
+ * `owner_scope_delivery: fail` into `off`. An isolation boundary
+ * disabled by a typo, with no signal on any surface, is the exact class
+ * of degradation this block exists to gate.
+ */
+describe("loadIntegrityConfigSafe distinguishes absent from unreadable", () => {
+ let vault: string;
+
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-integrity-safe-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("a never-initialized vault gets the documented defaults", () => {
+ expect(loadIntegrityConfigSafe(vault)).toEqual(BRAIN_INTEGRITY_DEFAULTS);
+ expect(brainConfigReadFailure(vault)).toBeNull();
+ });
+
+ test("an unrelated syntax error does NOT disable the isolation gate", () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nintegrity:\n owner_scope_delivery: fail\nnotes:\n read_paths: 5\n",
+ "utf8",
+ );
+ const resolved = loadIntegrityConfigSafe(vault);
+ expect(resolved.owner_scope_delivery).not.toBe(GATE_MODE.off);
+ expect(resolved).toEqual(BRAIN_INTEGRITY_STRICT_FALLBACK);
+ });
+
+ test("an unreadable config is nameable rather than silent", () => {
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 9\n", "utf8");
+ const failure = brainConfigReadFailure(vault);
+ expect(failure).not.toBeNull();
+ expect(failure!.length).toBeGreaterThan(0);
+ });
+
+ test("a valid config still resolves exactly what the operator wrote", () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nintegrity:\n owner_scope_delivery: warn\n",
+ "utf8",
+ );
+ expect(loadIntegrityConfigSafe(vault).owner_scope_delivery).toBe(GATE_MODE.warn);
+ expect(brainConfigReadFailure(vault)).toBeNull();
+ });
+});
diff --git a/tests/core/brain/portability/profiles.test.ts b/tests/core/brain/portability/profiles.test.ts
index 47adb78c..056217eb 100644
--- a/tests/core/brain/portability/profiles.test.ts
+++ b/tests/core/brain/portability/profiles.test.ts
@@ -9,7 +9,7 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -49,16 +49,32 @@ describe("profile registry", () => {
});
test("switch sets the active pointer", () => {
- createProfile(configPath, "work", "/srv/vaults/work");
+ const workVault = join(home, "work-vault");
+ mkdirSync(workVault, { recursive: true });
+ createProfile(configPath, "work", workVault);
switchProfile(configPath, "work");
expect(listProfiles(configPath).active).toBe("work");
- expect(resolveActiveProfileVault(configPath)).toBe("/srv/vaults/work");
+ expect(resolveActiveProfileVault(configPath)).toBe(workVault);
});
test("switching to an unknown profile throws", () => {
expect(() => switchProfile(configPath, "ghost")).toThrow();
});
+ test("switching to a profile whose vault is not a directory fails at switch time", () => {
+ // Unit J: activation used to succeed and fail in a LATER process,
+ // where the first write would materialize the mis-resolved root.
+ createProfile(configPath, "ghost-vault", join(home, "does-not-exist"));
+ expect(() => switchProfile(configPath, "ghost-vault")).toThrow(/not a directory/);
+ // The active pointer is unchanged, so nothing resolves to it.
+ expect(listProfiles(configPath).active).toBeNull();
+
+ const filePath = join(home, "a-file");
+ atomicWriteFileSync(filePath, "not a vault\n");
+ createProfile(configPath, "file-vault", filePath);
+ expect(() => switchProfile(configPath, "file-vault")).toThrow(/not a directory/);
+ });
+
test("resolveActiveProfileVault is null with no active profile", () => {
expect(resolveActiveProfileVault(configPath)).toBeNull();
});
@@ -79,9 +95,11 @@ describe("profile registry", () => {
describe("resolveVault integration", () => {
test("returns the active profile's vault when one is active", () => {
- createProfile(configPath, "work", "/srv/vaults/work");
+ const workVault = join(home, "work-vault");
+ mkdirSync(workVault, { recursive: true });
+ createProfile(configPath, "work", workVault);
switchProfile(configPath, "work");
- expect(resolveVault(configPath)).toBe("/srv/vaults/work");
+ expect(resolveVault(configPath)).toBe(workVault);
});
test("falls back to the config vault when no profile is active (back-compat)", () => {
diff --git a/tests/core/brain/preferences-collect.test.ts b/tests/core/brain/preferences-collect.test.ts
new file mode 100644
index 00000000..f4ecc2c0
--- /dev/null
+++ b/tests/core/brain/preferences-collect.test.ts
@@ -0,0 +1,173 @@
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ collectPreferencePages,
+ collectPreferences,
+ listPreferenceFiles,
+ PREFERENCE_FILE_EXT,
+ PREFERENCE_ID_PREFIX,
+} from "../../../src/core/brain/preferences-collect.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import { GATE_MODE } from "../../../src/core/integrity/stamp.ts";
+import type { OwnerScopeDelivery } from "../../../src/core/brain/preferences-collect.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-pref-collect-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function makePref(slug: string, extra: Record<string, unknown> = {}): 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,
+ ...extra,
+ });
+}
+
+test("constants name the on-disk grammar the delivery path shares", () => {
+ expect(PREFERENCE_FILE_EXT).toBe(".md");
+ expect(PREFERENCE_ID_PREFIX).toBe("pref-");
+});
+
+test("an absent directory collects nothing rather than throwing", () => {
+ const missing = join(vault, "Brain", "does-not-exist");
+ expect(listPreferenceFiles(missing)).toEqual([]);
+ expect(collectPreferences(missing).entries).toEqual([]);
+ expect(collectPreferencePages(missing).entries).toEqual([]);
+});
+
+test("listing keeps readdirSync order and drops non-markdown names", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("alpha");
+ makePref("beta");
+ writeFileSync(join(dir, "notes.txt"), "ignored\n");
+ writeFileSync(join(dir, ".keep"), "");
+
+ const expected = readdirSync(dir).filter((n) => n.endsWith(".md"));
+ expect(listPreferenceFiles(dir).map((f) => f.name)).toEqual(expected);
+ for (const file of listPreferenceFiles(dir)) {
+ expect(file.path).toBe(join(dir, file.name));
+ }
+});
+
+test("namePrefix restricts the listing the way the digest scan does", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("alpha");
+ writeFileSync(join(dir, "stray-note.md"), "---\nkind: brain-preference\n---\n");
+
+ expect(listPreferenceFiles(dir).map((f) => f.name)).toContain("stray-note.md");
+ expect(listPreferenceFiles(dir, { namePrefix: PREFERENCE_ID_PREFIX }).map((f) => f.name)).toEqual(
+ ["pref-alpha.md"],
+ );
+});
+
+test("regularFilesOnly excludes a directory whose name ends in .md", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("alpha");
+ mkdirSync(join(dir, "pref-decoy.md"));
+
+ expect(listPreferenceFiles(dir).map((f) => f.name)).toContain("pref-decoy.md");
+ expect(listPreferenceFiles(dir, { regularFilesOnly: true }).map((f) => f.name)).toEqual([
+ "pref-alpha.md",
+ ]);
+});
+
+test("collectPreferences parses each file and skips an unparseable one", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("alpha");
+ writeFileSync(join(dir, "pref-broken.md"), "not frontmatter at all\n");
+
+ const collected = collectPreferences(dir).entries;
+ expect(collected.map((c) => c.pref.id)).toEqual(["pref-alpha"]);
+ expect(collected[0]!.name).toBe("pref-alpha.md");
+ expect(collected[0]!.path).toBe(join(dir, "pref-alpha.md"));
+ expect(collected[0]!.pref.principle).toBe("principle for alpha");
+});
+
+test("collectPreferencePages returns raw frontmatter and body without throwing", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("alpha");
+ writeFileSync(join(dir, "pref-freeform.md"), "---\ntopic: freeform\n---\nbody text\n");
+
+ const pages = collectPreferencePages(dir).entries;
+ const byName = new Map(pages.map((p) => [p.name, p]));
+ expect(byName.get("pref-freeform.md")!.meta["topic"]).toBe("freeform");
+ expect(byName.get("pref-freeform.md")!.body.trim()).toBe("body text");
+ expect(byName.get("pref-alpha.md")!.meta["kind"]).toBe("brain-preference");
+});
+
+// ----- A2: a present-but-unresolvable `owner:` is never ownerless ----------
+
+/** The gate verdict an operator who set `fail` produces for `scope`. */
+function enforcing(scope: string): OwnerScopeDelivery {
+ return Object.freeze({
+ mode: GATE_MODE.fail,
+ enforcedScope: scope,
+ requestedScope: scope,
+ });
+}
+
+/**
+ * Rewrite the preference's scalar `owner:` into a block-style YAML
+ * sequence β€” the shape Obsidian Properties writes for any list-valued
+ * field, and the shape `parseFrontmatterText` has parsed into an array
+ * since commit 426d06f8.
+ */
+function makeListOwnedPref(slug: string, owners: ReadonlyArray<string>): void {
+ makePref(slug, { owner: owners[0] });
+ const path = join(brainDirs(vault).preferences, `pref-${slug}.md`);
+ const text = readFileSync(path, "utf8");
+ const block = ["owner:", ...owners.map((o) => ` - ${o}`)].join("\n");
+ writeFileSync(path, text.replace(`owner: ${owners[0]}`, block));
+}
+
+test("a list-valued owner is withheld from every scope, not shared with all", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("shared");
+ makeListOwnedPref("listed", ["agent-a", "agent-b"]);
+
+ for (const scope of ["agent-a", "agent-b"]) {
+ const collected = collectPreferences(dir, { ownerScope: enforcing(scope) });
+ expect(collected.entries.map((c) => c.pref.id)).toEqual(["pref-shared"]);
+ expect(collected.hiddenByOwnerScope).toBe(1);
+
+ const pages = collectPreferencePages(dir, { ownerScope: enforcing(scope) });
+ expect(pages.entries.map((p) => p.name)).toEqual(["pref-shared.md"]);
+ expect(pages.hiddenByOwnerScope).toBe(1);
+ }
+});
+
+test("with the gate off, a list-valued owner changes nothing", () => {
+ const dir = brainDirs(vault).preferences;
+ makePref("shared");
+ makeListOwnedPref("listed", ["agent-a"]);
+
+ const collected = collectPreferences(dir);
+ expect(collected.entries.map((c) => c.pref.id).toSorted()).toEqual([
+ "pref-listed",
+ "pref-shared",
+ ]);
+ expect(collected.hiddenByOwnerScope).toBe(0);
+});
diff --git a/tests/core/brain/runtime-notices.test.ts b/tests/core/brain/runtime-notices.test.ts
index 0e30e3af..fec756b5 100644
--- a/tests/core/brain/runtime-notices.test.ts
+++ b/tests/core/brain/runtime-notices.test.ts
@@ -7,6 +7,7 @@ import {
collectRuntimeNotices,
renderRuntimeNotices,
} from "../../../src/core/brain/runtime-notices.ts";
+import { writeVaultIdentity } from "../../../src/core/brain/vault-identity.ts";
let vault: string;
let configPath: string;
@@ -108,3 +109,49 @@ test("renderRuntimeNotices formats a compact block and is empty when clean", ()
expect(block).toContain("no key");
expect(block).toContain("build it");
});
+
+test("an initialized vault with no identity marker yields a marker notice", () => {
+ writeConfig("");
+ seedIndex();
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ const codes = collectRuntimeNotices(vault, { configPath, env: {} }).map((n) => n.code);
+ expect(codes).toContain("vault_marker_absent");
+});
+
+test("a vault with no Brain tree yields no marker notice", () => {
+ // Nothing has been written here, so there is no store to be wrong
+ // about - and `o2b brain init` must not be nagged at before it runs.
+ writeConfig("");
+ seedIndex();
+ const codes = collectRuntimeNotices(vault, { configPath, env: {} }).map((n) => n.code);
+ expect(codes).not.toContain("vault_marker_absent");
+});
+
+test("a marked vault yields no marker notice", () => {
+ writeConfig("");
+ seedIndex();
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeVaultIdentity(vault);
+ const codes = collectRuntimeNotices(vault, { configPath, env: {} }).map((n) => n.code);
+ expect(codes).not.toContain("vault_marker_absent");
+});
+
+test("an unreadable _brain.yaml is named rather than silently defaulted", () => {
+ writeConfig("");
+ seedIndex();
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeVaultIdentity(vault);
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 9\n", "utf8");
+ const codes = collectRuntimeNotices(vault, { configPath, env: {} }).map((n) => n.code);
+ expect(codes).toContain("brain_config_unreadable");
+});
+
+test("a readable _brain.yaml yields no config notice", () => {
+ writeConfig("");
+ seedIndex();
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeVaultIdentity(vault);
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n", "utf8");
+ const codes = collectRuntimeNotices(vault, { configPath, env: {} }).map((n) => n.code);
+ expect(codes).not.toContain("brain_config_unreadable");
+});
diff --git a/tests/core/brain/vault-guard-census.test.ts b/tests/core/brain/vault-guard-census.test.ts
new file mode 100644
index 00000000..be9f2b3f
--- /dev/null
+++ b/tests/core/brain/vault-guard-census.test.ts
@@ -0,0 +1,152 @@
+/**
+ * Unit J - the guard's coverage claim, measured rather than asserted.
+ *
+ * The first cut of the write guard shipped with a docblock describing
+ * coverage nobody had counted: a review found roughly two thirds of the
+ * write-capable modules under `src/core/brain/` had no guard on any path,
+ * including the module behind `brain_create_note`. A prose claim cannot
+ * catch that; a census can.
+ *
+ * This test walks the tree, classifies every module that can put bytes on
+ * disk, and compares the unguarded set against an explicit inventory of
+ * exclusions - one entry, one reason. Adding a write-capable module
+ * without a guard fails here and names the file, so "we forgot" is not a
+ * reachable state and the release-note numbers are measured, not
+ * estimated.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { readdirSync, readFileSync } from "node:fs";
+import { join, relative } from "node:path";
+
+const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
+const BRAIN_ROOT = join(REPO_ROOT, "src", "core", "brain");
+
+/**
+ * Calls that can create, replace, move, or delete bytes on disk. A module
+ * naming any of them is write-capable and owes an answer to the census.
+ */
+const WRITE_CALL_RE = new RegExp(
+ "\\b(?:" +
+ [
+ "writeFileSync",
+ "appendFileSync",
+ "mkdirSync",
+ "renameSync",
+ "rmSync",
+ "unlinkSync",
+ "rmdirSync",
+ "cpSync",
+ "copyFileSync",
+ "atomicWriteFileSync",
+ "atomicWriteText",
+ "atomicCreateFileSyncExclusive",
+ "writeFrontmatterAtomic",
+ "withTempFile",
+ "appendAuditRecord",
+ "openSync",
+ "createWriteStream",
+ "writeSync",
+ "utimesSync",
+ "chmodSync",
+ ].join("|") +
+ ")\\s*\\(",
+);
+
+/** A module is guarded when it names the assertion or its wrapper. */
+const GUARD_RE = /assertVaultIdentityForWrite|brainDirsForWrite/;
+
+/**
+ * Every write-capable module that deliberately carries no guard, with the
+ * reason it does not. A module may only be here because asserting would
+ * be wrong, never because asserting was inconvenient.
+ */
+const UNGUARDED_WITH_REASON: Readonly<Record<string, string>> = Object.freeze({
+ "src/core/brain/init.ts":
+ "bootstrap. This is the path that CREATES the tree and stamps the marker; " +
+ "gating it on the marker it is about to write would refuse `o2b brain init` " +
+ "on the very root it exists to serve.",
+ "src/core/brain/inject-failopen.ts":
+ "fail-open injection cache. The hook contract is that a degraded injection " +
+ "still returns something; a refusal here would turn a cache miss into a " +
+ "broken SessionStart.",
+ "src/core/brain/maintenance/lease.ts":
+ "lock primitive. The lease file is how concurrent maintenance runs " +
+ "serialize; the runs it protects are guarded at their own entry points, " +
+ "and refusing to take a lock would strand the holder rather than protect " +
+ "anything.",
+ "src/core/brain/inline-rewrite.ts":
+ "takes an absolute file path and no vault, so there is no identity to " +
+ "assert against. Its only caller, `applyMarkerWritebacks`, is guarded.",
+ "src/core/brain/portability/pointer.ts":
+ "writes the project-side pointer that NAMES a vault, outside that vault " +
+ "(`assertNotInsideVault`). It cannot be gated on the identity of the store " +
+ "it is in the act of selecting.",
+ "src/core/brain/portability/profiles.ts":
+ "machine-local profile registry under the config directory, not vault " +
+ "content. Keyed by `configPath`; no vault is in scope.",
+ "src/core/brain/portability/recall-sources.ts":
+ "machine-local recall-source registry under the config directory, not " +
+ "vault content. Keyed by `configPath`; no vault is in scope.",
+ "src/core/brain/secrets/crypto.ts":
+ "takes a keyfile path, not a vault. The three public entry points in " +
+ "`secrets/store.ts` that reach it are guarded ahead of their first byte.",
+ "src/core/brain/sync-lockfile.ts":
+ "lock primitive over a caller-supplied path; the writers that acquire it " +
+ "are guarded at their own entry points.",
+});
+
+interface CensusRow {
+ readonly path: string;
+ readonly guarded: boolean;
+}
+
+function census(): CensusRow[] {
+ const files: string[] = [];
+ const walk = (dir: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ if (entry.isDirectory()) walk(abs);
+ else if (entry.name.endsWith(".ts")) files.push(abs);
+ }
+ };
+ walk(BRAIN_ROOT);
+ files.sort();
+
+ const rows: CensusRow[] = [];
+ for (const file of files) {
+ const text = readFileSync(file, "utf8");
+ if (!WRITE_CALL_RE.test(text)) continue;
+ rows.push({
+ path: relative(REPO_ROOT, file).split("\\").join("/"),
+ guarded: GUARD_RE.test(text),
+ });
+ }
+ return rows;
+}
+
+describe("vault write-guard census", () => {
+ test("every write-capable Brain module is guarded or excluded with a reason", () => {
+ const rows = census();
+ const unguarded = rows.filter((row) => !row.guarded).map((row) => row.path);
+ const excluded = Object.keys(UNGUARDED_WITH_REASON).toSorted();
+
+ // Named first so the failure message is the file list, not a count.
+ expect(unguarded.toSorted()).toEqual(excluded);
+ });
+
+ test("no exclusion outlives the module it excuses", () => {
+ const paths = new Set(census().map((row) => row.path));
+ for (const excluded of Object.keys(UNGUARDED_WITH_REASON)) {
+ expect(paths.has(excluded)).toBe(true);
+ }
+ });
+
+ test("the census is not vacuous", () => {
+ const rows = census();
+ // A regex that stopped matching would report a clean sweep over an
+ // empty set. Pin the shape of the measurement, not just its verdict.
+ expect(rows.length).toBeGreaterThan(90);
+ expect(rows.filter((row) => row.guarded).length).toBeGreaterThan(90);
+ });
+});
diff --git a/tests/core/brain/vault-identity.test.ts b/tests/core/brain/vault-identity.test.ts
new file mode 100644
index 00000000..6fd153aa
--- /dev/null
+++ b/tests/core/brain/vault-identity.test.ts
@@ -0,0 +1,1017 @@
+/**
+ * Unit J - guard against writes to an unexpected memory-store location.
+ *
+ * `resolveVault` returns a path from four branches with no existence
+ * validation at all, and the first Brain write materializes whatever it
+ * got. These tests pin the two halves of the answer: an unmarked root is
+ * ambiguous and warns, a root whose recorded identity changed under a
+ * live process is unambiguous and refuses.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { createHash } from "node:crypto";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join, posix, relative } from "node:path";
+
+import { regenerateActive } from "../../../src/core/brain/active.ts";
+import { refreshAnticipatoryCache } from "../../../src/core/brain/anticipatory-cache.ts";
+import { ensureDefaultAttentionFlows } from "../../../src/core/brain/attention-flows.ts";
+import { writeCaptureNote } from "../../../src/core/brain/capture/capture-note.ts";
+import {
+ appendContinuityRecord,
+ appendContinuityRecords,
+} from "../../../src/core/brain/continuity/store.ts";
+import { recordDeadEnd } from "../../../src/core/brain/dead-ends.ts";
+import { recordDecision } from "../../../src/core/brain/decisions/record.ts";
+import { appendDecisionChangeReceipt } from "../../../src/core/brain/decisions/receipts.ts";
+import { distillSource } from "../../../src/core/brain/distill/distill-source.ts";
+import { runDoctor } from "../../../src/core/brain/doctor.ts";
+import { upsertEntity } from "../../../src/core/brain/entities/registry.ts";
+import { writeExactState, clearExactState } from "../../../src/core/brain/exact-state.ts";
+import { collectExportRows } from "../../../src/core/brain/export.ts";
+import {
+ autoCloseRecalledGaps,
+ promoteGapsToTasks,
+} from "../../../src/core/brain/gaps/gap-loop.ts";
+import { writeHandoffNote } from "../../../src/core/brain/handoff.ts";
+import { appendEditHistory } from "../../../src/core/brain/health/edit-history.ts";
+import { recordThesis } from "../../../src/core/brain/health/thesis.ts";
+import { applyHygienePlan } from "../../../src/core/brain/hygiene/apply.ts";
+import type { HygienePlan } from "../../../src/core/brain/hygiene/plan.ts";
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { setIntention } from "../../../src/core/brain/intentions.ts";
+import { assignNoteLabel } from "../../../src/core/brain/labels.ts";
+import { regenerateLessons } from "../../../src/core/brain/lessons.ts";
+import { recordLineageObservation } from "../../../src/core/brain/lineage/ledger.ts";
+import { appendLogEvent } from "../../../src/core/brain/log.ts";
+import { createNote } from "../../../src/core/brain/notes/create-note.ts";
+import { addObligation } from "../../../src/core/brain/obligations.ts";
+import { brainDirs, brainDirsForWrite } from "../../../src/core/brain/paths.ts";
+import {
+ applyPending,
+ listPending,
+ rejectPending,
+ stagePendingSignal,
+} from "../../../src/core/brain/pending.ts";
+import { setPinned } from "../../../src/core/brain/pin.ts";
+import {
+ appendPinnedContext,
+ applyPinnedOperations,
+ clearPinnedContext,
+ writePinnedContext,
+} from "../../../src/core/brain/pinned.ts";
+import { writePreference } from "../../../src/core/brain/preference.ts";
+import { appendPrefAudit } from "../../../src/core/brain/pref-audit.ts";
+import type { RecallResultSet, RecallRetriever } from "../../../src/core/brain/recall-inject.ts";
+import { archivePage } from "../../../src/core/brain/recompile.ts";
+import { writeResearchReport } from "../../../src/core/brain/research/research.ts";
+import { writeRollupLedger } from "../../../src/core/brain/rollup-ladder.ts";
+import { parseSchemaPack } from "../../../src/core/brain/schema-pack.ts";
+import { applySchemaMutations } from "../../../src/core/brain/schema-mutate.ts";
+import {
+ removeSecret,
+ resolveSecretForExec,
+ setSecret,
+} from "../../../src/core/brain/secrets/store.ts";
+import { writeSignal } from "../../../src/core/brain/signal.ts";
+import { retireSignal } from "../../../src/core/brain/signal-retire.ts";
+import { learnSkillProposals } from "../../../src/core/brain/skill-proposals.ts";
+import { pruneSnapshots } from "../../../src/core/brain/snapshot.ts";
+import { computeBrainStatus } from "../../../src/core/brain/status.ts";
+import { confirmTension, persistTension } from "../../../src/core/brain/tensions.ts";
+import { createTriggers } from "../../../src/core/brain/triggers/store.ts";
+import type { InsightCandidate } from "../../../src/core/brain/triggers/types.ts";
+import { appendClaimEvent, writeTruthState } from "../../../src/core/brain/truth/store.ts";
+import { TRUTH_SCHEMA_VERSION } from "../../../src/core/brain/truth/types.ts";
+import { PREF_AUDIT_OP } from "../../../src/core/brain/types.ts";
+import { runBrainWatchdog } from "../../../src/core/brain/watchdog.ts";
+import { applyWriteBatch } from "../../../src/core/brain/write-batch.ts";
+import { createWriteSession } from "../../../src/core/brain/write-session/store.ts";
+import type { WriteSessionRecord } from "../../../src/core/brain/write-session/types.ts";
+import {
+ VaultIdentityMismatchError,
+ readVaultIdentity,
+ resetVaultIdentityPins,
+ vaultIdentityPath,
+ vaultMarkerAbsentNotice,
+ writeVaultIdentity,
+} from "../../../src/core/brain/vault-identity.ts";
+import type { DegradationNotice } from "../../../src/core/integrity/degradation.ts";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-vault-identity-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-vault-identity-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ writeFileSync(configPath, `vault: "${vault}"\n`, "utf8");
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ resetVaultIdentityPins();
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+ resetVaultIdentityPins();
+});
+
+/** One-finding hygiene plan that archives `page`. */
+function archivePlan(page: string): HygienePlan {
+ return {
+ selected: [
+ {
+ id: "usefulness:guard",
+ detector: "usefulness",
+ severity: "action",
+ title: "archive the guard page",
+ targets: [page],
+ proposed_action: "archive",
+ evidence: {},
+ },
+ ],
+ excluded_review: [],
+ unknown_ids: [],
+ };
+}
+
+describe("vault identity marker", () => {
+ test("writing is idempotent and records no machine-local path", () => {
+ const first = writeVaultIdentity(vault);
+ const second = writeVaultIdentity(vault);
+ expect(second.vault_id).toBe(first.vault_id);
+ expect(readVaultIdentity(vault)?.vault_id).toBe(first.vault_id);
+ // The marker travels with the vault across synced devices, so it must
+ // carry no absolute path - a machine-local key is stale on every peer.
+ expect(JSON.stringify(first)).not.toContain(vault);
+ expect(first.schema_version).toBe(1);
+ });
+
+ test("an unreadable or malformed marker reads as absent, never as a mismatch", () => {
+ writeFileSync(vaultIdentityPath(vault), "{ not json", "utf8");
+ expect(readVaultIdentity(vault)).toBeNull();
+ });
+});
+
+describe("brainDirsForWrite", () => {
+ test("returns the same directories as brainDirs", () => {
+ writeVaultIdentity(vault);
+ expect(brainDirsForWrite(vault)).toEqual(brainDirs(vault));
+ });
+
+ test("an absent marker warns instead of refusing", () => {
+ const notices: DegradationNotice[] = [];
+ const dirs = brainDirsForWrite(vault, notices);
+ expect(dirs.brain).toBe(brainDirs(vault).brain);
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.code).toBe("vault-marker-absent");
+ expect(notices[0]!.path).toBe(vault);
+ });
+
+ test("a marker that changed under a live process refuses the write", () => {
+ writeVaultIdentity(vault);
+ // First write pins what this process is writing to.
+ brainDirsForWrite(vault);
+
+ // The store at this path is now a different vault.
+ rmSync(vaultIdentityPath(vault));
+ const replacement = writeVaultIdentity(vault);
+
+ let raised: unknown;
+ try {
+ brainDirsForWrite(vault);
+ } catch (err) {
+ raised = err;
+ }
+ expect(raised).toBeInstanceOf(VaultIdentityMismatchError);
+ const error = raised as VaultIdentityMismatchError;
+ expect(error.notice.code).toBe("vault-marker-mismatch");
+ expect(error.message).toContain(replacement.vault_id);
+ expect(error.message).toContain(vault);
+ });
+
+ test("a replacement marker of identical size is still caught", () => {
+ // The guard memoizes (inode, size, mtime) so the hot write path costs
+ // one stat instead of an open-read-parse. Two markers minted by
+ // `writeVaultIdentity` serialize to the same byte length, so this
+ // pins that the memo keys on more than size.
+ const first = writeVaultIdentity(vault);
+ brainDirsForWrite(vault);
+ const firstBytes = readFileSync(vaultIdentityPath(vault)).length;
+
+ rmSync(vaultIdentityPath(vault));
+ const replacement = writeVaultIdentity(vault);
+ expect(replacement.vault_id).not.toBe(first.vault_id);
+ expect(readFileSync(vaultIdentityPath(vault)).length).toBe(firstBytes);
+
+ expect(() => brainDirsForWrite(vault)).toThrow(VaultIdentityMismatchError);
+ });
+
+ test("a matching marker never refuses, however many writes follow", () => {
+ writeVaultIdentity(vault);
+ for (let i = 0; i < 3; i++) expect(() => brainDirsForWrite(vault)).not.toThrow();
+ });
+});
+
+/**
+ * The guard is only worth its docblock if it fires on the write paths
+ * an operator actually drives, not just on the three call sites the
+ * first cut converted. One row per representative Brain writer; adding
+ * a writer that skips the guard makes its row fail.
+ */
+describe("the guard fires on Brain write paths", () => {
+ interface WriteCase {
+ readonly name: string;
+ /** Bring the vault into the state the write needs. */
+ readonly seed?: (vault: string) => void | Promise<void>;
+ readonly write: (vault: string) => void | Promise<void>;
+ }
+
+ const SIGNAL_INPUT = {
+ topic: "guard-topic",
+ signal: "positive",
+ agent: "test-agent",
+ principle: "guard the write path",
+ created_at: "2026-07-26T00:00:00Z",
+ date: "2026-07-26",
+ slug: "guard-topic",
+ } as const;
+
+ const NOW = new Date("2026-07-26T00:00:00Z");
+
+ const PREF_INPUT = {
+ slug: "guard-pref",
+ topic: "guard-topic",
+ principle: "guard the write path",
+ created_at: "2026-07-26T00:00:00Z",
+ unconfirmed_until: "2026-08-02T00:00:00Z",
+ status: "unconfirmed",
+ evidenced_by: [],
+ } as const;
+
+ const SECRET_INPUT = {
+ name: "guard-secret",
+ value: "s3cret-material",
+ allow: ["echo *"],
+ agent: "test-agent",
+ now: NOW,
+ } as const;
+
+ const GUARD_PAGE_REL = posix.join("Brain", "notes", "guard-page.md");
+
+ function guardPagePath(vaultRoot: string): string {
+ return join(vaultRoot, "Brain", "notes", "guard-page.md");
+ }
+
+ function writeGuardPage(vaultRoot: string): void {
+ mkdirSync(join(vaultRoot, "Brain", "notes"), { recursive: true });
+ writeFileSync(guardPagePath(vaultRoot), "---\ntitle: Guard\n---\n\nGuarded page.\n", "utf8");
+ }
+
+ const TENSION_FINDING = {
+ aId: "note-a",
+ bId: "note-b",
+ subject: "write guard",
+ jaccard: 0.9,
+ aSign: "positive",
+ bSign: "negative",
+ aQuote: "the guard covers writes",
+ bQuote: "the guard does not cover writes",
+ action: "ask_user",
+ } as const;
+
+ /** Slug the seeded tension landed under, captured for the transition. */
+ let seededTensionSlug = "";
+
+ function seedOpenGapTask(vaultRoot: string): void {
+ const dir = join(vaultRoot, "Brain", "gap-tasks");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(
+ join(dir, "guard-gap.md"),
+ [
+ "---",
+ "kind: brain-gap-task",
+ "gap_key: guard-gap",
+ "gap_topic: guard topic",
+ "status: open",
+ 'occurrences: "3"',
+ "created_at: 2026-07-26T00:00:00Z",
+ "---",
+ "",
+ "Recurring recall gap.",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+ }
+
+ const RECALL_RETRIEVER: RecallRetriever = () =>
+ Promise.resolve({
+ candidates: [
+ {
+ path: "Brain/x.md",
+ title: "X",
+ score: 0.92,
+ searchType: "hybrid",
+ startLine: 1,
+ endLine: 2,
+ },
+ ],
+ total: 1,
+ } satisfies RecallResultSet);
+
+ function seedSnapshotArchive(vaultRoot: string): void {
+ const dir = join(vaultRoot, "Brain", ".snapshots");
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "2026-07-26T00-00-00Z.tar.zst"), "not a real archive", "utf8");
+ }
+
+ const WRITE_SESSION_NOW = "2026-07-26T00:00:00Z";
+
+ function writeSessionRecord(id: string): WriteSessionRecord {
+ return {
+ id,
+ kind: "artifact",
+ status: "needs-llm-step",
+ step: "artifact",
+ agent: "test-agent",
+ createdAt: WRITE_SESSION_NOW,
+ updatedAt: WRITE_SESSION_NOW,
+ expiresAt: "2026-07-27T00:00:00Z",
+ attempts: 0,
+ retryCap: 3,
+ targetPath: "Brain/notes/guard-session.md",
+ intent: "create",
+ requireReview: false,
+ prompt: "Guard the write path.",
+ schemaType: null,
+ topic: null,
+ personas: [],
+ responses: {},
+ pendingArtifact: null,
+ lastErrors: [],
+ failReason: null,
+ };
+ }
+
+ const TRIGGER_CANDIDATE: InsightCandidate = {
+ kind: "contradiction",
+ urgency: "high",
+ reason: "pref-a contradicts pref-b on the same scope",
+ suggestedAction: "Review both preferences and retire one",
+ sourceArtifacts: ["[[pref-a]]", "[[pref-b]]"],
+ contextSnippets: ["pref-a: do X", "pref-b: never do X"],
+ cooldownKey: "contradiction:pref-a:pref-b",
+ };
+
+ const LABEL_PACK = parseSchemaPack(
+ ["schema_version: 1", "schema:", " labels:", " - priority=high"].join("\n") + "\n",
+ );
+
+ const CASES: ReadonlyArray<WriteCase> = [
+ {
+ name: "writeSignal",
+ write: (v) => void writeSignal(v, SIGNAL_INPUT),
+ },
+ {
+ name: "appendLogEvent",
+ write: (v) =>
+ void appendLogEvent(v, {
+ timestamp: "2026-07-26T00:00:00Z",
+ eventType: "note",
+ agent: "test-agent",
+ body: { text: "guarded" },
+ }),
+ },
+ {
+ name: "retireSignal",
+ seed: (v) => void writeSignal(v, SIGNAL_INPUT),
+ write: (v) => void retireSignal(v, "sig-2026-07-26-guard-topic", { reason: "obsolete" }),
+ },
+ {
+ name: "stagePendingSignal",
+ write: (v) => void stagePendingSignal(v, SIGNAL_INPUT),
+ },
+ {
+ name: "applyPending",
+ seed: (v) => void stagePendingSignal(v, SIGNAL_INPUT),
+ write: (v) => void applyPending(v, "sig-2026-07-26-guard-topic"),
+ },
+ {
+ name: "rejectPending",
+ seed: (v) => void stagePendingSignal(v, SIGNAL_INPUT),
+ write: (v) => void rejectPending(v, "sig-2026-07-26-guard-topic", "not durable"),
+ },
+ {
+ name: "regenerateActive",
+ write: (v) => void regenerateActive(v),
+ },
+ {
+ name: "regenerateLessons",
+ write: (v) => void regenerateLessons(v),
+ },
+ {
+ // Every watchdog run appends an audit record under `Brain/log/`,
+ // so the probe form is a write path too - not only the remediating
+ // one, which also creates and replaces directories.
+ name: "runBrainWatchdog",
+ write: (v) => void runBrainWatchdog(v, { remediate: true }),
+ },
+
+ // ----- Writers that reach the tree through a `paths.ts` builder -----
+ //
+ // These never touch `brainDirs`, so `brainDirsForWrite` cannot cover
+ // them. `writePreference` is the headline: the single most important
+ // writer in the system, and the one the first cut of the guard missed.
+ {
+ name: "writePreference",
+ write: (v) => void writePreference(v, PREF_INPUT),
+ },
+ {
+ name: "setPinned",
+ seed: (v) => void writePreference(v, PREF_INPUT),
+ write: (v) => void setPinned(v, `pref-${PREF_INPUT.slug}`, true),
+ },
+ {
+ name: "appendPrefAudit",
+ write: (v) =>
+ void appendPrefAudit(v, {
+ pref_id: `pref-${PREF_INPUT.slug}`,
+ op: PREF_AUDIT_OP.create,
+ agent: "test-agent",
+ revision_before: null,
+ revision_after: 1,
+ hash_before: null,
+ hash_after: "abc",
+ }),
+ },
+ {
+ name: "appendEditHistory",
+ write: (v) =>
+ void appendEditHistory(v, PREF_INPUT.slug, [
+ {
+ ts: "2026-07-26T00:00:00Z",
+ agent: "test-agent",
+ revision: 1,
+ field: "principle",
+ before: "a",
+ after: "b",
+ },
+ ]),
+ },
+ {
+ name: "writePinnedContext",
+ write: (v) => void writePinnedContext(v, "guarded"),
+ },
+ {
+ name: "appendPinnedContext",
+ write: (v) => void appendPinnedContext(v, "guarded"),
+ },
+ {
+ name: "clearPinnedContext",
+ write: (v) => void clearPinnedContext(v),
+ },
+ {
+ name: "writeExactState",
+ write: (v) => void writeExactState(v, "guard-aspect", "value"),
+ },
+ {
+ name: "clearExactState",
+ seed: (v) => void writeExactState(v, "guard-aspect", "value"),
+ write: (v) => void clearExactState(v, "guard-aspect"),
+ },
+ {
+ name: "upsertEntity",
+ write: (v) =>
+ void upsertEntity(v, {
+ category: "person",
+ name: "Guard Subject",
+ agent: "test-agent",
+ now: NOW,
+ }),
+ },
+ {
+ name: "recordDecision",
+ write: (v) =>
+ void recordDecision(v, {
+ title: "Guard the write path",
+ chosen: "guard at the writer entry point",
+ assumption: "the builders stay intent-neutral",
+ reviewDate: "2026-08-26",
+ agent: "test-agent",
+ now: NOW,
+ }),
+ },
+ {
+ name: "recordThesis",
+ write: (v) =>
+ void recordThesis(v, {
+ statement: "the write guard must cover the preference writer",
+ agent: "test-agent",
+ now: NOW,
+ }),
+ },
+ {
+ name: "addObligation",
+ write: (v) =>
+ void addObligation(v, {
+ title: "Review the write guard",
+ cadence: "monthly",
+ agent: "test-agent",
+ now: NOW,
+ }),
+ },
+ {
+ name: "persistTension",
+ write: (v) =>
+ void persistTension(
+ v,
+ {
+ aId: "note-a",
+ bId: "note-b",
+ subject: "write guard",
+ jaccard: 0.9,
+ aSign: "positive",
+ bSign: "negative",
+ aQuote: "the guard covers writes",
+ bQuote: "the guard does not cover writes",
+ action: "ask_user",
+ },
+ { now: NOW },
+ ),
+ },
+ {
+ name: "writeResearchReport",
+ write: (v) =>
+ void writeResearchReport(
+ v,
+ {
+ title: "Guarded report",
+ findings: [{ statement: "the guard fires", sources: ["src-a"] }],
+ sources: ["src-a"],
+ },
+ { agent: "test-agent", now: NOW },
+ ),
+ },
+ {
+ name: "distillSource",
+ write: (v) =>
+ void distillSource(
+ v,
+ {
+ sourcePath: "sources/guard.md",
+ claims: [{ text: "the guard fires" }],
+ },
+ { agent: "test-agent", now: NOW },
+ ),
+ },
+ {
+ name: "writeCaptureNote",
+ write: (v) =>
+ void writeCaptureNote(v, {
+ body: "guarded capture",
+ provenance: {
+ source: "telegram",
+ sender: "1",
+ capturedAt: "2026-07-26T00:00:00Z",
+ },
+ }),
+ },
+ {
+ name: "promoteGapsToTasks",
+ write: (v) => void promoteGapsToTasks(v, { now: NOW }),
+ },
+ {
+ name: "learnSkillProposals",
+ write: (v) => void learnSkillProposals(v, { now: NOW }),
+ },
+ {
+ name: "ensureDefaultAttentionFlows",
+ write: (v) => void ensureDefaultAttentionFlows(v),
+ },
+ {
+ name: "writeRollupLedger",
+ write: (v) => void writeRollupLedger(v, { version: 1, baselines: {}, produced: {} }),
+ },
+ {
+ name: "applyWriteBatch",
+ write: (v) =>
+ void applyWriteBatch(v, [
+ { kind: "create_note", path: "guard-note.md", content: "guarded" },
+ ]),
+ },
+
+ // ----- Writers whose only guard was a TRAILING audit append --------
+ //
+ // Every one of these put bytes on disk and raised the mismatch
+ // afterwards. The secret custody store is the worst: the keyfile and
+ // the encrypted store landed in the wrong vault, outside `Brain/`,
+ // where the first cut of this harness could not even see them.
+ {
+ name: "setSecret",
+ write: (v) => void setSecret(v, SECRET_INPUT),
+ },
+ {
+ name: "removeSecret",
+ seed: (v) => void setSecret(v, SECRET_INPUT),
+ write: (v) => void removeSecret(v, SECRET_INPUT.name, { agent: "test-agent", now: NOW }),
+ },
+ {
+ // The read-shaped surface that still writes: it stamps
+ // `last_used_at` and appends a custody record.
+ name: "resolveSecretForExec",
+ seed: (v) => void setSecret(v, SECRET_INPUT),
+ write: (v) =>
+ void resolveSecretForExec(v, SECRET_INPUT.name, { agent: "test-agent", now: NOW }),
+ },
+ {
+ name: "applySchemaMutations",
+ write: async (v) => {
+ await applySchemaMutations(v, [{ op: "add_link_type", token: "guards" }], {
+ actor: "test-agent",
+ now: NOW,
+ });
+ },
+ },
+ {
+ name: "archivePage",
+ seed: (v) => void writeGuardPage(v),
+ write: (v) => void archivePage(v, guardPagePath(v), NOW),
+ },
+ {
+ name: "applyHygienePlan",
+ seed: (v) => void writeGuardPage(v),
+ write: async (v) => {
+ await applyHygienePlan(v, archivePlan(guardPagePath(v)), {
+ agent: "test-agent",
+ now: NOW,
+ });
+ },
+ },
+
+ // ----- Unguarded writers inside modules counted as guarded ---------
+ //
+ // `brain_pinned_context` refused a mismatched vault in single-op
+ // mode and wrote to it in `operations` batch mode - same tool, same
+ // file, same call.
+ {
+ name: "applyPinnedOperations",
+ write: (v) => void applyPinnedOperations(v, [{ op: "write", content: "guarded" }]),
+ },
+ {
+ name: "confirmTension",
+ seed: (v) => {
+ seededTensionSlug = persistTension(v, TENSION_FINDING, { now: NOW }).record.slug;
+ },
+ write: (v) => void confirmTension(v, seededTensionSlug, { now: NOW }),
+ },
+ {
+ name: "autoCloseRecalledGaps",
+ seed: (v) => void seedOpenGapTask(v),
+ write: async (v) => {
+ await autoCloseRecalledGaps(v, RECALL_RETRIEVER, { confidenceFloor: 0.5, now: NOW });
+ },
+ },
+ {
+ name: "pruneSnapshots",
+ seed: (v) => void seedSnapshotArchive(v),
+ write: (v) => void pruneSnapshots(v, 0),
+ },
+
+ // ----- High-traffic MCP-reachable writers with no guard at all -----
+ {
+ name: "createNote",
+ write: (v) => void createNote(v, { path: "notes/guard-created.md", content: "x" }),
+ },
+ {
+ name: "appendContinuityRecord",
+ write: (v) =>
+ void appendContinuityRecord(v, {
+ kind: "session_turn",
+ createdAt: "2026-07-26T00:00:00Z",
+ payload: { session_id: "guard", turn_id: "t-1", role: "user", text: "guarded" },
+ }),
+ },
+ {
+ name: "appendContinuityRecords",
+ write: (v) =>
+ void appendContinuityRecords(v, [
+ {
+ kind: "session_turn",
+ createdAt: "2026-07-26T00:00:00Z",
+ payload: { session_id: "guard", turn_id: "t-2", role: "user", text: "guarded" },
+ },
+ ]),
+ },
+ {
+ name: "recordDeadEnd",
+ write: (v) =>
+ void recordDeadEnd(v, {
+ approach: "Trailing audit append as a write guard",
+ reason: "the bytes land before the refusal",
+ agent: "test-agent",
+ now: NOW,
+ }),
+ },
+ {
+ name: "appendDecisionChangeReceipt",
+ write: (v) =>
+ void appendDecisionChangeReceipt(v, {
+ ts: "2026-07-26T00:00:00Z",
+ subject: "pref-guard-pref",
+ before: "confidence:medium(0.55)",
+ after: "confidence:high(0.88)",
+ evidenceTriggers: [],
+ confidenceDelta: 0.33,
+ alternatives: [],
+ actor: "test-agent",
+ rationale: "guard the write path",
+ reasonCode: "confidence-refresh",
+ }),
+ },
+ {
+ name: "createWriteSession",
+ write: (v) => void createWriteSession(v, WRITE_SESSION_NOW, (id) => writeSessionRecord(id)),
+ },
+ {
+ name: "appendClaimEvent",
+ write: (v) =>
+ void appendClaimEvent(v, {
+ ts: "2026-07-26T00:00:00Z",
+ agent: "test-agent",
+ entity: "Guard Subject",
+ aspect: "employer",
+ value: "Anthropic",
+ source: "[[Brain/notes/guard.md]]",
+ }),
+ },
+ {
+ name: "writeTruthState",
+ write: (v) =>
+ void writeTruthState(v, {
+ version: TRUTH_SCHEMA_VERSION,
+ events: 0,
+ updatedAt: null,
+ slots: [],
+ conflicts: [],
+ }),
+ },
+ {
+ name: "setIntention",
+ write: (v) =>
+ void setIntention(v, {
+ scope: "guard",
+ text: "Guard the write path",
+ agent: "test-agent",
+ now: NOW,
+ }),
+ },
+ {
+ name: "createTriggers",
+ write: (v) => void createTriggers(v, [TRIGGER_CANDIDATE], { now: NOW }),
+ },
+ {
+ name: "assignNoteLabel",
+ seed: (v) => void writeGuardPage(v),
+ write: (v) =>
+ void assignNoteLabel(v, GUARD_PAGE_REL, {
+ dimension: "priority",
+ value: "high",
+ pack: LABEL_PACK,
+ agent: "test-agent",
+ now: NOW,
+ }),
+ },
+ {
+ name: "writeHandoffNote",
+ write: (v) =>
+ void writeHandoffNote(v, {
+ turns: [
+ {
+ turnId: "t-1",
+ timestamp: "2026-07-26T00:00:00Z",
+ role: "user",
+ text: "guard the write path",
+ },
+ ],
+ sessionId: "guard-session",
+ agent: "test-agent",
+ now: NOW,
+ }),
+ },
+ {
+ name: "refreshAnticipatoryCache",
+ seed: (v) =>
+ void recordLineageObservation(v, {
+ sessionId: "guard-child",
+ at: NOW.toISOString(),
+ event: "SessionStart",
+ lineage: { rootId: "guard-root", parentId: "guard-root", depth: 1, source: "payload" },
+ }),
+ write: (v) =>
+ void refreshAnticipatoryCache(v, {
+ sessionId: "guard-child",
+ signalText: "guarding the write path",
+ now: NOW,
+ }),
+ },
+ ];
+
+ for (const testCase of CASES) {
+ test(`${testCase.name} refuses a vault whose marker changed`, async () => {
+ bootstrapBrain(vault, { configPath });
+ await testCase.seed?.(vault);
+ // Pin what this process has been writing to.
+ brainDirsForWrite(vault);
+
+ // The store under this path is now a different vault.
+ rmSync(vaultIdentityPath(vault));
+ writeVaultIdentity(vault);
+ const before = snapshotVaultTree(vault);
+
+ let raised: unknown;
+ try {
+ await testCase.write(vault);
+ } catch (err) {
+ raised = err;
+ }
+ // The byte assertion comes FIRST and deliberately so. Refusing
+ // AFTER the bytes landed is not refusing: a writer that trips the
+ // guard only on a downstream log append has already materialized a
+ // page in the wrong store. Asserting the throw first would report
+ // "it threw" and hide the bytes, which is exactly how this class of
+ // defect survived the previous review.
+ expect(snapshotVaultTree(vault)).toEqual(before);
+ expect(raised).toBeInstanceOf(VaultIdentityMismatchError);
+ });
+ }
+});
+
+/**
+ * Digest of EVERY file under the vault root, keyed by vault-relative
+ * path, PLUS one entry per directory.
+ *
+ * The whole root, not just `Brain/`: the secret custody store lives in
+ * `<vault>/.open-second-brain/secrets/` and `createNote` authors notes
+ * anywhere the vault scope allows, so a `Brain/`-only walk cannot see
+ * the bytes those writers land - which is precisely why the secrets
+ * store shipped with its guard behind the first byte.
+ *
+ * Directories are recorded because a bare `mkdirSync` leaves no file
+ * behind: `loadOrCreateKey` creates the 0700 secrets directory before it
+ * writes anything, and a file-only digest would call that "no trace".
+ * The identity marker is excluded because the harness rewrites it
+ * between the snapshot and the call.
+ */
+function snapshotVaultTree(vaultRoot: string): Record<string, string> {
+ const markerRel = relative(vaultRoot, vaultIdentityPath(vaultRoot));
+ const out: Record<string, string> = {};
+ const walk = (dir: string): void => {
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
+ const abs = join(dir, entry.name);
+ const rel = relative(vaultRoot, abs);
+ if (entry.isDirectory()) {
+ out[`${rel}/`] = "<dir>";
+ walk(abs);
+ continue;
+ }
+ if (rel === markerRel) continue;
+ out[rel] = createHash("sha256").update(readFileSync(abs)).digest("hex");
+ }
+ };
+ if (existsSync(vaultRoot)) walk(vaultRoot);
+ return out;
+}
+
+/**
+ * The other half of the contract: widening the guard onto read paths
+ * would break the fail-open surfaces (`src/openclaw`, the hooks), so a
+ * read must stay indifferent to the marker.
+ */
+describe("the guard stays off read paths", () => {
+ const READS: ReadonlyArray<{ name: string; read: (vault: string) => void }> = [
+ { name: "listPending", read: (v) => void listPending(v) },
+ { name: "runDoctor", read: (v) => void runDoctor(v) },
+ { name: "computeBrainStatus", read: (v) => void computeBrainStatus(v) },
+ { name: "collectExportRows", read: (v) => void collectExportRows(v) },
+ ];
+
+ for (const testCase of READS) {
+ test(`${testCase.name} is indifferent to a changed marker`, () => {
+ bootstrapBrain(vault, { configPath });
+ brainDirsForWrite(vault);
+ rmSync(vaultIdentityPath(vault));
+ writeVaultIdentity(vault);
+ expect(() => testCase.read(vault)).not.toThrow();
+ });
+ }
+});
+
+/**
+ * The absent-marker half used to be reachable only by passing an optional
+ * sink no production call site passed, and the module docblock claimed the
+ * doctor surfaced it while `runDoctor` imported nothing from here. These
+ * pin the replacement: one exported check that reads the marker, and one
+ * production channel that reports it.
+ */
+describe("vaultMarkerAbsentNotice", () => {
+ test("names an unmarked root with the closed-vocabulary code", () => {
+ const notice = vaultMarkerAbsentNotice(vault);
+ expect(notice).not.toBeNull();
+ expect(notice!.code).toBe("vault-marker-absent");
+ expect(notice!.site).toBe("vault-identity");
+ expect(notice!.path).toBe(vault);
+ });
+
+ test("is silent once the root carries a marker", () => {
+ writeVaultIdentity(vault);
+ expect(vaultMarkerAbsentNotice(vault)).toBeNull();
+ });
+
+ test("treats a malformed marker as absent, never as a mismatch", () => {
+ writeFileSync(vaultIdentityPath(vault), "{ not json", "utf8");
+ expect(vaultMarkerAbsentNotice(vault)?.code).toBe("vault-marker-absent");
+ });
+
+ test("is the same record the write-path sink receives", () => {
+ const notices: DegradationNotice[] = [];
+ brainDirsForWrite(vault, notices);
+ expect(notices).toHaveLength(1);
+ expect(notices[0]).toEqual(vaultMarkerAbsentNotice(vault)!);
+ });
+});
+
+/**
+ * The honest limit of the mechanism, asserted rather than described: the
+ * only reachable refusal is same-path, marker-changed, mid-process.
+ */
+describe("what the guard does NOT catch", () => {
+ test("a cold-start mis-resolution proceeds and is reported, not refused", () => {
+ // The reviewer's probe: a never-existent sibling root.
+ const wrong = `${vault}t`;
+ try {
+ expect(() =>
+ appendLogEvent(wrong, {
+ timestamp: "2026-07-26T00:00:00Z",
+ eventType: "note",
+ agent: "test-agent",
+ body: { text: "mis-resolved" },
+ }),
+ ).not.toThrow();
+ // The bytes really did land under the wrong root - the guard has no
+ // durable expectation to compare a cold start against.
+ expect(existsSync(join(wrong, "Brain", "log"))).toBe(true);
+ // What it gets instead is a named notice on that root.
+ expect(vaultMarkerAbsentNotice(wrong)?.code).toBe("vault-marker-absent");
+ } finally {
+ rmSync(wrong, { recursive: true, force: true });
+ }
+ });
+
+ test("two distinct roots in one process are independent", () => {
+ const other = mkdtempSync(join(tmpdir(), "o2b-vault-identity-other-"));
+ try {
+ mkdirSync(join(other, "Brain"), { recursive: true });
+ writeVaultIdentity(vault);
+ writeVaultIdentity(other);
+ expect(() => brainDirsForWrite(vault)).not.toThrow();
+ expect(() => brainDirsForWrite(other)).not.toThrow();
+ } finally {
+ rmSync(other, { recursive: true, force: true });
+ }
+ });
+
+ test("a deleted marker stops refusing rather than starting to", () => {
+ writeVaultIdentity(vault);
+ brainDirsForWrite(vault);
+ rmSync(vaultIdentityPath(vault));
+ expect(() => brainDirsForWrite(vault)).not.toThrow();
+ });
+});
+
+describe("bootstrap path", () => {
+ test("o2b brain init stamps the marker and never trips the guard", () => {
+ expect(existsSync(vaultIdentityPath(vault))).toBe(false);
+ expect(() => bootstrapBrain(vault, { configPath })).not.toThrow();
+ const identity = readVaultIdentity(vault);
+ expect(identity).not.toBeNull();
+
+ // A second bootstrap keeps the identity it already established.
+ bootstrapBrain(vault, { configPath });
+ expect(readVaultIdentity(vault)!.vault_id).toBe(identity!.vault_id);
+
+ const notices: DegradationNotice[] = [];
+ expect(() => brainDirsForWrite(vault, notices)).not.toThrow();
+ expect(notices).toHaveLength(0);
+ });
+});
diff --git a/tests/core/graph/agent-scope.test.ts b/tests/core/graph/agent-scope.test.ts
index 4490b808..01198e38 100644
--- a/tests/core/graph/agent-scope.test.ts
+++ b/tests/core/graph/agent-scope.test.ts
@@ -17,24 +17,65 @@
import { describe, expect, test } from "bun:test";
import {
+ OWNER_UNRESOLVED,
isOwnerVisible,
normalizeAgentScope,
+ ownerToken,
pageOwner,
} from "../../../src/core/graph/agent-scope.ts";
+import { parseFrontmatterText } from "../../../src/core/vault.ts";
describe("pageOwner", () => {
test("returns null when no owner is declared", () => {
expect(pageOwner({})).toBeNull();
- expect(pageOwner({ owner: "" })).toBeNull();
});
test("normalizes the declared owner token (NFC + lowercase + trim)", () => {
expect(pageOwner({ owner: " Agent-A " })).toBe("agent-a");
});
- test("ignores a non-string owner", () => {
- expect(pageOwner({ owner: 42 })).toBeNull();
- expect(pageOwner({ owner: ["a", "b"] })).toBeNull();
+ /**
+ * A present-but-unresolvable `owner:` is an ownership CLAIM, so it must
+ * never read as ownerless - that would share an owner-private page with
+ * every agent. It resolves to the poison token instead, which no
+ * requested scope can equal.
+ */
+ test("a present-but-unusable owner is unresolved, never ownerless", () => {
+ expect(pageOwner({ owner: "" })).toBe(OWNER_UNRESOLVED);
+ expect(pageOwner({ owner: 42 })).toBe(OWNER_UNRESOLVED);
+ expect(pageOwner({ owner: ["a", "b"] })).toBe(OWNER_UNRESOLVED);
+ });
+
+ /**
+ * Commit 426d06f8 taught `parseFrontmatterText` to parse block-style
+ * YAML lists into arrays, which is how Obsidian Properties writes any
+ * list-shaped field. These are the exact shapes it produces.
+ */
+ test.each([
+ ["block sequence", "owner:\n - agent-a\n - agent-b"],
+ ["inline array", "owner: [agent-a, agent-b]"],
+ ["nested mapping", "owner:\n name: agent-a"],
+ ["empty value", "owner:"],
+ ])("a %s owner: is unresolved, not shared", (_label, frontmatter) => {
+ const [meta] = parseFrontmatterText(`---\n${frontmatter}\n---\nbody\n`);
+ expect(pageOwner(meta)).toBe(OWNER_UNRESOLVED);
+ expect(isOwnerVisible(pageOwner(meta), "agent-a")).toBe(false);
+ expect(isOwnerVisible(pageOwner(meta), "agent-b")).toBe(false);
+ // Byte-identical with no scope requested.
+ expect(isOwnerVisible(pageOwner(meta), null)).toBe(true);
+ });
+});
+
+describe("ownerToken", () => {
+ test("is idempotent on the poison token", () => {
+ expect(ownerToken(OWNER_UNRESOLVED)).toBe(OWNER_UNRESOLVED);
+ });
+
+ test("no requested scope can ever equal the poison token", () => {
+ // `normalizeAgentScope` lower-cases, so an upper-case token is
+ // unreachable from any caller-supplied scope.
+ expect(normalizeAgentScope(OWNER_UNRESOLVED)).not.toBe(OWNER_UNRESOLVED);
+ expect(isOwnerVisible(OWNER_UNRESOLVED, normalizeAgentScope(OWNER_UNRESOLVED))).toBe(false);
});
});
diff --git a/tests/core/integrity/degradation.test.ts b/tests/core/integrity/degradation.test.ts
new file mode 100644
index 00000000..fe230005
--- /dev/null
+++ b/tests/core/integrity/degradation.test.ts
@@ -0,0 +1,232 @@
+/**
+ * Seam 1 - the typed degradation notice channel.
+ *
+ * Pins the two properties the seam exists for: the code vocabulary is
+ * CLOSED (an unhandled member is a compile error at the consumer, which
+ * the exhaustive switch below proves), and a notice renders to exactly
+ * one English line that names the path when one is known.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ DEGRADATION_CODE,
+ DegradationNoticeError,
+ degradationNotice,
+ emitDegradationNotice,
+ formatDegradationNotice,
+ type DegradationCode,
+ type DegradationNotice,
+} from "../../../src/core/integrity/degradation.ts";
+
+const ALL_CODES = Object.values(DEGRADATION_CODE) as ReadonlyArray<DegradationCode>;
+
+function assertNever(value: never): never {
+ throw new Error(`unhandled degradation code: ${String(value)}`);
+}
+
+/**
+ * The exhaustiveness proof. Every member is handled explicitly; the
+ * `default` arm binds `code` to `never`, so adding a member to the union
+ * without adding an arm here fails `bun run typecheck`.
+ */
+function owningUnit(code: DegradationCode): string {
+ switch (code) {
+ case DEGRADATION_CODE.frontmatterLineDropped:
+ return "F";
+ case DEGRADATION_CODE.frontmatterUnreadable:
+ return "F";
+ case DEGRADATION_CODE.vaultWalkEntrySkipped:
+ return "F";
+ case DEGRADATION_CODE.sessionLinkAbstained:
+ return "C";
+ case DEGRADATION_CODE.lineageObservationDropped:
+ return "D";
+ case DEGRADATION_CODE.lineageChainBroken:
+ return "D";
+ case DEGRADATION_CODE.vaultMarkerAbsent:
+ return "J";
+ case DEGRADATION_CODE.vaultMarkerMismatch:
+ return "J";
+ default:
+ return assertNever(code);
+ }
+}
+
+describe("DEGRADATION_CODE vocabulary", () => {
+ test("is a non-empty closed set of unique kebab-case tokens", () => {
+ expect(ALL_CODES.length).toBeGreaterThan(0);
+ expect(new Set(ALL_CODES).size).toBe(ALL_CODES.length);
+ for (const code of ALL_CODES) {
+ expect(code).toMatch(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/);
+ }
+ });
+
+ test("every member is handled by an exhaustive switch", () => {
+ for (const code of ALL_CODES) {
+ expect(owningUnit(code)).toBeTypeOf("string");
+ }
+ });
+
+ test("the frozen table cannot be extended at runtime", () => {
+ expect(Object.isFrozen(DEGRADATION_CODE)).toBe(true);
+ });
+});
+
+describe("degradationNotice", () => {
+ test("builds a frozen record carrying code, site and detail", () => {
+ const notice = degradationNotice({
+ code: DEGRADATION_CODE.frontmatterLineDropped,
+ site: "parseFrontmatterText",
+ detail: "line 3 is not a 'key: value' pair",
+ });
+ expect(notice.code).toBe(DEGRADATION_CODE.frontmatterLineDropped);
+ expect(notice.site).toBe("parseFrontmatterText");
+ expect(notice.detail).toBe("line 3 is not a 'key: value' pair");
+ expect(Object.isFrozen(notice)).toBe(true);
+ });
+
+ test("omits the path key entirely when no path is known", () => {
+ const notice = degradationNotice({
+ code: DEGRADATION_CODE.sessionLinkAbstained,
+ site: "resolveCrutchLink",
+ detail: "two candidates inside the freshness window",
+ });
+ expect("path" in notice).toBe(false);
+ expect(JSON.parse(JSON.stringify(notice))).toEqual({
+ code: DEGRADATION_CODE.sessionLinkAbstained,
+ site: "resolveCrutchLink",
+ detail: "two candidates inside the freshness window",
+ });
+ });
+
+ test("keeps the path when one is supplied", () => {
+ const notice = degradationNotice({
+ code: DEGRADATION_CODE.frontmatterUnreadable,
+ site: "indexVault",
+ detail: "EACCES",
+ path: "Brain/preferences/pref-a.md",
+ });
+ expect(notice.path).toBe("Brain/preferences/pref-a.md");
+ });
+
+ test("rejects a blank site rather than emitting an unattributable notice", () => {
+ expect(() =>
+ degradationNotice({
+ code: DEGRADATION_CODE.frontmatterLineDropped,
+ site: " ",
+ detail: "something",
+ }),
+ ).toThrow(DegradationNoticeError);
+ });
+
+ test("rejects a blank detail rather than emitting an empty explanation", () => {
+ expect(() =>
+ degradationNotice({
+ code: DEGRADATION_CODE.frontmatterLineDropped,
+ site: "parseFrontmatterText",
+ detail: "",
+ }),
+ ).toThrow(DegradationNoticeError);
+ });
+
+ test("rejects a present-but-blank path (omit the field instead)", () => {
+ expect(() =>
+ degradationNotice({
+ code: DEGRADATION_CODE.frontmatterLineDropped,
+ site: "parseFrontmatterText",
+ detail: "something",
+ path: "",
+ }),
+ ).toThrow(DegradationNoticeError);
+ });
+});
+
+describe("formatDegradationNotice", () => {
+ const base: DegradationNotice = degradationNotice({
+ code: DEGRADATION_CODE.vaultMarkerMismatch,
+ site: "assertBrainWriteTarget",
+ detail: "recorded vault id does not match the resolved root",
+ });
+
+ test("renders a single line naming code, site and detail", () => {
+ const line = formatDegradationNotice(base);
+ expect(line.includes("\n")).toBe(false);
+ expect(line).toContain(DEGRADATION_CODE.vaultMarkerMismatch);
+ expect(line).toContain("assertBrainWriteTarget");
+ expect(line).toContain("recorded vault id does not match the resolved root");
+ });
+
+ test("includes the path when known and nothing path-shaped when not", () => {
+ const withPath = degradationNotice({
+ code: DEGRADATION_CODE.frontmatterUnreadable,
+ site: "indexVault",
+ detail: "EACCES",
+ path: "Brain/log/2026-07-25.md",
+ });
+ expect(formatDegradationNotice(withPath)).toContain("Brain/log/2026-07-25.md");
+ expect(formatDegradationNotice(base)).not.toContain("(");
+ });
+
+ test("collapses embedded newlines so the result is always one line", () => {
+ const multiline = degradationNotice({
+ code: DEGRADATION_CODE.lineageChainBroken,
+ site: "verifyLineageLedger",
+ detail: "sequence 7:\n hash mismatch\r\n recomputed locally",
+ path: "Brain/.state/lineage.jsonl",
+ });
+ const line = formatDegradationNotice(multiline);
+ expect(line.includes("\n")).toBe(false);
+ expect(line.includes("\r")).toBe(false);
+ expect(line).toContain("sequence 7: hash mismatch recomputed locally");
+ });
+
+ test("passes the detail through verbatim - no vocabulary classification", () => {
+ // A structural formatter must not inspect, translate, or match words:
+ // arbitrary script survives to the rendered line unchanged.
+ const detail = "ΠΏΠΎΠ»Π΅ _status ΠΎΡ‚Π±Ρ€ΠΎΡˆΠ΅Π½ΠΎ";
+ const notice = degradationNotice({
+ code: DEGRADATION_CODE.frontmatterLineDropped,
+ site: "parseFrontmatterText",
+ detail,
+ });
+ expect(formatDegradationNotice(notice)).toContain(detail);
+ });
+
+ test("is deterministic for equal inputs", () => {
+ expect(formatDegradationNotice(base)).toBe(formatDegradationNotice({ ...base }));
+ });
+});
+
+describe("emitDegradationNotice", () => {
+ test("appends to the sink in call order and returns the notice", () => {
+ const sink: DegradationNotice[] = [];
+ const first = emitDegradationNotice(sink, {
+ code: DEGRADATION_CODE.vaultWalkEntrySkipped,
+ site: "walk",
+ detail: "ENOENT",
+ path: "Archive",
+ });
+ emitDegradationNotice(sink, {
+ code: DEGRADATION_CODE.lineageObservationDropped,
+ site: "appendLineageObservation",
+ detail: "writer lock held by another process",
+ });
+ expect(sink.length).toBe(2);
+ expect(sink[0]).toBe(first);
+ expect(sink[0]?.code).toBe(DEGRADATION_CODE.vaultWalkEntrySkipped);
+ expect(sink[1]?.code).toBe(DEGRADATION_CODE.lineageObservationDropped);
+ });
+
+ test("propagates the construction error instead of pushing a blank notice", () => {
+ const sink: DegradationNotice[] = [];
+ expect(() =>
+ emitDegradationNotice(sink, {
+ code: DEGRADATION_CODE.vaultWalkEntrySkipped,
+ site: "walk",
+ detail: " ",
+ }),
+ ).toThrow(DegradationNoticeError);
+ expect(sink.length).toBe(0);
+ });
+});
diff --git a/tests/core/integrity/stamp.test.ts b/tests/core/integrity/stamp.test.ts
new file mode 100644
index 00000000..2fcd9389
--- /dev/null
+++ b/tests/core/integrity/stamp.test.ts
@@ -0,0 +1,227 @@
+/**
+ * Seam 2 - stamp comparison, the typed mismatch, and the three-mode gate.
+ *
+ * The module is domain-agnostic on purpose: units B, E and J each supply
+ * their own token map, so these tests use field names from three
+ * unrelated domains (and some that belong to none) to prove nothing is
+ * baked in.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ GATE_MODE,
+ GATE_MODES,
+ STAMP_VERDICT,
+ checkStamp,
+ compareStamps,
+ formatStampMismatch,
+ isGateMode,
+ type GateMode,
+ type StampTokens,
+} from "../../../src/core/integrity/stamp.ts";
+
+function assertNever(value: never): never {
+ throw new Error(`unhandled gate mode: ${String(value)}`);
+}
+
+/** Exhaustiveness proof - a new mode without an arm fails typecheck. */
+function refusesOn(mode: GateMode): boolean {
+ switch (mode) {
+ case GATE_MODE.off:
+ return false;
+ case GATE_MODE.warn:
+ return false;
+ case GATE_MODE.fail:
+ return true;
+ default:
+ return assertNever(mode);
+ }
+}
+
+describe("GATE_MODE vocabulary", () => {
+ test("is exactly off | warn | fail and is frozen", () => {
+ expect([...GATE_MODES]).toEqual(["off", "warn", "fail"]);
+ expect(Object.isFrozen(GATE_MODE)).toBe(true);
+ });
+
+ test("every member is handled by an exhaustive switch", () => {
+ for (const mode of GATE_MODES) {
+ expect(refusesOn(mode)).toBeTypeOf("boolean");
+ }
+ });
+
+ test("isGateMode accepts the three tokens and nothing else", () => {
+ for (const mode of GATE_MODES) {
+ expect(isGateMode(mode)).toBe(true);
+ }
+ for (const bad of ["OFF", "Off", "on", "true", "", " off", "fail ", 0, 1, true, null, {}, []]) {
+ expect(isGateMode(bad)).toBe(false);
+ }
+ });
+});
+
+describe("compareStamps", () => {
+ test("identical token maps produce no mismatch", () => {
+ const tokens: StampTokens = { corpus_generation: "41", brain_tree: "ab12" };
+ expect(compareStamps(tokens, { ...tokens })).toEqual([]);
+ });
+
+ test("two empty maps produce no mismatch", () => {
+ expect(compareStamps({}, {})).toEqual([]);
+ });
+
+ test("a differing value yields one mismatch carrying field, expected and actual", () => {
+ const found = compareStamps(
+ { embedding_model: "modelA", embedding_dimension: "384" },
+ { embedding_model: "modelB", embedding_dimension: "384" },
+ );
+ expect(found).toEqual([{ field: "embedding_model", expected: "modelA", actual: "modelB" }]);
+ });
+
+ test("a key recorded on one side only compares against null", () => {
+ expect(compareStamps({ vec_version: "0.1.7" }, {})).toEqual([
+ { field: "vec_version", expected: "0.1.7", actual: null },
+ ]);
+ expect(compareStamps({}, { vault_id: "01J..." })).toEqual([
+ { field: "vault_id", expected: null, actual: "01J..." },
+ ]);
+ });
+
+ test("an explicit null is identical to an absent key", () => {
+ expect(compareStamps({ vec_version: null }, {})).toEqual([]);
+ expect(compareStamps({}, { vec_version: null })).toEqual([]);
+ expect(compareStamps({ vec_version: null }, { vec_version: null })).toEqual([]);
+ });
+
+ test("an empty string is a recorded value, distinct from null", () => {
+ expect(compareStamps({ token: "" }, { token: null })).toEqual([
+ { field: "token", expected: "", actual: null },
+ ]);
+ });
+
+ test("mismatches are ordered by field name regardless of key insertion order", () => {
+ const a = compareStamps(
+ { zeta: "1", alpha: "1", middle: "1" },
+ { middle: "2", zeta: "2", alpha: "2" },
+ );
+ const b = compareStamps(
+ { alpha: "1", middle: "1", zeta: "1" },
+ { alpha: "2", middle: "2", zeta: "2" },
+ );
+ expect(a.map((m) => m.field)).toEqual(["alpha", "middle", "zeta"]);
+ expect(a).toEqual(b);
+ });
+
+ test("is domain-agnostic: arbitrary field names are compared the same way", () => {
+ const found = compareStamps(
+ { "some.unrelated/field": "x", 另一δΈͺ: "y" },
+ { "some.unrelated/field": "x", 另一δΈͺ: "z" },
+ );
+ expect(found).toEqual([{ field: "另一δΈͺ", expected: "y", actual: "z" }]);
+ });
+
+ test("each mismatch record is frozen", () => {
+ const [first] = compareStamps({ a: "1" }, { a: "2" });
+ expect(first).toBeDefined();
+ expect(Object.isFrozen(first)).toBe(true);
+ });
+});
+
+describe("checkStamp", () => {
+ const expected: StampTokens = { generation: "41", digest: "aaaa" };
+ const drifted: StampTokens = { generation: "42", digest: "aaaa" };
+
+ test("off does not compare at all - no verdict, no evidence, no output to emit", () => {
+ const check = checkStamp(expected, drifted, GATE_MODE.off);
+ expect(check.verdict).toBe(STAMP_VERDICT.pass);
+ expect(check.mismatches).toEqual([]);
+ expect(check.mode).toBe(GATE_MODE.off);
+ });
+
+ test("warn reports the drift without refusing", () => {
+ const check = checkStamp(expected, drifted, GATE_MODE.warn);
+ expect(check.verdict).toBe(STAMP_VERDICT.warn);
+ expect(check.mismatches.map((m) => m.field)).toEqual(["generation"]);
+ });
+
+ test("fail reports the drift as a refusal", () => {
+ const check = checkStamp(expected, drifted, GATE_MODE.fail);
+ expect(check.verdict).toBe(STAMP_VERDICT.fail);
+ expect(check.mismatches.map((m) => m.field)).toEqual(["generation"]);
+ });
+
+ test("a matching stamp passes under every mode with no mismatches", () => {
+ for (const mode of GATE_MODES) {
+ const check = checkStamp(expected, { ...expected }, mode);
+ expect(check.verdict).toBe(STAMP_VERDICT.pass);
+ expect(check.mismatches).toEqual([]);
+ }
+ });
+
+ test("the check record is frozen", () => {
+ expect(Object.isFrozen(checkStamp(expected, drifted, GATE_MODE.warn))).toBe(true);
+ });
+});
+
+describe("formatStampMismatch", () => {
+ test("renders one English line naming the field and both values", () => {
+ const line = formatStampMismatch({
+ field: "embedding_dimension",
+ expected: "384",
+ actual: "768",
+ });
+ expect(line.includes("\n")).toBe(false);
+ expect(line).toContain("embedding_dimension");
+ expect(line).toContain("384");
+ expect(line).toContain("768");
+ });
+
+ test("renders an unrecorded side explicitly rather than as an empty gap", () => {
+ const line = formatStampMismatch({ field: "vec_version", expected: "0.1.7", actual: null });
+ expect(line.includes("\n")).toBe(false);
+ expect(line).toContain("vec_version");
+ expect(line).toContain("0.1.7");
+ // A null side must be visibly named, not rendered as nothing.
+ expect(line.trim().endsWith(":")).toBe(false);
+ expect(line).not.toContain("null,");
+ });
+
+ test("distinguishes an empty recorded value from an unrecorded one", () => {
+ const empty = formatStampMismatch({ field: "t", expected: "", actual: "x" });
+ const missing = formatStampMismatch({ field: "t", expected: null, actual: "x" });
+ expect(empty).not.toBe(missing);
+ });
+
+ test("collapses whitespace so a token carrying a newline stays on one line", () => {
+ const line = formatStampMismatch({ field: "t", expected: "a\nb", actual: "c" });
+ expect(line.includes("\n")).toBe(false);
+ });
+
+ test("is deterministic for equal inputs", () => {
+ const m = { field: "t", expected: "a", actual: "b" } as const;
+ expect(formatStampMismatch(m)).toBe(formatStampMismatch({ ...m }));
+ });
+});
+
+/**
+ * The gate vocabulary is closed, and `checkStamp` used to coerce
+ * anything that was not `off` or `fail` into `warn` - so a mode that
+ * reached it from an unvalidated path resolved to the softest verdict.
+ * A gate that softens on an unrecognised token is indistinguishable from
+ * an operator who asked for a warning, which is the class of silent
+ * degradation this seam exists to remove.
+ */
+describe("checkStamp rejects a mode outside the closed vocabulary", () => {
+ test("an unknown mode throws instead of resolving to warn", () => {
+ expect(() => checkStamp({ a: "1" }, { a: "2" }, "lenient" as unknown as GateMode)).toThrow(
+ /lenient/,
+ );
+ });
+
+ test("every declared mode is accepted", () => {
+ for (const mode of GATE_MODES) {
+ expect(() => checkStamp({ a: "1" }, { a: "2" }, mode)).not.toThrow();
+ }
+ });
+});
diff --git a/tests/core/search/agent-scope-surfaces.test.ts b/tests/core/search/agent-scope-surfaces.test.ts
new file mode 100644
index 00000000..90636cd1
--- /dev/null
+++ b/tests/core/search/agent-scope-surfaces.test.ts
@@ -0,0 +1,233 @@
+/**
+ * Owner-scope isolation on the search-backed surfaces and the
+ * progressive-disclosure drill-down (context-integrity-gates, Unit A /
+ * Task 7).
+ *
+ * These surfaces reach `isOwnerVisible` through the existing
+ * `SearchOptions.agentScope`, so the filter is per-call opt-in and NOT
+ * behind `integrity.owner_scope_delivery`: a caller that explicitly asks
+ * for a scope has asked to be isolated, and a gate that quietly ignored
+ * the request would return another owner's pages to a caller who
+ * believed it was scoped. An omitted scope filters nothing.
+ */
+
+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 { deepSynthesis } from "../../../src/core/brain/deep-synthesis.ts";
+import { fileContextRecall } from "../../../src/core/brain/file-recall.ts";
+import { expandHit } from "../../../src/core/search/cards.ts";
+import { indexVault, resolveSearchConfig, search } from "../../../src/core/search/index.ts";
+import { SearchError, type ResolvedSearchConfig } from "../../../src/core/search/types.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+
+const OWNER_A = "agent-a";
+const OWNER_B = "agent-b";
+const QUERY = "lattice widgets";
+/** Probe path whose derived query terms appear verbatim in every note. */
+const PROBE = "lattice-widgets.md";
+const PROBE_TERMS = `${PROBE} lattice-widgets`;
+
+const NOW = new Date("2026-05-10T00:00:00Z");
+
+let vault: string;
+let configHome: string;
+let config: ResolvedSearchConfig;
+
+beforeEach(async () => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-agent-scope-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-agent-scope-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "notes", "owned-a.md"),
+ `---\nowner: ${OWNER_A}\n---\n\n${QUERY} ${PROBE_TERMS} owned by a\n`,
+ );
+ writeFileSync(
+ join(vault, "notes", "owned-b.md"),
+ `---\nowner: ${OWNER_B}\n---\n\n${QUERY} ${PROBE_TERMS} owned by b\n`,
+ );
+ writeFileSync(join(vault, "notes", "shared.md"), `# Shared\n\n${QUERY} ${PROBE_TERMS} shared\n`);
+ config = resolveSearchConfig({ vault, configPath });
+ await indexVault(config, {});
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+async function chunkIdFor(relPath: string): Promise<number> {
+ const outcome = await search(config, { query: QUERY, limit: 20 });
+ const hit = outcome.results.find((r) => r.path === relPath);
+ expect(hit).toBeDefined();
+ return hit!.chunkId;
+}
+
+test("fileContextRecall scopes to the requesting owner", async () => {
+ const unscoped = await fileContextRecall(config, {
+ filePath: join(vault, "notes", PROBE),
+ minBytes: 0,
+ });
+ const unscopedPaths = unscoped.results.map((r) => r.path);
+ expect(unscopedPaths).toContain("notes/owned-a.md");
+ expect(unscopedPaths).toContain("notes/owned-b.md");
+
+ const scoped = await fileContextRecall(config, {
+ filePath: join(vault, "notes", PROBE),
+ minBytes: 0,
+ agentScope: OWNER_A,
+ });
+ const scopedPaths = scoped.results.map((r) => r.path);
+ expect(scopedPaths).not.toContain("notes/owned-b.md");
+ expect(scopedPaths).toContain("notes/owned-a.md");
+ expect(scopedPaths).toContain("notes/shared.md");
+});
+
+test("deepSynthesis scopes to the requesting owner", async () => {
+ const unscoped = await deepSynthesis(config, QUERY, { now: NOW, limit: 20 });
+ expect(unscoped.notes.map((m) => m.path)).toContain("notes/owned-b.md");
+
+ const scoped = await deepSynthesis(config, QUERY, { now: NOW, limit: 20, agentScope: OWNER_A });
+ const paths = scoped.notes.map((m) => m.path);
+ expect(paths).not.toContain("notes/owned-b.md");
+ expect(paths).toContain("notes/owned-a.md");
+ expect(paths).toContain("notes/shared.md");
+});
+
+test("expandHit refuses another owner's chunk exactly as if it were absent", async () => {
+ const foreign = await chunkIdFor("notes/owned-b.md");
+
+ // Unscoped: the drill-down works, so the refusal below is the scope.
+ const open = await expandHit(config, { chunkId: foreign });
+ expect(open.note.path).toBe("notes/owned-b.md");
+
+ const absentId = 999_999;
+ const absentError = await expandHit(config, { chunkId: absentId }).then(
+ () => null,
+ (e: unknown) => e as SearchError,
+ );
+ const refusedError = await expandHit(config, { chunkId: foreign, agentScope: OWNER_A }).then(
+ () => null,
+ (e: unknown) => e as SearchError,
+ );
+
+ expect(absentError).toBeInstanceOf(SearchError);
+ expect(refusedError).toBeInstanceOf(SearchError);
+ expect(refusedError!.code).toBe(absentError!.code);
+ // Indistinguishable but for the id the caller itself supplied: the
+ // message must not reveal that the chunk exists and is owned.
+ expect(refusedError!.message).toBe(`chunk not found: ${foreign}`);
+ expect(absentError!.message).toBe(`chunk not found: ${absentId}`);
+});
+
+test("expandHit serves the owner's own chunk and every shared one", async () => {
+ const own = await chunkIdFor("notes/owned-a.md");
+ const shared = await chunkIdFor("notes/shared.md");
+
+ expect((await expandHit(config, { chunkId: own, agentScope: OWNER_A })).note.path).toBe(
+ "notes/owned-a.md",
+ );
+ expect((await expandHit(config, { chunkId: shared, agentScope: OWNER_A })).note.path).toBe(
+ "notes/shared.md",
+ );
+});
+
+test("expandHit with a blank scope is byte-identical to an unscoped call", async () => {
+ const foreign = await chunkIdFor("notes/owned-b.md");
+ const unscoped = await expandHit(config, { chunkId: foreign });
+ const blank = await expandHit(config, { chunkId: foreign, agentScope: " " });
+ expect(JSON.stringify(blank)).toBe(JSON.stringify(unscoped));
+});
+
+// ----- A1: the isolation boundary must fail CLOSED -------------------------
+
+/**
+ * A document still in the index whose FILE is gone (deleted, renamed, or
+ * made unreadable since the last index run) has an unknowable owner. Both
+ * `isPathOwnerVisible` and `expandHit`'s per-hit check document that they
+ * fail closed; this pins that they actually do, on the ranked path and on
+ * the drill-down.
+ */
+test("a deleted owner-tagged file is hidden from another owner, not shared", async () => {
+ const foreign = await chunkIdFor("notes/owned-a.md");
+ rmSync(join(vault, "notes", "owned-a.md"));
+
+ const scoped = await search(config, { query: QUERY, limit: 20, agentScope: OWNER_B });
+ expect(scoped.results.map((r) => r.path)).not.toContain("notes/owned-a.md");
+
+ const refused = await expandHit(config, { chunkId: foreign, agentScope: OWNER_B }).then(
+ () => null,
+ (e: unknown) => e as SearchError,
+ );
+ expect(refused).toBeInstanceOf(SearchError);
+ expect(refused!.message).toBe(`chunk not found: ${foreign}`);
+});
+
+test("an unreadable owner-tagged file is hidden from another owner", async () => {
+ const target = join(vault, "notes", "owned-a.md");
+ const foreign = await chunkIdFor("notes/owned-a.md");
+ chmodSync(target, 0o000);
+ try {
+ const scoped = await search(config, { query: QUERY, limit: 20, agentScope: OWNER_B });
+ expect(scoped.results.map((r) => r.path)).not.toContain("notes/owned-a.md");
+ const refused = await expandHit(config, { chunkId: foreign, agentScope: OWNER_B }).then(
+ () => null,
+ (e: unknown) => e as SearchError,
+ );
+ expect(refused).toBeInstanceOf(SearchError);
+ } finally {
+ chmodSync(target, 0o644);
+ }
+});
+
+test("an unscoped call still serves a deleted file's indexed chunk", async () => {
+ const chunkId = await chunkIdFor("notes/owned-a.md");
+ rmSync(join(vault, "notes", "owned-a.md"));
+ const unscoped = await search(config, { query: QUERY, limit: 20 });
+ expect(unscoped.results.map((r) => r.path)).toContain("notes/owned-a.md");
+ expect((await expandHit(config, { chunkId })).note.path).toBe("notes/owned-a.md");
+});
+
+// ----- A2: a present-but-unusable `owner:` is never ownerless --------------
+
+const LIST_OWNER_SHAPES: ReadonlyArray<readonly [string, string]> = Object.freeze([
+ ["block", `owner:\n - ${OWNER_A}\n - ${OWNER_B}`],
+ ["inline", `owner: [${OWNER_A}, ${OWNER_B}]`],
+ ["mapping", `owner:\n name: ${OWNER_A}`],
+]);
+
+for (const [shape, frontmatter] of LIST_OWNER_SHAPES) {
+ test(`a ${shape}-shaped owner: is withheld from a scoped caller, not shared`, async () => {
+ const rel = `notes/owner-${shape}.md`;
+ writeFileSync(
+ join(vault, rel),
+ `---\n${frontmatter}\n---\n\n${QUERY} ${PROBE_TERMS} ${shape} owner\n`,
+ );
+ await indexVault(config, {});
+
+ const unscoped = await search(config, { query: QUERY, limit: 20 });
+ expect(unscoped.results.map((r) => r.path)).toContain(rel);
+
+ const perScope = await Promise.all(
+ [OWNER_A, OWNER_B].map((scope) =>
+ search(config, { query: QUERY, limit: 20, agentScope: scope }),
+ ),
+ );
+ for (const scoped of perScope) {
+ expect(scoped.results.map((r) => r.path)).not.toContain(rel);
+ }
+
+ const chunkId = (await search(config, { query: QUERY, limit: 20 })).results.find(
+ (r) => r.path === rel,
+ )!.chunkId;
+ const refused = await expandHit(config, { chunkId, agentScope: OWNER_A }).then(
+ () => null,
+ (e: unknown) => e as SearchError,
+ );
+ expect(refused).toBeInstanceOf(SearchError);
+ });
+}
diff --git a/tests/core/search/embedding-abi.test.ts b/tests/core/search/embedding-abi.test.ts
new file mode 100644
index 00000000..b62d3f44
--- /dev/null
+++ b/tests/core/search/embedding-abi.test.ts
@@ -0,0 +1,281 @@
+/**
+ * Embedding ABI stamp and read-path mismatch detection
+ * (context-integrity-gates, Unit E / Task 10).
+ *
+ * `index_state` already stamps the embedding model and dimension, but
+ * the comparison ran ONLY on a write-mode open. Every MCP query is a
+ * read-mode open, so `semanticTopK` executed `WHERE v.embedding MATCH ?`
+ * against a `chunk_vec` of unknown declared width with nothing checking
+ * it. These tests pin the stamp (now including the sqlite-vec version),
+ * the read-path comparison, and its gate.
+ *
+ * Vector assertions are skipped where the sqlite-vec extension cannot be
+ * loaded, following the repository-wide `sqliteVecLoadable()` pattern.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { indexCheck, indexStatus, indexVault } from "../../../src/core/search/indexer.ts";
+import {
+ EMBEDDING_ABI_FIX_COMMAND,
+ EMBEDDING_DIMENSION_STATE_KEY,
+ EMBEDDING_VEC_VERSION_STATE_KEY,
+ Store,
+} from "../../../src/core/search/store.ts";
+import { SearchError, type ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
+import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { runCli } from "../../helpers/run-cli.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+let server: FakeHttp;
+
+beforeEach(async () => {
+ const v = createTempVault("embedding-abi");
+ vault = v.vault;
+ dbPath = v.dbPath;
+ cleanup = v.cleanup;
+ server = await startFakeHttp();
+});
+
+afterEach(async () => {
+ cleanup();
+ await server.close();
+});
+
+function cfg(semantic: Partial<ResolvedEmbeddingConfig> = {}) {
+ return makeConfig({
+ vault,
+ dbPath,
+ semantic: {
+ enabled: true,
+ provider: "openai-compat",
+ baseUrl: server.url,
+ model: "fake-model",
+ apiKey: "test-key",
+ dimension: 4,
+ timeoutMs: 5_000,
+ concurrency: 2,
+ batchSize: 8,
+ costGateUsd: 0,
+ maxRetries: 3,
+ ...semantic,
+ },
+ });
+}
+
+/** Write a `_brain.yaml` selecting the `integrity.embedding_abi` mode. */
+function writeGate(mode: string): void {
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ ["schema_version: 1", "integrity:", ` embedding_abi: ${mode}`, ""].join("\n"),
+ );
+}
+
+/**
+ * Mutate recorded ABI state behind the stamp's back. The write open
+ * re-stamps first, so the edit lands after `ensureEmbeddingModel` and
+ * survives the close - which is exactly the shape of a store written by
+ * a different build.
+ */
+async function tamper(edit: (store: Store) => void): Promise<void> {
+ const store = await Store.open(cfg(), { mode: "write" });
+ edit(store);
+ await store.close();
+}
+
+test("a write open stamps the runtime sqlite-vec version beside the model and dimension", async () => {
+ if (!sqliteVecLoadable()) return;
+ const store = await Store.open(cfg(), { mode: "write" });
+ const recorded = store.getState(EMBEDDING_VEC_VERSION_STATE_KEY);
+ expect(recorded).toBe(store.vecVersion());
+ expect(typeof recorded).toBe("string");
+ expect((recorded as string).length).toBeGreaterThan(0);
+ await store.close();
+});
+
+test("the vec_version stamp is dropped when a model change clears the vectors it described", async () => {
+ if (!sqliteVecLoadable()) return;
+ const first = await Store.open(cfg(), { mode: "write" });
+ expect(first.getState(EMBEDDING_VEC_VERSION_STATE_KEY)).not.toBe(null);
+ await first.close();
+
+ // A model change clears the embeddings. The recorded vec_version
+ // described those vectors, so it must not survive them; with the
+ // extension unavailable on this open there is no runtime value to
+ // re-stamp, which makes the delete observable.
+ const second = await Store.open(cfg({ model: "other-model" }), {
+ mode: "write",
+ loadVec: false,
+ });
+ expect(second.getState(EMBEDDING_VEC_VERSION_STATE_KEY)).toBe(null);
+ await second.close();
+});
+
+test("a read-mode open detects a recorded-vs-configured dimension mismatch", async () => {
+ if (!sqliteVecLoadable()) return;
+ await tamper((s) => s.setState(EMBEDDING_DIMENSION_STATE_KEY, "8"));
+
+ const store = await Store.open(cfg(), { mode: "read" });
+ const drift = store.embeddingAbiMismatches();
+ expect(drift.map((m) => m.field)).toContain(EMBEDDING_DIMENSION_STATE_KEY);
+ const dim = drift.find((m) => m.field === EMBEDDING_DIMENSION_STATE_KEY)!;
+ expect(dim.expected).toBe("8");
+ expect(dim.actual).toBe("4");
+ await store.close();
+});
+
+test("a matching store reports no drift on a read-mode open", async () => {
+ if (!sqliteVecLoadable()) return;
+ const written = await Store.open(cfg(), { mode: "write" });
+ await written.close();
+
+ const store = await Store.open(cfg(), { mode: "read" });
+ expect(store.embeddingAbiMismatches()).toEqual([]);
+ await store.close();
+});
+
+test("under `fail` a read-mode open refuses a drifted store and names the fix", async () => {
+ if (!sqliteVecLoadable()) return;
+ writeGate("fail");
+ await tamper((s) => s.setState(EMBEDDING_DIMENSION_STATE_KEY, "8"));
+
+ let raised: unknown = null;
+ try {
+ const store = await Store.open(cfg(), { mode: "read" });
+ await store.close();
+ } catch (e) {
+ raised = e;
+ }
+ expect(raised).toBeInstanceOf(SearchError);
+ const err = raised as SearchError;
+ expect(err.code).toBe("EMBEDDING_DIMENSION_MISMATCH");
+ expect(err.message).toContain(EMBEDDING_DIMENSION_STATE_KEY);
+ expect(err.message).toContain(EMBEDDING_ABI_FIX_COMMAND);
+});
+
+test("under `warn` a drifted store still opens for reading", async () => {
+ if (!sqliteVecLoadable()) return;
+ writeGate("warn");
+ await tamper((s) => s.setState(EMBEDDING_DIMENSION_STATE_KEY, "8"));
+
+ const store = await Store.open(cfg(), { mode: "read" });
+ expect(store.embeddingAbiMismatches().length).toBeGreaterThan(0);
+ await store.close();
+});
+
+test("under `off` a read-mode open compares nothing at all", async () => {
+ if (!sqliteVecLoadable()) return;
+ writeGate("off");
+ await tamper((s) => s.setState(EMBEDDING_DIMENSION_STATE_KEY, "8"));
+
+ const store = await Store.open(cfg(), { mode: "read" });
+ expect(store.embeddingAbiMismatches()).toEqual([]);
+ await store.close();
+});
+
+test("a legacy store with no recorded vec_version warns rather than erroring, even under `fail`", async () => {
+ if (!sqliteVecLoadable()) return;
+ writeGate("fail");
+ await tamper((s) => s.deleteState(EMBEDDING_VEC_VERSION_STATE_KEY));
+
+ // `null` means UNRECORDED, not "different". An old store cannot be
+ // told apart from a wrong one by a value it never wrote, so it is
+ // reported and never refused.
+ const store = await Store.open(cfg(), { mode: "read" });
+ const drift = store.embeddingAbiMismatches();
+ const vec = drift.find((m) => m.field === EMBEDDING_VEC_VERSION_STATE_KEY);
+ expect(vec).toBeDefined();
+ expect(vec!.expected).toBe(null);
+ expect(typeof vec!.actual).toBe("string");
+ await store.close();
+});
+
+test("indexStatus surfaces the drift as a reindex-required warning", async () => {
+ if (!sqliteVecLoadable()) return;
+ writeMd(vault, "a.md", "# A\n\nA note with vectors.");
+ await indexVault(cfg(), { embeddings: true });
+ await tamper((s) => s.setState(EMBEDDING_DIMENSION_STATE_KEY, "8"));
+
+ const status = await indexStatus(cfg());
+ const warning = status.warnings.find((w) => w.includes(EMBEDDING_DIMENSION_STATE_KEY));
+ expect(warning).toBeDefined();
+ expect(warning!).toContain(EMBEDDING_ABI_FIX_COMMAND);
+ // The same finding, machine-readable, so a consumer need not match on
+ // message text. Both sides are emitted under one condition.
+ expect(status.embeddingAbi.map((m) => m.field)).toContain(EMBEDDING_DIMENSION_STATE_KEY);
+});
+
+test("indexStatus on a matching store adds no ABI warning", async () => {
+ if (!sqliteVecLoadable()) return;
+ writeMd(vault, "a.md", "# A\n\nA note with vectors.");
+ await indexVault(cfg(), { embeddings: true });
+
+ const status = await indexStatus(cfg());
+ expect(status.warnings.some((w) => w.includes(EMBEDDING_VEC_VERSION_STATE_KEY))).toBe(false);
+ expect(status.warnings.some((w) => w.includes(EMBEDDING_DIMENSION_STATE_KEY))).toBe(false);
+});
+
+test("`search check` reports the stored-vs-runtime mismatch with a copy-pasteable fix", async () => {
+ if (!sqliteVecLoadable()) return;
+ writeMd(vault, "a.md", "# A\n\nA note with vectors.");
+ await indexVault(cfg(), { embeddings: true });
+ await tamper((s) => s.setState(EMBEDDING_DIMENSION_STATE_KEY, "8"));
+
+ const report = await indexCheck(cfg());
+ expect(report.embeddingAbi.map((m) => m.field)).toContain(EMBEDDING_DIMENSION_STATE_KEY);
+ // Keyed on the drifted field, not on the command alone: an unrelated
+ // "no vectors yet" hint already names the same command.
+ expect(
+ report.recommendations.some(
+ (r) => r.includes(EMBEDDING_DIMENSION_STATE_KEY) && r.includes(EMBEDDING_ABI_FIX_COMMAND),
+ ),
+ ).toBe(true);
+});
+
+test("under `off` the diagnostic still reports what the serving path stopped enforcing", async () => {
+ if (!sqliteVecLoadable()) return;
+ writeGate("off");
+ writeMd(vault, "a.md", "# A\n\nA note with vectors.");
+ await indexVault(cfg(), { embeddings: true });
+ await tamper((s) => s.setState(EMBEDDING_DIMENSION_STATE_KEY, "8"));
+
+ // The split is deliberate and must survive any later "unify these two"
+ // refactor: `indexStatus` reports what the GATED read open enforced,
+ // so `off` silences it; `indexCheck` is a diagnostic the operator
+ // explicitly ran and refuses nothing, so it compares ungated.
+ const status = await indexStatus(cfg());
+ expect(status.embeddingAbi).toEqual([]);
+ expect(status.warnings.some((w) => w.includes(EMBEDDING_ABI_FIX_COMMAND))).toBe(false);
+
+ const report = await indexCheck(cfg());
+ expect(report.embeddingAbi.map((m) => m.field)).toContain(EMBEDDING_DIMENSION_STATE_KEY);
+});
+
+test("`search check` on a matching store reports no ABI drift", async () => {
+ if (!sqliteVecLoadable()) return;
+ writeMd(vault, "a.md", "# A\n\nA note with vectors.");
+ await indexVault(cfg(), { embeddings: true });
+
+ const report = await indexCheck(cfg());
+ expect(report.embeddingAbi).toEqual([]);
+ expect(report.recommendations.some((r) => r.includes(EMBEDDING_DIMENSION_STATE_KEY))).toBe(false);
+});
+
+test("`search check` on a vault with no index reports no ABI drift", async () => {
+ const report = await indexCheck(cfg());
+ expect(report.embeddingAbi).toEqual([]);
+});
+
+test("`o2b search check --json` omits the ABI key entirely when nothing drifted", async () => {
+ const out = await runCli(["search", "check", "--json", "--vault", vault, "--db", dbPath]);
+ expect(out.returncode).toBe(0);
+ const parsed = JSON.parse(out.stdout) as Record<string, unknown>;
+ expect("embedding_abi" in parsed).toBe(false);
+});
diff --git a/tests/core/search/indexer.frontmatter-notices.test.ts b/tests/core/search/indexer.frontmatter-notices.test.ts
new file mode 100644
index 00000000..5f5271e6
--- /dev/null
+++ b/tests/core/search/indexer.frontmatter-notices.test.ts
@@ -0,0 +1,61 @@
+/**
+ * Unit F: an index run reports the frontmatter lines its scanner dropped.
+ *
+ * The reader is a line scanner, not a YAML parser, so unsupported grammar
+ * never fails the run - the file indexes and the field silently vanishes.
+ * These tests pin that the file still indexes (control flow unchanged) and
+ * that the drop now reaches `IndexStats` as a named notice.
+ */
+
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { DEGRADATION_CODE } from "../../../src/core/integrity/degradation.ts";
+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+
+let vault: string;
+let dbPath: string;
+let cleanup: () => void;
+
+beforeEach(() => {
+ const v = createTempVault("indexer-fm-notices");
+ vault = v.vault;
+ dbPath = v.dbPath;
+ cleanup = v.cleanup;
+});
+
+afterEach(() => {
+ cleanup();
+});
+
+test("a vault with no malformed frontmatter reports no notices", async () => {
+ writeFileSync(
+ join(vault, "clean.md"),
+ "---\ntitle: Clean\ntype: note\ntags:\n - a\n - b\n---\n\nBody text here.\n",
+ );
+ const stats = await indexVault(makeConfig({ vault, dbPath }));
+ expect(stats.added).toBe(1);
+ expect(stats.frontmatterNotices).toEqual([]);
+ expect(stats.errors).toEqual([]);
+});
+
+test("an unsupported frontmatter line is named in the run stats and the note still indexes", async () => {
+ writeFileSync(
+ join(vault, "odd.md"),
+ "---\ntitle: Odd\n-foo\ntype: note\n---\n\nBody text here.\n",
+ );
+ writeMd(vault, "good.md", "plain content");
+ const stats = await indexVault(makeConfig({ vault, dbPath }));
+
+ // Control flow is unchanged: both notes index, nothing is an error.
+ expect(stats.added).toBe(2);
+ expect(stats.errors).toEqual([]);
+
+ expect(stats.frontmatterNotices).toHaveLength(1);
+ const notice = stats.frontmatterNotices[0]!;
+ expect(notice.code).toBe(DEGRADATION_CODE.frontmatterLineDropped);
+ expect(notice.path).toBe("odd.md");
+ expect(notice.detail).toContain("-foo");
+});
diff --git a/tests/core/search/link-ratchet.test.ts b/tests/core/search/link-ratchet.test.ts
new file mode 100644
index 00000000..ae875236
--- /dev/null
+++ b/tests/core/search/link-ratchet.test.ts
@@ -0,0 +1,318 @@
+/**
+ * Vault-wide broken-link ratchet (context-integrity-gates, unit G).
+ *
+ * Pins the three properties the gate rests on:
+ * - the counting definition: a link is broken when the READ-TIME
+ * resolution ladder cannot resolve it, so a basename wikilink a
+ * reader follows is not counted and an ambiguous one is;
+ * - determinism: two measurements over an unchanged vault agree;
+ * - the full-resolution precondition: a count taken after an
+ * incremental run is reported as UNMEASURABLE, never as a number
+ * and never as "clean".
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ DANGLING_LINK_DEFINITION,
+ LINK_RATCHET_FIX_COMMAND,
+ LINK_RATCHET_SCHEMA_VERSION,
+ judgeSubject,
+ measureFromIndex,
+ measureVault,
+ parseCeiling,
+ ratchetSearchConfig,
+ serializeCeiling,
+ LinkRatchetError,
+ type LinkRatchetMeasurement,
+} from "../../../src/core/search/link-ratchet.ts";
+import { indexVault } from "../../../src/core/search/indexer.ts";
+import { Store } from "../../../src/core/search/store.ts";
+import { writeMd } from "../../helpers/search-fixtures.ts";
+
+let tmp: string;
+let vault: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-link-ratchet-"));
+ vault = join(tmp, "vault");
+ // notes/a.md carries five link rows with a target path plus one tag:
+ // [[notes/b.md]] β†’ resolves by exact path
+ // [[b]] β†’ resolves by unambiguous basename (ladder rung 3)
+ // [[gone]] β†’ unresolvable, no such document
+ // (notes/c.md) β†’ resolves by exact path
+ // (missing.md) β†’ unresolvable, no such document
+ // #topic β†’ tag, target_path IS NULL, never counted
+ writeMd(
+ vault,
+ "notes/a.md",
+ [
+ "# A",
+ "",
+ "See [[notes/b.md]] and [[b]] and [[gone]].",
+ "Also [c](notes/c.md) and [nope](missing.md).",
+ "Tag #topic",
+ "",
+ ].join("\n"),
+ );
+ writeMd(vault, "notes/b.md", "# B\n\nbody\n");
+ writeMd(vault, "notes/c.md", "# C\n\nbody\n");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function measured(m: LinkRatchetMeasurement): number {
+ if (!m.measurable) throw new Error(`expected a measurable result, got ${m.reason}`);
+ return m.dangling;
+}
+
+describe("unresolved-after-the-ladder definition", () => {
+ test("counts exactly the links the read-time ladder cannot resolve", async () => {
+ const m = await measureVault(vault);
+ expect(m.measurable).toBe(true);
+ expect(measured(m)).toBe(2);
+ if (m.measurable) {
+ expect(m.links).toBe(5);
+ expect(m.documents).toBe(3);
+ expect(m.definition).toBe(DANGLING_LINK_DEFINITION);
+ }
+ });
+
+ test("a basename wikilink a reader resolves does not raise the count", async () => {
+ const before = await measureVault(vault);
+ // `notes/c.md` exists and its basename is unambiguous, so `[[c]]` is
+ // a healthy edit - the exact case that made the SQL predicate fire on
+ // a vault written in Obsidian-style basename links.
+ writeMd(vault, "notes/d.md", "# D\n\nSee [[c]].\n");
+ const after = await measureVault(vault);
+ expect(measured(after)).toBe(measured(before));
+ });
+
+ test("an ambiguous basename stays counted - the ladder refuses to guess", async () => {
+ const before = await measureVault(vault);
+ // Two nested documents named `dup` make `[[dup]]` unresolvable at read
+ // time, so it is broken by the same definition the reader applies.
+ writeMd(vault, "one/dup.md", "# Dup one\n");
+ writeMd(vault, "two/dup.md", "# Dup two\n");
+ writeMd(vault, "notes/e.md", "# E\n\nSee [[dup]].\n");
+ const after = await measureVault(vault);
+ expect(measured(after)).toBe(measured(before) + 1);
+ });
+
+ test("the count agrees with the ladder the readers use", async () => {
+ // One link row per distinct edge, so the DISTINCT in
+ // `resolvedDocLinkPairs` cannot mask a disagreement: whatever that
+ // ladder resolves is exactly what this gate does not count.
+ const agree = join(tmp, "agree");
+ writeMd(agree, "x.md", "# X\n\nSee [[y]], [[z.md]] and [[gone]].\n");
+ writeMd(agree, "sub/y.md", "# Y\n");
+ writeMd(agree, "z.md", "# Z\n");
+ const config = ratchetSearchConfig(agree, join(tmp, "agree.sqlite"));
+ await indexVault(config, { force: true });
+ const store = await Store.open(config, { mode: "read" });
+ try {
+ const counts = store.linkResolutionCounts();
+ const resolvable = store.resolvedDocLinkPairs().length;
+ expect(counts.total).toBe(3);
+ expect(counts.total - counts.unresolved).toBe(resolvable);
+ expect(counts.unresolved).toBe(1);
+ } finally {
+ await store.close();
+ }
+ });
+
+ test("a vault with no links measures zero, distinctly from unmeasurable", async () => {
+ const clean = join(tmp, "clean");
+ writeMd(clean, "solo.md", "# Solo\n\nno links here\n");
+ const m = await measureVault(clean);
+ expect(m.measurable).toBe(true);
+ expect(measured(m)).toBe(0);
+ });
+
+ test("measuring never writes into the subject vault", async () => {
+ const before = Bun.file(join(vault, "notes/a.md")).size;
+ await measureVault(vault);
+ expect(Bun.file(join(vault, "notes/a.md")).size).toBe(before);
+ // The index run appends a metrics record into `<vault>/Brain/metrics`
+ // when it is pointed at the subject directly; the hermetic copy is
+ // what keeps the subject byte-identical.
+ expect(await Bun.file(join(vault, "Brain", "metrics", "index.jsonl")).exists()).toBe(false);
+ });
+});
+
+describe("determinism", () => {
+ test("two measurements over an unchanged vault produce the same count", async () => {
+ const first = await measureVault(vault);
+ const second = await measureVault(vault);
+ expect(measured(second)).toBe(measured(first));
+ expect(second).toEqual(first);
+ });
+});
+
+describe("full-resolution precondition", () => {
+ test("a count after an incremental run is unmeasurable, not clean", async () => {
+ const dbPath = join(tmp, "index.sqlite");
+ const config = ratchetSearchConfig(vault, dbPath);
+ await indexVault(config, { force: true });
+ expect(measured(await measureFromIndex(config))).toBe(2);
+
+ // An incremental pass leaves `last_indexed_at` ahead of
+ // `last_full_index_at`; the resolution state is then not provably
+ // complete, so the count must be refused.
+ await indexVault(config, { force: false });
+ const m = await measureFromIndex(config);
+ expect(m.measurable).toBe(false);
+ if (!m.measurable) expect(m.reason).toBe("partial-resolution");
+ });
+
+ test("a missing index is unmeasurable, not clean", async () => {
+ const config = ratchetSearchConfig(vault, join(tmp, "absent.sqlite"));
+ const m = await measureFromIndex(config);
+ expect(m.measurable).toBe(false);
+ if (!m.measurable) expect(m.reason).toBe("index-missing");
+ });
+});
+
+describe("ceiling file", () => {
+ const valid = {
+ schema_version: LINK_RATCHET_SCHEMA_VERSION,
+ definition: DANGLING_LINK_DEFINITION,
+ subjects: [{ path: "templates/brain-starter", dangling: 4 }],
+ };
+
+ test("round-trips through serialize/parse", () => {
+ const text = serializeCeiling(valid);
+ expect(parseCeiling(text)).toEqual(valid);
+ expect(serializeCeiling(parseCeiling(text))).toBe(text);
+ });
+
+ test("serialization is newline-terminated and sorted by subject path", () => {
+ const text = serializeCeiling({
+ ...valid,
+ subjects: [
+ { path: "b", dangling: 1 },
+ { path: "a", dangling: 2 },
+ ],
+ });
+ expect(text.endsWith("\n")).toBe(true);
+ expect(text.indexOf('"a"')).toBeLessThan(text.indexOf('"b"'));
+ });
+
+ test("a foreign schema_version is refused", () => {
+ const text = JSON.stringify({ ...valid, schema_version: 99 });
+ expect(() => parseCeiling(text)).toThrow(LinkRatchetError);
+ });
+
+ test("a ceiling recorded under a different definition is refused by name", () => {
+ const text = JSON.stringify({ ...valid, definition: "some-other-definition" });
+ let message = "";
+ try {
+ parseCeiling(text);
+ } catch (e) {
+ message = e instanceof Error ? e.message : String(e);
+ }
+ expect(message).toContain("definition");
+ expect(message).toContain(LINK_RATCHET_FIX_COMMAND);
+ });
+
+ test("a negative or fractional count is refused", () => {
+ expect(() =>
+ parseCeiling(JSON.stringify({ ...valid, subjects: [{ path: "x", dangling: -1 }] })),
+ ).toThrow(LinkRatchetError);
+ expect(() =>
+ parseCeiling(JSON.stringify({ ...valid, subjects: [{ path: "x", dangling: 1.5 }] })),
+ ).toThrow(LinkRatchetError);
+ });
+
+ test("an empty subject list is refused - a gate with nothing to measure is not a gate", () => {
+ expect(() => parseCeiling(JSON.stringify({ ...valid, subjects: [] }))).toThrow(
+ LinkRatchetError,
+ );
+ });
+
+ test("duplicate subject paths are refused", () => {
+ const text = JSON.stringify({
+ ...valid,
+ subjects: [
+ { path: "x", dangling: 1 },
+ { path: "x", dangling: 2 },
+ ],
+ });
+ expect(() => parseCeiling(text)).toThrow(LinkRatchetError);
+ });
+});
+
+describe("judgeSubject", () => {
+ const clean: LinkRatchetMeasurement = Object.freeze({
+ measurable: true,
+ definition: DANGLING_LINK_DEFINITION,
+ dangling: 3,
+ links: 5,
+ documents: 3,
+ });
+
+ test("equal is level, fewer is a drop, more is a rise", () => {
+ expect(judgeSubject("s", 3, clean).status).toBe("level");
+ expect(judgeSubject("s", 4, clean).status).toBe("drop");
+ expect(judgeSubject("s", 2, clean).status).toBe("rise");
+ });
+
+ test("an unmeasurable subject is its own status, never level", () => {
+ const v = judgeSubject("s", 0, {
+ measurable: false,
+ definition: DANGLING_LINK_DEFINITION,
+ reason: "index-missing",
+ detail: "no index",
+ });
+ expect(v.status).toBe("unmeasurable");
+ });
+});
+
+/**
+ * A present-but-empty subject used to measure `dangling: 0` and PASS:
+ * `walked === 0` and `documents === 0` satisfy both completeness guards,
+ * so a subject that was emptied, renamed, sparse-checked-out, or fully
+ * excluded by its own ignore rules produced a clean bill of health -
+ * and the write form then committed `0` as a permanent ceiling for a
+ * subject nobody measured.
+ */
+describe("an empty subject is unmeasurable, not clean", () => {
+ test("measureVault reports subject-empty rather than zero dangling", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "o2b-ratchet-empty-"));
+ try {
+ const measurement = await measureVault(dir);
+ expect(measurement.measurable).toBe(false);
+ if (!measurement.measurable) {
+ expect(measurement.reason).toBe("subject-empty");
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ test("a subject whose only markdown is excluded by its own rules is subject-empty", async () => {
+ const dir = mkdtempSync(join(tmpdir(), "o2b-ratchet-excluded-"));
+ try {
+ mkdirSync(join(dir, "Brain"), { recursive: true });
+ writeFileSync(
+ join(dir, "Brain", "_brain.yaml"),
+ "schema_version: 1\nvault:\n ignore_paths:\n - notes\n",
+ "utf8",
+ );
+ mkdirSync(join(dir, "notes"), { recursive: true });
+ writeFileSync(join(dir, "notes", "a.md"), "# A\n\n[[missing]]\n", "utf8");
+ const measurement = await measureVault(dir);
+ expect(measurement.measurable).toBe(false);
+ if (!measurement.measurable) {
+ expect(measurement.reason).toBe("subject-empty");
+ }
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/tests/core/vault.test.ts b/tests/core/vault.test.ts
index a9cdc78c..3bc9d929 100644
--- a/tests/core/vault.test.ts
+++ b/tests/core/vault.test.ts
@@ -1,12 +1,16 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { DEGRADATION_CODE, type DegradationNotice } from "../../src/core/integrity/degradation.ts";
import {
extractWikilinks,
listVaultPages,
parseFrontmatter,
+ parseFrontmatterText,
+ parseFrontmatterTextWithNotices,
+ parseFrontmatterWithNotices,
slugify,
writeFrontmatter,
} from "../../src/core/vault.ts";
@@ -114,6 +118,110 @@ describe("parseFrontmatter", () => {
});
});
+describe("parseFrontmatterWithNotices", () => {
+ test("a dash-prefixed non-list line yields exactly one notice naming the line", () => {
+ // `-foo` is pinned above as "simply ignored as a non-key/value line".
+ // Ignoring it is still the right control flow; what was missing is the
+ // trace. The parse result must stay identical to `parseFrontmatterText`.
+ const text = "---\nkey: value\n-foo\nother: end\n---\n\nBody.\n";
+ const [meta, body, notices] = parseFrontmatterTextWithNotices(text);
+ expect(meta["key"]).toBe("value");
+ expect(meta["other"]).toBe("end");
+ expect(meta["-foo"]).toBeUndefined();
+ expect(body).toBe("Body.");
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.code).toBe(DEGRADATION_CODE.frontmatterLineDropped);
+ expect(notices[0]!.detail).toContain("-foo");
+ });
+
+ test("supported grammar produces no notices at all", () => {
+ // The block-list regression from 426d06f8 is SUPPORTED grammar, so it
+ // must parse and stay silent. Blank lines and `#` comments are content
+ // the format expects to skip and are likewise not drops.
+ const text =
+ "---\nkind: brain-signal\n\n# a comment\ntags:\n - brain\n - brain/signal\n -\ninline: [x, y]\nsummary:\ntopic: foo\n---\n\nBody.\n";
+ const [meta, , notices] = parseFrontmatterTextWithNotices(text);
+ expect(meta["tags"]).toEqual(["brain", "brain/signal", ""]);
+ expect(meta["inline"]).toEqual(["x", "y"]);
+ expect(meta["summary"]).toBe("");
+ expect(notices).toEqual([]);
+ });
+
+ test("a note with no frontmatter block at all produces no notices", () => {
+ const [meta, body, notices] = parseFrontmatterTextWithNotices("Just a note.");
+ expect(meta).toEqual({});
+ expect(body).toBe("Just a note.");
+ expect(notices).toEqual([]);
+ });
+
+ test("an orphan block-list item outside any open key is reported", () => {
+ // A dash item with no preceding `key:` header has nowhere to land, so
+ // the scanner drops it. Today that is structurally silent.
+ const text = "---\n- orphan\ntitle: T\n---\n\nBody.\n";
+ const [meta, , notices] = parseFrontmatterTextWithNotices(text);
+ expect(meta["title"]).toBe("T");
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.code).toBe(DEGRADATION_CODE.frontmatterLineDropped);
+ expect(notices[0]!.detail).toContain("orphan");
+ });
+
+ test("every dropped line is reported, and the notice carries the caller's site and path", () => {
+ const text = "---\nkey: value\n-foo\n> folded\ntitle: T\n---\n\nBody.\n";
+ const [, , notices] = parseFrontmatterTextWithNotices(text, {
+ site: "unit-test",
+ path: "notes/a.md",
+ });
+ expect(notices).toHaveLength(2);
+ for (const n of notices) {
+ expect(n.site).toBe("unit-test");
+ expect(n.path).toBe("notes/a.md");
+ }
+ });
+
+ test("an unreadable file yields one frontmatter-unreadable notice naming the path", () => {
+ const missing = join(tmp, "nope", "gone.md");
+ const [meta, body, notices] = parseFrontmatterWithNotices(missing);
+ expect(meta).toEqual({});
+ expect(body).toBe("");
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.code).toBe(DEGRADATION_CODE.frontmatterUnreadable);
+ expect(notices[0]!.path).toBe(missing);
+ });
+
+ test("the path form attributes line drops to the file it read", () => {
+ const path = join(tmp, "note.md");
+ writeFileSync(path, "---\nkey: value\n-foo\n---\n\nBody.\n");
+ const [meta, , notices] = parseFrontmatterWithNotices(path, { site: "unit-test" });
+ expect(meta["key"]).toBe("value");
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.path).toBe(path);
+ expect(notices[0]!.site).toBe("unit-test");
+ });
+
+ test("the two-tuple functions delegate and stay byte-identical", () => {
+ const text = "---\nkey: value\n-foo\ntags:\n - a\n---\n\nBody.\n";
+ const [meta, body] = parseFrontmatterText(text);
+ const [metaN, bodyN] = parseFrontmatterTextWithNotices(text);
+ expect(meta).toEqual(metaN);
+ expect(body).toBe(bodyN);
+
+ const path = join(tmp, "note.md");
+ writeFileSync(path, text);
+ const [fileMeta, fileBody] = parseFrontmatter(path);
+ const [fileMetaN, fileBodyN, notices] = parseFrontmatterWithNotices(path);
+ expect(fileMeta).toEqual(fileMetaN);
+ expect(fileBody).toBe(fileBodyN);
+ expect(notices).toHaveLength(1);
+ });
+
+ test("a very long dropped line is truncated in the notice detail", () => {
+ const long = "x".repeat(500);
+ const [, , notices] = parseFrontmatterTextWithNotices(`---\n${long}\n---\n\nBody.\n`);
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.detail.length).toBeLessThan(300);
+ });
+});
+
describe("writeFrontmatter", () => {
test("roundtrip preserves title and body", () => {
const path = join(tmp, "note.md");
@@ -289,4 +397,43 @@ describe("listVaultPages", () => {
expect(pages.length).toBe(1);
expect(pages[0]!.title).toBe("page");
});
+
+ test("an opt-in notices sink collects dropped frontmatter lines per page", () => {
+ writeFileSync(join(tmp, "clean.md"), "---\ntitle: Alpha\ntags:\n - a\n---\n\nContent.");
+ writeFileSync(join(tmp, "odd.md"), "---\ntitle: Beta\n-foo\n---\n\nContent.");
+ const notices: DegradationNotice[] = [];
+ const pages = listVaultPages(tmp, { notices });
+ // Control flow unchanged: the odd page is still listed.
+ expect(pages.length).toBe(2);
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.code).toBe(DEGRADATION_CODE.frontmatterLineDropped);
+ expect(notices[0]!.path).toBe(join(tmp, "odd.md"));
+ });
+
+ test("the notices sink stays empty for a vault with supported grammar only", () => {
+ writeFileSync(join(tmp, "clean.md"), "---\ntitle: Alpha\ntags:\n - a\n---\n\nContent.");
+ writeFileSync(join(tmp, "plain.md"), "No frontmatter at all.");
+ const notices: DegradationNotice[] = [];
+ listVaultPages(tmp, { notices });
+ expect(notices).toEqual([]);
+ });
+
+ test("a directory the walker cannot read is reported instead of vanishing", () => {
+ writeFileSync(join(tmp, "page.md"), "Content.");
+ const locked = join(tmp, "locked");
+ mkdirSync(locked);
+ writeFileSync(join(locked, "inner.md"), "Inner.");
+ chmodSync(locked, 0o000);
+ const notices: DegradationNotice[] = [];
+ try {
+ const pages = listVaultPages(tmp, { notices });
+ // Same control flow as before: the unreadable subtree is skipped.
+ expect(pages.length).toBe(1);
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.code).toBe(DEGRADATION_CODE.vaultWalkEntrySkipped);
+ expect(notices[0]!.path).toBe(locked);
+ } finally {
+ chmodSync(locked, 0o755);
+ }
+ });
});
diff --git a/tests/hooks/active-inject-meter.test.ts b/tests/hooks/active-inject-meter.test.ts
new file mode 100644
index 00000000..ba197adc
--- /dev/null
+++ b/tests/hooks/active-inject-meter.test.ts
@@ -0,0 +1,223 @@
+/**
+ * Unit H - injection-size meter for the SessionStart eager layer.
+ *
+ * The hook is fail-soft by absolute contract, so every assertion here is
+ * paired with the invariant that matters more than the measurement: the
+ * emitted context and the exit code are what they were without the meter.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const HOOK = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "hooks",
+ "active-inject.ts",
+);
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-inject-meter-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-inject-meter-cfg-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+interface RunResult {
+ readonly stdout: string;
+ readonly exit: number;
+}
+
+async function runHook(payload: unknown, env: Record<string, string> = {}): Promise<RunResult> {
+ const inherited: Record<string, string> = {
+ PATH: process.env["PATH"] ?? "",
+ HOME: configHome,
+ OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "false",
+ VAULT_DIR: vault,
+ };
+ const proc = Bun.spawn(["bun", "run", HOOK], {
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ env: { ...inherited, ...env },
+ });
+ proc.stdin.write(JSON.stringify(payload));
+ await proc.stdin.end();
+ const [stdout] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ const exit = await proc.exited;
+ return { stdout, exit };
+}
+
+function writeActive(body: string): void {
+ writeFileSync(join(vault, "Brain", "active.md"), body, "utf8");
+}
+
+function writeLessons(body: string): void {
+ writeFileSync(join(vault, "Brain", "lessons.md"), body, "utf8");
+}
+
+interface ReceiptRecord {
+ readonly kind: string;
+ readonly payload: Record<string, unknown>;
+}
+
+function readReceipts(): ReceiptRecord[] {
+ const dir = join(vault, "Brain", "log", "continuity");
+ if (!existsSync(dir)) return [];
+ const out: ReceiptRecord[] = [];
+ for (const name of readdirSync(dir)) {
+ if (!name.endsWith(".jsonl")) continue;
+ for (const line of readFileSync(join(dir, name), "utf8").split("\n")) {
+ if (!line.trim()) continue;
+ out.push(JSON.parse(line) as ReceiptRecord);
+ }
+ }
+ return out;
+}
+
+function injectionReceipts(): ReceiptRecord[] {
+ return readReceipts().filter(
+ (r) => r.kind === "context_receipt" && r.payload["trigger"] === "session_inject",
+ );
+}
+
+const ACTIVE_BODY =
+ "---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (1)\n\n- `pref-foo` β€” Rule body\n";
+const LESSONS_BODY =
+ "---\nkind: brain-lessons\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Lessons\n\n## Avoid (1)\n\n- `de-2026-05-18-x` (score: -0.95) β€” the flaky retry loop\n";
+
+describe("active-inject injection meter", () => {
+ test("records one session_inject receipt per injection with per-source bytes and tokens", async () => {
+ writeActive(ACTIVE_BODY);
+ writeLessons(LESSONS_BODY);
+
+ const r = await runHook({ hook_event_name: "SessionStart" });
+ expect(r.exit).toBe(0);
+ const injected: string = JSON.parse(r.stdout).hookSpecificOutput.additionalContext;
+
+ const receipts = injectionReceipts();
+ expect(receipts.length).toBe(1);
+ const payload = receipts[0]!.payload;
+ const injection = payload["injection"] as Record<string, unknown>;
+ expect(injection["hook_event"]).toBe("SessionStart");
+ expect(injection["loader_source"]).toBe("fresh");
+ expect(injection["sources_measured"]).toBe(true);
+ expect(injection["total_bytes"]).toBe(Buffer.byteLength(injected, "utf8"));
+ expect(injection["total_tokens"]).toBe(Math.ceil(Buffer.byteLength(injected, "utf8") / 4));
+
+ const items = payload["items"] as ReadonlyArray<Record<string, unknown>>;
+ const byId = new Map(items.map((i) => [i["id"], i]));
+ expect([...byId.keys()].toSorted()).toEqual(["active-body", "lessons-body"]);
+ for (const item of items) {
+ const bytes = item["bytes"] as number;
+ expect(bytes).toBeGreaterThan(0);
+ expect(item["tokens"]).toBe(Math.ceil(bytes / 4));
+ }
+ });
+
+ test("scopes the meter to this hook and names the runtime-notice source", async () => {
+ writeActive(ACTIVE_BODY);
+ const r = await runHook(
+ { hook_event_name: "SessionStart" },
+ { OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "true" },
+ );
+ expect(r.exit).toBe(0);
+ const items = injectionReceipts()[0]!.payload["items"] as ReadonlyArray<
+ Record<string, unknown>
+ >;
+ expect(items.map((i) => i["id"]).toSorted()).toEqual(["active-body", "runtime-notices"]);
+ });
+
+ test("records the hook event name so a non-SessionStart injection is distinguishable", async () => {
+ writeActive(ACTIVE_BODY);
+ const r = await runHook({ hook_event_name: "UserPromptSubmit" });
+ expect(r.exit).toBe(0);
+ const injection = injectionReceipts()[0]!.payload["injection"] as Record<string, unknown>;
+ expect(injection["hook_event"]).toBe("UserPromptSubmit");
+ });
+
+ test("records the budget the sources were measured against", async () => {
+ writeFileSync(
+ join(vault, "Brain", "_brain.yaml"),
+ "schema_version: 1\nactive:\n inject_budget_chars: 500\n",
+ "utf8",
+ );
+ writeActive(ACTIVE_BODY);
+ writeLessons(LESSONS_BODY);
+ const r = await runHook({ hook_event_name: "SessionStart" });
+ expect(r.exit).toBe(0);
+ const budget = injectionReceipts()[0]!.payload["budget"] as Record<string, unknown>;
+ // Both budgeted sub-bodies are charged against the SAME configured
+ // ceiling, so the effective ceiling is a multiple of it. The record
+ // states both numbers rather than implying one.
+ expect(budget["inject_budget_chars"]).toBe(500);
+ expect(budget["budgeted_source_count"]).toBe(2);
+ });
+
+ test("a degraded-to-cache injection is distinguishable from a genuinely small one", async () => {
+ writeActive(ACTIVE_BODY);
+ const first = await runHook({ hook_event_name: "SessionStart" });
+ expect(first.exit).toBe(0);
+ const fresh: string = JSON.parse(first.stdout).hookSpecificOutput.additionalContext;
+
+ // A directory where active.md was makes the assembly throw, so the
+ // fail-open loader degrades to the last-good cache.
+ rmSync(join(vault, "Brain", "active.md"));
+ mkdirSync(join(vault, "Brain", "active.md"));
+
+ const second = await runHook({ hook_event_name: "SessionStart" });
+ expect(second.exit).toBe(0);
+ const cached: string = JSON.parse(second.stdout).hookSpecificOutput.additionalContext;
+ expect(cached).toBe(fresh);
+
+ const receipts = injectionReceipts();
+ expect(receipts.length).toBe(2);
+ const injection = receipts[1]!.payload["injection"] as Record<string, unknown>;
+ expect(injection["loader_source"]).toBe("cached");
+ // Nothing was assembled, so there is no per-source attribution to
+ // report - and reporting zeros would be a finding that never happened.
+ expect(injection["sources_measured"]).toBe(false);
+ expect(receipts[1]!.payload["items"]).toEqual([]);
+ expect(injection["total_bytes"]).toBe(Buffer.byteLength(cached, "utf8"));
+ });
+
+ test("a throwing receipt sink changes neither the emitted context nor the exit code", async () => {
+ writeActive(ACTIVE_BODY);
+ writeLessons(LESSONS_BODY);
+
+ const healthy = await runHook({ hook_event_name: "SessionStart" });
+ expect(healthy.exit).toBe(0);
+ expect(injectionReceipts().length).toBe(1);
+
+ // A regular file where the continuity store expects its directory
+ // makes every append throw (mkdirSync recursive raises EEXIST).
+ rmSync(join(vault, "Brain", "log", "continuity"), { recursive: true, force: true });
+ writeFileSync(join(vault, "Brain", "log", "continuity"), "not a directory", "utf8");
+
+ const broken = await runHook({ hook_event_name: "SessionStart" });
+ expect(broken.exit).toBe(0);
+ expect(broken.stdout).toBe(healthy.stdout);
+ });
+});
diff --git a/tests/mcp/agent-scope-matrix.test.ts b/tests/mcp/agent-scope-matrix.test.ts
new file mode 100644
index 00000000..017602d6
--- /dev/null
+++ b/tests/mcp/agent-scope-matrix.test.ts
@@ -0,0 +1,613 @@
+/**
+ * Owner-scope isolation regression matrix (context-integrity-gates,
+ * Unit A / Task 8).
+ *
+ * Before this wave, `isOwnerVisible` β€” the vault's ONLY isolation rule β€”
+ * had two callers, and every other content-returning MCP surface
+ * bypassed it. The defect was not any single missing filter; it was that
+ * nothing enumerated the surfaces, so each new one silently opted out.
+ *
+ * This file is that enumeration. Every tool in the table is classified
+ * exactly once, and the three buckets are asserted to partition the tool
+ * table exactly β€” in BOTH directions. A new tool therefore fails this
+ * 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.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { chmodSync, 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 { regenerateActive } from "../../src/core/brain/active.ts";
+import { writePreference } from "../../src/core/brain/preference.ts";
+import { writeSignal } from "../../src/core/brain/signal.ts";
+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.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";
+const QUERY = "lattice widgets";
+/** Probe path whose derived query terms appear verbatim in every note. */
+const PROBE = "lattice.md";
+const PROBE_TERMS = `${PROBE} lattice`;
+
+/** How a surface learns which agent is asking. */
+const SCOPE_SOURCE = Object.freeze({
+ /** An explicit `agent_scope` input argument. */
+ argument: "argument",
+ /** `ServerContext.agentName`, for a surface that takes no arguments. */
+ serverIdentity: "server-identity",
+} as const);
+
+type ScopeSource = (typeof SCOPE_SOURCE)[keyof typeof SCOPE_SOURCE];
+
+interface ScopedSurface {
+ readonly name: string;
+ readonly source: ScopeSource;
+ /**
+ * True when isolation is behind `integrity.owner_scope_delivery`.
+ * Preference-backed surfaces are gated (their scope may be defaulted
+ * from the server identity, which would narrow a vault that never
+ * opted in). Search-backed surfaces are not: their scope only ever
+ * arrives as an explicit per-call argument, so honouring it cannot
+ * narrow anything the caller did not ask to narrow.
+ */
+ readonly gated: boolean;
+}
+
+/** Content-returning tools that consult the ownership rule. */
+const SCOPED_SURFACES: ReadonlyArray<ScopedSurface> = [
+ { name: "brain_context", source: SCOPE_SOURCE.serverIdentity, gated: true },
+ { name: "brain_context_pack", source: SCOPE_SOURCE.argument, gated: true },
+ { name: "brain_pre_compress_pack", source: SCOPE_SOURCE.argument, gated: true },
+ { name: "brain_anticipatory_context", source: SCOPE_SOURCE.argument, gated: true },
+ { name: "brain_brief", source: SCOPE_SOURCE.argument, gated: true },
+ { name: "brain_retrieval_plan", source: SCOPE_SOURCE.argument, gated: true },
+ { name: "brain_query", source: SCOPE_SOURCE.argument, gated: false },
+ { name: "brain_search", source: SCOPE_SOURCE.argument, gated: false },
+ { name: "brain_search_expand", source: SCOPE_SOURCE.argument, gated: false },
+ { name: "brain_file_context", source: SCOPE_SOURCE.argument, gated: false },
+ { name: "brain_deep_synthesis", source: SCOPE_SOURCE.argument, gated: false },
+ { name: "brain_search_by_source", source: SCOPE_SOURCE.argument, gated: false },
+ { name: "second_brain_query", source: SCOPE_SOURCE.argument, gated: false },
+ { name: "brain_agent_query", source: SCOPE_SOURCE.argument, gated: false },
+];
+
+/**
+ * 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" },
+ {
+ name: "brain_note_history",
+ reason:
+ "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.",
+ },
+ {
+ name: "brain_artifact_get",
+ reason:
+ "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.",
+ },
+ {
+ name: "brain_pre_compact_extract",
+ reason: "extracts from caller-supplied text, not the vault",
+ },
+ { name: "brain_recall_gate", reason: "verdict over a caller-supplied question, no bodies" },
+];
+
+/** 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_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_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",
+];
+
+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!;
+};
+
+let vault: string;
+let configHome: string;
+let ctx: ServerContext;
+
+beforeEach(async () => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-scope-matrix-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-scope-matrix-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 });
+ }
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "notes", "owned-a.md"),
+ `---\nowner: ${OWNER_A}\n---\n\n${QUERY} ${PROBE_TERMS} owned by a\n`,
+ );
+ writeFileSync(join(vault, "notes", "shared.md"), `# Shared\n\n${QUERY} ${PROBE_TERMS} shared\n`);
+ makePref("shared");
+ makePref("owned-by-a", OWNER_A);
+ ctx = { vault, configPath, repoRoot: null, agentName: OWNER_B };
+ await indexVault(resolveSearchConfig({ vault, configPath }), {});
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function setGate(mode: string | null): void {
+ const body = mode === null ? "" : `integrity:\n owner_scope_delivery: ${mode}\n`;
+ writeFileSync(brainConfigPath(vault), `schema_version: 1\n${body}`);
+}
+
+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`. Argument-scoped surfaces read the scope
+ * from `args`; `brain_context` takes no arguments and can only read the
+ * server identity, so the identity is varied alongside the argument and
+ * each surface picks up whichever source it declares.
+ */
+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));
+}
+
+/** Vault-relative paths a listing surface returned. */
+function pagePaths(result: { pages: Array<{ path: string }> }): string[] {
+ return result.pages.map((p) => p.path);
+}
+
+/** Entry ids a source-trace surface returned. */
+function entryIds(result: { entries: Array<{ id: string }> }): string[] {
+ return result.entries.map((e) => e.id);
+}
+
+/** Contribution ids a provenance surface returned, sorted. */
+function contributionIds(result: { contributions: Array<{ id: string }> }): string[] {
+ return result.contributions.map((c) => c.id).toSorted();
+}
+
+// ----- 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,
+ ];
+ expect(new Set(classified).size).toBe(classified.length);
+
+ const actual = TOOLS.map((t) => t.name).toSorted();
+ // Both directions: a NEW tool fails until it is classified, and a
+ // REMOVED tool fails until its entry is deleted.
+ expect(classified.toSorted()).toEqual(actual);
+});
+
+test("the tool count is unchanged: an argument was added, never a tool", () => {
+ expect(TOOLS.length).toBe(108);
+});
+
+test("every argument-scoped surface declares agent_scope in its input schema", () => {
+ for (const surface of SCOPED_SURFACES) {
+ const schema = tool(surface.name).inputSchema as {
+ properties?: Record<string, unknown>;
+ };
+ const declared = Object.keys(schema.properties ?? {});
+ if (surface.source === SCOPE_SOURCE.argument) {
+ expect(declared, `${surface.name} must accept agent_scope`).toContain("agent_scope");
+ } else {
+ expect(declared, `${surface.name} takes no arguments`).toEqual([]);
+ }
+ }
+});
+
+test("brain_context keeps its no-argument contract and reads the server identity", () => {
+ const schema = tool("brain_context").inputSchema as Record<string, unknown>;
+ expect(schema["additionalProperties"]).toBe(false);
+ expect(Object.keys((schema["properties"] ?? {}) as Record<string, unknown>)).toEqual([]);
+});
+
+// ----- gated preference-backed surfaces -------------------------------------
+
+const GATED_CALLS: ReadonlyArray<{
+ readonly name: string;
+ readonly args: (scope: string | null) => Record<string, unknown>;
+}> = [
+ { name: "brain_context", args: () => ({}) },
+ {
+ name: "brain_context_pack",
+ args: (s) => ({ max_tokens: 4000, ...(s === null ? {} : { agent_scope: s }) }),
+ },
+ {
+ name: "brain_pre_compress_pack",
+ args: (s) => ({ top_k: 10, ...(s === null ? {} : { agent_scope: s }) }),
+ },
+ {
+ name: "brain_brief",
+ args: (s) => ({ view: "morning", ...(s === null ? {} : { agent_scope: s }) }),
+ },
+ {
+ name: "brain_anticipatory_context",
+ args: (s) => ({ session_id: "sess-1", ...(s === null ? {} : { agent_scope: s }) }),
+ },
+];
+
+for (const surface of GATED_CALLS) {
+ test(`${surface.name}: gate off delivers every owner's memory`, async () => {
+ setGate(GATE_MODE.off);
+ expect(await call(surface.name, surface.args(OWNER_B), OWNER_B)).toContain("owned-by-a");
+ });
+
+ test(`${surface.name}: gate fail withholds another owner's memory`, async () => {
+ setGate(GATE_MODE.fail);
+ const out = await call(surface.name, surface.args(OWNER_B), OWNER_B);
+ expect(out).not.toContain("owned-by-a");
+ expect(out).toContain("shared");
+ });
+
+ test(`${surface.name}: gate fail keeps the owner's own memory`, async () => {
+ setGate(GATE_MODE.fail);
+ expect(await call(surface.name, surface.args(OWNER_A), OWNER_A)).toContain("owned-by-a");
+ });
+}
+
+/**
+ * A3: a per-request visibility filter must never drive a shared write.
+ *
+ * `brain_context` used to reach `regenerateActive(vault, { agentScope })`,
+ * and `regenerateActive` WRITES `Brain/active.md`. Under `fail` a call from
+ * agent-b therefore rewrote the shared file without agent-a's memories -
+ * and `hooks/active-inject.ts` injects that same file into every agent's
+ * SessionStart, while `resources.ts` regenerates it unscoped. The file
+ * thrashed and an agent could lose its own memories from session start.
+ */
+test("brain_context scopes what it returns without narrowing active.md", async () => {
+ setGate(GATE_MODE.fail);
+ regenerateActive(vault);
+ const activePath = brainActivePath(vault);
+ const before = readFileSync(activePath, "utf8");
+ expect(before).toContain("owned-by-a");
+
+ const out = await call("brain_context", {}, OWNER_B);
+ expect(out).not.toContain("owned-by-a");
+ expect(out).toContain("shared");
+
+ // The SHARED file is untouched: same bytes, still carrying every owner.
+ expect(readFileSync(activePath, "utf8")).toBe(before);
+});
+
+test("brain_context creates active.md unscoped on a vault that has none", async () => {
+ setGate(GATE_MODE.fail);
+ const activePath = brainActivePath(vault);
+ rmSync(activePath, { force: true });
+
+ await call("brain_context", {}, OWNER_B);
+ expect(readFileSync(activePath, "utf8")).toContain("owned-by-a");
+});
+
+/**
+ * A6: `agent_scope` is declared once for the whole `brain_brief` tool, but
+ * only two of its seven views thread it. The other five returned
+ * preference ids (`weekly.retired[].prefId`, the operator dashboard's
+ * ranked actions) to a caller that believed it was scoped. An argument a
+ * tool accepts and silently ignores is exactly the failure mode this wave
+ * exists to remove, so those views refuse it.
+ */
+test("brain_brief refuses agent_scope on the views that cannot honour it", async () => {
+ const views = ["daily", "weekly", "monthly", "operator", "today"];
+ const outcomes = await Promise.all(
+ views.map((view) =>
+ call("brain_brief", { view, agent_scope: OWNER_B }).then(
+ () => null,
+ (e: unknown) => (e as Error).message,
+ ),
+ ),
+ );
+ for (const [i, message] of outcomes.entries()) {
+ expect(message, `view=${views[i]}`).toContain(
+ `brain_brief view=${views[i]} cannot honour 'agent_scope'`,
+ );
+ }
+});
+
+test("brain_brief still serves those views without the argument", async () => {
+ const served = await Promise.all(
+ ["daily", "weekly", "monthly", "today"].map((view) => call("brain_brief", { view })),
+ );
+ for (const out of served) expect(typeof out).toBe("string");
+});
+
+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 }),
+ );
+ const asB = JSON.parse(
+ await call("brain_retrieval_plan", { question: QUERY, agent_scope: OWNER_B }),
+ );
+ expect(asA.allocation.item_count).toBeGreaterThan(asB.allocation.item_count);
+});
+
+// ----- ungated search-backed surfaces ---------------------------------------
+
+test("brain_search_expand refuses another owner's chunk as if it were absent", async () => {
+ const config = resolveSearchConfig({ vault, configPath: ctx.configPath ?? undefined });
+ const hit = (await search(config, { query: QUERY, limit: 20 })).results.find(
+ (r) => r.path === "notes/owned-a.md",
+ );
+ expect(hit).toBeDefined();
+
+ expect(await call("brain_search_expand", { chunk_id: hit!.chunkId })).toContain(
+ "notes/owned-a.md",
+ );
+ await expect(
+ call("brain_search_expand", { chunk_id: hit!.chunkId, agent_scope: OWNER_B }),
+ ).rejects.toThrow(`chunk not found: ${hit!.chunkId}`);
+});
+
+test("second_brain_query excludes another owner's pages from the listing", async () => {
+ const unscoped = JSON.parse(await call("second_brain_query", { limit: 500 }));
+ const scoped = JSON.parse(await call("second_brain_query", { limit: 500, agent_scope: OWNER_B }));
+ expect(pagePaths(unscoped)).toContain("notes/owned-a.md");
+ expect(pagePaths(unscoped)).toContain("Brain/preferences/pref-owned-by-a.md");
+ expect(pagePaths(scoped)).not.toContain("notes/owned-a.md");
+ expect(pagePaths(scoped)).not.toContain("Brain/preferences/pref-owned-by-a.md");
+ // The shared pages survive, and the reported total is the visible one -
+ // a count that still included the hidden pages would leak their number.
+ expect(pagePaths(scoped)).toContain("notes/shared.md");
+ expect(scoped.total_pages).toBe(scoped.pages.length);
+ expect(scoped.total_pages).toBeLessThan(unscoped.total_pages);
+});
+
+/**
+ * A5/A8: the listing must fail CLOSED on an unreadable page, matching
+ * `brain_search_by_source` and the ranked search path. Empty frontmatter
+ * from a failed read is byte-indistinguishable from a genuinely ownerless
+ * page, so without the walk's diagnostic sink an owner-tagged page becomes
+ * shared the moment its file stops being readable.
+ */
+test("second_brain_query hides a page it cannot read from a scoped caller", async () => {
+ const target = join(vault, "notes", "owned-a.md");
+ chmodSync(target, 0o000);
+ try {
+ const scoped = JSON.parse(
+ await call("second_brain_query", { limit: 500, agent_scope: OWNER_B }),
+ );
+ expect(pagePaths(scoped)).not.toContain("notes/owned-a.md");
+ expect(pagePaths(scoped)).toContain("notes/shared.md");
+ } finally {
+ chmodSync(target, 0o644);
+ }
+});
+
+test("brain_search_by_source excludes another owner's derived pages", async () => {
+ const sourceFile = "sources/paper.md";
+ const derived = join(vault, "Brain", "sources");
+ mkdirSync(derived, { recursive: true });
+ writeFileSync(
+ join(derived, "src-owned-a.md"),
+ `---\nid: src-owned-a\nowner: ${OWNER_A}\nsource_path: ${sourceFile}\n---\n\nderived for a\n`,
+ );
+ writeFileSync(
+ join(derived, "src-shared.md"),
+ `---\nid: src-shared\nsource_path: ${sourceFile}\n---\n\nderived for everyone\n`,
+ );
+
+ const unscoped = JSON.parse(await call("brain_search_by_source", { source_file: sourceFile }));
+ const scoped = JSON.parse(
+ await call("brain_search_by_source", { source_file: sourceFile, agent_scope: OWNER_B }),
+ );
+ expect(entryIds(unscoped).toSorted()).toEqual(["src-owned-a", "src-shared"]);
+ expect(entryIds(scoped)).toEqual(["src-shared"]);
+ expect(scoped.total).toBe(1);
+});
+
+test("brain_agent_query excludes another owner's preference contributions", async () => {
+ // A preference contribution only surfaces once its evidence signals
+ // exist, because the contribution's agents are read from them.
+ for (const slug of ["shared", "owned-by-a"]) {
+ writeSignal(vault, {
+ topic: slug,
+ signal: "positive",
+ agent: "agent-x",
+ principle: `principle for ${slug}`,
+ created_at: "2026-05-01T00:00:00Z",
+ date: "2026-05-01",
+ slug,
+ });
+ }
+
+ const unscoped = JSON.parse(await call("brain_agent_query", { kind: "preference" }));
+ const scoped = JSON.parse(
+ await call("brain_agent_query", { kind: "preference", agent_scope: OWNER_B }),
+ );
+ expect(contributionIds(unscoped)).toEqual(["pref-owned-by-a", "pref-shared"]);
+ expect(contributionIds(scoped)).toEqual(["pref-shared"]);
+ expect(scoped.total_matched).toBe(1);
+});
+
+/**
+ * A5: the roster must be folded from the SAME filtered set the
+ * contributions are. Built independently of the owner filter it reported
+ * a correct `total_matched` beside an `available_agents` entry naming the
+ * withheld preference's topic verbatim and counting it - which is the
+ * existence leak the boundary exists to prevent.
+ *
+ * The evidence signal carries a DIFFERENT topic from the preference it
+ * evidences, so the preference's topic can only reach the roster through
+ * the preference contribution itself.
+ */
+test("brain_agent_query's roster names only what the caller may see", async () => {
+ writeSignal(vault, {
+ topic: "neutral-topic",
+ signal: "positive",
+ agent: "agent-y",
+ principle: "principle for the neutral signal",
+ created_at: "2026-05-01T00:00:00Z",
+ date: "2026-05-01",
+ slug: "secret-pref",
+ });
+ makePref("secret-pref", OWNER_A);
+
+ const rosterFor = (result: {
+ available_agents: Array<{ id: string; topics: string[]; contribution_count: number }>;
+ }): { topics: string[]; contribution_count: number } => {
+ const entry = result.available_agents.find((a) => a.id === "agent-y");
+ expect(entry).toBeDefined();
+ return entry!;
+ };
+
+ const unscoped = rosterFor(JSON.parse(await call("brain_agent_query", {})));
+ expect(unscoped.topics).toEqual(["neutral-topic", "secret-pref"]);
+ expect(unscoped.contribution_count).toBe(2);
+
+ const scoped = rosterFor(JSON.parse(await call("brain_agent_query", { agent_scope: OWNER_B })));
+ expect(scoped.topics).toEqual(["neutral-topic"]);
+ expect(scoped.contribution_count).toBe(1);
+});
+
+test("brain_file_context and brain_deep_synthesis exclude another owner's page", async () => {
+ const cases = [
+ { name: "brain_file_context", args: { file_path: join(vault, "notes", PROBE), min_bytes: 0 } },
+ { name: "brain_deep_synthesis", args: { topic: QUERY } },
+ ];
+ // Both calls per case are issued together: they share no state, and a
+ // sequential await here is only a slower way to reach the same result.
+ const outcomes = await Promise.all(
+ cases.map(async ({ name, args }) => ({
+ name,
+ unscoped: await call(name, args),
+ scoped: await call(name, { ...args, agent_scope: OWNER_B }),
+ })),
+ );
+ for (const { name, unscoped, scoped } of outcomes) {
+ expect(unscoped, `${name} unscoped`).toContain("notes/owned-a.md");
+ expect(scoped, `${name} scoped`).not.toContain("notes/owned-a.md");
+ expect(scoped, `${name} scoped`).toContain("notes/shared.md");
+ }
+});
diff --git a/tests/mcp/brain-retrieval-plan.test.ts b/tests/mcp/brain-retrieval-plan.test.ts
index dc65ad68..33b6dc60 100644
--- a/tests/mcp/brain-retrieval-plan.test.ts
+++ b/tests/mcp/brain-retrieval-plan.test.ts
@@ -97,7 +97,7 @@ describe("brain_retrieval_plan", () => {
expect(plan["marginal_stop"]).toBeDefined();
});
- test("exposes no mutating parameters (only question + token_budget)", async () => {
+ test("exposes no mutating parameters (question, token_budget, agent_scope)", async () => {
const server = new MCPServer({ vault });
await initialize(server);
const r = (await server.handleRequest({
@@ -110,7 +110,11 @@ describe("brain_retrieval_plan", () => {
};
const tool = r.result.tools.find((t) => t.name === "brain_retrieval_plan")!;
const props = (tool.inputSchema as { properties: Record<string, unknown> }).properties;
- expect(Object.keys(props).toSorted()).toEqual(["question", "token_budget"]);
+ // `agent_scope` (context-integrity-gates, Unit A) is a READ filter:
+ // it narrows the pack the advice is computed over, and the surface
+ // stays read-only. The pin exists to catch a mutating parameter
+ // being added, not to freeze the read parameters.
+ expect(Object.keys(props).toSorted()).toEqual(["agent_scope", "question", "token_budget"]);
expect((tool.inputSchema as { additionalProperties?: boolean }).additionalProperties).toBe(
false,
);
diff --git a/tests/mcp/brain-trust-mcp-fields.test.ts b/tests/mcp/brain-trust-mcp-fields.test.ts
index 680999ef..813a20a8 100644
--- a/tests/mcp/brain-trust-mcp-fields.test.ts
+++ b/tests/mcp/brain-trust-mcp-fields.test.ts
@@ -13,6 +13,7 @@ import { join } from "node:path";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { resetVaultIdentityPins, writeVaultIdentity } from "../../src/core/brain/vault-identity.ts";
let tmp: string;
let vault: string;
@@ -36,9 +37,11 @@ beforeEach(() => {
}
process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);
+ resetVaultIdentityPins();
});
afterEach(() => {
+ resetVaultIdentityPins();
rmSync(tmp, { recursive: true, force: true });
rmSync(configHome, { recursive: true, force: true });
for (const [k, v] of Object.entries(savedEnv)) {
@@ -98,6 +101,51 @@ describe("brain_doctor MCP wrapper - trust fields", () => {
expect(out["instruction_file_warnings"]).toEqual([]);
});
+ test("the uncertain stream reaches an MCP caller, not only the terminal", async () => {
+ // The whole degradation stream - frontmatter lines the scanner
+ // dropped, lineage-ledger findings, an unmarked vault root, stale
+ // writer locks - was rendered by the CLI alone. An agent driving the
+ // doctor over MCP could not see any of it.
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callTool(server, "brain_doctor", {});
+ const uncertain = out["uncertain"] as Array<{
+ code: string;
+ path?: string;
+ message: string;
+ }>;
+ expect(Array.isArray(uncertain)).toBe(true);
+ // This fixture builds the Brain tree by hand, so it carries no
+ // identity marker - the exact shape a mis-resolved root takes.
+ const marker = uncertain.find((u) => u.code === "vault-marker-absent");
+ expect(marker).toBeDefined();
+ expect(marker!.message.length).toBeGreaterThan(0);
+ });
+
+ test("a frontmatter drop reaches brain_doctor under its own code", async () => {
+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });
+ writeFileSync(
+ join(vault, "Brain", "notes", "odd.md"),
+ "---\ntitle: Odd\ntopic: odd\n-foo\n---\n\nBody.\n",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callTool(server, "brain_doctor", {});
+ const uncertain = out["uncertain"] as Array<{ code: string; path?: string }>;
+ const hit = uncertain.find((u) => u.code === "frontmatter-line-dropped");
+ expect(hit).toBeDefined();
+ // Paths are vault-relative on the wire, exactly like errors/warnings.
+ expect(hit!.path).toBe("Brain/notes/odd.md");
+ });
+
+ test("a vault with nothing uncertain omits the key entirely", async () => {
+ writeVaultIdentity(vault);
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callTool(server, "brain_doctor", {});
+ expect(Object.hasOwn(out, "uncertain")).toBe(false);
+ });
+
test("long CLAUDE.md surfaces instruction_file_warnings via brain_doctor", async () => {
writeFileSync(join(vault, "CLAUDE.md"), "line\n".repeat(300));
const server = new MCPServer({ vault, configPath });
diff --git a/tests/mcp/context-receipts-tool.test.ts b/tests/mcp/context-receipts-tool.test.ts
index dfea2652..e34cda76 100644
--- a/tests/mcp/context-receipts-tool.test.ts
+++ b/tests/mcp/context-receipts-tool.test.ts
@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { emitContextReceipt } from "../../src/core/brain/context-receipts.ts";
+import { emitObservedUse } from "../../src/core/brain/observed-use.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
@@ -118,4 +119,124 @@ describe("brain_context_receipts tool", () => {
expect(show["id"]).toBe(receipt.id);
expect((show["payload"] as Record<string, unknown>)["session_id"]).toBe("session-mcp");
});
+
+ test("summary folds a session and joins the observed-use verdicts", async () => {
+ for (const [createdAt, tokens] of [
+ ["2026-05-21T14:00:00.000Z", 10],
+ ["2026-05-21T14:05:00.000Z", 14],
+ ] as const) {
+ emitContextReceipt(vault, {
+ options: {
+ host: "mcp-test",
+ trigger: "context_pack",
+ createdAt,
+ sessionId: "session-fold",
+ },
+ finalText: "pack",
+ items: [{ id: "pref-alpha", path: "Brain/preferences/pref-alpha.md", tokens }],
+ });
+ }
+ emitObservedUse(vault, {
+ createdAt: "2026-05-21T14:10:00.000Z",
+ host: "mcp-test",
+ sessionId: "session-fold",
+ entries: [{ id: "pref-alpha", path: "Brain/preferences/pref-alpha.md", verdict: "USED" }],
+ });
+
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const summary = await callReceipts(server, {
+ operation: "summary",
+ session_id: "session-fold",
+ });
+ expect(summary["recorded"]).toBe(true);
+ expect(summary["receipt_count"]).toBe(2);
+ expect(summary["distinct_items"]).toBe(1);
+ expect(summary["item_total"]).toBe(2);
+ expect(summary["truncated"]).toBe(false);
+ const items = summary["items"] as Array<Record<string, unknown>>;
+ expect(items[0]).toMatchObject({
+ id: "pref-alpha",
+ injections: 2,
+ tokens: 24,
+ observed: { used: 1, ignored: 0, contradicted: 0, total: 1 },
+ });
+ });
+
+ test("summary over a vault with no receipts says so instead of returning zeros", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const summary = await callReceipts(server, { operation: "summary" });
+ expect(summary["recorded"]).toBe(false);
+ expect(summary["receipt_count"]).toBeUndefined();
+ expect(summary["items"]).toBeUndefined();
+ expect(typeof summary["note"]).toBe("string");
+ });
+
+ test("a malformed window bound is INVALID_PARAMS, never an empty window", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ emitContextReceipt(vault, {
+ options: {
+ host: "unit",
+ trigger: "context_pack",
+ createdAt: "2026-06-01T10:00:00Z",
+ sessionId: "s1",
+ },
+ items: [{ id: "pref-a", tokens: 1 }],
+ finalText: "x",
+ });
+ const summarize = async (
+ args: Record<string, unknown>,
+ ): Promise<{ error?: { code: number; message: string } }> =>
+ (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 12,
+ method: "tools/call",
+ params: { name: "brain_context_receipts", arguments: { operation: "summary", ...args } },
+ })) as { error?: { code: number; message: string } };
+
+ // Before this, "yesterday" sorted after every stored timestamp and
+ // the tool answered `recorded: false, note: "no receipts recorded
+ // for this filter"` - a finding about the vault, for a typo.
+ const [word, offset] = await Promise.all([
+ summarize({ since: "yesterday" }),
+ summarize({ until: "2026-06-01T10:00:00+03:00" }),
+ ]);
+ expect(word.error?.message).toContain("canonical UTC");
+ expect(offset.error?.message).toContain("canonical UTC");
+ });
+
+ test("summary counts the receipts that carried nothing", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ emitContextReceipt(vault, {
+ options: {
+ host: "hook",
+ trigger: "session_inject",
+ createdAt: "2026-06-01T10:00:00Z",
+ sessionId: "s2",
+ },
+ items: [],
+ finalText: "degraded-to-cache injection",
+ });
+ const summary = await callReceipts(server, { operation: "summary", session_id: "s2" });
+ expect(summary["receipt_count"]).toBe(1);
+ expect(summary["item_total"]).toBe(0);
+ expect(summary["empty_receipts"]).toBe(1);
+ expect(summary["malformed_receipts"]).toBe(0);
+ });
+
+ test("an unknown operation names every branch", async () => {
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const response = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 11,
+ method: "tools/call",
+ params: { name: "brain_context_receipts", arguments: { operation: "nope" } },
+ })) as { error?: { message: string }; result?: { content: ReadonlyArray<{ text: string }> } };
+ const text = response.error?.message ?? response.result?.content[0]?.text ?? "";
+ expect(text).toContain("summary");
+ });
});
diff --git a/tests/mcp/embedding-abi-visibility.test.ts b/tests/mcp/embedding-abi-visibility.test.ts
new file mode 100644
index 00000000..de1e8d6e
--- /dev/null
+++ b/tests/mcp/embedding-abi-visibility.test.ts
@@ -0,0 +1,223 @@
+/**
+ * Embedding-ABI drift on the MCP surface (context-integrity-gates,
+ * Unit E).
+ *
+ * The gated comparison landed on the read-mode open, but every consumer
+ * of its result was a CLI one: `o2b search status` printed a warning and
+ * `o2b search check` reported the structured mismatch. The MCP surface -
+ * the primary consumer of this product - saw neither.
+ * `buildSearchStatusBlock` destructured the whole `warnings` array away,
+ * and the query path had no ABI branch at all, so an agent driving the
+ * vault over MCP was served semantic results from a mismatched vector
+ * table with nothing to observe at any setting short of `fail`.
+ *
+ * These tests pin both halves of the fix: the diagnostic
+ * (`second_brain_status`) and the degraded read itself (`brain_search`).
+ *
+ * Vector assertions are skipped where sqlite-vec cannot be loaded,
+ * following the repository-wide `sqliteVecLoadable()` pattern; the
+ * embedding provider is a loopback stub, never a real endpoint.
+ */
+
+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 { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { indexVault } from "../../src/core/search/indexer.ts";
+import { resolveSearchConfig } from "../../src/core/search/index.ts";
+import {
+ EMBEDDING_ABI_FIX_COMMAND,
+ EMBEDDING_DIMENSION_STATE_KEY,
+ EMBEDDING_VEC_VERSION_STATE_KEY,
+ Store,
+} from "../../src/core/search/store.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { startFakeHttp, type FakeHttp } from "../helpers/fake-http.ts";
+import { sqliteVecLoadable } from "../helpers/sqlite-vec.ts";
+
+const QUERY = "lattice widgets";
+
+let tmp: string;
+let vault: string;
+let configPath: string;
+let server: FakeHttp;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(async () => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-abi-"));
+ vault = join(tmp, "vault");
+ mkdirSync(vault, { recursive: true });
+ configPath = join(tmp, "config.yaml");
+ for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {
+ savedEnv[k] = process.env[k];
+ delete process.env[k];
+ }
+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
+ server = await startFakeHttp();
+ atomicWriteFileSync(
+ configPath,
+ [
+ `vault: ${vault}`,
+ "agent_name: claude",
+ "search_semantic_enabled: true",
+ "embedding_provider: openai-compat",
+ `embedding_base_url: ${server.url}`,
+ "embedding_model: fake-model",
+ "embedding_api_key: test-key",
+ "embedding_dimension: 4",
+ "",
+ ].join("\n"),
+ );
+});
+
+afterEach(async () => {
+ await server.close();
+ rmSync(tmp, { recursive: true, force: true });
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+});
+
+function writeMd(rel: string, content: string): void {
+ const abs = join(vault, rel);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, content);
+}
+
+async function initialize(mcp: MCPServer): Promise<void> {
+ await mcp.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "abi-test", version: "0" },
+ },
+ });
+ await mcp.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+}
+
+function call(mcp: MCPServer, name: string, args: Record<string, unknown> = {}): Promise<unknown> {
+ return mcp.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 99,
+ method: "tools/call",
+ params: { name, arguments: args },
+ }) as Promise<unknown>;
+}
+
+function extractToolResult(resp: unknown): Record<string, unknown> {
+ const r = resp as {
+ result?: {
+ content?: Array<{ type?: string; text?: string }>;
+ structuredContent?: Record<string, unknown>;
+ };
+ };
+ const content = r?.result?.content?.[0];
+ if (content?.type === "text" && typeof content.text === "string") {
+ return JSON.parse(content.text) as Record<string, unknown>;
+ }
+ if (r?.result?.structuredContent) return r.result.structuredContent;
+ return (r?.result ?? {}) as Record<string, unknown>;
+}
+
+/** Index one embedded note so there are stored vectors to be wrong about. */
+async function indexOneEmbeddedNote(): Promise<void> {
+ writeMd("notes/a.md", `# A\n\n${QUERY} in a note with vectors.\n`);
+ await indexVault(resolveSearchConfig({ vault, configPath }), { embeddings: true });
+}
+
+/**
+ * Mutate recorded ABI state behind the stamp's back. The write open
+ * re-stamps first, so the edit lands after `ensureEmbeddingModel` and
+ * survives the close - the shape of a store written by another build.
+ */
+async function tamper(edit: (store: Store) => void): Promise<void> {
+ const store = await Store.open(resolveSearchConfig({ vault, configPath }), { mode: "write" });
+ edit(store);
+ await store.close();
+}
+
+async function statusSearchBlock(): Promise<Record<string, unknown>> {
+ const mcp = new MCPServer({ vault, configPath });
+ await initialize(mcp);
+ const body = extractToolResult(await call(mcp, "second_brain_status", {}));
+ return body["search"] as Record<string, unknown>;
+}
+
+async function searchWarnings(): Promise<string[]> {
+ const mcp = new MCPServer({ vault, configPath });
+ await initialize(mcp);
+ const body = extractToolResult(await call(mcp, "brain_search", { query: QUERY, limit: 5 }));
+ return body["warnings"] as string[];
+}
+
+test("second_brain_status names the embedding-ABI drift it serves results under", async () => {
+ if (!sqliteVecLoadable()) return;
+ await indexOneEmbeddedNote();
+ await tamper((s) => s.setState(EMBEDDING_DIMENSION_STATE_KEY, "8"));
+
+ const search = await statusSearchBlock();
+ const drift = search["embedding_abi"] as Array<Record<string, unknown>> | undefined;
+ expect(drift).toBeDefined();
+ const dim = drift!.find((m) => m["field"] === EMBEDDING_DIMENSION_STATE_KEY);
+ expect(dim).toBeDefined();
+ expect(dim!["recorded"]).toBe("8");
+ expect(dim!["runtime"]).toBe("4");
+
+ // The structured field says WHAT drifted; the warning says what to run.
+ const warnings = (search["warnings"] as string[] | undefined) ?? [];
+ expect(warnings.some((w) => w.includes(EMBEDDING_ABI_FIX_COMMAND))).toBe(true);
+});
+
+test("second_brain_status on a matching store carries neither the field nor a warning", async () => {
+ if (!sqliteVecLoadable()) return;
+ await indexOneEmbeddedNote();
+
+ const search = await statusSearchBlock();
+ expect("embedding_abi" in search).toBe(false);
+ expect("warnings" in search).toBe(false);
+});
+
+test("brain_search warns that its semantic results came from a mismatched vector table", async () => {
+ if (!sqliteVecLoadable()) return;
+ await indexOneEmbeddedNote();
+ await tamper((s) => s.setState(EMBEDDING_DIMENSION_STATE_KEY, "8"));
+
+ const warnings = await searchWarnings();
+ expect(
+ warnings.some(
+ (w) => w.includes(EMBEDDING_DIMENSION_STATE_KEY) && w.includes(EMBEDDING_ABI_FIX_COMMAND),
+ ),
+ ).toBe(true);
+});
+
+test("brain_search on a matching store adds no ABI warning", async () => {
+ if (!sqliteVecLoadable()) return;
+ await indexOneEmbeddedNote();
+
+ const warnings = await searchWarnings();
+ expect(warnings.some((w) => w.includes(EMBEDDING_ABI_FIX_COMMAND))).toBe(false);
+});
+
+test("an unrecorded vec_version is a status finding, not a per-query warning", async () => {
+ if (!sqliteVecLoadable()) return;
+ await indexOneEmbeddedNote();
+ await tamper((s) => s.deleteState(EMBEDDING_VEC_VERSION_STATE_KEY));
+
+ // Every store written before the stamp existed reads this way. It is
+ // reported where an operator went looking...
+ const search = await statusSearchBlock();
+ const drift = (search["embedding_abi"] as Array<Record<string, unknown>> | undefined) ?? [];
+ expect(drift.some((m) => m["field"] === EMBEDDING_VEC_VERSION_STATE_KEY)).toBe(true);
+
+ // ...and NOT on every query, because an absent token cannot tell an
+ // old store from a wrong one - the same rule that keeps `fail` from
+ // refusing it.
+ const warnings = await searchWarnings();
+ expect(warnings.some((w) => w.includes(EMBEDDING_ABI_FIX_COMMAND))).toBe(false);
+});
diff --git a/tests/mcp/hygiene-link-integrity.test.ts b/tests/mcp/hygiene-link-integrity.test.ts
new file mode 100644
index 00000000..c5e3ef97
--- /dev/null
+++ b/tests/mcp/hygiene-link-integrity.test.ts
@@ -0,0 +1,103 @@
+/**
+ * `brain_hygiene` scan gains ONE additive top-level key
+ * (`link_integrity`) from the broken-link ratchet
+ * (context-integrity-gates, unit G).
+ *
+ * Additive means additive: the existing keys keep their names and
+ * meanings, and the closed detector tuple - validated in three places,
+ * including this tool's input-schema enum - is untouched. A fifth
+ * detector would change the tool contract; a top-level key does not.
+ */
+
+import { afterEach, beforeEach, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { HYGIENE_DETECTOR_IDS } from "../../src/core/brain/hygiene/types.ts";
+import { indexVault } from "../../src/core/search/indexer.ts";
+import { resolveSearchConfig } from "../../src/core/search/index.ts";
+import { DANGLING_LINK_DEFINITION } from "../../src/core/search/link-ratchet.ts";
+import { HYGIENE_TOOLS } from "../../src/mcp/brain/hygiene-tools.ts";
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+
+const SCAN_KEYS_BEFORE = [
+ "mode",
+ "generated_at",
+ "detectors_run",
+ "counts",
+ "findings",
+ "errors",
+] as const;
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-hygiene-links-"));
+ bootstrapBrain(vault);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+async function scan(): Promise<any> {
+ const server = new MCPServer({ vault });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "t", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+ const r = (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 2,
+ method: "tools/call",
+ params: { name: "brain_hygiene", arguments: { mode: "scan" } },
+ })) as any;
+ return r.result.structuredContent;
+}
+
+test("the detector tuple and its input-schema enum are untouched", () => {
+ expect(HYGIENE_DETECTOR_IDS).toEqual(["conflicts", "dedup", "freshness", "usefulness"]);
+ const schema = HYGIENE_TOOLS[0]!.inputSchema as any;
+ expect(schema.properties.detectors.items.enum).toEqual([
+ "conflicts",
+ "dedup",
+ "freshness",
+ "usefulness",
+ ]);
+});
+
+test("scan keeps every existing key and adds exactly one", async () => {
+ const s = await scan();
+ for (const key of SCAN_KEYS_BEFORE) expect(Object.keys(s)).toContain(key);
+ expect(Object.keys(s).toSorted()).toEqual([...SCAN_KEYS_BEFORE, "link_integrity"].toSorted());
+ expect(s.mode).toBe("scan");
+});
+
+test("an unindexed vault reports link integrity as unmeasurable, never as clean", async () => {
+ const s = await scan();
+ expect(s.link_integrity.measured).toBe(false);
+ expect(s.link_integrity.reason).toBe("index-missing");
+ expect(s.link_integrity.definition).toBe(DANGLING_LINK_DEFINITION);
+ expect(s.link_integrity.dangling).toBeUndefined();
+});
+
+test("after a full index run the dangling count is reported with its definition", async () => {
+ writeFileSync(join(vault, "Brain", "note-a.md"), "# A\n\n[[Brain/note-b.md]] and [[gone]]\n");
+ writeFileSync(join(vault, "Brain", "note-b.md"), "# B\n");
+ await indexVault(resolveSearchConfig({ vault }), { force: true });
+
+ const s = await scan();
+ expect(s.link_integrity.measured).toBe(true);
+ expect(s.link_integrity.definition).toBe(DANGLING_LINK_DEFINITION);
+ expect(s.link_integrity.dangling).toBeGreaterThanOrEqual(1);
+ expect(typeof s.link_integrity.links).toBe("number");
+});
diff --git a/tests/scripts/link-ratchet.test.ts b/tests/scripts/link-ratchet.test.ts
new file mode 100644
index 00000000..db1b9eab
--- /dev/null
+++ b/tests/scripts/link-ratchet.test.ts
@@ -0,0 +1,189 @@
+/**
+ * `scripts/link-ratchet.ts` β€” the write and `--check` forms of the
+ * broken-link ratchet gate (context-integrity-gates, unit G).
+ *
+ * The property that matters most here is the one `scripts/sync-version.ts`
+ * establishes: `--check` is the SAME code path with writing disabled, so
+ * what CI detects and what the write form records can never diverge.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { appendFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import {
+ DANGLING_LINK_DEFINITION,
+ LINK_RATCHET_FIX_COMMAND,
+ LINK_RATCHET_SCHEMA_VERSION,
+ parseCeiling,
+} from "../../src/core/search/link-ratchet.ts";
+import { CEILING_FILE, runLinkRatchet } from "../../scripts/link-ratchet.ts";
+import { writeMd } from "../helpers/search-fixtures.ts";
+
+const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+
+let root: string;
+
+interface Captured {
+ readonly exitCode: number;
+ readonly verdicts: unknown;
+ readonly out: string;
+ readonly err: string;
+}
+
+async function run(check: boolean): Promise<Captured> {
+ let out = "";
+ let err = "";
+ const result = await runLinkRatchet({
+ root,
+ check,
+ stdout: (s) => {
+ out += s;
+ },
+ stderr: (s) => {
+ err += s;
+ },
+ });
+ return { exitCode: result.exitCode, verdicts: result.verdicts, out, err };
+}
+
+function ceilingText(): string {
+ return readFileSync(join(root, CEILING_FILE), "utf8");
+}
+
+function writeCeiling(subjects: ReadonlyArray<{ path: string; dangling: number }>): void {
+ writeFileSync(
+ join(root, CEILING_FILE),
+ JSON.stringify(
+ {
+ schema_version: LINK_RATCHET_SCHEMA_VERSION,
+ definition: DANGLING_LINK_DEFINITION,
+ subjects,
+ },
+ null,
+ 2,
+ ) + "\n",
+ "utf8",
+ );
+}
+
+/** A ceiling recorded under a definition this build no longer counts by. */
+function writeLegacyCeiling(): void {
+ writeFileSync(
+ join(root, CEILING_FILE),
+ JSON.stringify({
+ schema_version: LINK_RATCHET_SCHEMA_VERSION,
+ definition: "legacy-definition",
+ subjects: [{ path: "subject", dangling: 99 }],
+ }),
+ "utf8",
+ );
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "o2b-ratchet-script-"));
+ // Two broken links: [[gone]] and (missing.md). [[b]] resolves through
+ // the read-time ladder (`b.md` exact), so the honest baseline is two.
+ writeMd(
+ join(root, "subject"),
+ "a.md",
+ ["# A", "", "[[b.md]] [[b]] [[gone]] [nope](missing.md)", ""].join("\n"),
+ );
+ writeMd(join(root, "subject"), "b.md", "# B\n");
+ writeCeiling([{ path: "subject", dangling: 2 }]);
+});
+
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe("the gate", () => {
+ test("an unchanged vault at its ceiling passes both forms with no summary", async () => {
+ const check = await run(true);
+ expect(check.exitCode).toBe(0);
+ expect(check.out).toContain("ok:");
+ expect(check.err).toBe("");
+ });
+
+ test("a new broken link fails --check with exit 1 and names the fix command", async () => {
+ appendFileSync(join(root, "subject", "a.md"), "\nAnd [[newly-broken]].\n");
+ const check = await run(true);
+ expect(check.exitCode).toBe(1);
+ expect(check.out).toContain("RISE:");
+ expect(check.err).toContain(LINK_RATCHET_FIX_COMMAND);
+ // Refused, not recorded: the committed ceiling is untouched.
+ expect(parseCeiling(ceilingText()).subjects[0]!.dangling).toBe(2);
+ });
+
+ test("fixing links and rerunning the write form lowers the ceiling", async () => {
+ writeMd(join(root, "subject"), "a.md", "# A\n\n[[b.md]]\n");
+ const write = await run(false);
+ expect(write.exitCode).toBe(0);
+ expect(parseCeiling(ceilingText()).subjects[0]!.dangling).toBe(0);
+ });
+
+ test("the detection code path is identical between the write and check forms", async () => {
+ appendFileSync(join(root, "subject", "a.md"), "\nAnd [[newly-broken]].\n");
+ const before = ceilingText();
+ const check = await run(true);
+ // The check form provably wrote nothing.
+ expect(ceilingText()).toBe(before);
+ const write = await run(false);
+ // ... and reached exactly the same verdicts from the same inputs.
+ expect(write.verdicts).toEqual(check.verdicts);
+ expect(ceilingText()).not.toBe(before);
+ });
+
+ test("a subject that cannot be measured fails BOTH forms and is not silently recorded", async () => {
+ writeCeiling([{ path: "no-such-directory", dangling: 0 }]);
+ const before = ceilingText();
+ const [checkForm, writeForm] = [await run(true), await run(false)];
+ for (const r of [checkForm, writeForm]) {
+ expect(r.exitCode).toBe(1);
+ expect(r.out).toContain("UNMEASURABLE:");
+ expect(r.err).toContain("could not be measured");
+ }
+ expect(ceilingText()).toBe(before);
+ });
+
+ test("a ceiling file recorded under a foreign definition fails --check rather than comparing", async () => {
+ writeLegacyCeiling();
+ const r = await run(true);
+ expect(r.exitCode).toBe(1);
+ expect(r.err).toContain("definition");
+ });
+
+ test("the write form re-measures a foreign definition instead of deadlocking on it", async () => {
+ // The refusal above names `bun run link-ratchet` as the fix, so that
+ // command must actually be able to record the new definition -
+ // otherwise a definition change can never be adopted.
+ writeLegacyCeiling();
+ const write = await run(false);
+ expect(write.exitCode).toBe(0);
+ // The stale count (99) is replaced by a real measurement under the
+ // current rule, and the recorded definition follows it.
+ const recorded = parseCeiling(ceilingText());
+ expect(recorded.definition).toBe(DANGLING_LINK_DEFINITION);
+ expect(recorded.subjects[0]!.dangling).toBe(2);
+ // An incomparable number is never dressed up as a rise or a drop.
+ expect(write.out).toContain("REDEFINED:");
+ expect(write.out).not.toContain("RISE:");
+ });
+});
+
+describe("the committed ceiling", () => {
+ test("parses under the current schema version and definition token", () => {
+ const ceiling = parseCeiling(readFileSync(join(REPO_ROOT, CEILING_FILE), "utf8"));
+ expect(ceiling.schema_version).toBe(LINK_RATCHET_SCHEMA_VERSION);
+ expect(ceiling.definition).toBe(DANGLING_LINK_DEFINITION);
+ expect(ceiling.subjects.length).toBeGreaterThan(0);
+ });
+
+ test("is byte-identical to what the writer would emit (no formatter drift)", async () => {
+ const text = readFileSync(join(REPO_ROOT, CEILING_FILE), "utf8");
+ const { serializeCeiling } = await import("../../src/core/search/link-ratchet.ts");
+ expect(serializeCeiling(parseCeiling(text))).toBe(text);
+ });
+});