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: silence is not an answer (v1.45.0) (#159)
Sol Aitken8d05a62a329d
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 328c3613..da645427 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.44.1",+ "version": "1.45.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 5b87f700..457167ff 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.44.1",+ "version": "1.45.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3175b3b8..3b9e5330 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,54 @@ 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.45.0] - 2026-08-10++Eight units on one seam: what this system does when it cannot answer. A check that could not run reported the same thing as a check that passed. An archive that omitted a file reported the same thing as one that contained it. A search over a stale index returned the same nothing as a search over a complete one. A rule dropped under budget pressure was reported as dropped without saying which rule. A finding an operator had judged benign had no state meaning benign, only a seven-day timer. A retired preference left every decision built on it looking current.++In six of the eight, the information needed to tell the two cases apart was already computed and then discarded. The section budgeter returned the list of keys it dropped and its caller kept only the text. The manifest walker hashed a tree whose sibling store it did not mention. The retirement path wrote the alias that makes the reverse lookup possible and nothing performed the lookup. The trigger store computed a recurrence and held it for the duration of one scan. A grounding pass over the code preceded the design and falsified a load-bearing claim in six of the eight task descriptions, so what shipped has a shape none of them predicted.++Two independent reviewers then read the finished branch against the base, with no knowledge of how the work was done, one told to treat every claim as unproven. They found this release's own theme broken by its own code in five places, and each is fixed below: a cron health gate that passed on input its parser could not read, a test-runner guard that reported its own setup failures as concurrency, a staleness audit that discarded a computable finding and then said nothing was knowable, an unreadable optional manifest field that voided the record drift detection runs on, and a per-record refusal with no per-record boundary that took a whole queue down with one corrupt file.++Some of what was asked for is not here. There is no maintenance-lane task that runs the external code indexer: it would be the first lane task to spawn a foreign binary and the first to touch state outside the vault, and the cron recipe delivers the capability without either. There are no snapshots at session, plan or decision boundaries; the history is typed and has a log surface, but changing when snapshots happen interacts with retention and with the derived store's size and should be measured first. Retention still orders by modification time, so a replicated archive arriving from another device can evict a locally newer recovery point - real, and a data-loss path, but the fix changes which snapshot a retention pass deletes and deserves its own release rather than a line in this one. The doubled injection ceiling is untouched: two preamble sources are each budgeted against the full configured limit, so the effective ceiling is twice the configured number, and halving an operator's context window is not a silent change. And the sixteen sites that inline a hash with an ad-hoc truncation are left alone, because they persist nothing this release reads.++### Added++- Schema-pack integrity is reported as `ok`, `modified` or `unverified` with a named reason, on both read surfaces and in `o2b brain schema report`. The expectation it compares against is new: applying a mutation now seals the pack by writing a digest of the rendered schema block into its audit record, so a hand-edit after an apply is detectable rather than indistinguishable from the pack that apply produced. Digesting the rendered block rather than the file is what makes it invariant to comment and whitespace churn elsewhere in the config.+- Negative recall is typed. `not_found`, `unknown` and `did_not_happen` are separate answers, and a complete negative requires a digest-bound receipt over the document set actually searched - the index side, with the divergence from the configured note roots reported rather than folded in. Every negative therefore says how far it was checked: an absent index, stale embeddings, an unreadable index instant and a configured root the index does not cover each produce `unknown` with their own reason instead of a confident nothing. A vault that never configured an embedding model still receives a `not_found`, with the vector count and the absent model signature inside the receipt and its digest, because running without embeddings is a supported configuration rather than an unfinished job - and a verdict nobody can obtain stops being read. An interrupted embedding run is the case that is genuinely indeterminate, and it says so.+- A reverse stale-dependency audit joins the instant a state stopped being current against the instant each consumer was written, and names the context receipts, decision receipts and live records that rest on it. The join needs no new store: retirement already writes the former identifier into the retired file's aliases, so the backlink index answers across the rename. It plugs into `o2b brain doctor` as a warning. The arm that reads the backlink graph needs no telemetry and always runs, so a vault with the receipt gates off still gets every finding the evidence supports; what an absent receipt trail costs is named separately, and only when something actually stopped being current.+- `o2b partner codegraph resync --cron-template` emits an installable recipe that re-indexes an external code graph after the watched repository moves. Open Second Brain writes nothing: the recipe is text, and every write in it is a shell command the operator's own scheduler runs on their host, which keeps the module invariant that this project never writes into the partner's store. `o2b partner codegraph report --fail-on-health` gives the health verdict an exit code, so a script can gate on it - the report returned success unconditionally before, including for an index built against the wrong root.+- The proactive trigger queue gains `suppress` and `unsuppress`. Suppression is indefinite by construction rather than by a second timer, because expiry applies only to open statuses, and it records the status it interrupted so restoring returns the finding to exactly where it was, with its original cooldown arithmetic intact. Alongside it, the recurrence ledger the audit trail needed: a blocked finding now increments a persisted count inside the directory lock, so the operator can ask how often a silenced finding has fired since they silenced it.+- `o2b brain snapshot` can cover the derived store, off by default. What it protects is spend rather than information - a rebuild restores everything except the embeddings, which cost an API key - and retention keeps ten copies inside a vault that replicates to every peer, so inclusion is a cost decision and the live store size is reported in every manifest whether or not it was included. Every incompleteness is named: an absent store, a store the integrity scanner has condemned, and one over the configured ceiling each refuse with their own reason, and the store is archived before the tar so a refusal leaves nothing behind.+- Every recovery point carries a typed reason, the event log gains the `snapshot` kind it had been missing since `rollback` was added, and `o2b brain snapshot log` completes log, diff and revert over the snapshot family. A reason written by a build that did not know it reads as unrecorded rather than being guessed from the run-id prefix.+- An operator-authored `Brain/standing-rules.md` is injected first, ahead of everything the agent learned about itself, and is exempt from the adaptive budget. It survives a memory-layer failure because it is read outside that boundary, and it is never written to the injection cache, so a stale constitution cannot be served from disk. The file is treated as opaque bytes throughout - read, trim, and cut at a line boundary - so it behaves identically whatever language the operator writes in, and its truncation notice is built from counts alone.+- Truncation says what it dropped. The section budgeter already returned the list of dropped keys and the caller kept only the text, so the notice named nothing; it now names the sections that were cut and the character delta.++### Fixed++- On a host without `zstd`, the gzip fallback wrote the snapshot archive with a plain file write and silently overwrote an existing one, while the `zstd` path refused - and the run-id collision logic depended on that refusal. Two concurrent destructive operations could therefore destroy each other's recovery point with no error. Both paths now refuse through one guard ahead of either compressor.+- A rollback replaced every entry under `Brain/` and only then looked for the derived-store archive, so a missing companion threw over work that had already completed: exit 1, nothing logged, and the vault rolled back regardless. Both conditions are checked before anything is touched, which is the ordering the create path already used.+- An unreadable optional field in a snapshot's sidecar failed the whole manifest closed, file map included, which reproduced the loss that keeping the manifest version unchanged exists to prevent: a peer on a later build writes a value this one does not know, this one discards the record, and the rollback gate then reports no sidecar at all and skips drift detection. Each optional field now has three states - valid, absent, or present and unreadable - and the third is recorded rather than folded into either of the others.+- `o2b brain schema sync` returned a success report and performed no work at all; it did not even take a vault. It refuses now, because what a schema backfill should write is undefined and an invented one would rewrite notes nobody asked it to touch.+- An absent `Brain/_brain.yaml` was substituted with a valid empty schema pack, so a vault with no ontology was indistinguishable from one that declares nothing.+- A malformed grounding-artifact list on a trigger degraded to empty, so an unparseable finding presented as an ungrounded one. It refuses now - and the refusal is confined to the record that is broken, because the first form of it had no per-record boundary and one corrupt file took down list, history, the morning brief, delivery marking, every transition and the scan that records new findings. Two callers then swallowed that into a bare catch and the brief rendered with its pending section absent, which is indistinguishable from an empty queue. Every surface now reports what it could not read alongside what it could.+- A trigger record with no creation instant was written back with an empty last-seen field and refused on the next read, so its first recurrence write made it permanently unreadable.+- The occurrence counter was race-free only against itself: the two writers outside the scan path wrote the whole record from an earlier snapshot without the directory lock, so a scan interleaving with a suppress lost one of the two.+- A decision-receipt directory that could not be read reported as a vault that had never recorded a decision, which additionally defeated the duplicate-append guard directly above it.+- The snapshot diff classifier predated per-device log sharding and mislabelled both the sharded Markdown and the machine-primary log - the surface a pre-restore diff is most likely to be showing.+- `Brain/.artifacts/` is documented as never backed up and was archived in every snapshot and hashed into every manifest, so ephemeral tool output tripped the drift gate.+- The derived-store archiver resolved the store by its default location and ignored a configured override, so a vault with one either refused as absent for the wrong reason or archived a stale database and reported success.+- An operator configuration error in the vault-instruction path was swallowed into a null field: the key simply vanished from the response and the operator was told nothing.+- The emitted resync recipe gated on `if jq -e`, and a bare `if` collapses every non-zero exit into one answer - so a parse error read as no mismatch and the recipe re-indexed over a root nobody had verified, against the comment three lines above it. The status is read explicitly and only a literal falsy result is a pass.+- Shell completions hand-listed the three root commands with subcommands, so every `o2b partner` verb had been offered by no shell since that surface was added, and an absent completion reads as a command that does not exist. The groups are derived from the command manifest at every depth now, and a test asserts each shell's output covers them.+- `o2b brain trigger`'s verb map routed any accepted verb that was not `ack` or `dismiss` to the act transition, and `o2b search reindex` declared none of its eight flags in the command manifest, so help and completions could not offer the cron template.+- Two test files ran CLI invocations concurrently. An in-process run swaps the environment, the working directory and both output streams and restores them in a `finally`, so overlapping runs restored each other's swapped state: one left a temporary config path installed for the rest of the process and seventeen assertions in unrelated files failed with a vault that could not be found, at a stack with nothing to do with the test that broke them. The runner refuses to overlap now, which immediately surfaced a second such race that had been silently wrong.+- The tree-wide format check walked into nested git worktrees, because the vendored bundle it excludes was matched by a root-relative pattern, and failed for changes that were entirely clean.++### Changed++- One digest encoding. Ten modules carried a byte-identical private SHA-256 helper and three reimplemented canonical JSON serialization independently, which was survivable while every digest stayed inside the process that computed it and stops being survivable the moment one is persisted: this release persists two digests, into a vault that replicates between machines. The three canonical-JSON copies disagreed about an object entry whose value is `undefined`. In the two that feed a persisted digest the divergence was unreachable, because every parser building their input uses a conditional spread, so no stored value changes. The third keyed an in-process request cache and rendered such an entry as an explicit null, which was distinguishing two requests that are byte-identical once they leave through `JSON.stringify` - so absorbing it closes a latent cache miss rather than changing a value.+- Every closed verdict vocabulary this release introduces registers in one census that asserts its frozen object, its membership list and its type guard agree, with synthetic negative cases proving each assertion bites. The status partition behind the trigger queue was three hand-maintained copies across core, CLI and the tool layer, with a fourth copy of the status list as a literal in a tool schema and nothing asserting the two matched; there is one owner now.+## [1.44.1] - 2026-08-08### Fixed@@ -6895,6 +6943,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.45.0]: https://github.com/itechmeat/open-second-brain/compare/v1.44.1...v1.45.0[1.44.1]: https://github.com/itechmeat/open-second-brain/compare/v1.44.0...v1.44.1[1.44.0]: https://github.com/itechmeat/open-second-brain/compare/v1.43.0...v1.44.0[1.43.0]: https://github.com/itechmeat/open-second-brain/compare/v1.42.0...v1.43.0diff --git a/docs/brainstorm/silence-is-not-an-answer/cli-output/claude.md b/docs/brainstorm/silence-is-not-an-answer/cli-output/claude.mdnew file mode 100644index 00000000..303ffec2--- /dev/null+++ b/docs/brainstorm/silence-is-not-an-answer/cli-output/claude.md@@ -0,0 +1,44 @@+### Variant 1: Kernel-first โ one verdict-and-digest foundation landed ahead of the eight++- **Approach**: Open the branch with two leaf modules before any unit: a `Verdict` kernel (frozen vocabulary where `unverified` is a member alongside checked-clean and checked-bad, each carrying a reason code drawn from a single registered table) and a `digest` module that absorbs the ~10 private SHA-256 copies, the 16 inline sites, the 3 ad-hoc truncation lengths and the 2 canonical-JSON implementations behind named constants. All eight units then express their local vocabulary as a parameterisation of the kernel โ U1's `ok`/`modified`/`unverified`, U2's `not_found`/`unknown`/`did_not_happen`, U6's `included`/`excluded_because`/`unknown-because-predates`, U3's `recorded: false` โ and every read surface renders through one renderer.+- **Trade-offs**:+ - Pro: the two persisted digest decisions (U1's schema-pack digest, U2's coverage receipt) are made once, by one module, with one truncation constant โ under the additive-only rule a divergence here would be permanent across replicated peers.+ - Pro: the reason axis becomes census-enforceable in the existing signal table from day one; a unit that invents an unregistered reason fails the build rather than shipping a private string.+ - Pro: the digest consolidation is a debt the wave has to touch anyway; doing it once at the front is cheaper than eight partial touches.+ - Con: the wide half of the kernel is a god-type risk. U5's `suppressed` is a lifecycle status with a recurrence counter, U7's snapshot reason is a causal vocabulary, U8's truncation notice is a payload naming dropped items โ forcing all three into one verdict shape produces a type whose members do not mean the same thing, and that shape survives the release.+ - Con: the largest single-PR blast radius of the three: ~26 pre-existing digest call sites refactored in the same diff as eight features, so an unrelated regression in the digest sweep can block the whole wave.+ - Con: a leaf module consumed by schema, recall, doctor, snapshot, trigger and injection layers is a new central dependency in a codebase that recently spent a release removing all import cycles.+- **Complexity**: large+- **Risk**: medium++### Variant 2: Narrow shared kernel โ share the reason axis and the digest bytes, keep every verdict vocabulary local++- **Approach**: Split the primitive along its two axes and share only the one that is genuinely identical across the eight. The reason axis โ the named, machine-readable *why-could-not-check* code โ is an extension of the existing closed could-not-check condition vocabulary, widened into a leaf registry that the census test already enforces; the digest module is consolidated as in Variant 1 because two units persist digests. The verdict axis stays local to each unit: eight small frozen vocabularies with their own arity and their own exhaustive switches, each obliged to carry a reason code from the shared registry on its unverifiable member.+- **Trade-offs**:+ - Pro: directly satisfies "prefer extending an existing surface to adding a parallel one" โ the could-not-check vocabulary and the existing `pass`/`warn`/`fail` mismatch renderer are the precedents, and this widens them rather than standing up a rival.+ - Pro: smallest surface that can still be wrong. If the shared piece turns out wrong halfway, the reason registry is additive by construction and only U1 and U2 depend on the digest module, so rework is two units, not eight.+ - Pro: keeps arity honest. U3 needs `recorded: false` versus `rows: []`, U4 needs a non-zero exit code, U5 needs a status plus a counter โ none of these is a tri-state, and none has to pretend to be.+ - Pro: the repeated-constant convention is satisfied where the repetition is real (reason codes, digest algorithm, truncation length) without inventing repetition where it is not.+ - Con: eight local vocabularies means eight exhaustive switches and eight renderer adapters; the family resemblance is enforced by convention and review, not by the compiler.+ - Con: U5's status partition is currently hand-maintained in three copies across core, CLI and MCP โ this variant fixes that within U5 but does not give the wave a general mechanism preventing the next such triplication.+ - Con: the boundary between "reason" and "verdict" has to be adjudicated per unit and one or two will be arguable (U6's `unknown-because-predates-the-feature` is arguably a reason wearing a verdict's clothes).+- **Complexity**: medium+- **Risk**: low++### Variant 3: Local-first with an enforced census โ eight private vocabularies, one ratchet, harvest in a later wave++- **Approach**: Ship each unit with its own frozen vocabulary, its own reason strings and its own digest call, sharing nothing new; the only cross-cutting addition is a census/ratchet test that requires every new verdict member and every reason code to be registered in the existing diagnostic signal table, plus a written refusal in the release notes naming the shared kernel as deliberately not built and why. The eight then serve as the eight real call sites a later refactor wave needs in order to design the kernel from evidence rather than from anticipation.+- **Trade-offs**:+ - Pro: maximum unit independence โ the eight can be built and reviewed in any order, and a stalled unit blocks nothing else in the branch.+ - Pro: zero wrong-kernel cost. There is no shared piece that can turn out wrong halfway.+ - Pro: the refusal is shippable release content in the project's established style, so the decision is recorded rather than silently deferred.+ - Con: two units persist a digest, independently choosing algorithm and truncation length. Under additive-only on persisted formats, two divergent digest encodings in one release are permanent for replicated peers โ this is the one place where the repetition is not merely untidy.+ - Con: leaves the ~10 SHA-256 copies and 2 canonical-JSON implementations at 12 and 18, in a wave whose stated theme is that duplicated silence-handling is the defect.+ - Con: sits against two written conventions at once ("anything repeated goes into a named constant", "no new subsystem where an existing one can carry the capability") โ the census test makes the duplication visible but does not make it legal.+ - Con: the later harvest wave has to touch all eight units again, and by then their vocabularies are released and additive-only.+- **Complexity**: small per unit, large in aggregate+- **Risk**: high++### Recommended: Variant 2++**Rationale**: The eight units genuinely share the *reason* axis and the digest bytes, and they genuinely do not share the verdict axis โ a suppression status with a recurrence counter, an exit code and a coverage receipt are not the same type, and a kernel that claims they are would outlive the release under the additive-only rule. Variant 2 shares exactly the two things whose divergence would be permanent and unfixable across replicated peers (one digest encoding, one registered reason vocabulary), extends existing precedents instead of standing up a parallel one, and confines mid-wave rework to the two digest consumers if the shared piece proves wrong โ whereas Variant 1 bets the whole wave on a wide type designed before its call sites exist, and Variant 3 buys independence by shipping two irreconcilable persisted digests.diff --git a/docs/brainstorm/silence-is-not-an-answer/cli-output/prompt.md b/docs/brainstorm/silence-is-not-an-answer/cli-output/prompt.mdnew file mode 100644index 00000000..4f91c0c3--- /dev/null+++ b/docs/brainstorm/silence-is-not-an-answer/cli-output/prompt.md@@ -0,0 +1,97 @@+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++One release wave of eight kanban units in Open Second Brain, selected because they share one seam: **a state that cannot be verified, is absent, or has gone stale is currently reported as silence, and silence is indistinguishable from health.**++A read-only grounding pass over the current code preceded this brief. Every claim below is verified at `file:line` against HEAD. Several of the original task descriptions were falsified by that pass and the corrected findings are what appear here.++## The eight units++**U1 โ Schema-pack integrity tri-state.** The `schema:` block of `Brain/_brain.yaml` is the operator-curated ontology that gates every write. `applySchemaMutations` records *which mutations were requested* into an audit shard but never a digest of the pack that resulted, so no recorded expectation exists to compare against. Four distinct states โ sealed-and-intact, hand-edited-since-apply, never-audited, config-file-absent โ render identically on every read surface (`schema_inspect view: active_pack` / `view: packs`, `o2b brain schema report`). Needs: a digest of the rendered schema block written at apply time, and an `ok` / `modified` / `unverified` status with a named reason for each unverifiable case. Note: there is exactly one pack; `listSchemaPacks` returns a hardcoded one-element list and there is no registry, no external pack, and no signature machinery anywhere in the project (a prior release explicitly refused pack-by-URL for this reason).++**U2 โ Typed negative recall with a coverage receipt.** Every negative the system can produce today is a statement about the *retrieval attempt*, never about the *corpus*. A typed 3-state negative already exists on the injection path (`empty_prompt` / `no_matches` / `below_floor`, with a separate `error` arm), so the often-repeated claim that absence collapses into one empty result is already false there. What is genuinely missing: a "no" derived from a stale, partial, or embedding-disabled index is byte-identical to a "no" derived from a complete one. Needs: `not_found` / `unknown` / `did_not_happen`, where a complete negative claim is inadmissible without a digest-bound receipt over the document set actually searched. Complication: two candidate universes disagree โ the *authorized* set (configured note roots minus ignores) and the *searched* set (what the index actually covers). A receipt over the authorized set overclaims; one over the index alone hides the divergence. `did_not_happen` can only be grounded in stored evidence (existing tombstone / `superseded_by` / `valid_until` edges in the claim graph), never inferred from absence.++**U3 โ Reverse stale-dependency audit.** Given a preference retired or a fact superseded at time T, nothing enumerates the downstream consumers written before T that cited it: context receipts naming it in `items[].id`, decision-change receipts naming it in `evidence_triggers`, live Brain artifacts still linking to it. All the edges are already durable and already normalized across the `pref-` โ `ret-` rename (retirement writes the old id into the new file's `aliases:`), so this is a time-ordered join over existing data, not a new store. Two constraints: one coarse prior art exists (a whole-corpus tree digest that invalidates one cache) and must be named rather than reinvented; and receipt emission is opt-in, so a vault with telemetry off has zero receipts โ the audit must distinguish "measured nothing" from "found nothing" or it reports a clean bill of health for a vault that measured nothing.++**U4 โ Codegraph resync recipe.** The system detects that an external code-index is empty, edge-collapsed, or built for the wrong root, and its only exit is prose inside a warning string. A hard module invariant forbids ever writing into the external tool's store; the project has also explicitly refused daemons and file watchers. The sanctioned mechanism is the existing "emit a cron recipe to stdout, write nothing" pattern โ but that renderer is welded to the search index (script name, command and change-detection expression are hardcoded), so a second consumer cannot reuse its interval-to-cron kernel. Also blocking: the report verb returns exit 0 unconditionally, including when health is bad, so nothing can gate on it.++**U5 โ Trigger suppress / unsuppress.** The proactive-finding queue is a one-way funnel with a clock on the exit: every terminal state either re-opens after a cooldown or immediately, and there is no edge back out. An operator who judges a finding structurally benign can buy seven days of silence and then it re-nags forever; a mistaken judgement can only be undone by hand-editing Markdown frontmatter. A new non-open status is indefinite for free because expiry is applied only to open statuses. The task assumes an occurrence counter it can preserve; no such counter exists โ recurrence lives as a transient per-scan value and is discarded, so the audit trail has to be built. The status partition is currently hand-maintained in three separate copies across core, CLI and the MCP layer.++**U6 โ Derived-store coverage in the snapshot archive.** The snapshot/rollback family (checksum sidecar, drift refusal, pre-restore diff, confirmation, retention) already ships and is complete for the Markdown tree. It archives exactly the top-level entries of `Brain/`; the derived SQLite store is a sibling directory away and is in no snapshot, no manifest and no rollback โ and nothing says so, so the pre-restore diff renders a complete-looking picture while embeddings silently stay at whatever the live store holds. What is at stake is spend, not information: a rebuild restores everything except the embeddings, which cost money. The store is WAL-mode so a file copy is not consistent; the runtime exposes no online-backup API but does support a compacting `VACUUM INTO`. The sibling directory also holds encrypted secrets and lock files, so only the one store file may ever be archived. Retention defaults to ten copies and the snapshot directory is inside a peer-to-peer-replicated vault, so inclusion multiplies disk and network cost.++**U7 โ Typed lifecycle history with a log surface.** Two histories exist and do not join. The event log is richly typed (41 kinds, machine-primary JSONL, per-device sharded, filterable) and records a *rollback* but has no kind for the *snapshot* it rolls back to. The snapshot family is the only revertible history and each entry is an opaque run id plus an mtime โ no reason, no type โ so an operator cannot ask which recovery point covers a given boundary or filter the revertible history by why it happened. Snapshot reasons exist de-facto as run-id prefixes at five call sites, three of them inline string literals, and nothing parses them back. Hard architectural constraint: the vault is plain Markdown replicated peer-to-peer with no git transport, so a `.git` directory under the synced path is forbidden; the existing snapshot family is the native journal.++**U8 โ Operator standing rules.** There is no lane in the session preamble whose content the operator authors, whose position is guaranteed ahead of everything the agent learned about itself, and whose presence is independent of whether the memory layer assembled successfully. The one operator-authored file the system reads is delivered on a single pull surface, positioned last, silently dropped on any read error, and freely rewritable by four write tools because it sits outside the path-prefix refusal that protects everything else. A budget-exempt lane already exists as precedent (runtime notices are never budgeted). When the budget bites, the injection shrinks behind a notice that says *that* content was dropped but never *which* โ even though the drop list is computed and discarded one line earlier.++## The architectural question you are being asked++Every one of the eight independently reinvents the same primitive: **a closed verdict vocabulary in which "could not check" is a first-class value distinct from both "checked and clean" and "checked and bad", carrying a named machine-readable reason.**++Concretely the eight want: `ok`/`modified`/`unverified` (+reason); `not_found`/`unknown`/`did_not_happen` (+reason, +coverage digest); `recorded: false` vs `rows: []`; `included`/`excluded_because`/`unknown-because-predates-the-feature`; a bad-health exit code; a `suppressed` state plus a recurrence count; a truncation notice that names what it dropped; a snapshot reason vocabulary.++The codebase already contains at least three partial precedents: a frozen `pass`/`warn`/`fail` verdict with a mismatch-report type and a renderer; a closed "could-not-check condition" code vocabulary consumed by exhaustive switches; and a typed fold-empty error asserting that no-mechanism-ran must never read as no-findings. It also contains roughly ten private copies of the same SHA-256 helper, sixteen further inline digest sites with three ad-hoc truncation lengths, and two independent reimplementations of canonical JSON serialization โ and two of the eight units need a digest.++Produce variants for **how to structure this wave**: whether to introduce a shared kernel for the verdict-and-reason primitive and the digest helper before the eight units, to extend one of the existing precedents to serve all eight, or to keep every vocabulary local to its unit and accept the repetition. Consider ordering, blast radius, and what happens to the wave if the shared piece turns out to be wrong halfway through.++# Project context++Open Second Brain โ TypeScript on the Bun runtime. A CLI (`o2b`) plus an MCP server over an Obsidian-compatible Markdown vault. The vault is the source of truth and is replicated peer-to-peer between machines by Syncthing; there is no git transport for it. A derived SQLite store beside the vault holds the search index and embeddings. The kernel never calls a language model; the operator owns configuration.++Recent commits:++```+34f96b84 fix: reuse and reap Hermes MCP bridges (v1.44.1)+3ee1963a feat: what the index already knew (v1.44.0)+0ae4b097 feat: provenance at the boundary (v1.43.0)+7e6a5672 refactor: module boundaries and the fallbacks behind them (v1.42.0)+5ac866eb feat: signals that survive (v1.41.0)+0963ef0a feat: no dead ends - every diagnosis names its exit (v1.40.0)+f91a698b feat: context integrity gates (v1.39.0)+c31a2574 feat: semantic-health baseline watermark (v1.38.0)+b0c37977 feat: retrieval quality and context delivery (v1.37.0)+842d690f feat: knowledge intake and consolidation (v1.36.0)+95dc8577 feat: trusted recall and memory write surface (v1.35.0)+4b8100ca feat: source pipeline integrity and operator tooling (v1.34.0)+77513f2b feat: belief lifecycle and decision memory (v1.33.0)+9a649dd6 feat: memory write-path integrity and store safety wave (v1.32.0)+13bde6c3 refactor: remove all import cycles, decompose search.ts (v1.30.1)+```++Related areas, by unit: schema pack storage and the mutation-audit shard (U1); the recall gate, the index-status snapshot and the note-root resolver (U2); the doctor check registry, the backlink index, context receipts and decision receipts (U3); the partner code-index health module and the cron-recipe renderer (U4); the trigger store, its frontmatter reader/writer and two duplicated verb tables (U5); the snapshot engine, its manifest and the destructive-snapshot gate (U6); the log event-kind table and the snapshot manifest (U7); the session-start injection hook, the section-budget primitive and the note-target path refusal (U8).++Conventions:++- Every check that can fail to run reports that it did not run, distinctly from reporting a pass. A prior release states the rule as: never-checked must never read as healthy, and only refusals are recorded, so the absence of a fault is not a pass.+- Refusals are shipped as first-class release content. Release notes name what was asked for and deliberately not built, with the reason.+- Closed vocabularies are frozen objects with a companion `Set` and a type guard, consumed by exhaustive switches that fail to compile when a member is added.+- Pure kernel plus impure collector: the joinable logic is a pure function with no I/O and the caller does the reads.+- Config keys are declared in a template that a ratchet test enforces; adding a key without a template entry or a written omission reason fails the build.+- Diagnostic codes are registered in a signal table that a census test enforces.+- Tests build disposable vaults in a temp directory; there are no network calls in tests.+- Documentation and all identifiers are English. Natural-language phrases are never hardcoded and content authored by the operator is treated as opaque bytes โ never inspected for particular words, in any language.++Constraints:++- No misleading fallback of any kind. A path that returns empty, null, zero or ok when it actually failed is forbidden; the failure must surface. No stubs and no placeholders.+- Prefer extending an existing surface to adding a parallel one. No new subsystem where an existing one can carry the capability.+- Additive-only on persisted formats where a version bump would make older peers in a replicated set silently lose a guarantee.+- The wave ships as one pull request and one release version.+- Anything repeated goes into a named constant. No magic strings and no magic numbers.++# Required output format++Produce exactly 3 distinct architectural variants. 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/silence-is-not-an-answer/design.md b/docs/brainstorm/silence-is-not-an-answer/design.mdnew file mode 100644index 00000000..b2e91b74--- /dev/null+++ b/docs/brainstorm/silence-is-not-an-answer/design.md@@ -0,0 +1,300 @@+# Silence is not an answer - eight units on absence, staleness and integrity++**Status:** draft+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Eight kanban tasks were selected as one wave because they sit on one seam: what+this system does when it cannot answer. A read-only grounding pass over the+current code preceded any design and falsified a load-bearing claim in six of+the eight task bodies, so what follows is grounded state, not task prose.++The pattern underneath all eight is the same. A check that could not run reports+the same thing as a check that passed. An archive that omitted a file reports+the same thing as one that contained it. A search over a stale index returns the+same "nothing" as a search over a complete one. A rule dropped under budget+pressure is reported as dropped without saying which rule. A finding an operator+has judged benign has no state meaning "benign" - only a seven-day timer. A+retired preference leaves every decision built on it looking current.++None of these is a missing feature in the ordinary sense. In six of the eight,+the information needed to tell the two cases apart is already computed and then+discarded: the section budgeter returns the list of keys it dropped and its+caller keeps only the text; the manifest walker hashes a tree whose sibling+store it does not mention; the retirement path writes the alias that makes the+reverse lookup possible and nothing performs the lookup; the trigger store+computes a recurrence and holds it for the duration of one scan.++## Scope++One shared kernel, eight units, and the defects found in their blast radius.++**Kernel, before the units**++- One digest module. Ten byte-identical private SHA-256 helpers and three+ independent reimplementations of canonical JSON serialization collapse into one+ module. Two units in this wave persist a digest into a replicated vault, and+ under the additive-only rule two divergent encodings shipped together could+ never be reconciled. The sixteen further sites that inline a hash with an+ ad-hoc truncation length are out of scope, for the reason given below, so the+ module exports no truncation constant it has no caller for.+- One census test over every verdict vocabulary the wave introduces. It asserts+ the trio is complete and consistent: the companion `Set` holds exactly the+ frozen object's values, the guard accepts every member and rejects a+ non-member, and no vocabulary carries a duplicate value. It deliberately does+ not require code strings to be unique across vocabularies - an absent config+ file and an absent store file are both honestly named `absent`, and forcing+ them apart would buy nothing.++**The eight units**++- **U1** Schema-pack integrity reports `ok` / `modified` / `unverified` with a+ named reason, backed by a digest of the rendered schema block written at apply+ time. Four states that render identically today become four distinct answers.+- **U2** Negative recall is typed `not_found` / `unknown` / `did_not_happen`, and+ a complete negative is inadmissible without a digest-bound receipt over the+ document set actually searched. `did_not_happen` is grounded in stored+ retraction evidence, never inferred from absence.+- **U3** A reverse stale-dependency audit joins retirement time against consumer+ write time and names the context receipts, decision receipts and live artifacts+ that rest on a state which has since changed.+- **U4** The code-index health surface gains an exit code, and the cron-recipe+ renderer is generalized so a second consumer can emit a resync recipe without+ copying it.+- **U5** The trigger queue gains an indefinite `suppressed` status, an+ `unsuppress` edge that restores the prior state, and the recurrence ledger the+ audit trail needs.+- **U6** The snapshot archive can cover the derived store, off by default, with+ every omission named and every failure refused rather than skipped.+- **U7** Snapshots carry a typed reason, the event log gains the `snapshot` kind+ it has been missing since `rollback` was added, and `snapshot log` completes+ log / diff / revert.+- **U8** An operator-authored standing-rules block is injected first, is exempt+ from the adaptive budget, survives a memory-layer failure, is refused by the+ two write paths that can address it by name (inherited for the four+ caller-named note-write tools, an explicit named guard for the label writer),+ and names what it dropped when it is capped.++**Defects fixed in the same wave**++Found by grounding, all in the blast radius of the eight, all the same class as+the wave itself:++- A snapshot gzip fallback silently overwrites an existing archive while the+ zstd path refuses - and the run-id collision resolution depends on that+ refusal, so on a host without zstd two concurrent destructive operations can+ destroy each other's recovery point with no error.+- A schema sync verb returns a success report and performs no work at all.+- An absent config file is substituted with a valid empty schema pack, so "no+ ontology" is indistinguishable from "an ontology that declares nothing".+- An operator configuration error in the vault-instruction path is swallowed into+ `null`; the field vanishes from the response and the operator is told nothing.+- A malformed grounding-artifact list degrades to empty, so an unparseable+ finding presents as an ungrounded one.+- A decision-receipt directory that cannot be read reports as a vault with no+ decisions, which additionally defeats the duplicate-append guard directly above+ it.+- The snapshot diff classifier predates per-device log sharding and mislabels the+ log surface it is most likely to be displaying.+- The artifact directory documented as never backed up is archived in every+ snapshot and hashed into every manifest, so unrelated churn trips the drift+ gate.+- Three hand-maintained copies of one status partition, a fourth copy of the+ status list as a literal in a schema, and two copies of an identifier-prefix+ regex whose declared home already exists.++## Out of scope++Named here and in the release notes, because a deferral that is not written down+reads as an omission.++- **The full digest sweep.** The ten identical private helpers and all three+ canonical-JSON copies are absorbed - the third is the external-fetch cache+ key, which differed only in rendering an `undefined` object entry as+ `"key":null` instead of omitting it; nothing persists that key and the request+ it identifies goes out through `JSON.stringify`, which omits the entry, so the+ copy was distinguishing requests that are identical on the wire. The sixteen+ further sites that inline a+ hash with an ad-hoc truncation are not: they are correct today, they persist+ nothing this wave reads, and folding twenty-six call sites into a diff that+ also carries eight features trades a real regression risk for tidiness.+- **A maintenance-lane task that runs the external code indexer.** It would be+ the first lane task to spawn a foreign binary and the first to touch state+ outside the vault, and it would amend a module invariant that is currently+ absolute. The cron recipe delivers the capability without any of that. The lane+ entry is a separate decision.+- **Snapshots at session, plan and decision boundaries, and on demand.** U7 types+ the history and gives it a log surface; making snapshots *happen* at three new+ seams changes their frequency, which interacts with retention and, if the+ derived store is included, with disk in a way that should be measured before it+ is shipped. The `manual` reason is deferred with them and for the same reason+ it is declared at all - a peer running a later release may write it, and this+ build must read it - so no verb and no tool in this wave takes a recovery point+ on demand. Four of the nine members therefore have no producer here, which the+ vocabulary's own documentation states so `snapshot log --reason manual`+ listing nothing reads as the deferral it is.+- **Retention ordering under replication.** Snapshot listing and pruning both+ order by mtime, and a replicated archive arriving from another device carries+ its origin mtime, so pruning can evict a locally newer recovery point. This is+ real and it is a data-loss path, but the fix changes which snapshot a retention+ pass deletes, and that behavioural change deserves its own wave rather than a+ line in this one. It is recorded here so it is not rediscovered as new.+- **The doubled injection ceiling.** Two preamble sources are each budgeted+ against the full configured ceiling, so the effective limit is twice the+ configured number. U8 makes the truncation notice honest about what was+ dropped; it does not change the ceiling, because halving an operator's+ effective context window is a behavioural change that must be announced on its+ own terms.++## Chosen approach++Variant 2 of three, adopted with one override; the full audit trail is in+`variants.md`.++Share the two things whose divergence would be permanent - one digest encoding,+one enforced registration discipline for reason codes - and share nothing else.+Every unit keeps its own verdict vocabulary, because a suppression status with a+recurrence counter, a process exit code, a coverage receipt and an archive+inclusion decision are four types, not one, and a kernel asserting otherwise+would have to be widened for every arity it failed to anticipate.++The override concerns where the reason axis lives. The consultant proposed+widening the existing could-not-check condition vocabulary; grounding shows it is+consumed by exhaustive switches with `never` defaults, which makes adding a+member a compile-breaking edit for unrelated consumers. It is the wrong host+precisely because it is well-typed. The reason codes are also disjoint in+meaning across the eight, and a union of disjoint sets is a namespace rather than+an abstraction. So the reason axis is shared as a shape and a census: each unit+owns the frozen-object / `Set` / guard trio the project already uses, and one+test asserts that the trio is complete and that no member is unregistered.+Uniqueness ACROSS vocabularies is deliberately not asserted, for the reason+given under Scope.++## Design decisions++- **Refuse, do not skip.** Where an operation cannot be completed as requested,+ it fails loudly rather than completing partially and reporting success. The+ derived-store archive throws when it cannot include a store it was asked to+ include; because the destructive-snapshot gate already aborts before the+ operation when the snapshot throws, a mutation that cannot be fully protected+ simply does not run. No new plumbing is needed to get that property; it follows+ from refusing in the right place.++- **Never-checked is not clean, and measured-nothing is not found-nothing.** Both+ are established precedents in this codebase - one from the integrity scanner,+ one from the context-receipt fold, which ships a typed error asserting that no+ mechanism having run must never read as no findings. Every verdict this wave+ introduces inherits them. U3 reports `recorded: false` for a vault whose+ telemetry is off rather than a clean bill of health, and U6 renders a snapshot+ taken before this feature as `unknown` rather than `excluded`.++- **Additive-only on persisted formats.** The manifest sidecar reader rejects any+ schema version it does not recognize, so bumping it would make every older peer+ in a replicated set silently lose drift detection on new snapshots. U6 and U7+ both add optional keys at the existing version instead; an old reader ignores+ them and its own guarantee is untouched.++- **The authorized universe and the searched universe are different sets, and the+ receipt says so.** U2 digests the searched set, because that is what a negative+ claim can honestly attest to, and reports the divergence from the authorized+ set as a named reason that forces `unknown`. A receipt over the authorized set+ would overclaim; one over the index alone would hide the gap.++- **Uneditability is mostly inherited, and the rest is one named guard.** U8's+ standing-rules file lives under the tree whose first path segment the+ note-target resolver already refuses for the four caller-named note-write+ tools, so for that class choosing the directory is the whole enforcement+ mechanism and the new code is the test that asserts it, plus the assertion+ that no tool description mentions the path. It is not the whole class:+ `brain_labels` also takes a caller-named path and reaches the file through the+ containment-only resolver, so it gets an explicit guard that refuses this one+ file by name. The guard is not the Brain-root refusal moved down a layer -+ several legitimate callers write inside `Brain/` through that resolver (marker+ write-back, tombstones, temporal replace) - and every claim in the docs is+ scoped to these two mechanisms rather than to "any tool".++- **Operator bytes are opaque.** The standing-rules reader performs exactly three+ operations on the operator's text: read, trim, and truncate at a line boundary.+ It never splits on headings, never inspects words, never classifies. The+ truncation notice is built from integers only, so it is identical whatever+ language the operator writes in.++- **Trigger suppression is restore-with-state by construction.** Suppressing+ stamps the prior status and leaves the delivery and resolution instants+ untouched, so unsuppressing restores the original state and the original+ cooldown arithmetic without any bookkeeping. A missing prior status on a+ hand-edited file throws naming the field rather than defaulting to pending.++- **The recurrence ledger is written for every candidate an existing record+ silenced, not only suppressed ones.** One code path, no special case, and it+ is precisely the event worth recording: the finding fired again and the+ system stayed silent. What silenced it - suppression, an open twin, a+ cooldown window, the per-kind cap - changes nothing about that. Two limits+ are stated rather than implied: the count is per scan, so one scan seeing the+ same finding twice counts once, and a candidate silenced before any record+ for its cooldown key existed has no ledger to write to and is reported in the+ skipped list alone. Every writer in the store - creation, the transitions and+ brief delivery - takes the trigger-directory lock, because each persists the+ whole record and two of them interleaving would otherwise lose an increment.++- **U4 writes nothing.** The resync recipe is text on stdout; every write in it is+ a shell command run by the operator's own crontab on the operator's own host.+ The module invariant that this project never writes into the external tool's+ store is preserved exactly. The recipe's health pre-flight aborts when its JSON+ parser is absent rather than falling back to a looser match, because a gate+ that cannot parse its input must not pass.++## File changes++Kernel: a new digest module under the integrity tree, absorbing ten private+helpers and two canonical-JSON copies; a new census test.++U1: a new schema-integrity module; the mutation-audit writer gains a pack digest;+the two schema read surfaces and the CLI report gain a status. U2: a new+negative-recall module; the recall-gate output schema gains an optional block;+the continuity record kind union gains a member. U3: a new stale-dependency+collector plus a doctor check module; registry and diagnostic-signal entries; one+extraction into the identifier-vocabulary module with two call sites repointed.+U4: a new shared cron-recipe kernel extracted from the search template, which+keeps every exported name and must produce byte-identical output; a new codegraph+recipe module; a new verb and a new flag in the partner CLI plus their manifest+nodes; the partner CLI vocabulary hoisted into one frozen constant. U5: the+status partition moves to the types module and three copies are deleted; the+store gains a status, four persisted fields, a recurrence writer and two+transitions; both verb tables and both JSON projections follow. U6: two path+constants, one snapshot path helper, an optional manifest field with a named+exclusion vocabulary, an archive step gated on the existing writer lock and+integrity scanner, two config keys, and the list and restore surfaces. U7: a+snapshot-reason vocabulary and one new log event kind; an optional manifest+field; the destructive-snapshot gate splits out a reusable take-snapshot entry+point; a new CLI subcommand. U8: two path constants, a new standing-rules module,+a widened notice type on the section budgeter, the injection hook composing the+block outside the fail-open boundary, and the pull surface prepending it.++Documentation: the how-it-works surface table, the CLI reference, the changelog+entry, and the version bump propagated through the manifest sync script.++## Risks and open questions++- **The wave is large.** Eight units plus a kernel, plus the defects found in+ their blast radius, in one pull request. The mitigation is ordering: the kernel lands first and is proved+ by the two units that persist a digest, then the units land in dependency order+ with the full check suite green at every commit.+- **The cron-recipe extraction must not change a byte of existing output.** It is+ guarded by the existing template test, extended with a pinned fixture. If the+ output moves, the extraction is wrong.+- **U6 introduces a SQLite fixture into the snapshot test surface**, which has+ none today. If the fixture proves flaky under the writer lock, the unit ships+ with the archive step covered by a smaller integration test rather than being+ weakened.+- **U2's `did_not_happen` arm depends on the claim graph** for retraction+ evidence. If that projection turns out not to expose an instant that can be+ compared against the coverage receipt, the arm ships as a refusal with the+ reason recorded, and the other two states plus the receipt ship regardless.+- **U5 changes a persisted frontmatter shape.** Records written before this wave+ carry no recurrence count and parse as one, which is the true number of+ recorded occurrences rather than a papered-over unknown. That reading needs to+ be stated in the field's documentation so it is not later mistaken for a+ default.diff --git a/docs/brainstorm/silence-is-not-an-answer/plan.md b/docs/brainstorm/silence-is-not-an-answer/plan.mdnew file mode 100644index 00000000..2896e1f3--- /dev/null+++ b/docs/brainstorm/silence-is-not-an-answer/plan.md@@ -0,0 +1,221 @@+# Silence is not an answer - implementation plan++Ordering rule: the kernel lands first because two units persist what it produces.+After that, units are ordered so that every shared edit is made by the unit that+needs it first and merely consumed afterwards. Every task is one conventional+commit; formatter and linter are green before each commit, and the full check+suite is green before the next task starts.++Each task lists the defect fixes that belong to its blast radius. They are not+deferred to a cleanup commit: a defect found while reading a file is fixed while+that file is open.++## Tasks++### Task 0: Digest kernel and verdict census+- **Files**: new `src/core/integrity/digest.ts`; the ten modules carrying a+ byte-identical private SHA-256 helper; the two modules reimplementing canonical+ JSON serialization; new `tests/core/integrity/digest.test.ts`; new+ `tests/core/architecture/verdict-vocabulary-census.test.ts`.+- **Acceptance**: one exported hex-digest function and one canonical-JSON+ function with named truncation-length constants; every absorbed call site+ produces the identical digest it produced before, proved by a test that pins+ the hash of a fixed input; the census test passes over the vocabularies that+ exist today and fails when given a synthetic vocabulary missing its guard, its+ `Set`, or claiming a duplicate code.+- **Depends on**: none.++### Task 1: Schema-pack integrity tri-state (U1)+- **Files**: new `src/core/brain/schema-integrity.ts`; `schema-mutate.ts` (write+ the pack digest into the mutation audit, replace the audit-directory literal+ with a constant, add the digest to the apply result); `schema-admin.ts` (both+ read surfaces carry the status); `src/cli/brain/verbs/schema.ts` (report line);+ new `tests/core/brain/schema-integrity.test.ts`; extend+ `tests/core/brain/schema-mutate.test.ts` and `tests/mcp/schema-tools.test.ts`.+- **Acceptance**: apply then read gives `ok`; hand-editing the schema block gives+ `modified` with a populated mismatch on both sides; editing an unrelated comment+ in the same file still gives `ok`, because the digest is over the rendered block+ and not the raw file; a missing audit directory gives `unverified` with the+ no-apply-recorded reason and never `ok`; an unparseable audit shard gives+ `unverified` with the audit-unreadable reason; a deleted config file gives+ `unverified` with the config-absent reason.+- **Defects in scope**: the sync verb that reports success and does no work; the+ absent-config substitution that presents as a valid empty pack; the active-pack+ reader that reports a path it never checks.+- **Depends on**: Task 0.++### Task 2: Typed negative recall with a coverage receipt (U2)+- **Files**: new `src/core/brain/negative-recall.ts`; `src/mcp/search-tools.ts`+ (optional output block on the recall gate, computed only when the query yields+ no usable result); `src/core/brain/continuity/types.ts` (one new record kind);+ new `tests/core/brain/negative-recall.test.ts`; extend the recall-gate handler+ and telemetry tests.+- **Acceptance**: the receipt is deterministic over a fixed index snapshot and+ moves when the document count, chunk count or embedding signature moves;+ building a receipt over a non-existent index throws rather than returning a+ zero-count receipt; zero results over a healthy index give `not_found` with a+ receipt attached; no index gives `unknown` with the index-absent reason and no+ receipt; stale embeddings give `unknown` with the index-stale reason; a+ configured note root the index does not cover gives `unknown` with the+ coverage-divergent reason and names the root; asserting `did_not_happen` with+ no retraction evidence throws rather than being downgraded; a tombstoned or+ superseded claim gives `did_not_happen` with a receipt.+- **Depends on**: Task 0.++### Task 3: Reverse stale-dependency audit (U3)+- **Files**: new `src/core/brain/stale-dependency.ts` (collector) and new+ `src/core/brain/doctor/stale-dependency-check.ts` (pure join plus registry+ entry); `doctor.ts` registry; `diagnostics.ts` signal table; `wikilink.ts`+ gains the identifier-prefix helper and two call sites are repointed;+ `doctor/records.ts` gains the retired-record read; new+ `tests/core/brain/doctor/stale-dependency-check.test.ts`.+- **Acceptance**: a consumer written before a retirement is reported and one+ written after is not, on a strict comparison; a receipt naming the pre-retirement+ identifier joins the retired record through its alias; the bare, wikilink and+ path spellings of one subject fold to one row; a retired artifact citing another+ retired artifact is not reported; the retirement's own log entry and back-pointer+ do not self-flag; a vault with retired states and no receipts at all reports+ not-recorded with an empty row set, distinguishably from a clean result; an+ unreadable continuity directory leaves the other checks intact and surfaces an+ uncertainty entry naming the consequence; the per-state consumer cap reports the+ true total rather than a silent prefix.+- **Defects in scope**: the decision-receipt directory read that conflates+ unreadable with absent, and the duplicate-append it causes.+- **Depends on**: Task 0.++### Task 4: Code-index health exit and the shared cron recipe (U4)+- **Files**: new `src/cli/cron-recipe.ts` (kernel extracted from the search+ template); `src/cli/search-cron-template.ts` (re-exports every existing name and+ delegates); new `src/cli/partner-codegraph-cron.ts`; `src/cli/partner.ts` (new+ verb, new health-exit flag, both usage strings); `src/cli/command-manifest.ts`;+ `src/core/partner/codegraph.ts` (partner CLI vocabulary hoisted to one frozen+ constant); extend `tests/cli/search-cron-template.test.ts` with a pinned+ fixture; new `tests/cli/cron-recipe.test.ts` and+ `tests/cli/partner-codegraph-resync.test.ts`.+- **Acceptance**: the existing template's output is byte-identical to a pinned+ fixture after the extraction; the resync recipe emits the interval as cron, the+ recipe name, the scheduler recipe and the external indexer command; running the+ verb writes nothing anywhere, proved by comparing directory listings before and+ after; omitting the template flag exits with a usage error and does not run an+ indexer; the health flag exits non-zero when health is bad and the verb's+ default behaviour is unchanged without it; in the emitted script the+ wrong-root guard precedes the indexer invocation and the missing-parser branch+ exits non-zero.+- **Defects in scope**: the report verb that always exits zero; the five inline+ copies of the partner CLI vocabulary, two of which are the same sentence written+ twice.+- **Depends on**: Task 0.++### Task 5: Trigger suppress and unsuppress (U5)+- **Files**: `src/core/brain/triggers/types.ts` (new status, the two status+ partitions move here, four new record fields); `triggers/store.ts` (parse and+ render the new fields, block reason, recurrence writer, two new transitions);+ `src/cli/brain/verbs/trigger.ts` (verbs, JSON projection, suppressed count, the+ nested-ternary verb map replaced by a constant map);+ `src/mcp/brain/workspace-tools.ts` (operations, error text, the status enum+ sourced from the shared list, JSON projection); help text, CLI reference and+ how-it-works; extend the trigger store and MCP tool tests; new+ `tests/cli/brain-trigger.test.ts`.+- **Acceptance**: suppressing blocks recreation a year later with the suppressed+ reason; three scans against a suppressed twin leave a recurrence count of four+ and the last-seen instant of the last scan; a materially different finding keys+ differently and is created normally while the twin is suppressed; dismiss then+ suppress then unsuppress restores the dismissed status with its original+ resolution instant and its original cooldown arithmetic; unsuppressing something+ that is not suppressed throws naming its actual status; suppressing twice is+ idempotent; a suppressed trigger never reaches the morning brief; the tool's+ status enum equals the shared status list.+- **Defects in scope**: three hand-maintained copies of the status partition; the+ fourth copy of the status list as a schema literal; the malformed+ grounding-artifact list that degrades to empty; the verb map that routes an+ unknown verb to the act transition.+- **Depends on**: Task 0.++### Task 6: Derived-store coverage in the snapshot archive (U6)+- **Files**: `src/core/brain/path-constants.ts` and `paths.ts` (the derived-store+ literal becomes a constant and gains a snapshot path helper);+ `src/core/brain/manifest.ts` (optional derived-store field with a named+ exclusion vocabulary, validated on read); `src/core/brain/snapshot.ts` (options+ bag, archive step, new typed error, list and prune and restore); policy+ lifecycle block, defaults, config template; `src/cli/brain/verbs/rollback.ts`;+ help text and how-it-works; extend the snapshot, manifest, snapshot-gate and CLI+ tests.+- **Acceptance**: with the default configuration no store archive is written and+ the manifest records not-requested together with the live store size; enabled+ over a valid store, the archive is written and its digest matches the manifest;+ enabled with the store absent, integrity-faulted, or over the size ceiling, the+ snapshot throws with the corresponding reason and leaves no partial archive+ behind, and the destructive-snapshot gate consequently does not run the+ operation; pruning removes the store archive alongside the tar and the sidecar;+ a sidecar written before this feature parses and renders as unknown rather than+ excluded; restoring a snapshot that included the store swaps it under the writer+ lock and says so, and restoring one that did not says that too.+- **Defects in scope**: the gzip fallback that silently overwrites an existing+ archive while the collision-resolution logic depends on refusal; the artifact+ directory archived and hashed despite being documented as never backed up; the+ version literal repeated in four places; the empty conditional, the unused+ parameter behind a lint suppression, and the statement keeping a dead import+ alive.+- **Depends on**: Task 0.++### Task 7: Typed lifecycle history and the log surface (U7)+- **Files**: `src/core/brain/types.ts` (snapshot-reason vocabulary and one new log+ event kind); `manifest.ts` (optional reason field);+ `src/core/brain/snapshot.ts` (stamp the reason, emit the log event);+ `snapshot-gate.ts` (extract a reusable take-snapshot entry point, require a+ reason, repoint five call sites and replace three inline label literals);+ `src/cli/brain/verbs/snapshot.ts` (new subcommand); `rollback.ts` (reason+ column); command manifest, help text, how-it-works; extend the types, snapshot,+ manifest, snapshot-gate and CLI tests.+- **Acceptance**: creating a snapshot stamps its reason into the sidecar and emits+ exactly one log event carrying the run id and the reason; a log-append failure+ does not fail the snapshot; a sidecar with no reason reads as null rather than+ being guessed from the run-id prefix; an invalid reason fails the manifest+ closed, consistent with the existing rule; the new subcommand lists newest+ first, filters by reason, rejects an unknown reason with a usage exit, honours+ a limit, and exits zero on an empty snapshot directory; the extracted entry+ point and the gate produce byte-identical archives for the same input.+- **Defects in scope**: the snapshot diff classifier that predates per-device log+ sharding and mislabels both the sharded markdown and the machine-primary log.+- **Depends on**: Task 6 (both add an optional manifest field and both touch the+ same list and restore surfaces; sequencing them avoids a merge of two partial+ shapes).++### Task 8: Operator standing rules and loud truncation (U8)+- **Files**: `src/core/brain/path-constants.ts` and `paths.ts`; new+ `src/core/brain/standing-rules.ts`; `src/core/brain/text/text-budget.ts` (the+ notice becomes a function of the truncation report as well as a string);+ `src/core/brain/active-budget.ts` (the constant notice becomes a function that+ names the dropped sections); `hooks/active-inject.ts` (compose the block outside+ the fail-open boundary, first, metered as an exempt source, and amend the+ docblock that currently claims a different head of payload);+ `src/mcp/brain/context-tools.ts` (prepend on every return path including the+ error branch, plus an optional response key); policy active block, defaults,+ config template; how-it-works; new standing-rules, uneditability and+ context-surface tests; extend the text-budget, active-budget and injection-hook+ tests.+- **Acceptance**: the injected preamble begins with the standing block and the+ memory body follows; with no active memory file the block is still emitted;+ when memory assembly throws and no cache exists the block is still emitted and+ the hook exits zero; with the budget at its minimum and an oversized rules file,+ the block is emitted whole and only the memory body carries a truncation notice;+ an over-cap rules file is cut on a line boundary and its notice names the kept+ and total line and character counts and the path; an unreadable rules file+ throws naming the path and does not return null; a body of non-Latin text+ round-trips byte-identically and produces the same counts as a Latin body of+ equal length; each caller-named write tool refuses the rules path and leaves the+ bytes unchanged; no tool name, description or schema property mentions the path;+ an over-budget memory body's notice names the sections that were dropped.+- **Defects in scope**: the truncation report computed and discarded one line+ before the return; the vault-instruction reader whose configuration errors are+ swallowed into null.+- **Depends on**: Task 0.++### Task 9: Documentation, changelog and version+- **Files**: `README.md` if a described capability changed; `CHANGELOG.md` under+ one new version heading with its comparison link; `package.json`; every mirrored+ manifest via the version sync script.+- **Acceptance**: the sync check passes; the changelog entry names what shipped,+ what was refused and why, in the shape the two preceding releases use; the+ changelog heading and the package version agree.+- **Depends on**: Tasks 0 through 8.diff --git a/docs/brainstorm/silence-is-not-an-answer/variants.md b/docs/brainstorm/silence-is-not-an-answer/variants.mdnew file mode 100644index 00000000..47f96e7c--- /dev/null+++ b/docs/brainstorm/silence-is-not-an-answer/variants.md@@ -0,0 +1,108 @@+# Silence is not an answer - variant audit trail++**Consultant:** Claude Code CLI (`claude -p`), single pass, exit 0, three parseable+variants plus a recommendation. The fallback consultant (`codex exec`) was not+run: the playbook invokes it only when the primary exits non-zero or returns+fewer than two parseable variants, and neither condition held.++**Question put to the consultant:** not "how do I build unit N", but how to+structure a wave in which eight independently-scoped units each reinvent the+same primitive - a closed verdict vocabulary where "could not check" is a+first-class value distinct from both "checked and clean" and "checked and bad".+The full prompt, including the grounded state of all eight units, is in+`cli-output/prompt.md`; the raw reply is in `cli-output/claude.md`.++---++## Consultant output, verbatim++### Variant 1: Kernel-first โ one verdict-and-digest foundation landed ahead of the eight++- **Approach**: Open the branch with two leaf modules before any unit: a `Verdict` kernel (frozen vocabulary where `unverified` is a member alongside checked-clean and checked-bad, each carrying a reason code drawn from a single registered table) and a `digest` module that absorbs the ~10 private SHA-256 copies, the 16 inline sites, the 3 ad-hoc truncation lengths and the 2 canonical-JSON implementations behind named constants. All eight units then express their local vocabulary as a parameterisation of the kernel โ U1's `ok`/`modified`/`unverified`, U2's `not_found`/`unknown`/`did_not_happen`, U6's `included`/`excluded_because`/`unknown-because-predates`, U3's `recorded: false` โ and every read surface renders through one renderer.+- **Trade-offs**:+ - Pro: the two persisted digest decisions (U1's schema-pack digest, U2's coverage receipt) are made once, by one module, with one truncation constant โ under the additive-only rule a divergence here would be permanent across replicated peers.+ - Pro: the reason axis becomes census-enforceable in the existing signal table from day one; a unit that invents an unregistered reason fails the build rather than shipping a private string.+ - Pro: the digest consolidation is a debt the wave has to touch anyway; doing it once at the front is cheaper than eight partial touches.+ - Con: the wide half of the kernel is a god-type risk. U5's `suppressed` is a lifecycle status with a recurrence counter, U7's snapshot reason is a causal vocabulary, U8's truncation notice is a payload naming dropped items โ forcing all three into one verdict shape produces a type whose members do not mean the same thing, and that shape survives the release.+ - Con: the largest single-PR blast radius of the three: ~26 pre-existing digest call sites refactored in the same diff as eight features, so an unrelated regression in the digest sweep can block the whole wave.+ - Con: a leaf module consumed by schema, recall, doctor, snapshot, trigger and injection layers is a new central dependency in a codebase that recently spent a release removing all import cycles.+- **Complexity**: large+- **Risk**: medium++### Variant 2: Narrow shared kernel โ share the reason axis and the digest bytes, keep every verdict vocabulary local++- **Approach**: Split the primitive along its two axes and share only the one that is genuinely identical across the eight. The reason axis โ the named, machine-readable *why-could-not-check* code โ is an extension of the existing closed could-not-check condition vocabulary, widened into a leaf registry that the census test already enforces; the digest module is consolidated as in Variant 1 because two units persist digests. The verdict axis stays local to each unit: eight small frozen vocabularies with their own arity and their own exhaustive switches, each obliged to carry a reason code from the shared registry on its unverifiable member.+- **Trade-offs**:+ - Pro: directly satisfies "prefer extending an existing surface to adding a parallel one" โ the could-not-check vocabulary and the existing `pass`/`warn`/`fail` mismatch renderer are the precedents, and this widens them rather than standing up a rival.+ - Pro: smallest surface that can still be wrong. If the shared piece turns out wrong halfway, the reason registry is additive by construction and only U1 and U2 depend on the digest module, so rework is two units, not eight.+ - Pro: keeps arity honest. U3 needs `recorded: false` versus `rows: []`, U4 needs a non-zero exit code, U5 needs a status plus a counter โ none of these is a tri-state, and none has to pretend to be.+ - Pro: the repeated-constant convention is satisfied where the repetition is real (reason codes, digest algorithm, truncation length) without inventing repetition where it is not.+ - Con: eight local vocabularies means eight exhaustive switches and eight renderer adapters; the family resemblance is enforced by convention and review, not by the compiler.+ - Con: U5's status partition is currently hand-maintained in three copies across core, CLI and MCP โ this variant fixes that within U5 but does not give the wave a general mechanism preventing the next such triplication.+ - Con: the boundary between "reason" and "verdict" has to be adjudicated per unit and one or two will be arguable (U6's `unknown-because-predates-the-feature` is arguably a reason wearing a verdict's clothes).+- **Complexity**: medium+- **Risk**: low++### Variant 3: Local-first with an enforced census โ eight private vocabularies, one ratchet, harvest in a later wave++- **Approach**: Ship each unit with its own frozen vocabulary, its own reason strings and its own digest call, sharing nothing new; the only cross-cutting addition is a census/ratchet test that requires every new verdict member and every reason code to be registered in the existing diagnostic signal table, plus a written refusal in the release notes naming the shared kernel as deliberately not built and why. The eight then serve as the eight real call sites a later refactor wave needs in order to design the kernel from evidence rather than from anticipation.+- **Trade-offs**:+ - Pro: maximum unit independence โ the eight can be built and reviewed in any order, and a stalled unit blocks nothing else in the branch.+ - Pro: zero wrong-kernel cost. There is no shared piece that can turn out wrong halfway.+ - Pro: the refusal is shippable release content in the project's established style, so the decision is recorded rather than silently deferred.+ - Con: two units persist a digest, independently choosing algorithm and truncation length. Under additive-only on persisted formats, two divergent digest encodings in one release are permanent for replicated peers โ this is the one place where the repetition is not merely untidy.+ - Con: leaves the ~10 SHA-256 copies and 2 canonical-JSON implementations at 12 and 18, in a wave whose stated theme is that duplicated silence-handling is the defect.+ - Con: sits against two written conventions at once ("anything repeated goes into a named constant", "no new subsystem where an existing one can carry the capability") โ the census test makes the duplication visible but does not make it legal.+ - Con: the later harvest wave has to touch all eight units again, and by then their vocabularies are released and additive-only.+- **Complexity**: small per unit, large in aggregate+- **Risk**: high++### Recommended: Variant 2++**Rationale**: The eight units genuinely share the *reason* axis and the digest bytes, and they genuinely do not share the verdict axis โ a suppression status with a recurrence counter, an exit code and a coverage receipt are not the same type, and a kernel that claims they are would outlive the release under the additive-only rule. Variant 2 shares exactly the two things whose divergence would be permanent and unfixable across replicated peers (one digest encoding, one registered reason vocabulary), extends existing precedents instead of standing up a parallel one, and confines mid-wave rework to the two digest consumers if the shared piece proves wrong โ whereas Variant 1 bets the whole wave on a wide type designed before its call sites exist, and Variant 3 buys independence by shipping two irreconcilable persisted digests.++---++## Orchestrator decision++**Variant 2 is adopted, with one override.**++The recommendation is correct about where the sharing is real. Two of the eight+units persist a digest, and the vault is replicated peer-to-peer: two divergent+digest encodings shipped in one release cannot be reconciled later without+breaking a guarantee for peers that already wrote records under the old one.+That is the single place in this wave where duplication is not untidiness but+permanence, and it is the reason the digest module lands before the units rather+than beside them.++The recommendation is equally correct that the verdict axis is not shared. A+suppression status carrying a recurrence counter, a process exit code, a+coverage receipt bound to a document set, and a snapshot-inclusion decision are+four different types. A kernel asserting they are one type would have to be+widened for every arity it did not anticipate, and under the additive-only rule+it would outlive the release that introduced it.++**The override:** the consultant proposes carrying the shared reason axis by+widening the existing could-not-check condition vocabulary. Grounding shows that+vocabulary is consumed by exhaustive switches with `never` defaults, so adding a+member is a compile-breaking edit for consumers that have nothing to do with+this wave - it is the wrong host precisely because it is well-typed. The reason+codes are also disjoint in meaning across the eight: an absent config file, a+divergent coverage set, and an over-size-ceiling refusal are not members of one+concept, and a union of disjoint sets is a namespace, not an abstraction.++So the reason axis is shared as a **shape and a census**, not as a vocabulary.+Each unit owns a frozen object plus a companion `Set` plus a type guard, which+is already the project's convention; one census test imports all of them and+fails when the trio is incomplete, when the `Set` and the object disagree, when+the guard admits a non-member, or when one vocabulary carries a duplicate value.+That buys the property the consultant valued - no unit ships a vocabulary whose+members and guard can drift apart - at the cost of one test file instead of one+central type. It does not require codes to be unique across vocabularies:+an absent config file and an absent store file are both honestly named `absent`.++**What this costs if it is wrong:** the digest module has exactly two persisted+consumers, so a wrong encoding is a two-unit rework, and it is caught by their+own round-trip tests before anything is released. The census test is a test; if+it proves to be the wrong shape it is deleted without touching a single shipped+byte. Neither failure mode can stall the other seven units.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 4dcfaa7a..c70e605e 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -45,8 +45,9 @@ o2b brain pin / unpin (CLI-only) Toggle pinned: true on a preference (exo2b brain set-primary (CLI-only) Declare or clear primary_agent in Brain/_brain.yaml (--clear)o2b brain protect (CLI-only) Emit / apply native deny rules for Brain/ (--target {claudecode|codex} [--apply])o2b brain unprotect (CLI-only) Remove the Open-Second-Brain-managed deny rules for the chosen target+o2b brain snapshot log (CLI-only) Newest-first listing of every recovery point: run id, created_at, typed reason, size, manifest presence, derived-store coverage; --reason filters (unregistered value exits 2), --limit caps, --jsono2b brain snapshot diff (CLI-only) Read-only diff between two snapshots, or snapshot vs live Brain/-o2b brain rollback (CLI-only) Restore Brain/ from a pre-dream snapshot (--dry-run previews; drift abort vs --force-rollback)+o2b brain rollback (CLI-only) Restore Brain/ from a snapshot (--dry-run previews; drift abort vs --force-rollback); --list, the prompt and --json name the snapshot reason ('unknown' when the sidecar records none)o2b brain upgrade (CLI-only) Migrate release-owned files forward (_brain.yaml, _BRAIN.md, _OPEN_SECOND_BRAIN.md); --dry-run / --check / --apply --yeso2b brain export Read-only dump of active preferences (--format json|llms-txt [--out <path>] [--force])o2b brain explorer (CLI-only) Force-directed HTML graph of Brain/preferences + retired; live HTTP on 127.0.0.1 or --export <path> single-file. Keyboard-accessible listbox + localStorage layout persistence. Double-click a node to open it in Obsidian (live mode).@@ -58,6 +59,8 @@ o2b brain morning-brief Read-only session-start summary (since v0.21.0): to2b brain codec Deterministic lossless session codec (since v0.22.0): --compress | --expand over stdin or --in <file>; structured content preserved byte-for-byteo2b brain sources Read-only dashboard of signals by (agent, source_type) (since v0.22.0): active/processed + distinct-topic counts; --jsono2b brain schema Runtime schema report/admin (since v0.26.0): report|stats|lint|graph|explain|orphans|apply|sync; mutation writes are locked and audited+ report names the pack's integrity: `ok` (digests to what the newest audited apply recorded), `modified` (with both digests), or `unverified` with the reason - `no-apply-recorded`, `audit-unreadable`, or `config-absent`. The digest is over the rendered `schema:` block, so comment and whitespace churn elsewhere in `_brain.yaml` never moves it+ sync is NOT implemented and exits non-zero. It previously returned `{updated: 0, skipped: 0}` with a "no backfill was required" note without reading the vault at all, so a caller could not tell "nothing needed doing" from "nothing was done"o2b brain schema apply --mutation '<json>' (repeatable) applies audited, locked mutations to Brain/_brain.yaml; --actor NAME --reason TEXT annotate the audit record--dry-run previews instead (since v1.43.0): it returns the pack that would result plus its leaf-level diff and writes nothing at all - no config write, no audit record, no lock file. Before v1.43.0 `apply` parsed the flag and mutated anyway. The preview runs the same pack validator the apply runs, but NOT the two checks that exist only because the apply writes (the vault-identity write guard, and the atomic writer's re-parse of the rendered YAML), so a batch that renders to unparseable YAML previews clean and fails on applyo2b brain watchdog Probe Brain config/dirs/search index and plan safe recovery (since v0.26.0): --remediate [--dry-run], --restore <run_id> [--force-restore], --json@@ -156,7 +159,7 @@ o2b brain source add <vault> --alias <name> | list | remove <alias>o2b brain links normalize [path-prefix] [--mode preserve|full|short] [--write] [--json] - wikilink path format rewrite; dry-run by default; config key wiki_link_formato2b brain profile [--stale-seconds N] [--force] [--json] - materialize Brain/profile.md digest + .o2bfs root marker (age-gated)o2b brain sgrep <query> [path-prefix] [--limit N] [--keyword-only] [--json] - grep-shaped semantic search; path:line: lines; exit 1 on no matches-o2b brain trigger scan | list [--status S] | ack <id> | dismiss <id> | act <id> | history [--json] - grounded trigger queue; cooldown via trigger_cooldown_days (default 7)+o2b brain trigger scan | list [--status S] | ack <id> | dismiss <id> | act <id> | suppress <id> | unsuppress <id> | history [--json] - grounded trigger queue; cooldown via trigger_cooldown_days (default 7); suppress silences a finding indefinitely and unsuppress restores the status it interrupted; list reports the suppressed count; scan, list and history all print `unreadable: <n>` followed by one line per record the store could not parse - printed at zero too, so an omitted line can never read as a clean queue, and printed BEFORE "no open triggers" so that line is never the only thing said about a queue holding something unparseableo2b brain deep-synthesis <topic> [--limit N] [--triggers] [--json] - deterministic topic dossier: agreements, contradictions, stale claims, knowledge gaps, plus a strongest-objection steelmano2b brain ideas [--cap N] [--triggers] [--json] - ranked next-direction candidates from open questions, orphan notes, aging signalso2b brain recall-telemetry gate-list | gate-summary [--host <name>] [--since <iso>] [--until <iso>] [--limit <n>] [--json] - recall-gate decision telemetry (recall_gate_telemetry, default off)@@ -567,9 +570,16 @@ See [`hermes-cron.md`](hermes-cron.md) for the cron envelope and Telegram deliveReports on external code-project partners. Strictly read-only: never installs, initializes, extracts, or mutates a partner index or the vault.```text-o2b partner codegraph report Resolve the in-scope code project and report the codegraph index state (no_project | absent | not_indexed | indexed with node/file/edge counts | error) plus a structural Cargo.toml workspace-member list. When indexed, runs a read-only, non-blocking graph-health gate (index.health) that flags empty-graph, collapsed-edges, dangling-references, self-loops, and cache-root-mismatch before labeling/import/recall trust the graph. Non-Rust projects report cargo_workspace: null with a reason. --vault sharpens the scan scope; --json emits the schema-versioned report+o2b partner codegraph report Resolve the in-scope code project and report the codegraph index state (no_project | absent | not_indexed | indexed with node/file/edge counts | error) plus a structural Cargo.toml workspace-member list. When indexed, runs a read-only, non-blocking graph-health gate (index.health) that flags empty-graph, collapsed-edges, dangling-references, self-loops, and cache-root-mismatch before labeling/import/recall trust the graph. Non-Rust projects report cargo_workspace: null with a reason. --vault sharpens the scan scope; --json emits the schema-versioned report; --fail-on-health exits 1 unless the index is present AND its health gate is clean, so a scheduled job can branch on it (without the flag the exit stays 0 whatever the report says)+o2b partner codegraph resync Print a cron recipe that re-indexes the in-scope code project whenever its commit moves. --cron-template is REQUIRED (there is nothing else this verb does, and it never runs an indexer); --interval accepts <N>m|h|d and defaults to 6h; --project names the repository instead of resolving it from the scan; --vault sharpens that scan. Output is text on stdout and nothing else: the emitted script aborts on a cache-root-mismatch health warning, aborts when jq is missing rather than matching the report loosely, skips quietly when the commit is unchanged, invokes codegraph itself, and records the commit in a stamp under ${XDG_STATE_HOME:-$HOME/.local/state}/open-second-brain only after a --fail-on-health check passes```+Every write in the resync recipe is a shell command the operator's own+crontab runs on the operator's own host. Open Second Brain never installs,+initializes, or writes data for codegraph, and rendering the recipe creates+nothing - which is also why there is no maintenance-lane task that re-indexes+on its own.+## Search```text@@ -603,6 +613,12 @@ o2b search focus clear Clear the persisted focus file next to the searcho2b search reindex Rebuild the SQLite + FTS5 index from scratch(required after upgrading to v0.13.0 recall schema or v0.26.0 CJK FTS content)--force-cost bypasses the embedding cost gate for this run (since v0.36.0)+ --embeddings computes vectors; --concurrency N, --db PATH, --verbose+ --cron-template prints a periodic-reindex cron recipe on stdout and+ writes nothing at all (no index run, no file, no scheduler entry)+ --interval <N>m|h|d sets that recipe's cadence, default 30m; an interval+ cron cannot express (seconds, 60m+, 24h+, 28d+) is refused with the+ reason rather than rendered as a schedule that means something elseo2b search index Incrementally update the index; --embeddings computes vectors--force-cost bypasses the embedding cost gate (since v0.36.0)o2b search vector-backfill Run the vector phase ALONE for indexed chunks that have no vector -diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 1163169b..131bdf0b 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -441,6 +441,25 @@ flowchart LRnet-negative). Rendered top-N (`lessons.limit`, default 20), rankedby decayed salience. Regenerated at the tail of every `dream` passalongside `active.md`, with the same idempotent write.+- **`Brain/standing-rules.md`** is the one preamble lane the operator+ writes by hand. It is injected **first**, ahead of the runtime+ notices and every recalled body, under a header stating that it takes+ precedence over them. It is **exempt** from the injection budget and+ capped by its own `active.standing_rules_max_chars` (default 4,000);+ a capped block says how many lines and characters survived out of how+ many, and names the file. Because it is read outside the fail-open+ memory load it survives a memory-layer failure and is never written to+ the inject cache, so a stale copy can never be served in its place. If+ the file cannot be read, the block says so and states that no standing+ rules are in force - it never degrades to silence. Two mechanisms, not+ one, keep it out of an agent's reach, and the claim is exactly as wide+ as they are: the file sits under `Brain/`, whose first path segment the+ note-target resolver refuses for the four caller-named note-write tools+ (`brain_create_note`, `brain_update_note`, `brain_append_note`,+ `brain_write_batch`), and `brain_labels` - which takes a caller-named+ path but resolves it through the weaker containment-only resolver - is+ refused by a named guard that knows this one file. Nothing generates or+ rewrites it.- **SessionStart hook** (`startup | resume | clear | compact`) injectsthe body as `additionalContext` so the agent sees current rules atthe start of every session and again after `/compact` - the@@ -448,11 +467,18 @@ flowchart LRevent no longer exists in current Claude Code. The injected body isbudgeted (`active.inject_budget_chars`, default 8,000 chars):sections drop deterministically (recently retired first, then- quarantine, then most-applied) and a one-line notice points the- agent at `brain_context` for the full set. When `Brain/lessons.md`+ quarantine, then most-applied) and a one-line notice names the+ sections that were dropped, how many characters survived out of how+ many, and points the agent at `brain_context` for the full set. When `Brain/lessons.md`exists, its (separately budgeted) body is appended so the unified- lessons corpus loads on the same surface. Fails closed - any error- path exits 0 with no output so the runtime proceeds unaffected.+ lessons corpus loads on the same surface. Fails soft - every error+ path in the memory lane exits 0 and the runtime proceeds unaffected,+ emitting no memory context. The standing-rules block is the one+ exception, by design: it is read outside that boundary, so a vault+ with an operator rules file still speaks even when the memory layer+ is down, and a rules file that cannot be read is stated rather than+ skipped. The hook emits nothing at all only when there are NEITHER+ standing rules NOR memory.- **MCP Resources** expose the same content for hosts that preferpull access (`osb://preferences/active` and friends in the tableabove). The MCP `initialize` reply advertises the `resources`@@ -461,7 +487,9 @@ flowchart LRwriter-scope MCP server. Runtimes that lack a `SessionStart` hook_and_ do not auto-load MCP resources (Cursor, Aider, raw ClaudeAPI) can fetch the same `active.md` body, pinned current-task context,- and active-preference counts with a single tool call.+ and active-preference counts with a single tool call. The standing-rules+ block leads that content too, and rides an optional `standing_rules`+ key (path, content, truncated) omitted when the file is absent.- **`Brain/pinned.md`** is a transient scratchpad for current-task facts.Agents update it through `brain_pinned_context` when a fact should survivecontext rotation but should not become a durable preference. Clearing it@@ -550,12 +578,18 @@ flowchart TD```A snapshot captures every file under `Brain/` **except** `.snapshots/`-itself โ otherwise rollback would erase any snapshots taken after-this one. Retention defaults to ten newest archives.+and `.artifacts/` โ the first because rollback would otherwise erase+any snapshots taken after this one, the second because it is TTL'd MCP+tool output documented as never backed up (archiving and hashing it+made unrelated cache churn trip the drift gate). Retention defaults to+ten newest archives.From v0.10.6 every snapshot ships with a SHA-256 sidecar manifest(`Brain/.snapshots/<run_id>.manifest.json`) listing every regular-file under `Brain/` and its hash. `o2b brain rollback` reads the+file the snapshot **covers** โ the same tree, minus the two excluded+entries named above โ and its hash. Hashing a file the archive does+not contain and the restore does not replace would fire the drift+gate on churn no rollback could ever undo. `o2b brain rollback` reads thesidecar back, rebuilds a fresh manifest from the live tree, andcompares: any added / removed / changed entry aborts the rollbackwith exit code 2 and a compact drift report on stderr. The intent@@ -570,9 +604,147 @@ archives still recover cleanly. The same sidecar primitive backs`src/core/brain/manifest.ts` as the single source of truth for"what does `Brain/` look like right now".+### Derived-store coverage++The derived SQLite store (`<vault>/.open-second-brain/brain.sqlite`)+is a sibling of `Brain/`, not a member of it, and it used to be in no+snapshot, no manifest and no rollback โ with nothing saying so, so a+pre-restore diff rendered a complete-looking picture while the+embeddings silently stayed at whatever the live store held.++What coverage protects is **spend, not information**. Feedback,+activation and tuning are replayable JSON folds inside `Brain/`; only+the embeddings and a tier baseline are database-only, so a lost store+costs an embedding bill and a reindex, never a fact. Against that:+retention keeps ten archives and `.snapshots/` rides the same+peer-to-peer replication as the rest of the vault, so every retained+copy lands on every device. Hence the three-part answer:++- **Opt-in.** `snapshots.include_derived_store` defaults to `false`.+- **A ceiling that refuses.** `snapshots.derived_store_max_bytes`+ (256 MiB by default) is compared against the live store and the+ snapshot **throws** when it is exceeded, naming the measured size.+ Half a database is not a recovery point, so it is never truncated.+- **The live store size in every manifest**, included or not, so an+ operator who has never enabled coverage still sees what it would+ cost.++When coverage is on, `createSnapshot` resolves the store path through+the search layer's resolver, refuses when the file is absent, takes the+**same writer lock** every indexer serialises on, runs the structural+integrity scanner and refuses a condemned store rather than archiving+it over a good snapshot, checks the ceiling, then `VACUUM INTO`s a+temporary file and compresses it to+`Brain/.snapshots/<run_id>.store.sqlite.zst`. `VACUUM INTO` rather than+a file copy because the store runs in WAL mode and the runtime exposes+no online-backup API. The archive sits **beside** the tar rather than+inside it: the extractor requires a `Brain/` root and the restore is+defined as "live `Brain/` equals archive `Brain/` minus the excluded+entries", so a second top-level tar member would break both contracts.+Keeping it in the same directory keeps listing and retention one+family with one loop.++Any of those steps failing is a **refusal**, not a skip: `createSnapshot`+throws and leaves no tar behind, so the destructive-snapshot gate โ+which already aborts before the operation when the snapshot throws โ+simply does not run the mutation it could not fully protect.++The manifest records what happened under an additive `derived_store`+key **at the existing schema version** (bumping it would make every+older peer silently lose drift detection on new snapshots): whether it+was included, the resolved source path, the archive name, the digest+over the archived bytes, the compressed size, the live store size+always, and one of four named exclusion reasons โ+`not-requested`, `absent`, `integrity-fault`, `over-size-ceiling`.+A sidecar with **no** `derived_store` key predates the feature and+renders as `unknown`, never as excluded.++Retention deletes the store archive alongside the tar and the sidecar.+`rollback` replaces the store only when the manifest says it was+included, decompressing to a sibling temp file and renaming it into+place under the writer lock โ the same swap discipline the indexer+uses โ and prints in every case which answer applied: **replaced**,+**not restored** with the recorded reason, **record missing** when there+is no record but a store archive is sitting beside the tar (the sidecar+write is non-fatal, so coverage can run and leave nothing behind saying+so), or **unknown** when there is neither a record nor an archive. The+third and fourth used to share one sentence that named the feature as+absent while the feature's own archive was on disk.++### Why a recovery point was taken++Two histories existed here and did not join. The Brain event log is+richly typed, per-device sharded and machine-primary, and it recorded a+`rollback`; the snapshot family is the only **revertible** history, and+every entry in it was an opaque run id plus an mtime. The reasons existed+de facto โ as run-id **prefixes** at five call sites, three of them inline+string literals โ and nothing parsed them back, so an operator could not+ask which recovery point covers a given boundary, could not filter the+revertible history by why it happened, and could not walk from a logged+event to the archive that would undo it.++Every snapshot now carries a typed reason from one closed vocabulary+(`BRAIN_SNAPSHOT_REASON`): `dream`, `upgrade`, `import-claude-memory`,+`delete-by-source`, `entity-prune` for the five destructive call sites,+plus four members with **no producer in this release** โ+`session-boundary`, `plan-boundary`, `decision-boundary` for boundaries a+later release may snapshot at, and `manual`, because nothing takes a+recovery point on demand: no CLI verb and no MCP tool does, and the+take-snapshot entry point is reached only by the destructive-operation+gate. The reason is required by+`createSnapshot`, doubles as the run-id prefix so the filename and the+recorded provenance can never disagree, and is stamped into the manifest+sidecar as an additive `snapshot_reason` key **at the existing schema+version** โ same reasoning as the derived-store key: bumping it would make+every older peer silently lose drift detection on new snapshots.++A sidecar with **no** reason reads as `unknown` and the reason is **never**+reconstructed from the run-id prefix that happens to spell it. That+inference would look correct on almost every archive this project writes,+and would manufacture provenance for an unstamped, hand-named or+third-party archive at exactly the moment an operator is deciding whether+to overwrite their live tree with it. An unregistered reason fails the+whole manifest closed, as one malformed file entry already does.++Each created recovery point also emits one `snapshot` log event carrying+the run id, the reason and the archive size โ the counterpart the log has+been missing since `rollback` shipped, which recorded the restore while+the point it restores to left no trace but a filename. The append is+best-effort: `createSnapshot` runs before the mutation the+destructive-snapshot gate protects, so a throw would turn a lost audit+line into a refused mutation.++Taking snapshots **at** session, plan and decision boundaries is+deliberately **not** shipped. That changes how often snapshots happen,+which interacts with retention and with the optional derived-store+archive. An **on-demand** snapshot verb is not shipped either, for its+own reasons: every recovery point this build takes exists to protect a+specific mutation that is about to run, and an operator-triggered+snapshot is a separate decision about retention pressure and about what+an operator does with a point nothing was going to overwrite. The+vocabulary carries all four members anyway so this build can read a+sidecar a later release writes and replicates back โ which also means+`snapshot log --reason manual` is a valid filter over a history that,+in this release, no local operation can add to.+### Read-only inspectors over the snapshot family-Two CLI surfaces share the same diff renderer over the snapshot+With `snapshot log` the family is complete: **log / diff / revert**.++- **`o2b brain snapshot log`** โ newest-first listing of every recovery+ point (by archive mtime, because a hand-named run id carries no+ timestamp to sort on): run id, created-at, reason, archive size,+ whether a drift manifest is present, and the derived-store record.+ `--reason <reason>` filters by why it happened and rejects an+ unregistered value with a usage exit (2) rather than an empty listing,+ which would say "you have no such snapshots" when the truth is "that is+ not a reason". `--limit <n>` caps the listing, `--json` yields the+ structured rows. An empty snapshots directory exits 0; a snapshots+ directory that exists and **cannot be read** exits non-zero naming the+ path, because "no snapshots available" over an unenumerable directory is+ the same substitution one line up.++Two further surfaces share the same diff renderer over the snapshotextraction primitive (`extractSnapshotToTemp`), so previewing andauditing stay byte-equal:@@ -585,6 +757,10 @@ auditing stay byte-equal:supplied (and snapshot โ live when only one is). `--json` yieldsthe structured `BrainTreeDiff` payload for scripting.+`rollback --list`, the confirmation prompt and the `--json` result all+name the reason too โ it is the one fact that distinguishes two archives+minted seconds apart.+The diff classifies every file under each root into six artifactkinds (preference, retired, signal, log, config, other). Preferenceand retired files receive a typed field-level diff for the derived@@ -593,6 +769,17 @@ counters (`_status`, `_applied_count`, `_violated_count`,adjuncts); other kinds compare by byte equality and surface as`(body changed)`.+The `log` kind covers every shape the log path helpers write โ+`<date>.md`, `<date>.jsonl` and their per-device `<date>.<deviceId>.โฆ`+shards โ and it decides that through the recogniser in `log-jsonl.ts`,+the module whose contract is that the shard layout lives in exactly one+place. The differ used to carry a pattern of its own, which is how it+came to predate sharding and classify both the per-device markdown and+the machine-primary JSONL as `other`, mislabelling the surface a+`rollback --dry-run` is most likely to be showing. Ledgers and+subdirectories under `log/` (`capture-decisions.jsonl`, `dream-runs/`,+`pref-audit/`) are not days of the log and stay in the catch-all class.+## Primary agent declaration`Brain/_brain.yaml` carries an optional `primary_agent: <name> | null`@@ -893,11 +1080,44 @@ a compact `Brain/profile.md` digest plus a `.o2bfs` root marker, andProactive insight: `o2b brain trigger scan` converts semantic-healthand retention findings into Markdown trigger records under`Brain/triggers/` with a strict lifecycle (pending, delivered,-acknowledged, acted, dismissed, expired). Stable cooldown keys make-scans idempotent, and the morning brief delivers pending triggers at-most once per cooldown window - the Brain remembers what the operator-already saw, dismissed, or acted on instead of rediscovering it every-run. `o2b brain deep-synthesis <topic>` builds a deterministic topic+acknowledged, acted, dismissed, expired, suppressed). Stable cooldown+keys make scans idempotent, and the morning brief delivers pending+triggers at most once per cooldown window - the Brain remembers what+the operator already saw, dismissed, or acted on instead of+rediscovering it every run.++`dismissed` and `acted` carry a clock: after `trigger_cooldown_days`+the same finding may return. `suppressed` carries none, and it is the+answer for a finding the operator has judged structurally benign -+`o2b brain trigger suppress <id>` silences that cooldown key+indefinitely, from any state including an expired or already-acted+one. It is reversible: suppressing stamps the status it interrupted+and leaves the delivery and resolution instants untouched, so+`unsuppress` restores the original state together with its original+cooldown arithmetic rather than reconstructing them. A suppressed+trigger is terminal, so it is hidden from `list`, shown in `history`,+and never reaches the morning brief; `list` prints how many triggers+are currently suppressed so silence is always accounted for. Silence+is also audited: a scan whose candidate an existing record silenced -+suppressed, cooling down, still open, or dropped by the per-kind cap -+increments `occurrences` and stamps `last_seen_at` on that record, so a+suppressed finding that keeps firing is distinguishable from one that+never fired again. The count is per scan, not per candidate: one scan+seeing the same finding twice counts once, and a candidate silenced+before any record for its cooldown key existed has no ledger to write to+and is reported in the scan's skipped list instead.++A record nobody can parse is confined to itself. A hand-edited field is+still refused rather than degraded, but the refusal now names the file+and the field and stops there, so `list`, `history`, the brief, delivery,+a new scan and the transitions all keep working on the records that read+cleanly - the operator can still dismiss or suppress a healthy trigger+while a sibling is broken. Every read reports the records it could not+read next to the ones it could, and the morning brief says the queue is+unreadable rather than rendering the pending-trigger section as absent,+which used to be indistinguishable from an empty queue.++`o2b brain deep-synthesis <topic>` builds a deterministic topicdossier (agreements, contradictions, stale claims, knowledge gaps)and `o2b brain ideas` ranks next directions from open loops; both canenqueue their findings as triggers. Opt-in recall-gate telemetrydiff --git a/docs/mcp.md b/docs/mcp.mdindex ede5c28a..253a0fa6 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -407,6 +407,29 @@ generates deduped triggers from semantic-health and retention data,keep the same issue from reappearing while an earlier trigger is openor cooling down; `brain_brief` `view="morning"` surfaces capped pendingtriggers and marks them delivered (once per `trigger_cooldown_days`).+`suppress` silences a cooldown key indefinitely - it is legal from any+status and carries no clock, so the finding never re-nags - and+`unsuppress` restores the status suppression interrupted along with its+original cooldown arithmetic. Suppressed triggers are terminal: hidden+from `list`, present in `history`, never in the brief. A candidate an+existing record silenced increments `occurrences` and stamps+`last_seen_at` on that record, whatever silenced it - suppression, an+open twin, a cooldown window, or the per-kind cap - so silence is+auditable. Two limits are exact rather than implied: one scan seeing the+same finding twice counts once, so `occurrences` counts scans and not+candidates, and a candidate silenced before any record for its cooldown+key existed has no ledger to write to and is reported only in `skipped`.++One unreadable record never costs the operator the rest of the queue.+`scan`, `list` and `history` each return an additive `unreadable` array -+`path`, the frontmatter `key` at fault (`null` when the file itself could+not be read), and the refusal text - so a hand-edited record is named+instead of omitted, and the readable records stay listable and+transitionable while it is broken. `brain_brief` `view="morning"` carries+the same information as `triggers_unreadable` plus a+`trigger_queue_error` when the queue could not be read at all, and+renders both into the brief text: an absent pending-trigger section now+means the queue was read and held nothing.`brain_deep_synthesis` assembles a deterministic topic dossier(matched notes, agreements, contradictions, stale claims, knowledgediff --git a/docs/observability.md b/docs/observability.mdindex 9a27b5be..e0f62ff5 100644--- a/docs/observability.md+++ b/docs/observability.md@@ -36,6 +36,7 @@ Every continuity record shares one envelope, and exactly these eight fields in t| `recall_telemetry` | opt-in per call (`telemetry` option/param) | `packContext` (`mode: context_pack`), `buildPreCompressPack` (`mode: pre_compress`), `brain_search` MCP handler (`mode: search`), `brain_query` MCP handler (`mode: query`, since v0.40.0 - payload carries the query kind only, never the supplied preference id / topic / timestamp) || `context_receipt` | opt-in per call (`receipt` option/param) | `packContext`, `buildPreCompressPack` || `gate_telemetry` | config key `recall_gate_telemetry` (default off) | `brain_recall_gate` MCP handler |+| `negative_recall` | config key `recall_gate_telemetry` (default off - the SAME gate as `gate_telemetry` above, so one config decision governs both observations the recall gate makes) | `brain_recall_gate` MCP handler on the zero-usable-result path only (`emitNegativeRecallTelemetry` in `src/core/brain/gate-telemetry.ts`) - one record per gate call whose caller reported no usable result, carrying the typed corpus verdict (`state`, `complete`, the named `unknown_reason` when the verdict is `unknown`, `reason`) plus the reduced coverage receipt when one could be built (`coverage_digest`, `documents`, `chunks`, `schema_version`, `embedding_signature`, `last_indexed_at`, `scope`, `unindexed_roots`). Two receipt fields are not copied into the payload: `index_path` is deliberately dropped - a host filesystem path is not vault content and these records sync between devices, and the digest already binds it; the `embeddings` census the receipt carries is likewise absent from the payload and likewise bound by `coverage_digest`, so a reader comparing two records still sees a keyword-only index differ from a fully embedded one. Same prompt invariant as `gate_telemetry`: a SHA-256 prefix (`prompt_hash`) and the length (`prompt_chars`), never the prompt. A call with usable results writes NO record, so a corpus statement is never invented for an attempt that had one || `generation_report` | opt-in per call (`enable`) or config key `generation_trace_enabled` (default off) | inbound agent report after a generation handoff (`brain_generation_reports` action `record`, `o2b brain generation-reports record`) || `mcp_route_latency` | config key `mcp_route_metrics_enabled` (default off) | the MCP server's tool-call seam (`MCPServer.invokeToolHandler` in `src/mcp/server.ts`) - one record per `tools/call` and per CLI-bridge `callTool`; payload carries the tool name, scope, status, duration, and argument KEY NAMES only, never argument values || `token_impact` | config key `token_impact_ledger_enabled` (default off) | `brain_token_impact` action `record` (`emitTokenImpact` in `src/core/brain/token-impact.ts`) - one sample per context pack; payload carries the tokenizer-exact prompt-token counts (`baseline_tokens`, `packed_tokens`, signed `delta_tokens`), the `method` label (`exact`/`fallback`), an optional opaque `pack_id`, and the optional modeled inference-avoidance estimate - never raw prompts or recalled text |@@ -78,7 +79,7 @@ Every continuity payload passes `safeContinuityPayload()` (`src/core/brain/conti- `<private>...</private>` regions are stripped and replaced; the record is flagged `private: true`.- Secret-shaped tokens are redacted to `***REDACTED***`; the record is flagged `redacted: true`.- The sanitized payload is deep-frozen; nothing mutates it after the flags are computed.-- `gate_telemetry` never stores the raw prompt by construction - only a SHA-256 prefix (`prompt_hash`) and the length (`prompt_chars`). The test suite asserts this against the persisted files, not just returned values.+- `gate_telemetry` never stores the raw prompt by construction - only a SHA-256 prefix (`prompt_hash`) and the length (`prompt_chars`). The test suite asserts this against the persisted files, not just returned values. `negative_recall` shares that construction (same module, same hash helper) and adds one rule of its own: the coverage receipt it carries drops `index_path`, so no host filesystem path replicates with the vault.- `generation_report` follows the same rule: the handoff prompt is hashed and counted but never persisted - only `prompt_hash` (full SHA-256 hex) and `prompt_chars` land on disk, plus token counts. The kernel never calls an LLM; the report is the agent's INBOUND record after it performed a generation for a brain handoff, so the local token estimate (`local_estimate.input_tokens`) is always present while the agent-reported `usage` block is present only when supplied - absent is reported as absent, never fabricated. A grep-guarded regression test pins that no `fetch`/provider HTTP call exists under `src/core` for this feature, and a persisted-file assertion confirms no raw prompt survives.- `mcp_route_latency` records the route (tool name), MCP scope, status, duration, and the sorted set of argument KEY NAMES only - the tool's own JSON-Schema property names, never operator-supplied argument values - so no prompt, note body, or preference id can land on disk. A persisted-file test asserts key names survive while values never do.- The masking policy lives in the read-model (`src/core/brain/continuity/read-model.ts`) and governs only the readers that go through it: records flagged `private` are dropped by default and kept only on explicit request; masked text is never un-masked. That is FOUR modules - the `o2b brain continuity` verbs (trajectory export and listing), the bench harness, `brain_event_trace`, and skill-usage aggregation. Twenty other modules call `listContinuityRecords` on the store directly and see raw records: no `private` drop and no schema-version dispatch. The policy is read-model-wide, NOT store-wide. Both lists are asserted in `tests/core/brain/continuity/reader-census.test.ts`, which fails when a module joins or leaves either set; auditing the direct readers is tracked separately.diff --git a/hooks/active-inject.ts b/hooks/active-inject.tsindex a151cf3d..d51784f6 100644--- a/hooks/active-inject.ts+++ b/hooks/active-inject.ts@@ -5,6 +5,14 @@* confirmed and quarantined preferences without explicitly calling* `brain_query` first.*+ * Two lanes share the surface, and the order between them is the point.+ * `Brain/standing-rules.md` is operator-authored and goes FIRST, read+ * outside the fail-open memory load so it survives a memory-layer+ * failure and never enters the inject cache. Everything after it -+ * runtime notices, `active.md`, `lessons.md` - is what the agent learned+ * about itself, assembled inside the fail-open boundary and charged+ * against the configured injection budget.+ ** Contract (identical for Claude Code and Codex):* stdin: hook payload JSON. The vault path is resolved from the* persisted Open Second Brain config (env `VAULT_DIR` โ config@@ -15,16 +23,26 @@* {* "hookSpecificOutput": {* "hookEventName": "SessionStart" | "PostCompact",- * "additionalContext": "<rendered Brain/active.md body>"+ * "additionalContext": "<standing-rules block, then the budgeted+ * memory context: runtime notices, the+ * rendered Brain/active.md body, lessons>"* }* }*- * Quiet on every failure mode (no config, no vault, no `Brain/active.md`,- * malformed payload, missing file): the hook exits 0 with no output and- * the runtime proceeds as if the hook never ran. A SessionStart that- * silently fails is far less harmful than one that aborts the session- * with a stderr trace. The agent simply does not get the per-session- * preferences nudge โ exactly the v0.9.0 behaviour.+ * Quiet on the failure modes that leave it with nothing to say (no config,+ * no vault, malformed payload): the hook exits 0 with no output and the+ * runtime proceeds as if it never ran. A SessionStart that silently fails+ * is far less harmful than one that aborts the session with a stderr+ * trace. The agent simply does not get the per-session preferences nudge โ+ * exactly the v0.9.0 behaviour.+ *+ * A missing `Brain/active.md` is NOT one of those modes any more, and+ * neither is a memory layer that threw. The standing-rules lane is read+ * outside the fail-open boundary, so a vault whose operator wrote rules+ * still emits them with an empty memory context behind them; a rules file+ * that exists and cannot be read emits the block that says so. The empty+ * exit is reached only when there are NEITHER standing rules NOR memory,+ * and `tests/hooks/active-inject.test.ts` asserts it.*/import { existsSync, readFileSync } from "node:fs";@@ -32,9 +50,22 @@ import { join } from "node:path";import { resolveVault } from "../src/core/config.ts";import { parseFrontmatterText } from "../src/core/vault.ts";-import { brainActivePath, brainLessonsPath } from "../src/core/brain/paths.ts";+import {+ brainActivePath,+ brainLessonsPath,+ brainStandingRulesPath,+} from "../src/core/brain/paths.ts";import { budgetActiveBody } from "../src/core/brain/active-budget.ts";-import { INJECT_BUDGET_CHARS_DEFAULT, loadBrainConfig } from "../src/core/brain/policy.ts";+import {+ INJECT_BUDGET_CHARS_DEFAULT,+ loadBrainConfig,+ resolveStandingRulesMaxChars,+} from "../src/core/brain/policy.ts";+import {+ readStandingRules,+ renderStandingRules,+ renderStandingRulesFailure,+} from "../src/core/brain/standing-rules.ts";import { healCliSymlinks } from "../src/cli/install-cli.ts";import { ensureVaultCurrent } from "../src/core/maintenance/ensure-current.ts";import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";@@ -46,6 +77,7 @@ 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";+import type { BrainConfig } from "../src/core/brain/types.ts";/*** Best-effort hook audit line. Never throws: a failure to record must never@@ -131,21 +163,35 @@ async function main(): Promise<void> {});}+ const meter: InjectionMeter = { sources: [], budgetChars: null };+ const limits = resolveInjectionLimits(vault);++ // The operator's standing rules, read BEFORE and OUTSIDE the fail-open+ // load below. That single placement buys three properties at once:+ // the block never reaches the budgeter, so the configured injection+ // budget cannot shrink it; a throw inside memory assembly cannot take+ // it down with it; and it is never written to the inject cache, so a+ // stale constitution can never be served from disk while the live one+ // is unreadable.+ const standingBlock = renderStandingBlock(vault, limits.standingRulesMaxChars, meter);+// Fail-open context load: assemble the injected body inside a guard that// 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 meter: InjectionMeter = { sources: [], budgetChars: null };- const { context, source } = await loadInjectContextFailOpen({+ const { context: memoryContext, source } = await loadInjectContextFailOpen({vault,key: "active",- assemble: () => assembleActiveContext(vault, meter),+ assemble: () => assembleActiveContext(vault, limits.injectBudgetChars, meter),audit: (degradedSource) =>auditHook(vault, "inject_failopen_degraded", {hook: "active-inject",source: degradedSource,}),});+ // The early return now fires only when there are NEITHER standing rules+ // NOR memory - a vault with rules and a broken memory layer still speaks.+ const context = joinBlocks([standingBlock, memoryContext]);if (context.length === 0) return;const out = {@@ -166,16 +212,38 @@ async function main(): Promise<void> {// ----- injection-size meter (context-integrity-gates, Unit H) --------------+/**+ * Which ceiling a sub-body was charged against, and whether it was+ * emitted at all when the memory assembly failed.+ *+ * - EXEMPT: produced outside the fail-open boundary. Charged against+ * its own cap, not `inject_budget_chars`, and emitted whatever the+ * memory layer does - so it is the one lane still real in a+ * degraded injection.+ * - BUDGETED: charged against `inject_budget_chars`. Two of these+ * exist today and each is charged against the FULL configured+ * ceiling, which is why the receipt records their count.+ * - UNBUDGETED: assembled inside the boundary but not charged (the+ * runtime notices, which are bounded by the number of conditions+ * that can hold rather than by a character count).+ */+const LANE_EXEMPT = "exempt";+const LANE_BUDGETED = "budgeted";+const LANE_UNBUDGETED = "unbudgeted";++type InjectionLane = typeof LANE_EXEMPT | typeof LANE_BUDGETED | typeof LANE_UNBUDGETED;+/*** 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.+ * The parts are joined into one string before emission, 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;+ readonly lane: InjectionLane;}/** Mutable accumulator threaded through the assembly, read after it returns. */@@ -186,10 +254,19 @@ interface InjectionMeter {}/** Sub-body identifiers recorded per injection. Structural, not content-derived. */+const SOURCE_STANDING_RULES = "standing-rules";const SOURCE_RUNTIME_NOTICES = "runtime-notices";const SOURCE_ACTIVE_BODY = "active-body";const SOURCE_LESSONS_BODY = "lessons-body";+/** Blank line between two injected blocks. */+const BLOCK_SEPARATOR = "\n\n";++/** Join the non-empty blocks in order; an all-empty list yields "". */+function joinBlocks(blocks: ReadonlyArray<string>): string {+ return blocks.filter((block) => block.length > 0).join(BLOCK_SEPARATOR);+}+const UTF8 = new TextEncoder();function byteLength(text: string): number {@@ -214,10 +291,13 @@ interface RecordInjectionSizeInput {** 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.+ * ones. When the loader degraded to its last-good cache the ASSEMBLED+ * sub-bodies in `meter` were never emitted (assembly threw), so the+ * record says `sources_measured: false` and drops them - a per-source+ * breakdown of a body that was replaced by a cached one would be a+ * finding that never happened. The exempt lane is kept in that case,+ * because it is produced outside the boundary and did reach the payload;+ * omitting it would understate an injection that really 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@@ -232,13 +312,13 @@ function recordInjectionSize(vault: string, input: RecordInjectionSizeInput): voconst 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),- }))- : [],+ items: input.meter.sources+ .filter((source) => measured || source.lane === LANE_EXEMPT)+ .map((source) => ({+ id: source.name,+ bytes: byteLength(source.text),+ tokens: estimateTokens(source.text),+ })),finalText: input.context,...(input.meter.budgetChars !== null && measured? {@@ -270,9 +350,80 @@ function recordInjectionSize(vault: string, input: RecordInjectionSizeInput): vo/** 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;+ return meter.sources.filter((source) => source.lane === LANE_BUDGETED).length;+}++/**+ * The two character ceilings this hook applies, resolved once.+ *+ * They are separate numbers because they govern separate lanes: the+ * injection budget rations what the agent recalled about itself, the+ * standing-rules cap bounds what the operator wrote. Reading them+ * together is only an efficiency - one config open instead of two.+ */+interface InjectionLimits {+ readonly injectBudgetChars: number;+ readonly standingRulesMaxChars: number;+}++/**+ * Resolve both ceilings, falling back to their documented defaults when+ * `_brain.yaml` cannot be read.+ *+ * Both `_brain.yaml` failures - ABSENT and PRESENT BUT UNREADABLE -+ * resolve to the defaults here, and the unreadable one is not silent for+ * it: the runtime-notice channel runs inside the assembly below and puts+ * `brain_config_unreadable` immediately after the standing-rules block+ * and ahead of every budgeted body, naming the file and the parse+ * failure. It no longer heads the payload - the operator's own rules do -+ * but it still precedes everything these ceilings are applied to, which+ * is the property the argument rests on. The split the `load*ConfigSafe`+ * readers make is already made on this surface; making it a second time+ * here would be a second channel saying the same thing.+ *+ * Raising instead would report less, not more. A throw on this line+ * would escape the hook entirely and emit nothing at all, so the+ * condition would go from stated to invisible.+ *+ * The one quiet path left is `OPEN_SECOND_BRAIN_RUNTIME_NOTICES=false`,+ * which is the operator switching the channel off by name.+ */+function resolveInjectionLimits(vault: string): InjectionLimits {+ let cfg: BrainConfig | null = null;+ try {+ cfg = loadBrainConfig(vault);+ } catch {+ // absorbed deliberately - see the note above+ }+ return {+ injectBudgetChars: cfg?.active?.inject_budget_chars ?? INJECT_BUDGET_CHARS_DEFAULT,+ standingRulesMaxChars: resolveStandingRulesMaxChars(cfg),+ };+}++/**+ * Render the operator's standing-rules block, or the explicit statement+ * that it is unavailable.+ *+ * An absent or empty file yields "" and the lane simply does not appear.+ * A read that FAILED yields a block naming the path and the reason: the+ * agent must never be able to mistake "the operator wrote no rules" for+ * "the rules could not be read", and this is the surface where that+ * distinction has to be made, because there is no second channel the+ * operator would see.+ */+function renderStandingBlock(vault: string, maxChars: number, meter: InjectionMeter): string {+ const path = brainStandingRulesPath(vault);+ let block: string;+ try {+ const rules = readStandingRules(vault, { maxChars });+ if (rules === null) return "";+ block = renderStandingRules(rules);+ } catch (err) {+ block = renderStandingRulesFailure(path, err);+ }+ meter.sources.push({ name: SOURCE_STANDING_RULES, text: block, lane: LANE_EXEMPT });+ return block;}/**@@ -283,7 +434,7 @@ function budgetedSourceCount(meter: InjectionMeter): number {* 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, meter: InjectionMeter): string {+function assembleActiveContext(vault: string, budget: number, 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)@@ -291,14 +442,17 @@ function assembleActiveContext(vault: string, meter: InjectionMeter): string {// 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 });+ meter.sources.push({+ name: SOURCE_RUNTIME_NOTICES,+ text: noticesBlock,+ lane: LANE_UNBUDGETED,+ });}const activePath = brainActivePath(vault);- const activeBody = existsSync(activePath) ? readActiveBody(vault, activePath, meter) : "";+ const activeBody = existsSync(activePath) ? readActiveBody(vault, activePath, budget, meter) : "";- const parts = [noticesBlock, activeBody].filter((p) => p.length > 0);- return parts.join("\n\n");+ return joinBlocks([noticesBlock, activeBody]);}/**@@ -306,7 +460,12 @@ function assembleActiveContext(vault: string, meter: InjectionMeter): 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, meter: InjectionMeter): string {+function readActiveBody(+ vault: string,+ activePath: string,+ budget: number,+ meter: InjectionMeter,+): string {const body = readFileSync(activePath, "utf8");// Drop the `kind: brain-active / generated_at` frontmatter - it@@ -315,36 +474,13 @@ function readActiveBody(vault: string, activePath: string, meter: InjectionMeterconst trimmed = fmBody.trim();if (trimmed.length === 0) return "";- // Injection budget (token-diet): a large preference set must not- // flood the session preamble.- //- // Both `_brain.yaml` failures - ABSENT and PRESENT BUT UNREADABLE -- // resolve to the default budget here, and the unreadable one is not- // silent for it: `assembleActiveContext` runs the runtime-notice- // channel BEFORE this read, so a config the operator broke puts- // `brain_config_unreadable` at the head of the very payload this- // budget is applied to, naming the file and the parse failure. The- // split the `load*ConfigSafe` readers make is already made on this- // surface; making it a second time here would be a second channel- // saying the same thing.- //- // Raising instead would report less, not more. This function is the- // `assemble` callback of the fail-open loader, so a throw degrades the- // whole injection to the last-good cache - a body captured while the- // config still read, and therefore carrying no word of the breakage.- // The condition would go from stated to invisible.- //- // The one quiet path left is `OPEN_SECOND_BRAIN_RUNTIME_NOTICES=false`,- // which is the operator switching the channel off by name.- let budget = INJECT_BUDGET_CHARS_DEFAULT;- try {- const cfg = loadBrainConfig(vault);- if (cfg.active?.inject_budget_chars !== undefined) {- budget = cfg.active.inject_budget_chars;- }- } catch {- // absorbed deliberately - see the budget note above- }+ // Injection budget (token-diet): a large preference set must not flood+ // the session preamble. Resolved once in `resolveInjectionLimits`,+ // which also carries the reasoning for why a config failure lands on+ // the default here rather than raising. Recorded on the meter only at+ // this point, because a vault with no `active.md` charged nothing+ // against it and a receipt naming a budget nothing was measured under+ // would be a number with no measurement behind it.meter.budgetChars = budget;// Auto-load the lessons digest alongside active.md so the agent gets@@ -355,12 +491,12 @@ function readActiveBody(vault: string, activePath: string, meter: InjectionMeterconst lessonsBody = readLessonsBody(brainLessonsPath(vault), budget);const budgetedActive = budgetActiveBody(trimmed, budget);- meter.sources.push({ name: SOURCE_ACTIVE_BODY, text: budgetedActive });+ meter.sources.push({ name: SOURCE_ACTIVE_BODY, text: budgetedActive, lane: LANE_BUDGETED });if (lessonsBody !== null) {- meter.sources.push({ name: SOURCE_LESSONS_BODY, text: lessonsBody });+ meter.sources.push({ name: SOURCE_LESSONS_BODY, text: lessonsBody, lane: LANE_BUDGETED });}- return lessonsBody === null ? budgetedActive : `${budgetedActive}\n\n${lessonsBody}`;+ return lessonsBody === null ? budgetedActive : joinBlocks([budgetedActive, lessonsBody]);}/**diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 251147b1..d0aa4b3c 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.44.1",+ "version": "1.45.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex d81d0ae6..6e2c774f 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -1742,6 +1742,14 @@ import { existsSync, readdirSync, realpathSync } from "node:fs";import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";// src/core/partner/codegraph-health.ts+var GRAPH_HEALTH_CODES = Object.freeze({+ emptyGraph: "empty-graph",+ collapsedEdges: "collapsed-edges",+ danglingReferences: "dangling-references",+ selfLoops: "self-loops",+ cacheRootMismatch: "cache-root-mismatch"+});+var GRAPH_HEALTH_CODE_LIST = Object.freeze(Object.values(GRAPH_HEALTH_CODES));function stripTrailingSlash(p) {return p.replace(/\/+$/, "");}@@ -1754,30 +1762,30 @@ function assessGraphHealth(input) {const edges = Number.isFinite(input.edgeCount) ? input.edgeCount : 0;if (nodes <= 0) {warnings.push({- code: "empty-graph",+ code: GRAPH_HEALTH_CODES.emptyGraph,message: "index is initialized but holds 0 nodes; extraction produced an empty graph - " + "labeling and recall will find nothing until it is re-indexed"});} else if (edges <= 0) {warnings.push({- code: "collapsed-edges",+ code: GRAPH_HEALTH_CODES.collapsedEdges,message: `graph has ${nodes} node(s) but 0 edges; relationship extraction collapsed - ` + "callers/callees/impact traversal will be empty"});}if (input.danglingRefs !== undefined && input.danglingRefs > 0) {warnings.push({- code: "dangling-references",+ code: GRAPH_HEALTH_CODES.danglingReferences,message: `${input.danglingRefs} dangling reference(s): edges point at nodes absent from the ` + "index; derived labels/imports built from them would reference missing symbols"});}if (input.selfLoops !== undefined && input.selfLoops > 0) {warnings.push({- code: "self-loops",+ code: GRAPH_HEALTH_CODES.selfLoops,message: `${input.selfLoops} self-loop edge(s): a node references itself; ` + "impact and traversal surfaces may double-count or cycle"});}if (input.indexRoot && input.worktreeRoot && !samePath(input.indexRoot, input.worktreeRoot)) {warnings.push({- code: "cache-root-mismatch",+ code: GRAPH_HEALTH_CODES.cacheRootMismatch,message: `index was built for '${input.indexRoot}' but is being read from ` + `'${input.worktreeRoot}'; file and line references may be stale for this tree - ` + "re-index the current root before trusting graph-derived artifacts"});}@@ -1803,6 +1811,15 @@ var CODE_MANIFESTS = ["pom.xml"];var DEFAULT_LIMIT = 50;+var CODEGRAPH_CLI = Object.freeze({+ bin: "codegraph",+ statusSubcommand: "status",+ statusJsonFlag: "-j",+ initSubcommand: "init"+});+function codegraphInitCommand(projectPath) {+ return `${CODEGRAPH_CLI.bin} ${CODEGRAPH_CLI.initSubcommand} ${projectPath}`;+}function isCodeProject(dir) {try {if (!existsSync(dir))@@ -1857,16 +1874,17 @@ function findCodeProjects(opts) {}function defaultWhichCodegraph() {if (typeof Bun !== "undefined" && typeof Bun.which === "function") {- const found = Bun.which("codegraph");+ const found = Bun.which(CODEGRAPH_CLI.bin);return found ?? null;}return null;}var CODEGRAPH_PROJECT_PATH_USAGE_TOKEN = /\[path\]/;+var HELP_FLAG = "--help";function defaultDetectProjectPathSupport() {try {const proc = Bun.spawnSync({- cmd: ["codegraph", "status", "--help"],+ cmd: [CODEGRAPH_CLI.bin, CODEGRAPH_CLI.statusSubcommand, HELP_FLAG],stdout: "pipe",stderr: "pipe"});@@ -1879,7 +1897,12 @@ function defaultDetectProjectPathSupport() {function defaultRunStatusJson(projectPath) {try {const proc = Bun.spawnSync({- cmd: ["codegraph", "status", "-j", projectPath],+ cmd: [+ CODEGRAPH_CLI.bin,+ CODEGRAPH_CLI.statusSubcommand,+ CODEGRAPH_CLI.statusJsonFlag,+ projectPath+ ],stdout: "pipe",stderr: "pipe"});@@ -1892,7 +1915,10 @@ function defaultRunStatusJson(projectPath) {return { ok: true, data: parsed2 };} catch {}}- return { ok: false, error: stderr || `codegraph status exited ${proc.exitCode}` };+ return {+ ok: false,+ error: stderr || `${CODEGRAPH_CLI.bin} ${CODEGRAPH_CLI.statusSubcommand} exited ${proc.exitCode}`+ };}if (!stdout) {return { ok: false, error: stderr || "empty status output" };@@ -1952,7 +1978,7 @@ function evaluateProjectStatus(project, deps) {return {name: "code_graph",ok: false,- message: `code project at ${project}: not indexed (run: codegraph init ${project})`+ message: `code project at ${project}: not indexed (run: ${codegraphInitCommand(project)})`};}const runFn = deps?.runStatusJson ?? defaultRunStatusJson;@@ -1968,7 +1994,7 @@ function evaluateProjectStatus(project, deps) {return {name: "code_graph",ok: false,- message: `code project at ${project}: not indexed (run: codegraph init ${project})`+ message: `code project at ${project}: not indexed (run: ${codegraphInitCommand(project)})`};}const nodes = status.data.nodeCount ?? 0;diff --git a/package.json b/package.jsonindex 3627e974..b6dfd0ad 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.44.1",+ "version": "1.45.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [@@ -39,8 +39,8 @@"test": "bash scripts/test","lint": "oxlint -c oxlint.json","lint:fix": "oxlint -c oxlint.json --fix",- "fmt": "oxfmt --write '**/*.{ts,js,json}' '.oxfmtrc.json' '!openclaw/index.js' --no-error-on-unmatched-pattern",- "fmt:check": "oxfmt --check '**/*.{ts,js,json}' '.oxfmtrc.json' '!openclaw/index.js' --no-error-on-unmatched-pattern",+ "fmt": "oxfmt --write '**/*.{ts,js,json}' '.oxfmtrc.json' '!**/openclaw/index.js' '!.claude/**' --no-error-on-unmatched-pattern",+ "fmt:check": "oxfmt --check '**/*.{ts,js,json}' '.oxfmtrc.json' '!**/openclaw/index.js' '!.claude/**' --no-error-on-unmatched-pattern","typecheck": "tsc --noEmit","validate": "bun run typecheck && bun run lint && bun run test","validate:fix": "bun run lint:fix && bun run fmt",diff --git a/plugin.yaml b/plugin.yamlindex f6c342d0..5afe9c5f 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.44.1"+version: "1.45.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 309fe66f..e7b0f41a 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.44.1",+ "version": "1.45.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex f6c342d0..5afe9c5f 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.44.1"+version: "1.45.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex a5b0dde9..c27c0a20 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.44.1"+version = "1.45.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex f094b9ed..a31e7785 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -1,12 +1,17 @@/*** Help text for `o2b brain` and each of its verbs.*- * Pure data: no runtime imports beyond what the dispatcher needs.+ * Pure data plus one imported constant: the release the sidecar manifest+ * shipped in. That version used to be a literal here, a second literal+ * in the rollback warning and a third in the operating manual, so it is+ * imported from the module that owns the format rather than re-typed.* Split out of `./helpers.ts` so the verb-handler bundle does not* have to load this ~200-line string table when it only needs* `parse` / `resolveBrainVault`.*/+import { BRAIN_MANIFEST_SIDECAR_SINCE_VERSION } from "../../core/brain/manifest.ts";+export const BRAIN_HELP = `usage: o2b brain <verb> [args...]Brain verbs (observing memory):@@ -39,7 +44,8 @@ Brain verbs (observing memory):okf-export Write a portable Open Knowledge Format bundle (--out <dir> [--force])okf-import Import an OKF bundle (<dir>; staged as review candidates, --trusted writes direct)explorer Launch the loopback HTML explorer; --export <path> writes a single offline file- snapshot diff Read-only diff between two snapshots, or snapshot vs live+ snapshot Inspect recovery points: log (newest-first, --reason filter),+ diff (two snapshots, or a snapshot vs live)rollback Restore Brain/ from a snapshot (--list or <run_id>; --yes;--dry-run previews via the same diff renderer)doctor Validate Brain invariants (--strict; --remediate/--repair [--apply])@@ -132,7 +138,7 @@ Brain verbs (observing memory):links Normalize wikilink path format (preserve/full/short); dry-run by defaultprofile Materialize Brain/profile.md digest + .o2bfs root marker (age-gated)sgrep Grep-shaped semantic search: o2b brain sgrep <query> [path]- trigger Proactive trigger queue with anti-nag lifecycle (scan/list/ack/dismiss/act/history)+ trigger Proactive trigger queue with anti-nag lifecycle (scan/list/ack/dismiss/act/suppress/unsuppress/history)deep-synthesis Topic dossier: notes, agreements, contradictions, stale claims, gapsdiarize Subject profile: document set, stated-vs-evidenced gap, needs-llm-step skeletonideas Ranked next-direction candidates from open loops (--triggers to enqueue)@@ -284,20 +290,37 @@ export const VERB_HELP: Record<string, string> = {"Restore Brain/ from a snapshot. Interactive prompt unless --yes.\n" +"--dry-run prints the would-be restore plan as live โ snapshot\n" +"diff and exits 0 without writing.\n" +- "From v0.10.6 each snapshot carries a sidecar sha256 manifest of\n" ++ `From ${BRAIN_MANIFEST_SIDECAR_SINCE_VERSION} each snapshot carries a sidecar sha256 manifest of\n` +"the Brain/ tree captured at snapshot time. rollback compares it\n" +"against the current Brain/ and aborts with exit 2 if they\n" +"differ โ typically because another device (Syncthing) edited the\n" +"vault between snapshot and rollback. Pass --force-rollback to\n" +"overwrite anyway; the log entry records `drift_overridden: true`.\n" +- "Snapshots produced before v0.10.6 have no sidecar; rollback emits\n" ++ `Snapshots produced before ${BRAIN_MANIFEST_SIDECAR_SINCE_VERSION} have no sidecar; rollback emits\n` +"a stderr warning and falls through to the legacy direct-restore\n" +- "path.\n",+ "path.\n" ++ "The derived SQLite store is covered only when\n" ++ "snapshots.include_derived_store is on (off by default). Every\n" ++ "rollback reports what it did about it: replaced, not restored with\n" ++ "the manifest's named reason, or unknown for a snapshot taken before\n" ++ "coverage existed. --list carries the same answer per snapshot.\n" ++ "--list, the confirmation prompt and the --json result all name the\n" ++ "reason the snapshot was taken; 'unknown' means the snapshot carries\n" ++ "no sidecar reason and is never inferred from its run id. Filter the\n" ++ "history by reason with `o2b brain snapshot log --reason <reason>`.\n",snapshot:- "usage: o2b brain snapshot diff <run_id_a> [<run_id_b>]\n" ++ "usage: o2b brain snapshot log [--reason <reason>] [--limit <n>]\n" ++ " [--vault <path>] [--json]\n" ++ " o2b brain snapshot diff <run_id_a> [<run_id_b>]\n" +" [--vault <path>] [--json]\n" +- "Read-only diff between two snapshots, or between a snapshot and\n" +- "the live Brain/ tree (when <run_id_b> is omitted).\n",+ "log lists every recovery point newest first: run id, created_at, the\n" ++ "reason it was taken, archive size, whether a drift manifest is present,\n" ++ "and what it did about the derived store. --reason filters by why it\n" ++ "happened and rejects an unregistered value with exit 2. A snapshot with\n" ++ "no sidecar reads as reason 'unknown' - never as its run-id prefix.\n" ++ "diff is a read-only diff between two snapshots, or between a snapshot\n" ++ "and the live Brain/ tree (when <run_id_b> is omitted).\n" ++ "Together with rollback, the family is log / diff / revert.\n",hygiene:"usage: o2b brain hygiene <scan|apply> [--vault <path>] [--json]\n" +" [--detectors conflicts,dedup,freshness,usefulness]\n" +@@ -504,7 +527,9 @@ export const VERB_HELP: Record<string, string> = {"with active/processed and distinct-topic counts.\n",schema:"usage: o2b brain schema [report|stats|lint|graph|explain|orphans|apply|sync] [--vault <path>] [--json]\n" +- "Inspect and mutate the active runtime schema vocabulary through locked, audited writes.\n",+ "Inspect and mutate the active runtime schema vocabulary through locked, audited writes.\n" ++ "report names the pack's integrity: ok, modified, or unverified with the reason.\n" ++ "sync is not implemented and refuses; it never reported real work.\n","session-hook":"usage: o2b brain session-hook [--vault <path>] [--agent <name>] [--dry-run] [--json]\n" +"Read one runtime hook JSON payload from stdin, capture inline @osb markers / brain_feedback tool calls,\n" +@@ -959,11 +984,15 @@ export const VERB_HELP: Record<string, string> = {"Grep-shaped semantic Brain search: path:line: output lines, path\n" +"scoping, exit 1 on no matches (also in --json mode).\n",trigger:- "usage: o2b brain trigger <scan|list|ack|dismiss|act|history> [id] [--status <s>] [--vault <path>] [--json]\n" ++ "usage: o2b brain trigger <scan|list|ack|dismiss|act|suppress|unsuppress|history> [id] [--status <s>] [--vault <path>] [--json]\n" +"Grounded proactive trigger queue under Brain/triggers/. scan generates\n" +"deduped triggers from health/retention data (cooldown via\n" +"trigger_cooldown_days, default 7); ack/dismiss/act transition one\n" +- "trigger; history lists terminal ones.\n",+ "trigger; history lists terminal ones. suppress silences a finding\n" ++ "indefinitely - no cooldown clock, so it never re-nags - and unsuppress\n" ++ "restores the status it interrupted along with its original cooldown.\n" ++ "list prints how many triggers are currently suppressed; every silenced\n" ++ "recurrence is counted on the record (occurrences, last_seen_at).\n","deep-synthesis":"usage: o2b brain deep-synthesis <topic> [--limit <n>] [--triggers] [--vault <path>] [--json]\n" +"Deterministic topic dossier: matched notes, agreements, contradictions,\n" +diff --git a/src/cli/brain/snapshot-render.ts b/src/cli/brain/snapshot-render.tsnew file mode 100644index 00000000..3f64a30e--- /dev/null+++ b/src/cli/brain/snapshot-render.ts@@ -0,0 +1,101 @@+/**+ * The words two surfaces use for one snapshot record.+ *+ * `o2b brain snapshot log` and `o2b brain rollback --list` both answer+ * "why was this taken" and "does it cover the derived store", and both+ * shipped their own copy of the answer. The copies had already begun to+ * disagree: one drew the no-record case from a named constant and the+ * other from a bare literal, and only one of them showed the archive+ * size. Two renderings of one vocabulary is how a surface starts telling+ * an operator two different things about the same file, which is the+ * defect class this release is about - so they live here, once.+ *+ * The `unknown` cases carry the load. A snapshot with no derived-store+ * record recorded nothing, so nothing may be claimed, and rendering it as+ * `excluded` would state a decision that was never made - just as+ * rendering an unreadable snapshots directory as an empty one would state+ * a listing that never happened.+ */++import type { BrainManifestDerivedStore } from "../../core/brain/manifest.ts";+import type {+ BrainSnapshotListingError,+ RestoreDerivedStoreResult,+} from "../../core/brain/snapshot.ts";++/**+ * What both surfaces print where a value was never recorded. Shared so+ * the two cannot drift into `unknown` and `unrecorded`.+ */+export const SNAPSHOT_UNKNOWN_LABEL = "unknown";++/** Printed when an exclusion reason is missing from a record that has one. */+const UNSPECIFIED_EXCLUSION_LABEL = "unspecified";++/** Said in every not-replaced case, so no operator has to infer it. */+const LIVE_STORE_UNTOUCHED = "live store left untouched";++/** Why a snapshot was taken, or the shared label when it went unrecorded. */+export function renderSnapshotReason(reason: string | null): string {+ return reason ?? SNAPSHOT_UNKNOWN_LABEL;+}++export interface DerivedStoreCoverageOptions {+ /**+ * Append the archived byte count to the included case. The listing+ * surface shows it because size is the cost an operator is deciding+ * about; the log surface has its own size column and would repeat it.+ */+ readonly withArchiveSize?: boolean;+}++/** One-column derived-store answer: included, excluded with a reason, or unknown. */+export function renderDerivedStoreCoverage(+ record: BrainManifestDerivedStore | null,+ opts: DerivedStoreCoverageOptions = {},+): string {+ if (record === null) return SNAPSHOT_UNKNOWN_LABEL;+ if (record.included) {+ return opts.withArchiveSize === true+ ? `included (${record.archive_size ?? 0} bytes)`+ : "included";+ }+ return `excluded (${record.exclusion_reason ?? UNSPECIFIED_EXCLUSION_LABEL})`;+}++/**+ * One-line outcome for a completed restore, and the one place the+ * no-record case is put into words.+ *+ * That case used to be a single sentence - "snapshot predates+ * derived-store coverage" - for two different facts. The sidecar write is+ * non-fatal at snapshot time, so a snapshot can carry a store archive and+ * no record of it, and the restore then reported a manufactured reason:+ * it named the feature as absent while the feature's own archive sat next+ * to the tar. The archive probe splits them, and neither sentence claims+ * more than the disk supports - a snapshot with no record and no archive+ * is not evidence of WHEN it was taken either, only that nothing was+ * archived and nothing was recorded.+ */+export function renderDerivedStoreRestore(outcome: RestoreDerivedStoreResult): string {+ if (outcome.replaced) return `replaced ${outcome.path ?? ""}`.trimEnd();+ if (!outcome.coverage_known) {+ return outcome.store_archive_present+ ? `record missing (a store archive is on disk beside the snapshot, so coverage ran and ` ++ `its record did not survive); ${LIVE_STORE_UNTOUCHED}`+ : `${SNAPSHOT_UNKNOWN_LABEL} (no derived-store record and no store archive for this ` ++ `snapshot); ${LIVE_STORE_UNTOUCHED}`;+ }+ return `not restored (${outcome.exclusion_reason ?? UNSPECIFIED_EXCLUSION_LABEL}); ${LIVE_STORE_UNTOUCHED}`;+}++/**+ * Wording for a snapshots directory that exists and could not be read.+ *+ * Both listing surfaces need it and neither may fall back to their+ * empty-history line, so the sentence lives here with the rest of the+ * shared vocabulary rather than being spelled twice.+ */+export function renderSnapshotListingFailure(err: BrainSnapshotListingError): string {+ return `${err.message}; an unreadable snapshots directory is not an empty history`;+}diff --git a/src/cli/brain/verbs/audit.ts b/src/cli/brain/verbs/audit.tsindex 10875597..6dd8a8a6 100644--- a/src/cli/brain/verbs/audit.ts+++ b/src/cli/brain/verbs/audit.ts@@ -1,4 +1,5 @@import { readPrefAudit, renderPrefAudit } from "../../../core/brain/pref-audit.ts";+import { stripBrainIdPrefix } from "../../../core/brain/wikilink.ts";import { brainVerbContext, fail, parse } from "../helpers.ts";/**@@ -14,7 +15,7 @@ export async function cmdBrainAudit(argv: string[]): Promise<number> {});const raw = positional[0];if (!raw) return fail("usage: o2b brain audit <pref-id>");- const slug = raw.replace(/^(?:pref-|ret-)/, "").trim();+ const slug = stripBrainIdPrefix(raw);if (slug.length === 0) {return fail(`audit: empty preference slug after stripping prefix from '${raw}'`);}diff --git a/src/cli/brain/verbs/morning-brief.ts b/src/cli/brain/verbs/morning-brief.tsindex d1181854..8bc09aac 100644--- a/src/cli/brain/verbs/morning-brief.ts+++ b/src/cli/brain/verbs/morning-brief.ts@@ -4,6 +4,11 @@ import {deliverBriefTriggers,renderTriggerBriefSection,} from "../../../core/brain/triggers/brief.ts";+import {+ readTriggerQueueFailures,+ renderTriggerQueueFailures,+ unreadableTriggerJson,+} from "../../../core/brain/triggers/store.ts";import { parseOptionalNumberFlag } from "../../coerce.ts";import { brainVerbContext, fail, localTimeFields, parse } from "../helpers.ts";@@ -60,15 +65,23 @@ export async function cmdBrainMorningBrief(argv: string[]): Promise<number> {// Pending-trigger section (t_cd1fee79): renders only when a trigger// scan has produced surfaceable triggers; included triggers are// marked delivered so the same prompt shows once per cooldown window.+ //+ // Still fail-soft - a broken queue must not cost the operator the rest+ // of the brief - but no longer silent. The bare catch this replaces set+ // the section to null, so a refusal rendered exactly like an empty+ // queue: the one outcome the anti-nag ledger exists to rule out.const now = new Date();+ const triggerFailures = readTriggerQueueFailures(vault, now);+ let queueError = triggerFailures.queueError;let triggerSection;try {triggerSection = renderTriggerBriefSection(vault, {now,cooldownDays: resolveTriggerCooldownDays(config),});- } catch {+ } catch (exc) {triggerSection = null;+ queueError = (exc as Error).message ?? String(exc);}// Delivery is the store mutation: do it BEFORE emitting output so a@@ -89,17 +102,29 @@ export async function cmdBrainMorningBrief(argv: string[]): Promise<number> {})),}: {}),+ ...(triggerFailures.unreadable.length > 0+ ? { triggers_unreadable: triggerFailures.unreadable.map(unreadableTriggerJson) }+ : {}),+ ...(queueError !== null ? { trigger_queue_error: queueError } : {}),};process.stdout.write(JSON.stringify({ ...payload, ...localTimeFields(config) }, null, 2) + "\n",);} else {- const base = brief.text.length > 0 ? brief.text : "(nothing to surface)";- const text =- triggerSection !== null && triggerSection.text !== ""- ? `${base}\n\n${triggerSection.text}`- : base;- process.stdout.write(text + "\n");+ const failureText = renderTriggerQueueFailures({+ unreadable: triggerFailures.unreadable,+ queueError,+ });+ const sections = [+ brief.text,+ triggerSection !== null ? triggerSection.text : "",+ failureText,+ ].filter((section) => section !== "");+ // The placeholder stands for a brief with nothing in it, so it must+ // not stand in for one whose trigger queue could not be read.+ process.stdout.write(+ (sections.length > 0 ? sections.join("\n\n") : "(nothing to surface)") + "\n",+ );}return 0;}diff --git a/src/cli/brain/verbs/rollback.ts b/src/cli/brain/verbs/rollback.tsindex b57a729a..a8a0ae77 100644--- a/src/cli/brain/verbs/rollback.ts+++ b/src/cli/brain/verbs/rollback.ts@@ -1,16 +1,20 @@import {+ BrainSnapshotListingError,listSnapshots,extractSnapshotToTemp,restoreSnapshot,type ExtractSnapshotResult,+ type SnapshotInfo,} from "../../../core/brain/snapshot.ts";import {+ BRAIN_MANIFEST_SIDECAR_SINCE_VERSION,buildManifest,diffManifests,manifestDiffHasDrift,readManifestSidecar,renderManifestDriftJson,renderManifestDriftMarkdown,+ type BrainManifestDerivedStore,} from "../../../core/brain/manifest.ts";import { diffBrainTrees } from "../../../core/brain/snapshot-diff.ts";import { renderDiffJson, renderDiffMarkdown } from "../../../core/brain/snapshot-diff-render.ts";@@ -27,6 +31,12 @@ import {parse,readSingleLine,} from "../helpers.ts";+import {+ renderDerivedStoreCoverage,+ renderDerivedStoreRestore,+ renderSnapshotListingFailure,+ renderSnapshotReason,+} from "../snapshot-render.ts";export async function cmdBrainRollback(argv: string[]): Promise<number> {const { flags, positional } = parse(argv, {@@ -40,8 +50,24 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {const { vault } = brainVerbContext(flags);const forceRollback = Boolean(flags["force-rollback"]);+ // The usage check precedes the listing so a missing argument is still a+ // usage error rather than a filesystem report, and the listing is then+ // read ONCE for both surfaces below.+ if (!flags["list"] && positional.length < 1)+ return fail("brain rollback requires a <run_id> argument (or --list to enumerate snapshots)");++ let snaps: SnapshotInfo[];+ try {+ snaps = listSnapshots(vault);+ } catch (exc) {+ // A directory nobody could read must never be rendered as a vault+ // with no recovery points: that is the answer an operator would act+ // on by taking a fresh snapshot over a history that is still there.+ if (exc instanceof BrainSnapshotListingError) return fail(renderSnapshotListingFailure(exc));+ throw exc;+ }+if (flags["list"]) {- const snaps = listSnapshots(vault);if (flags["json"]) {process.stdout.write(JSON.stringify(snaps, null, 2) + "\n");return 0;@@ -50,17 +76,19 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {ok("no snapshots available");return 0;}- ok("run_id\tcreated_at\tsize_bytes");- for (const s of snaps) ok(`${s.run_id}\t${s.created_at}\t${s.size_bytes}`);+ ok("run_id\tcreated_at\treason\tsize_bytes\tderived_store");+ for (const s of snaps) {+ ok(+ `${s.run_id}\t${s.created_at}\t${renderSnapshotReason(s.reason)}\t${s.size_bytes}\t` ++ renderDerivedStoreCoverage(s.derived_store, { withArchiveSize: true }),+ );+ }return 0;}- if (positional.length < 1)- return fail("brain rollback requires a <run_id> argument (or --list to enumerate snapshots)");const runId = positional[0]!;-- const allSnaps = listSnapshots(vault);- if (!allSnaps.some((s) => s.run_id === runId)) {+ const target = snaps.find((s) => s.run_id === runId);+ if (target === undefined) {process.stderr.write(`snapshot not found: ${runId}; run \`o2b brain rollback --list\` to enumerate.\n`,);@@ -73,7 +101,8 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {const stored = readManifestSidecar(vault, runId);if (stored === null) {process.stderr.write(- `warning: no manifest sidecar for snapshot '${runId}'; drift detection skipped (snapshot predates v0.10.6).\n`,+ `warning: no manifest sidecar for snapshot '${runId}'; drift detection ` ++ `skipped (snapshot predates ${BRAIN_MANIFEST_SIDECAR_SINCE_VERSION}).\n`,);return null;}@@ -117,8 +146,13 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {if (flags["json"] || !process.stdin.isTTY)return fail("rollback requires --yes in non-interactive mode (--json or non-TTY stdin)");const summary = diffSummary(vault);+ // The reason is in the prompt because it is the one fact that tells an+ // operator WHICH point they are about to restore. Two archives minted+ // seconds apart differ only in why they were taken, and a run id is a+ // timestamp, not an explanation.process.stderr.write(`About to restore snapshot '${runId}' over Brain/.\n` ++ `Snapshot reason: ${renderSnapshotReason(target.reason)}.\n` +`Current state: ${summary.preferences} preferences, ${summary.retired} retired, ${summary.signals} signals.\n` +`This will OVERWRITE the live Brain/ tree (.snapshots/ is preserved).\nProceed? [y/N] `,);@@ -152,9 +186,24 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {}if (flags["json"]) {- okJson({ run_id: runId, restored_files: result.restored_files });+ okJson({+ run_id: runId,+ // Null when the snapshot predates the reason or its sidecar is+ // unreadable: UNKNOWN provenance stays null rather than borrowing a+ // label from the run id.+ reason: target.reason,+ restored_files: result.restored_files,+ derived_store: result.derived_store,+ });} else {- ok(`restored: ${runId} (${result.restored_files} files)`);+ ok(+ `restored: ${runId} (${result.restored_files} files, reason ${renderSnapshotReason(target.reason)})`,+ );+ // Always printed, in all three shapes. A restore that silently says+ // nothing about the derived store is exactly the silence this+ // feature exists to remove: the operator cannot tell a store that+ // was put back from one that was never in the archive.+ ok(`derived store: ${renderDerivedStoreRestore(result.derived_store)}`);}return 0;}diff --git a/src/cli/brain/verbs/schema.ts b/src/cli/brain/verbs/schema.tsindex 38781181..ac8ab379 100644--- a/src/cli/brain/verbs/schema.ts+++ b/src/cli/brain/verbs/schema.ts@@ -10,7 +10,13 @@ import {parseSchemaMutationPayloads,reviewSchemaOrphans,} from "../../../core/brain/schema-admin.ts";+import {+ assessSchemaPackIntegrity,+ SCHEMA_PACK_INTEGRITY,+ type SchemaPackIntegrity,+} from "../../../core/brain/schema-integrity.ts";import { previewSchemaMutations } from "../../../core/brain/schema-mutate.ts";+import { formatStampMismatch } from "../../../core/integrity/stamp.ts";import {buildSchemaReport,type BrainSchemaReport,@@ -60,8 +66,12 @@ export async function cmdBrainSchema(argv: string[]): Promise<number> {switch (subcommand) {case "report": {const report = buildSchemaReport(vault);- if (flags["json"]) return writeJson(report);- process.stdout.write(renderSchemaReportText(report));+ // The report used to describe the ontology without saying whether+ // it is still the ontology that was applied. An intact pack, a+ // hand-edited one, and one nothing ever sealed rendered the same.+ const integrity = assessSchemaPackIntegrity(vault);+ if (flags["json"]) return writeJson({ ...report, integrity });+ process.stdout.write(renderSchemaReportText(report, integrity));return 0;}case "stats":@@ -112,14 +122,10 @@ export async function cmdBrainSchema(argv: string[]): Promise<number> {if (!Number.isInteger(batchSize) || batchSize <= 0) {throw new Error("--batch-size must be a positive integer");}- return writeResult(- buildSchemaSyncResult({- dryRun: Boolean(flags["dry-run"]),- batchSize,- }),- Boolean(flags["json"]),- renderGenericText,- );+ // Refuses and exits non-zero: see `SchemaSyncUnavailableError`. The+ // flags above are still validated so an operator learns about a bad+ // `--batch-size` from the same message they always did.+ return writeResult(buildSchemaSyncResult(vault), Boolean(flags["json"]), renderGenericText);}}} catch (exc) {@@ -144,8 +150,28 @@ function renderGenericText(value: unknown): string {return JSON.stringify(value, null, 2) + "\n";}-function renderSchemaReportText(report: BrainSchemaReport): string {- const lines = ["brain schema", "", "vocabulary:"];+/**+ * One line naming the integrity verdict, plus the evidence behind it.+ *+ * `unverified` carries its reason on the same line: the status alone would+ * tell an operator that something could not be checked without telling+ * them which of the three ways it happened, which is the silence this unit+ * removes rather than relocates. `modified` is followed by the shared+ * mismatch rendering, so it reads the same here as on every other+ * integrity surface.+ */+function renderIntegrityLines(integrity: SchemaPackIntegrity): ReadonlyArray<string> {+ const reason =+ integrity.unverified_reason === undefined ? "" : ` (${integrity.unverified_reason})`;+ const lines = [`integrity: ${integrity.status}${reason}`];+ if (integrity.status === SCHEMA_PACK_INTEGRITY.modified) {+ for (const mismatch of integrity.mismatches) lines.push(` ${formatStampMismatch(mismatch)}`);+ }+ return lines;+}++function renderSchemaReportText(report: BrainSchemaReport, integrity: SchemaPackIntegrity): string {+ const lines = ["brain schema", "", ...renderIntegrityLines(integrity), "", "vocabulary:"];for (const category of SCHEMA_VOCAB_CATEGORIES) {lines.push(` ${category}: ${report.vocabulary[category].join(", ") || "(none)"}`);}diff --git a/src/cli/brain/verbs/snapshot.ts b/src/cli/brain/verbs/snapshot.tsindex 2fbd92d8..170de5b1 100644--- a/src/cli/brain/verbs/snapshot.ts+++ b/src/cli/brain/verbs/snapshot.ts@@ -1,12 +1,165 @@import {+ BrainSnapshotListingError,listSnapshots,extractSnapshotToTemp,type ExtractSnapshotResult,+ type SnapshotInfo,} from "../../../core/brain/snapshot.ts";import { diffBrainTrees } from "../../../core/brain/snapshot-diff.ts";import { renderDiffJson, renderDiffMarkdown } from "../../../core/brain/snapshot-diff-render.ts";import { brainDirs } from "../../../core/brain/paths.ts";-import { brainVerbContext, fail, parse } from "../helpers.ts";+import {+ BRAIN_SNAPSHOT_REASONS,+ isBrainSnapshotReason,+ type BrainSnapshotReason,+} from "../../../core/brain/types.ts";+import { brainVerbContext, fail, ok, parse, usageError } from "../helpers.ts";+import {+ renderDerivedStoreCoverage,+ renderSnapshotListingFailure,+ SNAPSHOT_UNKNOWN_LABEL,+} from "../snapshot-render.ts";++/** Verbs this dispatcher routes, named once for the help and the error. */+const SNAPSHOT_VERBS = Object.freeze({ log: "log", diff: "diff" } as const);++/** Rendered for an unstamped or unreadable sidecar. Never a guessed reason. */+const UNKNOWN_REASON_LABEL = SNAPSHOT_UNKNOWN_LABEL;++/** Column order of the `log` text table, and its header line. */+const LOG_COLUMNS: ReadonlyArray<string> = Object.freeze([+ "run_id",+ "created_at",+ "reason",+ "size_bytes",+ "manifest",+ "derived_store",+]);++/**+ * `o2b brain snapshot log` โ the missing third surface over the snapshot+ * family.+ *+ * `snapshot diff` and `rollback` already gave the family a diff and a+ * revert; the LIST was the gap, so the only way to ask which recovery+ * point covers a given boundary was to read filenames out of+ * `.snapshots/`. With this, log / diff / revert is complete.+ *+ * Newest-first, because that is the order an operator looking for "the+ * point just before the thing I regret" reads in. The ordering comes from+ * {@link listSnapshots} (by archive mtime) rather than from the run id: a+ * hand-named recovery point carries no timestamp to sort on.+ */+export async function cmdBrainSnapshotLog(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ reason: { type: "string" },+ limit: { type: "string" },+ });++ // Both flag checks run BEFORE the vault is resolved, and both are usage+ // errors (exit 2), matching how `brain event-trace` rejects a bad+ // --kind. An unregistered reason must never degrade into an empty+ // listing: that would report "your vault has no such snapshots" when+ // the truth is "that is not a reason".+ const reasonRaw = trimOrUndefined(flags["reason"]);+ if (reasonRaw !== undefined && !isBrainSnapshotReason(reasonRaw)) {+ return usageError(+ `brain snapshot log: unknown snapshot reason '${reasonRaw}'; ` ++ `supported: ${BRAIN_SNAPSHOT_REASONS.join(", ")}`,+ );+ }+ const reason: BrainSnapshotReason | undefined = reasonRaw;++ const limitRaw = trimOrUndefined(flags["limit"]);+ if (limitRaw !== undefined && (!/^[0-9]+$/.test(limitRaw) || Number.parseInt(limitRaw, 10) < 1)) {+ return usageError("brain snapshot log: --limit must be a positive integer");+ }+ const limit = limitRaw !== undefined ? Number.parseInt(limitRaw, 10) : undefined;++ const { vault } = brainVerbContext(flags);++ // A snapshots directory that exists and cannot be enumerated is a+ // failure of the listing, not a listing of nothing - so it is reported+ // before either output shape, and neither the empty-history line below+ // nor an empty `--json` array can stand in for it.+ let all: SnapshotInfo[];+ try {+ all = listSnapshots(vault);+ } catch (exc) {+ if (exc instanceof BrainSnapshotListingError) return fail(renderSnapshotListingFailure(exc));+ throw exc;+ }++ // The reason filter compares against what the SIDECAR recorded, so a+ // snapshot whose reason is unknown is never swept into a named bucket by+ // its run-id prefix.+ const matching = all.filter((s) => reason === undefined || s.reason === reason);+ const snaps = limit === undefined ? matching : matching.slice(0, limit);++ if (flags["json"]) {+ process.stdout.write(+ JSON.stringify({ total: snaps.length, snapshots: snaps.map(renderLogJson) }, null, 2) + "\n",+ );+ return 0;+ }++ if (snaps.length === 0) {+ // Zero, not an error: the directory was read (an unreadable one was+ // reported above) and the answer is none. The filter is echoed so an+ // operator who mistyped a valid reason can see which one was applied.+ ok(reason === undefined ? "no snapshots available" : `no snapshots with reason '${reason}'`);+ return 0;+ }+ ok(LOG_COLUMNS.join("\t"));+ for (const s of snaps) {+ ok(+ [+ s.run_id,+ s.created_at,+ s.reason ?? UNKNOWN_REASON_LABEL,+ String(s.size_bytes),+ s.manifest_path === null ? "absent" : "present",+ renderDerivedStore(s),+ ].join("\t"),+ );+ }+ return 0;+}++/** Structured row for `--json`, one per listed recovery point. */+function renderLogJson(s: SnapshotInfo): Record<string, unknown> {+ return {+ run_id: s.run_id,+ created_at: s.created_at,+ // `null` is UNKNOWN provenance and stays null in the payload: a+ // consumer must be able to tell an unstamped snapshot from a stamped+ // one, which a substituted label would hide.+ reason: s.reason,+ size_bytes: s.size_bytes,+ path: s.path,+ manifest: s.manifest_path !== null,+ manifest_path: s.manifest_path,+ derived_store: s.derived_store,+ store_archive_path: s.store_archive_path,+ };+}++/**+ * One-column derived-store answer. The size is omitted here because this+ * surface already has its own size column; the rollback listing appends+ * it, and both draw the words from one renderer so they cannot drift.+ */+function renderDerivedStore(s: SnapshotInfo): string {+ return renderDerivedStoreCoverage(s.derived_store);+}++function trimOrUndefined(value: string | boolean | string[] | undefined): string | undefined {+ if (typeof value !== "string") return undefined;+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : undefined;+}export async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {const { flags, positional } = parse(argv, {@@ -21,16 +174,24 @@ export async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {);}const [a, b] = positional;- const snaps = listSnapshots(vault);+ // Same reason as the log verb: "snapshot not found" over a directory+ // nobody could read names the wrong cause.+ let snaps: SnapshotInfo[];+ try {+ snaps = listSnapshots(vault);+ } catch (exc) {+ if (exc instanceof BrainSnapshotListingError) return fail(renderSnapshotListingFailure(exc));+ throw exc;+ }if (!snaps.some((s) => s.run_id === a)) {process.stderr.write(- `snapshot not found: ${a}; run \`o2b brain rollback --list\` to enumerate.\n`,+ `snapshot not found: ${a}; run \`o2b brain snapshot log\` to enumerate.\n`,);return 2;}if (b !== undefined && !snaps.some((s) => s.run_id === b)) {process.stderr.write(- `snapshot not found: ${b}; run \`o2b brain rollback --list\` to enumerate.\n`,+ `snapshot not found: ${b}; run \`o2b brain snapshot log\` to enumerate.\n`,);return 2;}@@ -60,6 +221,9 @@ export async function handleBrainSnapshotSubcommand(argv: ReadonlyArray<string>)process.stdout.write("usage: o2b brain snapshot <verb> [args...]\n" +"Verbs:\n" ++ " log [--reason <r>] [--limit <n>] Newest-first listing of every recovery\n" ++ " point: run id, created_at, reason, size,\n" ++ " manifest presence, derived-store coverage.\n" +" diff <run_id_a> [<run_id_b>] Read-only diff between two snapshots,\n" +" or between a snapshot and live Brain/.\n",);@@ -68,10 +232,15 @@ export async function handleBrainSnapshotSubcommand(argv: ReadonlyArray<string>)const sub = argv[0]!;const rest = argv.slice(1);switch (sub) {- case "diff":+ case SNAPSHOT_VERBS.log:+ return await cmdBrainSnapshotLog([...rest]);+ case SNAPSHOT_VERBS.diff:return await cmdBrainSnapshotDiff([...rest]);default:- process.stderr.write(`unknown brain snapshot verb: ${sub}; supported: diff\n`);+ process.stderr.write(+ `unknown brain snapshot verb: ${sub}; supported: ` ++ `${Object.values(SNAPSHOT_VERBS).join(", ")}\n`,+ );return 2;}}diff --git a/src/cli/brain/verbs/trigger.ts b/src/cli/brain/verbs/trigger.tsindex 207af977..b4eba815 100644--- a/src/cli/brain/verbs/trigger.ts+++ b/src/cli/brain/verbs/trigger.ts@@ -1,20 +1,56 @@/**- * `o2b brain trigger <scan|list|ack|dismiss|act|history>` (Workspace- * Insight Suite, t_cd1fee79): the grounded proactive trigger queue- * with its anti-nag lifecycle.+ * `o2b brain trigger <scan|list|ack|dismiss|act|suppress|unsuppress|history>`+ * (Workspace Insight Suite, t_cd1fee79): the grounded proactive trigger+ * queue with its anti-nag lifecycle.*/import { defaultConfigPath, resolveTriggerCooldownDays } from "../../../core/config.ts";import { scanTriggers } from "../../../core/brain/triggers/scan.ts";import {- listTriggers,+ readTriggers,transitionTrigger,+ unreadableTriggerJson,type TriggerAction,+ type UnreadableTrigger,} from "../../../core/brain/triggers/store.ts";-import { isTriggerStatus, type TriggerRecord } from "../../../core/brain/triggers/types.ts";+import {+ isTriggerStatus,+ TRIGGER_STATUS,+ TRIGGER_TERMINAL_STATUSES,+ type TriggerRecord,+} from "../../../core/brain/triggers/types.ts";import { fail, normalizeFlagString, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";-const TERMINAL = new Set(["acted", "dismissed", "expired"]);+/**+ * Verb to lifecycle action, stated exhaustively.+ *+ * This was a nested ternary whose final arm was `act`, so every verb+ * that was not `ack` or `dismiss` acted on the trigger - safe only for+ * as long as nobody added a verb to the accepted list without also+ * amending the ternary. An explicit map has no fallback arm to route+ * into: a verb missing from here is not a transition verb at all.+ */+const VERB_TO_ACTION: Readonly<Record<string, TriggerAction>> = Object.freeze({+ ack: "acknowledge",+ dismiss: "dismiss",+ act: "act",+ suppress: "suppress",+ unsuppress: "unsuppress",+});++/**+ * Every accepted verb, in the order the usage string lists them: the+ * read verbs around the transition verbs, which are taken from+ * {@link VERB_TO_ACTION} so the two can never disagree.+ */+const TRIGGER_VERBS: ReadonlyArray<string> = Object.freeze([+ "scan",+ "list",+ ...Object.keys(VERB_TO_ACTION),+ "history",+]);++const USAGE = `usage: o2b brain trigger <${TRIGGER_VERBS.join("|")}> [id] [--status S] [--json]`;function triggerJson(record: TriggerRecord): Record<string, unknown> {return {@@ -30,6 +66,10 @@ function triggerJson(record: TriggerRecord): Record<string, unknown> {expires_at: record.expiresAt,delivered_at: record.deliveredAt,resolved_at: record.resolvedAt,+ suppressed_at: record.suppressedAt,+ suppressed_from: record.suppressedFrom,+ occurrences: record.occurrences,+ last_seen_at: record.lastSeenAt,};}@@ -37,14 +77,21 @@ function printTrigger(record: TriggerRecord): void {ok(`${record.id} [${record.effectiveStatus}] (${record.urgency}) ${record.reason}`);}+/**+ * Report the records the store could not read.+ *+ * The count prints whether or not any exist, exactly like the suppressed+ * total: "unreadable: 0" is the surface stating that it looked, which is+ * what stops an omitted line from reading as a clean queue.+ */+function printUnreadable(unreadable: ReadonlyArray<UnreadableTrigger>): void {+ ok(`unreadable: ${unreadable.length}`);+ for (const entry of unreadable) ok(entry.error.message);+}+export async function cmdBrainTrigger(argv: string[]): Promise<number> {const action = argv[0];- const actions = ["scan", "list", "ack", "dismiss", "act", "history"];- if (!action || !actions.includes(action)) {- return fail(- "usage: o2b brain trigger <scan|list|ack|dismiss|act|history> [id] [--status S] [--json]",- );- }+ if (!action || !TRIGGER_VERBS.includes(action)) return fail(USAGE);const { flags, positional } = parse(argv.slice(1), {vault: { type: "string" },status: { type: "string" },@@ -66,6 +113,7 @@ export async function cmdBrainTrigger(argv: string[]): Promise<number> {candidates: result.candidates,created: result.created.map(triggerJson),skipped: result.skipped.map((s) => ({ cooldown_key: s.cooldownKey, reason: s.reason })),+ unreadable: result.unreadable.map(unreadableTriggerJson),});return 0;}@@ -73,6 +121,8 @@ export async function cmdBrainTrigger(argv: string[]): Promise<number> {`candidates: ${result.candidates}, created: ${result.created.length}, skipped: ${result.skipped.length}`,);for (const record of result.created) printTrigger(record);+ // A scan that walked around a broken record is not a clean scan.+ printUnreadable(result.unreadable);return 0;}@@ -81,20 +131,33 @@ export async function cmdBrainTrigger(argv: string[]): Promise<number> {if (statusFlag !== null && !isTriggerStatus(statusFlag)) {return fail(`unknown trigger status: ${statusFlag}`);}- let records = listTriggers(vault, {- now,- ...(statusFlag !== null ? { status: statusFlag } : {}),- });+ // One unfiltered pass: `list` reports the suppressed total from it+ // so the operator sees what is silenced without having to ask, and+ // the status filter is then applied to the same records.+ const scan = readTriggers(vault, { now });+ const all = scan.records;+ const suppressed = all.filter((r) => r.effectiveStatus === TRIGGER_STATUS.suppressed).length;+ let records = statusFlag !== null ? all.filter((r) => r.effectiveStatus === statusFlag) : all;if (action === "history") {- records = records.filter((r) => TERMINAL.has(r.effectiveStatus));+ records = records.filter((r) => TRIGGER_TERMINAL_STATUSES.has(r.effectiveStatus));} else if (statusFlag === null) {- records = records.filter((r) => !TERMINAL.has(r.effectiveStatus));+ records = records.filter((r) => !TRIGGER_TERMINAL_STATUSES.has(r.effectiveStatus));}if (json) {- okJson({ ok: true, triggers: records.map(triggerJson) });+ okJson({+ ok: true,+ triggers: records.map(triggerJson),+ ...(action === "list" ? { suppressed } : {}),+ unreadable: scan.unreadable.map(unreadableTriggerJson),+ });return 0;}+ if (action === "list") ok(`suppressed: ${suppressed}`);+ printUnreadable(scan.unreadable);if (records.length === 0) {+ // Said AFTER the unreadable report, so "no open triggers" can+ // never be the only thing an operator reads about a queue that+ // held something nobody could parse.ok(action === "history" ? "no trigger history" : "no open triggers");return 0;}@@ -102,11 +165,13 @@ export async function cmdBrainTrigger(argv: string[]): Promise<number> {return 0;}- // ack / dismiss / act+ const verb = VERB_TO_ACTION[action];+ // Unreachable while TRIGGER_VERBS is the union of the read verbs and+ // this map's keys, and stated rather than assumed so that adding a+ // verb to one without the other is a usage error, not a transition.+ if (verb === undefined) return fail(USAGE);const id = positional[0];if (!id) return fail(`brain trigger ${action} requires a trigger id`);- const verb: TriggerAction =- action === "ack" ? "acknowledge" : action === "dismiss" ? "dismiss" : "act";const record = transitionTrigger(vault, id, verb, { now });if (json) okJson({ ok: true, trigger: triggerJson(record) });else printTrigger(record);diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex 58d4f3e0..d494b554 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -147,7 +147,21 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({command("set-primary", "Set primary Brain agent"),command("protect", "Emit runtime deny rules for Brain"),command("unprotect", "Remove managed runtime deny rules"),- command("snapshot", "Inspect Brain snapshots"),+ command(+ "snapshot",+ "Inspect Brain snapshots",+ [],+ [+ command("log", "Newest-first listing of every recovery point with its reason", [+ flag("vault", "string"),+ flag("reason", "string"),+ flag("limit", "string"),+ ]),+ command("diff", "Read-only diff between two snapshots, or snapshot vs live", [+ flag("vault", "string"),+ ]),+ ],+ ),command("rollback", "Restore Brain from a snapshot"),command("upgrade", "Migrate release-owned Brain files"),command("export", "Export active preferences"),@@ -207,7 +221,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({flag("actor", "string"),flag("reason", "string"),]),- command("sync", "Preview Brain schema sync", [+ command("sync", "Brain schema sync (not implemented; refuses)", [flag("vault", "string"),flag("dry-run", "boolean"),flag("batch-size", "string"),@@ -281,7 +295,10 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({"Agent write sessions: open, submit, approve, abandon, status, list, sweep",),command("panel", "Multi-persona decision panel riding the write-session kernel"),- command("trigger", "Grounded proactive trigger queue (scan/list/ack/dismiss/act/history)"),+ command(+ "trigger",+ "Grounded proactive trigger queue (scan/list/ack/dismiss/act/suppress/unsuppress/history)",+ ),command("deep-synthesis", "Topic dossier: agreements, contradictions, stale claims, gaps"),command("ideas", "Ranked next-direction candidates from open loops"),command("entity", "Canonical entity registry: set, get, list, relate, archive"),@@ -479,8 +496,32 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({flag("verbose", "boolean"),flag("explain", "boolean"),]),- command("index", "Incrementally update the search index"),- command("reindex", "Rebuild the search index"),+ // Both builders declare their whole `parseFlags` schema for the+ // same reason `query` does, and `tests/cli/search-query-flag-manifest.test.ts`+ // holds all three to it: `--cron-template` and `--interval` were+ // parsed by `reindex` and advertised nowhere, so neither help nor+ // completions could offer the recipe this CLI knows how to print.+ command("index", "Incrementally update the search index", [+ flag("vault", "string"),+ flag("config", "string"),+ flag("db", "string"),+ flag("embeddings", "boolean"),+ flag("force", "boolean"),+ flag("force-cost", "boolean"),+ flag("concurrency", "string"),+ flag("verbose", "boolean"),+ ]),+ command("reindex", "Rebuild the search index", [+ flag("vault", "string"),+ flag("config", "string"),+ flag("db", "string"),+ flag("embeddings", "boolean"),+ flag("force-cost", "boolean"),+ flag("concurrency", "string"),+ flag("verbose", "boolean"),+ flag("cron-template", "boolean"),+ flag("interval", "string"),+ ]),command("watch", "Watch the vault and incrementally sync the index on .md edits"),command("status", "Print search index status"),command(@@ -539,7 +580,18 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({[command("report", "Report codegraph index status and workspace members", [flag("vault", "string"),+ flag("fail-on-health", "boolean"),]),+ command(+ "resync",+ "Print a cron recipe that re-indexes the code project when its commit moves (requires --cron-template; writes nothing)",+ [+ flag("cron-template", "boolean"),+ flag("interval", "string"),+ flag("project", "string"),+ flag("vault", "string"),+ ],+ ),],),],@@ -560,6 +612,38 @@ export function nestedCommandNames(parent: string): string[] {return node?.commands?.map((item) => item.name) ?? [];}+/**+ * Every root command that models nested subcommands, paired with them.+ *+ * The completion renderer used to hand-list the three roots it knew about,+ * so a fourth that grew subcommands was offered by no shell and nothing+ * anywhere said so. Deriving the groups from the manifest is what makes+ * the completion surface follow the manifest rather than trail it.+ */+export function nestedCommandGroups(+ manifest: CliRootManifest = CLI_COMMAND_MANIFEST,+): Array<{ parent: string; children: string[] }> {+ // Every depth, not only the first. Shell completion keys off the word+ // immediately before the cursor, so a verb two levels down is reachable+ // by its own parent's name and needs no path context - which is what+ // makes a flat, recursively-collected map the right shape here.+ const byParent = new Map<string, string[]>();+ const visit = (items: ReadonlyArray<CliCommandManifest>): void => {+ for (const item of items) {+ const children = item.commands ?? [];+ if (children.length === 0) continue;+ const merged = byParent.get(item.name) ?? [];+ for (const child of children) {+ if (!merged.includes(child.name)) merged.push(child.name);+ }+ byParent.set(item.name, merged);+ visit(children);+ }+ };+ visit(manifest.commands);+ return [...byParent].map(([parent, children]) => ({ parent, children }));+}+/** One modelled subcommand, e.g. `nestedCommand("search", "query")`. */export function nestedCommand(parent: string, child: string): CliCommandManifest | undefined {const node = CLI_COMMAND_MANIFEST.commands.find((item) => item.name === parent);diff --git a/src/cli/completions.ts b/src/cli/completions.tsindex a5df80bc..d8644382 100644--- a/src/cli/completions.ts+++ b/src/cli/completions.ts@@ -1,7 +1,7 @@import {allFlagNames,commandNames,- nestedCommandNames,+ nestedCommandGroups,type CliRootManifest,} from "./command-manifest.ts";@@ -22,9 +22,8 @@ export function isCompletionShell(value: string): value is CompletionShell {export function renderCompletions(shell: CompletionShell, manifest: CliRootManifest): string {const roots = commandNames(manifest);- const brain = nestedCommandNames("brain");- const search = nestedCommandNames("search");- const vault = nestedCommandNames("vault");+ const groups = nestedCommandGroups(manifest);+ const nested = groups.flatMap((group) => group.children);const flags = allFlagNames(manifest).map((flag) => `--${flag}`);const words = [...roots, ...flags];const header = `# o2b completions for ${shell}\n# commands: ${roots.join(" ")}\n# flags: ${flags.join(" ")}\n`;@@ -36,10 +35,14 @@ _o2b_completions() {COMPREPLY=()cur="\${COMP_WORDS[COMP_CWORD]}"prev="\${COMP_WORDS[COMP_CWORD-1]}"- if [[ "$prev" == "brain" ]]; then- COMPREPLY=( $(compgen -W "${brain.join(" ")}" -- "$cur") )+${groups+ .map(+ (group) => ` if [[ "$prev" == "${group.parent}" ]]; then+ COMPREPLY=( $(compgen -W "${group.children.join(" ")}" -- "$cur") )return 0- fi+ fi`,+ )+ .join("\n")}COMPREPLY=( $(compgen -W "${words.join(" ")}" -- "$cur") )}complete -F _o2b_completions o2b@@ -49,12 +52,19 @@ complete -F _o2b_completions o2b#compdef o2b_arguments \\'1:command:(${roots.join(" ")})' \\- '2:subcommand:(${[...brain, ...search, ...vault].join(" ")})' \\+ '2:subcommand:(${nested.join(" ")})' \\'*:flags:(${flags.join(" ")})'`;case "fish":return `${header}${roots.map((root) => `complete -c o2b -f -a ${quoteFish(root)}`).join("\n")}-${brain.map((verb) => `complete -c o2b -n '__fish_seen_subcommand_from brain' -f -a ${quoteFish(verb)}`).join("\n")}+${groups+ .flatMap((group) =>+ group.children.map(+ (verb) =>+ `complete -c o2b -n '__fish_seen_subcommand_from ${group.parent}' -f -a ${quoteFish(verb)}`,+ ),+ )+ .join("\n")}${flags.map((flag) => `complete -c o2b -l ${flag.slice(2)}`).join("\n")}`;case "elvish":diff --git a/src/cli/cron-recipe.ts b/src/cli/cron-recipe.tsnew file mode 100644index 00000000..00fc3b17--- /dev/null+++ b/src/cli/cron-recipe.ts@@ -0,0 +1,293 @@+/**+ * Shared renderer for every `--cron-template` recipe this CLI prints.+ *+ * A recipe is text on stdout and nothing else. It prints a script body,+ * a native crontab line, and an optional 'hermes cron create'+ * invocation; the operator (or an agent acting in the operator's name)+ * copies whichever path fits their host into their own scheduler. No+ * verb that renders a recipe writes a file, spawns a scheduler, or+ * installs anything - the writes all happen later, on the operator's+ * host, from the operator's own crontab.+ *+ * That shape was previously welded to one consumer: the search reindex+ * template hardcoded its script name, its command and its+ * change-detection expression inside the renderer, so a second consumer+ * could not reach the interval-to-cron kernel without copying the whole+ * file. This module is that kernel. The section headers, the heredoc+ * mechanics and the scheduler-recipe block now live in exactly one+ * place, and each consumer supplies a {@link CronRecipeSpec} for the+ * parts that genuinely differ.+ *+ * Duration parser accepts <N>s|m|h|d. Mapping to a cron expression+ * covers the common cadences:+ * - minutes: every N (N less than 60) maps to N-step minutes+ * - hours: every N (N less than 24) maps to N-step hours+ * - days: every N (N less than 28) maps to N-step days+ * - seconds: rejected (cron's finest grain is one minute)+ *+ * Every cron step field restarts at the head of its enclosing period, and+ * each unit is bounded so the rendered expression means what the operator+ * asked for INSIDE that period. The day bound is the strictest of the+ * three because its enclosing period varies: `*โ/N` in the day-of-month+ * field means "the 1st, then every Nth day within each month", so at 28 -+ * the shortest month - and above it collapses to the 1st of every month.+ * `--interval 90d` used to render exactly that and call it 90 days.+ *+ * Inputs outside those bounds raise a CronTemplateError naming what the+ * field can express, rather than a schedule that quietly means something+ * else.+ */++export class CronTemplateError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "CronTemplateError";+ }+}++/** Cron's minute field restarts every hour, so a step must stay under it. */+const MINUTES_PER_HOUR = 60;++/** Cron's hour field restarts every day. */+const HOURS_PER_DAY = 24;++/**+ * The shortest month, and therefore the ceiling on a day-of-month step.+ *+ * A `*โ/N` day step fires on the 1st and every Nth day after it WITHIN the+ * month; at 28 no month is long enough for a second firing, so the+ * expression is a monthly schedule whatever N says. Refusing at that+ * boundary is what keeps the rendered cadence and the requested cadence+ * the same claim.+ */+const SHORTEST_MONTH_DAYS = 28;++/** The expression an operator wanting a monthly cadence installs by hand. */+const MONTHLY_CRON_EXPRESSION = "0 0 1 * *";++export interface ParsedInterval {+ /** Cron expression for the chosen interval. */+ readonly cron: string;+ /** Human-readable label (e.g. "30 minutes"). */+ readonly human: string;+ /** Schedule string for 'hermes cron create --schedule ...'. */+ readonly hermesSchedule: string;+}++export function parseInterval(raw: string): ParsedInterval {+ const trimmed = raw.trim();+ const m = /^(\d+)\s*(s|m|h|d)$/.exec(trimmed);+ if (!m) {+ throw new CronTemplateError(+ "cannot parse interval " + JSON.stringify(raw) + ": expected <N>s|m|h|d (e.g. 30m, 6h, 1d)",+ );+ }+ const n = parseInt(m[1]!, 10);+ const unit = m[2]!;+ if (n <= 0) {+ throw new CronTemplateError("interval must be positive; got " + JSON.stringify(raw));+ }+ if (unit === "s") {+ throw new CronTemplateError(+ "cron grain is one minute -- second-level intervals are not supported",+ );+ }+ if (unit === "m") {+ if (n >= MINUTES_PER_HOUR) {+ const hours = Math.round(n / MINUTES_PER_HOUR);+ throw new CronTemplateError(+ "intervals of " ++ MINUTES_PER_HOUR ++ " minutes or more must use the h unit (e.g. " ++ hours ++ "h)",+ );+ }+ const cron = "*/" + n + " * * * *";+ return { cron, human: n + " minutes", hermesSchedule: cron };+ }+ if (unit === "h") {+ if (n >= HOURS_PER_DAY) {+ const days = Math.round(n / HOURS_PER_DAY);+ throw new CronTemplateError(+ "intervals of " + HOURS_PER_DAY + " hours or more must use the d unit (e.g. " + days + "d)",+ );+ }+ const cron = "0 */" + n + " * * *";+ return { cron, human: n + " hours", hermesSchedule: cron };+ }+ // unit === "d". The day-of-month field is the one that cannot be widened+ // by moving to a larger unit, because there is none - so the refusal+ // states what the field means and hands over the monthly expression+ // instead of rendering a step that silently becomes it.+ if (n >= SHORTEST_MONTH_DAYS) {+ throw new CronTemplateError(+ "cron's day-of-month field restarts every month, so an interval of " ++ n ++ " days cannot be expressed: '0 0 */" ++ n ++ " * *' fires on the 1st of every month, not every " ++ n ++ " days. Use an interval below " ++ SHORTEST_MONTH_DAYS ++ "d, or install a monthly job with '" ++ MONTHLY_CRON_EXPRESSION ++ "' yourself.",+ );+ }+ const cron = "0 0 */" + n + " * *";+ return { cron, human: n + " days", hermesSchedule: cron };+}++/** Options every recipe accepts. Consumers widen this with their own inputs. */+export interface CronRecipeOptions {+ /** Override the resolved o2b binary path (test seam). */+ readonly o2bBin?: string;+}++/**+ * A recipe's options with every default filled in - what the spec's+ * builders receive, so a builder never repeats a default resolution and+ * never has to answer "which binary" for itself.+ */+export type ResolvedCronRecipeOptions<TOptions extends CronRecipeOptions> = TOptions & {+ readonly o2bBin: string;+};++/**+ * Everything one recipe contributes to the shared layout. Anything not+ * named here is common to every recipe and is rendered by+ * {@link renderCronRecipe} from a single source.+ */+export interface CronRecipeSpec<TOptions extends CronRecipeOptions = CronRecipeOptions> {+ /** Header line naming the recipe, e.g. "... - periodic reindex template". */+ readonly title: string;+ /** Job name for the scheduler recipe (`hermes cron create --name`). */+ readonly cronName: string;+ /** Where the operator saves the script, in tilde form. */+ readonly scriptPath: string;+ /** Extra `##` lines under the script section, without their prefix. */+ readonly scriptNotes: ReadonlyArray<string>;+ /** Parenthetical appended to the scheduler section header. */+ readonly schedulerNote: string;+ /** The bash body placed inside the heredoc, newline-terminated. */+ readonly buildScriptBody: (opts: ResolvedCronRecipeOptions<TOptions>) => string;+ /** The command the footer tells the operator to verify the install with. */+ readonly buildVerifyCommand: (opts: ResolvedCronRecipeOptions<TOptions>) => string;+}++/** The binary name assumed when the caller does not override it. */+export const DEFAULT_O2B_BIN = "o2b";++/** Directory the recipes tell operators to keep their scripts in. */+const OPERATOR_SCRIPT_DIR = "~/.local/bin/";++/** Extension of the emitted script. */+const SCRIPT_EXTENSION = ".sh";++/** Heredoc delimiter wrapping the script body. */+const HEREDOC_MARKER = "OSBEOF";++/** Prefix of a tilde-relative home path, and its shell-variable form. */+const TILDE_HOME_PREFIX = "~/";+const SHELL_HOME_PREFIX = "$HOME/";++/** The horizontal rule that opens and closes the recipe. */+const RULE = "# ----------------------------------------------------------------------\n";++/** Prefix of the commentary lines under the script section. */+const NOTE_PREFIX = "## ";++/**+ * Conventional install path for a recipe's script, derived from the cron+ * job name so the two can never drift: `osb-reindex` becomes+ * `~/.local/bin/osb-reindex.sh`.+ */+export function operatorScriptPath(cronName: string): string {+ return OPERATOR_SCRIPT_DIR + cronName + SCRIPT_EXTENSION;+}++/**+ * Rewrite a tilde-relative path into its `$HOME` form. The scheduler+ * recipe passes the script path as a quoted argument, where a leading+ * `~` is not expanded by the shell, so the variable form is the only+ * one that resolves. Paths that are not tilde-relative pass through.+ */+function homeExpanded(path: string): string {+ return path.startsWith(TILDE_HOME_PREFIX)+ ? SHELL_HOME_PREFIX + path.slice(TILDE_HOME_PREFIX.length)+ : path;+}++/**+ * Render one recipe: header, script section, native crontab section,+ * scheduler section, footer. Throws {@link CronTemplateError} for an+ * interval cron cannot express - the caller reports it rather than+ * emitting a recipe on a cadence the scheduler would silently round.+ */+export function renderCronRecipe<TOptions extends CronRecipeOptions>(+ spec: CronRecipeSpec<TOptions>,+ interval: string,+ opts: TOptions,+): string {+ const parsed = parseInterval(interval);+ const resolved: ResolvedCronRecipeOptions<TOptions> = {+ ...opts,+ o2bBin: opts.o2bBin ?? DEFAULT_O2B_BIN,+ };+ const header =+ RULE ++ "# " ++ spec.title ++ "\n" ++ "# interval: " ++ parsed.human ++ "\n" ++ "#\n" ++ "# Pick ONE of the three paths below. The watchdog script is the\n" ++ "# common piece; both crontab and Hermes-cron rely on it.\n" ++ RULE;+ const watchdog =+ "## 1. Watchdog script - save to " ++ spec.scriptPath ++ "\n" ++ spec.scriptNotes.map((line) => NOTE_PREFIX + line + "\n").join("") ++ "\n" ++ "cat >" ++ spec.scriptPath ++ " <<'" ++ HEREDOC_MARKER ++ "'\n" ++ spec.buildScriptBody(resolved) ++ HEREDOC_MARKER ++ "\n" ++ "chmod +x " ++ spec.scriptPath ++ "\n";+ const nativeCron =+ "## 2. Native crontab - open 'crontab -e' and append:\n" ++ "\n" ++ parsed.cron ++ " " ++ spec.scriptPath ++ "\n";+ const hermesCron =+ "## 3. Hermes cron " ++ spec.schedulerNote ++ ":\n" ++ "\n" ++ "hermes cron create \\\n" ++ " --name " ++ spec.cronName ++ " \\\n" ++ " --schedule '" ++ parsed.hermesSchedule ++ "' \\\n" ++ ' --command "' ++ homeExpanded(spec.scriptPath) ++ '" \\\n' ++ " --no-agent\n";+ const footer =+ RULE + "# After install, verify with: " + spec.buildVerifyCommand(resolved) + "\n" + RULE;+ return [header, "", watchdog, "", nativeCron, "", hermesCron, "", footer].join("\n");+}diff --git a/src/cli/partner-codegraph-cron.ts b/src/cli/partner-codegraph-cron.tsnew file mode 100644index 00000000..a6eb6df0--- /dev/null+++ b/src/cli/partner-codegraph-cron.ts@@ -0,0 +1,215 @@+/**+ * `o2b partner codegraph resync --cron-template` renderer.+ *+ * An external code index goes stale the moment the repository moves ahead+ * of it, and this project deliberately owns no mechanism that would notice:+ * it refuses daemons and filesystem watchers for this purpose, and the+ * partner module's invariant - OSB never installs, initializes, or writes+ * data for codegraph - forbids the obvious alternative of re-indexing from+ * a maintenance lane. The sanctioned mechanism is a cron recipe: text on+ * stdout, in which every write is a shell command the operator's own+ * crontab runs on the operator's own host. Rendering it touches nothing.+ *+ * The emitted script runs four steps, in this order:+ *+ * 1. A health pre-flight through `o2b partner codegraph report --json`+ * that aborts non-zero when the index was built for a different root.+ * Re-indexing over a mismatched root would bake the wrong provenance+ * into the graph, so reconciling it stays an operator decision. The+ * gate needs a JSON parser and refuses to run without one, rather+ * than falling back to a text match that would answer "no mismatch"+ * for output it failed to understand.+ * 2. Change detection: the repository's current commit against a stamp+ * file on the operator's host. Unchanged means exit quietly, so the+ * common case costs one `git rev-parse`.+ * 3. The partner's own indexer, quoted from the shared partner CLI+ * vocabulary so a renamed subcommand cannot drift out of the recipe.+ * 4. A post-state verification through `--fail-on-health`. The stamp is+ * written only after that passes: a stamp written after a failed or+ * empty index would suppress every later attempt, which is exactly+ * the silence this recipe exists to end.+ */++import {+ operatorScriptPath,+ renderCronRecipe,+ type CronRecipeOptions,+ type CronRecipeSpec,+} from "./cron-recipe.ts";+import { CODEGRAPH_CLI } from "../core/partner/codegraph.ts";+import { GRAPH_HEALTH_CODES } from "../core/partner/codegraph-health.ts";++/** Inputs the codegraph recipe needs on top of the shared ones. */+export interface CodegraphResyncOptions extends CronRecipeOptions {+ /** Absolute path of the repository the emitted script keeps indexed. */+ readonly projectPath: string;+}++/** Cron job name, and the stem of the script path derived from it. */+const CODEGRAPH_RESYNC_CRON_NAME = "osb-codegraph-resync";++/**+ * Where the emitted script keeps its stamp: the operator's XDG state+ * directory, never the vault and never the partner's index. State+ * directories are for exactly this - data a program may lose without the+ * operator losing anything they authored.+ */+const STAMP_DIR_EXPRESSION = "${XDG_STATE_HOME:-$HOME/.local/state}/open-second-brain";++/** Extension of the per-repository stamp file. */+const STAMP_EXTENSION = ".stamp";++/** Characters kept verbatim in a stamp file name; everything else folds to a dash. */+const STAMP_NAME_UNSAFE = /[^A-Za-z0-9._-]+/g;++/** The `o2b partner codegraph` verb path the emitted script calls back into. */+const REPORT_COMMAND = "partner codegraph report";++/** Flag that turns the report's health verdict into its exit code. */+const FAIL_ON_HEALTH_FLAG = "--fail-on-health";++/** Flag that makes the report machine-readable. */+const JSON_FLAG = "--json";++/** The JSON parser the health gate requires. */+const JSON_PARSER = "jq";++/**+ * One stamp file per repository, named after the repository's path so two+ * recipes on one host cannot silently share a change detector and starve+ * each other of re-indexes.+ */+function stampFileName(projectPath: string): string {+ const slug = projectPath.replace(STAMP_NAME_UNSAFE, "-").replace(/^-+|-+$/g, "");+ return `${CODEGRAPH_RESYNC_CRON_NAME}-${slug}${STAMP_EXTENSION}`;+}++/**+ * The bash body of the resync script. JS-side strings are plain text: the+ * heredoc that carries them is quoted, so nothing here is interpolated by+ * the shell that installs the script, and every `$name` below is expanded+ * later, when cron runs it.+ */+function renderResyncBody(o2bBin: string, projectPath: string): string {+ const report = `${o2bBin} ${REPORT_COMMAND}`;+ const lines = [+ "#!/usr/bin/env bash",+ "set -euo pipefail",+ "",+ "# The repository this recipe keeps indexed, baked in when the recipe",+ "# was rendered. Re-render for a different repository.",+ 'project="' + projectPath + '"',+ 'stamp_dir="' + STAMP_DIR_EXPRESSION + '"',+ 'stamp_file="$stamp_dir/' + stampFileName(projectPath) + '"',+ "",+ "# 1. Health pre-flight. " + JSON_PARSER + " is REQUIRED here, not preferred:",+ "# this gate decides whether a re-index may run, and a gate that",+ "# cannot parse its input must not pass. A looser text match would",+ "# report no mismatch for output it failed to understand, so a",+ "# missing parser aborts instead of guessing.",+ "if ! command -v " + JSON_PARSER + " >/dev/null 2>&1; then",+ ' printf "%s\\n" "' ++ CODEGRAPH_RESYNC_CRON_NAME ++ ": " ++ JSON_PARSER ++ ' is required to read the health report; aborting" >&2',+ " exit 1",+ "fi",+ "",+ 'health=$(cd "$project" && ' + report + " " + JSON_FLAG + ")",+ "# An index built for another root must be reconciled by a human before",+ "# a re-index writes over it; every other finding is what re-indexing is",+ "# for, so only this one blocks.",+ // The exit status is read explicitly rather than through `if`, because+ // `if` collapses every non-zero status into one answer. This parser+ // exits 0 when the selection is truthy, 1 when it is falsy, and+ // something larger when it could not read its input at all - and a+ // bare `if` reads that last case as "no mismatch" and re-indexes over+ // a root nobody verified. Only a literal 1 is a pass.+ "mismatch_status=0",+ 'printf "%s" "$health" | ' ++ JSON_PARSER ++ " -e '[.index.health.warnings[]? | select(.code == \"" ++ GRAPH_HEALTH_CODES.cacheRootMismatch ++ "\")] | length > 0' >/dev/null || mismatch_status=$?",+ 'if [ "$mismatch_status" -eq 0 ]; then',+ ' printf "%s\\n" "' ++ CODEGRAPH_RESYNC_CRON_NAME ++ ": index was built for a different root (" ++ GRAPH_HEALTH_CODES.cacheRootMismatch ++ '); reconcile it before re-indexing" >&2',+ " exit 1",+ 'elif [ "$mismatch_status" -ne 1 ]; then',+ ' printf "%s\\n" "' ++ CODEGRAPH_RESYNC_CRON_NAME ++ ": could not read the health report (" ++ JSON_PARSER ++ ' exit $mismatch_status); aborting rather than re-indexing blind" >&2',+ " exit 1",+ "fi",+ "",+ "# 2. Change detection. The stamp holds the commit the last verified",+ "# index was built from; an unchanged commit exits quietly so the",+ "# common case costs one git call and prints nothing.",+ 'current=$(git -C "$project" rev-parse HEAD)',+ 'previous=""',+ 'if [[ -f "$stamp_file" ]]; then',+ ' previous=$(cat "$stamp_file")',+ "fi",+ 'if [[ "$current" == "$previous" ]]; then',+ " exit 0",+ "fi",+ "",+ "# 3. Re-index through the partner's own CLI. This is the operator's",+ "# command, running on the operator's host; o2b only quotes it.",+ CODEGRAPH_CLI.bin + " " + CODEGRAPH_CLI.initSubcommand + ' "$project"',+ "",+ "# 4. Verify the post-index state before recording the commit. A stamp",+ "# written after a failed or empty index would suppress every later",+ "# attempt and leave the graph quietly stale.",+ 'if ! (cd "$project" && ' ++ report ++ " " ++ JSON_FLAG ++ " " ++ FAIL_ON_HEALTH_FLAG ++ " >/dev/null); then",+ ' printf "%s\\n" "' ++ CODEGRAPH_RESYNC_CRON_NAME ++ ': re-index finished but the health gate refused the result; stamp not written" >&2',+ " exit 1",+ "fi",+ "",+ 'mkdir -p "$stamp_dir"',+ 'printf "%s\\n" "$current" >"$stamp_file"',+ ];+ return lines.join("\n") + "\n";+}++/** The resync recipe: the codegraph-specific half of the shared layout. */+export const CODEGRAPH_RESYNC_RECIPE: CronRecipeSpec<CodegraphResyncOptions> = Object.freeze<+ CronRecipeSpec<CodegraphResyncOptions>+>({+ title: "Open Second Brain - codegraph resync template",+ cronName: CODEGRAPH_RESYNC_CRON_NAME,+ scriptPath: operatorScriptPath(CODEGRAPH_RESYNC_CRON_NAME),+ scriptNotes: Object.freeze([+ "(then chmod +x). The repository is baked into the script, so a",+ "second repository needs its own script path and cron job name.",+ ]),+ schedulerNote: "(preferred when Hermes owns the host's scheduled jobs)",+ buildScriptBody: ({ o2bBin, projectPath }) => renderResyncBody(o2bBin, projectPath),+ buildVerifyCommand: ({ o2bBin }) => `${o2bBin} ${REPORT_COMMAND} ${FAIL_ON_HEALTH_FLAG}`,+});++/**+ * Render the resync recipe for one repository. Pure text: nothing is+ * created, spawned or scheduled here.+ */+export function renderCodegraphResyncTemplate(+ projectPath: string,+ interval: string,+ opts: CronRecipeOptions = {},+): string {+ return renderCronRecipe(CODEGRAPH_RESYNC_RECIPE, interval, { ...opts, projectPath });+}diff --git a/src/cli/partner.ts b/src/cli/partner.tsindex c91aa17d..826a2735 100644--- a/src/cli/partner.ts+++ b/src/cli/partner.ts@@ -5,13 +5,42 @@* top-level command rather than a `brain` verb because it inspects an external* code project, not vault memory content. Every verb here is strictly* read-only: it never installs, initializes, extracts, or mutates a partner- * index or the vault.+ * index or the vault. `resync` is no exception - it renders a cron recipe as+ * text and runs no indexer; the writes in the recipe belong to the operator's+ * own crontab, on the operator's own host.*/+import { resolve } from "node:path";+import { CliError, parseFlags } from "./argparse.ts";+import { CronTemplateError } from "./cron-recipe.ts";+import { renderCodegraphResyncTemplate } from "./partner-codegraph-cron.ts";import { defaultConfigPath, resolveVault } from "../core/config.ts";+import { isDir } from "../core/fs-utils.ts";+import { findCodeProjects } from "../core/partner/codegraph.ts";+import { summarizeGraphHealth } from "../core/partner/codegraph-health.ts";import { buildCodegraphReport, type CodegraphReport } from "../core/partner/codegraph-report.ts";+/** Both verbs, in one usage block so the two error paths cannot drift. */+const PARTNER_USAGE =+ "usage: o2b partner codegraph report [--vault <path>] [--fail-on-health] [--json]\n" ++ " o2b partner codegraph resync --cron-template [--interval <N>] " ++ "[--project <path>] [--vault <path>]\n";++/** Cadence the resync recipe uses when the caller names none. */+const DEFAULT_RESYNC_INTERVAL = "6h";++/**+ * Exit for a report whose graph health the caller asked to gate on and+ * which did not pass. Distinct from the 2 this command line reserves for a+ * mistake in the argv: nothing is wrong with the invocation here, the index+ * is simply not in a state the caller declared acceptable.+ */+const EXIT_HEALTH_REFUSED = 1;++/** Exit for an interval cron cannot express - the input is a value, not a flag error. */+const EXIT_INTERVAL_REFUSED = 1;+function resolveScopeVault(flagVal: string | undefined): string {// The report scans the cwd plus the vault parent's siblings. A configured// vault sharpens that scope; without one we fall back to the cwd so the@@ -53,8 +82,33 @@ function renderCodegraphReport(report: CodegraphReport): string {return lines.join("\n");}+/**+ * Why `--fail-on-health` refuses this report, or `null` when it passes.+ *+ * Passing requires a measured, healthy graph. An index that is absent, not+ * built, or unreadable does not pass by default: the caller asked for a gate,+ * and a gate that could not measure its subject must not report the same+ * thing as one that measured it and found it clean. Without the flag the+ * report's exit is unchanged, so nothing that reads this surface today moves.+ */+function healthGateRefusal(report: CodegraphReport): string | null {+ const idx = report.index;+ if (idx.state !== "indexed") {+ const detail = idx.reason ? ` (${idx.reason})` : "";+ return `index state is ${idx.state}${detail}, so graph health was never measured`;+ }+ if (!idx.health) {+ return "the report carries no graph-health block, so graph health was never measured";+ }+ if (idx.health.ok) return null;+ return `graph health: ${summarizeGraphHealth(idx.health)}`;+}+function codegraphReportVerb(argv: ReadonlyArray<string>): number {- const { flags, positional } = parseFlags(argv, { vault: { type: "string" } });+ const { flags, positional } = parseFlags(argv, {+ vault: { type: "string" },+ "fail-on-health": { type: "boolean" },+ });if (positional.length > 0) {throw new CliError(`partner codegraph report does not accept positional arguments: ${positional.join(" ")}`,@@ -68,23 +122,102 @@ function codegraphReportVerb(argv: ReadonlyArray<string>): number {} else {process.stdout.write(renderCodegraphReport(report) + "\n");}+ if (!flags["fail-on-health"]) return 0;+ const refusal = healthGateRefusal(report);+ if (refusal === null) return 0;+ process.stderr.write(`error: --fail-on-health: ${refusal}\n`);+ return EXIT_HEALTH_REFUSED;+}++/**+ * The repository the resync recipe is rendered for: the explicit `--project`+ * when given, otherwise the first project the same scan the report uses finds.+ * An empty scan is an error rather than a recipe for nothing - a cron job+ * pointed at no repository would run forever and index nothing.+ */+function resolveResyncProject(+ projectFlag: string | undefined,+ vaultFlag: string | undefined,+): string {+ if (projectFlag !== undefined) {+ const resolved = resolve(projectFlag);+ if (!isDir(resolved)) {+ throw new CliError(`--project ${projectFlag} is not a readable directory`);+ }+ return resolved;+ }+ const found = findCodeProjects({ cwd: process.cwd(), vault: resolveScopeVault(vaultFlag) });+ const first = found[0];+ if (first === undefined) {+ throw new CliError(+ "no code project in scope: pass --project <path> to name the repository to resync",+ );+ }+ return first;+}++/**+ * Render the resync cron recipe. `--cron-template` is required and has no+ * default-on twin: without it there is nothing this verb could honestly do.+ * Doing nothing quietly would be the silence this surface exists to end, and+ * running the partner's indexer would break the module invariant that OSB+ * never writes into the external tool's store. So it is a usage error.+ */+function codegraphResyncVerb(argv: ReadonlyArray<string>): number {+ const { flags, positional } = parseFlags(argv, {+ vault: { type: "string" },+ project: { type: "string" },+ interval: { type: "string" },+ "cron-template": { type: "boolean" },+ });+ if (positional.length > 0) {+ throw new CliError(+ `partner codegraph resync does not accept positional arguments: ${positional.join(" ")}`,+ );+ }+ if (!flags["cron-template"]) {+ throw new CliError(+ "partner codegraph resync requires --cron-template: this verb only prints a cron " ++ "recipe for the operator to install, and never runs an indexer itself",+ );+ }+ const projectPath = resolveResyncProject(+ flags["project"] as string | undefined,+ flags["vault"] as string | undefined,+ );+ const interval = (flags["interval"] as string | undefined) ?? DEFAULT_RESYNC_INTERVAL;+ try {+ process.stdout.write(renderCodegraphResyncTemplate(projectPath, interval));+ } catch (err) {+ if (err instanceof CronTemplateError) {+ process.stderr.write(`error: ${err.message}\n`);+ return EXIT_INTERVAL_REFUSED;+ }+ throw err;+ }return 0;}+/** Every codegraph verb, in one table the manifest ratchet enumerates. */+const CODEGRAPH_VERBS: Readonly<Record<string, (argv: ReadonlyArray<string>) => number>> =+ Object.freeze({+ report: codegraphReportVerb,+ resync: codegraphResyncVerb,+ });+export async function handlePartnerSubcommand(argv: ReadonlyArray<string>): Promise<number> {const partner = argv[0];const verb = argv[1];const rest = argv.slice(2);- if (partner === "codegraph" && verb === "report") {- return codegraphReportVerb(rest);- }if (partner === "codegraph") {+ const handler = verb === undefined ? undefined : CODEGRAPH_VERBS[verb];+ if (handler !== undefined) return handler(rest);process.stderr.write(`error: unknown partner codegraph subcommand: ${verb ?? "(none)"}\n`);- process.stderr.write("usage: o2b partner codegraph report [--vault <path>] [--json]\n");+ process.stderr.write(PARTNER_USAGE);return 2;}process.stderr.write(`error: unknown partner: ${partner ?? "(none)"}\n`);- process.stderr.write("usage: o2b partner codegraph report [--vault <path>] [--json]\n");+ process.stderr.write(PARTNER_USAGE);return 2;}diff --git a/src/cli/search-cron-template.ts b/src/cli/search-cron-template.tsindex 728da213..dee70297 100644--- a/src/cli/search-cron-template.ts+++ b/src/cli/search-cron-template.ts@@ -6,126 +6,53 @@* nothing. The operator (or agent in the user's name) copies what* fits their host into the cron infrastructure of choice.*- * Duration parser accepts <N>s|m|h|d. Mapping to a cron expression- * covers the common cadences:- * - minutes: every N (N less than 60) maps to N-step minutes- * - hours: every N hours maps to N-step hours- * - days: every N days maps to N-step days- * - seconds: rejected (cron's finest grain is one minute)+ * The layout, the interval parser and the heredoc mechanics live in+ * `cron-recipe.ts`, shared with every other recipe this CLI prints.+ * What stays here is what is specific to the reindex recipe: its name,+ * its command and its change-detection expression, gathered into+ * {@link SEARCH_REINDEX_RECIPE}. The extraction is required to be+ * output-preserving to the byte - `tests/cli/search-cron-template.test.ts`+ * pins the rendered text against a fixture - because operators already+ * have this script installed and a diff here is a diff in their crontab.*- * Inputs outside those bounds raise a CronTemplateError with a- * concrete suggestion (use the next unit up).+ * Every name this module exported before the extraction is still+ * exported from it, so existing importers are untouched.*/-export class CronTemplateError extends Error {- constructor(message: string) {- super(message);- this.name = "CronTemplateError";- }-}+import {+ CronTemplateError,+ operatorScriptPath,+ renderCronRecipe,+ parseInterval,+ type CronRecipeOptions,+ type CronRecipeSpec,+ type ParsedInterval,+} from "./cron-recipe.ts";-interface ParsedInterval {- /** Cron expression for the chosen interval. */- readonly cron: string;- /** Human-readable label (e.g. "30 minutes"). */- readonly human: string;- /** Schedule string for 'hermes cron create --schedule ...'. */- readonly hermesSchedule: string;-}+export { CronTemplateError, parseInterval };+export type { ParsedInterval };-export function parseInterval(raw: string): ParsedInterval {- const trimmed = raw.trim();- const m = /^(\d+)\s*(s|m|h|d)$/.exec(trimmed);- if (!m) {- throw new CronTemplateError(- "cannot parse interval " + JSON.stringify(raw) + ": expected <N>s|m|h|d (e.g. 30m, 6h, 1d)",- );- }- const n = parseInt(m[1]!, 10);- const unit = m[2]!;- if (n <= 0) {- throw new CronTemplateError("interval must be positive; got " + JSON.stringify(raw));- }- if (unit === "s") {- throw new CronTemplateError(- "cron grain is one minute -- second-level intervals are not supported",- );- }- if (unit === "m") {- if (n >= 60) {- const hours = Math.round(n / 60);- throw new CronTemplateError(- "intervals of 60 minutes or more must use the h unit (e.g. " + hours + "h)",- );- }- const cron = "*/" + n + " * * * *";- return { cron, human: n + " minutes", hermesSchedule: cron };- }- if (unit === "h") {- if (n >= 24) {- const days = Math.round(n / 24);- throw new CronTemplateError(- "intervals of 24 hours or more must use the d unit (e.g. " + days + "d)",- );- }- const cron = "0 */" + n + " * * *";- return { cron, human: n + " hours", hermesSchedule: cron };- }- // unit === "d"- const cron = "0 0 */" + n + " * *";- return { cron, human: n + " days", hermesSchedule: cron };-}+export type RenderCronTemplateOptions = CronRecipeOptions;-export interface RenderCronTemplateOptions {- /** Override the resolved o2b binary path (test seam). */- readonly o2bBin?: string;-}+/** Cron job name, and the stem of the script path derived from it. */+const SEARCH_REINDEX_CRON_NAME = "osb-reindex";++/** The reindex recipe: the reindex-specific half of the shared layout. */+export const SEARCH_REINDEX_RECIPE: CronRecipeSpec = Object.freeze<CronRecipeSpec>({+ title: "Open Second Brain - periodic reindex template",+ cronName: SEARCH_REINDEX_CRON_NAME,+ scriptPath: operatorScriptPath(SEARCH_REINDEX_CRON_NAME),+ scriptNotes: Object.freeze([+ "(then chmod +x). Sources ~/.hermes/.env if present so the",+ "embedding API key lands in the environment.",+ ]),+ schedulerNote: "(preferred when Hermes is the embedding owner)",+ buildScriptBody: ({ o2bBin }) => renderWatchdogBody(o2bBin),+ buildVerifyCommand: ({ o2bBin }) => o2bBin + " search status",+});export function renderCronTemplate(interval: string, opts: RenderCronTemplateOptions = {}): string {- const parsed = parseInterval(interval);- const o2bBin = opts.o2bBin ?? "o2b";- const watchdogBody = renderWatchdogBody(o2bBin);- const header =- "# ----------------------------------------------------------------------\n" +- "# Open Second Brain - periodic reindex template\n" +- "# interval: " +- parsed.human +- "\n" +- "#\n" +- "# Pick ONE of the three paths below. The watchdog script is the\n" +- "# common piece; both crontab and Hermes-cron rely on it.\n" +- "# ----------------------------------------------------------------------\n";- const watchdog =- "## 1. Watchdog script - save to ~/.local/bin/osb-reindex.sh\n" +- "## (then chmod +x). Sources ~/.hermes/.env if present so the\n" +- "## embedding API key lands in the environment.\n" +- "\n" +- "cat >~/.local/bin/osb-reindex.sh <<'OSBEOF'\n" +- watchdogBody +- "OSBEOF\n" +- "chmod +x ~/.local/bin/osb-reindex.sh\n";- const nativeCron =- "## 2. Native crontab - open 'crontab -e' and append:\n" +- "\n" +- parsed.cron +- " ~/.local/bin/osb-reindex.sh\n";- const hermesCron =- "## 3. Hermes cron (preferred when Hermes is the embedding owner):\n" +- "\n" +- "hermes cron create \\\n" +- " --name osb-reindex \\\n" +- " --schedule '" +- parsed.hermesSchedule +- "' \\\n" +- ' --command "$HOME/.local/bin/osb-reindex.sh" \\\n' +- " --no-agent\n";- const footer =- "# ----------------------------------------------------------------------\n" +- "# After install, verify with: " +- o2bBin +- " search status\n" +- "# ----------------------------------------------------------------------\n";- return [header, "", watchdog, "", nativeCron, "", hermesCron, "", footer].join("\n");+ return renderCronRecipe(SEARCH_REINDEX_RECIPE, interval, opts);}function renderWatchdogBody(o2bBin: string): string {diff --git a/src/core/bench/fixture.ts b/src/core/bench/fixture.tsindex 15d98083..7e000cac 100644--- a/src/core/bench/fixture.ts+++ b/src/core/bench/fixture.ts@@ -8,10 +8,10 @@* against traversal and absolutes at parse time.*/-import { createHash } from "node:crypto";import { mkdirSync, readFileSync, writeFileSync } from "node:fs";import { dirname, isAbsolute, join, normalize } from "node:path";+import { canonicalJson, sha256Hex } from "../integrity/digest.ts";import { appendContinuityRecord } from "../brain/continuity/store.ts";import {BENCH_CATEGORIES,@@ -73,9 +73,13 @@ export function loadBenchFixture(path: string): BenchFixture {return parseBenchFixture(JSON.parse(readFileSync(path, "utf8")));}+/** Hex characters kept from the fixture digest - enough to name a fixture in a+ * report without carrying a full 64-character hash through every line. */+const FIXTURE_HASH_HEX_CHARS = 16;+/** Canonical content hash - stable across key order, sensitive to content. */export function fixtureHash(fixture: BenchFixture): string {- return createHash("sha256").update(canonicalJson(fixture)).digest("hex").slice(0, 16);+ return sha256Hex(canonicalJson(fixture)).slice(0, FIXTURE_HASH_HEX_CHARS);}/** Write the fixture's notes and continuity records into a disposable vault. */@@ -213,15 +217,3 @@ function stringArray(value: unknown): ReadonlyArray<string> | undefined {if (!value.every((item) => typeof item === "string" && item.length > 0)) return undefined;return Object.freeze([...value]);}--/** JSON with recursively sorted object keys - the canonical hash input. */-function canonicalJson(value: unknown): string {- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;- if (value !== null && typeof value === "object") {- const entries = Object.entries(value as Record<string, unknown>)- .toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))- .map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`);- return `{${entries.join(",")}}`;- }- return JSON.stringify(value) ?? "null";-}diff --git a/src/core/brain/active-budget.ts b/src/core/brain/active-budget.tsindex e87c425c..0e877ca3 100644--- a/src/core/brain/active-budget.ts+++ b/src/core/brain/active-budget.ts@@ -8,16 +8,66 @@* section-aware truncation core: sections drop in fixed priority* order - recently retired first, then quarantine, then most-applied,* with the confirmed rules (and the document preamble) surviving- * longest - and a one-line notice points the agent at `brain_context`- * for the full view.+ * longest - and a one-line notice names the sections that went, says+ * how many characters survived out of how many, and points the agent at+ * `brain_context` for the full view.** Pure and deterministic; the hook stays a thin IO shell.*/-import { applySectionBudget, type BudgetSection } from "./text/text-budget.ts";+import {+ applySectionBudget,+ type BudgetSection,+ type SectionTruncationReport,+} from "./text/text-budget.ts";-export const ACTIVE_TRUNCATION_NOTICE =- "_Injection truncated to budget. Call `brain_context` (or read `Brain/active.md`) for the full preference set._";+/**+ * Separator between a section's ordinal and its heading inside a budget+ * key. The ordinal keeps keys unique when a vault renders two sections+ * with the same heading; the notice strips it back off, so the two sides+ * share the character rather than each spelling it.+ */+const SECTION_KEY_SEPARATOR = ":";++/** The Markdown level every active.md section heading is rendered at. */+const HEADING_PREFIX = "## ";++/** Key of the slice holding everything before the first heading. */+const PREAMBLE_KEY = "preamble";++/**+ * The truncation notice, built from the budgeter's own report.+ *+ * It used to be a fixed sentence. The budgeter has always returned the+ * list of keys it dropped, and the caller has always discarded it, so an+ * agent whose quarantine rules had just been evicted was told only that+ * "the injection was truncated" - the exact silence this release exists+ * to close. Naming the sections is safe because they are headings THIS+ * project renders, never operator or user text: no content crosses into+ * the notice, only keys and two integers.+ */+export function activeTruncationNotice(report: SectionTruncationReport): string {+ const dropped =+ report.droppedKeys.length > 0+ ? ` Dropped: ${report.droppedKeys.map(sectionLabel).join(", ")}.`+ : "";+ return (+ `_Injection truncated to budget: kept ${report.keptChars} of ${report.totalChars} ` ++ `characters.${dropped} Call \`brain_context\` (or read \`Brain/active.md\`) ` ++ "for the full preference set._"+ );+}++/**+ * Human-readable name of a dropped section: the ordinal prefix and the+ * Markdown heading marker removed, leaving the heading as the operator+ * reads it in `Brain/active.md`.+ */+function sectionLabel(key: string): string {+ const at = key.indexOf(SECTION_KEY_SEPARATOR);+ const heading = at === -1 ? key : key.slice(at + SECTION_KEY_SEPARATOR.length);+ return heading.startsWith(HEADING_PREFIX) ? heading.slice(HEADING_PREFIX.length) : heading;+}/*** Drop priority per known section heading; lower survives longer.@@ -34,10 +84,10 @@ export const SECTION_PRIORITIES: ReadonlyArray<{readonly prefix: string;readonly priority: number;}> = [- { prefix: "## Confirmed", priority: 0 },- { prefix: "## Most-applied", priority: 1 },- { prefix: "## Quarantine", priority: 3 },- { prefix: "## Recently retired", priority: 4 },+ { prefix: `${HEADING_PREFIX}Confirmed`, priority: 0 },+ { prefix: `${HEADING_PREFIX}Most-applied`, priority: 1 },+ { prefix: `${HEADING_PREFIX}Quarantine`, priority: 3 },+ { prefix: `${HEADING_PREFIX}Recently retired`, priority: 4 },];/**@@ -66,7 +116,7 @@ export function priorityFor(heading: string): number {export function splitSections(body: string): BudgetSection[] {const lines = body.split("\n");const sections: BudgetSection[] = [];- let currentKey = "preamble";+ let currentKey = PREAMBLE_KEY;let currentPriority = 0;let buffer: string[] = [];@@ -76,7 +126,7 @@ export function splitSections(body: string): BudgetSection[] {while (buffer.length > 0 && buffer[buffer.length - 1] === "") buffer.pop();if (buffer.length === 0) return;sections.push({- key: `${sections.length}:${currentKey}`,+ key: `${sections.length}${SECTION_KEY_SEPARATOR}${currentKey}`,priority: currentPriority,text: buffer.join("\n"),});@@ -84,11 +134,11 @@ export function splitSections(body: string): BudgetSection[] {};for (const line of lines) {- if (line.startsWith("## ")) {+ if (line.startsWith(HEADING_PREFIX)) {// The preamble merges into the first heading's section so the// document title can never be dropped ahead of its content.- if (currentKey !== "preamble" || priorityFor(line) !== 0) flush();- if (currentKey === "preamble" && priorityFor(line) === 0) {+ if (currentKey !== PREAMBLE_KEY || priorityFor(line) !== 0) flush();+ if (currentKey === PREAMBLE_KEY && priorityFor(line) === 0) {currentKey = line;currentPriority = 0;buffer.push(line);@@ -111,7 +161,7 @@ export function splitSections(body: string): BudgetSection[] {export function budgetActiveBody(body: string, budgetChars: number): string {if (body.length <= budgetChars) return body;const result = applySectionBudget(splitSections(body), budgetChars, {- notice: ACTIVE_TRUNCATION_NOTICE,+ notice: activeTruncationNotice,});return result.body;}diff --git a/src/core/brain/config-template.ts b/src/core/brain/config-template.tsindex 95dd6e13..f17c5bc4 100644--- a/src/core/brain/config-template.ts+++ b/src/core/brain/config-template.ts@@ -56,6 +56,7 @@ import {LESSONS_LIMIT_DEFAULT,MOST_APPLIED_LIMIT_DEFAULT,MOST_APPLIED_WINDOW_DAYS_DEFAULT,+ STANDING_RULES_MAX_CHARS_DEFAULT,} from "./policy.ts";import {DEFAULT_ANTICIPATORY_MAX_TOKENS,@@ -224,7 +225,24 @@ export const BRAIN_CONFIG_TEMPLATE: ReadonlyArray<BrainTemplateBlock> = Object.fkey: "snapshots",doc: [],emit: "live",- keys: [live("retention_count", DEFAULT_BRAIN_CONFIG.snapshots.retention_count)],+ keys: [+ live("retention_count", DEFAULT_BRAIN_CONFIG.snapshots.retention_count),+ def("include_derived_store", DEFAULT_BRAIN_CONFIG.snapshots.include_derived_store === true, [+ "Also archive the derived SQLite store next to each snapshot.",+ "Off by default: the store holds embeddings and a tier baseline,",+ "which cost money to rebuild but carry no information the",+ "Markdown tree cannot replay - and every retained archive is",+ "replicated to every peer. The live store size is recorded in",+ "each snapshot manifest whether or not this is on, so the cost",+ "of turning it on is visible before you do.",+ ]),+ def("derived_store_max_bytes", DEFAULT_BRAIN_CONFIG.snapshots.derived_store_max_bytes, [+ "Refuse the snapshot when the live store is larger than this.",+ "A refusal, never a truncation: half a database is not a recovery",+ "point. Worst case on disk is this times retention_count, on every",+ "device the vault replicates to.",+ ]),+ ],},{key: "vault",@@ -245,12 +263,18 @@ export const BRAIN_CONFIG_TEMPLATE: ReadonlyArray<BrainTemplateBlock> = Object.f{key: "active",- doc: ["Tuning for the active.md body injected at SessionStart."],+ doc: [+ "Tuning for the active.md body injected at SessionStart.",+ "standing_rules_max_chars caps the operator-authored",+ "Brain/standing-rules.md block, which is injected first and is",+ "exempt from inject_budget_chars - hence its own number.",+ ],emit: "commented-default",keys: [def("most_applied_window_days", MOST_APPLIED_WINDOW_DAYS_DEFAULT),def("most_applied_limit", MOST_APPLIED_LIMIT_DEFAULT),def("inject_budget_chars", INJECT_BUDGET_CHARS_DEFAULT),+ def("standing_rules_max_chars", STANDING_RULES_MAX_CHARS_DEFAULT),],},{diff --git a/src/core/brain/context-receipts.ts b/src/core/brain/context-receipts.tsindex 9ac6497d..25801119 100644--- a/src/core/brain/context-receipts.ts+++ b/src/core/brain/context-receipts.ts@@ -1,4 +1,4 @@-import { createHash } from "node:crypto";+import { sha256Hex } from "../integrity/digest.ts";import {appendContinuityRecord,@@ -120,7 +120,7 @@ export function emitContextReceipt(...(item.evidenceRefs && item.evidenceRefs.length > 0? { evidence_refs: [...item.evidenceRefs] }: {}),- ...(item.text ? { text_hash: sha256(item.text) } : {}),+ ...(item.text ? { text_hash: sha256Hex(item.text) } : {}),}));const payload: Record<string, unknown> = {host: input.options.host,@@ -128,7 +128,7 @@ export function emitContextReceipt(...(input.options.sessionId ? { session_id: input.options.sessionId } : {}),...(input.options.turnId ? { turn_id: input.options.turnId } : {}),item_count: input.items.length,- final_text_hash: sha256(input.finalText),+ final_text_hash: sha256Hex(input.finalText),final_text_chars: [...input.finalText].length,items: itemPayloads,...(input.budget ? { budget: input.budget } : {}),@@ -141,7 +141,7 @@ export function emitContextReceipt(sourceRefs: input.items.map((item) => ({id: item.id,...(item.path ? { path: item.path } : {}),- ...(item.text ? { hash: sha256(item.text) } : {}),+ ...(item.text ? { hash: sha256Hex(item.text) } : {}),})),payload,});@@ -462,10 +462,6 @@ export const CONTEXT_RECEIPT_TRIGGERS: ReadonlyArray<ContextReceiptTrigger> = Ob"session_inject",]);-function sha256(text: string): string {- return createHash("sha256").update(text, "utf8").digest("hex");-}-function matchesReceiptFilter(record: ContinuityRecord, filter: ContextReceiptFilter): boolean {const payload = record.payload;if (filter.trigger !== undefined && payload["trigger"] !== filter.trigger) return false;diff --git a/src/core/brain/continuity/types.ts b/src/core/brain/continuity/types.tsindex 9a6beb55..13cac407 100644--- a/src/core/brain/continuity/types.ts+++ b/src/core/brain/continuity/types.ts@@ -47,7 +47,14 @@ export type ContinuityRecordKind =| "host_memory_write"| "recall_observed_use"| "skill_invoked"- | "source_invalidation";+ | "source_invalidation"+ /**+ * One typed negative-recall verdict and the coverage receipt behind it+ * (silence-is-not-an-answer, U2). Written by the recall gate under the+ * `recall_gate_telemetry` opt-in so the corpus statement a "no" rested+ * on stays auditable after the answer has been given.+ */+ | "negative_recall";export type ContinuityPayload = Readonly<Record<string, unknown>>;diff --git a/src/core/brain/decisions/receipts.ts b/src/core/brain/decisions/receipts.tsindex 756583c3..bf77de6f 100644--- a/src/core/brain/decisions/receipts.ts+++ b/src/core/brain/decisions/receipts.ts@@ -66,6 +66,13 @@ const FIELD_MAX_LEN = 2000;/** Default page size for {@link queryDecisionChangeHistory}. */export const DECISION_HISTORY_DEFAULT_LIMIT = 50;+/**+ * The one `errno` that means the receipt store was never created, as+ * opposed to created and unreachable. See+ * {@link readDecisionChangeReceipts}.+ */+const DIR_ABSENT_ERRNO = "ENOENT";+/** Every failure path in this module raises this typed error. */export class ReceiptError extends Error {constructor(message: string, options?: ErrorOptions) {@@ -263,7 +270,10 @@ export function appendDecisionChangeReceipt(const idempotencyKey = computeIdempotencyKey(subject, before, after);- // Idempotency: a matching key already on disk makes this a no-op.+ // Idempotency: a matching key already on disk makes this a no-op. The+ // read raises rather than reporting an empty store when the directory+ // exists and cannot be listed, so a replay under a denied read refuses+ // instead of appending a second copy of the same change.const existing = readDecisionChangeReceipts(vault).receipts.find((r) => r.idempotency_key === idempotencyKey,);@@ -329,15 +339,46 @@ export interface ReadReceiptsResult {/*** Read every receipt merged across device shards, sorted by* (ts, shardId, line). Fail-closed per line: a malformed or- * unknown-version line surfaces as a warning, never throws. Never writes.+ * unknown-version line surfaces as a warning. Never writes.+ *+ * ## An unreadable directory is not an empty one+ *+ * The directory read used to be wrapped in a bare `catch` returning no+ * receipts and no warnings, which gave a vault whose `Brain/truth/` the+ * process cannot enter exactly the answer a vault that has never+ * recorded a decision gets. Two consequences, both real:+ *+ * - every read surface - the history query, the audit join - reported+ * "no decisions" for a store it had not looked at;+ * - the idempotency probe in {@link appendDecisionChangeReceipt} reads+ * through this function, so an unreadable directory read as "no+ * prior receipt with this key" and the append went ahead. The one+ * guard against a duplicated accountability record was disabled by+ * precisely the condition under which it mattered most.+ *+ * So only ABSENCE is quiet, and it is quiet because a vault that has+ * never appended a receipt legitimately has no directory. Every other+ * failure - a permission denial, a file standing where the directory+ * should be, an I/O error - raises {@link ReceiptError} naming the path.+ * Per-shard failures below stay warnings: there the reader knows what it+ * did and did not read, and can say so.+ *+ * @throws {@link ReceiptError} when the receipt directory exists and+ * cannot be listed.*/export function readDecisionChangeReceipts(vault: string): ReadReceiptsResult {const dir = receiptsDir(vault);let names: string[];try {names = readdirSync(dir).toSorted();- } catch {- return { receipts: [], warnings: [] };+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === DIR_ABSENT_ERRNO) {+ return { receipts: [], warnings: [] };+ }+ throw new ReceiptError(+ `receipt: failed to list ${dir}: ${(err as Error).message ?? String(err)}`,+ { cause: err },+ );}interface Tagged {diff --git a/src/core/brain/deep-synthesis.ts b/src/core/brain/deep-synthesis.tsindex 54a51efe..bbdfdacb 100644--- a/src/core/brain/deep-synthesis.ts+++ b/src/core/brain/deep-synthesis.ts@@ -14,10 +14,10 @@* (Kernel B) via {@link synthesisCandidates}.*/-import { createHash } from "node:crypto";import { readFileSync, statSync } from "node:fs";import { join } from "node:path";+import { sha256Hex } from "../integrity/digest.ts";import { search } from "../search/search.ts";import { walkVault } from "../search/walker.ts";import type { BrainSearchResult, ResolvedSearchConfig } from "../search/types.ts";@@ -275,11 +275,6 @@ function noteNames(path: string): ReadonlySet<string> {return new Set(slash >= 0 ? [page, page.slice(slash + 1)] : [page]);}-/** Lowercase hex sha256 of a string; ties evidence identity to content. */-function sha256Hex(text: string): string {- return createHash("sha256").update(text, "utf8").digest("hex");-}-/*** Recency in [0,1]: 1 the day a note is touched, decaying linearly to 0* at the stale-age horizon and staying 0 beyond it. Rounded to fourdiff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.tsindex fbfba67d..4e5e2f20 100644--- a/src/core/brain/diagnostics.ts+++ b/src/core/brain/diagnostics.ts@@ -199,6 +199,18 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new MapnextCommand: "o2b brain backlinks",autoRepairable: false,},+ {+ // U3, silence-is-not-an-answer. The reverse of the backlink+ // question above: not "this reference points at nothing" but+ // "this reference points at something that has since changed,+ // and the thing holding it predates the change". The trail of+ // the state itself is where an operator starts, because it says+ // what the rule became and why.+ code: "stale-dependency",+ issueClass: "consumer resting on a superseded state",+ nextCommand: "o2b brain audit <pref-id>",+ autoRepairable: false,+ },{code: "sync-conflict-log",issueClass: "sync-conflict log copy",diff --git a/src/core/brain/diarization.ts b/src/core/brain/diarization.tsindex 69d716c6..0055daa3 100644--- a/src/core/brain/diarization.ts+++ b/src/core/brain/diarization.ts@@ -19,9 +19,9 @@* prose stays with the calling agent, never inside core.*/-import { createHash } from "node:crypto";import { posix, relative } from "node:path";+import { sha256Hex } from "../integrity/digest.ts";import { decomposeAtomicFacts, type AtomicEntityLike } from "./atomic-facts.ts";import { hasEvidenceIdentity, type EvidenceIdentity } from "./deep-synthesis.ts";import { getEntity } from "./entities/registry.ts";@@ -105,11 +105,6 @@ export interface DiarizationOptions {readonly now: Date;}-/** Lowercase hex sha256; ties evidence identity to content. */-function sha256Hex(text: string): string {- return createHash("sha256").update(text, "utf8").digest("hex");-}-function toPosixRel(vault: string, abs: string): string {return relative(vault, abs).split(/[\\/]/).join(posix.sep);}diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex 97f5fd2c..e19f61bb 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -69,6 +69,8 @@ import {readAllPreferenceRecords,} from "./doctor/records.ts";import { removedToolReferenceCheck } from "./doctor/removed-tool-checks.ts";+import { makeStaleDependencyCheck } from "./doctor/stale-dependency-check.ts";+import { auditStaleDependencies } from "./stale-dependency.ts";import { checkSemanticHealth } from "./doctor/semantic-health-check.ts";import {danglingWorkrunCheck,@@ -135,6 +137,11 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([duplicateIdCheck,logShardCheck,brokenBacklinkCheck,+ // The one check whose collector is supplied rather than imported: its+ // pure kernel is the leaf both halves share, so this registry - which+ // already reaches every check module and the store beneath them - is+ // where the two meet without closing a loop.+ makeStaleDependencyCheck(auditStaleDependencies),removedToolReferenceCheck,duplicatePreferenceCheck,lowEvidenceConfirmedCheck,diff --git a/src/core/brain/doctor/records.ts b/src/core/brain/doctor/records.tsindex 1516b15d..b856074a 100644--- a/src/core/brain/doctor/records.ts+++ b/src/core/brain/doctor/records.ts@@ -4,7 +4,9 @@* Built once per pass and handed round on the check context, so the* three preference-walking lints do not each re-parse* `Brain/preferences/` and the two log-walking lints do not each re-read- * `Brain/log/`.+ * `Brain/log/`. The retired snapshot joins them for the same reason: a+ * check that needs the supersession instants should be handed records,+ * not a directory to walk on its own terms.** Each reader takes an optional sweep sink. WITH one - the doctor pass,* which resolves this context before any check runs and therefore before@@ -19,7 +21,7 @@ import { join } from "node:path";import { listLogDates, readLogDay } from "../log-jsonl.ts";import { brainDirs } from "../paths.ts";-import { parsePreference } from "../preference.ts";+import { parsePreference, parseRetired } from "../preference.ts";import {readSweptDir,reportSweptFailure,@@ -32,11 +34,25 @@ export interface PreferenceRecord {readonly pref: import("../types.ts").BrainPreference;}+export interface RetiredRecord {+ readonly path: string;+ readonly retired: import("../types.ts").BrainRetired;+}+export interface LogRecord {readonly date: string;readonly entries: ReadonlyArray<import("../log.ts").BrainLogEntry>;}+/** Filename prefix of a preference file; also its id prefix. */+const PREFERENCE_FILE_PREFIX = "pref-";++/** Filename prefix of a retired file; also its id prefix. */+const RETIRED_FILE_PREFIX = "ret-";++/** Extension every Brain record file carries. */+const MARKDOWN_EXT = ".md";+/*** The entries of `dir`, or `null` when there are none to read.*@@ -68,7 +84,7 @@ export function readAllPreferenceRecords(const out: PreferenceRecord[] = [];for (const entry of entries) {const name = entry.name;- if (!name.endsWith(".md") || !name.startsWith("pref-")) continue;+ if (!name.endsWith(MARKDOWN_EXT) || !name.startsWith(PREFERENCE_FILE_PREFIX)) continue;const path = join(dirs.preferences, name);try {out.push({ path, pref: parsePreference(path) });@@ -79,6 +95,41 @@ export function readAllPreferenceRecords(return out;}+/**+ * The same pre-parsed snapshot for `Brain/retired/`.+ *+ * Retirement is the store's supersession event: `moveToRetired` stamps+ * `retired_at` and the lint that wants to know which consumers predate+ * that instant needs the records, not the directory. Reading them here+ * rather than inside the check keeps the parse discipline identical to+ * the preference snapshot above - one place decides what a record is,+ * and one sweep sink decides what an unreadable directory means.+ *+ * Files that fail to parse are omitted, exactly as above: a retired file+ * whose frontmatter is wrong is already a finding of the retired record+ * check, and reporting it twice would say nothing new.+ */+export function readAllRetiredRecords(+ vault: string,+ swept?: SweptPath,+): ReadonlyArray<RetiredRecord> {+ const dirs = brainDirs(vault);+ const entries = listRecordDir(dirs.retired, swept);+ if (entries === null) return [];+ const out: RetiredRecord[] = [];+ for (const entry of entries) {+ const name = entry.name;+ if (!name.endsWith(MARKDOWN_EXT) || !name.startsWith(RETIRED_FILE_PREFIX)) continue;+ const path = join(dirs.retired, name);+ try {+ out.push({ path, retired: parseRetired(path) });+ } catch {+ // schema error โ reported by the retired record check+ }+ }+ return out;+}+/*** Build a single pre-parsed snapshot of `Brain/log/` so the two* log-walking lints don't each re-parse the directory.@@ -143,8 +194,8 @@ export function collectAllBasenames(vault: string, swept?: SweptPath): ReadonlySif (entries === null) continue;for (const entry of entries) {if (!entry.isFile()) continue;- if (!entry.name.endsWith(".md")) continue;- out.add(entry.name.slice(0, -".md".length));+ if (!entry.name.endsWith(MARKDOWN_EXT)) continue;+ out.add(entry.name.slice(0, -MARKDOWN_EXT.length));}}return out;diff --git a/src/core/brain/doctor/stale-dependency-check.ts b/src/core/brain/doctor/stale-dependency-check.tsnew file mode 100644index 00000000..81acbc49--- /dev/null+++ b/src/core/brain/doctor/stale-dependency-check.ts@@ -0,0 +1,522 @@+/**+ * U3 - who is still standing on ground that moved?+ *+ * Supersession in this store runs one way. `moveToRetired` stamps+ * `retired_at` on a rule, `tombstone` stamps `tombstoned_at` on a memory,+ * `temporalReplace` closes a fact's `valid_until` - and each of them+ * writes the record forward. Nothing walks the other way. A decision+ * receipt written last month naming a rule retired last week reads today+ * exactly like one naming a rule that still holds, and so does a live+ * artifact whose body still cites it. The state changed; every consumer+ * of it kept its original appearance.+ *+ * This check is that reverse walk: given a state that changed at T, name+ * the consumers written strictly before T that still cite it.+ *+ * ## What already exists, at a different granularity+ *+ * `pack-stamp.ts` and the anticipatory cache already perform a BACKWARD+ * invalidation of a sort: a persisted context pack carries a digest over+ * the whole Brain tree plus the corpus generation, and a cached pack+ * whose digest no longer matches is discarded. That is a coarse,+ * whole-tree, binary answer - something under `Brain/` moved, so this+ * cached blob is suspect - and it is the right answer for a cache. It+ * cannot say WHICH state moved, WHICH consumers rest on it, or that a+ * consumer written after the move is fine. This check is the per-edge+ * reading of the same question, and it deliberately reuses none of that+ * machinery: a digest that changes on any byte is the wrong instrument+ * for naming one edge.+ *+ * ## The consumer side reads receipts, not outcomes+ *+ * `brain_context_pack_outcome` is a SELF-REPORTED row - an agent saying+ * how a pack went - and it does not record what the pack contained. The+ * record carrying the consumed item list is the `context_receipt`+ * continuity record, whose `payload.items[].id` is the injected set. The+ * join reads those.+ *+ * ## Never-measured is not clean+ *+ * Receipt emission is opt-in. A vault with the telemetry gate off has+ * zero receipts, and a join over zero consumers finds zero problems -+ * which is byte-identical to a vault whose consumers are all current.+ * `ContextReceiptFoldEmpty` in `context-receipts.ts` exists for exactly+ * this reason, and the report inherits its contract: `recorded: false`+ * says the mechanism did not run, and the check pushes no issue for it+ * rather than reporting a clean bill of health over an unmeasured store.+ *+ * ## The split+ *+ * {@link joinStaleDependencies} is pure - two lists in, rows out, no+ * clock, no filesystem - so every rule below is reachable from a unit+ * test without a vault. The collection lives in+ * `../stale-dependency.ts`, in the pure-kernel / impure-collector shape+ * `maintenance/action-scorer.ts` and `partner/codegraph-health.ts`+ * already use.+ *+ * This module is the LEAF of that pair: the collector imports the kernel,+ * the vocabularies and the constants from here, and nothing here imports+ * the collector. The check still needs one, so it takes it as an argument+ * - {@link makeStaleDependencyCheck} - and `doctor.ts`, which is already+ * the registry and therefore already the place both halves meet, supplies+ * it. Importing the collector directly instead would close a loop between+ * two modules that each define something the other needs, which is the+ * shape `tests/core/architecture/import-cycles.test.ts` refuses.+ */++import type { DoctorCheck } from "./check.ts";+import { reportSweptFailure, SWEEP_ORIGIN } from "./unreadable-path.ts";++// ----- Constants ------------------------------------------------------------++/** Doctor issue code for a consumer resting on a state that has changed. */+export const STALE_DEPENDENCY_CODE = "stale-dependency";++/** Subsystem name the collector's failed reads are reported under. */+const STALE_DEPENDENCY_SITE = "brain.doctor.staleDependency";++/**+ * What an operator reads when states changed and nothing recorded what+ * consumed them. It names the mechanism rather than the absence, because+ * the honest statement is about the measurement and not about the store,+ * and it carries the count so the sentence says how much is unaccounted+ * for rather than merely that something is.+ */+function STALE_DEPENDENCY_UNMEASURED(statesChanged: number): string {+ const states = statesChanged === 1 ? "1 state" : `${statesChanged} states`;+ return (+ `context and decision consumers were not measured: ${states} stopped being current and ` ++ "no context receipts or decision-change receipts were recorded in the audit window, so " ++ "packs and decisions built on them cannot be checked; live records citing them are " ++ "reported above"+ );+}++/**+ * How far back the consumer scan reaches, in days.+ *+ * A window rather than the whole history, because a receipt from two+ * years ago names a context that no longer exists in any working sense:+ * the row would be true and useless. Ninety days is one quarter - long+ * enough to span a retirement and the work that followed it, short+ * enough that the scan reads a bounded number of month shards.+ */+export const STALE_DEPENDENCY_LOOKBACK_DAYS = 90;++/**+ * Consumers reported per state.+ *+ * A rule cited by four hundred receipts produces one finding, not four+ * hundred lines of it. The cap bounds what is PRINTED; the row still+ * carries the true total, so the operator is never shown a prefix that+ * looks like the whole set.+ */+export const STALE_DEPENDENCY_MAX_CONSUMERS_PER_STATE = 20;++// ----- Vocabularies ---------------------------------------------------------++/**+ * What kind of thing is resting on the changed state.+ *+ * Closed, because the three arms are read from three different stores+ * and an operator acting on a row needs to know which: a context receipt+ * is retrieval history, a decision-change receipt is an accountability+ * record, and a Brain artifact is a live file that can be edited.+ */+export const STALE_DEPENDENCY_CONSUMER = Object.freeze({+ /** A `context_receipt` continuity record that injected the state. */+ contextReceipt: "context_receipt",+ /** A `decision_change.v1` receipt whose evidence cited the state. */+ decisionChange: "decision_change",+ /** A live Brain artifact whose links still reach the state. */+ brainArtifact: "brain_artifact",+} as const);++export type StaleDependencyConsumerKind =+ (typeof STALE_DEPENDENCY_CONSUMER)[keyof typeof STALE_DEPENDENCY_CONSUMER];++/** Every consumer kind, in declaration order. */+export const STALE_DEPENDENCY_CONSUMERS: ReadonlyArray<StaleDependencyConsumerKind> = Object.freeze(+ [+ STALE_DEPENDENCY_CONSUMER.contextReceipt,+ STALE_DEPENDENCY_CONSUMER.decisionChange,+ STALE_DEPENDENCY_CONSUMER.brainArtifact,+ ],+);++export function isStaleDependencyConsumerKind(+ value: unknown,+): value is StaleDependencyConsumerKind {+ return (+ typeof value === "string" &&+ (STALE_DEPENDENCY_CONSUMERS as ReadonlyArray<string>).includes(value)+ );+}++/**+ * How the state stopped being current.+ *+ * Three writers, three shapes on disk, one question. Naming the kind on+ * the row is what lets an operator go to the right remedy: a retired+ * rule has an audit trail, a tombstoned memory has a reason field, and a+ * closed validity interval has a successor fact.+ */+export const STALE_DEPENDENCY_STATE = Object.freeze({+ /** A preference `moveToRetired` renamed into `Brain/retired/`. */+ retired: "retired",+ /** An artifact `tombstone` marked, carrying `tombstoned_at`. */+ tombstoned: "tombstoned",+ /** A fact whose `valid_until` has closed, per `temporalReplace`. */+ validityClosed: "validity_closed",+} as const);++export type StaleDependencyStateKind =+ (typeof STALE_DEPENDENCY_STATE)[keyof typeof STALE_DEPENDENCY_STATE];++/** Every state kind, in declaration order. */+export const STALE_DEPENDENCY_STATES: ReadonlyArray<StaleDependencyStateKind> = Object.freeze([+ STALE_DEPENDENCY_STATE.retired,+ STALE_DEPENDENCY_STATE.tombstoned,+ STALE_DEPENDENCY_STATE.validityClosed,+]);++export function isStaleDependencyStateKind(value: unknown): value is StaleDependencyStateKind {+ return (+ typeof value === "string" && (STALE_DEPENDENCY_STATES as ReadonlyArray<string>).includes(value)+ );+}++// ----- Errors ---------------------------------------------------------------++/**+ * A store the audit depends on exists and could not be read.+ *+ * Raised by the collector, consumed here. It lives beside the reporting+ * rather than beside the reading because everything it carries exists+ * for the uncertainty entry: the path and the attempted action are what+ * that entry names, and the original error travels as `cause` so the+ * sweep can still read the `errno` and tell an absent optional directory+ * from one it failed to enter.+ */+export class StaleDependencyReadError extends Error {+ readonly path: string;+ readonly action: string;++ constructor(action: string, path: string, cause: unknown) {+ super(`stale-dependency audit: ${action}: ${path}`, { cause });+ this.name = "StaleDependencyReadError";+ this.path = path;+ this.action = action;+ }+}++// ----- Shapes ---------------------------------------------------------------++/**+ * One state that stopped being current, already placed in time.+ *+ * `changed_at_ms` is supplied rather than parsed here so the kernel has+ * no branch for an instant it cannot read: deciding what an unparseable+ * timestamp means belongs to the collector, which knows which file it+ * came from and which existing lint already reports it.+ */+export interface StaleDependencyState {+ /** Folded identifier, via `brainArtifactSlug` on both sides. */+ readonly key: string;+ readonly kind: StaleDependencyStateKind;+ /** Absolute path of the file carrying the state. */+ readonly path: string;+ readonly changed_at: string;+ readonly changed_at_ms: number;+}++/** One consumer and every state key it cites. */+export interface StaleDependencyCitation {+ readonly kind: StaleDependencyConsumerKind;+ /** Receipt id, decision subject, or artifact basename. */+ readonly id: string;+ /** Absolute path, for the consumers that are files. */+ readonly path?: string;+ readonly written_at: string;+ readonly written_at_ms: number;+ /**+ * Whether the consumer is still part of the live store. A retired+ * artifact citing another retired artifact is history agreeing with+ * itself, not a dependency anybody is standing on.+ */+ readonly live: boolean;+ /** Folded state keys this consumer cites. */+ readonly cites: ReadonlyArray<string>;+}++/** One consumer as it appears on a row. */+export interface StaleDependencyConsumer {+ readonly kind: StaleDependencyConsumerKind;+ readonly id: string;+ readonly path?: string;+ readonly written_at: string;+}++/** One changed state and the consumers that predate the change. */+export interface StaleDependencyRow {+ readonly state: string;+ readonly state_kind: StaleDependencyStateKind;+ readonly state_path: string;+ readonly changed_at: string;+ /** Capped at {@link StaleDependencyJoinInput.maxConsumersPerState}. */+ readonly consumers: ReadonlyArray<StaleDependencyConsumer>;+ /** How many consumers qualified, before the cap. */+ readonly consumer_total: number;+}++export interface StaleDependencyJoinInput {+ readonly states: ReadonlyArray<StaleDependencyState>;+ readonly citations: ReadonlyArray<StaleDependencyCitation>;+ readonly maxConsumersPerState: number;+}++// ----- The join -------------------------------------------------------------++/**+ * Join changed states against the consumers that predate the change.+ *+ * A row is emitted for a (state, consumer) pair when all three hold:+ *+ * 1. the consumer cites the state, on the folded key so the pre- and+ * post-rename spellings of one rule are one key;+ * 2. the consumer was written STRICTLY before the state changed - a+ * consumer written at the same instant, or after, has already had+ * the opportunity to see the change;+ * 3. the consumer is still live.+ *+ * Two states folding to one key - a preference retired and later+ * tombstoned - keep the EARLIEST instant. That is the first moment the+ * state stopped being current, and it is the widest honest reading of+ * "written before the change".+ *+ * Deterministic throughout: consumers sort by instant then kind then id,+ * rows by instant then key, and every comparison is on code points+ * rather than locale collation so two hosts produce one order.+ */+export function joinStaleDependencies(+ input: StaleDependencyJoinInput,+): ReadonlyArray<StaleDependencyRow> {+ const states = foldStates(input.states);+ if (states.size === 0) return Object.freeze([]);+ const cap = Math.max(1, Math.floor(input.maxConsumersPerState));++ const perState = new Map<string, StaleDependencyConsumer[]>();+ for (const citation of input.citations) {+ if (!citation.live) continue;+ if (!Number.isFinite(citation.written_at_ms)) continue;+ for (const key of new Set(citation.cites)) {+ const state = states.get(key);+ if (state === undefined) continue;+ if (citation.written_at_ms >= state.changed_at_ms) continue;+ const bucket = perState.get(key);+ const consumer: StaleDependencyConsumer = Object.freeze({+ kind: citation.kind,+ id: citation.id,+ ...(citation.path !== undefined ? { path: citation.path } : {}),+ written_at: citation.written_at,+ });+ if (bucket) bucket.push(consumer);+ else perState.set(key, [consumer]);+ }+ }++ const rows: StaleDependencyRow[] = [];+ for (const [key, consumers] of perState) {+ const state = states.get(key)!;+ const ordered = consumers.toSorted(compareConsumers);+ rows.push(+ Object.freeze({+ state: key,+ state_kind: state.kind,+ state_path: state.path,+ changed_at: state.changed_at,+ consumers: Object.freeze(ordered.slice(0, cap)),+ consumer_total: ordered.length,+ }),+ );+ }+ return Object.freeze(+ rows.toSorted(+ (a, b) => compareText(a.changed_at, b.changed_at) || compareText(a.state, b.state),+ ),+ );+}++/** Earliest change per folded key; ties broken on path for determinism. */+function foldStates(+ states: ReadonlyArray<StaleDependencyState>,+): ReadonlyMap<string, StaleDependencyState> {+ const out = new Map<string, StaleDependencyState>();+ for (const state of states) {+ if (state.key === "") continue;+ const held = out.get(state.key);+ if (held === undefined) {+ out.set(state.key, state);+ continue;+ }+ if (state.changed_at_ms < held.changed_at_ms) out.set(state.key, state);+ else if (state.changed_at_ms === held.changed_at_ms && compareText(state.path, held.path) < 0) {+ out.set(state.key, state);+ }+ }+ return out;+}++function compareConsumers(a: StaleDependencyConsumer, b: StaleDependencyConsumer): number {+ return (+ compareText(a.written_at, b.written_at) ||+ compareText(a.kind, b.kind) ||+ compareText(a.id, b.id)+ );+}++/** Code-point comparison, so the order does not vary with the host locale. */+function compareText(a: string, b: string): number {+ return a < b ? -1 : a > b ? 1 : 0;+}++// ----- The check ------------------------------------------------------------++/**+ * What the operator cannot conclude when the consumer read fails.+ *+ * Written out here because `[UNSURE]` renders it verbatim, and "a+ * directory could not be read" on its own does not say which question+ * went unanswered.+ */+const STALE_DEPENDENCY_CONSEQUENCE =+ "no consumer of a superseded state was joined, so a receipt or artifact resting on a retired " ++ "rule is missing from this report";++/**+ * The collector, as the check consumes it.+ *+ * Structural rather than imported: the check reads three fields off the+ * report, and declaring them here is what keeps this module a leaf.+ * `StaleDependencyReport` satisfies it by shape.+ */+export type StaleDependencyAudit = (+ vault: string,+ opts: { readonly now: Date },+) => {+ readonly receipts_recorded: boolean;+ readonly rows: ReadonlyArray<StaleDependencyRow>;+ readonly states_changed: number;+};++/**+ * Reverse stale-dependency audit, over the collector it is handed.+ *+ * `failSoft` because this is the first check to read the continuity log,+ * and a continuity store broken in a way nothing here anticipates must+ * not blank the twenty-five findings around it. That is a backstop, not+ * the handling: the read failure this check EXPECTS - a continuity or+ * receipt directory that exists and cannot be entered - is caught below+ * and reported through the uncertainty channel, because a swallowed+ * throw is the same false clean bill of health the wave exists to+ * remove.+ *+ * A vault that recorded no receipts produces no issue, and an+ * uncertainty entry only when states actually changed in the window. The+ * report has always carried `recorded: false`, but a flag nothing+ * renders is not a statement anybody reads: through the doctor an+ * unmeasured store looked exactly like a clean one, because both+ * produced an empty issue list. The uncertainty channel is where this+ * codebase already says "the check did not run", so that is where it+ * says it - and it stays quiet when nothing was retired, tombstoned or+ * superseded, because then there is nothing whose consumers could have+ * gone stale and the unmeasured audit cost the operator nothing.+ */+export function makeStaleDependencyCheck(audit: StaleDependencyAudit): DoctorCheck {+ return {+ failSoft: true,+ run({ vault, now }, { issues, uncertain }) {+ let report;+ try {+ report = audit(vault, { now });+ } catch (err) {+ const failure = asReadFailure(err);+ reportSweptFailure(+ failure.path,+ failure.action,+ failure.cause,+ {+ site: STALE_DEPENDENCY_SITE,+ consequence: STALE_DEPENDENCY_CONSEQUENCE,+ uncertain,+ },+ SWEEP_ORIGIN.root,+ );+ return;+ }+ // The receipt-borne half is what an absent telemetry trail costs;+ // the artifact half was computed either way, so its rows are reported+ // regardless and the notice below scopes itself to what was missed.+ if (!report.receipts_recorded && report.states_changed > 0) {+ uncertain.push({+ code: STALE_DEPENDENCY_CODE,+ message: STALE_DEPENDENCY_UNMEASURED(report.states_changed),+ });+ }+ for (const row of report.rows) {+ issues.push({+ severity: "warning",+ code: STALE_DEPENDENCY_CODE,+ path: row.state_path,+ target: row.state,+ sources: Object.freeze(row.consumers.map((consumer) => consumer.id)),+ message: describeRow(row),+ });+ }+ },+ };+}++/**+ * The sentence an operator reads.+ *+ * It names the true total first and the listed subset second, so a+ * capped row can never be mistaken for the complete set - the failure+ * mode a bare list of twenty entries has.+ */+function describeRow(row: StaleDependencyRow): string {+ const listed = row.consumers.map((c) => `${c.kind} ${c.id} (${c.written_at})`).join(", ");+ const shown =+ row.consumer_total > row.consumers.length+ ? `, showing ${row.consumers.length} of them: ${listed}`+ : `: ${listed}`;+ return (+ `${row.state} became ${row.state_kind} at ${row.changed_at}; ` ++ `${row.consumer_total} consumer(s) written before that still rest on it${shown}`+ );+}++/** What the collector could not read, in the shape the sweep reports. */+interface StaleDependencyReadFailure {+ readonly path: string;+ readonly action: string;+ readonly cause: unknown;+}++/**+ * Unwrap the collector's typed read failure.+ *+ * The original `cause` is handed on rather than the wrapper, because the+ * sweep decides absent-versus-unreadable from the `errno` and a wrapper+ * carries none - an absent optional directory would otherwise be+ * reported as a subtree the doctor failed to enter.+ */+function asReadFailure(err: unknown): StaleDependencyReadFailure {+ if (err instanceof StaleDependencyReadError) {+ return { path: err.path, action: err.action, cause: err.cause };+ }+ return { path: UNKNOWN_FAILURE_PATH, action: "stale-dependency audit failed", cause: err };+}++/** Stands where a path would, for a throw that named none. */+const UNKNOWN_FAILURE_PATH = "";diff --git a/src/core/brain/dream-stage.ts b/src/core/brain/dream-stage.tsindex 14299e6a..f7bd5508 100644--- a/src/core/brain/dream-stage.ts+++ b/src/core/brain/dream-stage.ts@@ -31,9 +31,9 @@import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";import { join } from "node:path";-import { createHash } from "node:crypto";import { atomicWriteFileSync } from "../fs-atomic.ts";+import { sha256Hex } from "../integrity/digest.ts";import { appendMetric } from "./metrics.ts";import { brainDirs } from "./paths.ts";import { dream, type DreamOptions, type DreamRunSummary } from "./dream.ts";@@ -162,10 +162,6 @@ function appliedRoot(vault: string): string {return join(vault, "Brain", "dream", "applied");}-function sha256(text: string): string {- return createHash("sha256").update(text).digest("hex");-}-/** Active inbox signals (not processed/) with content hashes. */function scanSources(vault: string): DreamStageSource[] {const inbox = brainDirs(vault).inbox;@@ -175,7 +171,7 @@ function scanSources(vault: string): DreamStageSource[] {if (!entry.isFile() || !entry.name.endsWith(".md")) continue;const abs = join(inbox, entry.name);try {- out.push({ path: `Brain/inbox/${entry.name}`, sha256: sha256(readFileSync(abs, "utf8")) });+ out.push({ path: `Brain/inbox/${entry.name}`, sha256: sha256Hex(readFileSync(abs, "utf8")) });} catch {// A torn read shows up as plan drift later, not as a stage crash.}@@ -279,8 +275,8 @@ export function stageDream(vault: string, opts: DreamStageOptions): DreamStageBuproposals: proposals.length,sources: sources.length,plan,- plan_hash: sha256(JSON.stringify(plan)),- sources_hash: sha256(sourcesBody),+ plan_hash: sha256Hex(JSON.stringify(plan)),+ sources_hash: sha256Hex(sourcesBody),},null,2,diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex 5babb636..c38709b3 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -80,6 +80,7 @@ import {} from "./rollup-ladder.ts";import { createSnapshot, pruneSnapshots } from "./snapshot.ts";import { compactRunStamp, isoDate } from "./time.ts";+import { BRAIN_SNAPSHOT_REASON } from "./types.ts";import type { BrainConfig } from "./types.ts";// ----- Public surface ------------------------------------------------------@@ -192,7 +193,13 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {if (rollupPlan.fired && runId !== baseRunId) {rollupPlan = buildRollupPlan(vault, cfg, scan.preferences.length, runId);}- snapshotPathStr = createSnapshot(vault, runId).path;+ // `now` rather than wall clock: the pass is byte-reproducible given+ // its injected clock, and the snapshot audit line must not be the one+ // thing that breaks that.+ snapshotPathStr = createSnapshot(vault, runId, {+ reason: BRAIN_SNAPSHOT_REASON.dream,+ now,+ }).path;}// v0.12.0 Brain Integrity Suite: durable workrun for the dream pass.@@ -384,8 +391,10 @@ function buildRollupPlan(}function formatRunId(d: Date): string {- // dream-YYYY-MM-DD-HHMMSS- return `dream-${compactRunStamp(d)}`;+ // <reason>-YYYY-MM-DD-HHMMSS. The prefix is the snapshot-reason+ // constant rather than a literal, so the archive's filename and the+ // provenance stamped into its sidecar are one string.+ return `${BRAIN_SNAPSHOT_REASON.dream}-${compactRunStamp(d)}`;}function nextAvailableDreamRunId(vault: string, baseRunId: string): string {diff --git a/src/core/brain/entities/label-hygiene.ts b/src/core/brain/entities/label-hygiene.tsindex cd867941..b7ba7a57 100644--- a/src/core/brain/entities/label-hygiene.ts+++ b/src/core/brain/entities/label-hygiene.ts@@ -26,11 +26,9 @@ import {} from "./canonical.ts";import { buildEntityIndex, type EntityIndex } from "./index-builder.ts";import type { BrainEntity } from "./types.ts";+import { BRAIN_SNAPSHOT_REASON } 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";-/** Config key / env twin for the operator-supplied exact-label denylist. */export const ENTITY_LABEL_DENYLIST_CONFIG_KEY = "entities.label_denylist";export const ENTITY_LABEL_DENYLIST_ENV_KEY = "OPEN_SECOND_BRAIN_ENTITIES_LABEL_DENYLIST";@@ -223,7 +221,7 @@ export function pruneEntityLabels(const gated = withDestructiveSnapshot(vault,- ENTITY_PRUNE_SNAPSHOT_LABEL,+ BRAIN_SNAPSHOT_REASON.entityPrune,() => {for (const path of prunePaths) rmSync(path, { force: true });for (const rewrite of rewrites) {diff --git a/src/core/brain/freshness.ts b/src/core/brain/freshness.tsindex 4cd47638..f84620af 100644--- a/src/core/brain/freshness.ts+++ b/src/core/brain/freshness.ts@@ -20,10 +20,10 @@* mismatch) is reported, never thrown.*/-import { createHash } from "node:crypto";import { existsSync, readFileSync, statSync } from "node:fs";import { isAbsolute, join } from "node:path";+import { sha256Hex } from "../integrity/digest.ts";import { listVaultPages, parseFrontmatter } from "../vault.ts";/** Hash value recorded for a source that did not exist at derivation. */@@ -59,10 +59,6 @@ export interface FreshnessReport {readonly invalid_contract: ReadonlyArray<string>;}-function sha256(content: string): string {- return createHash("sha256").update(content).digest("hex");-}-function resolveSourcePath(vault: string, source: string): string {return isAbsolute(source) ? source : join(vault, source);}@@ -72,7 +68,7 @@ function hashSource(vault: string, source: string): string {try {if (!existsSync(path)) return MISSING_SOURCE_HASH;if ((statSync(path).mode & 0o444) === 0) return UNREADABLE_SOURCE_HASH;- return sha256(readFileSync(path, "utf8"));+ return sha256Hex(readFileSync(path, "utf8"));} catch {// A transient permission / I/O failure is NOT a deleted source -// it must never feed orphan detection (and the cleanup/archivediff --git a/src/core/brain/gate-telemetry.ts b/src/core/brain/gate-telemetry.tsindex b6e07951..986e52ce 100644--- a/src/core/brain/gate-telemetry.ts+++ b/src/core/brain/gate-telemetry.ts@@ -11,12 +11,19 @@* `recall_gate_telemetry` config key is on, keeping the gate's* pure-diagnostic contract byte-identical otherwise. Reuses the* continuity-record kernel rather than inventing a new sink.+ *+ * The same handler's second observation lives here too: the typed+ * negative-recall verdict (silence-is-not-an-answer, U2), written as a+ * `negative_recall` record under the SAME opt-in. It is the same+ * surface's telemetry and shares the prompt-hashing invariant, so a+ * separate module would have duplicated both.*/import { createHash } from "node:crypto";import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";import type { ContinuityRecord } from "./continuity/types.ts";+import type { NegativeRecallVerdict } from "./negative-recall.ts";export interface GateTelemetryInput {readonly host: string;@@ -62,6 +69,61 @@ export function emitGateTelemetry(vault: string, input: GateTelemetryInput): Con});}+/** One typed negative-recall verdict, as the gate observed it. */+export interface NegativeRecallTelemetryInput {+ readonly prompt: string;+ readonly verdict: NegativeRecallVerdict;+ readonly sessionId?: string;+ readonly createdAt?: string;+}++/**+ * Record one negative-recall verdict (silence-is-not-an-answer, U2).+ *+ * Same sink, same privacy invariant and the same `recall_gate_telemetry`+ * opt-in as {@link emitGateTelemetry} - one config decision governs the+ * whole feature rather than one per surface.+ *+ * The coverage receipt rides along in the reduced form that is safe to+ * replicate: the digest, the counts, the searched roots and the gap.+ * `index_path` is deliberately dropped. It is a host filesystem path,+ * not vault content, and continuity records sync between devices; the+ * digest already binds it, so nothing is lost that an audit needs.+ */+export function emitNegativeRecallTelemetry(+ vault: string,+ input: NegativeRecallTelemetryInput,+): ContinuityRecord {+ const { verdict } = input;+ const coverage = verdict.coverage;+ return appendContinuityRecord(vault, {+ kind: "negative_recall",+ createdAt: input.createdAt ?? new Date().toISOString(),+ sourceRefs: [],+ payload: {+ ...(input.sessionId !== undefined ? { session_id: input.sessionId } : {}),+ state: verdict.state,+ complete: verdict.complete,+ ...(verdict.unknown_reason !== undefined ? { unknown_reason: verdict.unknown_reason } : {}),+ reason: verdict.reason,+ ...(coverage !== undefined+ ? {+ coverage_digest: coverage.digest,+ documents: coverage.documents,+ chunks: coverage.chunks,+ schema_version: coverage.schema_version,+ embedding_signature: coverage.embedding_signature,+ last_indexed_at: coverage.last_indexed_at,+ scope: coverage.scope,+ unindexed_roots: coverage.unindexed_roots,+ }+ : {}),+ prompt_hash: hashPrompt(input.prompt),+ prompt_chars: input.prompt.length,+ },+ });+}+/** Gate decisions, newest first. */export function listGateTelemetry(vault: string,diff --git a/src/core/brain/generation-reports.ts b/src/core/brain/generation-reports.tsindex 7fb27de6..c653bcd9 100644--- a/src/core/brain/generation-reports.ts+++ b/src/core/brain/generation-reports.ts@@ -25,8 +25,7 @@* never fails the primary operation.*/-import { createHash } from "node:crypto";-+import { sha256Hex } from "../integrity/digest.ts";import { emitGatedTelemetry } from "./continuity/emit.ts";import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";@@ -98,7 +97,7 @@ export function emitGenerationReport<G>(...(input.model !== undefined ? { model: input.model } : {}),...(input.finishReason !== undefined ? { finish_reason: input.finishReason } : {}),...(input.latencyMs !== undefined ? { latency_ms: input.latencyMs } : {}),- prompt_hash: sha256(prompt),+ prompt_hash: sha256Hex(prompt),prompt_chars: [...prompt].length,local_estimate: { input_tokens: estimateTokens(prompt) },...(usagePayload(input.usage) !== undefined ? { usage: usagePayload(input.usage) } : {}),@@ -237,10 +236,6 @@ export function getGenerationReport(vault: string, id: string): ContinuityRecord);}-function sha256(text: string): string {- return createHash("sha256").update(text, "utf8").digest("hex");-}-function numberOr0(value: unknown): number {return typeof value === "number" && Number.isFinite(value) ? value : 0;}diff --git a/src/core/brain/idempotency-ledger.ts b/src/core/brain/idempotency-ledger.tsindex bc3c6c69..8fc58362 100644--- a/src/core/brain/idempotency-ledger.ts+++ b/src/core/brain/idempotency-ledger.ts@@ -32,10 +32,10 @@* caller-supplied (or defaulted) `createdAt`.*/-import { createHash } from "node:crypto";import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";import { join } from "node:path";+import { canonicalJson, sha256Hex } from "../integrity/digest.ts";import { BRAIN_ROOT_REL, ensureInsideVault } from "./paths.ts";import { acquireLockSync } from "./sync-lockfile.ts";import { isoSecond } from "./time.ts";@@ -118,18 +118,7 @@ export class IdempotencyPayloadMismatchError extends Error {* the same content produces the same hash.*/export function computePayloadHash(fields: Readonly<Record<string, unknown>>): string {- return createHash("sha256").update(canonicalJson(fields), "utf8").digest("hex");-}--/** Deterministic JSON: object keys sorted recursively, arrays kept in order,- * `undefined` object entries omitted. */-function canonicalJson(value: unknown): string {- if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";- if (Array.isArray(value)) return `[${value.map((v) => canonicalJson(v)).join(",")}]`;- const entries = Object.entries(value as Record<string, unknown>)- .filter(([, v]) => v !== undefined)- .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));- return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;+ return sha256Hex(canonicalJson(fields));}export function idempotencyLogPath(vault: string, month: string): string {diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.tsindex c142b82e..1a783aa5 100644--- a/src/core/brain/import-claude-memory.ts+++ b/src/core/brain/import-claude-memory.ts@@ -3,7 +3,7 @@ import { basename, dirname, join } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";import { appendLogEvent } from "./log.ts";-import { BRAIN_LOG_EVENT_KIND } from "./types.ts";+import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "./types.ts";import { createSnapshot } from "./snapshot.ts";import { isoSecond } from "./time.ts";import { resolveAgentName } from "../config.ts";@@ -195,8 +195,13 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMelet snapshotRunId: string | null = null;if (filesToWrite.length > 0) {- const runId = `import-claude-memory-${importedAt.replace(/:/g, "-")}`;- createSnapshot(opts.vault, runId);+ // The run-id prefix and the recorded reason are one constant, so the+ // archive's filename can never disagree with its stamped provenance.+ const runId = `${BRAIN_SNAPSHOT_REASON.importClaudeMemory}-${importedAt.replace(/:/g, "-")}`;+ createSnapshot(opts.vault, runId, {+ reason: BRAIN_SNAPSHOT_REASON.importClaudeMemory,+ now,+ });snapshotRunId = runId;}diff --git a/src/core/brain/labels.ts b/src/core/brain/labels.tsindex bfacf4ef..dfd3047e 100644--- a/src/core/brain/labels.ts+++ b/src/core/brain/labels.ts@@ -10,10 +10,18 @@* array (filterable through the existing `--property` post-rank* filter) plus a canonical `label` entity in the registry so related* notes cluster without free-form tag drift.+ *+ * Both writes take a caller-named path and resolve it through+ * `resolveNotePath`, which guarantees containment and nothing about which+ * file is being rewritten. One file needs more than that:+ * `Brain/standing-rules.md` is the operator's own text, and+ * `assertStandingRulesNotTargeted` refuses it by name here because the+ * Brain-root refusal that covers the note-write tools is not on this path.*/import { parseFrontmatter, writeFrontmatterAtomic } from "../vault.ts";import { resolveNotePath } from "./note-path.ts";+import { assertStandingRulesNotTargeted } from "./standing-rules.ts";import { normalizeSchemaToken } from "./schema-vocab.ts";import { upsertEntity } from "./entities/registry.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";@@ -21,6 +29,14 @@ import type { SchemaPack } from "./schema-pack.ts";export const LABEL_ENTITY_CATEGORY = "label";+/**+ * How the two label writes name themselves in a refusal. Named constants+ * rather than inline strings because the words appear in an operator- and+ * agent-facing error and must not drift between the two paths.+ */+const LABEL_ASSIGN_SURFACE = "label assignment";+const LABEL_REMOVE_SURFACE = "label removal";+export class LabelVocabularyError extends Error {readonly dimension: string;readonly allowed: ReadonlyArray<string>;@@ -130,6 +146,14 @@ export function assignNoteLabel(): NoteLabelResult {// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);+ // The operator's standing rules are refused by NAME here. This surface+ // takes a caller-named path and reaches the file through+ // `resolveNotePath`, which enforces containment and symlinks and nothing+ // about which file is being written, so the Brain-root refusal that+ // protects the note-write tools does not reach it. Placed before the+ // vocabulary check so the refusal is about the target rather than about+ // whichever dimension the caller happened to invent.+ assertStandingRulesNotTargeted(vault, relPath, LABEL_ASSIGN_SURFACE);const assignment = validateLabelAssignment(opts.pack, opts.dimension, opts.value);const path = resolveNotePath(vault, relPath);const [metadata, body] = parseFrontmatter(path);@@ -162,6 +186,9 @@ export function removeNoteLabel(): RemoveNoteLabelResult {// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);+ // Removal rewrites the same frontmatter with the same overwrite, so it+ // is the same write and takes the same refusal.+ assertStandingRulesNotTargeted(vault, relPath, LABEL_REMOVE_SURFACE);const dimension = normalizeSchemaToken(opts.dimension);const path = resolveNotePath(vault, relPath);const [metadata, body] = parseFrontmatter(path);diff --git a/src/core/brain/log-jsonl.ts b/src/core/brain/log-jsonl.tsindex 52726a69..1665085d 100644--- a/src/core/brain/log-jsonl.ts+++ b/src/core/brain/log-jsonl.ts@@ -53,11 +53,50 @@ const ISO_UTC_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/;// that does not match are NOT log shards.const LOG_FILE_RE = /^(\d{4}-\d{2}-\d{2})(?:\.([a-z0-9-]{1,32}))?\.(jsonl|md)$/;-export interface LogShardFile {+/**+ * A Syncthing conflict copy is named `<stem>.sync-conflict-<stamp>.<ext>`,+ * so its middle segment can pass the shard-id shape. Named once because+ * both the recogniser that must REJECT it and the leftover reporter that+ * must FIND it key on the same marker.+ */+const SYNC_CONFLICT_SHARD_PREFIX = "sync-conflict";++/** The shape of one recognised `Brain/log/` daily file name. */+export interface ParsedLogFileName {readonly date: string;/** Empty string for the legacy un-sharded pair. */readonly shardId: string;readonly ext: "jsonl" | "md";+}++/**+ * Decide whether `name` is a day of the Brain log, and what day.+ *+ * The four shapes are exactly what `logPath`, `logJsonlPath`,+ * `logShardPath` and `logShardJsonlPath` write, which the shard+ * round-trip test asserts by feeding those builders' own output back+ * through here - a recogniser checked only against hand-written names+ * proves nothing about what the writers produce.+ *+ * Exported because a second consumer needs the same answer: the snapshot+ * diff classifier buckets files under two extracted `Brain/` trees, and+ * the copy of this shape it used to carry predated per-device sharding, so+ * both the markdown shard and the machine-primary JSONL fell through to+ * its catch-all class and `rollback --dry-run` mislabelled the log surface+ * it is most likely to be showing. One recogniser in the module that owns+ * the layout, rather than a third copy of the pattern.+ */+export function parseLogFileName(name: string): ParsedLogFileName | null {+ const m = LOG_FILE_RE.exec(name);+ if (m === null) return null;+ const shardId = m[2] ?? "";+ // Defensive: a hand-renamed Syncthing conflict copy could match the+ // shard-id shape; conflict copies are never log shards.+ if (shardId.startsWith(SYNC_CONFLICT_SHARD_PREFIX)) return null;+ return { date: m[1]!, shardId, ext: m[3] as "jsonl" | "md" };+}++export interface LogShardFile extends ParsedLogFileName {readonly path: string;readonly name: string;}@@ -76,19 +115,9 @@ export function listLogShardFiles(vault: string): LogShardFile[] {a.name.localeCompare(b.name),)) {if (!entry.isFile()) continue;- const m = LOG_FILE_RE.exec(entry.name);- if (!m) continue;- const shardId = m[2] ?? "";- // Defensive: a hand-renamed Syncthing conflict copy could match the- // shard-id shape; conflict copies are never log shards.- if (shardId.startsWith("sync-conflict")) continue;- out.push({- date: m[1]!,- shardId,- ext: m[3] as "jsonl" | "md",- path: join(dir, entry.name),- name: entry.name,- });+ const parsed = parseLogFileName(entry.name);+ if (parsed === null) continue;+ out.push({ ...parsed, path: join(dir, entry.name), name: entry.name });}return out;}@@ -113,7 +142,7 @@ export function listLogSyncConflicts(vault: string): string[] {const dir = brainDirs(vault).log;if (!existsSync(dir)) return [];return readdirSync(dir, { withFileTypes: true })- .filter((e) => e.isFile() && e.name.includes(".sync-conflict-"))+ .filter((e) => e.isFile() && e.name.includes(`.${SYNC_CONFLICT_SHARD_PREFIX}-`)).map((e) => join(dir, e.name)).toSorted();}diff --git a/src/core/brain/manifest.ts b/src/core/brain/manifest.tsindex 6cb66764..1dcfccc4 100644--- a/src/core/brain/manifest.ts+++ b/src/core/brain/manifest.ts@@ -1,5 +1,8 @@/**- * SHA-256 file inventory over `Brain/` minus `.snapshots/`.+ * SHA-256 file inventory over `Brain/` minus the entries the snapshot+ * family never touches, plus the record of what the snapshot did with+ * the derived SQLite store that lives one directory away, plus why the+ * snapshot was taken at all.** Symlinks are dropped via `lstatSync` โ a malicious snapshot archive* planting a symlink under `Brain/` must not let the walker hash@@ -7,22 +10,126 @@* identical bytes produce byte-identical JSON on disk.*/-import { createHash } from "node:crypto";import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";import { join, relative } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";-import { BRAIN_ROOT_REL, brainDirs } from "./paths.ts";+import { sha256Hex } from "../integrity/digest.ts";+import { BRAIN_ROOT_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, brainDirs } from "./paths.ts";import { isoSecond } from "./time.ts";+import { isBrainSnapshotReason, type BrainSnapshotReason } from "./types.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";+/**+ * NOT bumped by the derived-store or snapshot-reason fields, deliberately.+ *+ * {@link readManifestSidecar} rejects any version it does not recognize,+ * and the snapshots directory rides the same peer-to-peer replication as+ * the rest of the vault. Bumping would therefore make every older peer+ * read `null` for every NEW sidecar and silently lose drift detection on+ * exactly the snapshots that matter most. An additive key at the current+ * version is ignored by those readers and their guarantee is untouched,+ * which is this project's additive-only rule for persisted formats.+ */export const BRAIN_MANIFEST_SCHEMA_VERSION = 1 as const;+/**+ * The release that introduced the sidecar manifest, and therefore the+ * release before which a snapshot has no drift record at all.+ *+ * Named once because the warning the CLI prints, the help text that+ * explains it, and the operating manual all state it, and three+ * hand-kept copies of one version string is three chances to be wrong.+ */+export const BRAIN_MANIFEST_SIDECAR_SINCE_VERSION = "v0.10.6";++/**+ * Why a snapshot does not carry the derived store.+ *+ * Four members, and none of them is "it failed": inclusion never+ * degrades into an omission at snapshot time. When the store WAS+ * requested and any step could not be completed, `createSnapshot` throws+ * and no archive is left behind - the reason then travels in the error+ * rather than in a manifest that would claim a snapshot happened. These+ * codes are what a manifest can honestly record about a snapshot that+ * SUCCEEDED without the store in it.+ */+export const SNAPSHOT_STORE_EXCLUSION = Object.freeze({+ /** Coverage is off (the default). Nothing was attempted. */+ not_requested: "not-requested",+ /** There is no store file at the resolved path. */+ absent: "absent",+ /** The structural integrity scan condemned the file. */+ integrity_fault: "integrity-fault",+ /** The live store is larger than the configured ceiling. */+ over_size_ceiling: "over-size-ceiling",+} as const);++/** Closed union over {@link SNAPSHOT_STORE_EXCLUSION}. */+export type SnapshotStoreExclusionReason =+ (typeof SNAPSHOT_STORE_EXCLUSION)[keyof typeof SNAPSHOT_STORE_EXCLUSION];++/** Membership list, in the order the reasons are evaluated. */+export const SNAPSHOT_STORE_EXCLUSION_REASONS: ReadonlyArray<SnapshotStoreExclusionReason> =+ Object.freeze([+ SNAPSHOT_STORE_EXCLUSION.not_requested,+ SNAPSHOT_STORE_EXCLUSION.absent,+ SNAPSHOT_STORE_EXCLUSION.integrity_fault,+ SNAPSHOT_STORE_EXCLUSION.over_size_ceiling,+ ]);++/** Narrow a string read back off a sidecar written by any peer. */+export function isSnapshotStoreExclusionReason(+ value: unknown,+): value is SnapshotStoreExclusionReason {+ return (+ typeof value === "string" &&+ (SNAPSHOT_STORE_EXCLUSION_REASONS as ReadonlyArray<string>).includes(value)+ );+}+export interface BrainManifestEntry {readonly sha256: string;readonly size: number;}+/**+ * What one snapshot did about the derived SQLite store.+ *+ * ## Why `live_size` is recorded even when nothing was archived+ *+ * What derived-store coverage protects is SPEND, not information:+ * feedback, activation and tuning are replayable JSON folds inside+ * `Brain/`, and only the embeddings and a tier baseline are+ * database-only. So the question an operator actually has is "what would+ * this cost me", and the answer is a number they should not have to go+ * and measure. Retention keeps ten copies and the snapshots directory is+ * replicated to every peer, so the honest framing is ten times this+ * number on every device - which is exactly why coverage is opt-in, why+ * the ceiling refuses rather than truncates, and why this field is+ * present in every manifest whether or not the store was included.+ */+export interface BrainManifestDerivedStore {+ /** True when {@link archive_name} names a real sibling archive. */+ readonly included: boolean;+ /** Resolved absolute path of the live store this record describes. */+ readonly source_path: string;+ /** Filename of the sibling archive in `.snapshots/`; null when excluded. */+ readonly archive_name: string | null;+ /** SHA-256 over the archived (compressed) bytes; null when excluded. */+ readonly archive_sha256: string | null;+ /** Byte length of the archive as written; null when excluded. */+ readonly archive_size: number | null;+ /**+ * Byte length of the LIVE store at snapshot time. `null` means the+ * file was not there to measure - never "zero", which is a real size a+ * freshly created database can legitimately have.+ */+ readonly live_size: number | null;+ /** Named reason from {@link SNAPSHOT_STORE_EXCLUSION}; null when included. */+ readonly exclusion_reason: SnapshotStoreExclusionReason | null;+}+export interface BrainManifest {readonly schema_version: typeof BRAIN_MANIFEST_SCHEMA_VERSION;/** ISO-8601 UTC, second precision. */@@ -30,6 +137,43 @@ export interface BrainManifest {readonly brain_root: typeof BRAIN_ROOT_REL;/** Keys are vault-relative paths under `Brain/`, sorted lexicographically. */readonly files: Readonly<Record<string, BrainManifestEntry>>;+ /**+ * Set when a `derived_store` record was present and could not be read.+ *+ * Distinct from the field's absence, which means the snapshot predates+ * derived-store coverage. A caller that would restore the store must+ * refuse on this; a caller that only compares the Markdown tree may+ * ignore it, which is the whole reason the failure is contained here+ * rather than discarding the file map.+ */+ readonly derived_store_unreadable?: true;+ /**+ * Set when a `snapshot_reason` was present and is not a reason this+ * build registers - typically written by a later build, since the+ * vault replicates between machines that need not run the same one.+ *+ * The provenance is unusable and says so; the drift comparison the rest+ * of this record supports is unaffected.+ */+ readonly snapshot_reason_unreadable?: true;+ /**+ * Absent on every sidecar written before derived-store coverage+ * shipped. Absent means UNKNOWN - the snapshot predates the feature+ * and nothing can be said about what it covered. It must never be+ * rendered as `excluded`, which is a claim that a check ran.+ */+ readonly derived_store?: BrainManifestDerivedStore;+ /**+ * Why the recovery point was taken (U7). Absent on every sidecar+ * written before the reason existed, and absence is UNKNOWN: the run id+ * that names the archive begins with a registered reason at every call+ * site that writes one, so the temptation to recover the field by+ * parsing that prefix is real - and it would manufacture provenance the+ * archive does not carry, for a hand-named or third-party archive just+ * as readily as for one of ours. The key is omitted rather than nulled+ * so absence has exactly one spelling.+ */+ readonly snapshot_reason?: BrainSnapshotReason;}export interface BrainManifestDiffEntry {@@ -46,6 +190,22 @@ export interface BrainManifestDiff {// ---------- buildManifest --------------------------------------------------+/**+ * The two facts about a snapshot that the walker cannot discover for+ * itself, so the archiver hands them over.+ *+ * Both are omitted by the live-tree rebuild the drift check performs, and+ * that is correct rather than lax: drift is computed over `files` alone,+ * so a live manifest carrying neither field stays comparable with a+ * stored one carrying both.+ */+export interface BuildManifestOptions {+ /** What the snapshot did about the sibling SQLite store. */+ readonly derivedStore?: BrainManifestDerivedStore;+ /** Why the recovery point was taken. */+ readonly snapshotReason?: BrainSnapshotReason;+}+/*** Walk `brainRoot` (the `<vault>/Brain/` directory) and hash every* regular file. The caller is responsible for pointing at the@@ -55,13 +215,17 @@ export interface BrainManifestDiff {* The walker is iterative (explicit stack) to keep recursion depth* predictable on deeply-nested vault trees. Files are hashed* one-at-a-time; Brain trees in practice stay well under 10 MB.+ *+ * Only the archiver knows whether a store archive was written and why the+ * snapshot was taken, so both travel in {@link BuildManifestOptions}+ * rather than being rediscovered here.*/-export function buildManifest(brainRoot: string): BrainManifest {+export function buildManifest(brainRoot: string, opts: BuildManifestOptions = {}): BrainManifest {const generated_at = isoSecond();const collected = new Map<string, BrainManifestEntry>();if (!existsSync(brainRoot)) {- return freezeManifest(generated_at, collected);+ return freezeManifest(generated_at, collected, opts);}const stack: string[] = [brainRoot];@@ -84,10 +248,12 @@ export function buildManifest(brainRoot: string): BrainManifest {// Skip symlinks unconditionally โ see module docstring.if (st.isSymbolicLink()) continue;const rel = relative(brainRoot, abs).replaceAll("\\", "/");- // `.snapshots/` is the snapshot family's home; including its- // contents in the manifest would either explode the listing or- // create a self-referential loop on rotate.- if (rel === ".snapshots" || rel.startsWith(".snapshots/")) continue;+ // The entries the snapshot family never touches. Hashing something+ // the archive does not contain and the restore does not replace+ // makes the drift gate fire on churn no rollback would ever undo.+ if (BRAIN_SNAPSHOT_EXCLUDED_ENTRIES.some((e) => rel === e || rel.startsWith(`${e}/`))) {+ continue;+ }// Defense-in-depth: a `..` path *segment* cannot legitimately// appear inside a sane Brain tree. We anchor on the segment// boundary so an otherwise-valid filename like `..notes.md`@@ -103,7 +269,7 @@ export function buildManifest(brainRoot: string): BrainManifest {}}- return freezeManifest(generated_at, collected);+ return freezeManifest(generated_at, collected, opts);}function hashFile(abs: string): BrainManifestEntry {@@ -113,13 +279,14 @@ function hashFile(abs: string): BrainManifestEntry {// the stat-based size could disagree with the hash and confuse a// future drift comparison.const buf = readFileSync(abs);- const sha256 = createHash("sha256").update(buf).digest("hex");+ const sha256 = sha256Hex(buf);return Object.freeze({ sha256, size: buf.byteLength });}function freezeManifest(generated_at: string,entries: Map<string, BrainManifestEntry>,+ opts: BuildManifestOptions,): BrainManifest {// Materialise in sorted key order so JSON.stringify yields stable// bytes across runs.@@ -131,6 +298,13 @@ function freezeManifest(generated_at,brain_root: BRAIN_ROOT_REL,files: Object.freeze(files),+ // Spread rather than assign, for both optional keys: a manifest built+ // without a record must OMIT the key, because an explicit `undefined`+ // would serialise the same as absent here but read as present to a+ // structural check, and absent is a load-bearing state (unknown, not+ // excluded; unstamped, not reason-less).+ ...(opts.derivedStore !== undefined ? { derived_store: Object.freeze(opts.derivedStore) } : {}),+ ...(opts.snapshotReason !== undefined ? { snapshot_reason: opts.snapshotReason } : {}),});}@@ -286,14 +460,108 @@ export function readManifestSidecar(vault: string, runId: string): BrainManifestsize: entry["size"],});}+ // The derived-store record follows the SAME rule as the file map: an+ // absent key is a legal older sidecar, a present-but-malformed one+ // fails the whole manifest closed. Anything looser would let a+ // half-written record claim a coverage the archive does not have.+ const rawStore = obj["derived_store"];+ let derivedStore: BrainManifestDerivedStore | undefined;+ // An unreadable OPTIONAL field does not void the mandatory record.+ //+ // Failing the whole manifest closed was the first shape of this, and it+ // reproduced the loss that keeping `schema_version` at 1 exists to+ // prevent: a peer running a later build writes a value this one does+ // not know, this one discards the file map with it, and the rollback+ // gate then reports no sidecar at all and skips drift detection - the+ // silent-overwrite path, reached by a different route and announced+ // with a message that is false twice over.+ //+ // So each optional field has three states rather than two. Valid,+ // absent, or present-and-unreadable - and the third is recorded, never+ // folded into either of the others, because a caller that acts on the+ // field needs to refuse while a caller that only needs the file map+ // carries on.+ let derivedStoreUnreadable = false;+ if (rawStore !== undefined) {+ const parsedStore = parseDerivedStore(rawStore);+ if (parsedStore === null) derivedStoreUnreadable = true;+ else derivedStore = parsedStore;+ }+ const rawReason = obj["snapshot_reason"];+ const reasonUnreadable = rawReason !== undefined && !isBrainSnapshotReason(rawReason);+return Object.freeze({schema_version: BRAIN_MANIFEST_SCHEMA_VERSION,generated_at: obj["generated_at"],brain_root: BRAIN_ROOT_REL,files: Object.freeze(entries),+ ...(derivedStore !== undefined ? { derived_store: derivedStore } : {}),+ ...(derivedStoreUnreadable ? { derived_store_unreadable: true as const } : {}),+ ...(!reasonUnreadable && rawReason !== undefined ? { snapshot_reason: rawReason } : {}),+ ...(reasonUnreadable ? { snapshot_reason_unreadable: true as const } : {}),});}+/** `null` on any malformation, so the caller can fail the manifest closed. */+function parseDerivedStore(raw: unknown): BrainManifestDerivedStore | null {+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) return null;+ const rec = raw as Record<string, unknown>;+ const included = rec["included"];+ const sourcePath = rec["source_path"];+ if (typeof included !== "boolean") return null;+ if (typeof sourcePath !== "string" || sourcePath === "") return null;++ const archiveName = nullableOf(rec["archive_name"], (v) => typeof v === "string" && v !== "");+ const archiveSha = nullableOf(rec["archive_sha256"], (v) => typeof v === "string" && v !== "");+ const archiveSize = nullableOf(rec["archive_size"], isNonNegativeInteger);+ const liveSize = nullableOf(rec["live_size"], isNonNegativeInteger);+ const reason = nullableOf(rec["exclusion_reason"], isSnapshotStoreExclusionReason);+ if (+ archiveName === INVALID ||+ archiveSha === INVALID ||+ archiveSize === INVALID ||+ liveSize === INVALID ||+ reason === INVALID+ ) {+ return null;+ }++ // Cross-field consistency. A record claiming inclusion without the+ // three fields that make the archive verifiable is not a weaker+ // record, it is a false one - and the same holds in reverse for an+ // exclusion that names no reason.+ const archived = archiveName !== null && archiveSha !== null && archiveSize !== null;+ if (included !== archived) return null;+ if (included === (reason !== null)) return null;++ return Object.freeze({+ included,+ source_path: sourcePath,+ archive_name: archiveName as string | null,+ archive_sha256: archiveSha as string | null,+ archive_size: archiveSize as number | null,+ live_size: liveSize as number | null,+ exclusion_reason: reason as SnapshotStoreExclusionReason | null,+ });+}++/**+ * Sentinel for "the value was present and did not satisfy the check".+ * Distinct from `null`, which is a legal recorded value in every one of+ * these fields, so a rejection can never be mistaken for a null.+ */+const INVALID = Symbol("invalid-manifest-field");++/** `null`, a value passing `check`, or {@link INVALID}. */+function nullableOf(value: unknown, check: (v: unknown) => boolean): unknown {+ if (value === null) return null;+ return check(value) ? value : INVALID;+}++function isNonNegativeInteger(value: unknown): boolean {+ return typeof value === "number" && Number.isInteger(value) && value >= 0;+}+/*** Write the sidecar manifest atomically. Pretty-printed with two-space* indent so a manual `cat` or `git diff` stays readable.diff --git a/src/core/brain/negative-recall.ts b/src/core/brain/negative-recall.tsnew file mode 100644index 00000000..e65bd3aa--- /dev/null+++ b/src/core/brain/negative-recall.ts@@ -0,0 +1,693 @@+/**+ * U2 - what does a "no" from this system actually claim?+ *+ * Every negative the recall stack produces today is a statement about+ * the RETRIEVAL ATTEMPT, never about the CORPUS. A zero-result search+ * over a stale, partial or never-built index is byte-identical to one+ * over a complete index, so a caller cannot tell an exhaustive negative+ * from an under-powered one. That is the same failure as an integrity+ * check that could not run reporting the same thing as one that passed.+ *+ * This module supplies the corpus statement:+ *+ * - `not_found` - the searched corpus was ADMISSIBLE (defined+ * below) and held nothing matching.+ * - `unknown` - no honest claim about the corpus could be made,+ * with a named reason saying which way that+ * happened.+ * - `did_not_happen` - stored evidence positively attests the thing did+ * not occur, the caller asserted non-occurrence,+ * and the searched corpus already reflected that+ * evidence.+ *+ * ## What "admissible" means, precisely+ *+ * The word does real work, so it is spelled out rather than implied. An+ * index is admissible when all four hold, each of them a fact the index+ * reports about itself:+ *+ * 1. it exists and its facts could be read;+ * 2. it recorded a completed run, stamped with a readable instant;+ * 3. it carries at least one document under every authorized note root;+ * 4. it holds a current embedding for every chunk it holds.+ *+ * That is narrower than "the vault was searched exhaustively", and the+ * gap is named rather than hidden: (3) is satisfied by ONE document under+ * a root, so a folder of a thousand notes with one indexed note passes+ * it. The index cannot tell that case from a folder holding exactly one+ * note - it knows what it was given, never what it was not - so the+ * receipt reports the document count beside the root list and a reader+ * judging weight reads that. Closing the gap needs a filesystem census+ * against `resolveNoteRoots`, which this pure module deliberately does+ * not do.+ *+ * ## Why this is not part of `recall-adequacy.ts`+ *+ * That module's single responsibility is SCORE FITNESS: given the top-k+ * relevance scores of an attempt, is the grounding strong enough to+ * answer. It never looks at the corpus and it must not start to. Negative+ * recall is the orthogonal axis - not "were the hits good enough" but+ * "was the haystack the whole haystack" - so it is a sibling in the same+ * idiom rather than a widening of a well-scoped type. The two compose:+ * the recall gate computes adequacy first and reaches for this module+ * only on the zero-usable-result path.+ *+ * ## The receipt is over the SEARCHED set, and it names the gap+ *+ * Two universes disagree. `resolveNoteRoots` (notes/note-walk.ts)+ * enumerates the AUTHORIZED set - the note folders the operator declared+ * in `notes.read_paths`. `indexStatus` (search/indexer.ts) describes the+ * SEARCHED set - what the index actually holds. The digest is taken over+ * the searched set, because that is the only universe a negative can+ * honestly attest to; a receipt over the authorized set would claim+ * coverage that was never achieved. The divergence is not swallowed:+ * every authorized root the index holds no document under lands in+ * {@link CoverageReceipt.unindexed_roots} and forces `unknown` with+ * {@link NEGATIVE_RECALL_UNKNOWN_REASON.coverageDivergent}, so a receipt+ * over the index alone cannot hide the gap either.+ *+ * A root the index carries no document under is reported that way even+ * when the folder is genuinely empty. From the index alone those two+ * cases are indistinguishable, and the conservative reading - refuse to+ * claim completeness - is the one this wave exists to install. The+ * reverse asymmetry is condition (3) above: presence of one document is+ * not proof the root was read out, which is why the receipt reports the+ * document count and this module never calls a root exhausted.+ *+ * ## `did_not_happen` is never inferred from absence+ *+ * Absence of evidence is exactly what `not_found` reports. This state+ * requires POSITIVE stored evidence: a claim that existed and now carries+ * a tombstone, a closed `valid_until`, or a `superseded_by` edge, all of+ * which the claim graph already projects. It additionally requires that+ * the searched index is at least as new as that evidence - an index built+ * before the retraction was recorded has not seen it, and a negative from+ * it says nothing about the retraction - and that the caller ASSERTED+ * non-occurrence, so evidence handed over for context is never turned+ * into a verdict nobody asked for. See {@link retractionEvidenceFromClaim}+ * for the one projection limit.+ *+ * ### Deferred on the shipped surface+ *+ * No caller in `src/` supplies either half of that pair yet: the recall+ * gate in `src/mcp/search-tools.ts` passes neither evidence nor an+ * assertion, and nothing there reads the claim graph. So+ * `did_not_happen` is currently reachable through this function only, not+ * through `brain_recall_gate`, and that surface declares the narrower+ * subset it can actually produce rather than advertising a state its+ * handler cannot emit. Reading the claim graph on the gate's zero-result+ * path is a design decision with its own cost, taken separately; the arm+ * and its tests stay so that decision remains a wiring change.+ *+ * ## Pure by construction+ *+ * No filesystem, no clock, no store. Callers hand in the index facts and+ * the two root sets; the recall gate in `src/mcp/search-tools.ts` is the+ * wiring. That keeps every state above reachable in a unit test without a+ * vault, which is what makes the refusals testable at all.+ */++import { canonicalJson, sha256Hex } from "../integrity/digest.ts";+import type { ClaimNode } from "./claim-graph.ts";+import type { IndexStatusSnapshot } from "../search/types.ts";++/** The three answers a negative recall can honestly give. */+export const NEGATIVE_RECALL_STATE = Object.freeze({+ /** The searched index was admissible (module docblock) and held no match. */+ notFound: "not_found",+ /** No claim about the corpus could be made; `unknown_reason` says why. */+ unknown: "unknown",+ /**+ * Stored evidence attests non-occurrence and the caller claimed it;+ * never inferred from absence and never from evidence alone.+ */+ didNotHappen: "did_not_happen",+} as const);++/** Closed union over {@link NEGATIVE_RECALL_STATE}. */+export type NegativeRecallState =+ (typeof NEGATIVE_RECALL_STATE)[keyof typeof NEGATIVE_RECALL_STATE];++/** Membership list, ordered from weakest to strongest claim. */+export const NEGATIVE_RECALL_STATES: ReadonlyArray<NegativeRecallState> = Object.freeze([+ NEGATIVE_RECALL_STATE.notFound,+ NEGATIVE_RECALL_STATE.unknown,+ NEGATIVE_RECALL_STATE.didNotHappen,+]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isNegativeRecallState(value: unknown): value is NegativeRecallState {+ return (+ typeof value === "string" && (NEGATIVE_RECALL_STATES as ReadonlyArray<string>).includes(value)+ );+}++/**+ * Why no claim about the corpus could be made. Each member is a fact+ * about this vault's index, never a guess: none of them is a softer way+ * of saying `not_found`.+ */+export const NEGATIVE_RECALL_UNKNOWN_REASON = Object.freeze({+ /** There is no index, so nothing was searched and nothing can be attested. */+ indexAbsent: "index-absent",+ /**+ * The index exists but is not current: it carries embeddings that no+ * longer match their chunks, it has never recorded a completed run, or+ * the grounding evidence postdates the last run. A search over it may+ * simply not have seen the document.+ */+ indexStale: "index-stale",+ /**+ * The index does not cover every authorized note root; the uncovered+ * roots are named in {@link CoverageReceipt.unindexed_roots}. Part of+ * the corpus the operator authorized was never searched.+ */+ coverageDivergent: "coverage-divergent",+ /**+ * The index facts themselves could not be read, so not even the+ * absent/stale distinction could be drawn. Deliberately NOT+ * `index-absent` - an unreadable index is not a missing one.+ */+ coverageUnavailable: "coverage-unavailable",+ /**+ * The index recorded a completed run but stamped it with an instant no+ * calendar can read. Deliberately NOT `index-stale`: that reason means+ * the index is measurably behind, whereas this one means the+ * measurement is impossible, and every comparison this module makes+ * against the index instant is unsatisfiable while it holds.+ */+ indexInstantUnusable: "index-instant-unusable",+ /**+ * The index records an embedding model and holds fewer vectors than+ * chunks, so that model's run did not finish and part of the corpus is+ * reachable only by keyword while the rest is reachable both ways. No+ * negative over a half-converted index is well-founded.+ *+ * Deliberately NOT raised when no model was recorded at all: running+ * without embeddings is a supported configuration rather than an+ * unfinished job, and refusing it would leave such a vault permanently+ * unable to receive a `not_found`. The vector count and the signature+ * are in the receipt and in its digest either way, so the narrower+ * keyword-only negative is visible to whoever reads it.+ *+ * `staleEmbeddings` cannot report this case: a chunk with no embedding+ * row at all has no stored vector to be stale against.+ */+ embeddingsIncomplete: "embeddings-incomplete",+} as const);++/** Closed union over {@link NEGATIVE_RECALL_UNKNOWN_REASON}. */+export type NegativeRecallUnknownReason =+ (typeof NEGATIVE_RECALL_UNKNOWN_REASON)[keyof typeof NEGATIVE_RECALL_UNKNOWN_REASON];++/** Membership list for {@link NEGATIVE_RECALL_UNKNOWN_REASON}. */+export const NEGATIVE_RECALL_UNKNOWN_REASONS: ReadonlyArray<NegativeRecallUnknownReason> =+ Object.freeze([+ NEGATIVE_RECALL_UNKNOWN_REASON.indexAbsent,+ NEGATIVE_RECALL_UNKNOWN_REASON.indexStale,+ NEGATIVE_RECALL_UNKNOWN_REASON.coverageDivergent,+ NEGATIVE_RECALL_UNKNOWN_REASON.coverageUnavailable,+ NEGATIVE_RECALL_UNKNOWN_REASON.indexInstantUnusable,+ NEGATIVE_RECALL_UNKNOWN_REASON.embeddingsIncomplete,+ ]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isNegativeRecallUnknownReason(+ value: unknown,+): value is NegativeRecallUnknownReason {+ return (+ typeof value === "string" &&+ (NEGATIVE_RECALL_UNKNOWN_REASONS as ReadonlyArray<string>).includes(value)+ );+}++/**+ * Which stored edge carries the non-occurrence. The values are the+ * frontmatter field names the claim graph projects, so a persisted+ * verdict names the same thing the vault does.+ */+export const RETRACTION_EVIDENCE_KIND = Object.freeze({+ /** The claim's file is marked tombstoned. */+ tombstone: "tombstone",+ /** The claim's validity window is closed and nothing replaced it. */+ validUntil: "valid_until",+ /** The claim was replaced; the successor id rides on the evidence. */+ supersededBy: "superseded_by",+} as const);++/** Closed union over {@link RETRACTION_EVIDENCE_KIND}. */+export type RetractionEvidenceKind =+ (typeof RETRACTION_EVIDENCE_KIND)[keyof typeof RETRACTION_EVIDENCE_KIND];++/** Membership list for {@link RETRACTION_EVIDENCE_KIND}. */+export const RETRACTION_EVIDENCE_KINDS: ReadonlyArray<RetractionEvidenceKind> = Object.freeze([+ RETRACTION_EVIDENCE_KIND.tombstone,+ RETRACTION_EVIDENCE_KIND.validUntil,+ RETRACTION_EVIDENCE_KIND.supersededBy,+]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isRetractionEvidenceKind(value: unknown): value is RetractionEvidenceKind {+ return (+ typeof value === "string" &&+ (RETRACTION_EVIDENCE_KINDS as ReadonlyArray<string>).includes(value)+ );+}++/**+ * The ordered tuple the coverage digest is taken over.+ *+ * Order is load-bearing: the digest is computed over the field/value+ * PAIRS in this sequence, not over an object whose keys a canonical+ * serializer would sort for us. That makes the constant the encoding+ * itself, so a field appended here changes every digest deliberately and+ * visibly rather than by accident of key ordering.+ *+ * `unindexed_roots` is deliberately absent. The digest attests to what+ * WAS searched; the gap is reported beside it and forces `unknown`+ * anyway, so folding it in would make two receipts over the same searched+ * corpus disagree.+ *+ * `embeddings` was appended after the first draft of this tuple, which+ * changed every digest computed by it. That is deliberate and harmless+ * here because no release has carried a coverage receipt yet, so there is+ * no stored digest for the new encoding to contradict. Any later addition+ * does not get the same freedom: it would have to be introduced as a+ * second encoding rather than a silent recomputation of the first.+ */+export const COVERAGE_DIGEST_FIELDS = Object.freeze([+ "index_path",+ "schema_version",+ "documents",+ "chunks",+ "embeddings",+ "embedding_signature",+ "last_indexed_at",+ "scope",+] as const);++/** Closed union over {@link COVERAGE_DIGEST_FIELDS}. */+export type CoverageDigestField = (typeof COVERAGE_DIGEST_FIELDS)[number];++/**+ * The index facts a coverage receipt is built from - structurally a+ * subset of {@link IndexStatusSnapshot}, so a real snapshot is passed+ * straight through and a test builds only the fields that matter.+ */+export type CoverageIndexSnapshot = Pick<+ IndexStatusSnapshot,+ | "indexPath"+ | "exists"+ | "schemaVersion"+ | "documents"+ | "chunks"+ | "embeddings"+ | "embeddingSignature"+ | "lastIndexedAt"+ | "staleEmbeddings"+>;++/** The two universes a negative is judged against. */+export interface CoverageScope {+ /**+ * Note roots the operator authorized, from `resolveNoteRoots`. An+ * empty list is not a defect: `notes.read_paths` defaults to empty,+ * which declares no note space at all, so there is no root the index+ * can fail to cover and the negative is simply not root-scoped.+ */+ readonly authorizedRoots: ReadonlyArray<string>;+ /** Authorized roots the index actually carries documents under. */+ readonly indexedRoots: ReadonlyArray<string>;+}++/** A digest-bound attestation of the corpus a negative was drawn from. */+export interface CoverageReceipt {+ /** SHA-256 over {@link COVERAGE_DIGEST_FIELDS}, lowercase hex. */+ readonly digest: string;+ readonly documents: number;+ readonly chunks: number;+ /**+ * Stored embedding rows. Reported beside `chunks` because the two+ * together, and only together, say how much of the index a semantic+ * query could reach: `embeddings` below `chunks` is a keyword-only or+ * half-embedded corpus, which supports a narrower negative.+ */+ readonly embeddings: number;+ readonly index_path: string;+ readonly schema_version: number | null;+ readonly embedding_signature: string | null;+ readonly last_indexed_at: string | null;+ /**+ * Authorized note roots the index carries AT LEAST ONE document under,+ * sorted and deduplicated. Presence, never exhaustiveness: the index+ * cannot know how many documents the folder holds on disk, so a root+ * listed here is one the index reached, not one it read out. `documents`+ * above is what a reader weighs that against.+ */+ readonly scope: ReadonlyArray<string>;+ /**+ * Authorized roots the index holds no document under at all, sorted and+ * deduplicated - the complement of `scope` over the authorized set.+ */+ readonly unindexed_roots: ReadonlyArray<string>;+}++/** Stored positive evidence that something did not occur. */+export interface RetractionEvidence {+ /** Identifier of the claim the evidence hangs off. */+ readonly subject: string;+ readonly kind: RetractionEvidenceKind;+ /** ISO-8601 instant the retraction took effect. */+ readonly recorded_at: string;+ /** Successor id, present only for {@link RETRACTION_EVIDENCE_KIND.supersededBy}. */+ readonly replaced_by?: string;+}++/** The verdict on one negative recall. */+export interface NegativeRecallVerdict {+ readonly state: NegativeRecallState;+ /**+ * True only when the verdict rests on a receipt over an ADMISSIBLE+ * index, in the sense the module docblock spells out - which is a+ * statement about what the index reports about itself, never a promise+ * that every authored note reached it. Never true alongside `unknown`.+ */+ readonly complete: boolean;+ /** Present whenever a receipt could be built - absent, never null. */+ readonly coverage?: CoverageReceipt;+ /** Machine-independent explanation, built from identifiers and integers. */+ readonly reason: string;+ /** Present exactly when `state` is `unknown`. */+ readonly unknown_reason?: NegativeRecallUnknownReason;+}++/** Everything {@link classifyNegativeRecall} needs to reach a verdict. */+export interface NegativeRecallInput {+ /** Index facts, or `null` when they could not be read at all. */+ readonly snapshot: CoverageIndexSnapshot | null;+ readonly scope: CoverageScope;+ /** Stored non-occurrence evidence, when the caller found any. */+ readonly retraction?: RetractionEvidence | null;+ /**+ * True when the caller CLAIMS non-occurrence rather than merely asking+ * what the corpus supports.+ *+ * This flag GOVERNS the escalation to `did_not_happen`: evidence alone+ * never produces that state, because passing evidence for context is not+ * the same act as claiming the thing did not happen. Both are required.+ *+ * Asserting it without evidence is a programming error and throws. A+ * caller that leaves it off is asking the weaker question and gets the+ * weaker answer - `not_found` over an admissible index, or a named+ * refusal - even when its evidence would have supported more.+ */+ readonly assertDidNotHappen?: boolean;+}++/**+ * Raised when a negative recall is asked to claim more than its evidence+ * supports: a receipt over an index that does not exist, an assertion of+ * non-occurrence with nothing behind it, or evidence carrying an instant+ * that cannot be compared against the receipt.+ */+export class NegativeRecallError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "NegativeRecallError";+ }+}++/** Sorted, deduplicated, blank-free - the canonical form of a root list. */+function normalizeRoots(roots: ReadonlyArray<string>): ReadonlyArray<string> {+ return Object.freeze([...new Set(roots.filter((root) => root.trim().length > 0))].toSorted());+}++/**+ * Build the digest-bound receipt for one index snapshot and scope.+ *+ * Throws when the snapshot reports that the index does not exist. A+ * receipt over a missing index would be a digest of zeroes attesting to+ * an empty universe, which reads exactly like an exhaustively searched+ * one - the misleading fallback this unit exists to remove. Callers+ * handle that condition through+ * {@link NEGATIVE_RECALL_UNKNOWN_REASON.indexAbsent} instead.+ */+export function buildCoverageReceipt(+ snapshot: CoverageIndexSnapshot,+ scope: CoverageScope,+): CoverageReceipt {+ if (!snapshot.exists) {+ throw new NegativeRecallError(+ `negative recall: refusing to build a coverage receipt over a non-existent index (${snapshot.indexPath})`,+ );+ }+ const searched = normalizeRoots(scope.indexedRoots);+ const searchedSet = new Set(searched);+ const unindexed = normalizeRoots(+ normalizeRoots(scope.authorizedRoots).filter((root) => !searchedSet.has(root)),+ );+ const digested: Readonly<Record<CoverageDigestField, unknown>> = {+ index_path: snapshot.indexPath,+ schema_version: snapshot.schemaVersion,+ documents: snapshot.documents,+ chunks: snapshot.chunks,+ embeddings: snapshot.embeddings,+ embedding_signature: snapshot.embeddingSignature,+ last_indexed_at: snapshot.lastIndexedAt,+ scope: searched,+ };+ return Object.freeze({+ digest: sha256Hex(canonicalJson(COVERAGE_DIGEST_FIELDS.map((f) => [f, digested[f]]))),+ documents: snapshot.documents,+ chunks: snapshot.chunks,+ embeddings: snapshot.embeddings,+ index_path: snapshot.indexPath,+ schema_version: snapshot.schemaVersion,+ embedding_signature: snapshot.embeddingSignature,+ last_indexed_at: snapshot.lastIndexedAt,+ scope: searched,+ unindexed_roots: unindexed,+ });+}++/**+ * Project one claim-graph node into retraction evidence, or `null` when+ * the node carries none that this module can use.+ *+ * `brain_claims` operations `history` and `replaced` already return these+ * nodes, so the evidence path reuses the projection rather than reading+ * frontmatter a second time.+ *+ * One projection limit, stated rather than papered over: {@link ClaimNode}+ * exposes `tombstoned` as a BOOLEAN and does not carry `tombstoned_at`,+ * so a tombstone whose file declares no `valid_until` exposes no instant+ * to compare against the receipt. Such a node returns `null` here, which+ * leaves the caller with NO evidence: over an admissible corpus the+ * verdict is then the ordinary `not_found` (absence of a match, which is+ * all a search actually observed), and an attempt to assert non-occurrence+ * on it is refused by {@link classifyNegativeRecall}. What the null never+ * does is prove non-occurrence - a tombstone whose age is unknown cannot+ * show that the searched index had already seen it.+ *+ * No shipped surface calls this yet; see the deferral in the module+ * docblock. It is the unit-level half of the evidence arm, kept and tested+ * so that wiring it later is a call-site change rather than a design one.+ */+export function retractionEvidenceFromClaim(claim: ClaimNode): RetractionEvidence | null {+ const recordedAt = claim.valid_until;+ if (recordedAt === null || !Number.isFinite(Date.parse(recordedAt))) return null;+ if (claim.superseded_by !== null) {+ return Object.freeze({+ subject: claim.id,+ kind: RETRACTION_EVIDENCE_KIND.supersededBy,+ recorded_at: recordedAt,+ replaced_by: claim.superseded_by,+ });+ }+ return Object.freeze({+ subject: claim.id,+ kind: claim.tombstoned+ ? RETRACTION_EVIDENCE_KIND.tombstone+ : RETRACTION_EVIDENCE_KIND.validUntil,+ recorded_at: recordedAt,+ });+}++/**+ * Decide what a negative from this corpus is entitled to claim.+ *+ * The admissibility rule in one sentence: `not_found` and+ * `did_not_happen` both require a receipt over an ADMISSIBLE index -+ * one that exists, carries a datable completed run, reaches every+ * authorized root, and holds a current embedding for every chunk it+ * holds - and anything short of that is `unknown` with the reason named,+ * never a silent `not_found`.+ *+ * The admissibility checks run widest gap first: nothing searched, then+ * nothing datable, then a root never reached, then vectors that are out+ * of date or do not cover what was reached. A doubly-short index+ * therefore reports the outermost of its shortfalls, which is the one an+ * operator fixes first, and the narrower ones surface on the next pass.+ *+ * Beyond admissibility, the escalation to `did_not_happen` is governed by+ * `assertDidNotHappen`, not by the mere presence of evidence: see+ * {@link NegativeRecallInput.assertDidNotHappen}.+ */+export function classifyNegativeRecall(input: NegativeRecallInput): NegativeRecallVerdict {+ const evidence = input.retraction ?? null;+ if (input.assertDidNotHappen === true && evidence === null) {+ // The advice names `not_found` because that is what the advised input+ // actually yields over an admissible corpus: a search that found+ // nothing observed absence, which is the definition of that state.+ // Promising `unknown` here would send a caller after a WEAKER answer+ // than the one it is about to receive.+ throw new NegativeRecallError(+ `negative recall: cannot assert ${NEGATIVE_RECALL_STATE.didNotHappen} with no retraction evidence; omit the assertion to receive the corpus statement the search supports (${NEGATIVE_RECALL_STATE.notFound} over an admissible index, otherwise a named refusal)`,+ );+ }++ const { snapshot } = input;+ if (snapshot === null) {+ return unknownVerdict(+ NEGATIVE_RECALL_UNKNOWN_REASON.coverageUnavailable,+ "index facts could not be read, so nothing is known about the searched corpus",+ );+ }+ if (!snapshot.exists) {+ // The configured index path is deliberately NOT quoted here. Every+ // reason built by this module may be persisted into a continuity+ // record and replicated between devices, and a host filesystem path+ // is not vault content. Callers that need it read it from the index+ // status surface, where it is a structured field rather than prose.+ return unknownVerdict(+ NEGATIVE_RECALL_UNKNOWN_REASON.indexAbsent,+ "no index exists at the configured path, so nothing was searched",+ );+ }++ const coverage = buildCoverageReceipt(snapshot, input.scope);+ if (snapshot.lastIndexedAt === null) {+ return unknownVerdict(+ NEGATIVE_RECALL_UNKNOWN_REASON.indexStale,+ "the index has never recorded a completed run, so its coverage cannot be dated",+ coverage,+ );+ }+ // `lastIndexedAt` is a raw text cell in the index's own state table and+ // this function is exported, so the value reaching here is not+ // guaranteed to be a calendar instant. It is not treated as a caller+ // error, unlike the evidence instant below: it is the STORE's value, so+ // the honest report is a refusal about this vault's index. Validated+ // BEFORE any comparison, because `Date.parse` yields NaN and every+ // comparison against NaN is false - an unguarded fall-through would let+ // an undatable index admit the strongest claim in the module.+ const indexedMs = Date.parse(snapshot.lastIndexedAt);+ if (!Number.isFinite(indexedMs)) {+ return unknownVerdict(+ NEGATIVE_RECALL_UNKNOWN_REASON.indexInstantUnusable,+ "the index stamped its last completed run with an instant that cannot be read as a date, so nothing can be dated against it",+ coverage,+ );+ }+ if (coverage.unindexed_roots.length > 0) {+ return unknownVerdict(+ NEGATIVE_RECALL_UNKNOWN_REASON.coverageDivergent,+ `the index reaches ${coverage.scope.length} of ${coverage.scope.length + coverage.unindexed_roots.length} authorized note root(s); not reached: ${coverage.unindexed_roots.join(", ")}`,+ coverage,+ );+ }+ if (snapshot.staleEmbeddings > 0) {+ return unknownVerdict(+ NEGATIVE_RECALL_UNKNOWN_REASON.indexStale,+ `${snapshot.staleEmbeddings} of ${snapshot.chunks} chunk(s) carry an out-of-date embedding`,+ coverage,+ );+ }+ // Vectors that do not cover the chunks are the narrowest admissibility+ // gap and the easiest to mistake for a pass: a chunk with no embedding+ // row is counted by NEITHER `staleEmbeddings` nor the document census,+ // so an index with no embeddings at all clears every check above.+ //+ // But "fewer vectors than chunks" is two different situations, and only+ // one of them is indeterminate. A model was recorded for this index and+ // its run did not finish - so part of the corpus is reachable one way+ // and part another, and no negative over it is well-founded. Versus: no+ // model was ever recorded, which is a supported way to run this system+ // (semantic search needs a key the operator may not have) and a+ // deliberate, coherent configuration. Refusing the latter would leave a+ // keyword-only vault permanently unable to receive this module's main+ // answer, which is how a verdict stops being read. The receipt carries+ // the vector count and the signature and the digest binds both, so a+ // consumer can see the negative was keyword-only and judge for itself.+ const embeddingModelRecorded = snapshot.embeddingSignature !== null;+ if (embeddingModelRecorded && snapshot.embeddings < snapshot.chunks) {+ return unknownVerdict(+ NEGATIVE_RECALL_UNKNOWN_REASON.embeddingsIncomplete,+ `the index records embedding model '${snapshot.embeddingSignature}' and holds ${snapshot.embeddings} embedding(s) for ${snapshot.chunks} chunk(s), so its run is unfinished and part of the corpus is unreachable by a semantic query`,+ coverage,+ );+ }++ if (evidence !== null) {+ const recordedMs = Date.parse(evidence.recorded_at);+ if (!Number.isFinite(recordedMs)) {+ throw new NegativeRecallError(+ `negative recall: retraction evidence for ${evidence.subject} carries an unusable instant (${evidence.recorded_at})`,+ );+ }+ // The instant comparison is what makes the evidence load-bearing: an+ // index built before the retraction was recorded never saw it, so a+ // negative drawn from it attests to nothing about the retraction.+ // Checked whether or not the caller asserted anything, because an+ // index that predates known evidence is stale as a matter of fact and+ // its `not_found` would be no better founded than its+ // `did_not_happen`.+ if (recordedMs > indexedMs) {+ return unknownVerdict(+ NEGATIVE_RECALL_UNKNOWN_REASON.indexStale,+ `the retraction of ${evidence.subject} was recorded at ${evidence.recorded_at}, after the index was last built at ${snapshot.lastIndexedAt}`,+ coverage,+ );+ }+ // The assertion, not the evidence, is what escalates. A caller may+ // hand over retraction evidence while merely asking what the corpus+ // supports - the recall gate does exactly that with the adequacy+ // verdict - and answering it with the strongest state in the+ // vocabulary would be a claim it never made. Without the assertion+ // the evidence has still done work: it gated the staleness check+ // above, and the `not_found` below is now known to come from an index+ // that had already seen the retraction.+ if (input.assertDidNotHappen === true) {+ return Object.freeze({+ state: NEGATIVE_RECALL_STATE.didNotHappen,+ complete: true,+ coverage,+ reason: `${evidence.subject} carries a ${evidence.kind} edge recorded at ${evidence.recorded_at}, which the index at ${snapshot.lastIndexedAt} already reflects`,+ });+ }+ }++ return Object.freeze({+ state: NEGATIVE_RECALL_STATE.notFound,+ complete: true,+ coverage,+ reason: `no match across ${coverage.documents} document(s) and ${coverage.chunks} chunk(s) indexed at ${snapshot.lastIndexedAt}`,+ });+}++/** Every `unknown` leaves through here, so the shape cannot drift. */+function unknownVerdict(+ reason: NegativeRecallUnknownReason,+ detail: string,+ coverage?: CoverageReceipt,+): NegativeRecallVerdict {+ return Object.freeze({+ state: NEGATIVE_RECALL_STATE.unknown,+ complete: false,+ // Absent rather than null when no receipt could be built, matching+ // the optional-block convention the recall-gate output already uses.+ ...(coverage !== undefined ? { coverage } : {}),+ reason: detail,+ unknown_reason: reason,+ });+}diff --git a/src/core/brain/notes/create-note.ts b/src/core/brain/notes/create-note.tsindex 95d89e02..ecfa28b0 100644--- a/src/core/brain/notes/create-note.ts+++ b/src/core/brain/notes/create-note.ts@@ -327,8 +327,8 @@ export function resolveNoteTarget(vault: string, path: string): ResolvedNoteTarg}// The operator's declared write binding (provenance-at-the-boundary,- // unit B). This function is the ONE envelope every caller-named write- // shares - `createNote` and the batch core's create / update / append+ // unit B). This function is the ONE envelope every caller-named NOTE+ // write shares - `createNote` and the batch core's create / update / append// arms all resolve their target here - so the boundary is checked// exactly once, before any directory is created or byte written. The// refusal is composed in the binding module, never here; absentdiff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.tsindex ed53627e..c2c413a1 100644--- a/src/core/brain/path-constants.ts+++ b/src/core/brain/path-constants.ts@@ -1,6 +1,7 @@/*** Canonical vault-relative layout of the Brain tree: every directory and- * artefact filename under `<vault>/Brain/`, and nothing else.+ * artefact filename under `<vault>/Brain/`, plus the two names of the+ * sibling derived-store directory that the snapshot family has to reach.** Single source of truth. Every module that builds a path inside the* Brain layer imports these instead of repeating the literal. A future@@ -50,7 +51,15 @@ export const BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");export const BRAIN_GAP_TASKS_REL = posix.join(BRAIN_ROOT_REL, "gap-tasks");/** Persisted contradiction (tension) notes: `Brain/tensions/tension-<slug>.md` (S2). */export const BRAIN_TENSIONS_REL = posix.join(BRAIN_ROOT_REL, "tensions");-export const BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, "log");+/**+ * Directory NAME of the Brain log, as a top-level `Brain/` entry. Named+ * beside the vault-relative path because a consumer comparing paths that+ * are relative to `Brain/` itself - the snapshot differ, which walks two+ * extracted trees with no vault around them - needs the segment rather+ * than the path.+ */+export const BRAIN_LOG_DIR = "log";+export const BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, BRAIN_LOG_DIR);/*** Inbound-capture staging + archive (Knowledge intake suite, seam 1,* t_f8f5ef6a). Mirrors the inbox-versus-processed distinction: a capture@@ -77,19 +86,76 @@ export const BRAIN_SOURCES_REL = posix.join(BRAIN_ROOT_REL, "sources");export const BRAIN_REPORTS_REL = posix.join(BRAIN_ROOT_REL, "reports");/** Source-distillation pages: `Brain/distillations/dist-<slug>.md` (t_2e2e959f). */export const BRAIN_DISTILLATIONS_REL = posix.join(BRAIN_ROOT_REL, "distillations");-export const BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, ".snapshots");+/** Directory NAME of the snapshot archive home, as a top-level `Brain/` entry. */+export const BRAIN_SNAPSHOTS_DIR = ".snapshots";+export const BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_SNAPSHOTS_DIR);/*** Ephemeral MCP tool-result artifacts (v0.18.0). Dot-directory so the* vault walker excludes it from search/indexing exactly like* `.snapshots`; never backed up, pruned by TTL on server startup.*/-export const BRAIN_ARTIFACTS_REL = posix.join(BRAIN_ROOT_REL, ".artifacts");+export const BRAIN_ARTIFACTS_DIR = ".artifacts";+export const BRAIN_ARTIFACTS_REL = posix.join(BRAIN_ROOT_REL, BRAIN_ARTIFACTS_DIR);++/**+ * The top-level `Brain/` entries the snapshot family never touches:+ * never archived, never hashed into a manifest, and never removed by a+ * restore.+ *+ * `.snapshots` is excluded because archiving the archive home would+ * either explode the tar or let a rollback to an older state erase the+ * newer recovery points that are the operator's way forward.+ *+ * `.artifacts` is excluded because it is ephemeral tool output with a+ * TTL, documented above as never backed up. It was nevertheless archived+ * in every snapshot and hashed into every manifest, so churn in a cache+ * nobody wants restored tripped the rollback drift gate. One list, read+ * by the archiver, the manifest walker and the restore, is what keeps the+ * three from disagreeing again.+ */+export const BRAIN_SNAPSHOT_EXCLUDED_ENTRIES: ReadonlyArray<string> = Object.freeze([+ BRAIN_SNAPSHOTS_DIR,+ BRAIN_ARTIFACTS_DIR,+]);++/**+ * The DERIVED store: `<vault>/.open-second-brain/brain.sqlite`.+ *+ * A sibling of `Brain/`, not a member of it, and the only file in that+ * directory the snapshot family may ever touch. The directory also holds+ * encrypted secrets, the install and protect lockfiles, a second SQLite+ * lease database and the ingest checkpoints - none of which belongs in a+ * recovery archive of the Markdown tree, which is why the constant names+ * the FILE and every caller joins the two rather than archiving the+ * directory.+ *+ * The literal used to be repeated at roughly a dozen sites behind four+ * private per-module constants. Naming it here does not make this module+ * know what a search index is: it knows a name, exactly as it does for+ * every `Brain/` entry above.+ */+export const DERIVED_STORE_DIR = ".open-second-brain";+export const DERIVED_STORE_FILE = "brain.sqlite";/** Brain-internal artefact filenames at the root of `Brain/`. */export const BRAIN_CONFIG_FILE = "_brain.yaml";export const BRAIN_MANUAL_FILE = "_BRAIN.md";export const BRAIN_ACTIVE_FILE = "active.md";export const BRAIN_LESSONS_FILE = "lessons.md";+/**+ * Operator-authored standing rules injected at the head of every session+ * preamble (silence-is-not-an-answer, U8).+ *+ * The DIRECTORY is most of the enforcement mechanism, and the reason the+ * name is a constant rather than a config key. Living under `Brain/` means+ * the note-target resolver already refuses it for the four caller-named+ * note-write tools; the label writer, which reaches a caller-named path+ * through the containment-only resolver, is refused by name in+ * `standing-rules.ts` instead. A configurable filename would be a second+ * thing to keep protected on both of those paths and would buy nothing the+ * operator cannot get by editing this file.+ */+export const BRAIN_STANDING_RULES_FILE = "standing-rules.md";export const BRAIN_PINNED_FILE = "pinned.md";export const BRAIN_INDEX_FILE = "_INDEX.md";/** Persisted claim-graph projection artifact (Belief lifecycle suite, A3). */diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.tsindex b209151a..838cb3ee 100644--- a/src/core/brain/paths.ts+++ b/src/core/brain/paths.ts@@ -62,6 +62,7 @@ import {BRAIN_SKILL_PROPOSALS_REJECTED_REL,BRAIN_SNAPSHOTS_REL,BRAIN_SOURCES_REL,+ BRAIN_STANDING_RULES_FILE,BRAIN_STATE_REL,BRAIN_TENSIONS_REL,BRAIN_THESES_REL,@@ -207,6 +208,21 @@ export function brainLessonsPath(vault: string): string {return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_LESSONS_FILE), vault);}+/**+ * Path of the operator-authored standing-rules file+ * (`Brain/standing-rules.md`, silence-is-not-an-answer U8).+ *+ * Unlike every other artefact at this level it is written by hand and+ * never by this system: `dream` does not generate it, no CLI verb+ * rewrites it, and the note-target resolver refuses it to every+ * caller-named write tool because its first path segment is `Brain`.+ * Read by the `SessionStart` hook ahead of the memory layer and by+ * `brain_context`.+ */+export function brainStandingRulesPath(vault: string): string {+ return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_STANDING_RULES_FILE), vault);+}+/** Path of the transient current-task scratchpad read by `brain_context`. */export function brainPinnedPath(vault: string): string {return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_PINNED_FILE), vault);@@ -537,10 +553,49 @@ export function snapshotsDir(vault: string): string {return brainDirs(vault).snapshots;}+/**+ * Filename suffix of the Markdown-tree archive. The extension stays+ * `.zst` even when the host only has gzip: the restore probes the magic+ * bytes rather than the name, and one suffix keeps the listing filter a+ * single comparison.+ */+export const SNAPSHOT_ARCHIVE_SUFFIX = ".tar.zst";++/**+ * Filename suffix of the derived-store archive that may sit BESIDE the+ * tar for the same run id.+ *+ * Beside, not inside: the extractor requires a `Brain/` root and the+ * restore is defined as "live `Brain/` equals archive `Brain/` minus the+ * excluded entries", so a second top-level member in the tar would break+ * both invariants. Keeping the file in the SAME `.snapshots/` directory+ * keeps listing and retention one family with one loop.+ */+export const SNAPSHOT_STORE_ARCHIVE_SUFFIX = ".store.sqlite.zst";+/** Snapshot archive path: `Brain/.snapshots/<run_id>.tar.zst`. */export function snapshotPath(vault: string, runId: string): string {const id = validateRunId(runId);- return ensureInsideVault(join(brainDirs(vault).snapshots, `${id}.tar.zst`), vault);+ return ensureInsideVault(+ join(brainDirs(vault).snapshots, `${id}${SNAPSHOT_ARCHIVE_SUFFIX}`),+ vault,+ );+}++/**+ * Derived-store archive path:+ * `Brain/.snapshots/<run_id>.store.sqlite.zst`.+ *+ * Built through the same run-id validation and vault containment as+ * {@link snapshotPath}, because it is written into the same directory+ * from the same caller-supplied id and deserves no weaker guard.+ */+export function snapshotStorePath(vault: string, runId: string): string {+ const id = validateRunId(runId);+ return ensureInsideVault(+ join(brainDirs(vault).snapshots, `${id}${SNAPSHOT_STORE_ARCHIVE_SUFFIX}`),+ vault,+ );}/** Artifacts root: `Brain/.artifacts/`. */diff --git a/src/core/brain/payload-registry.ts b/src/core/brain/payload-registry.tsindex 08d2087f..5f90c927 100644--- a/src/core/brain/payload-registry.ts+++ b/src/core/brain/payload-registry.ts@@ -1,8 +1,8 @@-import { createHash } from "node:crypto";import { existsSync, mkdirSync, readFileSync } from "node:fs";import { join } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";+import { sha256Hex } from "../integrity/digest.ts";import { ensureInsideVault } from "./paths.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";@@ -77,7 +77,7 @@ export class PayloadRegistry {// 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 sha256 = sha256Hex(text);const ref = `${PAYLOAD_REF_PREFIX}${sha256}`;const placeholder = `[payload: ${ref} chars=${text.length}]`;mkdirSync(this.payloadDir(), { recursive: true });diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex f9726adb..40689811 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -35,7 +35,11 @@export { BrainConfigError, type BrainConfigLoadWarning } from "./policy/errors.ts";export { type BrainConfigKeyIndex } from "./policy/key-index.ts";-export { BRAIN_CONFIG_SUPPORTED_VERSIONS, DEFAULT_BRAIN_CONFIG } from "./policy/defaults.ts";+export {+ BRAIN_CONFIG_SUPPORTED_VERSIONS,+ DEFAULT_BRAIN_CONFIG,+ DERIVED_STORE_MAX_BYTES_DEFAULT,+} from "./policy/defaults.ts";export { formatPrimaryAgentYamlValue } from "./policy/primary-agent.ts";export {brainConfigKnownKeys,@@ -53,8 +57,10 @@ export {loadGuardrailsConfigSafe,loadIntegrityConfigSafe,loadNotesConfigSafe,+ loadSnapshotDerivedStorePolicySafe,loadSnapshotRetentionSafe,loadTemporalConfigSafe,+ type BrainDerivedStorePolicy,type LoadBrainConfigResult,} from "./policy/load.ts";@@ -69,7 +75,18 @@ export {MOST_APPLIED_WINDOW_DAYS_DEFAULT,MOST_APPLIED_WINDOW_DAYS_MAX,MOST_APPLIED_WINDOW_DAYS_MIN,+ resolveStandingRulesMaxChars,} from "./policy/blocks/active.ts";+/**+ * The standing-rules cap is declared beside the reader it governs+ * (`standing-rules.ts`) and re-exported here so every `active:` knob is+ * reachable from the one policy surface its neighbours already use.+ */+export {+ STANDING_RULES_MAX_CHARS_DEFAULT,+ STANDING_RULES_MAX_CHARS_MAX,+ STANDING_RULES_MAX_CHARS_MIN,+} from "./standing-rules.ts";export {LESSONS_CORROBORATION_MIN_DEFAULT,LESSONS_CORROBORATION_MIN_MAX,diff --git a/src/core/brain/policy/blocks/active.ts b/src/core/brain/policy/blocks/active.tsindex 03489e81..ada08f1a 100644--- a/src/core/brain/policy/blocks/active.ts+++ b/src/core/brain/policy/blocks/active.ts@@ -2,13 +2,21 @@* The `active:` block โ what `Brain/active.md` renders and how much of it* is injected at SessionStart.*- * One reason to change: the size of the agent's always-on preamble.+ * One reason to change: the size of the agent's always-on preamble -+ * which is why the cap on the operator's standing-rules block lives here+ * too, even though that block is exempt from the injection budget and+ * charged against its own number.* Out-of-range values are hard errors: an operator-tunable knob that* silently reverted to its default would be indistinguishable from never* having been set.*/import type { BrainActiveConfig, BrainConfig, BrainMostAppliedConfig } from "../../types.ts";+import {+ STANDING_RULES_MAX_CHARS_DEFAULT,+ STANDING_RULES_MAX_CHARS_MAX,+ STANDING_RULES_MAX_CHARS_MIN,+} from "../../standing-rules.ts";import { requireIntegerInRange } from "../field-checks.ts";import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";@@ -55,6 +63,7 @@ const KNOWN_KEYS = ["most_applied_window_days","most_applied_limit","inject_budget_chars",+ "standing_rules_max_chars",] as const;/**@@ -69,25 +78,50 @@ export function parseActiveBlock(ctx: BlockParseContext): BrainActiveConfig | unconst mostApplied = parseMostApplied(activeMap, ctx.source);- let injectBudgetChars: number | undefined;- if ("inject_budget_chars" in activeMap) {- requireIntegerInRange(- "active.inject_budget_chars",- activeMap["inject_budget_chars"],- INJECT_BUDGET_CHARS_MIN,- INJECT_BUDGET_CHARS_MAX,- ctx.source,- );- injectBudgetChars = activeMap["inject_budget_chars"] as number;- }+ const injectBudgetChars = optionalCharCount(+ activeMap,+ "inject_budget_chars",+ INJECT_BUDGET_CHARS_MIN,+ INJECT_BUDGET_CHARS_MAX,+ ctx.source,+ );+ const standingRulesMaxChars = optionalCharCount(+ activeMap,+ "standing_rules_max_chars",+ STANDING_RULES_MAX_CHARS_MIN,+ STANDING_RULES_MAX_CHARS_MAX,+ ctx.source,+ );warnUnknownKeys(ctx, activeMap, KNOWN_KEYS, BLOCK);return {...(mostApplied !== undefined ? { most_applied: mostApplied } : {}),...(injectBudgetChars !== undefined ? { inject_budget_chars: injectBudgetChars } : {}),+ ...(standingRulesMaxChars !== undefined+ ? { standing_rules_max_chars: standingRulesMaxChars }+ : {}),};}+/**+ * Read one optional character-count knob: absent stays absent so the+ * consumer's own default applies, present is range-checked as a hard+ * error. Both knobs in this block are the same shape, and writing the+ * `in`-check plus the range call twice is how the second one eventually+ * gets a clamped bound the first does not have.+ */+function optionalCharCount(+ activeMap: Readonly<Record<string, unknown>>,+ key: string,+ min: number,+ max: number,+ source: string | null,+): number | undefined {+ if (!(key in activeMap)) return undefined;+ requireIntegerInRange(`${BLOCK}.${key}`, activeMap[key], min, max, source);+ return activeMap[key] as number;+}+/*** Read side of `active.most_applied`: the configured window, or* {@link BRAIN_MOST_APPLIED_DEFAULTS} when the block (or the whole@@ -98,6 +132,17 @@ export function resolveMostApplied(cfg: BrainConfig): BrainMostAppliedConfig {return cfg.active?.most_applied ?? BRAIN_MOST_APPLIED_DEFAULTS;}+/**+ * Read side of `active.standing_rules_max_chars`: the configured cap, or+ * the reader's default. Takes a nullable config so the two callers - the+ * SessionStart hook, which absorbs an unreadable `_brain.yaml` into the+ * defaults, and `brain_context`, which does the same - resolve the+ * number through one function instead of each spelling the fallback.+ */+export function resolveStandingRulesMaxChars(cfg: BrainConfig | null): number {+ return cfg?.active?.standing_rules_max_chars ?? STANDING_RULES_MAX_CHARS_DEFAULT;+}+/*** Either key alone opts the block in; the other one falls back to its* default, so `most_applied` is always a complete struct or absentdiff --git a/src/core/brain/policy/blocks/lifecycle.ts b/src/core/brain/policy/blocks/lifecycle.tsindex e489dec4..eda069b2 100644--- a/src/core/brain/policy/blocks/lifecycle.ts+++ b/src/core/brain/policy/blocks/lifecycle.ts@@ -124,5 +124,18 @@ export function parseConfidenceBlock(ctx: BlockParseContext): BrainConfidenceConexport function parseSnapshotsBlock(ctx: BlockParseContext): BrainSnapshotsConfig {const snapshots = merge(ctx, "snapshots", DEFAULT_BRAIN_CONFIG.snapshots);requirePositiveInteger("snapshots.retention_count", snapshots.retention_count, ctx.source);- return { retention_count: snapshots.retention_count as number };+ requirePositiveInteger(+ "snapshots.derived_store_max_bytes",+ snapshots.derived_store_max_bytes,+ ctx.source,+ );+ return {+ retention_count: snapshots.retention_count as number,+ // Derived-store coverage is opt-in, so anything that is not+ // literally `true` leaves it off. Same rule as+ // `dream.heal_enrich_enabled`: a typo in a switch that costs disk on+ // every replicated peer must fail closed, not open.+ include_derived_store: snapshots.include_derived_store === true,+ derived_store_max_bytes: snapshots.derived_store_max_bytes as number,+ };}diff --git a/src/core/brain/policy/defaults.ts b/src/core/brain/policy/defaults.tsindex 0cdf9701..d5b0983c 100644--- a/src/core/brain/policy/defaults.ts+++ b/src/core/brain/policy/defaults.ts@@ -18,6 +18,19 @@ import { DEFAULT_VAULT_IGNORE_PATHS } from "../../vault-scope/defaults.ts";/** Schema versions this build understands. Bump on incompatible changes. */export const BRAIN_CONFIG_SUPPORTED_VERSIONS: ReadonlyArray<number> = [1];+/**+ * Default ceiling on the derived store a snapshot will archive: 256 MiB.+ *+ * Chosen against the two numbers that actually bound the cost. Retention+ * keeps ten archives, and `.snapshots/` is replicated peer-to-peer, so+ * the default ceiling admits at most ten compressed copies of a 256 MiB+ * database on every device. Larger stores are a deliberate decision the+ * operator makes by raising this number, which is why the ceiling+ * refuses and names the measured size instead of silently truncating or+ * silently skipping.+ */+export const DERIVED_STORE_MAX_BYTES_DEFAULT = 256 * 1024 * 1024;+/*** Default `_brain.yaml` content. Mirrors ยง10 of the design doc. Used by* `brain init` and as the fallback inside `loadBrainConfig` when callers@@ -43,6 +56,8 @@ export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({}),snapshots: Object.freeze({retention_count: 10,+ include_derived_store: false,+ derived_store_max_bytes: DERIVED_STORE_MAX_BYTES_DEFAULT,}),vault: Object.freeze({ignore_paths: DEFAULT_VAULT_IGNORE_PATHS,diff --git a/src/core/brain/policy/load.ts b/src/core/brain/policy/load.tsindex faef76c5..d4177f7b 100644--- a/src/core/brain/policy/load.ts+++ b/src/core/brain/policy/load.ts@@ -207,6 +207,43 @@ export const loadSnapshotRetentionSafe = makeAbsentTolerantLoader(DEFAULT_BRAIN_CONFIG.snapshots.retention_count,);+/**+ * Derived-store coverage as the archiver consumes it: whether to include+ * the store, and the ceiling above which inclusion is refused.+ *+ * A pair rather than two loaders because the two are never useful apart+ * - the ceiling only means anything when inclusion is on, and reading+ * them from two config loads would let one call see a file the other+ * did not.+ */+export interface BrainDerivedStorePolicy {+ readonly include: boolean;+ readonly maxBytes: number;+}++/**+ * Load `snapshots.include_derived_store` and+ * `snapshots.derived_store_max_bytes`, falling back to the defaults when+ * the config file is absent so a vault that has never run `brain init`+ * still snapshots its Markdown tree (with coverage off, which is what+ * the defaults say).+ *+ * An unreadable config raises, exactly as it does for the retention+ * count beside it: coverage is what an operator turned ON, and answering+ * with the default `false` would silently strip the store out of every+ * recovery point on a vault whose `_brain.yaml` merely has a typo.+ */+export const loadSnapshotDerivedStorePolicySafe = makeAbsentTolerantLoader<BrainDerivedStorePolicy>(+ (config: BrainConfig) => ({+ include: config.snapshots.include_derived_store,+ maxBytes: config.snapshots.derived_store_max_bytes,+ }),+ Object.freeze({+ include: DEFAULT_BRAIN_CONFIG.snapshots.include_derived_store,+ maxBytes: DEFAULT_BRAIN_CONFIG.snapshots.derived_store_max_bytes,+ }),+);+/*** Load + resolve `active.most_applied`, falling back to* `BRAIN_MOST_APPLIED_DEFAULTS` when the config file is absent, so a vaultdiff --git a/src/core/brain/research/external-fetch.ts b/src/core/brain/research/external-fetch.tsindex bbcc0853..810e774c 100644--- a/src/core/brain/research/external-fetch.ts+++ b/src/core/brain/research/external-fetch.ts@@ -24,6 +24,7 @@* error string that happens to embed the key is scrubbed before it surfaces.*/+import { canonicalJson } from "../../integrity/digest.ts";import { redactRawOutput } from "../../redactor.ts";/** Distinct failure kinds a keyed fetch can produce. */@@ -106,17 +107,6 @@ export interface KeyedFetchConfig {readonly cache?: ResponseCache;}-/** Stable stringify with sorted object keys, for deterministic cache keys. */-function stableStringify(value: unknown): string {- if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;- const record = value as Record<string, unknown>;- const parts = Object.keys(record)- .toSorted()- .map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`);- return `{${parts.join(",")}}`;-}-/** Query string in deterministic (sorted-key) order. */function sortedQuery(query: Readonly<Record<string, string>> | undefined): string {if (query === undefined) return "";@@ -132,12 +122,21 @@ function sortedQuery(query: Readonly<Record<string, string>> | undefined): strin* - so no credential can leak into a cache key or the paths derived from one.* The accept type is part of the key so a shared cache can never serve a JSON* value where text was expected (or vice versa).+ *+ * The body is serialized by the shared {@link canonicalJson}. This module+ * carried its own sorted-key stringifier with the same key ordering and one+ * difference: an object entry whose value is `undefined` rendered as+ * `"key":null` instead of being omitted. Omitting it is what the body+ * actually sent does - `JSON.stringify` drops those entries - so the shared+ * encoding keys two requests that go out as identical bytes to one entry+ * rather than two, and no value the module persists changes, because the key+ * is only ever an in-memory cache key.*/export function normalizeRequestKey(req: ExternalFetchRequest): string {const accept = req.accept ?? "json";const method = req.method ?? "GET";const query = sortedQuery(req.query);- const body = req.body === undefined ? "" : stableStringify(req.body);+ const body = req.body === undefined ? "" : canonicalJson(req.body);return `${accept} ${method} ${req.url}?${query}#${body}`;}diff --git a/src/core/brain/schema-admin.ts b/src/core/brain/schema-admin.tsindex 1bfb4252..349d5502 100644--- a/src/core/brain/schema-admin.ts+++ b/src/core/brain/schema-admin.ts@@ -1,13 +1,14 @@-import { brainConfigPath } from "./paths.ts";import { linkConstraintAllows, readBlockedRelationRows } from "../search/link-constraints.ts";import {buildSchemaReport,type BrainSchemaReport,type SchemaReportFinding,} from "./schema-report.ts";+import { assessSchemaPackIntegrity, type SchemaPackIntegrity } from "./schema-integrity.ts";import {FRONTMATTER_TIERS,loadSchemaPack,+ readSchemaPackSource,type FrontmatterTier,type SchemaPack,} from "./schema-pack.ts";@@ -79,27 +80,62 @@ export interface SchemaOrphanReport {readonly orphans: ReadonlyArray<SchemaReportFinding>;}-export interface SchemaSyncResult {- readonly dry_run: boolean;- readonly batch_size: number;- readonly updated: number;- readonly skipped: number;- readonly note: string;+/**+ * The one schema pack this vault has, described honestly: where it is,+ * whether that file is actually on disk, what it declares, and whether it+ * is still the pack the last audited apply produced.+ *+ * `exists` is not redundant with `integrity`. A reader that only renders+ * the path needs to know the path names a real file; a reader that cares+ * about tampering needs the verdict. Reporting a path nothing checked was+ * the defect this field closes.+ */+export interface ActiveSchemaPack {+ readonly path: string;+ readonly exists: boolean;+ readonly pack: SchemaPack;+ readonly integrity: SchemaPackIntegrity;}-export function getActiveSchemaPack(vault: string): {- path: string;- pack: SchemaPack;-} {- return { path: brainConfigPath(vault), pack: loadSchemaPack(vault) };+/** One entry of {@link listSchemaPacks}. */+export interface SchemaPackListing {+ readonly name: string;+ readonly path: string;+ readonly active: boolean;+ readonly exists: boolean;+ readonly integrity: SchemaPackIntegrity;+}++/** Name of the single pack; there is no registry and no second entry. */+const ACTIVE_SCHEMA_PACK_NAME = "active";++export function getActiveSchemaPack(vault: string): ActiveSchemaPack {+ const source = readSchemaPackSource(vault);+ return {+ path: source.path,+ exists: source.present,+ pack: source.pack,+ integrity: assessSchemaPackIntegrity(vault),+ };}export function listSchemaPacks(vault: string): {active: string;- packs: ReadonlyArray<{ name: string; path: string; active: boolean }>;+ packs: ReadonlyArray<SchemaPackListing>;} {- const active = brainConfigPath(vault);- return { active, packs: [{ name: "active", path: active, active: true }] };+ const source = readSchemaPackSource(vault);+ return {+ active: source.path,+ packs: [+ {+ name: ACTIVE_SCHEMA_PACK_NAME,+ path: source.path,+ active: true,+ exists: source.present,+ integrity: assessSchemaPackIntegrity(vault),+ },+ ],+ };}export function buildSchemaStats(vault: string): SchemaStats {@@ -256,16 +292,44 @@ export async function applySchemaAdminMutations(return await applySchemaMutations(vault, mutations, opts);}-export function buildSchemaSyncResult(- opts: { dryRun?: boolean; batchSize?: number } = {},-): SchemaSyncResult {- return {- dry_run: opts.dryRun ?? true,- batch_size: opts.batchSize ?? 100,- updated: 0,- skipped: 0,- note: "schema_type metadata is already stored in vault files; no backfill was required",- };+/**+ * `o2b brain schema sync` asked for a backfill that was never written.+ *+ * The verb returned `{updated: 0, skipped: 0, note: "no backfill was+ * required"}` unconditionally - it did not read the vault, and it did not+ * even take one: a caller could not tell "nothing needed doing" from+ * "nothing was done". A success report from a function that performed no+ * work is the exact failure this wave exists to remove, so the verb now+ * refuses.+ *+ * Refusing rather than implementing the backfill is deliberate. What+ * `sync` should write is undefined: no design says which frontmatter+ * fields a schema change is supposed to propagate into existing notes,+ * and inventing one inside an integrity unit would ship a vault-wide+ * rewrite nobody specified. An explicit refusal costs an operator one+ * error message; a guessed backfill costs them their notes.+ */+export class SchemaSyncUnavailableError extends Error {+ /** The vault the caller asked to sync, echoed so a log names the store. */+ readonly vault: string;++ constructor(vault: string) {+ super(+ `schema sync is not implemented: no schema backfill is defined for ${vault}, ` ++ "and the verb will not report success for work it did not do",+ );+ this.name = "SchemaSyncUnavailableError";+ this.vault = vault;+ }+}++/**+ * Refuse the schema sync, naming the vault it would have operated on. The+ * parameter is what the previous signature was missing: an implementation+ * can land behind this entry point without every caller changing.+ */+export function buildSchemaSyncResult(vault: string): never {+ throw new SchemaSyncUnavailableError(vault);}export function parseSchemaMutationPayloads(payloads: ReadonlyArray<string>): SchemaMutation[] {diff --git a/src/core/brain/schema-integrity.ts b/src/core/brain/schema-integrity.tsnew file mode 100644index 00000000..c07ef385--- /dev/null+++ b/src/core/brain/schema-integrity.ts@@ -0,0 +1,340 @@+/**+ * U1 - is the schema pack still the one that was applied?+ *+ * The `schema:` block of `Brain/_brain.yaml` is the operator-curated+ * ontology that gates every Brain write. Until now four distinct+ * conditions rendered identically on every read surface: the pack is+ * exactly what the last audited apply produced; it has been hand-edited+ * since; nothing has ever been applied so there is no expectation to+ * compare against; and there is no config file at all. A reader that+ * cannot tell those apart is being told nothing, which is the failure this+ * wave exists to remove.+ *+ * The mechanism is a digest recorded at apply time and recomputed at read+ * time:+ *+ * - `ok` - the pack on disk digests to the value the newest+ * audited apply recorded.+ * - `modified` - it does not, and the mismatch names both sides.+ * - `unverified` - no honest comparison could be made, with a reason+ * saying which of the three ways that happened.+ *+ * ## Why the digest is over the RENDERED block, not the raw file+ *+ * {@link computeSchemaPackDigest} hashes `renderSchemaBlock(pack)`. That+ * reuses the canonical serializer the apply path already writes through,+ * so the read side and the write side cannot drift into two encodings of+ * one ontology. It also makes the digest invariant to everything in+ * `_brain.yaml` that is not ontology - comments, blank lines, key order+ * elsewhere in the file - so only a real change of the declared schema+ * moves it, and an operator who reflows a comment is not accused of+ * tampering.+ *+ * ## There is exactly one pack+ *+ * `listSchemaPacks` returns a hardcoded single entry: there is no pack+ * registry, no external pack, and a prior release explicitly refused+ * pack-by-URL. There is also no signature machinery anywhere in this+ * project. So `unverified` never means "the signature could not be+ * checked" - it means precisely one of the three named reasons below, and+ * nothing here should be read as a stronger claim than that.+ *+ * ## Not a degradation code+ *+ * `DEGRADATION_CODE` in `../integrity/degradation.ts` is consumed by+ * exhaustive switches with `never` defaults, so widening it is a+ * compile-breaking edit for unrelated consumers. This unit owns its own+ * closed vocabulary instead, registered in the verdict-vocabulary census.+ * The mismatch it reports, on the other hand, IS the shared+ * {@link StampMismatch} shape, so `modified` renders through the same+ * `formatStampMismatch` every other integrity surface uses.+ */++import { existsSync, readdirSync, readFileSync } from "node:fs";+import { join } from "node:path";++import { sha256Hex } from "../integrity/digest.ts";+import { compareStamps, type StampMismatch } from "../integrity/stamp.ts";+import { brainDirs } from "./paths.ts";+import { readSchemaPackSource, renderSchemaBlock, type SchemaPack } from "./schema-pack.ts";++/** The three answers a schema-pack integrity read can honestly give. */+export const SCHEMA_PACK_INTEGRITY = Object.freeze({+ /** The pack on disk matches the digest the newest audited apply recorded. */+ ok: "ok",+ /** It does not match; `mismatches` names the recorded and the live digest. */+ modified: "modified",+ /** No comparison was possible; `unverified_reason` says why. */+ unverified: "unverified",+} as const);++/** Closed union over {@link SCHEMA_PACK_INTEGRITY}. */+export type SchemaPackIntegrityStatus =+ (typeof SCHEMA_PACK_INTEGRITY)[keyof typeof SCHEMA_PACK_INTEGRITY];++/** Membership list, in reporting order from best-known to least-known. */+export const SCHEMA_PACK_INTEGRITY_STATUSES: ReadonlyArray<SchemaPackIntegrityStatus> =+ Object.freeze([+ SCHEMA_PACK_INTEGRITY.ok,+ SCHEMA_PACK_INTEGRITY.modified,+ SCHEMA_PACK_INTEGRITY.unverified,+ ]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isSchemaPackIntegrityStatus(value: unknown): value is SchemaPackIntegrityStatus {+ return (+ typeof value === "string" &&+ (SCHEMA_PACK_INTEGRITY_STATUSES as ReadonlyArray<string>).includes(value)+ );+}++/**+ * Why no comparison could be made. Each member is a fact about this+ * vault's files, never a guess about intent: none of them is a softer way+ * of saying `ok`.+ */+export const SCHEMA_PACK_UNVERIFIED_REASON = Object.freeze({+ /**+ * The mutation-audit directory does not exist, or holds no+ * `schema_apply_mutations` record. Nothing was ever applied through the+ * audited path, so there is no recorded expectation to compare against.+ */+ noApplyRecorded: "no-apply-recorded",+ /**+ * The audit trail exists but could not be believed: a shard would not+ * read, a line would not parse, a record carried an unusable timestamp,+ * or the newest apply record carried no digest. Deliberately NOT `ok` -+ * an unreadable expectation is an absent one.+ */+ auditUnreadable: "audit-unreadable",+ /** `Brain/_brain.yaml` does not exist, so there is no pack to digest. */+ configAbsent: "config-absent",+} as const);++/** Closed union over {@link SCHEMA_PACK_UNVERIFIED_REASON}. */+export type SchemaPackUnverifiedReason =+ (typeof SCHEMA_PACK_UNVERIFIED_REASON)[keyof typeof SCHEMA_PACK_UNVERIFIED_REASON];++/** Membership list for {@link SCHEMA_PACK_UNVERIFIED_REASON}. */+export const SCHEMA_PACK_UNVERIFIED_REASONS: ReadonlyArray<SchemaPackUnverifiedReason> =+ Object.freeze([+ SCHEMA_PACK_UNVERIFIED_REASON.noApplyRecorded,+ SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable,+ SCHEMA_PACK_UNVERIFIED_REASON.configAbsent,+ ]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isSchemaPackUnverifiedReason(value: unknown): value is SchemaPackUnverifiedReason {+ return (+ typeof value === "string" &&+ (SCHEMA_PACK_UNVERIFIED_REASONS as ReadonlyArray<string>).includes(value)+ );+}++/**+ * Directory under `Brain/log/` holding the schema-mutation audit shards.+ * The writer and this reader must agree on it, so it is a constant rather+ * than the literal that used to sit at the apply site alone.+ */+export const SCHEMA_MUTATION_AUDIT_DIR = "schema-mutations";++/** The `action` value the apply path stamps on every mutation record. */+export const SCHEMA_MUTATION_AUDIT_ACTION = "schema_apply_mutations";++/** Key under an audit record's `details` holding the resulting pack digest. */+export const SCHEMA_PACK_DIGEST_FIELD = "pack_digest";++/** Audit shards are JSON Lines, one record per line. */+const AUDIT_SHARD_EXTENSION = ".jsonl";++/**+ * The shape of a digest this project writes: lowercase hex, nothing else.+ * The length is deliberately not asserted - the algorithm belongs to+ * `../integrity/digest.ts` and a future migration there must not have to+ * edit a number here - but a blank or non-hex value is not a digest and is+ * treated as an unreadable record rather than as a mismatch.+ */+const HEX_DIGEST_RE = /^[0-9a-f]+$/;++/** Frozen empty list, so every no-mismatch result shares one instance. */+const NO_MISMATCHES: ReadonlyArray<StampMismatch> = Object.freeze([]);++/**+ * The recorded expectation, or the named reason there is not one.+ *+ * A discriminated union rather than a nullable digest: a caller cannot+ * read the digest without having first established that one was found, so+ * "no expectation" can never be mistaken for "an empty expectation".+ */+export type RecordedSchemaPackDigest =+ | {+ readonly found: true;+ /** Digest of the pack the newest audited apply produced. */+ readonly digest: string;+ /** That apply's ISO-8601 timestamp, verbatim from the record. */+ readonly recorded_at: string;+ /** The shard the record was read from. */+ readonly audit_path: string;+ }+ | { readonly found: false; readonly reason: SchemaPackUnverifiedReason };++/** The verdict on one vault's schema pack. */+export interface SchemaPackIntegrity {+ readonly status: SchemaPackIntegrityStatus;+ /**+ * Digest of the pack currently on disk, or `null` when there is no+ * config file to digest. Never a digest of the substituted default:+ * digesting a file that is not there would be the fabrication this+ * whole unit exists to prevent.+ */+ readonly digest: string | null;+ /** The recorded digest, present only when one was found. */+ readonly expected?: string;+ /** When that digest was recorded, present only when one was found. */+ readonly recorded_at?: string;+ /** Which shard it was read from, present only when one was found. */+ readonly audit_path?: string;+ /** Present exactly when `status` is `unverified`. */+ readonly unverified_reason?: SchemaPackUnverifiedReason;+ /**+ * Non-empty exactly when `status` is `modified`, carrying the shared+ * mismatch shape so it renders through `formatStampMismatch`.+ */+ readonly mismatches: ReadonlyArray<StampMismatch>;+}++/** Absolute path of this vault's schema-mutation audit directory. */+export function schemaMutationAuditDir(vault: string): string {+ return join(brainDirs(vault).log, SCHEMA_MUTATION_AUDIT_DIR);+}++/**+ * Digest of a pack's canonical rendering - see the module docblock for why+ * the rendered block rather than the file is the thing that is hashed.+ */+export function computeSchemaPackDigest(pack: SchemaPack): string {+ return sha256Hex(renderSchemaBlock(pack));+}++/**+ * Read the digest recorded by the newest audited apply.+ *+ * "Newest" is by the record's own timestamp, not by shard name or line+ * order, so a replicated shard arriving out of order cannot make an older+ * apply win. Any shard that will not read, any line that will not parse,+ * and any record whose timestamp is unusable fails the whole read as+ * {@link SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable} rather than being+ * skipped: a partially-read audit trail would let a missing record present+ * as a clean one.+ */+export function readRecordedSchemaPackDigest(vault: string): RecordedSchemaPackDigest {+ const dir = schemaMutationAuditDir(vault);+ if (!existsSync(dir)) return notFound(SCHEMA_PACK_UNVERIFIED_REASON.noApplyRecorded);++ let shards: ReadonlyArray<string>;+ try {+ shards = readdirSync(dir)+ .filter((entry) => entry.endsWith(AUDIT_SHARD_EXTENSION))+ .toSorted();+ } catch {+ return notFound(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);+ }++ let newest: { record: Record<string, unknown>; at: number; path: string } | null = null;+ for (const shard of shards) {+ const path = join(dir, shard);+ let text: string;+ try {+ text = readFileSync(path, "utf8");+ } catch {+ return notFound(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);+ }+ for (const line of text.split("\n")) {+ if (line.trim().length === 0) continue;+ let parsed: unknown;+ try {+ parsed = JSON.parse(line) as unknown;+ } catch {+ return notFound(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);+ }+ if (!isRecord(parsed)) return notFound(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);+ if (parsed["action"] !== SCHEMA_MUTATION_AUDIT_ACTION) continue;+ const timestamp = parsed["timestamp"];+ if (typeof timestamp !== "string") {+ return notFound(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);+ }+ const at = Date.parse(timestamp);+ if (!Number.isFinite(at)) return notFound(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);+ if (newest === null || at >= newest.at) newest = { record: parsed, at, path };+ }+ }+ if (newest === null) return notFound(SCHEMA_PACK_UNVERIFIED_REASON.noApplyRecorded);++ const details = newest.record["details"];+ const digest = isRecord(details) ? details[SCHEMA_PACK_DIGEST_FIELD] : undefined;+ // An apply predating this feature recorded which mutations were+ // requested but no digest of the pack they produced. That record cannot+ // support a comparison, and reporting `ok` off the back of it would be a+ // claim nothing checked.+ if (typeof digest !== "string" || !HEX_DIGEST_RE.test(digest)) {+ return notFound(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);+ }+ const recordedAt = newest.record["timestamp"] as string;+ return Object.freeze({+ found: true as const,+ digest,+ recorded_at: recordedAt,+ audit_path: newest.path,+ });+}++/**+ * Compare the pack on disk against the digest the newest audited apply+ * recorded, and say which of the four conditions this vault is in.+ */+export function assessSchemaPackIntegrity(vault: string): SchemaPackIntegrity {+ const source = readSchemaPackSource(vault);+ if (!source.present) {+ return Object.freeze({+ status: SCHEMA_PACK_INTEGRITY.unverified,+ digest: null,+ unverified_reason: SCHEMA_PACK_UNVERIFIED_REASON.configAbsent,+ mismatches: NO_MISMATCHES,+ });+ }++ const digest = computeSchemaPackDigest(source.pack);+ const recorded = readRecordedSchemaPackDigest(vault);+ if (!recorded.found) {+ return Object.freeze({+ status: SCHEMA_PACK_INTEGRITY.unverified,+ digest,+ unverified_reason: recorded.reason,+ mismatches: NO_MISMATCHES,+ });+ }++ // The ungated comparison: this surface reports what it finds regardless+ // of any operator gate, and it reports it in the shape every other+ // integrity surface in this project emits.+ const mismatches = compareStamps(+ { [SCHEMA_PACK_DIGEST_FIELD]: recorded.digest },+ { [SCHEMA_PACK_DIGEST_FIELD]: digest },+ );+ return Object.freeze({+ status: mismatches.length === 0 ? SCHEMA_PACK_INTEGRITY.ok : SCHEMA_PACK_INTEGRITY.modified,+ digest,+ expected: recorded.digest,+ recorded_at: recorded.recorded_at,+ audit_path: recorded.audit_path,+ mismatches,+ });+}++function notFound(reason: SchemaPackUnverifiedReason): RecordedSchemaPackDigest {+ return Object.freeze({ found: false as const, reason });+}++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}diff --git a/src/core/brain/schema-mutate.ts b/src/core/brain/schema-mutate.tsindex f68ca19d..1ca5c6c8 100644--- a/src/core/brain/schema-mutate.ts+++ b/src/core/brain/schema-mutate.ts@@ -7,6 +7,13 @@ import { withFileLock } from "../reliability/lock.ts";import { brainConfigPath, brainDirsForWrite } from "./paths.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";import {+ computeSchemaPackDigest,+ SCHEMA_MUTATION_AUDIT_ACTION,+ SCHEMA_MUTATION_AUDIT_DIR,+ SCHEMA_PACK_DIGEST_FIELD,+} from "./schema-integrity.ts";+import {+ ABSENT_SCHEMA_CONFIG_TEXT,loadSchemaPack,parseSchemaPack,renderSchemaBlock,@@ -108,6 +115,14 @@ export interface ApplySchemaMutationsResult {readonly applied: number;readonly audit_path: string;readonly pack: SchemaPack;+ /**+ * Digest of the pack this batch produced, identical to the value written+ * into the audit record. Returned so a caller can seal a downstream+ * artifact against the same expectation a later+ * `assessSchemaPackIntegrity` will compare with, without re-reading the+ * audit trail it just wrote.+ */+ readonly pack_digest: string;}/**@@ -182,7 +197,7 @@ export async function applySchemaMutations(return await withFileLock(configPath, { staleMs: opts.lockStaleMs ?? 30_000, retries: 3 }, () => {const before = existsSync(configPath)? readFileSync(configPath, "utf8")- : "schema_version: 1\n";+ : ABSENT_SCHEMA_CONFIG_TEXT;const nextPack = applyMutationsToPack(parseSchemaPack(before), mutations);const nextText = replaceSchemaBlock(before, renderSchemaBlock(nextPack));atomicWriteText(configPath, nextText, {@@ -190,22 +205,32 @@ export async function applySchemaMutations(parseSchemaPack(candidate);},});- const auditPath = appendAuditRecord(join(brainDirsForWrite(vault).log, "schema-mutations"), {- timestamp: now.toISOString(),- actor: opts.actor,- action: "schema_apply_mutations",- target: "Brain/_brain.yaml",- ok: true,- details: {- applied: mutations.length,- mutations,- ...(opts.reason ? { reason: opts.reason } : {}),+ // The audit record has always said WHICH mutations were requested. The+ // digest is what it was missing: an expectation a later read can hold+ // the file against, so a hand-edit after this apply is detectable+ // rather than indistinguishable from the pack this batch produced.+ const packDigest = computeSchemaPackDigest(nextPack);+ const auditPath = appendAuditRecord(+ join(brainDirsForWrite(vault).log, SCHEMA_MUTATION_AUDIT_DIR),+ {+ timestamp: now.toISOString(),+ actor: opts.actor,+ action: SCHEMA_MUTATION_AUDIT_ACTION,+ target: "Brain/_brain.yaml",+ ok: true,+ details: {+ applied: mutations.length,+ mutations,+ [SCHEMA_PACK_DIGEST_FIELD]: packDigest,+ ...(opts.reason ? { reason: opts.reason } : {}),+ },},- });+ );return {applied: mutations.length,audit_path: auditPath,pack: nextPack,+ pack_digest: packDigest,};});}diff --git a/src/core/brain/schema-pack.ts b/src/core/brain/schema-pack.tsindex a96bbf54..28b10c06 100644--- a/src/core/brain/schema-pack.ts+++ b/src/core/brain/schema-pack.ts@@ -40,10 +40,50 @@ export const FRONTMATTER_TIERS = Object.freeze(["identity", "system", "business"export type FrontmatterTier = (typeof FRONTMATTER_TIERS)[number];-export function loadSchemaPack(vault: string): SchemaPack {+/**+ * The config text parsed in place of an absent `Brain/_brain.yaml`.+ *+ * It declares a schema version and nothing else, so it yields a pack with+ * an empty vocabulary - which is a legitimate default for the many callers+ * that only want to know what the ontology permits. It is named rather+ * than inlined because the substitution used to be an anonymous literal in+ * two modules, and because a caller that needs to tell "no ontology" from+ * "an ontology that declares nothing" must be able to see that the+ * substitution happened at all. {@link readSchemaPackSource} is how it+ * sees that; {@link loadSchemaPack} deliberately keeps the defaulting+ * behaviour for everyone else.+ */+export const ABSENT_SCHEMA_CONFIG_TEXT = "schema_version: 1\n";++/**+ * The schema pack together with the provenance a caller needs to judge it:+ * where it came from, and whether that file was actually there.+ *+ * `present === false` means the config file does not exist and+ * {@link ABSENT_SCHEMA_CONFIG_TEXT} was parsed instead. A caller that only+ * wants the ontology can keep calling {@link loadSchemaPack} and ignore+ * this entirely.+ */+export interface SchemaPackSource {+ /** Absolute path of `Brain/_brain.yaml`, whether or not it exists. */+ readonly path: string;+ /** False when the file is absent and the default text was substituted. */+ readonly present: boolean;+ /** The text that was parsed - the file's bytes, or the default. */+ readonly text: string;+ readonly pack: SchemaPack;+}++/** Read the schema pack and report whether its config file was there. */+export function readSchemaPackSource(vault: string): SchemaPackSource {const path = brainConfigPath(vault);- const text = existsSync(path) ? readFileSync(path, "utf8") : "schema_version: 1\n";- return parseSchemaPack(text);+ const present = existsSync(path);+ const text = present ? readFileSync(path, "utf8") : ABSENT_SCHEMA_CONFIG_TEXT;+ return Object.freeze({ path, present, text, pack: parseSchemaPack(text) });+}++export function loadSchemaPack(vault: string): SchemaPack {+ return readSchemaPackSource(vault).pack;}export function parseSchemaPack(configText: string): SchemaPack {diff --git a/src/core/brain/snapshot-diff.ts b/src/core/brain/snapshot-diff.tsindex e9516ed4..7cdd4940 100644--- a/src/core/brain/snapshot-diff.ts+++ b/src/core/brain/snapshot-diff.ts@@ -12,7 +12,8 @@* Preferences and retired files get a typed field-level diff for the* canonical set of derived/identity fields; everything else compares* by byte equality so the renderer can flag "log file body changed"- * without listing every byte.+ * without listing every byte. The log bucket covers every shape a log+ * file takes โ see {@link isBrainLogDay}.** Inputs are expected to be Brain/ root directories (not vault* roots). Callers feed `extractSnapshotToTemp(...).brainRoot` for@@ -22,6 +23,8 @@import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs";import { join, relative } from "node:path";+import { parseLogFileName } from "./log-jsonl.ts";+import { BRAIN_LOG_DIR, BRAIN_SNAPSHOTS_DIR } from "./path-constants.ts";import { parsePreference, parseRetired } from "./preference.ts";import type { BrainPreference, BrainRetired } from "./types.ts";@@ -145,6 +148,36 @@ export function diffBrainTrees(rootA: string, rootB: string): BrainTreeDiff {});}+/**+ * True for one day of the Brain log: `log/<date>.md`, `log/<date>.jsonl`,+ * or the per-device shards `log/<date>.<device-id>.{md,jsonl}`.+ *+ * The classifier predated per-device sharding and matched only the+ * unsharded markdown, so on any vault with a `device_id` configured โ the+ * normal case, and the only case where a rollback diff is interesting,+ * because sharding exists for multi-device replication โ every log file+ * fell through to `other`. The machine-primary `.jsonl` surface, which is+ * what `readLogDay` actually reads, was misclassified on every vault.+ *+ * The shape comes from {@link parseLogFileName} in `log-jsonl.ts`, the+ * module whose contract is that the shard layout lives in exactly one+ * place. This module previously carried a pattern of its own, and that+ * copy IS the defect above: a duplicated shape does not stay in step with+ * the builders, and a third copy written to repair the second would be a+ * third chance to fall behind them.+ *+ * The depth check keeps the bucket honest in the other direction. The log+ * directory also holds ledgers (`capture-decisions.jsonl`,+ * `recurrence-support.jsonl`) and subdirectories (`dream-runs/`,+ * `pref-audit/`) that are not days of the log, so the class is "a log day+ * directly under `log/`" rather than "anything below `log/`".+ */+function isBrainLogDay(rel: string): boolean {+ const segments = rel.split("/");+ if (segments.length !== 2 || segments[0] !== BRAIN_LOG_DIR) return false;+ return parseLogFileName(segments[1]!) !== null;+}+// ----- Walker + classifier -------------------------------------------------interface ScannedFile {@@ -186,7 +219,7 @@ function walkBrain(root: string): ReadonlyArray<ScannedFile> {// `.snapshots/` is the snapshot family itself โ comparing// archives across snapshots is not meaningful (each snapshot// owns its own archive set). Skip the tree entirely.- if (rel === ".snapshots" || rel.startsWith(".snapshots/")) continue;+ if (rel === BRAIN_SNAPSHOTS_DIR || rel.startsWith(`${BRAIN_SNAPSHOTS_DIR}/`)) continue;// Defense-in-depth: an entry whose relative path escapes the// walker root (`..` segment) cannot legitimately be inside// a Brain snapshot โ drop it rather than classify under a@@ -272,7 +305,7 @@ function scanFile(_root: string, abs: string, rel: string): ScannedFile {bytes: readFileSafe(abs),};}- if (rel.startsWith("log/") && /^log\/\d{4}-\d{2}-\d{2}\.md$/.test(rel)) {+ if (isBrainLogDay(rel)) {return {entry: {path: `Brain/${rel}`,diff --git a/src/core/brain/snapshot-gate.ts b/src/core/brain/snapshot-gate.tsindex f51e46eb..31676cfd 100644--- a/src/core/brain/snapshot-gate.ts+++ b/src/core/brain/snapshot-gate.ts@@ -5,7 +5,7 @@* guarantee: no destructive brain mutation runs without a recovery* point on disk first. The wrapper mints a validated, unique run id,* calls {@link createSnapshot} BEFORE the operation, runs the- * operation, then prunes to the configured retention.+ * operation, then returns the recovery point alongside its result.** Failure semantics (the reason this is a gate and not a helper):*@@ -13,11 +13,20 @@* propagates and `op` NEVER runs - a destructive operation that* cannot be protected must abort, never proceed unprotected.* - If `op` throws, the error propagates but the snapshot STAYS on- * disk - it is precisely the recovery point the caller needs. We- * therefore skip the post-run prune on the throwing path.+ * disk - it is precisely the recovery point the caller needs.*- * The engine module (656 lines) stays untouched; this sibling only- * composes its public functions.+ * ## One entry point, two callers+ *+ * {@link takeSnapshot} is the whole snapshot-and-prune path, exported so+ * that a caller wanting a recovery point with NO operation behind it has+ * somewhere to go. {@link withDestructiveSnapshot} calls it and then runs+ * the operation, which is what keeps the id minting, the collision+ * resolution and the retention pass in exactly one place: a second path+ * would be a second set of rules for the archives an operator later has+ * to reason about as one family.+ *+ * The engine module stays untouched; this sibling only composes its+ * public functions.*/import { existsSync } from "node:fs";@@ -26,10 +35,11 @@ import { loadSnapshotRetentionSafe } from "./policy.ts";import { snapshotPath, validateRunId } from "./paths.ts";import { createSnapshot, pruneSnapshots } from "./snapshot.ts";import { compactRunStamp } from "./time.ts";+import type { BrainSnapshotReason } from "./types.ts";/** The recovery point minted for a destructive operation. */export interface DestructiveSnapshot {- /** Validated run id of the archive (`<label>-<stamp>`). */+ /** Validated run id of the archive (`<reason>-<stamp>`). */readonly runId: string;/** Absolute path of the snapshot archive. */readonly path: string;@@ -40,8 +50,13 @@ export interface WithDestructiveSnapshotResult<T> {readonly result: T;}+/** Options of both entry points here, since both mint one run id. */export interface WithDestructiveSnapshotOptions {- /** Injected clock so callers can mint deterministic run ids in tests. */+ /**+ * Injected clock. It decides the run-id stamp AND the `snapshot` audit+ * line's timestamp, so a caller whose output is byte-reproducible given+ * its own clock stays that way across the recovery point it takes.+ */readonly now?: Date;}@@ -51,7 +66,7 @@ const MAX_SNAPSHOT_ID_ATTEMPTS = 64;/*** Create the recovery snapshot behind a unique run id. Selection and* creation are fused so a concurrent process cannot win the id between an- * availability probe and the write: we start from `<label>-<compactStamp>`,+ * availability probe and the write: we start from `<reason>-<compactStamp>`,* append `-2`, `-3`, ... on collision, and RETRY `createSnapshot` when the* write fails because the archive now exists (a racing process claimed it).* Any other create failure (missing tooling, unwritable archive) propagates@@ -61,12 +76,16 @@ const MAX_SNAPSHOT_ID_ATTEMPTS = 64;function createUniqueSnapshot(vault: string,baseRunId: string,-): { runId: string; snapshot: ReturnType<typeof createSnapshot> } {+ reason: BrainSnapshotReason,+ now: Date,+): DestructiveSnapshot {for (let n = 1; n <= MAX_SNAPSHOT_ID_ATTEMPTS; n++) {const candidate = n === 1 ? baseRunId : `${baseRunId}-${n}`;if (existsSync(snapshotPath(vault, candidate))) continue;try {- return { runId: candidate, snapshot: createSnapshot(vault, candidate) };+ // The clock that minted the id also stamps the audit line, so a+ // caller with an injected clock stays byte-reproducible.+ return { runId: candidate, path: createSnapshot(vault, candidate, { reason, now }).path };} catch (err) {// A concurrent op may have created this archive between our probe and// the write; createSnapshot refuses to overwrite. Retry the next id@@ -80,44 +99,75 @@ function createUniqueSnapshot(}/**- * Run `op` behind a pre-operation snapshot. Returns the recovery point- * alongside the operation's result. See the module header for the- * abort / retain failure semantics.+ * Write one recovery point for `reason` and enforce retention around it.+ *+ * The reason is required and doubles as the run-id label, so the archive's+ * filename and its recorded provenance can never disagree. It is also+ * what a later reader filters the revertible history by, which is why it+ * is a member of a closed vocabulary rather than a free label: five call+ * sites used to spell their labels three different ways and nothing+ * parsed any of them back.+ *+ * Retention runs here rather than after the caller's operation, and that+ * is safe by arithmetic rather than by luck: the configured+ * `retention_count` is a positive integer and this archive is the newest+ * in the directory, so the prune can never evict the point it just made.+ * A prune failure is a warning, never a throw - the recovery point exists,+ * and refusing the caller's operation because a cleanup pass could not run+ * would trade a real guarantee for a tidy directory.*/-export function withDestructiveSnapshot<T>(+export function takeSnapshot(vault: string,- label: string,- op: () => T,+ reason: BrainSnapshotReason,opts: WithDestructiveSnapshotOptions = {},-): WithDestructiveSnapshotResult<T> {- // validateRunId rejects a label that would form a filesystem-unsafe- // id (separators, traversal, Windows-reserved) - a typed error before- // any snapshot or mutation is attempted.- const baseRunId = validateRunId(`${label}-${compactRunStamp(opts.now ?? new Date())}`);+): DestructiveSnapshot {+ // Resolved once and used for both the run id and the audit line, so the+ // two can never name different instants.+ const now = opts.now ?? new Date();- // Snapshot FIRST, behind a collision-safe unique id. A throw here (missing- // tooling, unwritable archive) aborts before `op` runs - the destructive- // work never happens.- const { runId, snapshot: snap } = createUniqueSnapshot(vault, baseRunId);+ // validateRunId rejects a reason + stamp that would form a+ // filesystem-unsafe id (separators, traversal, Windows-reserved) - a+ // typed error before any snapshot or mutation is attempted.+ const baseRunId = validateRunId(`${reason}-${compactRunStamp(now)}`);- // Run the destructive operation. If it throws, we deliberately do NOT- // prune: the archive we just wrote is the recovery point, and letting- // the error propagate keeps it in place.- const result = op();+ // Snapshot behind a collision-safe unique id. A throw here (missing+ // tooling, unwritable archive, refused derived-store coverage) reaches+ // the caller with nothing left on disk.+ const snapshot = createUniqueSnapshot(vault, baseRunId, reason, now);- // Prune is best-effort: the destructive op has already committed, so a- // prune failure must NOT surface as an operation failure (that could- // trigger an unsafe retry of committed work). Retention is a cleanup- // concern, not a correctness one - warn and keep the successful result.try {pruneSnapshots(vault, loadSnapshotRetentionSafe(vault));} catch (err) {process.stderr.write(- `warning: snapshot prune after ${runId} failed (operation already committed): ${+ `warning: snapshot prune after ${snapshot.runId} failed (the recovery point is intact): ${(err as Error).message ?? String(err)}\n`,);}- return { snapshot: { runId, path: snap.path }, result };+ return snapshot;+}++/**+ * Run `op` behind a pre-operation snapshot. Returns the recovery point+ * alongside the operation's result. See the module header for the+ * abort / retain failure semantics.+ */+export function withDestructiveSnapshot<T>(+ vault: string,+ reason: BrainSnapshotReason,+ op: () => T,+ opts: WithDestructiveSnapshotOptions = {},+): WithDestructiveSnapshotResult<T> {+ // The one snapshot path, shared with the standalone entry point. A+ // throw here aborts before `op` runs - the destructive work never+ // happens.+ const snapshot = takeSnapshot(vault, reason, opts);++ // Run the destructive operation. If it throws, the error propagates and+ // the archive above stays exactly where it is: it is the recovery point+ // the caller now needs.+ const result = op();++ return { snapshot, result };}diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.tsindex 02441eaa..0bda0719 100644--- a/src/core/brain/snapshot.ts+++ b/src/core/brain/snapshot.ts@@ -5,9 +5,11 @@** - Before any state-changing operation in a `dream` run we write* `Brain/.snapshots/<run_id>.tar.zst` containing the entire- * `Brain/` tree **excluding** `Brain/.snapshots/` itself.+ * `Brain/` tree **excluding** {@link BRAIN_SNAPSHOT_EXCLUDED_ENTRIES}.* Including the snapshots dir would either explode the archive or- * racy-clobber an in-progress write.+ * racy-clobber an in-progress write; including the artifact cache+ * would hash TTL'd tool output into a drift gate that no rollback+ * would ever act on.** - Retention is enforced by `pruneSnapshots`: keep the* `snapshots.retention_count` newest files, delete the rest.@@ -30,8 +32,46 @@** No external dependencies. Everything is `node:child_process` +* `node:fs` so the cost is one subprocess per archive operation.+ *+ * ## Derived-store coverage, and why it is off by default+ *+ * The derived SQLite store (`<vault>/.open-second-brain/brain.sqlite`)+ * is a sibling of `Brain/`, and until now it was in no snapshot, no+ * manifest and no rollback - with nothing saying so, which made a+ * complete-looking pre-restore diff while the embeddings stayed at+ * whatever the live store happened to hold.+ *+ * What coverage buys is SPEND, not information. Feedback, activation and+ * tuning are replayable JSON folds inside `Brain/`; only the embeddings+ * and a tier baseline are database-only, so a lost store costs an+ * embedding bill and a reindex, never a fact. Against that: retention+ * keeps ten archives, and `.snapshots/` sits inside a vault replicated+ * peer-to-peer, so every retained copy is pushed to every device. Ten+ * multiples of a store on every peer is a real cost to pay for a+ * regenerable artifact.+ *+ * Hence the three-part answer. Coverage is opt-in. The ceiling REFUSES+ * rather than truncating, because half a database is not a recovery+ * point. And the live store size is recorded in every manifest whether+ * or not it was included, so an operator who has never enabled coverage+ * can still read what enabling it would cost.+ *+ * ## Every recovery point says why it exists+ *+ * `createSnapshot` requires a {@link BrainSnapshotReason}. It goes into+ * the manifest sidecar as an additive key at the existing schema version,+ * and into the Brain event log as one `snapshot` event carrying the run+ * id, the reason and the archive size โ the counterpart the log has been+ * missing since `rollback` shipped, which recorded the restore while the+ * point it restores to left no trace but a filename.+ *+ * The reason is also the run-id prefix at every call site, which is+ * exactly why the READ path must not parse it back out: recovering the+ * field from the filename would look right on almost every archive this+ * project writes and would invent provenance for one it did not.*/+import { Database } from "bun:sqlite";import { spawnSync } from "node:child_process";import {closeSync,@@ -40,23 +80,45 @@ import {mkdirSync,mkdtempSync,openSync,+ readFileSync,readSync,readdirSync,+ renameSync,rmSync,statSync,+ unlinkSync,writeFileSync,} from "node:fs";import { tmpdir } from "node:os";-import { basename, join } from "node:path";+import { basename, dirname, join } from "node:path";-import { buildManifest, manifestSidecarPath, writeManifestSidecar } from "./manifest.ts";+import { sha256Hex } from "../integrity/digest.ts";+import { resolveConfiguredIndexPath } from "../search/paths.ts";+import { runIntegrityCheck } from "../search/store/lifecycle.ts";+import { acquireWriterLockSync } from "../search/store/writer-lock.ts";+import { appendLogEvent } from "./log.ts";+import {+ buildManifest,+ manifestSidecarPath,+ readManifestSidecar,+ SNAPSHOT_STORE_EXCLUSION,+ writeManifestSidecar,+ type BrainManifestDerivedStore,+ type SnapshotStoreExclusionReason,+} from "./manifest.ts";import {BRAIN_ROOT_REL,+ BRAIN_SNAPSHOT_EXCLUDED_ENTRIES,brainDirs,brainDirsForWrite,+ SNAPSHOT_ARCHIVE_SUFFIX,snapshotPath,+ snapshotStorePath,validateRunId,} from "./paths.ts";+import { loadSnapshotDerivedStorePolicySafe, type BrainDerivedStorePolicy } from "./policy.ts";+import { isoSecond } from "./time.ts";+import { BRAIN_LOG_EVENT_KIND, type BrainSnapshotReason } from "./types.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";// ----- Errors ---------------------------------------------------------------@@ -87,11 +149,103 @@ export class BrainSnapshotError extends Error {}}+/**+ * Thrown when `.snapshots/` is present and cannot be enumerated.+ *+ * {@link listSnapshots} used to answer an unreadable directory with `[]`,+ * which put "this vault has taken no recovery points" and "nobody could+ * read the recovery points" on one wire - and every surface above it then+ * printed the first sentence over the second. It is not a+ * {@link BrainSnapshotError} because it belongs to no run id: the failure+ * is the directory, and naming an arbitrary archive in the message would+ * imply the read got as far as one.+ */+export class BrainSnapshotListingError extends Error {+ /** Absolute path of the directory that could not be read. */+ readonly path: string;+ constructor(path: string, cause: unknown) {+ super(+ `snapshots directory ${path} could not be read: ${+ cause instanceof Error ? cause.message : String(cause)+ }`,+ { cause },+ );+ this.name = "BrainSnapshotListingError";+ this.path = path;+ }+}++/**+ * Thrown when derived-store coverage was REQUESTED and could not be+ * honoured. Carries the reason from the same closed vocabulary a+ * manifest records, so the caller that reports the refusal and the+ * manifest that records an omission speak one language.+ *+ * It is a `BrainSnapshotError` because it is a snapshot failure in every+ * sense that matters to a caller: `createSnapshot` throws, nothing is+ * left on disk, and the destructive-snapshot gate consequently never+ * runs the operation it was protecting. That last property needs no+ * plumbing - it follows from refusing here rather than downgrading to a+ * partial snapshot that reports success.+ */+export class BrainSnapshotStoreError extends BrainSnapshotError {+ readonly reason: SnapshotStoreExclusionReason;+ constructor(message: string, runId: string, reason: SnapshotStoreExclusionReason) {+ super(`derived store not archived (${reason}): ${message}`, runId);+ this.name = "BrainSnapshotStoreError";+ this.reason = reason;+ }+}+// ----- Types ---------------------------------------------------------------export interface CreateSnapshotResult {/** Absolute path of the resulting archive. */readonly path: string;+ /** What this snapshot did about the derived store. */+ readonly derived_store: BrainManifestDerivedStore;+}++/**+ * The derived-store knobs, shared by the create and the restore path+ * because both resolve the same live store: one to archive it, one to+ * write it back.+ */+export interface SnapshotStoreOptions {+ /**+ * Derived-store coverage policy. Defaults to the vault's+ * `snapshots:` block, so every existing call site picks the operator's+ * setting up without threading it through.+ */+ readonly derivedStore?: BrainDerivedStorePolicy;+ /**+ * Absolute path of the live derived store. Defaults to+ * {@link liveDerivedStorePath}, which resolves it the way the search+ * layer does - honouring both the `OPEN_SECOND_BRAIN_SEARCH_DB`+ * environment variable and the `search_db_path` config key. A caller+ * that already holds a resolved search config passes its own answer.+ */+ readonly derivedStorePath?: string;+}++export interface CreateSnapshotOptions extends SnapshotStoreOptions {+ /**+ * Why this recovery point is being taken. REQUIRED, and required+ * precisely because it used to be optional in effect: the reasons+ * existed only as run-id prefixes, three of them inline literals, and+ * nothing read them back. A default here would restore that state -+ * every unnamed call site would silently claim whatever the default+ * said - so there is none, and the compiler asks each caller instead.+ */+ readonly reason: BrainSnapshotReason;+ /**+ * Clock for the `snapshot` audit line's timestamp. Defaults to wall+ * clock. A caller that already has an injected clock passes it, so a+ * pass whose output is byte-reproducible given `now` - the dream pass+ * is, and a test asserts it - does not become non-reproducible merely+ * by recording that it took a recovery point.+ */+ readonly now?: Date;}export interface SnapshotInfo {@@ -106,6 +260,28 @@ export interface SnapshotInfo {* similar). Rollback gracefully degrades on `null`.*/readonly manifest_path: string | null;+ /**+ * Absolute path of the sibling derived-store archive when one is on+ * disk, `null` otherwise. Probed rather than believed: the manifest+ * says what the snapshot INTENDED, this says what retention has to+ * delete.+ */+ readonly store_archive_path: string | null;+ /**+ * The sidecar's derived-store record, or `null` when there is no+ * sidecar or the sidecar predates the feature. `null` is UNKNOWN+ * coverage and must never be rendered as "excluded".+ */+ readonly derived_store: BrainManifestDerivedStore | null;+ /**+ * Why the recovery point was taken, read back off the sidecar, or+ * `null` when there is no sidecar, the sidecar is unreadable, or it+ * predates the reason. `null` is UNKNOWN and is NOT recovered from the+ * run id, even though every run id this project mints begins with the+ * reason: parsing it back would report provenance for an archive that+ * never recorded any.+ */+ readonly reason: BrainSnapshotReason | null;}export interface PruneSnapshotsResult {@@ -113,9 +289,43 @@ export interface PruneSnapshotsResult {readonly deleted: ReadonlyArray<string>;}+/**+ * What a restore did about the derived store. Separate fields rather than+ * a single verdict string, because "not replaced" splits into answers an+ * operator must be able to tell apart: the snapshot recorded that it did+ * not include the store, or the snapshot carries no record at all.+ */+export interface RestoreDerivedStoreResult {+ /** True when the archived store replaced the live one. */+ readonly replaced: boolean;+ /**+ * False when the snapshot carries no derived-store record: coverage is+ * unknown, and the live store was deliberately left untouched.+ */+ readonly coverage_known: boolean;+ /** Absolute path of the store that was replaced; null when none was. */+ readonly path: string | null;+ /** The manifest's named reason; null when included or unknown. */+ readonly exclusion_reason: SnapshotStoreExclusionReason | null;+ /**+ * Whether a sibling store archive is on disk for this snapshot, probed+ * rather than believed.+ *+ * Load-bearing exactly when {@link coverage_known} is false. The sidecar+ * write is non-fatal in `createSnapshot`, so coverage can run to+ * completion and leave no record of itself - and an archive sitting+ * beside the tar proves that happened. Without this field the reporting+ * surface had one sentence for two facts and chose the wrong one: it+ * called a lost RECORD a snapshot older than the FEATURE, while the+ * evidence to the contrary was in the same directory.+ */+ readonly store_archive_present: boolean;+}+export interface RestoreSnapshotResult {- /** Number of regular files restored under `Brain/` (excluding `.snapshots/`). */+ /** Number of regular files restored under `Brain/` (excluding the excluded entries). */readonly restored_files: number;+ readonly derived_store: RestoreDerivedStoreResult;}// ----- Tooling detection ---------------------------------------------------@@ -164,14 +374,16 @@ function detectTooling(): ToolAvailability {// ----- createSnapshot ------------------------------------------------------/**- * Archive `Brain/` (except `.snapshots/`) into- * `Brain/.snapshots/<run_id>.tar.zst`.+ * Archive `Brain/` (minus {@link BRAIN_SNAPSHOT_EXCLUDED_ENTRIES}) into+ * `Brain/.snapshots/<run_id>.tar.zst`, optionally beside a compressed+ * copy of the derived store.** Implementation:** 1. Detect available tools. If `tar` is absent we throw.- * 2. List the top-level entries under `Brain/`, drop `.snapshots/`.- * 3. `tar -c -C <vault> Brain/<entry> ...` streamed into `zstd -19`+ * 2. Cover the derived store FIRST, so a refusal leaves no tar behind.+ * 3. List the top-level entries under `Brain/`, drop the excluded ones.+ * 4. `tar -c -C <vault> Brain/<entry> ...` streamed into `zstd -19`* (or `gzip -9` fallback) โ output file.** Using `--exclude=Brain/.snapshots` is tempting, but tar's exclude@@ -179,7 +391,11 @@ function detectTooling(): ToolAvailability {* on filenames containing whitespace. Enumerating the kept entries* explicitly is byte-stable and easy to reason about.*/-export function createSnapshot(vault: string, runId: string): CreateSnapshotResult {+export function createSnapshot(+ vault: string,+ runId: string,+ opts: CreateSnapshotOptions,+): CreateSnapshotResult {validateRunId(runId);const dirs = brainDirsForWrite(vault);mkdirSync(dirs.snapshots, { recursive: true });@@ -193,47 +409,52 @@ export function createSnapshot(vault: string, runId: string): CreateSnapshotResu);}+ // The derived store goes first. It is the step that can REFUSE, and a+ // refusal must leave nothing behind - running it before the tar is+ // written is what makes "no partial archive" a property of the order+ // rather than of a cleanup path that could be forgotten.+ const derivedStore = coverDerivedStore(vault, runId, tools, opts);+// List top-level entries of Brain/ that we want to capture. Sort the// result so the resulting archive's contents are deterministic// across filesystems (readdirSync's order is FS-dependent).let topEntries: string[];try {- topEntries = readdirSync(dirs.brain).filter((e) => e !== ".snapshots");+ topEntries = readdirSync(dirs.brain).filter((e) => !isSnapshotExcludedEntry(e));} catch (err) {+ discardStoreArchive(derivedStore, vault, runId);throw new BrainSnapshotError(`failed to list Brain/: ${(err as Error).message ?? String(err)}`,runId,);}topEntries.sort();- if (topEntries.length === 0) {- // No content to archive. Tar would still produce an empty archive,- // which is fine โ `restoreSnapshot` on an empty archive is a no-op- // that doesn't delete anything (because the exclude-`.snapshots`- // rule keeps the dir intact).- }// Build `tar -c -C <vault> Brain/<entry> Brain/<entry>...` so paths// inside the archive start at `Brain/` โ matching the rollback// contract that the archive is "the Brain/ tree".const tarArgs = ["-c", "-C", vault, "--", ...topEntries.map((e) => `${BRAIN_ROOT_REL}/${e}`)];- if (tools.zstd) {- runArchivePipeline(["tar", tarArgs], ["zstd", ["-19", "-q", "-o", outPath, "-"]], runId);- } else if (tools.gzip) {- // Same on-disk extension keeps the snapshot listing logic- // homogeneous. The contents are gzip-compressed regardless; the- // restore probes both compressors so this is safe.- runArchivePipeline(["tar", tarArgs], ["gzip", ["-9", "-c"]], runId, outPath);- } else {- throw new BrainSnapshotToolingMissingError(- "zstd or gzip",- "install zstd (preferred) or gzip; we use the first available.",+ try {+ compressInto(+ { kind: "buffer", bytes: runArchiveProducer("tar", tarArgs, runId) },+ outPath,+ tools,+ runId,);- }-- if (!existsSync(outPath)) {- throw new BrainSnapshotError(`archive write reported success but ${outPath} is absent`, runId);+ if (!existsSync(outPath)) {+ throw new BrainSnapshotError(+ `archive write reported success but ${outPath} is absent`,+ runId,+ );+ }+ } catch (err) {+ // The store archive we just wrote belongs to a snapshot that does+ // not exist. Leaving it would make the run id look taken to the+ // collision resolver and would survive retention, which only prunes+ // archives it can list.+ discardStoreArchive(derivedStore, vault, runId);+ throw err;}// Sidecar manifest. Failure is non-fatal: the archive is the@@ -244,7 +465,11 @@ export function createSnapshot(vault: string, runId: string): CreateSnapshotResu// would block dream from making any progress on a read-only// `.snapshots/` directory.try {- writeManifestSidecar(vault, runId, buildManifest(dirs.brain));+ writeManifestSidecar(+ vault,+ runId,+ buildManifest(dirs.brain, { derivedStore, snapshotReason: opts.reason }),+ );} catch (err) {process.stderr.write(`warning: manifest sidecar write failed for snapshot ` +@@ -252,104 +477,460 @@ export function createSnapshot(vault: string, runId: string): CreateSnapshotResu`rollback drift detection will be skipped for this snapshot.\n`,);}- return { path: outPath };++ logSnapshotEvent(vault, runId, opts.reason, outPath, opts.now ?? new Date());+ return { path: outPath, derived_store: derivedStore };}/**- * Run `producer | consumer` synchronously. On Linux `spawnSync`- * supports a `stdio` pipe between two processes via the `input` field- * โ but we want a streaming pipe, not a full-buffer round-trip, since- * the Brain tree could in principle exceed available memory. Use- * `sh -c '<cmd1> | <cmd2>'` so the shell wires the pipe directly.- *- * Argument quoting: we deliberately do NOT shell-escape paths because- * `tar -C <vault>` already roots everything relative to the vault,- * and the only user-supplied bytes in `tarArgs` are the run id (which- * `validateRunId` constrains to `[A-Za-z0-9._-]`) and the top-level- * Brain/ entries (`inbox`, `preferences`, โฆ) which are themselves- * filesystem names produced by our own writers.+ * Record the recovery point in the Brain event log โ the counterpart the+ * log has been missing since `rollback` was added, which recorded the+ * restore while the point it restores to left no trace but a filename.*- * For full safety against any future caller pattern, callers can- * audit `tarArgs` to confirm no unconstrained user input lands here.+ * Best-effort, in the same shape the `rollback` verb already uses for its+ * own event, and for a stronger reason here: this function runs AFTER the+ * archive is on disk, and `createSnapshot` is called by the+ * destructive-snapshot gate before the mutation it protects. A throw would+ * therefore abort an operation whose recovery point already exists,+ * turning a lost audit line into a refused mutation. The archive is the+ * load-bearing artifact; the event is how it is found later.*/-function runArchivePipeline(- producer: readonly [string, ReadonlyArray<string>],- consumer: readonly [string, ReadonlyArray<string>],+function logSnapshotEvent(+ vault: string,runId: string,- outPath?: string,+ reason: BrainSnapshotReason,+ archivePath: string,+ now: Date,): void {- // We avoid shell pipe entirely: spawn the producer, capture its- // stdout into a Buffer (acceptable: Brain trees are small โ- // typical compressed output is well under 1 MB per the design- // doc), then feed it to the consumer's stdin synchronously.- //- // The previous approach used `sh -c "tar ... | zstd ..."` and broke- // on quoting of paths with whitespace. Buffering through Node is- // simpler and verifiably correct.- const [prodCmd, prodArgs] = producer;- const tarResult = spawnSync(prodCmd, [...prodArgs], {- maxBuffer: 256 * 1024 * 1024, // 256 MB hard ceiling matches the design's "small" guarantee.- stdio: ["ignore", "pipe", "pipe"],- });- if (tarResult.error) {- throw new BrainSnapshotError(`${prodCmd} failed to start: ${tarResult.error.message}`, runId);+ try {+ // Measured off the file rather than carried from the compressor, so+ // the number describes the archive an operator can `ls`. An+ // unmeasurable archive raises into the handler below and no event is+ // written: a `0` here would read as an empty archive, which is a real+ // and very different state.+ const sizeBytes = statSync(archivePath).size;+ appendLogEvent(vault, {+ timestamp: isoSecond(now),+ eventType: BRAIN_LOG_EVENT_KIND.snapshot,+ body: { run_id: runId, reason, size_bytes: String(sizeBytes) },+ });+ } catch (err) {+ process.stderr.write(+ `warning: append snapshot log event failed for '${runId}': ` ++ `${(err as Error).message ?? String(err)}; the archive itself is intact.\n`,+ );+ }+}++/** True for a top-level `Brain/` entry the snapshot family never touches. */+function isSnapshotExcludedEntry(name: string): boolean {+ return BRAIN_SNAPSHOT_EXCLUDED_ENTRIES.includes(name);+}++// ----- Derived-store coverage ----------------------------------------------++/**+ * Byte length of `path`, or `null` when it is not there to measure.+ * Never zero-as-absent: a freshly created SQLite file is legitimately+ * small, and an operator reading "0" needs it to mean zero bytes.+ */+function fileSizeOrNull(path: string): number | null {+ try {+ const st = statSync(path);+ return st.isFile() ? st.size : null;+ } catch {+ return null;}- if (tarResult.status !== 0) {- const stderr = (tarResult.stderr ?? Buffer.from("")).toString("utf8").trim();+}++/**+ * The live derived store, resolved the way the search layer resolves it.+ *+ * The resolver honours the `search_db_path` override; the bare path+ * helper answers only the default location. That distinction is the whole+ * point: on a vault carrying the override, an archive built from the+ * default would describe a file the search layer never reads, and if a+ * stale database happened to sit there it would have been archived and+ * reported as a success. It is imported from the resolver leaf rather+ * than the search barrel because the barrel is reachable from this module+ * and importing it back closes a cycle the architecture ratchet refuses.+ */+function liveDerivedStorePath(vault: string): string {+ return resolveConfiguredIndexPath(vault);+}++/**+ * Decide and, when asked, perform derived-store coverage for one+ * snapshot. Returns the record the manifest will carry; THROWS+ * {@link BrainSnapshotStoreError} when coverage was requested and any+ * step could not be completed.+ *+ * The refusal is the point. A snapshot that quietly dropped the store it+ * was asked to protect would report success, and the destructive+ * operation it guards would then run against a recovery point that is+ * not the one the operator configured.+ */+function coverDerivedStore(+ vault: string,+ runId: string,+ tools: ToolAvailability,+ opts: SnapshotStoreOptions,+): BrainManifestDerivedStore {+ const policy = opts.derivedStore ?? loadSnapshotDerivedStorePolicySafe(vault);+ // Resolved through the search layer's resolver, never re-derived here.+ const sourcePath = opts.derivedStorePath ?? liveDerivedStorePath(vault);+ const liveSize = fileSizeOrNull(sourcePath);++ const excluded = (reason: SnapshotStoreExclusionReason): BrainManifestDerivedStore =>+ Object.freeze({+ included: false,+ source_path: sourcePath,+ archive_name: null,+ archive_sha256: null,+ archive_size: null,+ live_size: liveSize,+ exclusion_reason: reason,+ });++ if (!policy.include) return excluded(SNAPSHOT_STORE_EXCLUSION.not_requested);++ if (liveSize === null) {+ throw new BrainSnapshotStoreError(+ `no store file at ${sourcePath}`,+ runId,+ SNAPSHOT_STORE_EXCLUSION.absent,+ );+ }++ const archivePath = snapshotStorePath(vault, runId);+ if (existsSync(archivePath)) {throw new BrainSnapshotError(- `${prodCmd} exited with status ${tarResult.status}: ${stderr}`,+ `refusing to overwrite an existing archive: ${archivePath}`,runId,);}- const tarPayload = tarResult.stdout;- if (!tarPayload) {- throw new BrainSnapshotError(`${prodCmd} produced no stdout`, runId);++ // The writer lock on the LIVE store path, held across the integrity+ // scan and the copy, so an index run cannot mutate the file underneath+ // the snapshot. It is the same lock every other writer serialises on,+ // taken synchronously because this whole module is synchronous.+ const release = acquireWriterLockSync(sourcePath);+ try {+ assertStoreIsSound(sourcePath, runId);++ // Measured against the LIVE size, which is what the operator's+ // ceiling is expressed in and what they can check with `ls`. The+ // compressed archive is smaller, but refusing on a number nobody can+ // predict before the work is done would be a worse contract.+ if (liveSize > policy.maxBytes) {+ throw new BrainSnapshotStoreError(+ `store is ${liveSize} bytes, over the ${policy.maxBytes}-byte ceiling ` ++ `(snapshots.derived_store_max_bytes)`,+ runId,+ SNAPSHOT_STORE_EXCLUSION.over_size_ceiling,+ );+ }++ writeStoreArchive(sourcePath, archivePath, tools, runId);+ } finally {+ release();}- const [consCmd, consArgs] = consumer;- // `zstd -o <out>` opens the file itself; gzip writes to stdout and- // we pipe to file via `outPath`.- if (outPath === undefined) {- const r = spawnSync(consCmd, [...consArgs], {- input: tarPayload,- stdio: ["pipe", "inherit", "pipe"],- });- if (r.error) {- throw new BrainSnapshotError(`${consCmd} failed to start: ${r.error.message}`, runId);+ const archiveSize = fileSizeOrNull(archivePath);+ if (archiveSize === null) {+ throw new BrainSnapshotError(+ `store archive write reported success but ${archivePath} is absent`,+ runId,+ );+ }+ return Object.freeze({+ included: true,+ source_path: sourcePath,+ archive_name: basename(archivePath),+ archive_sha256: sha256Hex(readFileSync(archivePath)),+ archive_size: archiveSize,+ live_size: liveSize,+ exclusion_reason: null,+ });+}++/**+ * Refuse a condemned store rather than archiving it over a good+ * snapshot.+ *+ * This runs the integrity scanner the previous release already shipped -+ * `PRAGMA quick_check`, classified by {@link runIntegrityCheck} - rather+ * than inventing a second gate with its own opinion. A file that is not+ * a SQLite database at all fails here too: `new Database` is lazy, so+ * the first statement raises and the scanner classifies the raise as a+ * fault, which is the honest answer.+ */+function assertStoreIsSound(sourcePath: string, runId: string): void {+ let db: Database;+ try {+ db = new Database(sourcePath, { readonly: true });+ } catch (err) {+ throw new BrainSnapshotStoreError(+ `cannot open ${sourcePath}: ${(err as Error).message ?? String(err)}`,+ runId,+ SNAPSHOT_STORE_EXCLUSION.integrity_fault,+ );+ }+ try {+ const verdict = runIntegrityCheck(db);+ if (!verdict.ok) {+ throw new BrainSnapshotStoreError(+ `${sourcePath} failed a structural integrity check: ${verdict.fault}`,+ runId,+ SNAPSHOT_STORE_EXCLUSION.integrity_fault,+ );}- if (r.status !== 0) {- const stderr = (r.stderr ?? Buffer.from("")).toString("utf8").trim();- throw new BrainSnapshotError(`${consCmd} exited with status ${r.status}: ${stderr}`, runId);+ } finally {+ db.close();+ }+}++/**+ * `VACUUM INTO` a private temp file, then compress that into+ * `archivePath`.+ *+ * `VACUUM INTO` rather than a file copy because the store runs in WAL+ * mode: the main file alone is not a consistent database, and the+ * runtime exposes no online-backup API. `VACUUM INTO` is read-only with+ * respect to the source, produces a single self-contained and compacted+ * file, and is the native answer to exactly this question.+ *+ * The temp file lives in the OS temp directory rather than beside the+ * store, so a crash between the vacuum and the compression leaves+ * nothing in the vault for the next reader to find.+ */+function writeStoreArchive(+ sourcePath: string,+ archivePath: string,+ tools: ToolAvailability,+ runId: string,+): void {+ const tmp = mkdtempSync(join(tmpdir(), `o2b-store-vacuum-${runId}-`));+ const vacuumed = join(tmp, DERIVED_STORE_VACUUM_FILE);+ // Whether the destination was ALREADY taken when this call began. It+ // decides whether the cleanup below may touch it: an archive a racing+ // process wrote is the very thing the overwrite refusal protects, and+ // removing it in the name of cleaning up after that refusal would+ // reintroduce the data-loss path by the back door.+ const preexisting = existsSync(archivePath);+ try {+ const db = new Database(sourcePath, { readonly: true });+ try {+ db.query("VACUUM INTO ?").run(vacuumed);+ } finally {+ db.close();}- } else {- // gzip pipeline โ capture stdout, write to file.- const r = spawnSync(consCmd, [...consArgs], {- input: tarPayload,- stdio: ["pipe", "pipe", "pipe"],- maxBuffer: 256 * 1024 * 1024,- });- if (r.error) {- throw new BrainSnapshotError(`${consCmd} failed to start: ${r.error.message}`, runId);+ compressInto({ kind: "file", path: vacuumed }, archivePath, tools, runId);+ } catch (err) {+ // A failed compression may have left a partial archive of OUR making;+ // the snapshot is about to be refused, so nothing may survive that a+ // later read could mistake for a recovery point.+ if (!preexisting) {+ try {+ unlinkSync(archivePath);+ } catch {+ // Nothing was written, or it is already gone. Either is fine.+ }}- if (r.status !== 0) {- const stderr = (r.stderr ?? Buffer.from("")).toString("utf8").trim();- throw new BrainSnapshotError(`${consCmd} exited with status ${r.status}: ${stderr}`, runId);+ if (err instanceof BrainSnapshotError) throw err;+ throw new BrainSnapshotError(+ `failed to archive the derived store: ${(err as Error).message ?? String(err)}`,+ runId,+ );+ } finally {+ try {+ rmSync(tmp, { recursive: true, force: true });+ } catch {+ // tmp cleanup is best-effort; the OS will reclaim it eventually.}- // Write the compressed payload to the snapshot file atomically.- // Use writeFileSync since the file is binary and lives inside- // `.snapshots/` (no Markdown parser cares about torn writes here;- // worst case is a corrupt archive that fails on restore โ same- // outcome as any other interrupted snapshot).- writeFileSync(outPath, r.stdout ?? Buffer.from(""));}}+/** Filename of the vacuumed copy inside its private temp directory. */+const DERIVED_STORE_VACUUM_FILE = "store.sqlite";++/** Remove a store archive whose snapshot is being abandoned. */+function discardStoreArchive(+ record: BrainManifestDerivedStore,+ vault: string,+ runId: string,+): void {+ if (!record.included) return;+ try {+ rmSync(snapshotStorePath(vault, runId), { force: true });+ } catch (err) {+ process.stderr.write(+ `warning: could not remove the orphaned derived-store archive for ` ++ `'${runId}': ${(err as Error).message ?? String(err)}\n`,+ );+ }+}++/**+ * Compress the producer's stdout into `outPath`, choosing zstd when the+ * host has it and gzip otherwise.+ *+ * ## Both compressors refuse an existing target, and that is load-bearing+ *+ * `zstd -o` has always refused to overwrite. The gzip fallback wrote+ * through `writeFileSync`, which does not - so on a host without zstd+ * two concurrent destructive operations that landed on the same run id+ * would silently destroy each other's recovery point. That was not a+ * cosmetic asymmetry: `createUniqueSnapshot` in `snapshot-gate.ts`+ * resolves a run-id collision by RETRYING when the create fails and the+ * archive now exists, so on a gzip-only host the collision path had no+ * failure to retry on and the whole mechanism was inert.+ *+ * The refusal is therefore made explicit here, before either compressor+ * runs, so both paths fail with the same typed error and the same+ * message. The gzip write additionally opens with `wx` (exclusive+ * create), which closes the window between the check and the write that+ * a probe alone would leave open.+ *+ * The on-disk extension stays `.tar.zst` under gzip. The restore probes+ * the magic bytes rather than the name, and one suffix keeps listing and+ * retention a single comparison.+ */+function compressInto(+ payload: CompressionSource,+ outPath: string,+ tools: ToolAvailability,+ runId: string,+): void {+ if (existsSync(outPath)) {+ throw new BrainSnapshotError(`refusing to overwrite an existing archive: ${outPath}`, runId);+ }+ if (tools.zstd) {+ // `zstd -o` opens the destination itself and refuses an existing one.+ const args =+ payload.kind === "file"+ ? ["-19", "-q", "-o", outPath, payload.path]+ : ["-19", "-q", "-o", outPath, "-"];+ runCompressor("zstd", args, payload, runId, null);+ return;+ }+ if (tools.gzip) {+ // gzip only writes to stdout, so the destination is ours to open.+ const args = payload.kind === "file" ? ["-9", "-c", payload.path] : ["-9", "-c"];+ runCompressor("gzip", args, payload, runId, outPath);+ return;+ }+ throw new BrainSnapshotToolingMissingError(+ "zstd or gzip",+ "install zstd (preferred) or gzip; we use the first available.",+ );+}++/**+ * What a compressor reads. A `buffer` is the tar stream we already hold;+ * a `file` is the vacuumed store copy, handed over by path so a+ * multi-hundred-megabyte database never round-trips through memory.+ */+type CompressionSource =+ | { readonly kind: "buffer"; readonly bytes: Buffer }+ | { readonly kind: "file"; readonly path: string };++/** Hard ceiling on any single captured subprocess stream. */+const SUBPROCESS_MAX_BUFFER_BYTES = 256 * 1024 * 1024;++/**+ * Run one compressor over `payload`. When `outPath` is non-null the+ * compressor writes to stdout and we own the destination file; when it+ * is null the compressor was given the destination itself.+ */+function runCompressor(+ cmd: string,+ args: ReadonlyArray<string>,+ payload: CompressionSource,+ runId: string,+ outPath: string | null,+): void {+ const r = spawnSync(cmd, [...args], {+ ...(payload.kind === "buffer" ? { input: payload.bytes } : {}),+ stdio: [+ payload.kind === "buffer" ? "pipe" : "ignore",+ outPath === null ? "inherit" : "pipe",+ "pipe",+ ],+ maxBuffer: SUBPROCESS_MAX_BUFFER_BYTES,+ });+ if (r.error) {+ throw new BrainSnapshotError(`${cmd} failed to start: ${r.error.message}`, runId);+ }+ if (r.status !== 0) {+ const stderr = (r.stderr ?? Buffer.from("")).toString("utf8").trim();+ throw new BrainSnapshotError(`${cmd} exited with status ${r.status}: ${stderr}`, runId);+ }+ if (outPath === null) return;+ // Exclusive create. `wx` is what makes the gzip path refuse an+ // existing archive the way `zstd -o` always has; see+ // {@link compressInto} for why that refusal is load-bearing rather+ // than tidy. A torn write remains possible (worst case: a corrupt+ // archive that fails on restore, the same outcome as any other+ // interrupted snapshot) - what is no longer possible is silently+ // replacing someone else's recovery point.+ try {+ writeFileSync(outPath, r.stdout ?? Buffer.from(""), { flag: "wx" });+ } catch (err) {+ throw new BrainSnapshotError(+ `failed to write ${outPath}: ${(err as Error).message ?? String(err)}`,+ runId,+ );+ }+}++/**+ * Run the archive producer and capture its stdout.+ *+ * We avoid a shell pipe entirely: spawn `tar`, capture its stdout into a+ * Buffer (acceptable: Brain trees are Markdown and stay small), then+ * feed the compressor synchronously. The previous approach used+ * `sh -c "tar ... | zstd ..."` and broke on quoting of paths with+ * whitespace; buffering through Node is simpler and verifiably correct.+ *+ * Argument quoting: we deliberately do NOT shell-escape paths, because+ * `tar -C <vault>` already roots everything relative to the vault, and+ * the only user-supplied bytes in `tarArgs` are the run id (which+ * `validateRunId` constrains to `[A-Za-z0-9._-]`) and the top-level+ * `Brain/` entries (`inbox`, `preferences`, โฆ) which are themselves+ * filesystem names produced by our own writers.+ */+function runArchiveProducer(cmd: string, args: ReadonlyArray<string>, runId: string): Buffer {+ const r = spawnSync(cmd, [...args], {+ maxBuffer: SUBPROCESS_MAX_BUFFER_BYTES,+ stdio: ["ignore", "pipe", "pipe"],+ });+ if (r.error) {+ throw new BrainSnapshotError(`${cmd} failed to start: ${r.error.message}`, runId);+ }+ if (r.status !== 0) {+ const stderr = (r.stderr ?? Buffer.from("")).toString("utf8").trim();+ throw new BrainSnapshotError(`${cmd} exited with status ${r.status}: ${stderr}`, runId);+ }+ if (!r.stdout) {+ throw new BrainSnapshotError(`${cmd} produced no stdout`, runId);+ }+ return r.stdout;+}+// ----- listSnapshots / pruneSnapshots --------------------------------------/*** Enumerate `.snapshots/*.tar.zst` in newest-first order (by mtime).* Files outside the canonical naming pattern are silently skipped so* a stray text file in the dir doesn't poison the listing.+ *+ * A directory that is not there is an empty history and returns `[]`: no+ * snapshot has ever been taken, which is a real answer. A directory that+ * IS there and cannot be enumerated throws+ * {@link BrainSnapshotListingError} instead, because the two are+ * different facts and `[]` for both is what let the listing surfaces+ * print "no snapshots available" over a read that never happened.*/export function listSnapshots(vault: string): SnapshotInfo[] {const dirs = brainDirs(vault);@@ -357,13 +938,13 @@ export function listSnapshots(vault: string): SnapshotInfo[] {let entries: string[];try {entries = readdirSync(dirs.snapshots);- } catch {- return [];+ } catch (err) {+ throw new BrainSnapshotListingError(dirs.snapshots, err);}const infos: SnapshotInfo[] = [];for (const name of entries) {- if (!name.endsWith(".tar.zst")) continue;- const runId = name.slice(0, -".tar.zst".length);+ if (!name.endsWith(SNAPSHOT_ARCHIVE_SUFFIX)) continue;+ const runId = name.slice(0, -SNAPSHOT_ARCHIVE_SUFFIX.length);// The `.snapshots/` dir is ours, so a malformed run_id here would// indicate manual tampering โ we keep the listing tolerant and// skip rather than throw.@@ -380,12 +961,26 @@ export function listSnapshots(vault: string): SnapshotInfo[] {continue;}const sidecar = manifestSidecarPath(vault, runId);+ const storeArchive = snapshotStorePath(vault, runId);+ // One read for both sidecar-derived columns: two calls would parse+ // the same file twice and could disagree if a peer rewrote it between+ // them.+ const manifest = readManifestSidecar(vault, runId);infos.push({run_id: runId,path: full,created_at: new Date(st.mtimeMs).toISOString(),size_bytes: st.size,manifest_path: existsSync(sidecar) ? sidecar : null,+ store_archive_path: existsSync(storeArchive) ? storeArchive : null,+ // `?? null` collapses "no sidecar", "unreadable sidecar" and+ // "sidecar predating the feature" into one answer, which is+ // correct: all three mean the coverage is UNKNOWN, and none of+ // them is evidence that the store was excluded.+ derived_store: manifest?.derived_store ?? null,+ // Same three states, same single answer, and the same refusal to+ // improve on it: the run id is not evidence of a reason.+ reason: manifest?.snapshot_reason ?? null,});}// Sort newest-first by mtime. We deliberately avoid lexicographic@@ -426,13 +1021,15 @@ export function pruneSnapshots(vault: string, retentionCount: number): PruneSnap// Best-effort: a snapshot we can't delete (permission error)// stays put. The next dream run will try again.}- // Remove the matching sidecar manifest if present. Independent- // try/catch so a missing sidecar (snapshot whose sidecar write- // failed at creation time) must not abort the prune of- // subsequent victims.- if (v.manifest_path !== null) {+ // Remove the matching sidecar manifest and derived-store archive if+ // present. Independent try/catch per companion so a missing one (a+ // snapshot whose sidecar write failed at creation time, or one taken+ // without store coverage) must not abort the prune of subsequent+ // victims.+ for (const companion of [v.manifest_path, v.store_archive_path]) {+ if (companion === null) continue;try {- rmSync(v.manifest_path, { force: true });+ rmSync(companion, { force: true });} catch {// Same rationale as above โ best-effort.}@@ -443,22 +1040,6 @@ export function pruneSnapshots(vault: string, retentionCount: number): PruneSnap// ----- restoreSnapshot ------------------------------------------------------/**- * Restore the archive identified by `runId` over `Brain/`. The current- * `.snapshots/` directory is preserved verbatim so older rollbacks- * still have a path back.- *- * Steps:- *- * 1. Locate the archive.- * 2. Extract into a sibling temp dir.- * 3. Verify the extracted tree contains a `Brain/` root.- * 4. For each top-level entry under the extracted `Brain/` (which- * excludes `.snapshots/` by virtue of how the archive was- * written), remove the corresponding live entry and copy the- * extracted one into place.- * 5. Clean up the temp dir.- *//*** Result of {@link extractSnapshotToTemp}. `brainRoot` is the* extracted `Brain/` directory (sibling to the live tree, inside a@@ -572,27 +1153,63 @@ export function extractSnapshotToTemp(vault: string, runId: string): ExtractSnap}}+/**+ * Restore the archive identified by `runId` over `Brain/`, and the+ * derived store alongside it when the snapshot recorded one. The current+ * `.snapshots/` directory is preserved verbatim so older rollbacks still+ * have a path back.+ *+ * Steps:+ *+ * 1. Locate the archive.+ * 2. Extract into a sibling temp dir.+ * 3. Verify the extracted tree contains a `Brain/` root.+ * 4. For each top-level entry under the extracted `Brain/` (which+ * excludes {@link BRAIN_SNAPSHOT_EXCLUDED_ENTRIES} by virtue of how+ * the archive was written), remove the corresponding live entry and+ * copy the extracted one into place.+ * 5. Swap the derived store, when and only when the manifest says the+ * snapshot included one.+ * 6. Clean up the temp dir.+ */export function restoreSnapshot(vault: string,runId: string,- // eslint-disable-next-line @typescript-eslint/no-unused-vars -- reserved for future log emission- _opts: { now?: Date } = {},+ opts: SnapshotStoreOptions = {},): RestoreSnapshotResult {const dirs = brainDirsForWrite(vault);++ // Everything a restore needs is checked before anything is replaced.+ //+ // The store step used to run after the Markdown tree had already been+ // deleted and re-copied, so a missing store archive threw over work+ // that had in fact completed: the caller reported a failed rollback,+ // logged nothing, and the vault was rolled back anyway. Reachable+ // whenever the sidecar survives without its companion archive - partial+ // replication, a sync rule excluding large binaries, or an operator+ // reclaiming disk. The create path already refuses before it writes;+ // this is the same ordering on the way back.+ assertDerivedStoreRestorable(vault, runId);+const ext = extractSnapshotToTemp(vault, runId);try {- // Replace every top-level entry under Brain/, EXCEPT `.snapshots/`.- // The exclusion is the load-bearing safety guarantee: rolling back- // an older state must not erase newer snapshots, otherwise the- // operator is one click away from losing their forward path.- const replacementEntries = readdirSync(ext.brainRoot).filter((e) => e !== ".snapshots");-- // The correct semantics are "live tree == snapshot tree minus- // `.snapshots/`". Delete every live top-level entry except- // `.snapshots/`, then copy in from the extracted Brain/. This- // makes restore deterministic.+ // Replace every top-level entry under Brain/, except the entries the+ // snapshot family never touches. The `.snapshots/` exclusion is the+ // load-bearing safety guarantee: rolling back an older state must+ // not erase newer snapshots, otherwise the operator is one click+ // away from losing their forward path. `.artifacts/` is excluded for+ // the opposite reason - it is not in the archive at all, so deleting+ // the live copy would restore nothing over it.+ const replacementEntries = readdirSync(ext.brainRoot).filter(+ (e) => !isSnapshotExcludedEntry(e),+ );++ // The correct semantics are "live tree == snapshot tree minus the+ // excluded entries". Delete every live top-level entry except those,+ // then copy in from the extracted Brain/. This makes restore+ // deterministic.const liveEntries = existsSync(dirs.brain)- ? readdirSync(dirs.brain).filter((e) => e !== ".snapshots")+ ? readdirSync(dirs.brain).filter((e) => !isSnapshotExcludedEntry(e)): [];for (const name of liveEntries) {const target = join(dirs.brain, name);@@ -615,12 +1232,209 @@ export function restoreSnapshot(cpSync(from, to, { recursive: true });restoredFiles += countFiles(to);}- return { restored_files: restoredFiles };+ return {+ restored_files: restoredFiles,+ derived_store: restoreDerivedStore(vault, runId, opts),+ };} finally {ext.cleanup();}}+/**+ * Put the archived derived store back, but ONLY when the manifest says+ * this snapshot carried one.+ *+ * Three answers, and the caller reports whichever it gets rather than+ * leaving any of them implicit:+ *+ * - the manifest records inclusion: decompress and swap;+ * - the manifest records an exclusion: nothing is touched, and the+ * named reason travels back;+ * - there is no record at all: coverage is UNKNOWN, and whether a+ * sibling archive is on disk travels back with it. A restore must not+ * guess in either direction here - replacing a live store on a hunch+ * destroys embeddings the archive never held, and reporting+ * "excluded" would claim a check that never ran. The archive probe is+ * what lets the caller say WHY the record is missing instead of+ * asserting the snapshot is older than the feature.+ */+/**+ * Refuse a restore that cannot be completed, before it starts.+ *+ * Two conditions, both of which used to surface only after the Markdown+ * tree had been replaced. A derived-store record this build cannot read+ * means coverage is indeterminate, so neither replacing the live store+ * nor leaving it can be justified; a record that names an archive which+ * is not on disk means the restore is already incomplete. Either way the+ * honest answer is to touch nothing and say why.+ */+function assertDerivedStoreRestorable(vault: string, runId: string): void {+ const manifest = readManifestSidecar(vault, runId);+ if (manifest === null) return;+ if (manifest.derived_store_unreadable === true) {+ throw new BrainSnapshotError(+ "the manifest carries a derived-store record this build cannot read, so whether the " ++ "snapshot covered the store is indeterminate; refusing to restore rather than " ++ "guessing at the live store",+ runId,+ );+ }+ const record = manifest.derived_store ?? null;+ if (record === null || !record.included) return;+ const archive = snapshotStorePath(vault, runId);+ if (!existsSync(archive)) {+ throw new BrainSnapshotError(+ `manifest records a derived-store archive but ${archive} is absent; refusing before the ` ++ "Brain tree is touched, so nothing is half-restored",+ runId,+ );+ }+}++function restoreDerivedStore(+ vault: string,+ runId: string,+ opts: SnapshotStoreOptions,+): RestoreDerivedStoreResult {+ const record = readManifestSidecar(vault, runId)?.derived_store ?? null;+ // Probed once, for every branch, and deliberately independent of the+ // record: it is the only evidence that separates a snapshot with no+ // record from a snapshot whose record was lost after the archive landed.+ const storeArchivePresent = existsSync(snapshotStorePath(vault, runId));+ if (record === null) {+ return Object.freeze({+ replaced: false,+ coverage_known: false,+ path: null,+ exclusion_reason: null,+ store_archive_present: storeArchivePresent,+ });+ }+ if (!record.included) {+ return Object.freeze({+ replaced: false,+ coverage_known: true,+ path: null,+ exclusion_reason: record.exclusion_reason,+ store_archive_present: storeArchivePresent,+ });+ }++ const archive = snapshotStorePath(vault, runId);+ if (!existsSync(archive)) {+ // Unreachable through `restoreSnapshot`, which refuses this in its+ // pre-flight. Kept because this function is also the one a future+ // caller would reach directly, and a store swap must never begin+ // against an archive that is not there.+ throw new BrainSnapshotError(+ `manifest records a derived-store archive but ${archive} is absent`,+ runId,+ );+ }+ // The manifest's `source_path` is where the store WAS; the live target+ // is where it is now. They differ when the operator moved the vault or+ // set a `search_db_path` override after the snapshot, and the live+ // answer is the one a restore must write to.+ const target = opts.derivedStorePath ?? liveDerivedStorePath(vault);+ swapDerivedStore(archive, target, runId);+ return Object.freeze({+ replaced: true,+ coverage_known: true,+ path: target,+ exclusion_reason: null,+ store_archive_present: true,+ });+}++/**+ * Decompress `archive` beside the live store and rename it into place+ * under the writer lock.+ *+ * The same swap discipline `reindexVault` already uses: build the+ * replacement at a sibling path on the same filesystem, keep the+ * outgoing file as `.bak`, then a single atomic rename. Holding the+ * writer lock across it is what stops an index run from writing into the+ * file being replaced.+ *+ * The WAL siblings of the OUTGOING file are removed after the swap. The+ * decompressed archive came from `VACUUM INTO` and is a complete+ * database on its own; an orphan `-wal` from the file it replaced would+ * make the next open fail with SQLITE_IOERR_SHORT_READ, which is the+ * exact failure `consolidateWal` exists to prevent on the reindex path.+ */+function swapDerivedStore(archive: string, target: string, runId: string): void {+ mkdirSync(dirname(target), { recursive: true });+ const incoming = `${target}${RESTORE_STAGING_SUFFIX}`;+ const outgoing = `${target}${RESTORE_BACKUP_SUFFIX}`;+ const release = acquireWriterLockSync(target);+ try {+ rmSync(incoming, { force: true });+ decompressArchiveTo(archive, incoming, runId);+ rmSync(outgoing, { force: true });+ if (existsSync(target)) renameSync(target, outgoing);+ renameSync(incoming, target);+ for (const sidecar of WAL_SIBLING_SUFFIXES) {+ rmSync(`${target}${sidecar}`, { force: true });+ }+ } catch (err) {+ rmSync(incoming, { force: true });+ if (err instanceof BrainSnapshotError || err instanceof BrainSnapshotToolingMissingError) {+ throw err;+ }+ throw new BrainSnapshotError(+ `failed to restore the derived store to ${target}: ${(err as Error).message ?? String(err)}`,+ runId,+ );+ } finally {+ release();+ }+}++/** Staging name of the store being restored, beside its destination. */+const RESTORE_STAGING_SUFFIX = ".restore";+/**+ * The outgoing store, kept under the SAME `.bak` name the reindex swap+ * uses - so the crash-recovery preamble every `Store.open` runs restores+ * it if a rollback dies between the two renames.+ */+const RESTORE_BACKUP_SUFFIX = ".bak";+/** SQLite's write-ahead-log siblings of a database file. */+const WAL_SIBLING_SUFFIXES: ReadonlyArray<string> = Object.freeze(["-wal", "-shm"]);++/** Decompress a snapshot archive to `outPath`, probing the magic bytes. */+function decompressArchiveTo(archive: string, outPath: string, runId: string): void {+ const tools = detectTooling();+ const compressor = detectArchiveCompression(archive);+ if (compressor === "zstd" && !tools.zstd) {+ throw new BrainSnapshotToolingMissingError(+ "zstd",+ "archive is zstd-compressed; install zstd to restore it.",+ );+ }+ if (compressor === "gzip" && !tools.gzip) {+ throw new BrainSnapshotToolingMissingError(+ "gzip",+ "archive is gzip-compressed; install gzip to restore it.",+ );+ }+ if (compressor === "zstd") {+ // `zstd -o` opens the destination itself and refuses an existing one.+ runCompressor(+ "zstd",+ ["-d", "-q", "-o", outPath, archive],+ { kind: "file", path: archive },+ runId,+ null,+ );+ return;+ }+ // gzip only writes to stdout; `wx` keeps the destination exclusive.+ writeFileSync(outPath, runArchiveProducer("gzip", ["-d", "-c", archive], runId), {+ flag: "wx",+ });+}+// ----- Helpers -------------------------------------------------------------function detectArchiveCompression(archive: string): "zstd" | "gzip" {@@ -663,6 +1477,3 @@ function countFiles(path: string): number {}return count;}--// Silence unused-symbol lints for helpers exported only via re-export.-void basename;diff --git a/src/core/brain/source-cleanup.ts b/src/core/brain/source-cleanup.tsindex 5d999157..74414392 100644--- a/src/core/brain/source-cleanup.ts+++ b/src/core/brain/source-cleanup.ts@@ -59,11 +59,9 @@ import { manifestPath, readManifest, writeManifestAtomic } from "./ingest/contenimport { appendContinuitySourceInvalidation } from "./continuity/store.ts";import { isoSecond } from "./time.ts";import { withDestructiveSnapshot } from "./snapshot-gate.ts";+import { BRAIN_SNAPSHOT_REASON } from "./types.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";-/** How a page was found to trace back to the source. */export type SourceCleanupMatch = "source_path" | "session_ref" | "wikilink" | "evidenced_by";@@ -590,9 +588,12 @@ export function deleteBySource(let snapshotRunId: string | null = null;let snapshotArchivePath: string | null = null;if (hasWork) {- const gated = withDestructiveSnapshot(vault, DELETE_BY_SOURCE_SNAPSHOT_LABEL, runDeletion, {- now: opts.now,- });+ const gated = withDestructiveSnapshot(+ vault,+ BRAIN_SNAPSHOT_REASON.deleteBySource,+ runDeletion,+ { now: opts.now },+ );snapshotRunId = gated.snapshot.runId;snapshotArchivePath = gated.snapshot.path;} else {diff --git a/src/core/brain/stale-dependency.ts b/src/core/brain/stale-dependency.tsnew file mode 100644index 00000000..43a86acb--- /dev/null+++ b/src/core/brain/stale-dependency.ts@@ -0,0 +1,514 @@+/**+ * Collection side of the reverse stale-dependency audit (U3).+ *+ * The question and the reasoning behind it are in+ * `doctor/stale-dependency-check.ts`, which owns the pure join this+ * module feeds. What lives here is every read the join cannot perform+ * for itself, and the decisions each read forces.+ *+ * ## Three stores, one direction of travel+ *+ * The STATE side is assembled from the three writers that end a record's+ * currency:+ *+ * - `moveToRetired` renames `pref-<slug>` to `ret-<slug>` and stamps+ * `retired_at`. The records arrive through `doctor/records.ts`, so+ * the parse discipline is the doctor's, not this module's.+ * - `tombstone` stamps `_status: tombstoned` and `tombstoned_at` on+ * any Brain artifact.+ * - `temporalReplace` closes a fact's half-open interval by writing+ * `valid_until`.+ *+ * The CONSUMER side is assembled from the two receipt stores and the+ * live artifact graph. No identifier is rewritten anywhere: the rename+ * is already crossed by `moveToRetired` writing the old `pref-<slug>`+ * into the retired file's `aliases:`, which `buildBacklinkIndex`+ * resolves through the alias index, and by `brainArtifactSlug` folding+ * both spellings onto one key on both sides of the join.+ *+ * ## The log is not a consumer+ *+ * `buildBacklinkIndex` walks `Brain/log/` alongside the artifacts, and+ * every retirement writes its own log entry naming the rule it retired.+ * Counting those would make the check fire on its own audit trail, every+ * time, for every retirement. The append-only log is the record THAT the+ * state changed; it is not something resting on the state having not+ * changed. Log-sourced references are dropped.+ *+ * ## What an unreadable store does+ *+ * Nothing here turns a failed read into an empty result. A directory+ * that exists and cannot be entered raises `StaleDependencyReadError`+ * naming the path and the attempted action, and the doctor check reports+ * it through the uncertainty channel. An ABSENT store is different and+ * stays quiet: a vault that never emitted a receipt legitimately has no+ * continuity directory, and that case is already carried by+ * `recorded: false`.+ *+ * The kernel, the vocabularies, the shapes and that error all come from+ * `doctor/stale-dependency-check.ts`, which imports nothing back. The+ * dependency runs one way on purpose; see that module's docblock.+ */++import { readdirSync, statSync } from "node:fs";+import { join } from "node:path";++import { buildBacklinkIndex } from "./backlinks.ts";+import type { ContinuityRecord } from "./continuity/types.ts";+import { listContinuityRecords } from "./continuity/store.ts";+import {+ normalizeDecisionSubject,+ readDecisionChangeReceipts,+ receiptsDir,+} from "./decisions/receipts.ts";+import { readAllRetiredRecords } from "./doctor/records.ts";+import {+ joinStaleDependencies,+ STALE_DEPENDENCY_CONSUMER,+ STALE_DEPENDENCY_LOOKBACK_DAYS,+ STALE_DEPENDENCY_MAX_CONSUMERS_PER_STATE,+ STALE_DEPENDENCY_STATE,+ StaleDependencyReadError,+ type StaleDependencyCitation,+ type StaleDependencyRow,+ type StaleDependencyState,+} from "./doctor/stale-dependency-check.ts";+import { readLifecycleState } from "./lifecycle/tombstone.ts";+import { boundaryToMs, VALID_UNTIL_KEY } from "./lifecycle/temporal-replace.ts";+import { brainDirs } from "./paths.ts";+import { parseFrontmatter } from "../vault.ts";+import { brainArtifactSlug } from "./wikilink.ts";++// ----- Constants ------------------------------------------------------------++/** Milliseconds in one day, for the lookback arithmetic. */+const MS_PER_DAY = 86_400_000;++/** Extension of every Brain artifact this module reads. */+const MARKDOWN_EXT = ".md";++/**+ * `BacklinkRef.sourceKind` prefix marking a reference read out of the+ * append-only log. See the module docblock for why those are dropped.+ */+const LOG_SOURCE_KIND_PREFIX = "log-";++/** Continuity record kind carrying the injected item list. */+const CONTEXT_RECEIPT_KIND = "context_receipt";++/** Directory holding the continuity shards, relative to `Brain/log`. */+const CONTINUITY_DIR_NAME = "continuity";++/** Payload key holding a context receipt's injected items. */+const RECEIPT_ITEMS_KEY = "items";++/** Item key holding an injected artifact's identifier. */+const RECEIPT_ITEM_ID_KEY = "id";++/** The one `errno` meaning a directory was never created. */+const DIR_ABSENT_ERRNO = "ENOENT";++// ----- Public shapes --------------------------------------------------------++export interface StaleDependencyOptions {+ /** Wall clock; tests pin it. Defaults to now. */+ readonly now?: Date;+ /** Consumer window in days; defaults to {@link STALE_DEPENDENCY_LOOKBACK_DAYS}. */+ readonly lookbackDays?: number;+ /** Per-state report cap; defaults to {@link STALE_DEPENDENCY_MAX_CONSUMERS_PER_STATE}. */+ readonly maxConsumersPerState?: number;+}++/**+ * The audit's answer.+ *+ * `recorded` is the {@link import("./context-receipts.ts").ContextReceiptFoldEmpty}+ * contract restated: `false` means the window held no receipts of either+ * kind, so nothing measured what the store's consumers actually rest on.+ * It is emphatically NOT "no stale dependencies were found" - the rows+ * are empty in both cases, and only this flag tells them apart.+ */+export interface StaleDependencyReport {+ /**+ * Whether either receipt store held anything in the window.+ *+ * It is NOT "whether the audit found anything", and it no longer gates+ * the rows: the artifact arm reads the backlink graph and always runs,+ * so a vault with the receipt gates off still gets every finding that+ * evidence supports. What this flag scopes is the part that was not+ * measured - the packs and decisions whose consumption is only visible+ * through a receipt - so a caller can say which half of the answer is+ * missing instead of implying the whole of it is.+ */+ readonly receipts_recorded: boolean;+ readonly rows: ReadonlyArray<StaleDependencyRow>;+ /**+ * How many states this vault has that stopped being current - retired,+ * tombstoned, or with a closed validity interval.+ *+ * Deliberately over all of vault history rather than the window: the+ * question it answers is whether anything was at stake at all. A store+ * where nothing ever changed has nothing whose consumers could have gone+ * stale, so an unmeasured receipt trail costs it nothing and there is no+ * honest warning to raise. A store where states did change and nothing+ * recorded what consumed them is the case worth saying out loud, and+ * this is how a caller tells the two apart without re-walking the vault.+ */+ readonly states_changed: number;+ /** Inclusive lower bound of the consumer window, as a UTC instant. */+ readonly window_since: string;+ readonly lookback_days: number;+}++// ----- Entry point ----------------------------------------------------------++/**+ * Audit which consumers rest on a state that has since changed.+ *+ * Read-only. With no receipts in the window there is nothing to join,+ * so the citation collection and the join are skipped - but the state+ * walk is not. An unmeasured audit still has to report whether anything+ * changed, because "nobody measured, and nothing changed either" and+ * "nobody measured, and eleven states moved" are different answers and+ * only the second is worth an operator's attention.+ *+ * @throws {@link StaleDependencyReadError} when a store that exists+ * cannot be read.+ */+export function auditStaleDependencies(+ vault: string,+ opts: StaleDependencyOptions = {},+): StaleDependencyReport {+ const now = opts.now ?? new Date();+ const lookbackDays = Math.max(1, Math.floor(opts.lookbackDays ?? STALE_DEPENDENCY_LOOKBACK_DAYS));+ const windowSince = new Date(now.getTime() - lookbackDays * MS_PER_DAY).toISOString();+ const contextReceipts = readContextReceipts(vault, windowSince);+ const decisionReceipts = readDecisionCitations(vault, windowSince);+ const artifacts = walkBrainArtifacts(vault);+ const states = collectStates(vault, artifacts, now.getTime());+ const stateKeys = new Set(states.map((state) => state.key));++ // The artifact arm runs unconditionally, and that is the point. It reads+ // the backlink universe on disk and needs no telemetry, so a vault with+ // the receipt gates off can still be told which live records cite a rule+ // that was retired under them. An earlier shape returned empty here the+ // moment both receipt stores were quiet, which threw away a computable+ // answer and then reported that nothing was knowable - the exact trade+ // this release exists to stop making.+ const citations: StaleDependencyCitation[] = [+ ...contextReceipts,+ ...decisionReceipts,+ ...collectArtifactCitations(vault, artifacts, stateKeys),+ ];++ return Object.freeze({+ receipts_recorded: contextReceipts.length > 0 || decisionReceipts.length > 0,+ rows: joinStaleDependencies({+ states,+ citations,+ maxConsumersPerState: opts.maxConsumersPerState ?? STALE_DEPENDENCY_MAX_CONSUMERS_PER_STATE,+ }),+ window_since: windowSince,+ lookback_days: lookbackDays,+ states_changed: states.length,+ });+}++// ----- Consumer side: context receipts --------------------------------------++/**+ * Context receipts in the window, one citation each.+ *+ * Private and redacted receipts are counted as measurement having+ * happened but are never unfolded, mirroring the withheld rule in+ * `summarizeContextReceiptSession`: a redacted payload must not re-enter+ * the vault through an aggregate built over it.+ */+function readContextReceipts(vault: string, since: string): ReadonlyArray<StaleDependencyCitation> {+ let records: ReadonlyArray<ContinuityRecord>;+ try {+ records = listContinuityRecords(vault, { kind: CONTEXT_RECEIPT_KIND, since });+ } catch (err) {+ throw new StaleDependencyReadError(+ "continuity record read failed",+ join(brainDirs(vault).log, CONTINUITY_DIR_NAME),+ err,+ );+ }+ const out: StaleDependencyCitation[] = [];+ for (const record of records) {+ if (record.private || record.redacted) continue;+ const items = record.payload[RECEIPT_ITEMS_KEY];+ if (!Array.isArray(items)) continue;+ const cites = new Set<string>();+ for (const raw of items) {+ if (raw === null || typeof raw !== "object") continue;+ const id = (raw as Record<string, unknown>)[RECEIPT_ITEM_ID_KEY];+ if (typeof id !== "string") continue;+ const key = brainArtifactSlug(id);+ if (key !== "") cites.add(key);+ }+ if (cites.size === 0) continue;+ const writtenAtMs = Date.parse(record.createdAt);+ if (!Number.isFinite(writtenAtMs)) continue;+ out.push({+ kind: STALE_DEPENDENCY_CONSUMER.contextReceipt,+ id: record.id,+ written_at: record.createdAt,+ written_at_ms: writtenAtMs,+ live: true,+ cites: [...cites],+ });+ }+ return out;+}++// ----- Consumer side: decision-change receipts ------------------------------++/**+ * Decision-change receipts in the window, one citation each.+ *+ * The cited states are the receipt's `evidence_triggers` - the records+ * the writer said the change rested on. The consumer's own identity is+ * its `subject`, folded through `normalizeDecisionSubject`, which is the+ * existing read-side normalizer for the three shapes subjects are stored+ * in; inventing a second one here would be the drift this wave keeps+ * finding.+ *+ * A receipt whose `ts` did not survive the line parse cannot be placed+ * in time, so it contributes no citation. Its shard already produced a+ * parse warning at the read below.+ */+function readDecisionCitations(+ vault: string,+ since: string,+): ReadonlyArray<StaleDependencyCitation> {+ let receipts;+ try {+ receipts = readDecisionChangeReceipts(vault).receipts;+ } catch (err) {+ throw new StaleDependencyReadError(+ "decision-change receipt read failed",+ receiptsDir(vault),+ err,+ );+ }+ const out: StaleDependencyCitation[] = [];+ for (const receipt of receipts) {+ if (receipt.ts < since) continue;+ const writtenAtMs = Date.parse(receipt.ts);+ if (!Number.isFinite(writtenAtMs)) continue;+ const cites = new Set<string>();+ for (const trigger of receipt.evidence_triggers) {+ const key = brainArtifactSlug(trigger);+ if (key !== "") cites.add(key);+ }+ if (cites.size === 0) continue;+ out.push({+ kind: STALE_DEPENDENCY_CONSUMER.decisionChange,+ id: normalizeDecisionSubject(receipt.subject),+ written_at: receipt.ts,+ written_at_ms: writtenAtMs,+ live: true,+ cites: [...cites],+ });+ }+ return out;+}++// ----- The artifact walk ----------------------------------------------------++/** One Brain markdown file, read once and used by both sides of the join. */+interface BrainArtifactFile {+ readonly basename: string;+ readonly path: string;+ /** Last write instant, in milliseconds. */+ readonly mtimeMs: number;+ readonly mtimeIso: string;+ readonly meta: Readonly<Record<string, unknown>>;+}++/**+ * The directories the walk covers, resolved from {@link brainDirs}.+ *+ * Deliberately the same universe `buildBacklinkIndex` reads artifacts+ * from, minus the log: a state outside that universe could never be+ * joined to a live artifact anyway, and including the log would make the+ * audit trail its own consumer.+ */+function artifactDirs(vault: string): ReadonlyArray<string> {+ const dirs = brainDirs(vault);+ return [dirs.brain, dirs.preferences, dirs.retired, dirs.inbox, dirs.processed];+}++/**+ * Read every Brain markdown file once.+ *+ * `mtime` rather than `created_at` is the consumer instant, and+ * deliberately so: the question is whether the consumer has been written+ * since the state changed, and an artifact rewritten after a retirement+ * has had the opportunity to reflect it whatever its frontmatter says it+ * was created. Under replication an incoming file carries its origin+ * mtime, which is the same instant on every device holding it.+ *+ * A directory that is absent is skipped; one that exists and cannot be+ * listed raises, because a shorter artifact list means fewer findings+ * and that must not pass as a clean store.+ */+function walkBrainArtifacts(vault: string): ReadonlyArray<BrainArtifactFile> {+ const out: BrainArtifactFile[] = [];+ const seen = new Set<string>();+ for (const dir of artifactDirs(vault)) {+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === DIR_ABSENT_ERRNO) continue;+ throw new StaleDependencyReadError("artifact directory listing failed", dir, err);+ }+ for (const entry of entries) {+ if (!entry.isFile() || !entry.name.endsWith(MARKDOWN_EXT)) continue;+ const path = join(dir, entry.name);+ if (seen.has(path)) continue;+ seen.add(path);+ let mtimeMs: number;+ try {+ mtimeMs = statSync(path).mtimeMs;+ } catch (err) {+ throw new StaleDependencyReadError("artifact stat failed", path, err);+ }+ const [meta] = parseFrontmatter(path);+ out.push({+ basename: entry.name.slice(0, -MARKDOWN_EXT.length),+ path,+ mtimeMs,+ mtimeIso: new Date(mtimeMs).toISOString(),+ meta,+ });+ }+ }+ return out;+}++// ----- State side -----------------------------------------------------------++/**+ * Every state that has already stopped being current.+ *+ * `nowMs` bounds it: a `valid_until` in the future has not closed yet,+ * so nothing written before it can be resting on a change that has not+ * happened.+ *+ * An instant that does not parse contributes no state. For preferences,+ * retired records and signals that condition is the doctor's own+ * `iso-invalid` finding, which is where a malformed timestamp is+ * reported; this join reports on time relationships and has nothing to+ * add about a timestamp that has none.+ */+function collectStates(+ vault: string,+ artifacts: ReadonlyArray<BrainArtifactFile>,+ nowMs: number,+): ReadonlyArray<StaleDependencyState> {+ const out: StaleDependencyState[] = [];+ const push = (+ key: string,+ kind: StaleDependencyState["kind"],+ path: string,+ changedAt: string,+ ): void => {+ if (key === "") return;+ const changedAtMs = Date.parse(changedAt);+ if (!Number.isFinite(changedAtMs) || changedAtMs > nowMs) return;+ out.push({ key, kind, path, changed_at: changedAt, changed_at_ms: changedAtMs });+ };++ let retired;+ try {+ retired = readAllRetiredRecords(vault);+ } catch (err) {+ throw new StaleDependencyReadError("retired record read failed", brainDirs(vault).retired, err);+ }+ for (const record of retired) {+ push(+ brainArtifactSlug(record.retired.id),+ STALE_DEPENDENCY_STATE.retired,+ record.path,+ record.retired.retired_at,+ );+ }++ for (const artifact of artifacts) {+ const key = brainArtifactSlug(artifact.basename);+ const lifecycle = readLifecycleState(artifact.meta);+ if (lifecycle.tombstoned && lifecycle.tombstonedAt !== null) {+ push(key, STALE_DEPENDENCY_STATE.tombstoned, artifact.path, lifecycle.tombstonedAt);+ }+ const validUntil = artifact.meta[VALID_UNTIL_KEY];+ if (typeof validUntil === "string" && boundaryToMs(validUntil) !== null) {+ push(key, STALE_DEPENDENCY_STATE.validityClosed, artifact.path, validUntil);+ }+ }+ return out;+}++// ----- Consumer side: live Brain artifacts ----------------------------------++/**+ * Artifacts whose links still reach a changed state.+ *+ * The backlink index does the resolution, including through the+ * `aliases:` entry `moveToRetired` leaves behind, so a body still+ * spelling `[[pref-<slug>]]` lands on the retired record without this+ * module rewriting anything. Self-references are already dropped by the+ * index, which is why a retired file pointing back at its own former id+ * cannot flag itself.+ *+ * A source that is itself a changed state is not live: history citing+ * history is not a dependency anybody is standing on.+ */+function collectArtifactCitations(+ vault: string,+ artifacts: ReadonlyArray<BrainArtifactFile>,+ stateKeys: ReadonlySet<string>,+): ReadonlyArray<StaleDependencyCitation> {+ if (stateKeys.size === 0) return [];+ let index;+ try {+ index = buildBacklinkIndex(vault);+ } catch (err) {+ throw new StaleDependencyReadError("backlink index build failed", brainDirs(vault).brain, err);+ }++ const byBasename = new Map(artifacts.map((artifact) => [artifact.basename, artifact]));+ const cited = new Map<string, Set<string>>();+ for (const [target, refs] of index) {+ const key = brainArtifactSlug(target);+ if (!stateKeys.has(key)) continue;+ for (const ref of refs) {+ if (ref.sourceKind.startsWith(LOG_SOURCE_KIND_PREFIX)) continue;+ const bucket = cited.get(ref.source);+ if (bucket) bucket.add(key);+ else cited.set(ref.source, new Set([key]));+ }+ }++ const out: StaleDependencyCitation[] = [];+ for (const [source, keys] of cited) {+ const artifact = byBasename.get(source);+ // A source the walk did not see is a file outside the artifact+ // directories - it has no write instant this join can read, and+ // guessing one would decide the strict comparison by invention.+ if (artifact === undefined) continue;+ out.push({+ kind: STALE_DEPENDENCY_CONSUMER.brainArtifact,+ id: source,+ path: artifact.path,+ written_at: artifact.mtimeIso,+ written_at_ms: artifact.mtimeMs,+ live: !stateKeys.has(brainArtifactSlug(source)),+ cites: [...keys],+ });+ }+ return out;+}diff --git a/src/core/brain/standing-rules.ts b/src/core/brain/standing-rules.tsnew file mode 100644index 00000000..764c110b--- /dev/null+++ b/src/core/brain/standing-rules.ts@@ -0,0 +1,323 @@+/**+ * Operator standing rules: `Brain/standing-rules.md`+ * (silence-is-not-an-answer, U8).+ *+ * Every other lane of the session preamble is something the agent+ * learned about itself - preferences it recorded, lessons it distilled,+ * packs it assembled. This one is the operator talking, and the whole+ * point of the file is that it outranks all of that. So it is injected+ * first, it is exempt from the adaptive injection budget, it survives a+ * memory-layer failure because it is read outside that boundary, and no+ * tool can rewrite it.+ *+ * UNEDITABILITY IS MOSTLY INHERITED, AND THE REST IS ONE NAMED GUARD.+ * The honest scope of that claim belongs here rather than in a release+ * note. `Brain/` is the machinery root that `resolveNoteTarget` refuses+ * outright, so `Brain/standing-rules.md` is un-writable through the four+ * CALLER-NAMED note-write tools - `brain_create_note`,+ * `brain_update_note`, `brain_append_note` and `brain_write_batch` - which+ * all resolve their target through that one envelope. That class is the+ * boundary the write-site census maintains, and it is the class an agent+ * can address by naming a path.+ *+ * It is not the whole class, which is why {@link+ * assertStandingRulesNotTargeted} exists. `brain_labels` also takes a+ * caller-named path, and it reaches the file through the weaker+ * `resolveNotePath`, which checks containment and symlinks only - so the+ * inherited refusal did not cover it and a label write could rewrite the+ * operator's frontmatter. The guard is deliberately NOT the Brain-root+ * refusal moved down a layer: several legitimate callers write inside+ * `Brain/` through that same resolver (marker write-back, tombstones,+ * temporal replace), so what the guard names is one file.+ *+ * Neither mechanism is a claim that no code in this process can open the+ * file for writing; a module reaching `node:fs` directly is a different+ * population, counted by that same census.+ *+ * OPERATOR BYTES ARE OPAQUE. The reader performs exactly three+ * operations on them: read, trim, and line-boundary trimming at a+ * character cap. It never splits on headings, never inspects words,+ * never classifies, and the truncation notice is assembled from integers+ * and the path alone - so a rules file written in any language is capped+ * and reported identically to one written in English. Any future word+ * list or heading split here would break that, which is why the reader+ * has no branch that reads the content at all.+ *+ * ABSENCE AND FAILURE ARE DIFFERENT ANSWERS. {@link readStandingRules}+ * returns `null` only for a file that is not there or whose trimmed body+ * is empty. Every other outcome throws, naming the path and the reason,+ * and the hook path renders {@link renderStandingRulesFailure} rather+ * than degrading to nothing in silence. A constitution that disappears+ * without a word is worse than one that was never written.+ */++import { readFileSync, realpathSync } from "node:fs";+import { resolve } from "node:path";++import { brainStandingRulesPath } from "./paths.ts";+import { applySectionBudget } from "./text/text-budget.ts";++/**+ * Character cap for the standing-rules block. Generous next to the+ * default injection budget because this lane is exempt from that budget+ * and is the operator's own voice: the cap exists to stop a runaway file+ * from swallowing the context window, not to ration the operator.+ * Override via `active.standing_rules_max_chars`.+ */+export const STANDING_RULES_MAX_CHARS_DEFAULT = 4000;+export const STANDING_RULES_MAX_CHARS_MIN = 200;+export const STANDING_RULES_MAX_CHARS_MAX = 100_000;++/**+ * Budget-section key for the single section the cap operates on. The+ * body is never split, so there is exactly one, and the key never+ * reaches a rendered surface - the notice is built from integers.+ */+export const STANDING_RULES_SECTION_KEY = "standing-rules";++/**+ * The precedence sentence this project prepends to the operator's text.+ *+ * Authored here, in English, and never derived from the file: the+ * operator writes rules, not the framing that gives them force. Keeping+ * the framing ours is also what lets the block below it be treated as+ * opaque bytes - the agent is told how to weigh the text without anyone+ * having had to read it.+ */+export const STANDING_RULES_HEADER =+ "## Operator standing rules\n\n" ++ "The rules below are written by the operator of this vault. " ++ "They take precedence over every recalled preference, lesson and context pack that follows.";++/** Blank-line separator between the header, the body and the notice. */+const BLOCK_SEPARATOR = "\n\n";++/** A capped or uncapped read of the operator's standing rules. */+export interface StandingRules {+ /** Absolute path the bytes came from; named in the truncation notice. */+ readonly path: string;+ /** Operator bytes: trimmed, and cut at a line boundary when over the cap. Never reformatted. */+ readonly text: string;+ /** True when the cap removed anything. */+ readonly truncated: boolean;+ readonly keptLines: number;+ readonly totalLines: number;+ readonly keptChars: number;+ readonly totalChars: number;+}++export interface ReadStandingRulesOptions {+ /** Character cap; defaults to {@link STANDING_RULES_MAX_CHARS_DEFAULT}. */+ readonly maxChars?: number;+}++/**+ * Read `Brain/standing-rules.md`, trimmed and capped at a line boundary.+ *+ * Returns `null` for exactly two conditions: the file does not exist, or+ * its trimmed body is empty. Both mean the operator has written no rules,+ * which is a legitimate state and not a failure. Anything else - a+ * permission denial, a directory where the file should be, a read that+ * fails mid-stream - throws with the path and the reason, because the+ * caller must be able to tell "no rules" from "the rules could not be+ * read" and there is no cached substitute for a constitution.+ */+export function readStandingRules(+ vault: string,+ opts: ReadStandingRulesOptions = {},+): StandingRules | null {+ const path = brainStandingRulesPath(vault);++ // Read first and classify the failure, rather than probing with+ // `existsSync` and reading after: the probe leaves a window in which+ // the answer changes between the two syscalls, and ENOENT from the+ // read itself IS the absence the probe was looking for.+ let raw: string;+ try {+ raw = readFileSync(path, "utf8");+ } catch (err) {+ if (isFileAbsent(err)) return null;+ throw new Error(`standing rules at ${path} could not be read: ${describeError(err)}`, {+ cause: err,+ });+ }++ const trimmed = raw.trim();+ if (trimmed.length === 0) return null;++ const totalChars = trimmed.length;+ const totalLines = countLines(trimmed);+ const maxChars = opts.maxChars ?? STANDING_RULES_MAX_CHARS_DEFAULT;+ if (totalChars <= maxChars) {+ return freeze(path, trimmed, false, totalLines, totalChars, totalLines, totalChars);+ }++ // The cap goes through the shared section budgeter so the cut is the+ // same line-boundary trim the injected memory bodies get. One section,+ // so there is nothing to drop whole and nothing to reorder: the only+ // behaviour reached is the tail trim.+ //+ // No `notice` is passed. The notice belongs to the RENDER, not to the+ // capped text: `text` is the operator's own bytes and `keptChars`+ // counts them, so letting this project's prose into that string would+ // make the record describe something partly ours.+ const capped = applySectionBudget(+ [{ key: STANDING_RULES_SECTION_KEY, priority: 0, text: trimmed }],+ maxChars,+ );+ const text = capped.body;+ return freeze(path, text, true, countLines(text), text.length, totalLines, totalChars);+}++/** Refusal raised by {@link assertStandingRulesNotTargeted}. */+export class StandingRulesWriteRefusedError extends Error {+ /** Absolute path the guard protects. */+ readonly path: string;+ /** The write path that was refused, as its caller named itself. */+ readonly surface: string;+ constructor(path: string, surface: string) {+ // Scoped to this surface deliberately: the guard speaks for the write+ // path that called it, not for every write path in the process.+ super(+ `${surface} refused: ${path} is the operator's standing-rules file, which this ` ++ "surface does not rewrite",+ );+ this.name = "StandingRulesWriteRefusedError";+ this.path = path;+ this.surface = surface;+ }+}++/**+ * Refuse a write whose target is `Brain/standing-rules.md`.+ *+ * Narrow on purpose: it names ONE file, and it is called from the write+ * paths that resolve a caller-named path without going through the+ * note-target envelope that already refuses the whole `Brain/` root. It+ * runs before any I/O in its callers, so a refused call also performs no+ * read and no validation side effect.+ *+ * `notePath` is the caller's own vault-relative (or absolute) argument,+ * resolved here rather than taken pre-resolved, so the guard can run+ * ahead of its caller's path resolution and vocabulary checks. Both sides+ * are compared lexically and then canonically: a symlink pointing at the+ * rules file is the same target, and a symlinked vault root must not make+ * two spellings of one path look like two paths.+ */+export function assertStandingRulesNotTargeted(+ vault: string,+ notePath: string,+ surface: string,+): void {+ const target = brainStandingRulesPath(vault);+ const candidate = resolve(vault, notePath);+ if (candidate === target || canonicalPath(candidate) === canonicalPath(target)) {+ throw new StandingRulesWriteRefusedError(target, surface);+ }+}++/**+ * Canonical form of `path`, or the path itself when it cannot be+ * canonicalized. A missing file has nothing to resolve, and falling back+ * to the lexical form keeps the comparison total - the guard must never+ * fail open because one side does not exist yet.+ */+function canonicalPath(path: string): string {+ try {+ return realpathSync(path);+ } catch {+ return path;+ }+}++/**+ * Render the injected block: the precedence header, the operator's text,+ * and - only when the cap removed something - a notice built from+ * integers and the path.+ */+export function renderStandingRules(rules: StandingRules): string {+ const parts = [STANDING_RULES_HEADER, rules.text];+ if (rules.truncated) parts.push(renderTruncationNotice(rules));+ return parts.join(BLOCK_SEPARATOR);+}++/**+ * The block emitted in place of the rules when the read threw.+ *+ * The constitution never degrades to nothing without saying so, so this+ * names the file, names the reason, and states in one sentence that no+ * standing rules are in force for this session. An agent that sees the+ * ordinary header and no rules would reasonably conclude the operator+ * wrote none; this is what stops that conclusion being drawn from a+ * permission error.+ */+export function renderStandingRulesFailure(path: string, error: unknown): string {+ return [+ STANDING_RULES_HEADER,+ `UNAVAILABLE: ${path} could not be read (${describeError(error)}). ` ++ "No standing rules are in force this session.",+ ].join(BLOCK_SEPARATOR);+}++/**+ * The truncation notice: kept and total lines, kept and total+ * characters, and where the whole text lives.+ *+ * Integers and a path only. That is not terseness - it is what makes the+ * sentence identical whatever language the operator writes in, because+ * nothing in it is derived from the bytes that were cut.+ */+function renderTruncationNotice(rules: StandingRules): string {+ return (+ `_Standing rules truncated to the configured cap: kept ${rules.keptLines} of ` ++ `${rules.totalLines} lines, ${rules.keptChars} of ${rules.totalChars} characters. ` ++ `Read ${rules.path} for the full text._`+ );+}++function freeze(+ path: string,+ text: string,+ truncated: boolean,+ keptLines: number,+ keptChars: number,+ totalLines: number,+ totalChars: number,+): StandingRules {+ return Object.freeze({+ path,+ text,+ truncated,+ keptLines,+ totalLines,+ keptChars,+ totalChars,+ });+}++/** The one errno that means "the operator has not written this file". */+const ENOENT = "ENOENT";++function isFileAbsent(err: unknown): boolean {+ return typeof err === "object" && err !== null && (err as NodeJS.ErrnoException).code === ENOENT;+}++function describeError(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++/**+ * Newline-delimited line count. Empty text is 0 lines; a trailing+ * newline does not add a phantom line. The body is always trimmed+ * before it gets here, so the second case is theoretical and cheap to+ * keep correct anyway.+ */+function countLines(text: string): number {+ if (text.length === 0) return 0;+ let count = 0;+ for (let i = 0; i < text.length; i++) {+ if (text.charCodeAt(i) === 0x0a) count++;+ }+ if (text.charCodeAt(text.length - 1) !== 0x0a) count++;+ return count;+}diff --git a/src/core/brain/templates.ts b/src/core/brain/templates.tsindex db21f1be..e7a70df5 100644--- a/src/core/brain/templates.ts+++ b/src/core/brain/templates.ts@@ -14,6 +14,7 @@ import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";import { escapeRegex } from "../strings.ts";+import { BRAIN_MANIFEST_SIDECAR_SINCE_VERSION } from "./manifest.ts";import { DEFAULT_BRAIN_CONFIG } from "./policy.ts";import type { BrainConfig } from "./types.ts";@@ -79,6 +80,11 @@ export function buildSubstitutions(return new Map<string, string>([["vault_name", vaultDisplayName(vault)],["schema_version", String(config.schema_version)],+ // The release the sidecar manifest shipped in. A substitution rather+ // than a literal in the template, because the same version is stated+ // in the rollback warning and in the verb help; one owner, three+ // readers.+ ["manifest_sidecar_since", BRAIN_MANIFEST_SIDECAR_SINCE_VERSION],]);}diff --git a/src/core/brain/templates/_BRAIN.md.tpl b/src/core/brain/templates/_BRAIN.md.tplindex b36e7ab0..c4b16586 100644--- a/src/core/brain/templates/_BRAIN.md.tpl+++ b/src/core/brain/templates/_BRAIN.md.tpl@@ -137,9 +137,11 @@ them as part of normal agent work.preference requires `--yes` and prints a warning.- `o2b brain rollback <run_id>` โ restore Brain from a snapshot.Interactive by default; `--list` enumerates available snapshots.- From v0.10.6 a snapshot ships with a sha256 sidecar manifest so+ From {{manifest_sidecar_since}} a snapshot ships with a sha256 sidecar manifest sorollback aborts when the live tree drifted from the snapshot moment;- pass `--force-rollback` to override.+ pass `--force-rollback` to override. The derived SQLite store is+ covered only when `snapshots.include_derived_store` is on; every+ rollback says which of replaced / not restored / unknown applied.- `o2b brain pin <pref-id>` / `unpin <pref-id>` โ protect a preferencefrom automatic retirement (still subject to explicit reject).- `o2b brain upgrade` โ migrate the release-owned files (`_brain.yaml`,diff --git a/src/core/brain/text/text-budget.ts b/src/core/brain/text/text-budget.tsindex 078ced31..a1857e46 100644--- a/src/core/brain/text/text-budget.ts+++ b/src/core/brain/text/text-budget.ts@@ -12,7 +12,9 @@* never mid-line, so the output is always well-formed Markdown;* 3. appending an optional one-line truncation notice that rides* on top of the budget (it is the pointer to the full view, so- * it must survive even a zero budget).+ * it must survive even a zero budget). The notice may be a fixed+ * sentence or a function of the truncation report, so a caller can+ * say WHICH sections went instead of only that something did.** Pure and deterministic: no I/O, clock, or randomness. Identical* inputs produce identical outputs - the property the active.md@@ -31,13 +33,47 @@ export interface BudgetSection {readonly text: string;}+/**+ * What a notice function is told about the truncation it is announcing.+ *+ * Keys and integers ONLY, deliberately. A caller that wants to name what+ * went can do so from `droppedKeys`, which are the caller's own stable+ * identifiers, and can quantify it from the character pair - without this+ * module ever handing back a slice of section TEXT. That matters because+ * one consumer of this budgeter caps operator-authored bytes in an+ * unknown language, and a notice assembled from integers reads the same+ * whatever those bytes are.+ */+export interface SectionTruncationReport {+ /** Keys of fully dropped sections, in drop order. */+ readonly droppedKeys: ReadonlyArray<string>;+ /** Characters of section content in the budgeted body, notice excluded. */+ readonly keptChars: number;+ /** Characters the untruncated join of every section would have had. */+ readonly totalChars: number;+ /** True when the last kept section was tail-trimmed at a line boundary. */+ readonly trimmed: boolean;+}++/**+ * A fixed sentence, or a sentence built from the truncation report.+ *+ * The fixed form is right when there is only one thing the notice can+ * say. The function form exists because "something was dropped" and+ * "these three sections were dropped, keeping 7,980 of 30,412+ * characters" are different messages, and the second one was already+ * computed here and then thrown away by every caller.+ */+export type SectionBudgetNotice = string | ((report: SectionTruncationReport) => string);+export interface SectionBudgetOptions {/*** One-line notice appended (after a blank-line separator when any* content is kept) whenever truncation occurred. Not counted- * against the budget.+ * against the budget. Resolved once, only when truncation actually+ * happened, so the function form is never called on the common path.*/- readonly notice?: string;+ readonly notice?: SectionBudgetNotice;}export interface SectionBudgetResult {@@ -109,6 +145,7 @@ export function applySectionBudget(opts: SectionBudgetOptions = {},): SectionBudgetResult {const budget = Number.isFinite(budgetChars) ? Math.max(0, Math.floor(budgetChars)) : 0;+ const totalChars = joinedLength(sections);const kept: KeptSection[] = sections.map((s, index) => ({ ...s, index }));const droppedKeys: string[] = [];let trimmedAny = false;@@ -143,14 +180,32 @@ export function applySectionBudget(.map((s) => s.text).join(SEPARATOR);+ const frozenDroppedKeys = Object.freeze(droppedKeys);+let body = content;- if (truncated && opts.notice !== undefined && opts.notice.length > 0) {- body = content.length > 0 ? content + SEPARATOR + opts.notice : opts.notice;+ if (truncated && opts.notice !== undefined) {+ // The single place a notice is appended, and therefore the single+ // place the report is materialized. `keptChars` describes the+ // content alone: the notice rides on top of the budget, so counting+ // it would make the pair the notice reports disagree with itself.+ const notice = resolveNotice(opts.notice, {+ droppedKeys: frozenDroppedKeys,+ keptChars: content.length,+ totalChars,+ trimmed: trimmedAny,+ });+ if (notice.length > 0) {+ body = content.length > 0 ? content + SEPARATOR + notice : notice;+ }}return Object.freeze({body,truncated,- droppedKeys: Object.freeze(droppedKeys),+ droppedKeys: frozenDroppedKeys,});}++function resolveNotice(notice: SectionBudgetNotice, report: SectionTruncationReport): string {+ return typeof notice === "string" ? notice : notice(report);+}diff --git a/src/core/brain/triggers/store.ts b/src/core/brain/triggers/store.tsindex 8f96a94e..53e81d75 100644--- a/src/core/brain/triggers/store.ts+++ b/src/core/brain/triggers/store.ts@@ -5,19 +5,32 @@* Each trigger is one Markdown file under `Brain/triggers/` - operator* readable without tooling, frontmatter carries the machine state.* History is a status change, not a file move: terminal triggers- * (acted / dismissed / expired) stay in place so `history` is just a- * status filter and the cooldown logic can see them.+ * (acted / dismissed / expired / suppressed) stay in place so `history`+ * is just a status filter and the cooldown logic can see them.** Anti-nag invariants live here and only here:* - cooldown-key dedup across ALL statuses makes repeated scans- * idempotent (an open twin always blocks; a terminal twin blocks- * for `cooldownDays` after its resolution; an expired twin allows);+ * idempotent (a suppressed twin always blocks; an open twin always+ * blocks; a dismissed or acted twin blocks for `cooldownDays` after+ * its resolution; an expired twin allows);* - lifecycle transitions: acknowledge / act / dismiss are allowed* from ANY open state (an operator may act on a trigger they found* via `list` before the brief ever delivered it - delivery is a* surfacing step, not a gate), terminal states reject everything;+ * - suppression is the one edge OUT of a terminal state: it is legal+ * from any status, it carries no clock, and {@link transitionTrigger}+ * restores the interrupted status verbatim on `unsuppress` because+ * suppressing leaves the delivery and resolution instants untouched;+ * - the recurrence ledger records every silenced candidate that HAS a+ * record to write to, so a suppressed finding that keeps firing is+ * auditable rather than invisible ({@link recordRecurrence});* - brief delivery happens at most once per cooldown window- * ({@link briefTriggers} + {@link markTriggersDelivered}).+ * ({@link briefTriggers} + {@link markTriggersDelivered});+ * - an unreadable record is confined to itself. Every surface reads+ * through {@link readTriggers}, which partitions the directory into+ * the records it could parse and the ones it could not, so a single+ * hand-edited file names itself instead of taking `list`, `history`,+ * the brief, delivery, creation and the transitions down with it.*/import { createHash } from "node:crypto";@@ -33,6 +46,11 @@ import {isTriggerKind,isTriggerStatus,isTriggerUrgency,+ TRIGGER_KINDS,+ TRIGGER_OPEN_STATUSES,+ TRIGGER_STATUS,+ TRIGGER_STATUSES,+ TRIGGER_TERMINAL_STATUSES,TRIGGER_URGENCIES,type InsightCandidate,type TriggerRecord,@@ -43,8 +61,52 @@ export const TRIGGER_TTL_DAYS = 14;export const TRIGGER_COOLDOWN_DAYS = 7;export const TRIGGER_MAX_PER_KIND = 10;+/**+ * How long a held trigger-directory lock may sit before another process+ * treats it as abandoned. Exported so a test can hold the same lock the+ * writers take rather than guessing at its options.+ */+export const TRIGGER_LOCK_STALE_MS = 10_000;+const DAY_MS = 24 * 3600 * 1000;-const OPEN_STATUSES: ReadonlySet<TriggerStatus> = new Set(["pending", "delivered", "acknowledged"]);++/**+ * Occurrences credited to a record that predates the recurrence ledger.+ * It is the count of occurrences anyone actually recorded for such a+ * record - the creation - and not a placeholder for an unknown number.+ */+const OCCURRENCES_WHEN_UNRECORDED = 1;++/** Longest run of an unreadable field value reproduced in an error. */+const FIELD_EXCERPT_MAX = 120;++/**+ * The frontmatter keys of a stored trigger, in one frozen table.+ *+ * The renderer, the parser and the refusal messages all read the names+ * from here, so a key can never be spelled one way on the way out and+ * another way on the way back in - and a refusal always quotes the same+ * name the operator sees in the file.+ */+const TRIGGER_KEY = Object.freeze({+ id: "trigger_id",+ kind: "trigger_type",+ status: "status",+ urgency: "urgency",+ cooldownKey: "cooldown_key",+ createdAt: "created_at",+ expiresAt: "expires_at",+ deliveredAt: "delivered_at",+ resolvedAt: "resolved_at",+ suppressedAt: "suppressed_at",+ suppressedFrom: "suppressed_from",+ occurrences: "occurrences",+ lastSeenAt: "last_seen_at",+ sourceArtifacts: "source_artifacts",+} as const);++/** Extension of every trigger record file under `Brain/triggers/`. */+const TRIGGER_FILE_EXT = ".md";export function triggersDir(vault: string): string {return join(vault, "Brain", "triggers");@@ -57,18 +119,26 @@ interface StoredTrigger extends Omit<TriggerRecord, "effectiveStatus"> {}function renderTrigger(record: StoredTrigger): string {const lines = ["---",- `trigger_id: ${record.id}`,- `trigger_type: ${record.kind}`,- `status: ${record.status}`,- `urgency: ${record.urgency}`,+ `${TRIGGER_KEY.id}: ${record.id}`,+ `${TRIGGER_KEY.kind}: ${record.kind}`,+ `${TRIGGER_KEY.status}: ${record.status}`,+ `${TRIGGER_KEY.urgency}: ${record.urgency}`,// Free-text and list values are JSON-quoted so YAML-significant// characters can never corrupt the file (intentions/handoff pattern).- `cooldown_key: ${JSON.stringify(record.cooldownKey)}`,- `created_at: ${record.createdAt}`,- `expires_at: ${record.expiresAt}`,- ...(record.deliveredAt !== null ? [`delivered_at: ${record.deliveredAt}`] : []),- ...(record.resolvedAt !== null ? [`resolved_at: ${record.resolvedAt}`] : []),- `source_artifacts: ${JSON.stringify(record.sourceArtifacts)}`,+ `${TRIGGER_KEY.cooldownKey}: ${JSON.stringify(record.cooldownKey)}`,+ `${TRIGGER_KEY.createdAt}: ${record.createdAt}`,+ `${TRIGGER_KEY.expiresAt}: ${record.expiresAt}`,+ ...(record.deliveredAt !== null ? [`${TRIGGER_KEY.deliveredAt}: ${record.deliveredAt}`] : []),+ ...(record.resolvedAt !== null ? [`${TRIGGER_KEY.resolvedAt}: ${record.resolvedAt}`] : []),+ ...(record.suppressedAt !== null+ ? [`${TRIGGER_KEY.suppressedAt}: ${record.suppressedAt}`]+ : []),+ ...(record.suppressedFrom !== null+ ? [`${TRIGGER_KEY.suppressedFrom}: ${record.suppressedFrom}`]+ : []),+ `${TRIGGER_KEY.occurrences}: ${record.occurrences}`,+ `${TRIGGER_KEY.lastSeenAt}: ${record.lastSeenAt}`,+ `${TRIGGER_KEY.sourceArtifacts}: ${JSON.stringify(record.sourceArtifacts)}`,"---","","## Reason",@@ -98,50 +168,277 @@ function sectionText(body: string, heading: string): string {return body.slice(start, end).trim();}-function parseJsonArray(raw: unknown): ReadonlyArray<string> {+/**+ * One frontmatter field of one record cannot be read.+ *+ * Absent and unreadable are different claims and this type is what keeps+ * them apart. An absent field means nobody ever recorded the thing, which+ * several fields here have an honest reading for; a present field that+ * does not parse means a record says something and the store cannot tell+ * what. Substituting the absent-field reading for the second case would+ * state a value nothing supports - which is the failure this whole wave+ * exists to remove - so it refuses, naming the file, the key, and the+ * operator's own bytes so the broken line can be found.+ *+ * The refusal is scoped to ONE record: {@link readTriggers} catches it+ * per file and reports it alongside the records that read cleanly, so a+ * broken line stops the record that carries it and nothing else.+ */+export class TriggerFieldError extends Error {+ /** The trigger file carrying the unreadable value. */+ readonly path: string;+ /** The frontmatter key that could not be read. */+ readonly key: string;++ constructor(path: string, key: string, detail: string) {+ super(`trigger ${path}: ${key} ${detail}`);+ this.name = "TriggerFieldError";+ this.path = path;+ this.key = key;+ }+}++/**+ * A file listed in the trigger directory that cannot be read at all.+ *+ * Distinct from {@link TriggerFieldError} because no single field is at+ * fault: the record may hold a perfectly good finding that this process+ * simply cannot open. Reporting it as an absent trigger would be the same+ * mistake one level up.+ */+export class TriggerFileError extends Error {+ /** The trigger file that could not be opened. */+ readonly path: string;++ constructor(path: string, cause: string) {+ super(`trigger ${path}: the file cannot be read: ${cause}`);+ this.name = "TriggerFileError";+ this.path = path;+ }+}++/** Detail for a value that is recorded and cannot be read. */+function presentButUnreadable(expectation: string, raw: unknown): string {+ return `is present but ${expectation}: ${excerptFieldValue(raw)}`;+}++/** Detail for a value every record must carry and this one does not. */+function absentButRequired(requirement: string): string {+ return `is missing, and ${requirement}`;+}++/**+ * A `source_artifacts` value that is present and cannot be read as a+ * list of strings.+ *+ * It is a refusal rather than an empty list on purpose. The grounding+ * artifacts are the evidence a finding rests on, so a trigger reporting+ * none is a materially different claim from a trigger whose evidence+ * could not be read - and the earlier behaviour, which degraded a+ * hand-edited list to `[]`, made an unparseable finding present as an+ * ungrounded one with nothing anywhere saying so.+ */+export class TriggerSourceArtifactsError extends TriggerFieldError {+ constructor(path: string, raw: unknown) {+ super(path, TRIGGER_KEY.sourceArtifacts, presentButUnreadable("not a list of strings", raw));+ this.name = "TriggerSourceArtifactsError";+ }+}++/**+ * Operator bytes bounded to one line, so an error message stays one+ * line whatever the file contains. The value is reproduced verbatim and+ * never inspected - it is opaque content, quoted back so the operator+ * can find the line they broke.+ */+function excerptFieldValue(raw: unknown): string {+ const text = typeof raw === "string" ? raw : String(raw);+ return text.length <= FIELD_EXCERPT_MAX ? text : `${text.slice(0, FIELD_EXCERPT_MAX)}โฆ`;+}++/**+ * Read the grounding artifact list. An absent key names no artifacts and+ * yields an empty list; a present but unreadable one throws - see+ * {@link TriggerSourceArtifactsError}.+ */+function parseArtifactList(raw: unknown, path: string): ReadonlyArray<string> {+ if (raw === undefined) return Object.freeze([]);// Defensive: a frontmatter parser that materializes the value as a// real array round-trips too.if (Array.isArray(raw) && raw.every((x) => typeof x === "string")) {return Object.freeze([...raw]);}- if (typeof raw !== "string" || raw.trim() === "") return Object.freeze([]);- try {- const parsed = JSON.parse(raw) as unknown;- if (Array.isArray(parsed) && parsed.every((x) => typeof x === "string")) {- return Object.freeze(parsed);+ if (typeof raw === "string") {+ try {+ const parsed = JSON.parse(raw) as unknown;+ if (Array.isArray(parsed) && parsed.every((x) => typeof x === "string")) {+ return Object.freeze(parsed);+ }+ } catch {+ // fall through to the refusal below}- } catch {- // fall through - a hand-edited list degrades to empty, never throws}- return Object.freeze([]);+ throw new TriggerSourceArtifactsError(path, raw);+}++/**+ * The recorded occurrence count.+ *+ * An ABSENT key yields {@link OCCURRENCES_WHEN_UNRECORDED}: the record+ * predates the ledger, and one - its creation - is the count of+ * occurrences anybody actually recorded for it. A PRESENT key that does+ * not read as a positive integer refuses, because crediting a corrupt+ * counter that same one would understate a finding that has fired forty+ * times and would make a hand-edit indistinguishable from a record+ * written before the ledger existed.+ *+ * The numeric arm is not defensive dressing: the count is written as a+ * bare integer, so a frontmatter parser that materializes it as a number+ * must not fall through and quietly discard a real count.+ */+function parseOccurrences(raw: unknown, path: string): number {+ if (raw === undefined) return OCCURRENCES_WHEN_UNRECORDED;+ const parsed = typeof raw === "number" ? raw : Number.parseInt(String(raw).trim(), 10);+ if (!Number.isSafeInteger(parsed) || parsed < OCCURRENCES_WHEN_UNRECORDED) {+ throw new TriggerFieldError(+ path,+ TRIGGER_KEY.occurrences,+ presentButUnreadable("not a positive integer", raw),+ );+ }+ return parsed;+}++/**+ * The instant the trigger was created.+ *+ * Required, and refused here rather than defaulted, because every later+ * use treats it as a real instant: it orders the listing, it is the+ * honest reading of an absent `last_seen_at`, and it is written back+ * verbatim on every recurrence. The empty string this used to substitute+ * did not stay a read-time inconvenience - the first recurrence write+ * emitted `last_seen_at:` with nothing after it, the next read+ * materialised that as `""` and refused THAT field, so a record with no+ * creation instant became permanently unreadable one write later and+ * blamed a line the operator never touched. Refusing at the origin keeps+ * the report pointing at the field that is actually missing.+ */+function parseCreatedAt(raw: unknown, path: string): string {+ if (raw === undefined) {+ throw new TriggerFieldError(+ path,+ TRIGGER_KEY.createdAt,+ absentButRequired("a trigger is ordered, dated and aged by it"),+ );+ }+ const text = typeof raw === "string" ? raw : String(raw);+ if (text.length === 0 || Number.isNaN(Date.parse(text))) {+ throw new TriggerFieldError(+ path,+ TRIGGER_KEY.createdAt,+ presentButUnreadable("not a readable instant", raw),+ );+ }+ return text;+}++/**+ * The instant the finding was last seen.+ *+ * An ABSENT key yields the creation instant: a record predating the+ * ledger last fired when it was created, and that is a true statement+ * about it - {@link parseCreatedAt} has already established that the+ * substitute is a real instant, so this reading can never manufacture an+ * unreadable value. A PRESENT key that is not a readable instant+ * refuses, for the same reason the occurrence count does.+ */+function parseLastSeenAt(raw: unknown, createdAt: string, path: string): string {+ if (raw === undefined) return createdAt;+ const text = typeof raw === "string" ? raw : String(raw);+ if (text.length === 0 || Number.isNaN(Date.parse(text))) {+ throw new TriggerFieldError(+ path,+ TRIGGER_KEY.lastSeenAt,+ presentButUnreadable("not a readable instant", raw),+ );+ }+ return text;+}++/**+ * A frontmatter value read as text, or "" when the key holds no string.+ * Used for the fields whose absence and whose emptiness are the same+ * claim to every reader below.+ */+function textOrEmpty(raw: unknown): string {+ return typeof raw === "string" ? raw : "";+}++/** A frontmatter value read as text, or `null` when nothing recorded one. */+function textOrNull(raw: unknown): string | null {+ return typeof raw === "string" ? raw : null;}function effectiveStatus(status: TriggerStatus, expiresAt: string, now: Date): TriggerStatus {- if (!OPEN_STATUSES.has(status)) return status;+ // Expiry applies to open statuses only, which is precisely what makes+ // `suppressed` indefinite: it is terminal, so no clock reaches it.+ if (!TRIGGER_OPEN_STATUSES.has(status)) return status;const expiry = Date.parse(expiresAt);if (Number.isFinite(expiry) && now.getTime() > expiry) return "expired";return status;}+/**+ * Read one file as a trigger record.+ *+ * `null` means the file is not a trigger record at all: it carries no+ * `trigger_id`, so nothing claims it belongs to the queue and skipping it+ * omits no finding - an operator may keep their own notes in the+ * directory. Every OTHER failure throws {@link TriggerFieldError} naming+ * the field, because a file that says it is trigger `tr-โฆ` and then+ * cannot be read is a finding the store must not pretend is absent.+ */function parseTrigger(vault: string, fileName: string, now: Date): TriggerRecord | null {const path = join(triggersDir(vault), fileName);let raw: string;try {raw = readFileSync(path, "utf8");- } catch {- return null;+ } catch (err) {+ throw new TriggerFileError(path, (err as Error).message ?? String(err));}const [meta, body] = parseFrontmatterText(raw);- const id = meta["trigger_id"];- const kind = meta["trigger_type"];- const status = meta["status"];- const urgency = meta["urgency"];- if (typeof id !== "string" || id === "") return null;- if (typeof kind !== "string" || !isTriggerKind(kind)) return null;- if (typeof status !== "string" || !isTriggerStatus(status)) return null;- if (typeof urgency !== "string" || !isTriggerUrgency(urgency)) return null;- const createdAt = typeof meta["created_at"] === "string" ? meta["created_at"] : "";- const expiresAt = typeof meta["expires_at"] === "string" ? meta["expires_at"] : "";+ const id = meta[TRIGGER_KEY.id];+ if (id === undefined) return null;+ if (typeof id !== "string" || id === "") {+ throw new TriggerFieldError(path, TRIGGER_KEY.id, presentButUnreadable("not an id", id));+ }+ const kind = meta[TRIGGER_KEY.kind];+ if (typeof kind !== "string" || !isTriggerKind(kind)) {+ throw new TriggerFieldError(+ path,+ TRIGGER_KEY.kind,+ presentButUnreadable(`not one of ${TRIGGER_KINDS.join(", ")}`, kind),+ );+ }+ const status = meta[TRIGGER_KEY.status];+ if (typeof status !== "string" || !isTriggerStatus(status)) {+ throw new TriggerFieldError(+ path,+ TRIGGER_KEY.status,+ presentButUnreadable(`not one of ${TRIGGER_STATUSES.join(", ")}`, status),+ );+ }+ const urgency = meta[TRIGGER_KEY.urgency];+ if (typeof urgency !== "string" || !isTriggerUrgency(urgency)) {+ throw new TriggerFieldError(+ path,+ TRIGGER_KEY.urgency,+ presentButUnreadable(`not one of ${TRIGGER_URGENCIES.join(", ")}`, urgency),+ );+ }+ const createdAt = parseCreatedAt(meta[TRIGGER_KEY.createdAt], path);+ const expiresAt = textOrEmpty(meta[TRIGGER_KEY.expiresAt]);+ const suppressedFrom = meta[TRIGGER_KEY.suppressedFrom];return Object.freeze({id,kind,@@ -150,7 +447,7 @@ function parseTrigger(vault: string, fileName: string, now: Date): TriggerRecordurgency,reason: sectionText(body, "Reason"),suggestedAction: sectionText(body, "Suggested action"),- sourceArtifacts: parseJsonArray(meta["source_artifacts"]),+ sourceArtifacts: parseArtifactList(meta[TRIGGER_KEY.sourceArtifacts], path),contextSnippets: Object.freeze(sectionText(body, "Context").split("\n")@@ -158,11 +455,15 @@ function parseTrigger(vault: string, fileName: string, now: Date): TriggerRecord.filter((line) => line.startsWith("- ")).map((line) => line.slice(2)),),- cooldownKey: typeof meta["cooldown_key"] === "string" ? meta["cooldown_key"] : "",+ cooldownKey: textOrEmpty(meta[TRIGGER_KEY.cooldownKey]),createdAt,expiresAt,- deliveredAt: typeof meta["delivered_at"] === "string" ? meta["delivered_at"] : null,- resolvedAt: typeof meta["resolved_at"] === "string" ? meta["resolved_at"] : null,+ deliveredAt: textOrNull(meta[TRIGGER_KEY.deliveredAt]),+ resolvedAt: textOrNull(meta[TRIGGER_KEY.resolvedAt]),+ suppressedAt: textOrNull(meta[TRIGGER_KEY.suppressedAt]),+ suppressedFrom: isTriggerStatus(suppressedFrom) ? suppressedFrom : null,+ occurrences: parseOccurrences(meta[TRIGGER_KEY.occurrences], path),+ lastSeenAt: parseLastSeenAt(meta[TRIGGER_KEY.lastSeenAt], createdAt, path),path,});}@@ -180,17 +481,84 @@ export interface ListTriggersOptions {readonly status?: TriggerStatus;}-/** Every trigger, newest first (created_at desc, then id). */-export function listTriggers(- vault: string,- opts: ListTriggersOptions,-): ReadonlyArray<TriggerRecord> {+/**+ * One record in the queue that could not be read, ready to be named.+ *+ * It exists so that "the queue holds nothing" and "the queue holds+ * something this process cannot read" are different answers at every+ * boundary above the store. Surfaces project it with+ * {@link unreadableTriggerJson} or render it with+ * {@link renderTriggerQueueFailures}.+ */+export interface UnreadableTrigger {+ /** The file the unreadable record lives in. */+ readonly path: string;+ /**+ * The frontmatter key at fault, or `null` when the file itself could+ * not be read and so no single field can be blamed.+ */+ readonly key: string | null;+ /** The refusal, whose message already names the file and the key. */+ readonly error: Error;+}++/** The trigger directory split into what could be read and what could not. */+export interface TriggerScan {+ /** Readable records, newest first (created_at desc, then id). */+ readonly records: ReadonlyArray<TriggerRecord>;+ /** Records that named themselves and then failed to parse, by path. */+ readonly unreadable: ReadonlyArray<UnreadableTrigger>;+}++const EMPTY_SCAN: TriggerScan = Object.freeze({+ records: Object.freeze([]),+ unreadable: Object.freeze([]),+});++/** Describe a per-record refusal, or `null` for anything else. */+function asUnreadable(err: unknown): UnreadableTrigger | null {+ if (err instanceof TriggerFieldError) {+ return Object.freeze({ path: err.path, key: err.key, error: err });+ }+ if (err instanceof TriggerFileError) {+ return Object.freeze({ path: err.path, key: null, error: err });+ }+ return null;+}++/**+ * Read the whole trigger directory, keeping a broken record's blast+ * radius to itself.+ *+ * This is the reader every surface goes through. A refusal from one file+ * is caught here and reported in {@link TriggerScan.unreadable} next to+ * the records that read cleanly, which is what lets an operator see a+ * healthy trigger - and dismiss or suppress it - while a hand-edited+ * sibling is still broken. Anything that is not a per-record refusal+ * propagates: a bug in this module must not be filed against the+ * operator's file.+ *+ * The status filter applies to the readable records only. An unreadable+ * record has no status to compare, and dropping it from a filtered view+ * would hide it exactly where a caller is most likely to conclude the+ * queue is empty.+ */+export function readTriggers(vault: string, opts: ListTriggersOptions): TriggerScan {const dir = triggersDir(vault);- if (!existsSync(dir)) return Object.freeze([]);+ if (!existsSync(dir)) return EMPTY_SCAN;const records: TriggerRecord[] = [];+ const unreadable: UnreadableTrigger[] = [];for (const name of readdirSync(dir)) {- if (!name.endsWith(".md")) continue;- const record = parseTrigger(vault, name, opts.now);+ if (!name.endsWith(TRIGGER_FILE_EXT)) continue;+ let record: TriggerRecord | null;+ try {+ record = parseTrigger(vault, name, opts.now);+ } catch (err) {+ const entry = asUnreadable(err);+ if (entry === null) throw err;+ unreadable.push(entry);+ continue;+ }if (record === null) continue;if (opts.status !== undefined && record.effectiveStatus !== opts.status) continue;records.push(record);@@ -199,7 +567,96 @@ export function listTriggers(if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;});- return Object.freeze(records);+ unreadable.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ return Object.freeze({ records: Object.freeze(records), unreadable: Object.freeze(unreadable) });+}++/**+ * Every trigger, newest first, or a refusal if any record is unreadable.+ *+ * The all-or-nothing view, for a caller that has no way to report a+ * partial one and must not act on it silently. It never drops a record:+ * an unreadable file surfaces as the original refusal, naming the file+ * and the field. Surfaces that report to an operator use+ * {@link readTriggers} instead, so one broken record does not deny them+ * the rest of the queue.+ */+export function listTriggers(+ vault: string,+ opts: ListTriggersOptions,+): ReadonlyArray<TriggerRecord> {+ const scan = readTriggers(vault, opts);+ const [first] = scan.unreadable;+ if (first !== undefined) throw first.error;+ return scan.records;+}++/** Envelope projection of one unreadable record. */+export function unreadableTriggerJson(entry: UnreadableTrigger): Record<string, unknown> {+ return { path: entry.path, key: entry.key, error: entry.error.message };+}++/** Heading of the block naming records the store could not read. */+export const UNREADABLE_TRIGGERS_HEADING = "## Unreadable triggers";++/** Heading of the block reporting that the queue could not be read at all. */+export const TRIGGER_QUEUE_UNREADABLE_HEADING = "## Trigger queue unreadable";++/** What a surface could not read about the trigger queue. */+export interface TriggerQueueFailures {+ /** Records that named themselves and could not be parsed. */+ readonly unreadable: ReadonlyArray<UnreadableTrigger>;+ /** Why the queue could not be read at all, or `null` when it was read. */+ readonly queueError: string | null;+}++/**+ * Everything a surface could not read about the queue, in one read.+ *+ * A per-record refusal lands in `unreadable`; a read that fails outright+ * - a vault that is not there, a directory that cannot be listed -+ * becomes `queueError`. Either way the caller has something to say, which+ * is the point: "the queue is empty" must never be the answer to "the+ * queue could not be read".+ */+export function readTriggerQueueFailures(vault: string, now: Date): TriggerQueueFailures {+ try {+ return Object.freeze({+ unreadable: readTriggers(vault, { now }).unreadable,+ queueError: null,+ });+ } catch (err) {+ return Object.freeze({+ unreadable: Object.freeze([]),+ queueError: (err as Error).message ?? String(err),+ });+ }+}++/**+ * The Markdown block a brief appends so an unreadable queue is never+ * rendered as an empty one.+ *+ * Returns "" only when there is genuinely nothing to report, which is+ * what lets a caller append it unconditionally: the pending-trigger+ * section being absent then means the queue was read and held nothing,+ * and that is the whole point of the block existing.+ */+export function renderTriggerQueueFailures(failures: TriggerQueueFailures): string {+ const blocks: string[] = [];+ if (failures.queueError !== null) {+ blocks.push([TRIGGER_QUEUE_UNREADABLE_HEADING, "", failures.queueError].join("\n"));+ }+ if (failures.unreadable.length > 0) {+ blocks.push(+ [+ UNREADABLE_TRIGGERS_HEADING,+ "",+ ...failures.unreadable.map((entry) => `- ${entry.error.message}`),+ ].join("\n"),+ );+ }+ return blocks.join("\n\n");}// โโ Creation with cooldown dedup โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ@@ -214,29 +671,103 @@ export interface CreateTriggersOptions {readonly maxPerKind?: number;}+/**+ * One candidate that produced no new trigger, and why.+ *+ * `invalid` - the candidate named no cooldown key or no reason.+ * `duplicate` - a candidate earlier in the SAME scan already claimed+ * this cooldown key; one scan seeing one finding twice is one+ * occurrence, so this reason never writes to the ledger.+ * `active` / `cooldown` / `suppressed` - an existing record blocked it,+ * and that record's ledger records the recurrence.+ * `kind-cap` - the per-kind budget for this scan was already spent.+ */export interface SkippedCandidate {readonly cooldownKey: string;- readonly reason: "active" | "cooldown" | "kind-cap" | "invalid";+ readonly reason: "active" | "cooldown" | "duplicate" | "kind-cap" | "invalid" | "suppressed";}export interface CreateTriggersResult {readonly created: ReadonlyArray<TriggerRecord>;readonly skipped: ReadonlyArray<SkippedCandidate>;+ /**+ * Records already in the queue that could not be read. A scan proceeds+ * around them - one broken file must not cost a run all of its new+ * findings - and names them here so the run is not reported as clean.+ */+ readonly unreadable: ReadonlyArray<UnreadableTrigger>;}function blockReason(twin: TriggerRecord,now: Date,cooldownDays: number,-): "active" | "cooldown" | null {- if (OPEN_STATUSES.has(twin.effectiveStatus)) return "active";- if (twin.effectiveStatus === "expired") return null;+): SkippedCandidate["reason"] | null {+ // Suppression comes first and carries no clock: the operator judged+ // this cooldown key structurally benign, so no arithmetic below can+ // ever let it back through.+ if (twin.effectiveStatus === TRIGGER_STATUS.suppressed) return "suppressed";+ if (TRIGGER_OPEN_STATUSES.has(twin.effectiveStatus)) return "active";+ if (twin.effectiveStatus === TRIGGER_STATUS.expired) return null;// dismissed / acted: silent for the cooldown window after resolution.const resolved = twin.resolvedAt !== null ? Date.parse(twin.resolvedAt) : Number.NaN;if (!Number.isFinite(resolved)) return null;return now.getTime() < resolved + cooldownDays * DAY_MS ? "cooldown" : null;}+/**+ * Record that a finding fired again while the queue stayed silent.+ *+ * Written for every candidate an existing record silenced, whatever+ * silenced it - suppression, an open twin, a cooldown window, or the+ * per-kind cap - because the event worth keeping is "the finding fired+ * and nothing surfaced", and the reason it did not surface changes+ * nothing about that. Without it a suppressed finding that recurs daily+ * is indistinguishable from one that never fired again.+ *+ * A candidate silenced when NO record exists for its cooldown key has no+ * ledger to write to and is reported in+ * {@link CreateTriggersResult.skipped} alone; a second candidate on one+ * key inside one scan is one occurrence and is not counted twice.+ *+ * Callers must hold the trigger-directory lock. Every writer in this+ * module takes it - {@link createTriggers}, {@link transitionTrigger} and+ * {@link markTriggersDelivered} - which is what makes the counter+ * race-free: each of them writes the WHOLE record from a snapshot read+ * inside the lock, so no pair of them can interleave and lose the other's+ * increment.+ */+export function recordRecurrence(record: TriggerRecord, now: Date): TriggerRecord {+ const next: TriggerRecord = Object.freeze({+ ...record,+ occurrences: record.occurrences + 1,+ lastSeenAt: now.toISOString(),+ });+ writeRecord(next);+ return next;+}++/**+ * Run one read-then-write pass over the trigger directory under its lock.+ *+ * Every writer here goes through this. Without it two callers (the CLI+ * and the MCP server can both reach the store) could each observe "no+ * twin" and persist duplicates for one cooldown key, and - because each+ * writer persists the WHOLE record, recurrence ledger included - a scan+ * interleaving with a transition or a brief delivery would silently drop+ * whichever increment landed first.+ */+function withTriggerDirLock<T>(vault: string, body: () => T): T {+ const dir = triggersDir(vault);+ mkdirSync(dir, { recursive: true });+ const release = lockfile.lockSync(dir, { stale: TRIGGER_LOCK_STALE_MS, realpath: false });+ try {+ return body();+ } finally {+ release();+ }+}+/** Persist candidates as triggers, skipping cooldown-blocked twins. */export function createTriggers(vault: string,@@ -245,17 +776,7 @@ export function createTriggers(): 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.- const dir = triggersDir(vault);- mkdirSync(dir, { recursive: true });- const release = lockfile.lockSync(dir, { stale: 10_000, realpath: false });- try {- return createTriggersLocked(vault, candidates, opts);- } finally {- release();- }+ return withTriggerDirLock(vault, () => createTriggersLocked(vault, candidates, opts));}function createTriggersLocked(@@ -266,9 +787,9 @@ function createTriggersLocked(const cooldownDays = opts.cooldownDays ?? TRIGGER_COOLDOWN_DAYS;const ttlDays = opts.ttlDays ?? TRIGGER_TTL_DAYS;const maxPerKind = opts.maxPerKind ?? TRIGGER_MAX_PER_KIND;- const existing = listTriggers(vault, { now: opts.now });+ const scan = readTriggers(vault, { now: opts.now });const byKey = new Map<string, TriggerRecord>();- for (const record of existing) {+ for (const record of scan.records) {// Newest record per key wins (list is newest-first, keep the first).if (!byKey.has(record.cooldownKey)) byKey.set(record.cooldownKey, record);}@@ -279,73 +800,123 @@ function createTriggersLocked(const dir = triggersDir(vault);const createdAt = opts.now.toISOString();const expiresAt = new Date(opts.now.getTime() + ttlDays * DAY_MS).toISOString();- const usedKeys = new Set<string>();+ const seenKeys = new Set<string>();for (const candidate of candidates) {if (candidate.cooldownKey.trim() === "" || candidate.reason.trim() === "") {skipped.push({ cooldownKey: candidate.cooldownKey, reason: "invalid" });continue;}- if (usedKeys.has(candidate.cooldownKey)) {- skipped.push({ cooldownKey: candidate.cooldownKey, reason: "active" });+ // One scan observing one finding twice is ONE occurrence, so the+ // duplicate is recognised before anything reaches the ledger -+ // whether or not a record already exists for the key.+ if (seenKeys.has(candidate.cooldownKey)) {+ skipped.push({ cooldownKey: candidate.cooldownKey, reason: "duplicate" });continue;}+ seenKeys.add(candidate.cooldownKey);const twin = byKey.get(candidate.cooldownKey);if (twin !== undefined) {const reason = blockReason(twin, opts.now, cooldownDays);if (reason !== null) {+ recordRecurrence(twin, opts.now);skipped.push({ cooldownKey: candidate.cooldownKey, reason });continue;}}const count = perKind.get(candidate.kind) ?? 0;if (count >= maxPerKind) {+ // The cap is a budget, not a judgement about the finding: it fired+ // and nothing surfaced, so when a record of it exists the ledger+ // gets the occurrence. When none does there is nothing to write to+ // and `skipped` is the whole report.+ if (twin !== undefined) recordRecurrence(twin, opts.now);skipped.push({ cooldownKey: candidate.cooldownKey, reason: "kind-cap" });continue;}perKind.set(candidate.kind, count + 1);- usedKeys.add(candidate.cooldownKey);const hash = createHash("sha256").update(candidate.cooldownKey).digest("hex").slice(0, 10);let id = `tr-${hash}-${createdAt.slice(0, 10)}`;let suffix = 2;- while (existsSync(join(dir, `${id}.md`))) {+ while (existsSync(join(dir, `${id}${TRIGGER_FILE_EXT}`))) {id = `tr-${hash}-${createdAt.slice(0, 10)}-${suffix}`;suffix += 1;}const record: TriggerRecord = Object.freeze({...candidate,id,- status: "pending" as const,- effectiveStatus: "pending" as const,+ status: TRIGGER_STATUS.pending,+ effectiveStatus: TRIGGER_STATUS.pending,createdAt,expiresAt,deliveredAt: null,resolvedAt: null,- path: join(dir, `${id}.md`),+ suppressedAt: null,+ suppressedFrom: null,+ // Creating the record IS the first recorded occurrence.+ occurrences: OCCURRENCES_WHEN_UNRECORDED,+ lastSeenAt: createdAt,+ path: join(dir, `${id}${TRIGGER_FILE_EXT}`),});writeRecord(record);created.push(record);}- return Object.freeze({ created: Object.freeze(created), skipped: Object.freeze(skipped) });+ return Object.freeze({+ created: Object.freeze(created),+ skipped: Object.freeze(skipped),+ unreadable: scan.unreadable,+ });}// โโ Transitions โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ-export type TriggerAction = "acknowledge" | "dismiss" | "act";+export type TriggerAction = "acknowledge" | "dismiss" | "act" | "suppress" | "unsuppress";export interface TransitionOptions {readonly now: Date;}-const ACTION_TO_STATUS: Record<TriggerAction, TriggerStatus> = {- acknowledge: "acknowledged",- dismiss: "dismissed",- act: "acted",+/**+ * Actions whose target status is fixed. `unsuppress` is absent because+ * its target is whatever status suppression interrupted, which is read+ * off the record rather than looked up here.+ */+/**+ * Refuse an id no readable record carries.+ *+ * When part of the queue is unreadable the refusal says so and names the+ * broken records: "no such trigger" would otherwise assert that the+ * finding is not there, when in truth the store could not look.+ */+function unknownTriggerError(id: string, unreadable: ReadonlyArray<UnreadableTrigger>): Error {+ if (unreadable.length === 0) return new Error(`unknown trigger: ${id}`);+ return new Error(+ `unknown trigger: ${id} - and ${unreadable.length} record(s) in the queue could not be read, ` ++ `so the id may belong to one of them: ${unreadable.map((u) => u.error.message).join("; ")}`,+ );+}++const ACTION_TO_STATUS: Record<Exclude<TriggerAction, "unsuppress">, TriggerStatus> = {+ acknowledge: TRIGGER_STATUS.acknowledged,+ dismiss: TRIGGER_STATUS.dismissed,+ act: TRIGGER_STATUS.acted,+ suppress: TRIGGER_STATUS.suppressed,};-/** Apply one lifecycle transition. Throws on unknown id or terminal state. */+/**+ * Apply one lifecycle transition. Throws on an unknown id, on a terminal+ * state for acknowledge / dismiss / act, and on `unsuppress` against+ * anything that is not suppressed.+ *+ * An unreadable sibling never blocks the transition: the operator's way+ * out of a broken queue is to dismiss or suppress the records that still+ * read, so the target is looked up among those. It does colour the+ * unknown-id refusal, because the requested id may well belong to a+ * record nobody could parse and "unknown" alone would be a claim the+ * store cannot support.+ */export function transitionTrigger(vault: string,id: string,@@ -354,15 +925,29 @@ export function transitionTrigger(): 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)) {+ return withTriggerDirLock(vault, () => transitionTriggerLocked(vault, id, action, opts));+}++function transitionTriggerLocked(+ vault: string,+ id: string,+ action: TriggerAction,+ opts: TransitionOptions,+): TriggerRecord {+ const scan = readTriggers(vault, { now: opts.now });+ const record = scan.records.find((r) => r.id === id);+ if (record === undefined) throw unknownTriggerError(id, scan.unreadable);+ const nowIso = opts.now.toISOString();++ if (action === "suppress") return suppress(record, nowIso);+ if (action === "unsuppress") return unsuppress(record, opts.now);++ if (TRIGGER_TERMINAL_STATUSES.has(record.effectiveStatus)) {throw new Error(`trigger ${id} is terminal (${record.effectiveStatus})`);}- if (action === "acknowledge" && record.effectiveStatus === "acknowledged") {+ if (action === "acknowledge" && record.effectiveStatus === TRIGGER_STATUS.acknowledged) {return record; // idempotent}- const nowIso = opts.now.toISOString();const next: TriggerRecord = Object.freeze({...record,status: ACTION_TO_STATUS[action],@@ -373,7 +958,68 @@ export function transitionTrigger(return next;}-/** Stamp delivered_at + status=delivered on the given pending triggers. */+/**+ * Silence a cooldown key indefinitely.+ *+ * Legal from ANY status - "never surface this again" is a meaningful+ * judgement about an expired or already-acted finding too, because what+ * it silences is the key, not the record. The delivery and resolution+ * instants are deliberately left untouched: that is what makes+ * {@link unsuppress} an exact restore rather than a reconstruction.+ */+function suppress(record: TriggerRecord, nowIso: string): TriggerRecord {+ if (record.effectiveStatus === TRIGGER_STATUS.suppressed) return record; // idempotent+ const next: TriggerRecord = Object.freeze({+ ...record,+ status: TRIGGER_STATUS.suppressed,+ effectiveStatus: TRIGGER_STATUS.suppressed,+ suppressedAt: nowIso,+ suppressedFrom: record.status,+ });+ writeRecord(next);+ return next;+}++/**+ * Undo a suppression, restoring the status it interrupted.+ *+ * The stored status is restored, not the effective one, so a trigger+ * suppressed while its TTL had already lapsed goes back to reading as+ * expired on the next read exactly as it did before.+ */+function unsuppress(record: TriggerRecord, now: Date): TriggerRecord {+ if (record.effectiveStatus !== TRIGGER_STATUS.suppressed) {+ throw new Error(`trigger ${record.id} is not suppressed (${record.effectiveStatus})`);+ }+ if (record.suppressedFrom === null) {+ // Never default to pending: that would invent a lifecycle position+ // and, for a formerly dismissed finding, silently restart its+ // cooldown from nothing.+ throw new Error(+ `trigger ${record.id} is suppressed but carries no suppressed_from; ` ++ "restore the field or dismiss the trigger instead",+ );+ }+ const restored = record.suppressedFrom;+ const next: TriggerRecord = Object.freeze({+ ...record,+ status: restored,+ effectiveStatus: effectiveStatus(restored, record.expiresAt, now),+ suppressedAt: null,+ suppressedFrom: null,+ });+ writeRecord(next);+ return next;+}++/**+ * Stamp delivered_at + status=delivered on the given pending triggers.+ *+ * The ids come from a brief that has just been rendered, so they name+ * records that read cleanly; an unreadable sibling is irrelevant here and+ * must not deny the delivery stamp to the triggers the operator was in+ * fact shown.+ */export function markTriggersDelivered(vault: string,ids: ReadonlyArray<string>,@@ -382,16 +1028,29 @@ export function markTriggersDelivered(if (ids.length === 0) return;// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);+ withTriggerDirLock(vault, () => markTriggersDeliveredLocked(vault, ids, opts));+}++function markTriggersDeliveredLocked(+ vault: string,+ ids: ReadonlyArray<string>,+ opts: TransitionOptions,+): void {const wanted = new Set(ids);const nowIso = opts.now.toISOString();- for (const record of listTriggers(vault, { now: opts.now })) {+ for (const record of readTriggers(vault, { now: opts.now }).records) {if (!wanted.has(record.id)) continue;- if (record.effectiveStatus !== "pending" && record.effectiveStatus !== "delivered") continue;+ if (+ record.effectiveStatus !== TRIGGER_STATUS.pending &&+ record.effectiveStatus !== TRIGGER_STATUS.delivered+ ) {+ continue;+ }writeRecord(Object.freeze({...record,- status: "delivered" as const,- effectiveStatus: "delivered" as const,+ status: TRIGGER_STATUS.delivered,+ effectiveStatus: TRIGGER_STATUS.delivered,deliveredAt: nowIso,}),);@@ -414,14 +1073,25 @@ const URGENCY_RANK: Record<string, number> = Object.fromEntries(* Triggers the morning brief may surface NOW: pending ones, plus* delivered-but-still-open ones whose last delivery is older than the* cooldown window. Ranked urgency desc, then newest first, capped.+ *+ * Eligibility is an allow-list of two statuses, so a suppressed trigger+ * is excluded by the same rule that excludes a dismissed one - no+ * suppression-specific branch exists or is needed here.+ *+ * Only readable records can be ranked, so an unreadable one is neither+ * surfaced nor allowed to empty the section. Naming it is the caller's+ * job: a brief surface reads {@link readTriggers} for+ * {@link TriggerScan.unreadable} and renders it with+ * {@link renderTriggerQueueFailures}, so an unreadable queue is never+ * shown as an empty one.*/export function briefTriggers(vault: string,opts: BriefTriggersOptions,): ReadonlyArray<TriggerRecord> {- const eligible = listTriggers(vault, { now: opts.now }).filter((record) => {- if (record.effectiveStatus === "pending") return true;- if (record.effectiveStatus !== "delivered") return false;+ const eligible = readTriggers(vault, { now: opts.now }).records.filter((record) => {+ if (record.effectiveStatus === TRIGGER_STATUS.pending) return true;+ if (record.effectiveStatus !== TRIGGER_STATUS.delivered) return false;const delivered = record.deliveredAt !== null ? Date.parse(record.deliveredAt) : Number.NaN;if (!Number.isFinite(delivered)) return true;return opts.now.getTime() >= delivered + opts.cooldownDays * DAY_MS;diff --git a/src/core/brain/triggers/types.ts b/src/core/brain/triggers/types.tsindex 57d93c3c..c17bba81 100644--- a/src/core/brain/triggers/types.ts+++ b/src/core/brain/triggers/types.ts@@ -7,20 +7,71 @@* trigger store is its single consumer (Kernel B of the suite).*/-export const TRIGGER_STATUSES = [- "pending",- "delivered",- "acknowledged",- "acted",- "dismissed",- "expired",-] as const;-export type TriggerStatus = (typeof TRIGGER_STATUSES)[number];+/**+ * Lifecycle states of one trigger.+ *+ * `suppressed` is the operator's judgement that a finding is+ * structurally benign: unlike `dismissed` and `acted` it carries no+ * clock, so the cooldown key stays silent until somebody unsuppresses+ * it. It is a member of {@link TRIGGER_TERMINAL_STATUSES}, and that+ * membership - not a branch anywhere - is what hides it from `list` and+ * shows it in `history`.+ */+export const TRIGGER_STATUS = Object.freeze({+ pending: "pending",+ delivered: "delivered",+ acknowledged: "acknowledged",+ acted: "acted",+ dismissed: "dismissed",+ expired: "expired",+ suppressed: "suppressed",+} as const);++export type TriggerStatus = (typeof TRIGGER_STATUS)[keyof typeof TRIGGER_STATUS];-export function isTriggerStatus(value: string): value is TriggerStatus {- return (TRIGGER_STATUSES as ReadonlyArray<string>).includes(value);+/**+ * The statuses in lifecycle order. The single source every schema, enum+ * and filter reads from - a literal copy of this list in a tool schema+ * is exactly the drift the vocabulary census exists to catch.+ */+export const TRIGGER_STATUSES: ReadonlyArray<TriggerStatus> = Object.freeze([+ TRIGGER_STATUS.pending,+ TRIGGER_STATUS.delivered,+ TRIGGER_STATUS.acknowledged,+ TRIGGER_STATUS.acted,+ TRIGGER_STATUS.dismissed,+ TRIGGER_STATUS.expired,+ TRIGGER_STATUS.suppressed,+]);++export function isTriggerStatus(value: unknown): value is TriggerStatus {+ return typeof value === "string" && (TRIGGER_STATUSES as ReadonlyArray<string>).includes(value);}+/**+ * Statuses a trigger can still move out of on its own. Expiry is applied+ * to these and only these, which is what makes `suppressed` indefinite+ * without any code saying so.+ */+export const TRIGGER_OPEN_STATUSES: ReadonlySet<TriggerStatus> = new Set([+ TRIGGER_STATUS.pending,+ TRIGGER_STATUS.delivered,+ TRIGGER_STATUS.acknowledged,+]);++/**+ * Statuses that end the trigger's own lifecycle. Every reader that hides+ * finished work from `list` and shows it in `history` partitions on this+ * set; the three hand-maintained copies it replaced (core, CLI, MCP)+ * could each drift from the others without a single test noticing.+ */+export const TRIGGER_TERMINAL_STATUSES: ReadonlySet<TriggerStatus> = new Set([+ TRIGGER_STATUS.acted,+ TRIGGER_STATUS.dismissed,+ TRIGGER_STATUS.expired,+ TRIGGER_STATUS.suppressed,+]);+export const TRIGGER_URGENCIES = ["low", "medium", "high"] as const;export type TriggerUrgency = (typeof TRIGGER_URGENCIES)[number];@@ -78,5 +129,31 @@ export interface TriggerRecord extends InsightCandidate {readonly deliveredAt: string | null;/** Timestamp of the terminal transition (acknowledge counts as open). */readonly resolvedAt: string | null;+ /** When the trigger was suppressed, or `null` while it is not. */+ readonly suppressedAt: string | null;+ /**+ * The status suppression interrupted, restored verbatim by+ * `unsuppress`. `null` while the trigger is not suppressed. A+ * suppressed record that lacks it has been hand-edited, and the+ * restore refuses rather than guessing a prior state.+ */+ readonly suppressedFrom: TriggerStatus | null;+ /**+ * How many times this finding has been observed: once when the trigger+ * was created, plus once for every later SCAN in which the finding+ * fired and this record is why nothing surfaced. One scan seeing the+ * same finding twice counts once, so this is a count of scans rather+ * than of candidates. A record written before the ledger existed+ * carries no count and reads as `1`, which is the true number of+ * occurrences anyone recorded for it - not a default standing in for+ * an unknown.+ */+ readonly occurrences: number;+ /**+ * When the finding last fired, whether or not anything was surfaced.+ * A record written before the ledger existed reads as its creation+ * instant, which is the last occurrence anyone recorded.+ */+ readonly lastSeenAt: string;readonly path: string;}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 3342a768..f696db11 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -160,8 +160,9 @@ export type BrainApplyOutcome = (typeof BRAIN_APPLY_OUTCOME)[keyof typeof BRAIN_* `reject` / `promote` / `retire` record the corresponding state* transitions; `noted-redundant` records same-sign signals collapsed onto* an active pref; `skip-corrupted-frontmatter` records files dream- * skipped; `pin` / `unpin` record protected-set changes; `rollback`- * records a snapshot restore. See ยง5.5 and ยง7.4 of the design doc.+ * skipped; `pin` / `unpin` record protected-set changes; `snapshot` and+ * `rollback` record the two ends of one recovery: the point being taken+ * and the restore back to it. See ยง5.5 and ยง7.4 of the design doc.*/export const BRAIN_LOG_EVENT_KIND = {dream: "dream",@@ -176,6 +177,19 @@ export const BRAIN_LOG_EVENT_KIND = {pin: "pin",unpin: "unpin",rollback: "rollback",+ /**+ * `snapshot` (silence-is-not-an-answer, U7) - a recovery point was+ * written to `Brain/.snapshots/`. This is the counterpart the log has+ * been missing since `rollback` shipped: the restore was recorded and+ * the point it restores to was not, so the only trace a recovery point+ * left was a file with an opaque name and an mtime. Payload carries the+ * `run_id`, the {@link BRAIN_SNAPSHOT_REASON} member that explains why+ * the point was taken, and the archive `size_bytes`. Emitted+ * best-effort: a log-append failure never fails the snapshot, because+ * the archive is the load-bearing artifact and the destructive+ * operation it guards must not be aborted over an audit line.+ */+ snapshot: "snapshot",/*** `signal-suppressed` โ a fresh signal landed on a topic that the* user explicitly retired via `o2b brain reject <pref> --reason`.@@ -509,6 +523,89 @@ export function isBrainLogEventKind(value: string): value is BrainLogEventKind {return BRAIN_LOG_EVENT_KIND_SET.has(value);}+/**+ * Why a recovery point was taken (silence-is-not-an-answer, U7).+ *+ * The snapshot family is the only revertible history this project has,+ * and until now every entry in it was an opaque run id plus an mtime. The+ * reasons existed de facto - as run-id PREFIXES at five call sites, three+ * of them inline string literals - and nothing parsed them back, so an+ * operator could not ask which recovery point covers a given boundary or+ * filter the revertible history by why it happened. This is that axis,+ * made first-class: written into the manifest sidecar, read back by the+ * listing, and never inferred from the run id.+ *+ * ## Why members nothing writes yet are not dead code+ *+ * FOUR MEMBERS HAVE NO PRODUCER IN THIS RELEASE: `session-boundary`,+ * `plan-boundary`, `decision-boundary` and `manual`. Snapshots at those+ * three seams are DEFERRED on purpose - it changes how often snapshots+ * happen, which interacts with retention and with the optional+ * derived-store archive, and that is a frequency change worth measuring+ * before it ships. `manual` is deferred for a different reason: nothing+ * takes a recovery point on demand. No CLI verb and no MCP tool does, and+ * `takeSnapshot` is reached only by the destructive-operation gate, so+ * `manual` is a reason a later release (or a peer already running one)+ * may write, not one this build can produce.+ *+ * All four are declared here anyway because `.snapshots/` rides the same+ * peer-to-peer replication as the rest of the vault: a later release+ * writing one of these reasons produces sidecars that THIS build must+ * still read, and a guard that rejected them would fail the manifest+ * closed and lose drift detection on exactly those snapshots. The read+ * side is the whole point, and it is why `snapshot log --reason` accepts+ * a producer-less member and honestly lists nothing for it rather than+ * rejecting the filter.+ *+ * The strings are the run-id prefixes already on disk, deliberately: an+ * operator reading `.snapshots/` and an operator reading the log see one+ * vocabulary rather than two spellings of it.+ */+export const BRAIN_SNAPSHOT_REASON = Object.freeze({+ /** Pre-consolidation point taken by the dream pass. */+ dream: "dream",+ /** Pre-apply point taken before release-owned files are rewritten. */+ upgrade: "upgrade",+ /** Pre-write point taken before Claude Code memory is imported. */+ importClaudeMemory: "import-claude-memory",+ /** Pre-deletion point taken before a source's derived material is removed. */+ deleteBySource: "delete-by-source",+ /** Pre-prune point taken before malformed entity notes are deleted. */+ entityPrune: "entity-prune",+ /** Deferred: a session boundary. No producer in this release. */+ sessionBoundary: "session-boundary",+ /** Deferred: a plan boundary. No producer in this release. */+ planBoundary: "plan-boundary",+ /** Deferred: a decision boundary. No producer in this release. */+ decisionBoundary: "decision-boundary",+ /**+ * Deferred: an operator asking for a recovery point with no operation+ * behind it. No producer in this release - nothing takes a snapshot on+ * demand.+ */+ manual: "manual",+} as const);++/** Closed union over {@link BRAIN_SNAPSHOT_REASON}. */+export type BrainSnapshotReason =+ (typeof BRAIN_SNAPSHOT_REASON)[keyof typeof BRAIN_SNAPSHOT_REASON];++/** Membership list, in declaration order (producers first, deferred after). */+export const BRAIN_SNAPSHOT_REASONS: ReadonlyArray<BrainSnapshotReason> = Object.freeze(+ Object.values(BRAIN_SNAPSHOT_REASON),+);++/**+ * Narrow a string read back off a manifest sidecar written by any peer, or+ * supplied as a CLI filter value. `unknown` rather than `string` because+ * both of those inputs arrive as parsed JSON or an unvalidated flag.+ */+export function isBrainSnapshotReason(value: unknown): value is BrainSnapshotReason {+ return (+ typeof value === "string" && (BRAIN_SNAPSHOT_REASONS as ReadonlyArray<string>).includes(value)+ );+}+/*** Per-preference mutation audit op kinds (Brain lifecycle suite,* Feature 1). Captured at the mutation chokepoints. The reader@@ -990,6 +1087,19 @@ export interface BrainRollbackLogEvent extends BrainLogEventBase {readonly run_id: string;}+/**+ * `snapshot` entry โ a recovery point was written. The counterpart of+ * {@link BrainRollbackLogEvent}: the two together are what let an+ * operator walk from a logged event to the archive that would undo it.+ */+export interface BrainSnapshotLogEvent extends BrainLogEventBase {+ readonly kind: typeof BRAIN_LOG_EVENT_KIND.snapshot;+ readonly run_id: string;+ readonly reason: BrainSnapshotReason;+ /** Byte length of the archive as written. */+ readonly size_bytes: string;+}+/*** `scan-inline` entry โ operator ran `o2b brain scan-inline`. Payload* keys are counters: `scanned`, `found`, `created`, `deduped`,@@ -1078,6 +1188,7 @@ export type BrainLogEvent =| BrainSkipCorruptedLogEvent| BrainPinLogEvent| BrainRollbackLogEvent+ | BrainSnapshotLogEvent| BrainScanInlineLogEvent| BrainImportSessionLogEvent| BrainMergeLogEvent@@ -1189,6 +1300,19 @@ export interface BrainConfidenceConfig {export interface BrainSnapshotsConfig {/** Keep this many newest `.snapshots/*.tar.zst`. Positive integer. */readonly retention_count: number;+ /**+ * Cover the derived SQLite store as well as the Markdown tree.+ * Default OFF: what coverage protects is the embedding spend, not+ * information, and every retained archive is replicated to every peer.+ * See the `snapshot.ts` module header for the full cost argument.+ */+ readonly include_derived_store: boolean;+ /**+ * Refuse - never truncate - when the live derived store exceeds this+ * many bytes. Positive integer. Read together with `retention_count`:+ * the worst case on every peer is the two multiplied.+ */+ readonly derived_store_max_bytes: number;}/**@@ -1244,6 +1368,15 @@ export interface BrainActiveConfig {* policy.ts applies.*/readonly inject_budget_chars?: number;+ /**+ * Character cap for the operator-authored `Brain/standing-rules.md`+ * block. Separate from `inject_budget_chars` because the standing+ * block is EXEMPT from that budget: it is injected ahead of the memory+ * layer and never passes through the section budgeter, so the two+ * numbers govern different lanes. Absent means the+ * STANDING_RULES_MAX_CHARS_DEFAULT from standing-rules.ts applies.+ */+ readonly standing_rules_max_chars?: number;}/**@@ -1836,12 +1969,19 @@ export interface DoctorIssue {* byte-identical to what it was.*/readonly field?: string;- /** Wikilink target that resolves to nothing (`broken-wikilink`, `broken-backlinks`). */+ /**+ * The artifact a reference points at (`broken-wikilink`,+ * `broken-backlinks`), or the folded key of the state that changed+ * under its consumers (`stale-dependency`). In both readings it is+ * what the sources below name.+ */readonly target?: string;/**- * Basenames of the artifacts that reference {@link target}- * (`broken-backlinks`). The dangling target has no file, so the issue- * carries no `path`; these sources are what an operator can act on.+ * The things that reference {@link target}: artifact basenames for+ * `broken-backlinks`, where the dangling target has no file so the+ * issue carries no `path` and these are all an operator can act on;+ * consumer identities for `stale-dependency`, capped at that check's+ * per-state limit while the message carries the true total.*/readonly sources?: ReadonlyArray<string>;}diff --git a/src/core/brain/untrusted-source.ts b/src/core/brain/untrusted-source.tsindex 5c246f66..efbd2c10 100644--- a/src/core/brain/untrusted-source.ts+++ b/src/core/brain/untrusted-source.ts@@ -26,8 +26,7 @@* against the file), while the embedded body is the neutralized form.*/-import { createHash } from "node:crypto";-+import { sha256Hex } from "../integrity/digest.ts";import { canonicalNotePath } from "../path-safety.ts";/** The delimiter tag name. Exported so callers and tests share one source. */@@ -119,7 +118,7 @@ export interface UntrustedProvenance {*/export function wrapUntrustedSource(text: string, provenance: UntrustedProvenance): string {const path = canonicalNotePath(provenance.path);- const sha256 = createHash("sha256").update(text, "utf8").digest("hex");+ const sha256 = sha256Hex(text);const body = neutralizeUntrustedText(text);const open = `<${UNTRUSTED_SOURCE_TAG} path="${escapeAttribute(path)}" sha256="${sha256}">`;return `${open}\n${body}\n</${UNTRUSTED_SOURCE_TAG}>`;diff --git a/src/core/brain/upgrade.ts b/src/core/brain/upgrade.tsindex b4b1a4ed..fcbc601a 100644--- a/src/core/brain/upgrade.ts+++ b/src/core/brain/upgrade.ts@@ -29,7 +29,7 @@ import { DEFAULT_BRAIN_CONFIG_YAML } from "./config-template.ts";import { createSnapshot } from "./snapshot.ts";import { renderBrainManual } from "./templates.ts";import { isoSecond } from "./time.ts";-import { BRAIN_LOG_EVENT_KIND } from "./types.ts";+import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "./types.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";// ----- Public types --------------------------------------------------------@@ -155,8 +155,9 @@ export function applyUpgrade(}const now = opts.now ?? new Date();- const runId = `upgrade-${isoSecondCompact(now)}`;- const snap = createSnapshot(vault, runId);+ // One constant for the run-id prefix and the recorded reason.+ const runId = `${BRAIN_SNAPSHOT_REASON.upgrade}-${isoSecondCompact(now)}`;+ const snap = createSnapshot(vault, runId, { reason: BRAIN_SNAPSHOT_REASON.upgrade, now });const updated: string[] = [];for (const file of plan.files) {diff --git a/src/core/brain/vault-instruction-file.ts b/src/core/brain/vault-instruction-file.tsindex 17b18537..949b2fd7 100644--- a/src/core/brain/vault-instruction-file.ts+++ b/src/core/brain/vault-instruction-file.ts@@ -32,9 +32,17 @@ export interface VaultInstructionEntry {* `link_graph.vault_instruction_file` config slot (or `VAULT.md`* when not configured). Caller may override by passing `name`.*- * Returns `null` when the file is absent. Throws on a relative- * path that escapes the vault or an absolute-path name (we never- * resolve outside the vault root).+ * Returns `null` when the file is absent, or when it is present but+ * refused by one of the boundary guards below (a symlink, a path that+ * resolves outside the vault, something that is not a regular file) -+ * in each of those cases the operator named something this reader will+ * not treat as an instruction file.+ *+ * Throws on a relative path that escapes the vault, an absolute-path+ * name, an empty name, and on a file that EXISTS but cannot be read.+ * The last one used to return `null` as well, which made an unreadable+ * instruction file indistinguishable from a vault that has none: the+ * field vanished from `brain_context` and the operator was told nothing.*/export function readVaultInstructionFile(vault: string,@@ -72,8 +80,14 @@ export function readVaultInstructionFile(const st = statSync(fullReal);if (!st.isFile()) return null;content = readFileSync(fullReal, "utf8");- } catch {- return null;+ } catch (err) {+ // `existsSync` already said the file is there, so this is a failure+ // to read it rather than an absence. Reporting it as `null` would+ // put a permission error and an empty vault on the same wire.+ throw new Error(+ `vault instruction file ${full} could not be read: ${err instanceof Error ? err.message : String(err)}`,+ { cause: err },+ );}const lines = countLines(content);return Object.freeze({diff --git a/src/core/brain/wikilink.ts b/src/core/brain/wikilink.tsindex eab36fd5..4ec91592 100644--- a/src/core/brain/wikilink.ts+++ b/src/core/brain/wikilink.ts@@ -139,6 +139,63 @@ export function isBrainArtifactId(target: string): boolean {return BRAIN_ID_RE.test(target);}+/**+ * The prefix a rule wears on each side of its retirement.+ *+ * Deliberately narrower than {@link BRAIN_ID_RE}. `sig-` is a different+ * artifact, not a second spelling of the same one, so folding it away+ * would merge a signal into whatever rule happens to share its slug.+ * `pref-<slug>` and `ret-<slug>` are the SAME record before and after+ * `moveToRetired` renamed it, which is the only reason a strip is+ * correct here at all.+ */+const BRAIN_ID_PREFIX_RE = /^(?:pref-|ret-)/;++/**+ * Drop the `pref-` / `ret-` prefix from a bare Brain id, leaving the slug+ * both spellings share.+ *+ * Two call sites had grown their own copy of this pattern - the `brain+ * audit` CLI verb and its MCP twin, both resolving a caller-supplied id+ * onto the one audit trail that is keyed by the ORIGINAL `pref-<slug>`.+ * One grammar in two files is one prefix away from disagreeing, and this+ * module is where the grammar already lives.+ *+ * Trims before matching as well as after, so a padded argument yields the+ * slug rather than falling through the pattern with its prefix intact.+ */+export function stripBrainIdPrefix(id: string): string {+ return id.trim().replace(BRAIN_ID_PREFIX_RE, "").trim();+}++/**+ * Fold any spelling of a Brain artifact reference onto one key.+ *+ * `[[pref-foo]]`, `pref-foo`, `ret-foo`, `Brain/retired/ret-foo.md` and+ * `[[Brain/preferences/pref-foo.md|Foo]]` all reduce to `foo`. The+ * composition is {@link normaliseWikilinkTarget} (brackets, alias,+ * anchor, folder, `.md`) followed by {@link stripBrainIdPrefix} (the+ * rename), which is exactly the pair a reverse lookup across a+ * retirement needs on BOTH sides of the join.+ *+ * The prefix strip is unconditional, and that has a consequence worth+ * naming rather than discovering: a basename that merely begins with one+ * of the two prefixes is folded like an id, so a note called+ * `ret-rospective.md` keys as `rospective`, and `pref-foo` shares a key+ * with a note called `foo.md`. Both collisions are between a preference+ * slug and an ordinary note basename, which is a namespace this project+ * does not otherwise keep apart.+ *+ * A caller that cannot tolerate that must match on exact ids plus the+ * `aliases:` a retirement records, rather than on a fold. This function+ * is for the reverse-lookup join, where the cost of a collision is one+ * extra advisory row naming a consumer that does not consume - not a+ * mutation, and visible to whoever reads it.+ */+export function brainArtifactSlug(value: string): string {+ return stripBrainIdPrefix(normaliseWikilinkTarget(value));+}+/*** Return the bare target id if `value` is exactly a wikilink form* (`^\[\[โฆ\]\]$` modulo surrounding whitespace), otherwise `null`.diff --git a/src/core/integrity/digest.ts b/src/core/integrity/digest.tsnew file mode 100644index 00000000..e5058686--- /dev/null+++ b/src/core/integrity/digest.ts@@ -0,0 +1,73 @@+/**+ * The one digest encoding.+ *+ * Ten modules across the brain, search and bench trees each carried a+ * private SHA-256 helper with the same body, and three reimplemented+ * canonical JSON serialization independently. That was survivable while+ * every digest stayed inside the process that computed it.+ *+ * It stops being survivable the moment a digest is persisted. The vault+ * is replicated peer-to-peer and persisted formats in this project are+ * additive-only: a record written under one encoding is read back by a+ * peer that may be running an older build, so two encodings shipped in+ * one release could never be reconciled afterwards. Two units of the+ * silence-is-not-an-answer wave persist a digest - a schema-pack seal and+ * a recall coverage receipt - which is why this module exists now rather+ * than as a tidying pass later.+ *+ * The module is deliberately narrow. It hashes bytes and it serializes a+ * value deterministically. It knows nothing about schema packs, coverage+ * receipts, or any other caller, it never truncates - a caller that wants+ * a short form slices its own result and owns that decision - and it+ * never inspects natural language: text is opaque bytes on the way in and+ * hex on the way out.+ */++import { createHash } from "node:crypto";++/**+ * The digest algorithm every persisted hash in this project is written+ * with. Named so that a future migration is one edit and one grep rather+ * than a sweep over call sites.+ */+export const DIGEST_ALGORITHM = "sha256";++/**+ * Lowercase hex SHA-256 of a string or a byte sequence.+ *+ * A string is hashed as UTF-8. The absorbed helpers were split between+ * `.update(text, "utf8")` and `.update(text)`, which are the same call+ * for a string argument; `tests/core/integrity/digest.test.ts` pins that+ * equivalence so the consolidation cannot silently re-key anything.+ */+export function sha256Hex(input: string | Uint8Array): string {+ return createHash(DIGEST_ALGORITHM).update(input).digest("hex");+}++/**+ * Deterministic JSON: object keys sorted recursively, array order kept,+ * object entries whose value is `undefined` omitted.+ *+ * The omission matches what `JSON.stringify` does to an object entry, and+ * it is what the persisted-ledger copy already did. Inside an array+ * `undefined` renders as `null`, again matching `JSON.stringify`, because+ * dropping it would change the array's length and therefore its meaning.+ *+ * The third absorbed copy - the external-fetch cache key - rendered such+ * an entry as `"key":null` instead. Nothing persisted it, and the request+ * it keys goes out through `JSON.stringify`, which drops the entry: the+ * copy was distinguishing two requests that are identical on the wire.+ */+export function canonicalJson(value: unknown): string {+ if (Array.isArray(value)) {+ return `[${value.map((item) => canonicalJson(item)).join(",")}]`;+ }+ if (value !== null && typeof value === "object") {+ const entries = Object.entries(value as Record<string, unknown>)+ .filter(([, child]) => child !== undefined)+ .toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))+ .map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`);+ return `{${entries.join(",")}}`;+ }+ return JSON.stringify(value) ?? "null";+}diff --git a/src/core/partner/codegraph-health.ts b/src/core/partner/codegraph-health.tsindex 8853c925..d94b1b60 100644--- a/src/core/partner/codegraph-health.ts+++ b/src/core/partner/codegraph-health.ts@@ -24,13 +24,51 @@* gate stays forward-compatible with a richer status surface.*/-/** Stable code per health finding so callers can filter without parsing text. */-export type GraphHealthCode =- | "empty-graph"- | "collapsed-edges"- | "dangling-references"- | "self-loops"- | "cache-root-mismatch";+/**+ * Stable code per health finding so callers can filter without parsing text.+ *+ * Frozen rather than a bare union because the codes are consumed outside+ * TypeScript: the codegraph resync cron recipe emits a shell gate that+ * selects one of them out of `--json` output, so the string has to be+ * reachable as a value, not only as a type.+ */+export const GRAPH_HEALTH_CODES = Object.freeze({+ emptyGraph: "empty-graph",+ collapsedEdges: "collapsed-edges",+ danglingReferences: "dangling-references",+ selfLoops: "self-loops",+ cacheRootMismatch: "cache-root-mismatch",+} as const);++export type GraphHealthCode = (typeof GRAPH_HEALTH_CODES)[keyof typeof GRAPH_HEALTH_CODES];++/**+ * Membership list, in declaration (severity) order.+ *+ * Named `_LIST` rather than pluralized because the frozen object above+ * already carries the plural name and is quoted by callers outside this+ * module; renaming it to free the plural would move a value the emitted+ * shell script selects on.+ */+export const GRAPH_HEALTH_CODE_LIST: ReadonlyArray<GraphHealthCode> = Object.freeze(+ Object.values(GRAPH_HEALTH_CODES),+);++/**+ * Narrow a string that arrives from outside TypeScript.+ *+ * The codes leave this process: the resync cron recipe interpolates one+ * into a shell gate that selects it out of `--json` output, and a caller+ * filtering the report by code may equally read one from a config file or+ * an operator's argument. A guard is what keeps "no finding with that+ * code" distinguishable from "that is not a code" - the same reason the+ * snapshot-reason filter has one.+ */+export function isGraphHealthCode(value: unknown): value is GraphHealthCode {+ return (+ typeof value === "string" && (GRAPH_HEALTH_CODE_LIST as ReadonlyArray<string>).includes(value)+ );+}/** One non-blocking graph-health finding. */export interface GraphHealthWarning {@@ -98,7 +136,7 @@ export function assessGraphHealth(input: GraphHealthInput): GraphHealthReport {if (nodes <= 0) {warnings.push({- code: "empty-graph",+ code: GRAPH_HEALTH_CODES.emptyGraph,message:"index is initialized but holds 0 nodes; extraction produced an empty graph - " +"labeling and recall will find nothing until it is re-indexed",@@ -108,7 +146,7 @@ export function assessGraphHealth(input: GraphHealthInput): GraphHealthReport {// meaningful when there is at least one node (an empty graph is reported// above and should not double-warn).warnings.push({- code: "collapsed-edges",+ code: GRAPH_HEALTH_CODES.collapsedEdges,message:`graph has ${nodes} node(s) but 0 edges; relationship extraction collapsed - ` +"callers/callees/impact traversal will be empty",@@ -117,7 +155,7 @@ export function assessGraphHealth(input: GraphHealthInput): GraphHealthReport {if (input.danglingRefs !== undefined && input.danglingRefs > 0) {warnings.push({- code: "dangling-references",+ code: GRAPH_HEALTH_CODES.danglingReferences,message:`${input.danglingRefs} dangling reference(s): edges point at nodes absent from the ` +"index; derived labels/imports built from them would reference missing symbols",@@ -126,7 +164,7 @@ export function assessGraphHealth(input: GraphHealthInput): GraphHealthReport {if (input.selfLoops !== undefined && input.selfLoops > 0) {warnings.push({- code: "self-loops",+ code: GRAPH_HEALTH_CODES.selfLoops,message:`${input.selfLoops} self-loop edge(s): a node references itself; ` +"impact and traversal surfaces may double-count or cycle",@@ -135,7 +173,7 @@ export function assessGraphHealth(input: GraphHealthInput): GraphHealthReport {if (input.indexRoot && input.worktreeRoot && !samePath(input.indexRoot, input.worktreeRoot)) {warnings.push({- code: "cache-root-mismatch",+ code: GRAPH_HEALTH_CODES.cacheRootMismatch,message:`index was built for '${input.indexRoot}' but is being read from ` +`'${input.worktreeRoot}'; file and line references may be stale for this tree - ` +diff --git a/src/core/partner/codegraph-report.ts b/src/core/partner/codegraph-report.tsindex 695a7a3c..1038c2fa 100644--- a/src/core/partner/codegraph-report.ts+++ b/src/core/partner/codegraph-report.ts@@ -18,6 +18,8 @@ import { existsSync, readFileSync, realpathSync } from "node:fs";import { join } from "node:path";import {+ CODEGRAPH_CLI,+ codegraphInitCommand,defaultRunStatusJson,defaultWhichCodegraph,findCodeProjects,@@ -270,10 +272,10 @@ function resolveIndexState(deps?: CodegraphReportDeps,): CodegraphReport["index"] {if (cliPath === null) {- return { state: "absent", reason: "codegraph CLI not on PATH (optional partner)" };+ return { state: "absent", reason: `${CODEGRAPH_CLI.bin} CLI not on PATH (optional partner)` };}if (!existsSync(join(project, ".codegraph"))) {- return { state: "not_indexed", reason: `run: codegraph init ${project}` };+ return { state: "not_indexed", reason: `run: ${codegraphInitCommand(project)}` };}const runFn = deps?.runStatusJson ?? defaultRunStatusJson;const status = runFn(project);@@ -281,7 +283,7 @@ function resolveIndexState(return { state: "error", reason: status.error };}if (!status.data.initialized) {- return { state: "not_indexed", reason: `run: codegraph init ${project}` };+ return { state: "not_indexed", reason: `run: ${codegraphInitCommand(project)}` };}const nodeCount = status.data.nodeCount ?? 0;const edgeCount = status.data.edgeCount ?? 0;diff --git a/src/core/partner/codegraph.ts b/src/core/partner/codegraph.tsindex 15e19f0a..ee327b22 100644--- a/src/core/partner/codegraph.ts+++ b/src/core/partner/codegraph.ts@@ -33,6 +33,41 @@ const CODE_MANIFESTS: ReadonlyArray<string> = [const DEFAULT_LIMIT = 50;+/**+ * The partner CLI's own vocabulary, in one place.+ *+ * These four tokens are the entire surface OSB knows about codegraph, and+ * they were previously written out five times across two modules - the+ * spawn arguments here, and the remediation sentence `run: codegraph init+ * <path>` in two separately worded messages. A partner that renames a+ * subcommand would have had to be chased through every copy, and the two+ * copies of the remediation could drift into saying different things about+ * the same repair.+ *+ * The invariant this constant serves is unchanged and absolute: OSB never+ * installs, initializes, or writes data for codegraph. `initSubcommand`+ * exists so OSB can *quote* the command an operator (or their crontab) runs+ * themselves, never so OSB can run it.+ */+export const CODEGRAPH_CLI = Object.freeze({+ /** Executable name looked up on PATH. */+ bin: "codegraph",+ /** Subcommand that reports index state. */+ statusSubcommand: "status",+ /** Flag making the status subcommand emit JSON. */+ statusJsonFlag: "-j",+ /** Subcommand that builds an index for a project root. */+ initSubcommand: "init",+} as const);++/**+ * The `codegraph init <path>` command line, as text. Quoted in operator-facing+ * remediation and in the resync cron recipe; never spawned by this project.+ */+export function codegraphInitCommand(projectPath: string): string {+ return `${CODEGRAPH_CLI.bin} ${CODEGRAPH_CLI.initSubcommand} ${projectPath}`;+}+/*** Heuristic check: does `dir` look like a code project root?* Requires BOTH a `.git/` directory AND at least one recognised@@ -160,7 +195,9 @@ export interface CodegraphCheckOptions {export function defaultWhichCodegraph(): string | null {if (typeof Bun !== "undefined" && typeof (Bun as { which?: unknown }).which === "function") {- const found = (Bun as unknown as { which: (cmd: string) => string | null }).which("codegraph");+ const found = (Bun as unknown as { which: (cmd: string) => string | null }).which(+ CODEGRAPH_CLI.bin,+ );return found ?? null;}return null;@@ -177,10 +214,13 @@ export function defaultWhichCodegraph(): string | null {*/const CODEGRAPH_PROJECT_PATH_USAGE_TOKEN = /\[path\]/;+/** The universal flag that makes a CLI print its own usage. */+const HELP_FLAG = "--help";+export function defaultDetectProjectPathSupport(): boolean {try {const proc = Bun.spawnSync({- cmd: ["codegraph", "status", "--help"],+ cmd: [CODEGRAPH_CLI.bin, CODEGRAPH_CLI.statusSubcommand, HELP_FLAG],stdout: "pipe",stderr: "pipe",});@@ -194,7 +234,12 @@ export function defaultDetectProjectPathSupport(): boolean {export function defaultRunStatusJson(projectPath: string): CodegraphStatusResult {try {const proc = Bun.spawnSync({- cmd: ["codegraph", "status", "-j", projectPath],+ cmd: [+ CODEGRAPH_CLI.bin,+ CODEGRAPH_CLI.statusSubcommand,+ CODEGRAPH_CLI.statusJsonFlag,+ projectPath,+ ],stdout: "pipe",stderr: "pipe",});@@ -207,7 +252,12 @@ export function defaultRunStatusJson(projectPath: string): CodegraphStatusResultreturn { ok: true, data: parsed };} catch {}}- return { ok: false, error: stderr || `codegraph status exited ${proc.exitCode}` };+ return {+ ok: false,+ error:+ stderr ||+ `${CODEGRAPH_CLI.bin} ${CODEGRAPH_CLI.statusSubcommand} exited ${proc.exitCode}`,+ };}if (!stdout) {return { ok: false, error: stderr || "empty status output" };@@ -307,7 +357,7 @@ function evaluateProjectStatus(project: string, deps?: CodegraphCheckDeps): Checreturn {name: "code_graph",ok: false,- message: `code project at ${project}: not indexed (run: codegraph init ${project})`,+ message: `code project at ${project}: not indexed (run: ${codegraphInitCommand(project)})`,};}@@ -325,7 +375,7 @@ function evaluateProjectStatus(project: string, deps?: CodegraphCheckDeps): Checreturn {name: "code_graph",ok: false,- message: `code project at ${project}: not indexed (run: codegraph init ${project})`,+ message: `code project at ${project}: not indexed (run: ${codegraphInitCommand(project)})`,};}diff --git a/src/core/search/index.ts b/src/core/search/index.tsindex 86506814..a43a5edb 100644--- a/src/core/search/index.ts+++ b/src/core/search/index.ts@@ -11,7 +11,7 @@ import {parseInteger as parseIntegerShared,} from "../validate.ts";import { resolveVaultScope } from "../vault-scope/index.ts";-import { resolveIndexPath } from "./paths.ts";+import { resolveIndexPath, SEARCH_DB_CONFIG_KEY, SEARCH_DB_ENV } from "./paths.ts";import { buildFtsTokenize } from "./schema.ts";import { isFusionMode, DEFAULT_RRF_K } from "./fusion.ts";import {@@ -117,12 +117,14 @@ export {type RerankEvalGateResult,} from "./rerank-eval-gate.ts";-export { resolveIndexPath } from "./paths.ts";+export { resolveConfiguredIndexPath, resolveIndexPath } from "./paths.ts";export {indexVault,reindexVault,indexStatus,indexCheck,+ indexRootCoverage,+ type IndexRootCoverage,type IndexVaultOptions,type IndexProgressEvent,} from "./indexer.ts";@@ -402,7 +404,7 @@ export function resolveSearchConfig(opts: {const dbPath = resolveIndexPath(opts.vault,- envOrConfig(env, config, "OPEN_SECOND_BRAIN_SEARCH_DB", "search_db_path"),+ envOrConfig(env, config, SEARCH_DB_ENV, SEARCH_DB_CONFIG_KEY),);const chunkSize = parseInteger(diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.tsindex db6210e0..6cd1ee71 100644--- a/src/core/search/indexer.ts+++ b/src/core/search/indexer.ts@@ -6,14 +6,14 @@* rebuild: write to `brain.sqlite.new`, then a same-file rename swap* with `.bak` retention.*- * `indexStatus` and `indexCheck` are the read-side diagnostics that- * power `o2b search status|check` and the MCP status enrichment.+ * `indexStatus`, `indexCheck` and `indexRootCoverage` are the read-side+ * diagnostics that power `o2b search status|check`, the MCP status+ * enrichment and the recall gate's coverage receipt.** Anchored in docs/plans/2026-05-16-brain-search-design.md ยง6, ยง8,* ยง13, ยง15.*/-import { createHash } from "node:crypto";import {accessSync,constants,@@ -34,6 +34,7 @@ import {semanticCapabilityLabel,SEMANTIC_VECTOR_CODE,} from "./capability-tier.ts";+import { sha256Hex } from "../integrity/digest.ts";import { chunkMarkdown } from "./chunker.ts";import { expandTextForCjkFts } from "./cjk-tokenizer.ts";import { declaredInputWindowTokens, passagePrefixSentByProvider } from "./embeddings/presets.ts";@@ -214,10 +215,6 @@ async function offlineDeferredReason(config: ResolvedSearchConfig): Promise<stri);}-function sha256(text: string): string {- return createHash("sha256").update(text).digest("hex");-}-/** Deep-ish equality for frontmatter scalar/array values. */function tierValueEquals(left: unknown, right: unknown): boolean {if (Array.isArray(left) && Array.isArray(right)) {@@ -338,7 +335,7 @@ async function indexInto(}const content = readUtf8(file.absPath);- const contentHash = sha256(content);+ const contentHash = sha256Hex(content);// Fallback: fastpath missed (mtime or size changed). If// the content hash still matches, the file is logically@@ -407,7 +404,7 @@ async function indexInto(chunkIndex: c.chunkIndex,content: c.content,ftsContent: expandTextForCjkFts(c.content),- contentHash: sha256(c.content),+ contentHash: sha256Hex(c.content),startLine: c.startLine,endLine: c.endLine,tokenCount: c.tokenCount,@@ -891,7 +888,7 @@ export async function runEmbeddingPhase(for (let j = 0; j < batch.length; j++) {const chunkId = batch[j]!.chunkId;const vec = vectors[j]!;- const embHash = sha256(vec.map((x) => x.toFixed(8)).join(","));+ const embHash = sha256Hex(vec.map((x) => x.toFixed(8)).join(","));store.vecUpsert(chunkId, vec, model, dim, embHash);stats.embeddingsComputed++;}@@ -1211,6 +1208,77 @@ export async function indexStatus(config: ResolvedSearchConfig): Promise<IndexSt}}+// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ+// indexRootCoverage+// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++/**+ * Which authorized note roots the index REACHED, and how far.+ *+ * The field names say presence rather than coverage on purpose. "Covered"+ * would claim the root was read out; what the index can show is that at+ * least one document under it was indexed, which is a strictly weaker+ * statement - see {@link indexRootCoverage}.+ */+export interface IndexRootCoverage {+ /** Roots carrying at least one indexed document. */+ readonly rootsWithDocuments: ReadonlyArray<string>;+ /** Roots the index holds no document under at all. */+ readonly rootsWithoutDocuments: ReadonlyArray<string>;+}++/**+ * Partition note roots by whether the index carries any document under+ * them (silence-is-not-an-answer, U2).+ *+ * `indexStatus` says how much was indexed in total; this says WHICH of+ * the folders the operator authorized were reached at all. A negative+ * recall needs both: the totals make the receipt, and the partition names+ * the roots that were never touched.+ *+ * The guarantee is deliberately named as presence, not coverage, and the+ * field names say so: a root lands in `rootsWithDocuments` on the+ * strength of ONE indexed document, so one note out of a thousand puts it+ * there. The index knows what it was given and never what it was not, so+ * it cannot tell that case from a folder that holds exactly one note;+ * deciding between them needs a filesystem census of the root, which is a+ * different measurement with a different cost. Until something needs that+ * census, the honest move is to promise only what this scan sees - the+ * document TOTAL rides on the receipt beside the root list, so a reader+ * weighing a negative is never left with the root list alone.+ *+ * Throws `SearchError` `INDEX_MISSING` when there is no index, rather+ * than reporting every root absent. The caller must establish that the+ * index exists first, and an all-absent answer over a missing index would+ * read like a measurement.+ *+ * Cost: one read-mode open and one full document-path scan. It runs only+ * on the recall gate's zero-result path, where a search has already+ * failed to produce anything, and the alternative - a per-root prefix+ * query - would buy microseconds for a new store surface.+ */+export async function indexRootCoverage(+ config: ResolvedSearchConfig,+ roots: ReadonlyArray<string>,+): Promise<IndexRootCoverage> {+ const store = await Store.open(config, { mode: "read" });+ try {+ const paths = [...store.listDocuments().keys()];+ const withDocuments: string[] = [];+ const withoutDocuments: string[] = [];+ for (const root of roots) {+ const reached = paths.some((path) => path === root || path.startsWith(`${root}/`));+ (reached ? withDocuments : withoutDocuments).push(root);+ }+ return Object.freeze({+ rootsWithDocuments: Object.freeze(withDocuments),+ rootsWithoutDocuments: Object.freeze(withoutDocuments),+ });+ } finally {+ await store.close();+ }+}+// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ// indexCheck// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโdiff --git a/src/core/search/paths.ts b/src/core/search/paths.tsindex eb658ac0..a3563e29 100644--- a/src/core/search/paths.ts+++ b/src/core/search/paths.ts@@ -3,14 +3,58 @@** Default: `<vault>/.open-second-brain/brain.sqlite`. Overridable* through CLI `--db` or config `search_db_path`.+ *+ * The two name components come from `brain/path-constants.ts`, the leaf+ * module that already owns every vault-relative name in this project.+ * They live there rather than here because the snapshot family needs to+ * name the same file, and a second copy of the literal is precisely how+ * an archiver and an indexer end up disagreeing about which file is the+ * store. This module remains the ONLY resolver: callers that need the+ * path ask it, and never re-join the parts themselves.*/import { join } from "node:path";+import { DERIVED_STORE_DIR, DERIVED_STORE_FILE } from "../brain/path-constants.ts";+import { defaultConfigPath, discoverConfig } from "../config.ts";+import { envOrConfig } from "../validate.ts";++/** Environment variable that overrides the store location. */+export const SEARCH_DB_ENV = "OPEN_SECOND_BRAIN_SEARCH_DB";++/** Machine-config key that overrides the store location. */+export const SEARCH_DB_CONFIG_KEY = "search_db_path";+export function resolveIndexPath(vault: string, override: string | null): string {if (override !== null) {const trimmed = override.trim();if (trimmed !== "") return trimmed;}- return join(vault, ".open-second-brain", "brain.sqlite");+ return join(vault, DERIVED_STORE_DIR, DERIVED_STORE_FILE);+}++/**+ * The store location a caller holding no resolved search config should+ * use: the default, unless the environment or the machine config moves it.+ *+ * It exists because {@link resolveIndexPath} answers only the default when+ * handed `null`, and a caller that does not know about the override reads+ * that as the truth. The snapshot family did: on a vault carrying a+ * `search_db_path` override it would have archived, or refused to find, a+ * file the search layer never reads - and if a stale database happened to+ * sit at the default location it would have archived that and reported+ * success. The pack stamp shipped the same bug against the same key.+ *+ * The config read is the discovering form, so a vault that was never+ * registered resolves to the default rather than throwing. An+ * unconfigured store is a real state, and refusing it by name belongs to+ * the caller that tries to use it, not here.+ */+export function resolveConfiguredIndexPath(vault: string, configPath?: string): string {+ const path = configPath ?? defaultConfigPath();+ const config = discoverConfig(path).data;+ return resolveIndexPath(+ vault,+ envOrConfig(process.env, config, SEARCH_DB_ENV, SEARCH_DB_CONFIG_KEY),+ );}diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.tsindex 114baef9..add3b84f 100644--- a/src/mcp/brain/admin-tools.ts+++ b/src/mcp/brain/admin-tools.ts@@ -16,6 +16,7 @@ import {readLabels,removeNoteLabel,} from "../../core/brain/labels.ts";+import { StandingRulesWriteRefusedError } from "../../core/brain/standing-rules.ts";import { loadSchemaPack } from "../../core/brain/schema-pack.ts";import { listSecrets } from "../../core/brain/secrets/store.ts";import { runWithSecret, SecretExecDeniedError } from "../../core/brain/secrets/exec.ts";@@ -85,6 +86,12 @@ function toolBrainLabels(if (exc instanceof LabelVocabularyError) {throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);}+ // A refused target is a bad argument, not a server fault: the caller+ // named a file this surface will not rewrite, and the message says+ // which one so the agent stops trying rather than retrying blind.+ if (exc instanceof StandingRulesWriteRefusedError) {+ throw new MCPError(INVALID_PARAMS, `brain_labels ${op}: ${exc.message}`);+ }throw exc;}}diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.tsindex 22f121cb..b8befee4 100644--- a/src/mcp/brain/brief-tools.ts+++ b/src/mcp/brain/brief-tools.ts@@ -12,6 +12,12 @@ import {deliverBriefTriggers,renderTriggerBriefSection,} from "../../core/brain/triggers/brief.ts";+import {+ readTriggerQueueFailures,+ renderTriggerQueueFailures,+ unreadableTriggerJson,+ type TriggerQueueFailures,+} from "../../core/brain/triggers/store.ts";import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";import { buildTodayDashboard } from "../../core/brain/today-dashboard.ts";import { buildDailyBrief } from "../../core/brain/temporal/daily-brief.ts";@@ -73,24 +79,38 @@ async function toolBrainMorningBrief(});// Pending-trigger section (t_cd1fee79): renders only when a trigger// scan persisted surfaceable triggers; included triggers are marked- // delivered so a prompt shows once per cooldown window. Fail-soft -- // a broken queue never breaks the brief.+ // delivered so a prompt shows once per cooldown window.+ //+ // Still fail-soft - a broken queue must not cost the operator the rest+ // of the brief - but no longer silent. The bare catch this replaces set+ // the section to null, so a refusal rendered exactly like an empty+ // queue: the one outcome the anti-nag ledger exists to rule out. The+ // records that could not be read are collected first and reported+ // alongside whatever did render.+ const triggerFailures: TriggerQueueFailures = readTriggerQueueFailures(ctx.vault, now);let triggerSection: ReturnType<typeof renderTriggerBriefSection> | null = null;+ let triggerQueueError = triggerFailures.queueError;try {triggerSection = renderTriggerBriefSection(ctx.vault, {now,cooldownDays: resolveTriggerCooldownDays(ctx.configPath ?? undefined),});if (triggerSection.triggers.length > 0) deliverBriefTriggers(ctx.vault, triggerSection, now);- } catch {+ } catch (err) {triggerSection = null;+ triggerQueueError = (err as Error).message ?? String(err);}- const text =- triggerSection !== null && triggerSection.text !== ""- ? `${brief.text}${brief.text.length > 0 ? "\n\n" : ""}${triggerSection.text}`- : brief.text;+ const failureText = renderTriggerQueueFailures({+ unreadable: triggerFailures.unreadable,+ queueError: triggerQueueError,+ });+ const sections = [+ brief.text,+ triggerSection !== null ? triggerSection.text : "",+ failureText,+ ].filter((section) => section !== "");return {- text,+ text: sections.join("\n\n"),preferences: brief.preferences,open_questions: brief.openQuestions,recent_notes: brief.recentNotes,@@ -105,6 +125,10 @@ async function toolBrainMorningBrief(})),}: {}),+ ...(triggerFailures.unreadable.length > 0+ ? { triggers_unreadable: triggerFailures.unreadable.map(unreadableTriggerJson) }+ : {}),+ ...(triggerQueueError !== null ? { trigger_queue_error: triggerQueueError } : {}),};}diff --git a/src/mcp/brain/context-tools.ts b/src/mcp/brain/context-tools.tsindex f5eae8fc..70282de9 100644--- a/src/mcp/brain/context-tools.ts+++ b/src/mcp/brain/context-tools.ts@@ -8,7 +8,15 @@import { existsSync, readFileSync } from "node:fs";import { resolveAgentName } from "../../core/config.ts";-import { brainActivePath, brainDirs } from "../../core/brain/paths.ts";+import { brainActivePath, brainDirs, brainStandingRulesPath } from "../../core/brain/paths.ts";+import {+ readStandingRules,+ renderStandingRules,+ renderStandingRulesFailure,+ type StandingRules,+} from "../../core/brain/standing-rules.ts";+import { loadBrainConfig, resolveStandingRulesMaxChars } from "../../core/brain/policy.ts";+import type { BrainConfig } from "../../core/brain/types.ts";import {regenerateActive,renderActive,@@ -299,7 +307,11 @@ const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {* automatically.** Behaviour matrix:- * - Brain/ absent โ present:false, content:"", zero counts.+ * - Brain/ absent โ present:false, zero counts, and content+ * carrying the standing-rules block or the+ * statement that it could not be read (empty+ * for the ordinary case, where there is no+ * such file either).* - Brain/ present, active.md absent โ call regenerateActive (idempotent)* and read the regenerated file.* - Brain/ present, active.md fresh โ idempotent regenerate is a no-op@@ -310,15 +322,31 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknconst dirs = brainDirs(ctx.vault);const activePath = brainActivePath(ctx.vault);const pinned = readPinnedContext(ctx.vault);++ // The operator's standing rules, resolved before anything else this+ // surface assembles - INCLUDING the no-Brain return below. `brain_context`+ // is the pull-mode twin of the SessionStart hook, so the constitution has+ // to lead the content here for exactly the reason it leads the injected+ // payload: on the error branch further down, which zeroes `content` and+ // would otherwise hand a runtime the memory layer's failure and none of+ // the rules that still govern it, and equally on the branch that reports+ // `Brain/` as absent. That probe answers false for a directory it cannot+ // TRAVERSE as well as one that is not there, and it was the one return+ // path that said nothing at all about the rules - the last silent answer+ // on a surface where every other path either carries the block or states+ // why it could not be read.+ const standing = readStandingBlock(ctx.vault);+if (!existsSync(dirs.brain)) {return {vault_path: ctx.vault,present: false,active_path: activePath,- content: "",+ content: prependStandingBlock(standing, ""),counts: EMPTY_CONTEXT_COUNTS,generated_at: null,pinned: serializePinnedContext(ctx, pinned),+ ...standingRulesField(ctx, standing),};}@@ -377,17 +405,25 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unkn}}+ content = prependStandingBlock(standing, content);content = appendPinnedToContextContent(content, pinned.content);// Optional vault-root instruction file (v0.10.17). Absent file =// field omitted so hosts that strip unknown fields stay- // byte-identical. Read errors are silently swallowed - this is a- // best-effort enrichment, not a hard contract.+ // byte-identical.+ //+ // A THROW IS NOT AN ABSENCE. This used to be `catch { null }`, which+ // put an operator configuration error - an absolute path, a `..`+ // segment, an empty name - and an unreadable file on the same wire as+ // a vault that simply has no instruction file: the field vanished and+ // nothing said why. The reason now rides its own key, so the+ // enrichment stays best-effort without being silent.let vaultInstruction: ReturnType<typeof readVaultInstructionFile> = null;+ let vaultInstructionError: string | undefined;try {vaultInstruction = readVaultInstructionFile(ctx.vault);- } catch {- vaultInstruction = null;+ } catch (err) {+ vaultInstructionError = (err as Error)?.message ?? String(err);}return {@@ -399,6 +435,7 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unkngenerated_at: generatedAt,pinned: serializePinnedContext(ctx, pinned),...(error ? { error } : {}),+ ...standingRulesField(ctx, standing),...(vaultInstruction? {vault_instruction: {@@ -408,9 +445,75 @@ async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unkn},}: {}),+ ...(vaultInstructionError !== undefined+ ? { vault_instruction_error: vaultInstructionError }+ : {}),};}+/**+ * The standing-rules block and the record behind it, or neither.+ *+ * The two travel together because the response reports them in two+ * different places - the block is prepended to `content`, the record+ * becomes the `standing_rules` key - and a read that FAILED produces a+ * block but no record: there is no path/content/truncated triple to+ * report for bytes nobody could read, and the block itself is what says+ * so in words the agent will read.+ */+interface StandingBlock {+ readonly text: string;+ readonly rules: StandingRules | null;+}++const NO_STANDING_BLOCK: StandingBlock = Object.freeze({ text: "", rules: null });++function readStandingBlock(vault: string): StandingBlock {+ const path = brainStandingRulesPath(vault);+ let cfg: BrainConfig | null = null;+ try {+ cfg = loadBrainConfig(vault);+ } catch {+ // A `_brain.yaml` this surface cannot read resolves the cap to its+ // default; the config failure itself surfaces through the `error`+ // slot that the regenerate arm above already populates.+ }+ try {+ const rules = readStandingRules(vault, { maxChars: resolveStandingRulesMaxChars(cfg) });+ if (rules === null) return NO_STANDING_BLOCK;+ return Object.freeze({ text: renderStandingRules(rules), rules });+ } catch (err) {+ return Object.freeze({ text: renderStandingRulesFailure(path, err), rules: null });+ }+}++/**+ * The optional `standing_rules` key, or nothing.+ *+ * Both return shapes spread it from here so the two cannot disagree about+ * when the key appears. It is omitted for a vault whose operator wrote no+ * rules AND for a read that failed - the failure has no path/content/+ * truncated triple to report, and the block inside `content` is what says+ * so in words.+ */+function standingRulesField(ctx: ServerContext, standing: StandingBlock): Record<string, unknown> {+ if (standing.rules === null) return {};+ return {+ standing_rules: {+ path: vaultRelativeSafe(ctx.vault, standing.rules.path),+ content: standing.rules.text,+ truncated: standing.rules.truncated,+ },+ };+}++/** Put the standing block at the head of the content, or leave it alone. */+function prependStandingBlock(standing: StandingBlock, content: string): string {+ if (standing.text.length === 0) return content;+ const trimmed = content.trimStart();+ return trimmed.length === 0 ? `${standing.text}\n` : `${standing.text}\n\n${trimmed}`;+}+// ----- brain_digest --------------------------------------------------------const PINNED_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {@@ -449,6 +552,23 @@ const BRAIN_CONTEXT_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> =},generated_at: {},pinned: PINNED_CONTEXT_OUTPUT_SCHEMA,+ // Declared but deliberately NOT required: a vault whose operator has+ // written no standing rules omits the key entirely, exactly as the+ // vault-instruction field does, so hosts that strip unknown fields+ // stay byte-identical on the common path.+ standing_rules: {+ type: "object",+ required: ["path", "content", "truncated"],+ properties: {+ path: { type: "string" },+ content: { type: "string" },+ truncated: { type: "boolean" },+ },+ additionalProperties: false,+ },+ // Present only when the instruction-file read failed; see the+ // "a throw is not an absence" note on the handler.+ vault_instruction_error: { type: "string" },},};diff --git a/src/mcp/brain/query-tools.ts b/src/mcp/brain/query-tools.tsindex c153b231..476e037e 100644--- a/src/mcp/brain/query-tools.ts+++ b/src/mcp/brain/query-tools.ts@@ -10,7 +10,7 @@ import { buildBacklinkIndex } from "../../core/brain/backlinks.ts";import { readPrefAudit } from "../../core/brain/pref-audit.ts";import { aggregateSources } from "../../core/brain/portability/sources.ts";import { findUnlinkedMentions } from "../../core/brain/link-graph/unlinked-mentions.ts";-import { normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";+import { brainArtifactSlug, normaliseWikilinkTarget } from "../../core/brain/wikilink.ts";import {BrainNotFoundError,queryByLogSince,@@ -323,13 +323,11 @@ async function toolBrainAudit(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const raw = coerceStr(args, "pref_id", true)!;- // The trail is keyed by the original `pref-<slug>` id. Run the input- // through the shared wikilink normaliser first (handles `[[id]]`,- // `[[id|Alias]]`, and `Brain/.../id.md` forms), then strip the- // pref-/ret- prefix so every reference resolves to one trail.- const slug = normaliseWikilinkTarget(raw)- .replace(/^(?:pref-|ret-)/, "")- .trim();+ // The trail is keyed by the original `pref-<slug>` id, and the shared+ // fold in `wikilink.ts` is what reduces every spelling of a reference+ // (`[[id]]`, `[[id|Alias]]`, `Brain/.../id.md`, and the pre- or+ // post-retirement prefix) onto that one key.+ const slug = brainArtifactSlug(raw);if (slug.length === 0) {throw new Error(`brain_audit: empty preference slug after normalising '${raw}'`);}diff --git a/src/mcp/brain/workspace-tools.ts b/src/mcp/brain/workspace-tools.tsindex 0de8b44c..6e894fc1 100644--- a/src/mcp/brain/workspace-tools.ts+++ b/src/mcp/brain/workspace-tools.ts@@ -8,8 +8,18 @@import { resolveAgentName, resolveTriggerCooldownDays } from "../../core/config.ts";import { scanTriggers } from "../../core/brain/triggers/scan.ts";-import { listTriggers, transitionTrigger } from "../../core/brain/triggers/store.ts";-import { isTriggerStatus, type TriggerRecord } from "../../core/brain/triggers/types.ts";+import {+ readTriggers,+ transitionTrigger,+ unreadableTriggerJson,+ type TriggerAction,+} from "../../core/brain/triggers/store.ts";+import {+ isTriggerStatus,+ TRIGGER_STATUSES,+ TRIGGER_TERMINAL_STATUSES,+ type TriggerRecord,+} from "../../core/brain/triggers/types.ts";import {listIntentions,moveIntentionToHistory,@@ -86,10 +96,37 @@ function triggerToJson(record: TriggerRecord): Record<string, unknown> {expires_at: record.expiresAt,delivered_at: record.deliveredAt,resolved_at: record.resolvedAt,+ suppressed_at: record.suppressedAt,+ suppressed_from: record.suppressedFrom,+ occurrences: record.occurrences,+ last_seen_at: record.lastSeenAt,};}-const TRIGGER_TERMINAL = new Set(["acted", "dismissed", "expired"]);+/** Operations that move one trigger through the lifecycle. */+const TRIGGER_TRANSITIONS: ReadonlyArray<TriggerAction> = Object.freeze([+ "acknowledge",+ "dismiss",+ "act",+ "suppress",+ "unsuppress",+]);++/**+ * Every accepted operation, in the order the schema enum lists them.+ * The read operations and {@link TRIGGER_TRANSITIONS} are the only+ * source: the enum, the guard and the error text are all this one list.+ */+const TRIGGER_OPERATIONS: ReadonlyArray<string> = Object.freeze([+ "scan",+ "list",+ "history",+ ...TRIGGER_TRANSITIONS,+]);++function isTriggerTransition(operation: string): operation is TriggerAction {+ return (TRIGGER_TRANSITIONS as ReadonlyArray<string>).includes(operation);+}function toolBrainTrigger(ctx: ServerContext,@@ -108,6 +145,8 @@ function toolBrainTrigger(cooldown_key: skip.cooldownKey,reason: skip.reason,})),+ // A scan that walked around a broken record is not a clean scan.+ unreadable: result.unreadable.map(unreadableTriggerJson),};}if (operation === "list" || operation === "history") {@@ -115,18 +154,25 @@ function toolBrainTrigger(if (statusRaw !== null && statusRaw !== undefined && !isTriggerStatus(statusRaw)) {throw new MCPError(INVALID_PARAMS, `brain_trigger: unknown status '${statusRaw}'`);}- let records = listTriggers(ctx.vault, {+ const scan = readTriggers(ctx.vault, {now,...(statusRaw ? { status: statusRaw } : {}),});+ let records = scan.records;if (operation === "history") {- records = records.filter((record) => TRIGGER_TERMINAL.has(record.effectiveStatus));+ records = records.filter((record) => TRIGGER_TERMINAL_STATUSES.has(record.effectiveStatus));} else if (!statusRaw) {- records = records.filter((record) => !TRIGGER_TERMINAL.has(record.effectiveStatus));+ records = records.filter((record) => !TRIGGER_TERMINAL_STATUSES.has(record.effectiveStatus));}- return { operation, triggers: records.map(triggerToJson) };+ // Always present, so an empty `triggers` list means the queue was+ // read and held nothing rather than that part of it was skipped.+ return {+ operation,+ triggers: records.map(triggerToJson),+ unreadable: scan.unreadable.map(unreadableTriggerJson),+ };}- if (operation === "acknowledge" || operation === "dismiss" || operation === "act") {+ if (isTriggerTransition(operation)) {const id = coerceStr(args, "id", true)!;try {return {@@ -139,7 +185,7 @@ function toolBrainTrigger(}throw new MCPError(INVALID_PARAMS,- "brain_trigger operation must be one of: scan, list, history, acknowledge, dismiss, act",+ `brain_trigger operation must be one of: ${TRIGGER_OPERATIONS.join(", ")}`,);}@@ -180,24 +226,31 @@ export const WORKSPACE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([{name: "brain_trigger",description:- "Grounded proactive trigger queue under Brain/triggers/: scan generates deduped triggers from health/retention data, list/history read by lifecycle status, acknowledge/dismiss/act transition one trigger. Anti-nag: cooldown keys keep the same issue from reappearing every run.",+ // Within the registry guard's tool-description ceiling, which is why+ // the wording is this tight: the unreadable partition has to be in+ // here, because a caller that does not know to look at it will read+ // an empty `triggers` list as an empty queue.+ "Proactive trigger queue in Brain/triggers/: scan makes deduped triggers, list/history read by status, acknowledge/dismiss/act transition one. suppress silences a finding indefinitely; unsuppress restores the status it interrupted. Recurrences stay counted; unreadable records are named, not omitted.",inputSchema: {type: "object",properties: {operation: {type: "string",- enum: ["scan", "list", "history", "acknowledge", "dismiss", "act"],+ enum: [...TRIGGER_OPERATIONS],description: "Operation to perform.",},id: {type: "string",minLength: 1,maxLength: 128,- description: "Trigger id for acknowledge/dismiss/act.",+ description: "Trigger id for acknowledge/dismiss/act/suppress/unsuppress.",},status: {+ // Sourced from the shared list, never copied: a literal copy+ // here would let a new status pass the handler's guard and be+ // rejected by this schema with nothing reporting the gap.type: "string",- enum: ["pending", "delivered", "acknowledged", "acted", "dismissed", "expired"],+ enum: [...TRIGGER_STATUSES],description: "Effective-status filter for list.",},},diff --git a/src/mcp/search-tools.ts b/src/mcp/search-tools.tsindex 865b9974..c5b8e31e 100644--- a/src/mcp/search-tools.ts+++ b/src/mcp/search-tools.ts@@ -15,6 +15,7 @@ import {EMBEDDING_QUOTA_MESSAGE,evaluateSurfacingGate,expandHit,+ indexRootCoverage,indexStatus,resolveSearchConfig,search,@@ -36,6 +37,16 @@ import {resolveRecallGateTelemetry,} from "../core/config.ts";import { assessRecallAdequacy } from "../core/brain/recall-adequacy.ts";+import {+ classifyNegativeRecall,+ NEGATIVE_RECALL_STATE,+ NEGATIVE_RECALL_UNKNOWN_REASONS,+ type CoverageIndexSnapshot,+ type CoverageScope,+ type NegativeRecallState,+ type NegativeRecallVerdict,+} from "../core/brain/negative-recall.ts";+import { resolveNoteRoots } from "../core/brain/notes/note-walk.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";import type { ServerContext, ToolDefinition } from "./tool-contract.ts";import {@@ -66,7 +77,7 @@ import {type RecallQualitySignals,type RecallSignalsUnmeasured,} from "../core/brain/recall-telemetry.ts";-import { emitGateTelemetry } from "../core/brain/gate-telemetry.ts";+import { emitGateTelemetry, emitNegativeRecallTelemetry } from "../core/brain/gate-telemetry.ts";import { emitGatedTelemetry } from "../core/brain/continuity/emit.ts";import { recordQueryDemand, recordRecallAdequacyDemand } from "../core/brain/query-demand.ts";@@ -398,13 +409,36 @@ const RECALL_GATE_INPUT_SCHEMA: Record<string, unknown> = {maxItems: 200,items: { type: "number" },description:- "Optional top-k recall relevance scores. When given, the gate adds an adequacy verdict: sufficient/proceed, weak/re_recall, or insufficient/abstain.",+ "Optional top-k recall scores. Adds an adequacy verdict: sufficient/proceed, weak/re_recall, insufficient/abstain. An empty array adds the negative verdict.",},},required: ["prompt"],additionalProperties: false,};+/**+ * The negative-recall states `brain_recall_gate` can actually produce.+ *+ * The vocabulary is three states wide (`NEGATIVE_RECALL_STATES` in+ * `core/brain/negative-recall.ts`); this surface reaches two of them. `did_not_happen` is missing because+ * {@link assessNegativeRecall} supplies neither of the two things that+ * state requires - stored retraction evidence and the caller's assertion+ * of non-occurrence - and it reads no claim graph to find any. Declaring+ * the full vocabulary here would leave a client unable to tell "this+ * surface cannot say that" from "it did not happen this time", which is+ * the same conflation between an unanswerable check and a passing one+ * that the negative-recall unit exists to remove.+ *+ * Enforced, not documentary: the server validates every response against+ * this schema, so wiring an evidence read into the gate without widening+ * this list fails the contract loudly instead of emitting an undeclared+ * value. Order follows the vocabulary's weakest-to-strongest ordering.+ */+export const RECALL_GATE_NEGATIVE_STATES: ReadonlyArray<NegativeRecallState> = Object.freeze([+ NEGATIVE_RECALL_STATE.notFound,+ NEGATIVE_RECALL_STATE.unknown,+]);+const RECALL_GATE_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {type: "object",required: ["retrieve", "reason"],@@ -432,6 +466,43 @@ const RECALL_GATE_OUTPUT_SCHEMA: NonNullable<ToolDefinition["outputSchema"]> = {reason: { type: "string" },},},+ // Typed negative recall (silence-is-not-an-answer, U2). Present only+ // when the caller reported no usable result, mirroring `adequacy`+ // above: absent - never null - when it does not apply.+ negative: {+ type: "object",+ required: ["state", "complete", "reason"],+ properties: {+ state: { type: "string", enum: [...RECALL_GATE_NEGATIVE_STATES] },+ complete: { type: "boolean" },+ reason: { type: "string" },+ unknown_reason: { type: "string", enum: [...NEGATIVE_RECALL_UNKNOWN_REASONS] },+ coverage: {+ type: "object",+ required: ["digest", "documents", "chunks", "embeddings", "scope", "unindexed_roots"],+ properties: {+ digest: { type: "string" },+ documents: { type: "integer" },+ chunks: { type: "integer" },+ // Declared beside `chunks` because the pair is the claim: a+ // count below the chunk count is an index a semantic query+ // could not read out in full.+ embeddings: { type: "integer" },+ index_path: { type: "string" },+ // Three fields whose value is an integer/string OR null.+ // The output-schema vocabulary declares one type per node+ // and has no union, so they are declared untyped rather+ // than declared wrongly: a `string` here would make the+ // never-indexed case fail its own contract.+ schema_version: {},+ embedding_signature: {},+ last_indexed_at: {},+ scope: { type: "array", items: { type: "string" } },+ unindexed_roots: { type: "array", items: { type: "string" } },+ },+ },+ },+ },},};@@ -932,6 +1003,22 @@ async function toolBrainRecallGate(emitGatedTelemetry(resolveRecallGateTelemetry(ctx.configPath ?? undefined), () =>recordRecallAdequacyDemand(ctx.vault, { query: prompt, verdict }),);+ // Typed negative recall (silence-is-not-an-answer, U2). The adequacy+ // verdict above judges the HITS; this judges the CORPUS they were drawn+ // from, and only a zero-usable-result attempt has a corpus statement to+ // make. Persisted behind the same `recall_gate_telemetry` opt-in and the+ // same fail-open kernel as everything else this handler writes.+ const negative = verdict.resultCount === 0 ? await assessNegativeRecall(ctx) : null;+ if (negative !== null) {+ emitGatedTelemetry(resolveRecallGateTelemetry(ctx.configPath ?? undefined), () => {+ const sessionId = coerceStringOptional(args, "session_id", 512);+ return emitNegativeRecallTelemetry(ctx.vault, {+ prompt,+ verdict: negative,+ ...(sessionId !== undefined ? { sessionId } : {}),+ });+ });+ }return {...decision,adequacy: {@@ -943,9 +1030,68 @@ async function toolBrainRecallGate(mean_score: verdict.meanScore,reason: verdict.reason,},+ // Absent, never null, when the attempt had usable results - the+ // convention the `explain` trace and the `adequacy` block above set.+ ...(negative !== null ? { negative } : {}),};}+/**+ * Both root sets unresolved. Handed to the classifier when the index+ * facts could not be read at all, which it reports as+ * `unknown`/`coverage-unavailable` - deliberately not as an absent index+ * and never as an exhaustively searched one.+ */+const UNRESOLVED_COVERAGE_SCOPE: CoverageScope = Object.freeze({+ authorizedRoots: Object.freeze([]),+ indexedRoots: Object.freeze([]),+});++/**+ * The corpus statement behind a zero-result recall attempt.+ *+ * Gathers the two universes the verdict is judged against - what the+ * index holds (`indexStatus`) and which authorized note roots it actually+ * reached (`indexRootCoverage` over `resolveNoteRoots`) - and hands them+ * to the pure classifier.+ *+ * It supplies no retraction evidence and asserts nothing, which is why+ * this surface declares only {@link RECALL_GATE_NEGATIVE_STATES}: a gate+ * that reads no claim graph has no grounds for `did_not_happen`, and+ * inventing grounds on the zero-result path is a design decision taken+ * separately from this wiring.+ *+ * Every read is attempted before anything is committed to, so a failure+ * anywhere leaves BOTH inputs unresolved rather than half-resolved: a+ * partially gathered picture is exactly the material a misleading+ * `not_found` would be built from. The failure is not swallowed either;+ * it surfaces as the named `coverage-unavailable` reason, which is the+ * whole point of the unit.+ */+async function assessNegativeRecall(ctx: ServerContext): Promise<NegativeRecallVerdict> {+ let snapshot: CoverageIndexSnapshot | null = null;+ let scope: CoverageScope = UNRESOLVED_COVERAGE_SCOPE;+ try {+ const config = resolveSearchConfig({+ vault: ctx.vault,+ configPath: ctx.configPath ?? undefined,+ });+ const status = await indexStatus(config);+ const authorizedRoots = resolveNoteRoots(ctx.vault);+ // Skip the second open when there is nothing it could answer: no+ // index to read, or no note root the operator authorized.+ const indexedRoots =+ status.exists && authorizedRoots.length > 0+ ? (await indexRootCoverage(config, authorizedRoots)).rootsWithDocuments+ : [];+ snapshot = status;+ scope = { authorizedRoots, indexedRoots };+ } catch {+ // Deliberately empty: the unresolved defaults above ARE the report.+ }+ return classifyNegativeRecall({ snapshot, scope });+}+/*** Parse the optional `scores` argument for the recall gate. Returns* `undefined` when absent (verdict skipped) and throws INVALID_PARAMS ondiff --git a/tests/cli/brain-schema-cli.test.ts b/tests/cli/brain-schema-cli.test.tsindex 1499ca57..80d5722e 100644--- a/tests/cli/brain-schema-cli.test.ts+++ b/tests/cli/brain-schema-cli.test.ts@@ -120,7 +120,7 @@ describe("o2b brain schema", () => {expect(r.stdout).toContain("[unused-declaration] preference_types decision");});- test("management subcommands expose stats, lint, graph, explain, orphans, and sync", async () => {+ test("management subcommands expose stats, lint, graph, explain, and orphans", async () => {seedSchemaVault();const stats = await runCli(["brain", "schema", "stats", "--json"], {@@ -154,10 +154,76 @@ describe("o2b brain schema", () => {});expect(orphans.returncode).toBe(0);expect(JSON.parse(orphans.stdout).orphans.length).toBeGreaterThan(0);+ });+ test("sync refuses instead of reporting a backfill it never ran", async () => {const sync = await runCli(["brain", "schema", "sync", "--dry-run", "--json"], { env: env() });- expect(sync.returncode).toBe(0);- expect(JSON.parse(sync.stdout).dry_run).toBe(true);++ expect(sync.returncode).not.toBe(0);+ expect(sync.stderr).toContain("schema sync is not implemented");+ // The old stub printed a success report on stdout; nothing may now.+ expect(sync.stdout).toBe("");+ });++ test("sync still validates its flags before refusing", async () => {+ const sync = await runCli(["brain", "schema", "sync", "--batch-size", "0"], { env: env() });++ expect(sync.returncode).not.toBe(0);+ expect(sync.stderr).toContain("--batch-size must be a positive integer");+ });++ test("the report names the integrity of the pack it describes", async () => {+ seedSchemaVault();++ // No audited apply has happened in this vault, so the pack carries no+ // recorded expectation - which must not read as an intact one.+ const before = await runCli(["brain", "schema", "--json"], { env: env() });+ expect(before.returncode).toBe(0);+ const unsealed = JSON.parse(before.stdout) as {+ integrity: { status: string; unverified_reason?: string };+ };+ expect(unsealed.integrity.status).toBe("unverified");+ expect(unsealed.integrity.unverified_reason).toBe("no-apply-recorded");++ const mutation = JSON.stringify({+ op: "add_type",+ category: "preference_types",+ token: "strategy",+ });+ const applied = await runCli(["brain", "schema", "apply", "--mutation", mutation, "--json"], {+ env: env(),+ });+ expect(applied.returncode).toBe(0);++ const after = await runCli(["brain", "schema"], { env: env() });+ expect(after.returncode).toBe(0);+ expect(after.stdout).toContain("integrity: ok");+ });++ test("the report reports a hand-edited pack as modified with both digests", async () => {+ const mutation = JSON.stringify({+ op: "add_type",+ category: "preference_types",+ token: "strategy",+ });+ const applied = await runCli(["brain", "schema", "apply", "--mutation", mutation, "--json"], {+ env: env(),+ });+ expect(applied.returncode).toBe(0);+ const sealed = JSON.parse(applied.stdout) as { pack_digest: string };++ const brainConfig = join(vault, "Brain", "_brain.yaml");+ writeFileSync(+ brainConfig,+ readFileSync(brainConfig, "utf8").replace(" - strategy", " - strategy\n - tactic"),+ "utf8",+ );++ const report = await runCli(["brain", "schema"], { env: env() });++ expect(report.returncode).toBe(0);+ expect(report.stdout).toContain("integrity: modified");+ expect(report.stdout).toContain(`expected "${sealed.pack_digest}"`);});test("apply subcommand mutates the schema pack", async () => {diff --git a/tests/cli/brain-timezone.test.ts b/tests/cli/brain-timezone.test.tsindex 16c787dc..b4ec1c22 100644--- a/tests/cli/brain-timezone.test.ts+++ b/tests/cli/brain-timezone.test.ts@@ -12,7 +12,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";-import { runCli } from "../helpers/run-cli.ts";+import { runCli, type RunResult } from "../helpers/run-cli.ts";let tmp: string;let vault: string;@@ -70,13 +70,21 @@ test("without a configured timezone the envelope carries no local fields", asynctest("weekly, monthly, and timeline envelopes localize the same way", async () => {enableTimezone("Asia/Tokyo");const env = { OPEN_SECOND_BRAIN_CONFIG: configPath };- const results = await Promise.all(- [- ["brain", "weekly", "--week-end", "2026-06-05", "--vault", vault, "--json"],- ["brain", "monthly", "--month", "2026-06", "--vault", vault, "--json"],- ["brain", "timeline", "--vault", vault, "--json"],- ].map((argv) => runCli(argv, { env })),- );+ // Sequential on purpose: an in-process run swaps process.env, the working+ // directory and both output streams, so overlapping runs restore each+ // otherโs saved state and corrupt both the captured output and the+ // environment every later test file reads. runCli refuses to overlap.+ const results: RunResult[] = [];+ for (const argv of [+ ["brain", "weekly", "--week-end", "2026-06-05", "--vault", vault, "--json"],+ ["brain", "monthly", "--month", "2026-06", "--vault", vault, "--json"],+ ["brain", "timeline", "--vault", vault, "--json"],+ ]) {+ // The rule suggests Promise.all, which is exactly the overlap runCli+ // now refuses; see the comment above this loop.+ // eslint-disable-next-line no-await-in-loop+ results.push(await runCli(argv, { env }));+ }for (const r of results) {expect(r.returncode).toBe(0);const parsed = JSON.parse(r.stdout) as Record<string, unknown>;diff --git a/tests/cli/brain-trigger.test.ts b/tests/cli/brain-trigger.test.tsnew file mode 100644index 00000000..b0819dbb--- /dev/null+++ b/tests/cli/brain-trigger.test.ts@@ -0,0 +1,262 @@+/**+ * `o2b brain trigger` (Workspace Insight Suite, t_cd1fee79; suppression+ * from silence-is-not-an-answer, U5).+ *+ * The verb had no CLI coverage at all, which is how a nested-ternary+ * verb map that routed every unrecognised verb to the `act` transition+ * survived unnoticed. These tests pin the JSON projection, the+ * suppressed summary, the usage string and the verb routing.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { createTriggers } from "../../src/core/brain/triggers/store.ts";+import type { InsightCandidate, TriggerRecord } from "../../src/core/brain/triggers/types.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let configPath: string;++const 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: [],+ cooldownKey: "contradiction:pref-a:pref-b",+};++interface TriggerJson {+ readonly id: string;+ readonly status: string;+ readonly occurrences: number;+ readonly last_seen_at: string;+ readonly suppressed_at: string | null;+ readonly suppressed_from: string | null;+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-trigger-cli-"));+ vault = join(tmp, "vault");+ configPath = join(tmp, "config.yaml");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test-agent\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });++function seedRecord(overrides: Partial<InsightCandidate> = {}): TriggerRecord {+ const { created } = createTriggers(vault, [{ ...CANDIDATE, ...overrides }], { now: new Date() });+ return created[0]!;+}++function seed(overrides: Partial<InsightCandidate> = {}): string {+ return seedRecord(overrides).id;+}++/** Seed one record and make a field of it unreadable, as a hand-edit would. */+function seedUnreadable(overrides: Partial<InsightCandidate> = {}): string {+ const { path } = seedRecord(overrides);+ writeFileSync(+ path,+ readFileSync(path, "utf8").replace(/^occurrences: .*$/mu, "occurrences: many"),+ "utf8",+ );+ return path;+}++interface UnreadableJson {+ readonly path: string;+ readonly key: string | null;+ readonly error: string;+}++async function listJson(): Promise<{+ triggers: TriggerJson[];+ suppressed: number;+ unreadable: UnreadableJson[];+}> {+ const out = await runCli(["brain", "trigger", "list", "--json"], { env: env() });+ expect(out.returncode).toBe(0);+ return JSON.parse(out.stdout) as {+ triggers: TriggerJson[];+ suppressed: number;+ unreadable: UnreadableJson[];+ };+}++describe("o2b brain trigger", () => {+ test("a bad verb prints the usage string naming every verb", async () => {+ const out = await runCli(["brain", "trigger", "explode"], { env: env() });+ expect(out.returncode).not.toBe(0);+ const usage = out.stdout + out.stderr;+ expect(usage).toContain("usage: o2b brain trigger");+ for (const verb of [+ "scan",+ "list",+ "ack",+ "dismiss",+ "act",+ "suppress",+ "unsuppress",+ "history",+ ]) {+ expect(usage).toContain(verb);+ }+ });++ test("list --json carries the suppression and recurrence fields", async () => {+ const id = seed();+ const listed = await listJson();+ expect(listed.triggers).toHaveLength(1);+ const record = listed.triggers[0]!;+ expect(record.id).toBe(id);+ expect(record.status).toBe("pending");+ expect(record.occurrences).toBe(1);+ expect(record.last_seen_at).toEqual(expect.any(String));+ expect(record.suppressed_at).toBeNull();+ expect(record.suppressed_from).toBeNull();+ });++ test("list reports how many triggers are silenced, in both output modes", async () => {+ const id = seed();+ seed({ cooldownKey: "contradiction:pref-c:pref-d" });+ expect((await listJson()).suppressed).toBe(0);++ const suppressed = await runCli(["brain", "trigger", "suppress", id], { env: env() });+ expect(suppressed.returncode).toBe(0);+ expect(suppressed.stdout).toContain("[suppressed]");++ const after = await listJson();+ expect(after.suppressed).toBe(1);+ // A suppressed trigger is terminal, so `list` no longer shows it.+ expect(after.triggers.map((t) => t.id)).not.toContain(id);++ const text = await runCli(["brain", "trigger", "list"], { env: env() });+ expect(text.returncode).toBe(0);+ expect(text.stdout).toContain("suppressed: 1");+ });++ test("suppress then unsuppress restores the prior status through the CLI", async () => {+ const id = seed();+ await runCli(["brain", "trigger", "dismiss", id], { env: env() });+ await runCli(["brain", "trigger", "suppress", id], { env: env() });++ const history = await runCli(["brain", "trigger", "history", "--json"], { env: env() });+ const historyRecords = (JSON.parse(history.stdout) as { triggers: TriggerJson[] }).triggers;+ expect(historyRecords.map((t) => t.status)).toEqual(["suppressed"]);+ expect(historyRecords[0]!.suppressed_from).toBe("dismissed");++ const restored = await runCli(["brain", "trigger", "unsuppress", id, "--json"], { env: env() });+ expect(restored.returncode).toBe(0);+ const record = (JSON.parse(restored.stdout) as { trigger: TriggerJson }).trigger;+ expect(record.status).toBe("dismissed");+ expect(record.suppressed_at).toBeNull();+ expect((await listJson()).suppressed).toBe(0);+ });++ test("unsuppressing a trigger that is not suppressed fails naming its status", async () => {+ const id = seed();+ const out = await runCli(["brain", "trigger", "unsuppress", id], { env: env() });+ expect(out.returncode).not.toBe(0);+ expect(out.stdout + out.stderr).toContain("pending");+ });++ test("each verb routes to its own transition", async () => {+ // The map this pins used to be a nested ternary whose fallback arm+ // was `act`, so any verb that was not `ack` or `dismiss` acted.+ // Sequential on purpose: an in-process CLI run swaps process.env, the+ // working directory and both output streams, so overlapping runs+ // restore each otherโs saved state. runCli refuses to overlap now, and+ // this loop is what that refusal expects.+ const transitioned: string[] = [];+ for (const verb of ["ack", "dismiss", "act"] as const) {+ const id = seed({ cooldownKey: `contradiction:${verb}` });+ // The rule suggests Promise.all, which is exactly the overlap runCli+ // now refuses; see the comment above this loop.+ // eslint-disable-next-line no-await-in-loop+ const out = await runCli(["brain", "trigger", verb, id, "--json"], { env: env() });+ expect(out.returncode).toBe(0);+ transitioned.push((JSON.parse(out.stdout) as { trigger: TriggerJson }).trigger.status);+ }+ expect(transitioned).toEqual(["acknowledged", "dismissed", "acted"]);+ });++ test("a transition verb without an id is a usage error", async () => {+ const out = await runCli(["brain", "trigger", "suppress"], { env: env() });+ expect(out.returncode).not.toBe(0);+ expect(out.stdout + out.stderr).toContain("requires a trigger id");+ });++ test("an unknown --status is rejected rather than silently ignored", async () => {+ seed();+ const out = await runCli(["brain", "trigger", "list", "--status", "nope"], { env: env() });+ expect(out.returncode).not.toBe(0);+ expect(out.stdout + out.stderr).toContain("unknown trigger status");+ });++ test("list reports an empty unreadable set on a healthy queue", async () => {+ seed();+ // Always present, so "none could not be read" is a statement the+ // output makes rather than something a caller has to assume.+ expect((await listJson()).unreadable).toEqual([]);+ });++ test("list names a record it could not read and still shows the healthy one", async () => {+ const healthy = seed();+ const brokenPath = seedUnreadable({ cooldownKey: "contradiction:pref-c:pref-d" });++ const listed = await listJson();+ expect(listed.triggers.map((t) => t.id)).toEqual([healthy]);+ expect(listed.unreadable).toHaveLength(1);+ expect(listed.unreadable[0]!.path).toBe(brokenPath);+ expect(listed.unreadable[0]!.key).toBe("occurrences");++ const text = await runCli(["brain", "trigger", "list"], { env: env() });+ expect(text.returncode).toBe(0);+ expect(text.stdout).toContain("unreadable: 1");+ expect(text.stdout).toContain(brokenPath);+ });++ test("a corrupt record still leaves the healthy one suppressible", async () => {+ const healthy = seed();+ seedUnreadable({ cooldownKey: "contradiction:pref-c:pref-d" });+ const out = await runCli(["brain", "trigger", "suppress", healthy], { env: env() });+ expect(out.returncode).toBe(0);+ expect(out.stdout).toContain("[suppressed]");+ });++ test("the morning brief says the queue is unreadable instead of falling silent", async () => {+ seedUnreadable();+ const json = await runCli(["brain", "morning-brief", "--json"], { env: env() });+ expect(json.returncode).toBe(0);+ const parsed = JSON.parse(json.stdout) as { triggers_unreadable?: UnreadableJson[] };+ expect(parsed.triggers_unreadable).toHaveLength(1);+ expect(parsed.triggers_unreadable![0]!.key).toBe("occurrences");++ const text = await runCli(["brain", "morning-brief"], { env: env() });+ expect(text.returncode).toBe(0);+ expect(text.stdout).toContain("Unreadable triggers");+ });++ test("--status suppressed lists exactly the silenced triggers", async () => {+ const id = seed();+ seed({ cooldownKey: "contradiction:pref-c:pref-d" });+ await runCli(["brain", "trigger", "suppress", id], { env: env() });+ const out = await runCli(["brain", "trigger", "list", "--status", "suppressed", "--json"], {+ env: env(),+ });+ expect(out.returncode).toBe(0);+ const parsed = JSON.parse(out.stdout) as { triggers: TriggerJson[] };+ expect(parsed.triggers.map((t) => t.id)).toEqual([id]);+ });+});diff --git a/tests/cli/brain.snapshot-log.test.ts b/tests/cli/brain.snapshot-log.test.tsnew file mode 100644index 00000000..5ddd5f0f--- /dev/null+++ b/tests/cli/brain.snapshot-log.test.ts@@ -0,0 +1,285 @@+/**+ * U7: `o2b brain snapshot log`.+ *+ * The snapshot family already had a diff and a revert (`snapshot diff`,+ * `rollback`); what it had no surface for was the LIST - so an operator+ * could not ask which recovery point covers a given boundary without+ * reading filenames out of `.snapshots/`. This file pins that surface:+ * newest-first ordering, the reason column, the reason filter, the usage+ * exit on an unregistered filter value, the limit, and the honest+ * zero-exit on a vault that has taken no snapshots at all.+ *+ * The snapshots are built through the core engine rather than by running+ * `brain dream` three times: the ordering assertions need controlled+ * mtimes and distinct reasons, and a dream run can only ever produce one+ * of the nine.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { chmodSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { createSnapshot } from "../../src/core/brain/snapshot.ts";+import { manifestSidecarPath } from "../../src/core/brain/manifest.ts";+import { brainDirs, snapshotPath } from "../../src/core/brain/paths.ts";+import { BRAIN_SNAPSHOT_REASON } from "../../src/core/brain/types.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-snaplog-"));+ vault = join(tmp, "vault");+ config = join(tmp, "config.yaml");+ atomicWriteFileSync(config, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath: config });+ writeFileSync(+ join(brainDirs(vault).preferences, "pref-seed.md"),+ "---\nkind: brain-preference\n---\n\n## Principle\n\nseed\n",+ );+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** Run the verb with this test's sandboxed config. */+async function snapshotLog(...args: string[]): ReturnType<typeof runCli> {+ return await runCli(["brain", "snapshot", "log", "--vault", vault, ...args], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+}++/**+ * Three recovery points with distinct reasons and deliberately-ordered+ * mtimes, so "newest first" is a real assertion rather than an artefact of+ * creation order. The listing sorts by mtime because a hand-named run id+ * carries no timestamp to sort on.+ */+const SEEDED = Object.freeze([+ { runId: "dream-oldest", reason: BRAIN_SNAPSHOT_REASON.dream, minutes: 30 },+ { runId: "entity-prune-middle", reason: BRAIN_SNAPSHOT_REASON.entityPrune, minutes: 20 },+ { runId: "dream-newest", reason: BRAIN_SNAPSHOT_REASON.dream, minutes: 10 },+]);++function seedSnapshots(): void {+ const now = Date.now();+ for (const s of SEEDED) {+ createSnapshot(vault, s.runId, { reason: s.reason });+ const when = new Date(now - s.minutes * 60_000);+ utimesSync(snapshotPath(vault, s.runId), when, when);+ }+}++describe("brain snapshot log", () => {+ test("lists newest first with the reason of each recovery point", async () => {+ seedSnapshots();+ const r = await snapshotLog();+ expect(r.returncode).toBe(0);+ const rows = r.stdout.trimEnd().split("\n");+ // A header line, then one row per snapshot in mtime-descending order.+ expect(rows[0]).toContain("run_id");+ expect(rows[0]).toContain("reason");+ expect(rows.slice(1).map((line) => line.split("\t")[0])).toEqual([+ "dream-newest",+ "entity-prune-middle",+ "dream-oldest",+ ]);+ expect(rows[1]).toContain(BRAIN_SNAPSHOT_REASON.dream);+ expect(rows[2]).toContain(BRAIN_SNAPSHOT_REASON.entityPrune);+ });++ test("--json carries the reason, the manifest and the derived-store record", async () => {+ seedSnapshots();+ const r = await snapshotLog("--json");+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ total: number;+ snapshots: ReadonlyArray<{+ run_id: string;+ reason: string | null;+ manifest: boolean;+ derived_store: unknown;+ size_bytes: number;+ created_at: string;+ }>;+ };+ expect(payload.total).toBe(3);+ expect(payload.snapshots.map((s) => s.run_id)).toEqual([+ "dream-newest",+ "entity-prune-middle",+ "dream-oldest",+ ]);+ expect(payload.snapshots[0]!.reason).toBe(BRAIN_SNAPSHOT_REASON.dream);+ expect(payload.snapshots[0]!.manifest).toBe(true);+ expect(payload.snapshots[0]!.size_bytes).toBeGreaterThan(0);+ expect(payload.snapshots[0]!.derived_store).not.toBeNull();+ });++ test("--reason filters the revertible history by why it happened", async () => {+ seedSnapshots();+ const r = await snapshotLog("--reason", BRAIN_SNAPSHOT_REASON.dream, "--json");+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ total: number;+ snapshots: ReadonlyArray<{ run_id: string }>;+ };+ expect(payload.snapshots.map((s) => s.run_id)).toEqual(["dream-newest", "dream-oldest"]);+ expect(payload.total).toBe(2);+ });++ test("a reason that matches nothing exits zero with an empty listing", async () => {+ seedSnapshots();+ const r = await snapshotLog("--reason", BRAIN_SNAPSHOT_REASON.manual);+ // Nothing found is not a failure: the question was answerable and the+ // answer is none.+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("no snapshots");+ });++ test("an unregistered reason is a usage error, not an empty result", async () => {+ seedSnapshots();+ const r = await snapshotLog("--reason", "spring-cleaning");+ // Exit 2 and a named cause, matching how `brain event-trace` rejects a+ // bad --kind. Returning an empty listing would tell the operator their+ // vault has no such snapshots when in fact their filter was invalid.+ expect(r.returncode).toBe(2);+ expect(r.stderr).toContain("spring-cleaning");+ });++ test("--limit honours a positive integer and rejects anything else", async () => {+ seedSnapshots();+ const limited = await snapshotLog("--limit", "2", "--json");+ expect(limited.returncode).toBe(0);+ const payload = JSON.parse(limited.stdout) as { snapshots: ReadonlyArray<{ run_id: string }> };+ expect(payload.snapshots.map((s) => s.run_id)).toEqual(["dream-newest", "entity-prune-middle"]);++ const zero = await snapshotLog("--limit", "0");+ expect(zero.returncode).toBe(2);+ const words = await snapshotLog("--limit", "many");+ expect(words.returncode).toBe(2);+ });++ test("an empty snapshots directory exits zero", async () => {+ const r = await snapshotLog();+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("no snapshots");+ });++ test("an empty snapshots directory exits zero under --json too", async () => {+ const r = await snapshotLog("--json");+ expect(r.returncode).toBe(0);+ expect(JSON.parse(r.stdout)).toEqual({ total: 0, snapshots: [] });+ });++ test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(+ "a snapshots directory it cannot read is a failure, not an empty history",+ async () => {+ seedSnapshots();+ const snapshots = brainDirs(vault).snapshots;+ chmodSync(snapshots, 0o000);+ try {+ const r = await snapshotLog();+ // "no snapshots available" over a directory nobody could read is+ // the exact confusion this release exists to remove.+ expect(r.returncode).not.toBe(0);+ expect(r.stdout).not.toContain("no snapshots");+ expect(r.stderr).toContain(snapshots);+ } finally {+ chmodSync(snapshots, 0o755);+ }+ },+ );++ test("a snapshot with no sidecar reports an unknown reason, not its run-id prefix", async () => {+ createSnapshot(vault, "dream-unstamped", { reason: BRAIN_SNAPSHOT_REASON.dream });+ rmSync(manifestSidecarPath(vault, "dream-unstamped"), { force: true });+ const r = await snapshotLog("--json");+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ snapshots: ReadonlyArray<{ reason: string | null; manifest: boolean }>;+ };+ expect(payload.snapshots[0]!.reason).toBeNull();+ expect(payload.snapshots[0]!.manifest).toBe(false);+ const text = await snapshotLog();+ expect(text.stdout).toContain("unknown");+ });++ test("the subcommand is offered by the snapshot help", async () => {+ const r = await runCli(["brain", "snapshot", "--help", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("log");+ expect(r.stdout).toContain("diff");+ });+});++describe("brain rollback --list carries the reason", () => {+ test("the text listing gains a reason column", async () => {+ seedSnapshots();+ const r = await runCli(["brain", "rollback", "--list", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ const rows = r.stdout.trimEnd().split("\n");+ expect(rows[0]!.split("\t")).toEqual([+ "run_id",+ "created_at",+ "reason",+ "size_bytes",+ "derived_store",+ ]);+ // Column 2 (zero-based) is the reason, read off the sidecar.+ expect(rows[1]!.split("\t")[2]).toBe(BRAIN_SNAPSHOT_REASON.dream);+ expect(rows[2]!.split("\t")[2]).toBe(BRAIN_SNAPSHOT_REASON.entityPrune);+ });++ test("--list --json carries the reason on every entry", async () => {+ seedSnapshots();+ const r = await runCli(["brain", "rollback", "--list", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ const snaps = JSON.parse(r.stdout) as ReadonlyArray<{ run_id: string; reason: string | null }>;+ expect(snaps.map((s) => s.reason)).toEqual([+ BRAIN_SNAPSHOT_REASON.dream,+ BRAIN_SNAPSHOT_REASON.entityPrune,+ BRAIN_SNAPSHOT_REASON.dream,+ ]);+ });++ test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(+ "an unreadable snapshots directory is reported, not listed as empty",+ async () => {+ seedSnapshots();+ const snapshots = brainDirs(vault).snapshots;+ chmodSync(snapshots, 0o000);+ try {+ const r = await runCli(["brain", "rollback", "--list", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).not.toBe(0);+ expect(r.stdout).not.toContain("no snapshots available");+ expect(r.stderr).toContain(snapshots);+ } finally {+ chmodSync(snapshots, 0o755);+ }+ },+ );++ test("an unstamped snapshot lists as unknown rather than as its prefix", async () => {+ createSnapshot(vault, "dream-unstamped", { reason: BRAIN_SNAPSHOT_REASON.dream });+ rmSync(manifestSidecarPath(vault, "dream-unstamped"), { force: true });+ const r = await runCli(["brain", "rollback", "--list", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).toBe(0);+ expect(r.stdout.trimEnd().split("\n")[1]!.split("\t")[2]).toBe("unknown");+ });+});diff --git a/tests/cli/brain.test.ts b/tests/cli/brain.test.tsindex ad85f339..f2b4afa5 100644--- a/tests/cli/brain.test.ts+++ b/tests/cli/brain.test.ts@@ -1132,6 +1132,52 @@ describe("brain rollback", () => {expect(r.returncode).toBe(0);expect(r.stderr).toContain("no manifest sidecar");expect(r.stderr).toContain("predates v0.10.6");+ // Coverage is unknown for a snapshot with no sidecar at all, and the+ // restore says so rather than leaving it implicit.+ expect(r.stdout).toContain("derived store: unknown");+ });++ test("reports derived-store coverage on --list and on a restore", async () => {+ await bootstrap();+ await runCli(+ [+ "brain",+ "feedback",+ "--vault",+ vault,+ "--topic",+ "store-coverage",+ "--signal",+ "positive",+ "--principle",+ "p",+ "--force-confirmed",+ "--agent",+ "claude",+ ],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ const dr = await runCli(["brain", "dream", "--vault", vault, "--json"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ const dpayload = JSON.parse(dr.stdout) as { run_id: string; changed: boolean };+ if (!dpayload.changed) return;++ const listed = await runCli(["brain", "rollback", "--vault", vault, "--list"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(listed.returncode).toBe(0);+ expect(listed.stdout).toContain("derived_store");+ // Default configuration: nothing was requested, and the listing+ // names that rather than showing a blank column.+ expect(listed.stdout).toContain("excluded (not-requested)");++ const restored = await runCli(+ ["brain", "rollback", "--vault", vault, dpayload.run_id, "--yes", "--force-rollback"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: config } },+ );+ expect(restored.returncode).toBe(0);+ expect(restored.stdout).toContain("derived store: not restored (not-requested)");});});diff --git a/tests/cli/completions.test.ts b/tests/cli/completions.test.tsindex 3beaaa9a..5e53ccae 100644--- a/tests/cli/completions.test.ts+++ b/tests/cli/completions.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from "bun:test";+import { nestedCommandGroups } from "../../src/cli/command-manifest.ts";import { runCli } from "../helpers/run-cli.ts";describe("CLI command manifest", () => {@@ -52,3 +53,46 @@ describe("o2b completions", () => {expect(result.stderr).toContain("unsupported completion shell: xonsh");});});++describe("nested subcommand coverage", () => {+ // The renderer used to hand-list the three roots it knew about. A fourth+ // that grew subcommands was therefore offered by no shell, and nothing+ // said so: the completion simply produced nothing where a verb existed.+ // Deriving the groups from the manifest fixed it; this is what keeps it+ // fixed, at every depth rather than only the first.+ const groups = nestedCommandGroups();++ test("the manifest models nested groups below the first level", () => {+ // Guards the assertions below against passing because the collector+ // silently stopped recursing.+ expect(groups.some((group) => group.parent === "partner")).toBe(true);+ expect(groups.find((group) => group.parent === "codegraph")?.children).toContain("resync");+ });++ test("bash offers every nested group", async () => {+ const out = await runCli(["completions", "bash"]);+ expect(out.returncode).toBe(0);+ for (const group of groups) {+ expect(out.stdout).toContain(`"$prev" == "${group.parent}"`);+ for (const child of group.children) expect(out.stdout).toContain(child);+ }+ });++ test("zsh offers every nested subcommand", async () => {+ const out = await runCli(["completions", "zsh"]);+ expect(out.returncode).toBe(0);+ const line = out.stdout.split("\n").find((l) => l.includes("2:subcommand:"));+ expect(line).toBeDefined();+ for (const group of groups) {+ for (const child of group.children) expect(line).toContain(child);+ }+ });++ test("fish scopes every nested group to its own parent", async () => {+ const out = await runCli(["completions", "fish"]);+ expect(out.returncode).toBe(0);+ for (const group of groups) {+ expect(out.stdout).toContain(`__fish_seen_subcommand_from ${group.parent}`);+ }+ });+});diff --git a/tests/cli/cron-recipe.test.ts b/tests/cli/cron-recipe.test.tsnew file mode 100644index 00000000..221b2796--- /dev/null+++ b/tests/cli/cron-recipe.test.ts@@ -0,0 +1,120 @@+/**+ * The shared cron-recipe kernel, exercised through a synthetic spec.+ *+ * Both real consumers pin their own rendered output, which proves what+ * they render but not what the kernel guarantees to ANY consumer. This+ * file renders a spec made of sentinels that appear nowhere else, so it+ * can assert two things the fixtures cannot:+ *+ * - every field of the spec actually reaches the output, and reaches it+ * in exactly one place - the script is written once, the cron job is+ * named once, the verification is stated once;+ * - every numbered section and the scheduler line are present, so a+ * future recipe cannot quietly lose one. A recipe missing its crontab+ * section still looks like a recipe.+ */++import { describe, expect, test } from "bun:test";++import {+ CronTemplateError,+ operatorScriptPath,+ renderCronRecipe,+ type CronRecipeSpec,+} from "../../src/cli/cron-recipe.ts";++/** Sentinels chosen so no two are a substring of another. */+const SENTINEL = Object.freeze({+ title: "Synthetic Suite - probe recipe",+ cronName: "probe-job",+ scriptStem: "probe-runner",+ note: "probe note line",+ schedulerNote: "(probe scheduler note)",+ bodyMarker: "probe_body_marker",+ verify: "probe-verify --now",+});++const SPEC: CronRecipeSpec = Object.freeze<CronRecipeSpec>({+ title: SENTINEL.title,+ cronName: SENTINEL.cronName,+ scriptPath: operatorScriptPath(SENTINEL.scriptStem),+ scriptNotes: Object.freeze([SENTINEL.note]),+ schedulerNote: SENTINEL.schedulerNote,+ buildScriptBody: ({ o2bBin }) => `#!/usr/bin/env bash\n${SENTINEL.bodyMarker} ${o2bBin}\n`,+ buildVerifyCommand: ({ o2bBin }) => `${o2bBin} ${SENTINEL.verify}`,+});++const SCRIPT_PATH = operatorScriptPath(SENTINEL.scriptStem);++function occurrences(haystack: string, needle: string): number {+ return haystack.split(needle).length - 1;+}++describe("renderCronRecipe", () => {+ test("every spec field reaches the output", () => {+ const out = renderCronRecipe(SPEC, "30m", {});+ for (const value of [+ SENTINEL.title,+ SENTINEL.cronName,+ SCRIPT_PATH,+ SENTINEL.note,+ SENTINEL.schedulerNote,+ SENTINEL.bodyMarker,+ SENTINEL.verify,+ ]) {+ expect(`${value} present: ${out.includes(value)}`).toBe(`${value} present: true`);+ }+ });++ test("the cron job is named once, the script written once, the verify stated once", () => {+ const out = renderCronRecipe(SPEC, "30m", {});+ // The job name appears only where the scheduler is told it.+ expect(occurrences(out, SENTINEL.cronName)).toBe(1);+ // The script path appears in four places by design (section heading,+ // heredoc, chmod, crontab line) but is CREATED exactly once - a second+ // heredoc would silently overwrite the first.+ expect(occurrences(out, `cat >${SCRIPT_PATH} <<`)).toBe(1);+ expect(occurrences(out, SENTINEL.verify)).toBe(1);+ });++ test("every numbered section and the scheduler line are present", () => {+ const out = renderCronRecipe(SPEC, "30m", {});+ for (const section of [+ "## 1. Watchdog script - save to ",+ "## 2. Native crontab - open 'crontab -e' and append:",+ "## 3. Hermes cron ",+ ]) {+ expect(`${section} present: ${out.includes(section)}`).toBe(`${section} present: true`);+ }+ expect(out).toContain("hermes cron create \\");+ expect(out).toContain(` --name ${SENTINEL.cronName} \\`);+ expect(out).toContain(" --no-agent");+ expect(out).toContain("# After install, verify with: ");+ });++ test("the interval is rendered as cron in both the crontab and the scheduler line", () => {+ const out = renderCronRecipe(SPEC, "6h", {});+ expect(out).toContain("# interval: 6 hours");+ expect(out).toContain(`0 */6 * * * ${SCRIPT_PATH}`);+ expect(out).toContain(" --schedule '0 */6 * * *' \\");+ });++ test("the scheduler command uses the $HOME form the shell will expand", () => {+ // A quoted "~/..." argument is not tilde-expanded, so the scheduler+ // would store a path that resolves to nothing.+ const out = renderCronRecipe(SPEC, "30m", {});+ expect(out).toContain(` --command "$HOME/.local/bin/${SENTINEL.scriptStem}.sh" \\`);+ expect(out).not.toContain(` --command "~/`);+ });++ test("the binary override reaches both builders", () => {+ const out = renderCronRecipe(SPEC, "30m", { o2bBin: "/opt/probe/o2b" });+ expect(out).toContain(`${SENTINEL.bodyMarker} /opt/probe/o2b`);+ expect(out).toContain(`# After install, verify with: /opt/probe/o2b ${SENTINEL.verify}`);+ });++ test("an interval cron cannot express is refused, not rounded", () => {+ expect(() => renderCronRecipe(SPEC, "90m", {})).toThrow(CronTemplateError);+ expect(() => renderCronRecipe(SPEC, "nonsense", {})).toThrow(CronTemplateError);+ });+});diff --git a/tests/cli/manifest-completeness.test.ts b/tests/cli/manifest-completeness.test.tsindex 4774a594..f4e97f0a 100644--- a/tests/cli/manifest-completeness.test.ts+++ b/tests/cli/manifest-completeness.test.ts@@ -15,10 +15,17 @@* the reverse. A manifest cannot vouch for its own completeness.** Scope is one level below each dispatcher - the switch in `main.ts`,- * the switch in `brain.ts`, and `KNOWN_VERBS` in `search.ts`. Deeper- * nesting (`brain schema report`, `brain git ingest`) is parsed by each- * verb from its own positionals, with no shared table to enumerate from,- * so it is out of this ratchet's reach and stays modelled by hand.+ * the switch in `brain.ts`, `KNOWN_VERBS` in `search.ts`, and the verb+ * table in `partner.ts`. Deeper nesting (`brain schema report`, `brain+ * git ingest`) is parsed by each verb from its own positionals, with no+ * shared table to enumerate from, so it is out of this ratchet's reach+ * and stays modelled by hand.+ *+ * `partner codegraph` sits two levels deep but IS enumerable, because its+ * dispatcher is a frozen verb table rather than a chain of comparisons.+ * That is why it was written as a table: a verb the manifest never heard+ * of is a verb no completion offers, and `resync --cron-template` is the+ * only way to reach the codegraph resync recipe at all.*/import { describe, expect, test } from "bun:test";@@ -48,6 +55,9 @@ const BRAIN_UNLISTED: Readonly<Record<string, string>> = Object.freeze({});/** `search` verbs with no manifest entry, and why. */const SEARCH_UNLISTED: Readonly<Record<string, string>> = Object.freeze({});+/** `partner codegraph` verbs with no manifest entry, and why. */+const PARTNER_CODEGRAPH_UNLISTED: Readonly<Record<string, string>> = Object.freeze({});+/** An exclusion reason has to say something; ten characters is the floor. */const MIN_REASON_LENGTH = 10;@@ -70,6 +80,31 @@ function switchCaseLabels(file: string, marker: string): string[] {return [...text.slice(start, end).matchAll(/case "([^"]+)":/g)].map((m) => m[1]!);}+/** The keys of the `CODEGRAPH_VERBS` table literal in `partner.ts`. */+function partnerCodegraphVerbs(): string[] {+ const text = cliSource("partner.ts");+ const start = text.indexOf("const CODEGRAPH_VERBS");+ expect(`partner.ts declares CODEGRAPH_VERBS: ${start >= 0}`).toBe(+ "partner.ts declares CODEGRAPH_VERBS: true",+ );+ const open = text.indexOf("Object.freeze({", start);+ const end = text.indexOf("});", open);+ expect(`the partner verb table is terminated: ${end > open}`).toBe(+ "the partner verb table is terminated: true",+ );+ return [...text.slice(open, end).matchAll(/^\s{4}([A-Za-z][\w-]*):/gm)].map((m) => m[1]!);+}++/** Manifest children of `o2b partner codegraph`. */+function manifestPartnerCodegraphVerbs(): string[] {+ const partner = CLI_COMMAND_MANIFEST.commands.find((c) => c.name === "partner");+ const codegraph = partner?.commands?.find((c) => c.name === "codegraph");+ expect(`the manifest models partner codegraph: ${codegraph !== undefined}`).toBe(+ "the manifest models partner codegraph: true",+ );+ return (codegraph?.commands ?? []).map((c) => c.name);+}+/** The `KNOWN_VERBS` set literal in `search.ts`. */function searchKnownVerbs(): string[] {const text = cliSource("search.ts");@@ -122,6 +157,12 @@ function levels(): ReadonlyArray<Level> {manifestVerbs: nestedCommandNames("search"),unlisted: SEARCH_UNLISTED,},+ {+ label: "o2b partner codegraph",+ dispatcherVerbs: partnerCodegraphVerbs(),+ manifestVerbs: manifestPartnerCodegraphVerbs(),+ unlisted: PARTNER_CODEGRAPH_UNLISTED,+ },];}@@ -170,10 +211,11 @@ describe("command manifest completeness", () => {test("the ratchet is not vacuous", () => {// A parser that silently stopped matching would report a clean sweep// over an empty set. Pin the measurement, not only its verdict.- const [top, brain, search] = levels();+ const [top, brain, search, partner] = levels();expect(top!.dispatcherVerbs.length).toBeGreaterThan(15);expect(brain!.dispatcherVerbs.length).toBeGreaterThan(130);expect(search!.dispatcherVerbs.length).toBeGreaterThan(10);+ expect(partner!.dispatcherVerbs.toSorted()).toEqual(["report", "resync"]);});test("the search dispatcher and its verb gate agree", () => {@@ -225,6 +267,34 @@ describe("the repaired manifest reaches its two consumers", () => {}});+ test("completions offer the flags that reach the cron recipes", () => {+ // `search reindex` declared no flags at all, so `--cron-template` -+ // the only entry point to the reindex recipe - completed nowhere.+ // Completion flag lists are built by walking the whole manifest, so a+ // declared flag at any depth reaches every shell.+ const zsh = renderCompletions("zsh", CLI_COMMAND_MANIFEST);+ for (const token of ["--cron-template", "--interval", "--fail-on-health", "--project"]) {+ expect(`${token}: ${zsh.includes(token)}`).toBe(`${token}: true`);+ }+ });++ test("help --json carries the partner codegraph verbs", async () => {+ // `partner` is the one modelled parent whose verbs live two levels+ // down, so the top-level census above cannot see them.+ const r = await runCli(["help", "--json"]);+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ commands: ReadonlyArray<{+ name: string;+ commands?: ReadonlyArray<{ name: string; commands?: ReadonlyArray<{ name: string }> }>;+ }>;+ };+ const codegraph = payload.commands+ .find((c) => c.name === "partner")+ ?.commands?.find((c) => c.name === "codegraph");+ expect((codegraph?.commands ?? []).map((c) => c.name).toSorted()).toEqual(["report", "resync"]);+ });+test("every modelled command carries a non-empty summary", () => {// An entry added only to satisfy the ratchet, with an empty summary,// would complete the manifest and tell a reader nothing.diff --git a/tests/cli/partner-codegraph-resync.test.ts b/tests/cli/partner-codegraph-resync.test.tsnew file mode 100644index 00000000..7ff11eab--- /dev/null+++ b/tests/cli/partner-codegraph-resync.test.ts@@ -0,0 +1,257 @@+/**+ * `o2b partner codegraph resync --cron-template` and the health exit on+ * `o2b partner codegraph report`.+ *+ * Both surfaces are strictly read-only, and the resync verb is the sharper+ * case: it exists to make a re-index happen on a cadence WITHOUT this+ * project ever writing into the partner's store. So the load-bearing+ * assertion is not what it prints but what it does not do - the directory+ * listings before and after a run are compared, and the run that omits the+ * required flag is required to fail rather than quietly do nothing.+ *+ * The emitted script is asserted as text, in order: a gate that ran after+ * the indexer would be no gate at all, and a missing-parser branch that+ * exited zero would be a gate that passes what it could not read.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { renderCodegraphResyncTemplate } from "../../src/cli/partner-codegraph-cron.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-resync-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** A directory the code-project scan recognises: `.git/` plus a manifest. */+function makeRepo(name: string): string {+ const repo = join(tmp, name);+ mkdirSync(join(repo, ".git"), { recursive: true });+ writeFileSync(join(repo, "package.json"), "{}\n");+ return repo;+}++/** Every path under `root`, recursively, as a sorted list. */+function listTree(root: string): string[] {+ const out: string[] = [];+ const walk = (dir: string, prefix: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const rel = prefix === "" ? entry.name : `${prefix}/${entry.name}`;+ out.push(rel);+ if (entry.isDirectory()) walk(join(dir, entry.name), rel);+ }+ };+ walk(root, "");+ return out.toSorted();+}++describe("the resync recipe renders", () => {+ test("the interval as cron, the recipe name, the scheduler and the indexer", () => {+ const body = renderCodegraphResyncTemplate("/srv/projects/demo", "6h");+ expect(body).toContain("# interval: 6 hours");+ expect(body).toContain("0 */6 * * * ~/.local/bin/osb-codegraph-resync.sh");+ expect(body).toContain("--name osb-codegraph-resync");+ expect(body).toContain("hermes cron create");+ expect(body).toContain('codegraph init "$project"');+ expect(body).toContain('project="/srv/projects/demo"');+ });++ test("the wrong-root guard precedes the indexer invocation", () => {+ const body = renderCodegraphResyncTemplate("/srv/projects/demo", "6h");+ const guard = body.indexOf("cache-root-mismatch");+ const indexer = body.indexOf('codegraph init "$project"');+ expect(guard).toBeGreaterThan(-1);+ expect(indexer).toBeGreaterThan(-1);+ expect(`guard before indexer: ${guard < indexer}`).toBe("guard before indexer: true");+ });++ test("the missing-parser branch exits non-zero instead of matching loosely", () => {+ const body = renderCodegraphResyncTemplate("/srv/projects/demo", "6h");+ const branch = body.slice(body.indexOf("if ! command -v jq"), body.indexOf("health=$(cd "));+ expect(branch).toContain("exit 1");+ expect(branch).not.toContain("exit 0");+ // No grep fallback: the reindex recipe has one, and copying it here+ // would let a host without jq index on an unread health verdict.+ expect(body).not.toContain("grep -Eq");+ });++ test("an unparseable health report aborts rather than reading as no mismatch", () => {+ // The gate used to be a bare `if`, which collapses every non-zero exit+ // into one answer: jq exits 5 on a parse error, `if` reads that as+ // false, and the recipe re-indexed over a root nobody verified. The+ // status is now read explicitly and only a literal 1 is a pass.+ const body = renderCodegraphResyncTemplate("/srv/projects/demo", "6h");+ expect(body).toContain("mismatch_status=$?");+ expect(body).toContain(`if [ "$mismatch_status" -eq 0 ]; then`);+ expect(body).toContain(`elif [ "$mismatch_status" -ne 1 ]; then`);+ // Both arms abort; neither falls through to the indexer.+ const gate = body.slice(+ body.indexOf("mismatch_status=0"),+ body.indexOf("# 2. Change detection"),+ );+ expect(gate.match(/exit 1/gu)?.length).toBe(2);+ expect(gate).toContain("aborting rather than re-indexing blind");+ });++ test("the stamp is written only after the post-index health gate passes", () => {+ const body = renderCodegraphResyncTemplate("/srv/projects/demo", "6h");+ const gate = body.indexOf("--fail-on-health");+ const stamp = body.indexOf('>"$stamp_file"');+ expect(gate).toBeGreaterThan(-1);+ expect(`gate before stamp: ${gate < stamp}`).toBe("gate before stamp: true");+ // The stamp lives on the operator's host, outside the vault and outside+ // the partner's index directory.+ expect(body).toContain("${XDG_STATE_HOME:-$HOME/.local/state}/open-second-brain");+ });++ test("two repositories get two stamp files", () => {+ const a = renderCodegraphResyncTemplate("/srv/projects/alpha", "6h");+ const b = renderCodegraphResyncTemplate("/srv/projects/beta", "6h");+ expect(a).toContain("osb-codegraph-resync-srv-projects-alpha.stamp");+ expect(b).toContain("osb-codegraph-resync-srv-projects-beta.stamp");+ });+});++describe("o2b partner codegraph resync (CLI)", () => {+ test("--cron-template prints the recipe and writes nothing anywhere", async () => {+ const repo = makeRepo("repo");+ const before = listTree(tmp);+ const res = await runCli(["partner", "codegraph", "resync", "--cron-template"], { cwd: repo });+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("cat >~/.local/bin/osb-codegraph-resync.sh");+ expect(res.stdout).toContain(`project="${repo}"`);+ expect(listTree(tmp)).toEqual(before);+ });++ test("--project names the repository without a scan", async () => {+ const repo = makeRepo("named");+ const before = listTree(tmp);+ const res = await runCli(+ ["partner", "codegraph", "resync", "--cron-template", "--project", repo],+ { cwd: tmp },+ );+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain(`project="${repo}"`);+ expect(listTree(tmp)).toEqual(before);+ });++ test("--interval renders that cadence", async () => {+ const repo = makeRepo("repo");+ const res = await runCli(+ ["partner", "codegraph", "resync", "--cron-template", "--interval", "1d"],+ { cwd: repo },+ );+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("0 0 */1 * *");+ });++ test("omitting --cron-template is a usage error that leaves no index behind", async () => {+ const repo = makeRepo("repo");+ const before = listTree(tmp);+ const res = await runCli(["partner", "codegraph", "resync"], { cwd: repo });+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("requires --cron-template");+ expect(res.stdout).toBe("");+ expect(existsSync(join(repo, ".codegraph"))).toBe(false);+ expect(listTree(tmp)).toEqual(before);+ });++ test("an interval cron cannot express exits 1 with the inherited parser error", async () => {+ const repo = makeRepo("repo");+ const res = await runCli(+ ["partner", "codegraph", "resync", "--cron-template", "--interval", "90m"],+ { cwd: repo },+ );+ expect(res.returncode).toBe(1);+ expect(res.stderr).toContain("h unit");+ });++ test("a --project that is not a directory is refused", async () => {+ const res = await runCli(+ ["partner", "codegraph", "resync", "--cron-template", "--project", join(tmp, "missing")],+ { cwd: tmp },+ );+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("is not a readable directory");+ });++ test("no code project in scope is named, not rendered as an empty recipe", async () => {+ const bare = join(tmp, "bare");+ mkdirSync(bare, { recursive: true });+ const res = await runCli(+ ["partner", "codegraph", "resync", "--cron-template", "--vault", join(bare, "vault")],+ { cwd: bare },+ );+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("no code project in scope");+ });++ test("positional arguments are rejected", async () => {+ const repo = makeRepo("repo");+ const res = await runCli(["partner", "codegraph", "resync", "extra"], { cwd: repo });+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("does not accept positional arguments");+ });++ test("the verb is reachable from the usage block on an unknown subcommand", async () => {+ const res = await runCli(["partner", "codegraph", "bogus"], { cwd: tmp });+ expect(res.returncode).toBe(2);+ expect(res.stderr).toContain("o2b partner codegraph resync --cron-template");+ });+});++describe("o2b partner codegraph report --fail-on-health", () => {+ test("exits non-zero when health could not be established", async () => {+ // No codegraph index exists under the fixture repo, so the report has+ // no health block. A gate that could not measure must not pass.+ const repo = makeRepo("repo");+ const res = await runCli(+ ["partner", "codegraph", "report", "--vault", join(tmp, "vault"), "--fail-on-health"],+ { cwd: repo },+ );+ expect(res.returncode).toBe(1);+ expect(res.stderr).toContain("--fail-on-health");+ expect(res.stderr).toContain("never measured");+ // The report itself is still printed - the flag changes the exit, not+ // whether the operator gets to see the answer.+ expect(res.stdout).toContain("index: ");+ });++ test("the flagless default is unchanged", async () => {+ const repo = makeRepo("repo");+ const res = await runCli(["partner", "codegraph", "report", "--vault", join(tmp, "vault")], {+ cwd: repo,+ });+ expect(res.returncode).toBe(0);+ expect(res.stderr).toBe("");+ });++ test("--json still emits the same report under the flag", async () => {+ const repo = makeRepo("repo");+ const res = await runCli(+ [+ "partner",+ "codegraph",+ "report",+ "--vault",+ join(tmp, "vault"),+ "--json",+ "--fail-on-health",+ ],+ { cwd: repo },+ );+ expect(res.returncode).toBe(1);+ const report = JSON.parse(res.stdout);+ expect(report.schema_version).toBe(1);+ expect(report.project).toBe(repo);+ });+});diff --git a/tests/cli/run-cli-helper.test.ts b/tests/cli/run-cli-helper.test.tsnew file mode 100644index 00000000..82fcc550--- /dev/null+++ b/tests/cli/run-cli-helper.test.ts@@ -0,0 +1,71 @@+/**+ * The in-process CLI runner owns process-wide state, so overlapping runs+ * corrupt each other. That corruption used to be silent and to surface+ * somewhere else entirely: a test file that ran three verbs through+ * `Promise.all` left a temp config path installed for the rest of the+ * process, and seventeen assertions in unrelated files failed with a vault+ * that could not be found. The refusal below is what turns that into an+ * error at the call site that caused it.+ */++import { expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { ConcurrentInProcessRunError, runCli } from "../helpers/run-cli.ts";++test("a second in-process run refuses while the first is still open", async () => {+ const first = runCli(["--help"]);+ await expect(runCli(["--help"])).rejects.toThrow(ConcurrentInProcessRunError);+ await first;+});++test("the guard clears, so sequential runs keep working", async () => {+ const first = await runCli(["--help"]);+ expect(first.returncode).toBe(0);+ const second = await runCli(["--help"]);+ expect(second.returncode).toBe(0);+});++test("a run that throws inside the CLI still clears the guard", async () => {+ // The flag is released in the same `finally` that restores the streams;+ // if it were released after the return, a failing command would wedge+ // every later run in the file.+ const failed = await runCli(["definitely-not-a-command"]);+ expect(failed.returncode).not.toBe(0);+ const after = await runCli(["--help"]);+ expect(after.returncode).toBe(0);+});++test("concurrency is available through the subprocess path", async () => {+ // The escape hatch the refusal points callers at owns none of the+ // process-global state, so it may overlap.+ const results = await Promise.all([+ runCli(["--help"], { subprocess: true }),+ runCli(["--help"], { subprocess: true }),+ ]);+ for (const result of results) expect(result.returncode).toBe(0);+});++test("a throw during setup clears the guard instead of wedging the process", async () => {+ // The flag used to be raised before the setup that resolves the+ // environment and reads the working directory, and process.cwd() throws+ // once the directory it names is deleted - routine in a suite that+ // chdirs into temp vaults and removes them. A throw in that window left+ // the flag raised for the rest of the process, and every later run+ // failed blaming a concurrency that never happened.+ const scratch = mkdtempSync(join(tmpdir(), "o2b-cwd-gone-"));+ const restore = process.cwd();+ process.chdir(scratch);+ rmSync(scratch, { recursive: true, force: true });+ try {+ const gone = await runCli(["--help"]);+ expect(gone.returncode).toBe(0);+ } finally {+ process.chdir(restore);+ }+ // The guard is clear, so the next run is not misdiagnosed as an overlap.+ const after = await runCli(["--help"]);+ expect(after.returncode).toBe(0);+});diff --git a/tests/cli/search-cron-template.test.ts b/tests/cli/search-cron-template.test.tsindex c925e25d..5b4abc96 100644--- a/tests/cli/search-cron-template.test.ts+++ b/tests/cli/search-cron-template.test.ts@@ -8,7 +8,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdtempSync, readdirSync, rmSync } from "node:fs";+import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -16,9 +16,26 @@ import {CronTemplateError,parseInterval,renderCronTemplate,+ SEARCH_REINDEX_RECIPE,} from "../../src/cli/search-cron-template.ts";import { runCli } from "../helpers/run-cli.ts";+/**+ * The rendered template, captured BEFORE the shared cron-recipe kernel was+ * extracted out of this module. Operators already have this script saved and+ * scheduled, so a byte of drift here is a byte of drift in their crontab: the+ * extraction is only correct if it changed nothing at all, and a fixture is+ * the only assertion that can say so. Anchor assertions cannot - they pass+ * over any output that still happens to contain the anchors.+ */+const PINNED_FIXTURE = join(+ import.meta.dir,+ "..",+ "fixtures",+ "cron-recipe",+ "search-reindex-30m.txt",+);+describe("parseInterval", () => {test("30m โ */30 * * * *", () => {const r = parseInterval("30m");@@ -52,6 +69,36 @@ describe("parseInterval", () => {expect(() => parseInterval("30s")).toThrow(CronTemplateError);});+ test("a day step below the shortest month still renders", () => {+ // Inside a month the step is the cadence it claims to be, which is the+ // same bargain the minute and hour fields already make.+ expect(parseInterval("27d").cron).toBe("0 0 */27 * *");+ });++ test("28d rejected: the day-of-month field restarts before the step lands", () => {+ // `*/28` in the day-of-month field means "the 1st, then every 28th day+ // WITHIN each month", and no month is long enough for a second firing+ // - so the expression is a monthly schedule wearing a 28-day label.+ expect(() => parseInterval("28d")).toThrow(CronTemplateError);+ try {+ parseInterval("28d");+ } catch (e) {+ expect((e as Error).message).toContain("day-of-month");+ }+ });++ test("90d rejected rather than silently rendered as a monthly schedule", () => {+ // The defect this closes: `0 0 */90 * *` fires on the 1st of every+ // month. Refusing is the same discipline the m and h units already+ // apply, rather than reinterpreting the operator's cadence.+ expect(() => parseInterval("90d")).toThrow(CronTemplateError);+ try {+ parseInterval("90d");+ } catch (e) {+ expect((e as Error).message).toContain("90");+ }+ });+test("zero rejected", () => {expect(() => parseInterval("0m")).toThrow(CronTemplateError);});@@ -66,6 +113,18 @@ describe("parseInterval", () => {});describe("renderCronTemplate", () => {+ test("the rendered template is byte-identical to the pinned fixture", () => {+ expect(renderCronTemplate("30m")).toBe(readFileSync(PINNED_FIXTURE, "utf8"));+ });++ test("the recipe spec is the one this module still owns", () => {+ // The fixture would also pass if the module delegated to some OTHER+ // recipe that happened to render the same text, so pin the identity of+ // the spec the delegation goes through as well.+ expect(SEARCH_REINDEX_RECIPE.cronName).toBe("osb-reindex");+ expect(SEARCH_REINDEX_RECIPE.scriptPath).toBe("~/.local/bin/osb-reindex.sh");+ });+test("body contains every expected anchor", () => {const body = renderCronTemplate("30m");expect(body).toContain("Open Second Brain");diff --git a/tests/cli/search-query-flag-manifest.test.ts b/tests/cli/search-query-flag-manifest.test.tsindex 70f63ea5..c1f2419e 100644--- a/tests/cli/search-query-flag-manifest.test.ts+++ b/tests/cli/search-query-flag-manifest.test.ts@@ -1,13 +1,19 @@/**- * `o2b search query` advertises every flag it parses.+ * The `o2b search` verbs advertise every flag they parse.** There is no per-verb `--help` for the search verbs (`o2b search query* --help` exits 2 with "unknown flag: --help"), so `o2b help` and `o2b- * help --json` are the ONLY discovery surface for this verb's flags. The+ * help --json` are the ONLY discovery surface for these flags. The* manifest declared none of them, which is worse than a partial list read* as complete: an agent parsing `help --json` concluded `search query`* takes nothing but `--json`.*+ * The same hole was still open one line away on the two index builders,+ * where `reindex` parsed `--cron-template` and `--interval` - the whole+ * cron-recipe surface - with neither reachable from help or completions.+ * So the ratchet is a table: adding a verb to {@link COVERED} is all it+ * takes to hold the next one to the same standard.+ ** The direction of enumeration is the point, exactly as in* `manifest-completeness.test.ts`: this reads the `parseFlags` schema in* the VERB and asks the manifest to account for each key, never the@@ -21,16 +27,46 @@ import { join } from "node:path";import { nestedCommand } from "../../src/cli/command-manifest.ts";import { VAULT_FLAGS } from "../../src/cli/search/helpers.ts";-const QUERY_VERB_SOURCE = join(- import.meta.dir,- "..",- "..",- "src",- "cli",- "search",- "verbs",- "query.ts",-);+const VERBS_DIR = join(import.meta.dir, "..", "..", "src", "cli", "search", "verbs");++/** One verb held to the ratchet: where it is parsed, and what models it. */+interface CoveredVerb {+ /** Manifest child name under `o2b search`. */+ readonly verb: string;+ /** Source file declaring the `parseFlags` schema. */+ readonly source: string;+ /** Function declaration the schema is read from, so sibling verbs in the+ * same module cannot leak into each other's census. */+ readonly marker: string;+ /** Lower bound on the parsed flag count, so a dead regex cannot pass. */+ readonly minFlags: number;+ /** A flag whose presence in help is the reason this entry exists. */+ readonly witness: readonly [name: string, type: string];+}++const COVERED: ReadonlyArray<CoveredVerb> = Object.freeze([+ {+ verb: "query",+ source: "query.ts",+ marker: "export async function cmdSearchQuery",+ minFlags: 20,+ witness: ["explain", "boolean"],+ },+ {+ verb: "index",+ source: "indexing.ts",+ marker: "export async function cmdSearchIndex",+ minFlags: 8,+ witness: ["force", "boolean"],+ },+ {+ verb: "reindex",+ source: "indexing.ts",+ marker: "export async function cmdSearchReindex",+ minFlags: 9,+ witness: ["cron-template", "boolean"],+ },+]);/*** The inherited flag the manifest states once in the help header instead@@ -45,16 +81,22 @@ const SCHEMA_ENTRY_RE = /(?:"([^"]+)"|([A-Za-z][\w-]*)):\s*\{\s*type:\s*"([^"]+)const VAULT_SPREAD = "...VAULT_FLAGS";/**- * The `parseFlags(argv, { ... })` schema `query.ts` declares, as+ * The `parseFlags(argv, { ... })` schema the named function declares, as* `name -> type`, with `...VAULT_FLAGS` resolved from the real constant.*/-function parsedFlagSchema(): ReadonlyMap<string, string> {- const text = readFileSync(QUERY_VERB_SOURCE, "utf8");- const start = text.indexOf("parseFlags(argv, {");- expect(`query.ts calls parseFlags: ${start >= 0}`).toBe("query.ts calls parseFlags: true");+function parsedFlagSchema(entry: CoveredVerb): ReadonlyMap<string, string> {+ const text = readFileSync(join(VERBS_DIR, entry.source), "utf8");+ const fn = text.indexOf(entry.marker);+ expect(`${entry.source} declares ${entry.marker}: ${fn >= 0}`).toBe(+ `${entry.source} declares ${entry.marker}: true`,+ );+ const start = text.indexOf("parseFlags(argv, {", fn);+ expect(`${entry.verb} calls parseFlags: ${start >= 0}`).toBe(+ `${entry.verb} calls parseFlags: true`,+ );const end = text.indexOf("});", start);- expect(`the parseFlags call is terminated: ${end > start}`).toBe(- "the parseFlags call is terminated: true",+ expect(`the ${entry.verb} parseFlags call is terminated: ${end > start}`).toBe(+ `the ${entry.verb} parseFlags call is terminated: true`,);const literal = text.slice(start, end);@@ -70,11 +112,11 @@ function parsedFlagSchema(): ReadonlyMap<string, string> {return out;}-/** The manifest's declared flags for `o2b search query`, as `name -> type`. */-function manifestFlagSchema(): ReadonlyMap<string, string> {- const entry = nestedCommand("search", "query");- expect(`the manifest models search query: ${entry !== undefined}`).toBe(- "the manifest models search query: true",+/** The manifest's declared flags for one `o2b search` verb, as `name -> type`. */+function manifestFlagSchema(verb: string): ReadonlyMap<string, string> {+ const entry = nestedCommand("search", verb);+ expect(`the manifest models search ${verb}: ${entry !== undefined}`).toBe(+ `the manifest models search ${verb}: true`,);return new Map((entry!.flags ?? []).map((f) => [f.name, f.type]));}@@ -86,59 +128,83 @@ function comparable(schema: ReadonlyMap<string, string>): ReadonlyMap<string, streturn out;}-describe("o2b search query declares the flags it parses", () => {+/** Every disagreement between one verb's parse and its manifest entry. */+function mismatches(+ parsed: ReadonlyMap<string, string>,+ modelled: ReadonlyMap<string, string>,+ label: string,+): string[] {+ const problems: string[] = [];+ for (const [name, type] of parsed) {+ const declared = modelled.get(name);+ if (declared === undefined) problems.push(`${label} --${name} is parsed but not modelled`);+ else if (declared !== type) {+ problems.push(`${label} --${name} is modelled as ${declared} but parsed as ${type}`);+ }+ }+ return problems;+}++describe("the search verbs declare the flags they parse", () => {test("every parsed flag is modelled by the manifest, with the same type", () => {- const parsed = comparable(parsedFlagSchema());- const modelled = comparable(manifestFlagSchema());- // Named, not counted: the failure message is the work to be done.+ // Every verb folds into ONE comparison so the failure message is the+ // complete list of work to be done.const problems: string[] = [];- for (const [name, type] of parsed) {- const declared = modelled.get(name);- if (declared === undefined) problems.push(`--${name} is parsed but not modelled`);- else if (declared !== type) {- problems.push(`--${name} is modelled as ${declared} but parsed as ${type}`);- }+ for (const entry of COVERED) {+ problems.push(+ ...mismatches(+ comparable(parsedFlagSchema(entry)),+ comparable(manifestFlagSchema(entry.verb)),+ entry.verb,+ ),+ );}expect(problems.toSorted().join("\n")).toBe("");});test("no modelled flag outlives the parse that would accept it", () => {- const parsed = comparable(parsedFlagSchema());- const modelled = comparable(manifestFlagSchema());- const stale = [...modelled.keys()].filter((name) => !parsed.has(name));+ const stale: string[] = [];+ for (const entry of COVERED) {+ const parsed = comparable(parsedFlagSchema(entry));+ for (const name of comparable(manifestFlagSchema(entry.verb)).keys()) {+ if (!parsed.has(name)) stale.push(`${entry.verb} --${name}`);+ }+ }expect(stale.toSorted().join("\n")).toBe("");});- test("the flag the trust receipts arrived with is reachable from help", () => {- // `--explain` is the branch's new flag and the reason this file exists.- expect([...manifestFlagSchema().keys()]).toContain("explain");+ test("each verb's witness flag is reachable from help", () => {+ for (const entry of COVERED) {+ const [name] = entry.witness;+ const modelled = manifestFlagSchema(entry.verb);+ expect(`search ${entry.verb} --${name}: ${modelled.has(name)}`).toBe(+ `search ${entry.verb} --${name}: true`,+ );+ }});test("the ratchet is not vacuous and can fail", () => {// Pin the measurement, not only its verdict: a regex that stopped// matching would report a clean sweep over an empty set.- const parsed = comparable(parsedFlagSchema());- expect(parsed.size).toBeGreaterThan(20);- expect(parsed.get("explain")).toBe("boolean");- expect(parsed.get("vault")).toBe("string");+ for (const entry of COVERED) {+ const parsed = comparable(parsedFlagSchema(entry));+ expect(`${entry.verb} parsed count above floor: ${parsed.size >= entry.minFlags}`).toBe(+ `${entry.verb} parsed count above floor: true`,+ );+ expect(parsed.get(entry.witness[0])).toBe(entry.witness[1]);+ expect(parsed.get("vault")).toBe("string");+ }// Prove the comparison catches a violation: a verb schema carrying a// flag the manifest never heard of, and one whose type disagrees.- const violating = new Map(parsed);+ const violating = new Map(comparable(parsedFlagSchema(COVERED[0]!)));violating.set("undeclared-flag", "boolean");violating.set("limit", "boolean");- const modelled = comparable(manifestFlagSchema());- const problems: string[] = [];- for (const [name, type] of violating) {- const declared = modelled.get(name);- if (declared === undefined) problems.push(`--${name} is parsed but not modelled`);- else if (declared !== type) {- problems.push(`--${name} is modelled as ${declared} but parsed as ${type}`);- }- }- expect(problems.toSorted()).toEqual([- "--limit is modelled as string but parsed as boolean",- "--undeclared-flag is parsed but not modelled",+ expect(+ mismatches(violating, comparable(manifestFlagSchema("query")), "query").toSorted(),+ ).toEqual([+ "query --limit is modelled as string but parsed as boolean",+ "query --undeclared-flag is parsed but not modelled",]);});});diff --git a/tests/cli/snapshot-render.test.ts b/tests/cli/snapshot-render.test.tsnew file mode 100644index 00000000..07bb6a15--- /dev/null+++ b/tests/cli/snapshot-render.test.ts@@ -0,0 +1,145 @@+/**+ * One vocabulary for two surfaces.+ *+ * `o2b brain snapshot log` and `o2b brain rollback --list` each shipped+ * their own copy of "does this snapshot cover the derived store", and the+ * copies had already begun to disagree - one drew the no-record case from+ * a named constant, the other from a bare literal. These assertions are+ * what keeps them one answer.+ */++import { describe, expect, test } from "bun:test";++import type { BrainManifestDerivedStore } from "../../src/core/brain/manifest.ts";+import type { RestoreDerivedStoreResult } from "../../src/core/brain/snapshot.ts";+import {+ renderDerivedStoreCoverage,+ renderDerivedStoreRestore,+ renderSnapshotReason,+ SNAPSHOT_UNKNOWN_LABEL,+} from "../../src/cli/brain/snapshot-render.ts";++function record(over: Partial<BrainManifestDerivedStore>): BrainManifestDerivedStore {+ return {+ included: false,+ source_path: "/tmp/vault/.open-second-brain/brain.sqlite",+ archive_name: null,+ archive_sha256: null,+ archive_size: null,+ live_size: 10,+ exclusion_reason: null,+ ...over,+ } as BrainManifestDerivedStore;+}++describe("renderDerivedStoreCoverage", () => {+ test("a snapshot with no record is unknown, never excluded", () => {+ // Nothing checked, so nothing may be claimed. Rendering this as+ // `excluded` would state a decision nobody made.+ const rendered = renderDerivedStoreCoverage(null);+ expect(rendered).toBe(SNAPSHOT_UNKNOWN_LABEL);+ expect(rendered).not.toContain("excluded");+ });++ test("the no-record answer is identical with and without the size option", () => {+ expect(renderDerivedStoreCoverage(null)).toBe(+ renderDerivedStoreCoverage(null, { withArchiveSize: true }),+ );+ });++ test("an excluded record names its reason on both surfaces", () => {+ const excluded = record({ exclusion_reason: "not-requested" });+ expect(renderDerivedStoreCoverage(excluded)).toBe("excluded (not-requested)");+ expect(renderDerivedStoreCoverage(excluded, { withArchiveSize: true })).toBe(+ "excluded (not-requested)",+ );+ });++ test("an excluded record with no reason says so rather than reading as clean", () => {+ expect(renderDerivedStoreCoverage(record({}))).toContain("unspecified");+ });++ test("the size is the only difference between the two surfaces", () => {+ const included = record({+ included: true,+ archive_name: "run.store.sqlite.zst",+ archive_size: 4096,+ });+ expect(renderDerivedStoreCoverage(included)).toBe("included");+ expect(renderDerivedStoreCoverage(included, { withArchiveSize: true })).toBe(+ "included (4096 bytes)",+ );+ });+});++/** A restore outcome with the no-record defaults, overridden per case. */+function outcome(over: Partial<RestoreDerivedStoreResult>): RestoreDerivedStoreResult {+ return {+ replaced: false,+ coverage_known: false,+ path: null,+ exclusion_reason: null,+ store_archive_present: false,+ ...over,+ };+}++describe("renderDerivedStoreRestore", () => {+ test("a replaced store names where it was written", () => {+ const rendered = renderDerivedStoreRestore(+ outcome({+ replaced: true,+ coverage_known: true,+ path: "/vault/.open-second-brain/brain.sqlite",+ store_archive_present: true,+ }),+ );+ expect(rendered).toContain("replaced");+ expect(rendered).toContain("/vault/.open-second-brain/brain.sqlite");+ });++ test("a recorded exclusion names the reason it recorded", () => {+ const rendered = renderDerivedStoreRestore(+ outcome({ coverage_known: true, exclusion_reason: "not-requested" }),+ );+ expect(rendered).toContain("not-requested");+ expect(rendered).toContain("live store left untouched");+ });++ test("no record and no archive does not claim the feature is younger than the snapshot", () => {+ // Nothing was archived either way, so the honest answer is that no+ // record exists - not that the archive is older than the feature,+ // which this surface cannot know.+ const rendered = renderDerivedStoreRestore(outcome({}));+ expect(rendered).toContain(SNAPSHOT_UNKNOWN_LABEL);+ expect(rendered).toContain("no store archive");+ expect(rendered).toContain("live store left untouched");+ });++ test("no record WITH an archive on disk says the record is missing", () => {+ // The rollback surface used to render this as "snapshot predates+ // derived-store coverage" while the store archive sat next to the tar.+ const rendered = renderDerivedStoreRestore(outcome({ store_archive_present: true }));+ expect(rendered).toContain("record");+ expect(rendered).not.toContain("predates");+ expect(rendered).toContain("live store left untouched");+ });++ test("the two no-record answers are different sentences", () => {+ expect(renderDerivedStoreRestore(outcome({}))).not.toBe(+ renderDerivedStoreRestore(outcome({ store_archive_present: true })),+ );+ });+});++describe("renderSnapshotReason", () => {+ test("an unrecorded reason uses the same word as an unrecorded coverage record", () => {+ // Two different unknowns spelled two different ways is how an+ // operator learns to distrust both columns.+ expect(renderSnapshotReason(null)).toBe(SNAPSHOT_UNKNOWN_LABEL);+ });++ test("a recorded reason is passed through verbatim", () => {+ expect(renderSnapshotReason("dream")).toBe("dream");+ });+});diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.tsnew file mode 100644index 00000000..99a6ec3f--- /dev/null+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts@@ -0,0 +1,312 @@+/**+ * Census over the closed verdict vocabularies.+ *+ * The silence-is-not-an-answer wave turns "could not check" into a+ * first-class value in several unrelated subsystems. Each one owns its own+ * vocabulary, because a suppression status, a coverage verdict and an+ * archive-inclusion decision are not the same type - but they all follow+ * one convention this project already uses: a frozen object of values, a+ * companion list of members, and a type guard that decides whether a+ * string read back off disk is one of them.+ *+ * That trio can drift. A value added to the object and forgotten in the+ * list makes the guard reject a value the code itself produces; a guard+ * written against a stale list silently rejects a member. Grounding found+ * exactly this class already shipped elsewhere - a status list copied as a+ * literal into a tool schema with nothing asserting the two agree.+ *+ * This file is the assertion that they agree. Every vocabulary the wave+ * introduces registers below, and so does any closed vocabulary whose+ * values the wave copies OUT of TypeScript - a code interpolated into an+ * emitted shell script is the same drift risk by another route.+ *+ * It deliberately does NOT require values to be unique across+ * vocabularies. An absent config file and an absent store file are both+ * honestly named `absent`, and forcing them apart would buy nothing.+ */++import { describe, expect, test } from "bun:test";++import {+ isSchemaPackIntegrityStatus,+ isSchemaPackUnverifiedReason,+ SCHEMA_PACK_INTEGRITY,+ SCHEMA_PACK_INTEGRITY_STATUSES,+ SCHEMA_PACK_UNVERIFIED_REASON,+ SCHEMA_PACK_UNVERIFIED_REASONS,+} from "../../../src/core/brain/schema-integrity.ts";+import {+ isNegativeRecallState,+ isNegativeRecallUnknownReason,+ isRetractionEvidenceKind,+ NEGATIVE_RECALL_STATE,+ NEGATIVE_RECALL_STATES,+ NEGATIVE_RECALL_UNKNOWN_REASON,+ NEGATIVE_RECALL_UNKNOWN_REASONS,+ RETRACTION_EVIDENCE_KIND,+ RETRACTION_EVIDENCE_KINDS,+} from "../../../src/core/brain/negative-recall.ts";+import {+ isStaleDependencyConsumerKind,+ isStaleDependencyStateKind,+ STALE_DEPENDENCY_CONSUMER,+ STALE_DEPENDENCY_CONSUMERS,+ STALE_DEPENDENCY_STATE,+ STALE_DEPENDENCY_STATES,+} from "../../../src/core/brain/doctor/stale-dependency-check.ts";+import {+ isSnapshotStoreExclusionReason,+ SNAPSHOT_STORE_EXCLUSION,+ SNAPSHOT_STORE_EXCLUSION_REASONS,+} from "../../../src/core/brain/manifest.ts";+import { GATE_MODE, GATE_MODES, isGateMode } from "../../../src/core/integrity/stamp.ts";+import {+ isTriggerStatus,+ TRIGGER_STATUS,+ TRIGGER_STATUSES,+} from "../../../src/core/brain/triggers/types.ts";+import {+ BRAIN_SNAPSHOT_REASON,+ BRAIN_SNAPSHOT_REASONS,+ isBrainSnapshotReason,+} from "../../../src/core/brain/types.ts";+import {+ GRAPH_HEALTH_CODE_LIST,+ GRAPH_HEALTH_CODES,+ isGraphHealthCode,+} from "../../../src/core/partner/codegraph-health.ts";++interface VocabularyUnderCensus {+ /** Identifies the vocabulary in a failure message. */+ readonly name: string;+ /** The frozen object every producer reads its value from. */+ readonly values: Readonly<Record<string, string>>;+ /** The companion membership list every reader validates against. */+ readonly members: ReadonlyArray<string>;+ /** The guard that decides whether a persisted string is a member. */+ readonly guard: (value: unknown) => boolean;+}++/**+ * Strings that must never be accepted by any guard here. They are shaped+ * like plausible drift - a case change, a stray space, an empty value, a+ * near-miss spelling - rather than obvious garbage.+ */+const NON_MEMBERS: ReadonlyArray<unknown> = Object.freeze([+ "",+ " ",+ "unknown-vocabulary-member",+ null,+ undefined,+ 42,+ {},+]);++/** Returns one line per defect. An empty array is a clean vocabulary. */+function auditVocabulary(vocabulary: VocabularyUnderCensus): ReadonlyArray<string> {+ const problems: string[] = [];+ const { name, values, members, guard } = vocabulary;++ if (!Object.isFrozen(values)) problems.push(`${name}: values object is not frozen`);++ const declared = Object.values(values);+ const declaredSet = new Set(declared);+ if (declaredSet.size !== declared.length) {+ problems.push(`${name}: values object carries a duplicate value`);+ }++ const memberSet = new Set(members);+ if (memberSet.size !== members.length) {+ problems.push(`${name}: membership list carries a duplicate value`);+ }++ for (const value of declaredSet) {+ if (!memberSet.has(value)) problems.push(`${name}: "${value}" is declared but not a member`);+ if (!guard(value)) problems.push(`${name}: guard rejects declared value "${value}"`);+ }+ for (const member of memberSet) {+ if (!declaredSet.has(member)) problems.push(`${name}: "${member}" is a member of nothing`);+ }+ for (const outsider of NON_MEMBERS) {+ if (declaredSet.has(outsider as string)) continue;+ if (guard(outsider))+ problems.push(`${name}: guard accepts non-member ${JSON.stringify(outsider)}`);+ }+ return problems;+}++/**+ * Every closed vocabulary that follows the trio convention. Units of this+ * wave append here as they land; the seed entry is the one vocabulary that+ * already shipped the complete trio.+ */+const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([+ { name: "GATE_MODE", values: GATE_MODE, members: GATE_MODES, guard: isGateMode },+ {+ name: "SCHEMA_PACK_INTEGRITY",+ values: SCHEMA_PACK_INTEGRITY,+ members: SCHEMA_PACK_INTEGRITY_STATUSES,+ guard: isSchemaPackIntegrityStatus,+ },+ {+ name: "SCHEMA_PACK_UNVERIFIED_REASON",+ values: SCHEMA_PACK_UNVERIFIED_REASON,+ members: SCHEMA_PACK_UNVERIFIED_REASONS,+ guard: isSchemaPackUnverifiedReason,+ },+ {+ // U5. The trio was incomplete when the wave started: the list and+ // the guard shipped, the frozen object did not, and the MCP tool+ // schema carried a fourth hand-written copy of the list.+ name: "TRIGGER_STATUS",+ values: TRIGGER_STATUS,+ members: TRIGGER_STATUSES,+ guard: isTriggerStatus,+ },+ {+ // U2. Three vocabularies, because a corpus verdict, the reason it+ // could not be reached, and the stored edge that grounds a+ // non-occurrence are three types - the wave's rule that a union of+ // disjoint sets is a namespace rather than an abstraction.+ name: "NEGATIVE_RECALL_STATE",+ values: NEGATIVE_RECALL_STATE,+ members: NEGATIVE_RECALL_STATES,+ guard: isNegativeRecallState,+ },+ {+ name: "NEGATIVE_RECALL_UNKNOWN_REASON",+ values: NEGATIVE_RECALL_UNKNOWN_REASON,+ members: NEGATIVE_RECALL_UNKNOWN_REASONS,+ guard: isNegativeRecallUnknownReason,+ },+ {+ name: "RETRACTION_EVIDENCE_KIND",+ values: RETRACTION_EVIDENCE_KIND,+ members: RETRACTION_EVIDENCE_KINDS,+ guard: isRetractionEvidenceKind,+ },+ {+ // U3. Two vocabularies for the two sides of one row: what stopped+ // being current, and what kind of thing is still resting on it. They+ // are read from different stores and lead to different remedies, so+ // collapsing them into one axis would name neither.+ name: "STALE_DEPENDENCY_CONSUMER",+ values: STALE_DEPENDENCY_CONSUMER,+ members: STALE_DEPENDENCY_CONSUMERS,+ guard: isStaleDependencyConsumerKind,+ },+ {+ name: "STALE_DEPENDENCY_STATE",+ values: STALE_DEPENDENCY_STATE,+ members: STALE_DEPENDENCY_STATES,+ guard: isStaleDependencyStateKind,+ },+ {+ // U6. Persisted into a replicated sidecar, so the guard is what+ // stands between a peer's hand-edited manifest and a restore acting+ // on a reason this build does not understand.+ name: "SNAPSHOT_STORE_EXCLUSION",+ values: SNAPSHOT_STORE_EXCLUSION,+ members: SNAPSHOT_STORE_EXCLUSION_REASONS,+ guard: isSnapshotStoreExclusionReason,+ },+ {+ // U7. Four of its nine members have no producer in this release+ // (snapshots at a session, plan or decision boundary are deferred, and+ // nothing takes one on demand), and the census does not care: what it+ // asserts is that the guard accepts every member, which is precisely+ // what lets this build read a sidecar a later release wrote and+ // replicated back.+ name: "BRAIN_SNAPSHOT_REASON",+ values: BRAIN_SNAPSHOT_REASON,+ members: BRAIN_SNAPSHOT_REASONS,+ guard: isBrainSnapshotReason,+ },+ {+ // U4. Registered because the values leave TypeScript: the resync cron+ // recipe interpolates one of them into the shell gate it emits, which+ // is the copy-drift class this census exists for - a code renamed here+ // and left as a literal there would silently stop matching, and the+ // emitted gate would pass every report.+ name: "GRAPH_HEALTH_CODES",+ values: GRAPH_HEALTH_CODES,+ members: GRAPH_HEALTH_CODE_LIST,+ guard: isGraphHealthCode,+ },+]);++describe("verdict vocabulary census", () => {+ test("the registry is not empty", () => {+ // A census with nothing in it passes for the wrong reason. This is the+ // guard against the registry being emptied rather than fixed.+ expect(CENSUS.length).toBeGreaterThan(0);+ });++ for (const vocabulary of CENSUS) {+ test(`${vocabulary.name} object, membership list and guard agree`, () => {+ expect(auditVocabulary(vocabulary)).toEqual([]);+ });+ }+});++describe("the census itself catches drift", () => {+ // Without these, a broken audit would report every vocabulary clean and+ // the file above would be decoration.+ const values = Object.freeze({ ok: "ok", unverified: "unverified" });+ const members = ["ok", "unverified"];+ const guard = (value: unknown): boolean => members.includes(value as string);++ test("accepts a well-formed vocabulary", () => {+ expect(auditVocabulary({ name: "synthetic", values, members, guard })).toEqual([]);+ });++ test("catches a value that is missing from the membership list", () => {+ const problems = auditVocabulary({ name: "synthetic", values, members: ["ok"], guard });+ expect(problems).toContain('synthetic: "unverified" is declared but not a member');+ });++ test("catches a member that no value declares", () => {+ const problems = auditVocabulary({+ name: "synthetic",+ values,+ members: [...members, "modified"],+ guard,+ });+ expect(problems).toContain('synthetic: "modified" is a member of nothing');+ });++ test("catches a guard that rejects one of its own values", () => {+ const problems = auditVocabulary({+ name: "synthetic",+ values,+ members,+ guard: (value) => value === "ok",+ });+ expect(problems).toContain('synthetic: guard rejects declared value "unverified"');+ });++ test("catches a guard that accepts anything", () => {+ const problems = auditVocabulary({ name: "synthetic", values, members, guard: () => true });+ expect(problems).toContain('synthetic: guard accepts non-member ""');+ });++ test("catches an unfrozen values object", () => {+ const problems = auditVocabulary({+ name: "synthetic",+ values: { ok: "ok", unverified: "unverified" },+ members,+ guard,+ });+ expect(problems).toContain("synthetic: values object is not frozen");+ });++ test("catches a duplicate value", () => {+ const problems = auditVocabulary({+ name: "synthetic",+ values: Object.freeze({ ok: "ok", alsoOk: "ok" }),+ members: ["ok"],+ guard: (value) => value === "ok",+ });+ expect(problems).toContain("synthetic: values object carries a duplicate value");+ });+});diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.tsindex d93de2da..5452d4d8 100644--- a/tests/core/architecture/write-site-census.test.ts+++ b/tests/core/architecture/write-site-census.test.ts@@ -641,11 +641,16 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object},"src/core/brain/snapshot.ts": {categories: [C.archiveTransfer, C.retentionDelete],- calls: ["cpSync", "rmSync", "writeFileSync"],+ calls: ["cpSync", "renameSync", "rmSync", "unlinkSync", "writeFileSync"],reason:"writes the compressed archive BYTES into `.snapshots/`, prunes archives past " +"the retention count, and restores by recursive copy. A torn archive fails on " +- "restore exactly as any interrupted snapshot does; no Markdown parser reads it.",+ "restore exactly as any interrupted snapshot does; no Markdown parser reads it. " ++ "The derived-store restore adds the rename pair: it stages the decompressed " ++ "database beside its destination and swaps it in under the search writer lock, " ++ "which IS the atomic write for a SQLite file - the same discipline `reindexVault` " ++ "uses, and the reason a partial decompression can never be observed as the live " ++ "store. The unlink removes a partial store archive whose snapshot was refused.",},// --- Concurrency primitives --------------------------------------------diff --git a/tests/core/brain.backlinks.test.ts b/tests/core/brain.backlinks.test.tsindex 1089be90..dadd86a2 100644--- a/tests/core/brain.backlinks.test.ts+++ b/tests/core/brain.backlinks.test.ts@@ -9,6 +9,7 @@ import { writePreference, moveToRetired } from "../../src/core/brain/preference.import { writeSignal } from "../../src/core/brain/signal.ts";import { appendApplyEvidence } from "../../src/core/brain/apply-evidence.ts";import { preferencePath } from "../../src/core/brain/paths.ts";+import { brainArtifactSlug, stripBrainIdPrefix } from "../../src/core/brain/wikilink.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";let vault: string;@@ -151,6 +152,52 @@ describe("buildBacklinkIndex โ self-reference skip", () => {});});+describe("brainArtifactSlug โ the key both sides of a reverse lookup fold to", () => {+ test("every spelling of a retired rule folds to one key", () => {+ writePreference(vault, {+ slug: "folded",+ topic: "folded",+ principle: "test",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-30T00:00:00Z",+ status: "unconfirmed",+ evidenced_by: [],+ });+ moveToRetired(vault, preferencePath(vault, "folded"), "rebutted", {+ now: new Date("2026-05-12T00:00:00Z"),+ retired_by: "[[Brain/log/2026-05-12]]",+ });++ // The index resolves the pre-rename spelling through the alias the+ // retirement left behind; the helper folds both names to one key, so+ // a consumer citing either lands on the same record.+ const canonical = brainArtifactSlug("ret-folded");+ expect(canonical).toBe("folded");+ for (const spelling of [+ "pref-folded",+ "ret-folded",+ "[[pref-folded]]",+ "[[ret-folded|Folded rule]]",+ "Brain/retired/ret-folded.md",+ "[[Brain/preferences/pref-folded.md#Principle]]",+ ]) {+ expect(brainArtifactSlug(spelling)).toBe(canonical);+ }+ });++ test("a reference that is not a Brain rule keeps its own basename", () => {+ // `sig-` is a different artifact, not a second spelling of a rule,+ // so folding it away would merge a signal into a same-slug rule.+ expect(brainArtifactSlug("[[sig-2026-05-01-alpha]]")).toBe("sig-2026-05-01-alpha");+ expect(brainArtifactSlug("Notes/Meeting.md")).toBe("Meeting");+ });++ test("stripBrainIdPrefix trims before it matches, and leaves a bare slug alone", () => {+ expect(stripBrainIdPrefix(" pref-padded ")).toBe("padded");+ expect(stripBrainIdPrefix("padded")).toBe("padded");+ });+});+describe("buildBacklinkIndex โ frozen result", () => {test("returned arrays are frozen", () => {writePreference(vault, {diff --git a/tests/core/brain.snapshot-diff.test.ts b/tests/core/brain.snapshot-diff.test.tsindex 713b0b3c..33bb28d6 100644--- a/tests/core/brain.snapshot-diff.test.ts+++ b/tests/core/brain.snapshot-diff.test.ts@@ -198,6 +198,43 @@ describe("diffBrainTrees โ field-level modifications", () => {expect(d.modified[0]!.fields).toEqual([]);expect(d.modified[0]!.bodyChanged).toBe(true);});++ test("per-device shards and the JSONL surface classify as log, not other", () => {+ // The classifier predated per-device sharding and matched only+ // `log/<date>.md`, so on any vault with a `device_id` configured -+ // which is every vault where a rollback diff is interesting, since+ // sharding exists for multi-device replication - the log surface fell+ // through to `other`. The machine-primary `.jsonl` file, the one+ // `readLogDay` actually reads, was misclassified on every vault.+ const a = makeRoot("a");+ const b = makeRoot("b");+ const shards: ReadonlyArray<string> = [+ "2026-05-14.md",+ "2026-05-14.jsonl",+ "2026-05-14.laptop-1.md",+ "2026-05-14.laptop-1.jsonl",+ ];+ for (const name of shards) {+ writeFileSync(join(a, "log", name), "before\n", "utf8");+ writeFileSync(join(b, "log", name), "after\n", "utf8");+ }+ const d = diffBrainTrees(a, b);+ expect(d.modified).toHaveLength(shards.length);+ expect(d.modified.map((m) => m.entry.kind)).toEqual(shards.map(() => "log"));+ });++ test("a non-log file under log/ still classifies as other", () => {+ // The bucket must widen to the real shard shapes, not to everything+ // that happens to live in the directory - the dream workrun JSONL is+ // not a log day and must not be grouped with one.+ const a = makeRoot("a");+ const b = makeRoot("b");+ writeFileSync(join(a, "log", "notes.md"), "before\n", "utf8");+ writeFileSync(join(b, "log", "notes.md"), "after\n", "utf8");+ const d = diffBrainTrees(a, b);+ expect(d.modified).toHaveLength(1);+ expect(d.modified[0]!.entry.kind).toBe("other");+ });});describe("diffBrainTrees โ ignored regions", () => {diff --git a/tests/core/brain.snapshot.test.ts b/tests/core/brain.snapshot.test.tsindex 59012553..237543fb 100644--- a/tests/core/brain.snapshot.test.ts+++ b/tests/core/brain.snapshot.test.ts@@ -1,5 +1,6 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";import {+ chmodSync,existsSync,mkdirSync,mkdtempSync,@@ -12,6 +13,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import {+ BrainSnapshotListingError,BrainSnapshotToolingMissingError,createSnapshot,listSnapshots,@@ -26,6 +28,14 @@ import {manifestSidecarPath,readManifestSidecar,} from "../../src/core/brain/manifest.ts";+import { BRAIN_SNAPSHOT_REASON } from "../../src/core/brain/types.ts";++/**+ * The reason every fixture here takes its snapshot for. `createSnapshot`+ * requires one, and these cases are about the archive mechanics rather+ * than the provenance - which lives in `snapshot-reason.test.ts`.+ */+const DREAM = BRAIN_SNAPSHOT_REASON.dream;let vault: string;let configHome: string;@@ -66,7 +76,7 @@ describe("createSnapshot", () => {// into the new archive.writeFileSync(join(dirs.snapshots, "sentinel.tar.zst"), "X");- const res = createSnapshot(vault, "dream-2026-05-14-070000");+ const res = createSnapshot(vault, "dream-2026-05-14-070000", { reason: DREAM });expect(existsSync(res.path)).toBe(true);// Extract into a fresh tmp and inspect.@@ -100,11 +110,11 @@ describe("createSnapshot", () => {});test("rejects invalid run_id", () => {- expect(() => createSnapshot(vault, "../escape")).toThrow();+ expect(() => createSnapshot(vault, "../escape", { reason: DREAM })).toThrow();});test("writes sidecar manifest alongside the archive (ยง22 + ยง5-tail)", () => {- createSnapshot(vault, "dream-with-manifest");+ createSnapshot(vault, "dream-with-manifest", { reason: DREAM });const sidecar = manifestSidecarPath(vault, "dream-with-manifest");expect(existsSync(sidecar)).toBe(true);const m = readManifestSidecar(vault, "dream-with-manifest");@@ -123,19 +133,19 @@ describe("createSnapshot", () => {describe("listSnapshots", () => {test("returns archives in newest-first order by mtime", () => {- createSnapshot(vault, "dream-2026-05-14-070000");+ createSnapshot(vault, "dream-2026-05-14-070000", { reason: DREAM });// Force an older mtime on the first archive so the ordering is// unambiguous regardless of how fast the test runs.const a = snapshotPath(vault, "dream-2026-05-14-070000");const oldT = new Date("2026-05-13T00:00:00Z");utimesSync(a, oldT, oldT);- createSnapshot(vault, "dream-2026-05-14-080000");+ createSnapshot(vault, "dream-2026-05-14-080000", { reason: DREAM });const b = snapshotPath(vault, "dream-2026-05-14-080000");const midT = new Date("2026-05-14T00:00:00Z");utimesSync(b, midT, midT);- createSnapshot(vault, "dream-2026-05-14-090000");+ createSnapshot(vault, "dream-2026-05-14-090000", { reason: DREAM });const c = snapshotPath(vault, "dream-2026-05-14-090000");const newT = new Date("2026-05-15T00:00:00Z");utimesSync(c, newT, newT);@@ -155,14 +165,39 @@ describe("listSnapshots", () => {expect(listSnapshots(vault)).toEqual([]);});+ test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(+ "a snapshots directory it cannot read throws instead of reading as empty",+ () => {+ // An empty history and a history nobody could enumerate are+ // different answers, and `[]` for both is what let `snapshot log`+ // print "no snapshots available" over a directory it never read.+ createSnapshot(vault, "dream-unreadable-dir", { reason: DREAM });+ const snapshots = brainDirs(vault).snapshots;+ chmodSync(snapshots, 0o000);+ try {+ expect(() => listSnapshots(vault)).toThrow(BrainSnapshotListingError);+ try {+ listSnapshots(vault);+ } catch (err) {+ expect((err as Error).message).toContain(snapshots);+ }+ } finally {+ chmodSync(snapshots, 0o755);+ }+ // And the same directory, readable again, still lists its archive:+ // the throw is about the read, not about the snapshot.+ expect(listSnapshots(vault)).toHaveLength(1);+ },+ );+test("manifest_path populated when sidecar present, null otherwise", () => {- createSnapshot(vault, "dream-with-sidecar");+ createSnapshot(vault, "dream-with-sidecar", { reason: DREAM });// Simulate a legacy snapshot: drop the sidecar that// createSnapshot just wrote so only the archive remains.const sidecar = manifestSidecarPath(vault, "dream-with-sidecar");expect(existsSync(sidecar)).toBe(true);- createSnapshot(vault, "dream-legacy");+ createSnapshot(vault, "dream-legacy", { reason: DREAM });rmSync(manifestSidecarPath(vault, "dream-legacy"), { force: true });const list = listSnapshots(vault);@@ -184,7 +219,7 @@ describe("pruneSnapshots", () => {];for (let i = 0; i < labels.length; i++) {const runId = `dream-${labels[i]}-000000`;- createSnapshot(vault, runId);+ createSnapshot(vault, runId, { reason: DREAM });const p = snapshotPath(vault, runId);const t = new Date(ts[i]!);utimesSync(p, t, t);@@ -205,7 +240,7 @@ describe("pruneSnapshots", () => {});test("noop when fewer files than retention_count", () => {- createSnapshot(vault, "dream-only");+ createSnapshot(vault, "dream-only", { reason: DREAM });const res = pruneSnapshots(vault, 10);expect(res.deleted).toEqual([]);expect(listSnapshots(vault)).toHaveLength(1);@@ -216,7 +251,7 @@ describe("pruneSnapshots", () => {const ts = ["2026-05-10T00:00:00Z", "2026-05-11T00:00:00Z", "2026-05-12T00:00:00Z"];for (let i = 0; i < labels.length; i++) {const runId = `dream-prune-${labels[i]}`;- createSnapshot(vault, runId);+ createSnapshot(vault, runId, { reason: DREAM });const p = snapshotPath(vault, runId);const t = new Date(ts[i]!);utimesSync(p, t, t);@@ -235,13 +270,13 @@ describe("pruneSnapshots", () => {});test("legacy archive without sidecar still prunes cleanly", () => {- createSnapshot(vault, "dream-legacy-prune-old");+ createSnapshot(vault, "dream-legacy-prune-old", { reason: DREAM });rmSync(manifestSidecarPath(vault, "dream-legacy-prune-old"), { force: true });const old = snapshotPath(vault, "dream-legacy-prune-old");const t = new Date("2026-05-09T00:00:00Z");utimesSync(old, t, t);- createSnapshot(vault, "dream-legacy-prune-new");+ createSnapshot(vault, "dream-legacy-prune-new", { reason: DREAM });const res = pruneSnapshots(vault, 1);expect(res.deleted).toContain(old);expect(existsSync(old)).toBe(false);@@ -257,7 +292,7 @@ describe("restoreSnapshot โ round-trip integrity", () => {const stateAPref = readFileSync(prefPath, "utf8");const stateASig = readFileSync(sigPath, "utf8");- const snap = createSnapshot(vault, "dream-stateA");+ const snap = createSnapshot(vault, "dream-stateA", { reason: DREAM });expect(existsSync(snap.path)).toBe(true);// Mutate to state B: rewrite a pref, delete a signal, add a new@@ -267,7 +302,7 @@ describe("restoreSnapshot โ round-trip integrity", () => {rmSync(sigPath);writeFileSync(join(dirs.inbox, "sig-newer.md"), "newer-content");// Create another snapshot โ restoring stateA must NOT erase it.- const newer = createSnapshot(vault, "dream-stateB");+ const newer = createSnapshot(vault, "dream-stateB", { reason: DREAM });expect(existsSync(newer.path)).toBe(true);const res = restoreSnapshot(vault, "dream-stateA");@@ -294,7 +329,7 @@ describe("snapshot tooling absent", () => {const originalPath = process.env["PATH"];process.env["PATH"] = "/nonexistent-path-for-test";try {- expect(() => createSnapshot(vault, "dream-no-tools")).toThrow(+ expect(() => createSnapshot(vault, "dream-no-tools", { reason: DREAM })).toThrow(BrainSnapshotToolingMissingError,);} finally {diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.tsindex 1335edfc..3a1faca5 100644--- a/tests/core/brain.types.test.ts+++ b/tests/core/brain.types.test.ts@@ -4,9 +4,13 @@ import {BRAIN_APPLY_RESULT,BRAIN_CONFIDENCE,BRAIN_LOG_EVENT_KIND,+ BRAIN_LOG_EVENT_KIND_SET,BRAIN_PREFERENCE_STATUS,BRAIN_RETIRED_REASON,BRAIN_SIGNAL_SIGN,+ BRAIN_SNAPSHOT_REASON,+ BRAIN_SNAPSHOT_REASONS,+ isBrainSnapshotReason,} from "../../src/core/brain/types.ts";import type {BrainApplyEvidenceLogEvent,@@ -124,12 +128,71 @@ describe("BRAIN_* const enums", () => {"vector-backfill",// provenance-at-the-boundary (t_ac1c4176) event-anchor-only backfill"event-anchor-backfill",+ // silence-is-not-an-answer U7 (t_9d2a5f11) recovery point created โ+ // the counterpart `rollback` has had since it shipped+ "snapshot",]);const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));expect(actual).toEqual(expected);});});+/**+ * U7: the snapshot-reason vocabulary.+ *+ * The reason is persisted into a replicated manifest sidecar, so the trio+ * (frozen object, membership list, guard) is not decoration: the guard is+ * what stands between a peer's hand-edited sidecar and a listing that+ * claims a provenance this build does not understand.+ */+describe("BRAIN_SNAPSHOT_REASON", () => {+ test("the membership list covers every declared value", () => {+ expect([...BRAIN_SNAPSHOT_REASONS].toSorted()).toEqual(+ Object.values(BRAIN_SNAPSHOT_REASON).toSorted(),+ );+ });++ test("the five existing destructive call sites each have a member", () => {+ // Each of these is a run-id prefix that already exists on disk today+ // and that nothing parsed back. Pinning the strings keeps a rename+ // from silently orphaning the archives already in `.snapshots/`.+ expect(BRAIN_SNAPSHOT_REASON.dream).toBe("dream");+ expect(BRAIN_SNAPSHOT_REASON.upgrade).toBe("upgrade");+ expect(BRAIN_SNAPSHOT_REASON.importClaudeMemory).toBe("import-claude-memory");+ expect(BRAIN_SNAPSHOT_REASON.deleteBySource).toBe("delete-by-source");+ expect(BRAIN_SNAPSHOT_REASON.entityPrune).toBe("entity-prune");+ });++ test("the three deferred boundary reasons and the manual one are readable", () => {+ // Nothing WRITES these yet (taking snapshots at those boundaries is+ // deferred), and the manifest must still be able to read a reason a+ // later release writes into a sidecar this build then replicates.+ expect(BRAIN_SNAPSHOT_REASON.sessionBoundary).toBe("session-boundary");+ expect(BRAIN_SNAPSHOT_REASON.planBoundary).toBe("plan-boundary");+ expect(BRAIN_SNAPSHOT_REASON.decisionBoundary).toBe("decision-boundary");+ expect(BRAIN_SNAPSHOT_REASON.manual).toBe("manual");+ });++ test("the guard accepts every member and rejects a non-member", () => {+ for (const reason of BRAIN_SNAPSHOT_REASONS) {+ expect(`${reason}: ${isBrainSnapshotReason(reason)}`).toBe(`${reason}: true`);+ }+ for (const outsider of ["", " ", "Dream", "dream ", "rollback", null, undefined, 7, {}]) {+ expect(`${JSON.stringify(outsider)}: ${isBrainSnapshotReason(outsider)}`).toBe(+ `${JSON.stringify(outsider)}: false`,+ );+ }+ });++ test("the snapshot log kind sits in the shared kind set beside rollback", () => {+ // `appendLogEvent` and the JSONL reader both validate against the set,+ // so a kind missing from it is a kind no writer can emit.+ expect(BRAIN_LOG_EVENT_KIND.snapshot).toBe("snapshot");+ expect(BRAIN_LOG_EVENT_KIND_SET.has(BRAIN_LOG_EVENT_KIND.snapshot)).toBe(true);+ expect(BRAIN_LOG_EVENT_KIND_SET.has(BRAIN_LOG_EVENT_KIND.rollback)).toBe(true);+ });+});+describe("interface shape smoke (compile-time)", () => {test("BrainSignal literal satisfies the type", () => {const sig = {@@ -237,7 +300,11 @@ describe("interface shape smoke (compile-time)", () => {medium_min: 0.4,high_min: 0.75,},- snapshots: { retention_count: 10 },+ snapshots: {+ retention_count: 10,+ include_derived_store: false,+ derived_store_max_bytes: 268_435_456,+ },} as const satisfies BrainConfig;expect(cfg.schema_version).toBe(1);expect(cfg.primary_agent).toBeNull();diff --git a/tests/core/brain/active-budget.test.ts b/tests/core/brain/active-budget.test.tsindex 7f2c3fef..7bbae064 100644--- a/tests/core/brain/active-budget.test.ts+++ b/tests/core/brain/active-budget.test.ts@@ -68,7 +68,56 @@ describe("budgetActiveBody", () => {test("unsectioned body still respects the budget", () => {const flat = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n");const out = budgetActiveBody(flat, 120);- expect(out.length).toBeLessThanOrEqual(120 + 200); // content budget + notice overhead+ expect(out.length).toBeLessThanOrEqual(120 + 300); // content budget + notice overheadexpect(out).toContain("line 0");});});++/**+ * The truncation notice used to be a fixed sentence that named nothing,+ * while the budgeter one line above it returned the exact list of keys+ * it had dropped. The agent was told a rule had gone and not which one -+ * the same silence this release is about. Section headings are text this+ * project authors, never operator text, so naming them is safe.+ */+describe("budgetActiveBody: the truncation notice names what it dropped", () => {+ test("an over-budget body names the dropped headings", () => {+ const input = body();+ const out = budgetActiveBody(input, input.length - 20);+ expect(out).toContain("Recently retired");+ // Named as dropped, not merely present: the heading itself is gone.+ expect(out).not.toContain("## Recently retired");+ expect(out).not.toContain("pref-r");+ });++ test("a tighter budget names every dropped heading in drop order", () => {+ const out = budgetActiveBody(body(), 250);+ const notice = out.slice(out.lastIndexOf("_Injection truncated"));+ const retired = notice.indexOf("Recently retired");+ const quarantine = notice.indexOf("Quarantine");+ const mostApplied = notice.indexOf("Most-applied");+ expect(retired).toBeGreaterThanOrEqual(0);+ expect(quarantine).toBeGreaterThan(retired);+ expect(mostApplied).toBeGreaterThan(quarantine);+ });++ test("the notice quantifies the cut in characters", () => {+ const input = body();+ const out = budgetActiveBody(input, 250);+ expect(out).toContain(String(input.length));+ });++ test("a within-budget body is byte-identical to its input", () => {+ // The idempotent-write comparison upstream depends on this, so the+ // richer notice must stay strictly on the truncated path.+ const input = body();+ expect(budgetActiveBody(input, input.length)).toBe(input);+ expect(budgetActiveBody(input, 10_000)).toBe(input);+ });++ test("a body with no dropped sections still points at the full view", () => {+ const flat = Array.from({ length: 50 }, (_, i) => `line ${i}`).join("\n");+ const out = budgetActiveBody(flat, 120);+ expect(out).toContain("brain_context");+ });+});diff --git a/tests/core/brain/config-template-ratchet.test.ts b/tests/core/brain/config-template-ratchet.test.tsindex 795431c3..a138d197 100644--- a/tests/core/brain/config-template-ratchet.test.ts+++ b/tests/core/brain/config-template-ratchet.test.ts@@ -46,6 +46,7 @@ import {LESSONS_LIMIT_DEFAULT,MOST_APPLIED_LIMIT_DEFAULT,MOST_APPLIED_WINDOW_DAYS_DEFAULT,+ STANDING_RULES_MAX_CHARS_DEFAULT,} from "../../../src/core/brain/policy.ts";import { parseBrainYaml } from "../../../src/core/brain/yaml-parse.ts";import { DEFAULT_VAULT_IGNORE_PATHS } from "../../../src/core/vault-scope/defaults.ts";@@ -141,6 +142,8 @@ function resolvedView(cfg: BrainConfig): Record<string, unknown> {limit: MOST_APPLIED_LIMIT_DEFAULT,},active_inject_budget_chars: cfg.active?.inject_budget_chars ?? INJECT_BUDGET_CHARS_DEFAULT,+ active_standing_rules_max_chars:+ cfg.active?.standing_rules_max_chars ?? STANDING_RULES_MAX_CHARS_DEFAULT,lessons: {half_life_days: cfg.lessons?.half_life_days ?? LESSONS_HALF_LIFE_DAYS_DEFAULT,corroboration_min: cfg.lessons?.corroboration_min ?? LESSONS_CORROBORATION_MIN_DEFAULT,diff --git a/tests/core/brain/continuity/reader-census.test.ts b/tests/core/brain/continuity/reader-census.test.tsindex 13a09b26..3d3a174f 100644--- a/tests/core/brain/continuity/reader-census.test.ts+++ b/tests/core/brain/continuity/reader-census.test.ts@@ -106,6 +106,8 @@ const DIRECT_STORE_READERS: Readonly<Record<string, string>> = Object.freeze({"reads the WHOLE store for `session_turn` / `session_summary_node`, plus a " +"dedupe-key lookup.","src/core/brain/session-summary.ts": "reads `session_summary_digest` for listing and dedupe.",+ "src/core/brain/stale-dependency.ts":+ "reads `context_receipt` to find which consumers cited a state that has since changed.","src/core/brain/skill-proposals.ts":"reads the WHOLE store forward from a watermark to derive skill proposals.","src/core/brain/temporal/foresight.ts":@@ -129,7 +131,7 @@ const DIRECT_STORE_READERS: Readonly<Record<string, string>> = Object.freeze({* measurement.*/const MIN_READ_MODEL_READERS = 4;-const MIN_DIRECT_STORE_READERS = 19;+const MIN_DIRECT_STORE_READERS = 20;/** A file the classifier must see, and that `grep` alone does not. */diff --git a/tests/core/brain/doctor-exit-census.test.ts b/tests/core/brain/doctor-exit-census.test.tsindex 6c766a6f..ec6db3bf 100644--- a/tests/core/brain/doctor-exit-census.test.ts+++ b/tests/core/brain/doctor-exit-census.test.ts@@ -191,6 +191,7 @@ const DOCTOR_REGISTERED_CODES: ReadonlyArray<string> = ["principle-corrupted","schema-version-unknown","stale-claim",+ "stale-dependency","sync-conflict-log","tier-drift","vault-walk-entry-skipped",diff --git a/tests/core/brain/doctor/stale-dependency-check.test.ts b/tests/core/brain/doctor/stale-dependency-check.test.tsnew file mode 100644index 00000000..01e22511--- /dev/null+++ b/tests/core/brain/doctor/stale-dependency-check.test.ts@@ -0,0 +1,495 @@+/**+ * U3 - the reverse stale-dependency audit.+ *+ * The join is the whole feature, so the assertions are about the four+ * ways it could be wrong: reporting a consumer that postdates the change,+ * missing one that predates it because the identifier is spelled+ * differently on each side, flagging history for agreeing with itself,+ * and - the wave's own failure mode - reporting a store nobody measured+ * as a store with nothing wrong with it.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { emitContextReceipt } from "../../../../src/core/brain/context-receipts.ts";+import {+ appendDecisionChangeReceipt,+ readDecisionChangeReceipts,+ receiptsDir,+ ReceiptError,+} from "../../../../src/core/brain/decisions/receipts.ts";+import { DIAGNOSTIC_SIGNALS } from "../../../../src/core/brain/diagnostics.ts";+import { runDoctor } from "../../../../src/core/brain/doctor.ts";+import type { DoctorCheckContext } from "../../../../src/core/brain/doctor/check.ts";+import type { DoctorUncertainEntry } from "../../../../src/core/brain/doctor/report.ts";+import type { DoctorIssue } from "../../../../src/core/brain/types.ts";+import {+ joinStaleDependencies,+ makeStaleDependencyCheck,+ STALE_DEPENDENCY_CODE,+ STALE_DEPENDENCY_CONSUMER,+ STALE_DEPENDENCY_STATE,+ type StaleDependencyCitation,+ type StaleDependencyState,+} from "../../../../src/core/brain/doctor/stale-dependency-check.ts";+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import { appendLogEvent } from "../../../../src/core/brain/log.ts";+import { brainDirs, preferencePath, retiredPath } from "../../../../src/core/brain/paths.ts";+import { moveToRetired, writePreference } from "../../../../src/core/brain/preference.ts";+import { auditStaleDependencies } from "../../../../src/core/brain/stale-dependency.ts";+import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";++let vault: string;+let configHome: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-stale-dep-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-stale-dep-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ const truth = receiptsDir(vault);+ try {+ chmodSync(truth, 0o700);+ } catch {+ // The directory may never have been created; nothing to restore.+ }+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++// ----- helpers --------------------------------------------------------------++/** A preference whose `evidenced_by` cites `cites` by wikilink. */+function seedPreference(slug: string, createdAt: string, cites: ReadonlyArray<string> = []): void {+ writePreference(vault, {+ slug,+ topic: slug,+ principle: `rule ${slug}`,+ created_at: createdAt,+ unconfirmed_until: "2030-01-01T00:00:00Z",+ status: "confirmed",+ evidenced_by: cites.map((target) => `[[${target}]]`),+ });+}++function retire(slug: string, at: string): void {+ moveToRetired(vault, preferencePath(vault, slug), "rebutted", {+ now: new Date(at),+ retired_by: `[[Brain/log/${at.slice(0, 10)}]]`,+ });+}++/** Emit one context receipt naming `ids` at `createdAt`. */+function seedReceipt(createdAt: string, ids: ReadonlyArray<string>): void {+ emitContextReceipt(vault, {+ options: { host: "unit-test", trigger: "context_pack", createdAt },+ items: ids.map((id) => ({ id })),+ finalText: ids.join("|"),+ });+}++/** Pin a file's last-write instant, which is the consumer clock. */+function setWriteInstant(path: string, at: string): void {+ const seconds = new Date(at).getTime() / 1000;+ utimesSync(path, seconds, seconds);+}++const NOW = new Date("2026-06-01T00:00:00Z");++/** A window wide enough that no assertion below depends on its width. */+const WIDE_LOOKBACK_DAYS = 3650;++function audit(overrides: { readonly maxConsumersPerState?: number } = {}) {+ return auditStaleDependencies(vault, {+ now: NOW,+ lookbackDays: WIDE_LOOKBACK_DAYS,+ ...overrides,+ });+}++function state(key: string, changedAt: string): StaleDependencyState {+ return {+ key,+ kind: STALE_DEPENDENCY_STATE.retired,+ path: `/vault/Brain/retired/ret-${key}.md`,+ changed_at: changedAt,+ changed_at_ms: Date.parse(changedAt),+ };+}++function citation(+ id: string,+ writtenAt: string,+ cites: ReadonlyArray<string>,+ live = true,+): StaleDependencyCitation {+ return {+ kind: STALE_DEPENDENCY_CONSUMER.contextReceipt,+ id,+ written_at: writtenAt,+ written_at_ms: Date.parse(writtenAt),+ live,+ cites,+ };+}++// ----- the pure join --------------------------------------------------------++describe("joinStaleDependencies", () => {+ test("reports a consumer written before the change and not one written after", () => {+ const rows = joinStaleDependencies({+ states: [state("alpha", "2026-03-01T00:00:00Z")],+ citations: [+ citation("before", "2026-02-01T00:00:00Z", ["alpha"]),+ citation("after", "2026-04-01T00:00:00Z", ["alpha"]),+ ],+ maxConsumersPerState: 10,+ });+ expect(rows.length).toBe(1);+ expect(rows[0]!.consumers.map((c) => c.id)).toEqual(["before"]);+ });++ test("the comparison is strict: a consumer written at the change instant is current", () => {+ const rows = joinStaleDependencies({+ states: [state("alpha", "2026-03-01T00:00:00Z")],+ citations: [citation("simultaneous", "2026-03-01T00:00:00Z", ["alpha"])],+ maxConsumersPerState: 10,+ });+ expect(rows).toEqual([]);+ });++ test("a consumer that is no longer live is not a dependency anybody is standing on", () => {+ const rows = joinStaleDependencies({+ states: [state("alpha", "2026-03-01T00:00:00Z")],+ citations: [citation("retired-citer", "2026-02-01T00:00:00Z", ["alpha"], false)],+ maxConsumersPerState: 10,+ });+ expect(rows).toEqual([]);+ });++ test("two states folding to one key keep the earliest instant", () => {+ const later: StaleDependencyState = {+ ...state("alpha", "2026-05-01T00:00:00Z"),+ kind: STALE_DEPENDENCY_STATE.tombstoned,+ };+ const rows = joinStaleDependencies({+ states: [later, state("alpha", "2026-03-01T00:00:00Z")],+ citations: [citation("between", "2026-04-01T00:00:00Z", ["alpha"])],+ maxConsumersPerState: 10,+ });+ // Written after the retirement, so it is NOT stale even though the+ // tombstone came later; the earliest change is the honest boundary.+ expect(rows).toEqual([]);+ });++ test("the cap bounds what is listed and the row still reports the true total", () => {+ const rows = joinStaleDependencies({+ states: [state("alpha", "2026-03-01T00:00:00Z")],+ citations: [+ citation("c1", "2026-01-01T00:00:00Z", ["alpha"]),+ citation("c2", "2026-01-02T00:00:00Z", ["alpha"]),+ citation("c3", "2026-01-03T00:00:00Z", ["alpha"]),+ citation("c4", "2026-01-04T00:00:00Z", ["alpha"]),+ ],+ maxConsumersPerState: 2,+ });+ expect(rows[0]!.consumers.map((c) => c.id)).toEqual(["c1", "c2"]);+ expect(rows[0]!.consumer_total).toBe(4);+ });+});++// ----- the collector over a real vault --------------------------------------++describe("auditStaleDependencies", () => {+ test("a receipt naming the pre-retirement id joins the retired record", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedReceipt("2026-02-01T00:00:00Z", ["pref-alpha"]);+ retire("alpha", "2026-03-01T00:00:00Z");++ const report = audit();+ expect(report.receipts_recorded).toBe(true);+ expect(report.rows.length).toBe(1);+ const row = report.rows[0]!;+ expect(row.state).toBe("alpha");+ expect(row.state_kind).toBe(STALE_DEPENDENCY_STATE.retired);+ expect(row.state_path).toBe(retiredPath(vault, "alpha"));+ expect(row.changed_at).toBe("2026-03-01T00:00:00.000Z");+ expect(row.consumers.map((c) => c.kind)).toEqual([STALE_DEPENDENCY_CONSUMER.contextReceipt]);+ });++ test("bare, wikilink and note-path spellings of one subject fold to one row", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedReceipt("2026-02-01T00:00:00Z", ["alpha"]);+ seedReceipt("2026-02-02T00:00:00Z", ["[[pref-alpha]]"]);+ seedReceipt("2026-02-03T00:00:00Z", ["Brain/retired/ret-alpha.md"]);+ retire("alpha", "2026-03-01T00:00:00Z");++ const report = audit();+ expect(report.rows.length).toBe(1);+ expect(report.rows[0]!.state).toBe("alpha");+ expect(report.rows[0]!.consumer_total).toBe(3);+ });++ test("a decision-change receipt whose evidence cited the rule is a consumer", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ appendDecisionChangeReceipt(vault, {+ subject: "[[decision-adopt-bun]]",+ before: "undecided",+ after: "adopted",+ evidenceTriggers: ["[[pref-alpha]]"],+ actor: "unit-test",+ reasonCode: "decision-record",+ ts: "2026-02-01T00:00:00Z",+ configPath,+ });+ retire("alpha", "2026-03-01T00:00:00Z");++ const report = audit();+ expect(report.receipts_recorded).toBe(true);+ expect(report.rows.length).toBe(1);+ const consumer = report.rows[0]!.consumers[0]!;+ expect(consumer.kind).toBe(STALE_DEPENDENCY_CONSUMER.decisionChange);+ // Folded by the existing subject normalizer, not by a second copy.+ expect(consumer.id).toBe("decision-adopt-bun");+ });++ test("a live artifact citing the rule is reported and a retired one is not", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedPreference("beta", "2026-01-01T00:00:00Z", ["pref-alpha"]);+ seedPreference("gamma", "2026-01-01T00:00:00Z", ["pref-alpha"]);+ seedReceipt("2026-02-01T00:00:00Z", ["pref-alpha"]);+ retire("beta", "2026-02-10T00:00:00Z");+ retire("alpha", "2026-03-01T00:00:00Z");+ // Both citers last written well before the retirement, so only+ // liveness can separate them.+ setWriteInstant(retiredPath(vault, "beta"), "2026-01-05T00:00:00Z");+ setWriteInstant(preferencePath(vault, "gamma"), "2026-01-05T00:00:00Z");++ const report = audit();+ const row = report.rows.find((r) => r.state === "alpha")!;+ const artifacts = row.consumers.filter(+ (c) => c.kind === STALE_DEPENDENCY_CONSUMER.brainArtifact,+ );+ expect(artifacts.map((c) => c.id)).toEqual(["pref-gamma"]);+ });++ test("the retirement's own log entry and back-pointer do not self-flag", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ // A log entry naming the rule, written before the retirement: the+ // append-only log is the record THAT the state changed, never a+ // consumer resting on it having not changed.+ appendLogEvent(vault, {+ timestamp: "2026-02-01T00:00:00Z",+ eventType: BRAIN_LOG_EVENT_KIND.retire,+ body: { preference: "[[pref-alpha]]", agent: "unit-test" },+ });+ retire("alpha", "2026-03-01T00:00:00Z");+ // The retired file carries `pref-alpha` in its own `aliases:`, so a+ // naive reverse lookup would resolve it onto itself.+ setWriteInstant(retiredPath(vault, "alpha"), "2026-01-05T00:00:00Z");+ // Something unrelated has to be measured, or the report is+ // not-recorded and proves nothing about the join.+ seedReceipt("2026-02-01T00:00:00Z", ["pref-unrelated"]);++ expect(audit().rows).toEqual([]);+ });++ test("a receipt-less vault still reports the citations that need no receipts", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedPreference("beta", "2026-01-01T00:00:00Z", ["pref-alpha"]);+ retire("alpha", "2026-03-01T00:00:00Z");+ setWriteInstant(preferencePath(vault, "beta"), "2026-01-05T00:00:00Z");++ const report = audit();+ // The backlink evidence is on disk and costs no telemetry, so the live+ // record citing a rule retired under it is a finding either way. What+ // the absent receipt trail costs is the OTHER half - packs and+ // decisions - and that is all the flag claims.+ expect(report.receipts_recorded).toBe(false);+ expect(report.rows.length).toBe(1);+ expect(report.rows[0]!.state).toBe("alpha");+ expect(report.rows[0]!.consumers.map((consumer) => consumer.kind)).toEqual([+ STALE_DEPENDENCY_CONSUMER.brainArtifact,+ ]);+ expect(report.lookback_days).toBe(WIDE_LOOKBACK_DAYS);+ expect(report.window_since < NOW.toISOString()).toBe(true);+ });++ test("a vault where nothing ever changed reports no rows and nothing unmeasured", () => {+ // The other shape of a quiet answer, and the one that must stay quiet:+ // no state stopped being current, so no consumer of one can be stale+ // and an absent receipt trail costs this vault nothing.+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedPreference("beta", "2026-01-01T00:00:00Z", ["pref-alpha"]);++ const report = audit();+ expect(report.receipts_recorded).toBe(false);+ expect(report.rows).toEqual([]);+ expect(report.states_changed).toBe(0);+ });++ test("an unmeasured receipt trail is named without suppressing what was computed", () => {+ // Two things have to be true at once here. The half that needed a+ // receipt is named as unmeasured, because an empty issue list would+ // read as a clean bill of health for consumers nobody looked at - and+ // the half that needed nothing but the backlink graph is still+ // reported, because withholding a computed finding to say "nothing is+ // known" would be the same false silence pointed the other way.+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedPreference("beta", "2026-01-01T00:00:00Z", ["pref-alpha"]);+ retire("alpha", "2026-03-01T00:00:00Z");+ setWriteInstant(preferencePath(vault, "beta"), "2026-01-05T00:00:00Z");++ const issues: DoctorIssue[] = [];+ const uncertain: DoctorUncertainEntry[] = [];+ makeStaleDependencyCheck((v, opts) =>+ auditStaleDependencies(v, { ...opts, lookbackDays: WIDE_LOOKBACK_DAYS }),+ ).run({ vault, now: NOW } as unknown as DoctorCheckContext, { issues, uncertain });++ // The computed half reaches the issue stream...+ expect(issues.map((issue) => issue.target)).toEqual(["alpha"]);+ // ...and the unmeasured half is named rather than implied by silence,+ // scoped to the consumers a receipt would have carried.+ const entry = uncertain.find((item) => item.code === STALE_DEPENDENCY_CODE);+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("were not measured");+ expect(entry!.message).toContain("reported above");+ });++ test("a measured vault records no uncertainty", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedReceipt("2026-02-01T00:00:00Z", ["pref-alpha"]);+ retire("alpha", "2026-03-01T00:00:00Z");++ const issues: DoctorIssue[] = [];+ const uncertain: DoctorUncertainEntry[] = [];+ makeStaleDependencyCheck((v, opts) =>+ auditStaleDependencies(v, { ...opts, lookbackDays: WIDE_LOOKBACK_DAYS }),+ ).run({ vault, now: NOW } as unknown as DoctorCheckContext, { issues, uncertain });++ expect(uncertain.filter((item) => item.code === STALE_DEPENDENCY_CODE)).toEqual([]);+ expect(issues.length).toBeGreaterThan(0);+ });++ test("the per-state cap reports the true total rather than a silent prefix", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ for (const day of ["01", "02", "03", "04", "05"]) {+ seedReceipt(`2026-02-${day}T00:00:00Z`, ["pref-alpha"]);+ }+ retire("alpha", "2026-03-01T00:00:00Z");++ const report = audit({ maxConsumersPerState: 2 });+ expect(report.rows[0]!.consumers.length).toBe(2);+ expect(report.rows[0]!.consumer_total).toBe(5);+ });+});++// ----- the doctor check -----------------------------------------------------++describe("staleDependencyCheck inside the doctor pass", () => {+ test("a receipt-less vault still warns about the citation it could compute", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedPreference("beta", "2026-01-01T00:00:00Z", ["pref-alpha"]);+ retire("alpha", "2026-03-01T00:00:00Z");+ setWriteInstant(preferencePath(vault, "beta"), "2026-01-05T00:00:00Z");++ const result = runDoctor(vault, { now: NOW });+ const found = result.warnings.filter((w) => w.code === STALE_DEPENDENCY_CODE);+ expect(found.length).toBe(1);+ expect(found[0]!.target).toBe("alpha");+ });++ test("a vault where nothing ever changed stays silent on both channels", () => {+ // The permanent-notice trap: warning whenever a receipt trail is absent+ // would put this line on every clean vault, which is how a real signal+ // stops being read.+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedPreference("beta", "2026-01-01T00:00:00Z", ["pref-alpha"]);++ const result = runDoctor(vault, { now: NOW });+ expect(result.warnings.filter((w) => w.code === STALE_DEPENDENCY_CODE)).toEqual([]);+ expect((result.uncertain ?? []).filter((u) => u.code === STALE_DEPENDENCY_CODE)).toEqual([]);+ });++ test("a measured vault surfaces one warning naming the true consumer total", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ seedReceipt(new Date(NOW.getTime() - 86_400_000).toISOString(), ["pref-alpha"]);+ retire("alpha", NOW.toISOString());++ const found = runDoctor(vault, { now: NOW }).warnings.filter(+ (w) => w.code === STALE_DEPENDENCY_CODE,+ );+ expect(found.length).toBe(1);+ expect(found[0]!.target).toBe("alpha");+ expect(found[0]!.message).toContain("1 consumer(s) written before that still rest on it");+ });++ test("an unreadable continuity directory surfaces uncertainty and spares the other checks", () => {+ seedPreference("alpha", "2026-01-01T00:00:00Z");+ retire("alpha", "2026-03-01T00:00:00Z");+ // A dangling reference, so another check has something to report and+ // the assertion below is not vacuous.+ seedPreference("dangling", "2026-01-01T00:00:00Z", ["sig-2026-01-01-nowhere"]);+ // A regular file where the continuity shard directory belongs: the+ // store exists and cannot be listed, on every host and every uid.+ writeFileSync(join(brainDirs(vault).log, "continuity"), "not a directory\n", "utf8");++ const result = runDoctor(vault, { now: NOW });+ const others = result.warnings.filter((w) => w.code !== STALE_DEPENDENCY_CODE);+ expect(others.length).toBeGreaterThan(0);+ const uncertain = result.uncertain ?? [];+ const entry = uncertain.find((u) => u.message.includes("continuity record read failed"));+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("resting on a retired");+ });++ test("the issue code resolves to a registered next command", () => {+ const signal = DIAGNOSTIC_SIGNALS.get(STALE_DEPENDENCY_CODE);+ expect(signal).toBeDefined();+ expect(signal!.nextCommand.length).toBeGreaterThan(0);+ });+});++// ----- the defect in the blast radius ---------------------------------------++describe("readDecisionChangeReceipts separates an absent store from an unreadable one", () => {+ test("a store that was never created reports no decisions", () => {+ expect(readDecisionChangeReceipts(vault)).toEqual({ receipts: [], warnings: [] });+ });++ test("a store that cannot be listed raises instead of reporting no decisions", () => {+ mkdirSync(receiptsDir(vault), { recursive: true });+ chmodSync(receiptsDir(vault), 0o300);+ expect(() => readDecisionChangeReceipts(vault)).toThrow(ReceiptError);+ });++ test("an append whose idempotency probe cannot read the store refuses to duplicate", () => {+ const input = {+ subject: "Brain/decisions/decision-adopt-bun.md",+ before: "undecided",+ after: "adopted",+ actor: "unit-test",+ reasonCode: "decision-record",+ ts: "2026-02-01T00:00:00Z",+ configPath,+ };+ expect(appendDecisionChangeReceipt(vault, input).appended).toBe(true);++ // Writable, not listable: exactly the state in which the duplicate+ // guard used to read "no prior receipt" and append a second copy.+ chmodSync(receiptsDir(vault), 0o300);+ expect(() => appendDecisionChangeReceipt(vault, input)).toThrow(ReceiptError);++ chmodSync(receiptsDir(vault), 0o700);+ expect(readDecisionChangeReceipts(vault).receipts.length).toBe(1);+ });+});diff --git a/tests/core/brain/dream-checkpoints.test.ts b/tests/core/brain/dream-checkpoints.test.tsindex 82c739a2..f716acc3 100644--- a/tests/core/brain/dream-checkpoints.test.ts+++ b/tests/core/brain/dream-checkpoints.test.ts@@ -119,6 +119,29 @@ const DIGEST_EXCLUSIONS: ReadonlyArray<string> = Object.freeze([join("Brain", "vault-id.json"),]);+/**+ * The one value in the log that the comparison cannot ask to be+ * reproducible: the `snapshot` audit line records the archive's byte+ * length, and the archive is the artifact {@link DIGEST_EXCLUSIONS}+ * deliberately drops - tar embeds per-entry mtimes, so two identically+ * seeded vaults compress to near-identical but not byte-identical+ * archives. Only the digits are normalised, so the audit line's reason,+ * run id, key order and very presence all stay under byte comparison.+ */+const ARCHIVE_SIZE_RE = /(size_bytes"?:\s*"?)\d+/g;++/**+ * Where that normalisation is allowed to apply.+ *+ * Confining it matters because the substitution needs the file as text,+ * and a utf8 decode is lossy: two different byte sequences can decode to+ * the same string through replacement characters, so decoding the whole+ * tree would quietly weaken the comparison it exists to make. The log is+ * JSONL by construction, so decoding is exact there; everything else is+ * hashed as raw bytes.+ */+const NORMALISED_SUBTREE = join("Brain", "log");+/** Recursive `<relative path>:<sha256>` digest of a tree, sorted. */function treeDigest(root: string): string {const lines: string[] = [];@@ -127,8 +150,14 @@ function treeDigest(root: string): string {const full = join(dir, name);const rel = relative(root, full);if (DIGEST_EXCLUSIONS.some((v) => rel === v || rel.startsWith(`${v}/`))) continue;- if (statSync(full).isDirectory()) walk(full);- else lines.push(`${rel}:${createHash("sha256").update(readFileSync(full)).digest("hex")}`);+ if (statSync(full).isDirectory()) {+ walk(full);+ continue;+ }+ const content = rel.startsWith(`${NORMALISED_SUBTREE}/`)+ ? readFileSync(full, "utf8").replaceAll(ARCHIVE_SIZE_RE, "$1<archive-size>")+ : readFileSync(full);+ lines.push(`${rel}:${createHash("sha256").update(content).digest("hex")}`);}};walk(root);diff --git a/tests/core/brain/log-shards.read.test.ts b/tests/core/brain/log-shards.read.test.tsindex 72ab4e7b..0be4bc84 100644--- a/tests/core/brain/log-shards.read.test.ts+++ b/tests/core/brain/log-shards.read.test.ts@@ -11,13 +11,19 @@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 { basename, join } from "node:path";import { bootstrapBrain } from "../../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";import { appendLogEvent } from "../../../src/core/brain/log.ts";-import { listLogDates, readLogDay } from "../../../src/core/brain/log-jsonl.ts";-import { brainDirs } from "../../../src/core/brain/paths.ts";+import { listLogDates, parseLogFileName, readLogDay } from "../../../src/core/brain/log-jsonl.ts";+import {+ brainDirs,+ logJsonlPath,+ logPath,+ logShardJsonlPath,+ logShardPath,+} from "../../../src/core/brain/paths.ts";import { runDoctor } from "../../../src/core/brain/doctor.ts";let vault: string;@@ -129,6 +135,58 @@ describe("listLogDates", () => {});});+/**+ * The log-file recogniser is bound to the builders, not to itself.+ *+ * `parseLogFileName` is exported so a second consumer - the snapshot diff+ * classifier - can decide whether a file is a day of the log without+ * carrying its own copy of the shape. The copy it did carry predated+ * per-device sharding and mislabelled both files a current vault writes,+ * which is exactly what a duplicated pattern costs; a third copy would+ * have been a third chance to make the same mistake.+ *+ * A recogniser tested only against hand-written names proves that it+ * agrees with the test author. These assertions run the four path builders+ * and feed their real output back in, so the recogniser is pinned to what+ * the writers actually produce.+ */+describe("parseLogFileName agrees with the log path builders", () => {+ const DATE = "2026-06-01";+ const DEVICE = "mac1234";++ test("every builder's output parses back to what built it", () => {+ const cases: ReadonlyArray<{+ readonly path: string;+ readonly shardId: string;+ readonly ext: "jsonl" | "md";+ }> = [+ { path: logPath(vault, DATE), shardId: "", ext: "md" },+ { path: logJsonlPath(vault, DATE), shardId: "", ext: "jsonl" },+ { path: logShardPath(vault, DATE, DEVICE), shardId: DEVICE, ext: "md" },+ { path: logShardJsonlPath(vault, DATE, DEVICE), shardId: DEVICE, ext: "jsonl" },+ ];+ for (const expected of cases) {+ const name = basename(expected.path);+ expect(`${name} -> ${JSON.stringify(parseLogFileName(name))}`).toBe(+ `${name} -> ${JSON.stringify({ date: DATE, shardId: expected.shardId, ext: expected.ext })}`,+ );+ }+ });++ test("names no builder produces are not days of the log", () => {+ for (const name of [+ "capture-decisions.jsonl",+ "recurrence-support.jsonl",+ "not-a-date.md",+ "2026-06-01.txt",+ "2026-06-01.sync-conflict-20260601-120000-abcdef.jsonl",+ "2026-6-1.md",+ ]) {+ expect(`${name}: ${parseLogFileName(name) === null}`).toBe(`${name}: true`);+ }+ });+});+describe("doctor sync-conflict lint", () => {test("flags .sync-conflict-* files under Brain/log", () => {mkdirSync(logDir(), { recursive: true });diff --git a/tests/core/brain/manifest.test.ts b/tests/core/brain/manifest.test.tsindex 66e75ad7..8b924a03 100644--- a/tests/core/brain/manifest.test.ts+++ b/tests/core/brain/manifest.test.ts@@ -24,9 +24,11 @@ import {manifestDiffHasDrift,manifestSidecarPath,readManifestSidecar,+ SNAPSHOT_STORE_EXCLUSION,writeManifestSidecar,type BrainManifest,} from "../../../src/core/brain/manifest.ts";+import { BRAIN_SNAPSHOT_REASON, BRAIN_SNAPSHOT_REASONS } from "../../../src/core/brain/types.ts";let vault: string;let brain: string;@@ -75,6 +77,18 @@ describe("buildManifest", () => {expect(Object.keys(m.files)).toEqual(["preferences/pref-x.md"]);});+ test(".artifacts/ is excluded from the walk", () => {+ // Documented as never backed up, yet hashed into every manifest -+ // so TTL'd tool output churning between a snapshot and a rollback+ // tripped the drift gate on a directory no restore ever touches.+ mkdirSync(join(brain, ".artifacts", "run-1"), { recursive: true });+ writeFileSync(join(brain, ".artifacts", "run-1", "a.json"), "{}");+ mkdirSync(join(brain, "preferences"));+ writeFileSync(join(brain, "preferences", "pref-x.md"), "x");+ const m = buildManifest(brain);+ expect(Object.keys(m.files)).toEqual(["preferences/pref-x.md"]);+ });+test("symlink under Brain/ is skipped (security)", () => {mkdirSync(join(brain, "preferences"));writeFileSync(join(brain, "preferences", "pref-real.md"), "real");@@ -260,3 +274,306 @@ describe("sidecar I/O", () => {);});});++/**+ * The derived-store record travels on the same distribution channel as+ * the rest of the sidecar - Syncthing, a manual copy, an operator who+ * lost their nerves - so every field is validated on read and a single+ * malformation fails the WHOLE manifest closed, exactly as one bad file+ * entry already does. Anything looser would let a half-written record+ * claim a coverage the archive does not have, and the restore acts on+ * that claim.+ */+describe("the derived-store field on the sidecar", () => {+ /** A sidecar carrying `derived_store` verbatim, written to disk. */+ function writeSidecarWithStore(runId: string, derivedStore: unknown): void {+ writeFileSync(+ manifestSidecarPath(vault, runId),+ JSON.stringify({+ schema_version: 1,+ generated_at: "2026-05-18T00:00:00Z",+ brain_root: "Brain",+ files: {},+ derived_store: derivedStore,+ }),+ );+ }++ const INCLUDED = Object.freeze({+ included: true,+ source_path: "/vault/.open-second-brain/brain.sqlite",+ archive_name: "run.store.sqlite.zst",+ archive_sha256: "a".repeat(64),+ archive_size: 4096,+ live_size: 8192,+ exclusion_reason: null,+ });++ const EXCLUDED = Object.freeze({+ included: false,+ source_path: "/vault/.open-second-brain/brain.sqlite",+ archive_name: null,+ archive_sha256: null,+ archive_size: null,+ live_size: 8192,+ exclusion_reason: SNAPSHOT_STORE_EXCLUSION.not_requested,+ });++ test("an absent key parses and reads as unknown, never as excluded", () => {+ writeFileSync(+ manifestSidecarPath(vault, "pre-feature"),+ JSON.stringify({+ schema_version: 1,+ generated_at: "2026-05-18T00:00:00Z",+ brain_root: "Brain",+ files: {},+ }),+ );+ const back = readManifestSidecar(vault, "pre-feature");+ // The manifest itself is valid - an older peer's sidecar must keep+ // its drift guarantee, which is why the schema version was not+ // bumped for this field.+ expect(back).not.toBeNull();+ expect(back!.derived_store).toBeUndefined();+ });++ test("a well-formed inclusion record roundtrips", () => {+ writeSidecarWithStore("included", INCLUDED);+ expect(readManifestSidecar(vault, "included")!.derived_store).toEqual(INCLUDED);+ });++ test("a well-formed exclusion record roundtrips", () => {+ writeSidecarWithStore("excluded", EXCLUDED);+ expect(readManifestSidecar(vault, "excluded")!.derived_store).toEqual(EXCLUDED);+ });++ test("a live size of zero is kept, because zero is a real size", () => {+ writeSidecarWithStore("zero-size", { ...EXCLUDED, live_size: 0 });+ expect(readManifestSidecar(vault, "zero-size")!.derived_store!.live_size).toBe(0);+ });++ test("an explicit null record is contained to the field, not the record", () => {+ writeSidecarWithStore("null-record", null);+ const contained = readManifestSidecar(vault, "null-record");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.derived_store).toBeUndefined();+ expect(contained!.derived_store_unreadable).toBe(true);+ });++ test("a non-object record is contained to the field, not the record", () => {+ writeSidecarWithStore("scalar-record", "included");+ const contained = readManifestSidecar(vault, "scalar-record");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.derived_store).toBeUndefined();+ expect(contained!.derived_store_unreadable).toBe(true);+ });++ test("a missing `included` flag is contained to the field, not the record", () => {+ const { included: _drop, ...rest } = INCLUDED;+ writeSidecarWithStore("no-flag", rest);+ const contained = readManifestSidecar(vault, "no-flag");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.derived_store).toBeUndefined();+ expect(contained!.derived_store_unreadable).toBe(true);+ });++ test("a non-integer archive size is contained to the field, not the record", () => {+ writeSidecarWithStore("fractional", { ...INCLUDED, archive_size: 4096.5 });+ const contained = readManifestSidecar(vault, "fractional");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.derived_store).toBeUndefined();+ expect(contained!.derived_store_unreadable).toBe(true);+ });++ test("an unregistered exclusion reason is contained to the field, not the record", () => {+ writeSidecarWithStore("unknown-reason", { ...EXCLUDED, exclusion_reason: "ran-out-of-disk" });+ const contained = readManifestSidecar(vault, "unknown-reason");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.derived_store).toBeUndefined();+ expect(contained!.derived_store_unreadable).toBe(true);+ });++ test("inclusion without a digest is contained to the field, not the record", () => {+ // Not a weaker record - a false one. Nothing could verify the+ // archive it claims to have written.+ writeSidecarWithStore("no-digest", { ...INCLUDED, archive_sha256: null });+ const contained = readManifestSidecar(vault, "no-digest");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.derived_store).toBeUndefined();+ expect(contained!.derived_store_unreadable).toBe(true);+ });++ test("inclusion that also names an exclusion reason is contained to the field, not the record", () => {+ writeSidecarWithStore("both", {+ ...INCLUDED,+ exclusion_reason: SNAPSHOT_STORE_EXCLUSION.absent,+ });+ const contained = readManifestSidecar(vault, "both");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.derived_store).toBeUndefined();+ expect(contained!.derived_store_unreadable).toBe(true);+ });++ test("an exclusion that names no reason is contained to the field, not the record", () => {+ writeSidecarWithStore("reasonless", { ...EXCLUDED, exclusion_reason: null });+ const contained = readManifestSidecar(vault, "reasonless");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.derived_store).toBeUndefined();+ expect(contained!.derived_store_unreadable).toBe(true);+ });+});++/**+ * U7: the snapshot-reason field on the sidecar.+ *+ * Additive at the existing schema version for the same reason the+ * derived-store field is, and validated through the same closed guard.+ * The load-bearing negative is the last case here: the reason is also a+ * run-id PREFIX at every call site that writes one, so guessing it from+ * the run id would look right in almost every test and would manufacture+ * provenance for a hand-named archive the code never stamped.+ */+describe("the snapshot-reason field on the sidecar", () => {+ /** A sidecar carrying `snapshot_reason` verbatim, written to disk. */+ function writeSidecarWithReason(runId: string, reason: unknown): void {+ writeFileSync(+ manifestSidecarPath(vault, runId),+ JSON.stringify({+ schema_version: 1,+ generated_at: "2026-05-18T00:00:00Z",+ brain_root: "Brain",+ files: {},+ snapshot_reason: reason,+ }),+ );+ }++ test("buildManifest stamps the reason it was given", () => {+ const m = buildManifest(brain, { snapshotReason: BRAIN_SNAPSHOT_REASON.entityPrune });+ expect(m.snapshot_reason).toBe(BRAIN_SNAPSHOT_REASON.entityPrune);+ // Still the same schema version: an older peer ignores the key and+ // keeps its own drift detection, which is why it was not bumped.+ expect(m.schema_version).toBe(BRAIN_MANIFEST_SCHEMA_VERSION);+ });++ test("buildManifest omits the key entirely when given no reason", () => {+ const m = buildManifest(brain);+ expect("snapshot_reason" in m).toBe(false);+ });++ test("every registered reason roundtrips through the sidecar", () => {+ for (const reason of BRAIN_SNAPSHOT_REASONS) {+ writeSidecarWithReason(`roundtrip-${reason}`, reason);+ expect(readManifestSidecar(vault, `roundtrip-${reason}`)?.snapshot_reason).toBe(reason);+ }+ });++ test("a sidecar written before the feature reads as no reason at all", () => {+ writeFileSync(+ manifestSidecarPath(vault, "dream-2026-05-18-070000"),+ JSON.stringify({+ schema_version: 1,+ generated_at: "2026-05-18T00:00:00Z",+ brain_root: "Brain",+ files: {},+ }),+ );+ const back = readManifestSidecar(vault, "dream-2026-05-18-070000");+ expect(back).not.toBeNull();+ // The run id begins with a registered reason. It is NOT read back as+ // one: the archive does not carry that provenance, and inventing it+ // would make an unstamped snapshot indistinguishable from a stamped+ // one.+ expect(back!.snapshot_reason).toBeUndefined();+ });++ test("an unregistered reason is contained to the field, not the record", () => {+ writeSidecarWithReason("bogus", "spring-cleaning");+ const contained = readManifestSidecar(vault, "bogus");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.snapshot_reason).toBeUndefined();+ expect(contained!.snapshot_reason_unreadable).toBe(true);+ });++ test("an explicit null reason is contained to the field, not the record", () => {+ // Absence is spelled by omitting the key. A null is a present field+ // that names nothing, which no writer here produces.+ writeSidecarWithReason("null-reason", null);+ const contained = readManifestSidecar(vault, "null-reason");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.snapshot_reason).toBeUndefined();+ expect(contained!.snapshot_reason_unreadable).toBe(true);+ });++ test("a non-string reason is contained to the field, not the record", () => {+ writeSidecarWithReason("numeric", 3);+ const contained = readManifestSidecar(vault, "numeric");+ // Drift detection runs on the mandatory part, so an unreadable+ // optional field must not take it down: discarding the record+ // here reports no sidecar at all and skips the gate, which is+ // the silent-overwrite path this field was added beside.+ expect(contained).not.toBeNull();+ expect(contained!.generated_at).toBe("2026-05-18T00:00:00Z");+ expect(contained!.snapshot_reason).toBeUndefined();+ expect(contained!.snapshot_reason_unreadable).toBe(true);+ });++ test("write then read roundtrip preserves the reason", () => {+ writeFileSync(join(brain, "_brain.yaml"), "schema_version: 1\n");+ const original = buildManifest(brain, { snapshotReason: BRAIN_SNAPSHOT_REASON.manual });+ writeManifestSidecar(vault, "reason-rt", original);+ expect(readManifestSidecar(vault, "reason-rt")!.snapshot_reason).toBe(+ BRAIN_SNAPSHOT_REASON.manual,+ );+ });+});diff --git a/tests/core/brain/negative-recall.test.ts b/tests/core/brain/negative-recall.test.tsnew file mode 100644index 00000000..ec2b2421--- /dev/null+++ b/tests/core/brain/negative-recall.test.ts@@ -0,0 +1,485 @@+/**+ * U2 - typed negative recall with a digest-bound coverage receipt.+ *+ * Every case here is an assertion that one kind of "no" is told apart+ * from another kind of "no". The module under test is pure, so each+ * scenario is a literal index snapshot plus a literal scope; the wiring+ * into `brain_recall_gate` is covered by the MCP tests.+ */++import { describe, expect, test } from "bun:test";++import type { ClaimNode } from "../../../src/core/brain/claim-graph.ts";+import {+ buildCoverageReceipt,+ classifyNegativeRecall,+ COVERAGE_DIGEST_FIELDS,+ isNegativeRecallState,+ isNegativeRecallUnknownReason,+ isRetractionEvidenceKind,+ NEGATIVE_RECALL_STATE,+ NEGATIVE_RECALL_UNKNOWN_REASON,+ NegativeRecallError,+ RETRACTION_EVIDENCE_KIND,+ retractionEvidenceFromClaim,+ type CoverageIndexSnapshot,+ type CoverageScope,+} from "../../../src/core/brain/negative-recall.ts";++const INDEXED_AT = "2026-08-01T00:00:00.000Z";++/**+ * Receipt fields that are deliberately outside the digest: the digest+ * itself, and the gap the digest is explicitly not taken over.+ */+const NON_DIGESTED_RECEIPT_FIELDS = Object.freeze(["digest", "unindexed_roots"] as const);++/** The digest of `snapshot()` under `scope()`, pinned against drift. */+const KNOWN_ANSWER_DIGEST = "c9096179d5a00561535e96af00eca957b4e9c5e16aa3bd302da5c21087c02f01";++function snapshot(overrides: Partial<CoverageIndexSnapshot> = {}): CoverageIndexSnapshot {+ return {+ indexPath: "/vault/.o2b/search.sqlite",+ exists: true,+ schemaVersion: 12,+ documents: 42,+ chunks: 311,+ embeddings: 311,+ embeddingSignature: "openai:text-embedding-3-small:1536",+ lastIndexedAt: INDEXED_AT,+ staleEmbeddings: 0,+ ...overrides,+ };+}++function scope(overrides: Partial<CoverageScope> = {}): CoverageScope {+ return { authorizedRoots: ["notes"], indexedRoots: ["notes"], ...overrides };+}++function claim(overrides: Partial<ClaimNode> = {}): ClaimNode {+ return {+ id: "pref-coolant",+ path: "Brain/preferences/pref-coolant.md",+ topic: "coolant",+ principle: "principle text",+ valid_from: "2026-01-01T00:00:00.000Z",+ valid_until: null,+ superseded_by: null,+ contradicts: [],+ provenance: null,+ tombstoned: false,+ ...overrides,+ };+}++describe("coverage receipt", () => {+ test("is deterministic over a fixed snapshot and scope", () => {+ const a = buildCoverageReceipt(snapshot(), scope());+ const b = buildCoverageReceipt(snapshot(), scope());+ expect(a.digest).toBe(b.digest);+ expect(a.digest).toMatch(/^[0-9a-f]{64}$/);+ expect(a).toEqual(b);+ });++ test("carries the searched facts verbatim", () => {+ const receipt = buildCoverageReceipt(snapshot(), scope());+ expect(receipt.documents).toBe(42);+ expect(receipt.chunks).toBe(311);+ expect(receipt.index_path).toBe("/vault/.o2b/search.sqlite");+ expect(receipt.schema_version).toBe(12);+ expect(receipt.embedding_signature).toBe("openai:text-embedding-3-small:1536");+ expect(receipt.last_indexed_at).toBe(INDEXED_AT);+ expect(receipt.scope).toEqual(["notes"]);+ expect(receipt.unindexed_roots).toEqual([]);+ });++ test("the digest moves when the document count moves", () => {+ const before = buildCoverageReceipt(snapshot(), scope()).digest;+ const after = buildCoverageReceipt(snapshot({ documents: 43 }), scope()).digest;+ expect(after).not.toBe(before);+ });++ test("the digest moves when the chunk count moves", () => {+ const before = buildCoverageReceipt(snapshot(), scope()).digest;+ const after = buildCoverageReceipt(snapshot({ chunks: 312 }), scope()).digest;+ expect(after).not.toBe(before);+ });++ test("the digest moves when the embedding signature moves", () => {+ const before = buildCoverageReceipt(snapshot(), scope()).digest;+ const after = buildCoverageReceipt(+ snapshot({ embeddingSignature: "openai:text-embedding-3-large:3072" }),+ scope(),+ ).digest;+ expect(after).not.toBe(before);+ });++ test("the digest moves when the searched scope moves", () => {+ const before = buildCoverageReceipt(snapshot(), scope()).digest;+ const after = buildCoverageReceipt(+ snapshot(),+ scope({ authorizedRoots: ["notes", "journal"], indexedRoots: ["notes", "journal"] }),+ ).digest;+ expect(after).not.toBe(before);+ });++ test("the digest is stable under root ordering", () => {+ const one = buildCoverageReceipt(+ snapshot(),+ scope({ authorizedRoots: ["notes", "journal"], indexedRoots: ["notes", "journal"] }),+ );+ const other = buildCoverageReceipt(+ snapshot(),+ scope({ authorizedRoots: ["journal", "notes"], indexedRoots: ["journal", "notes"] }),+ );+ expect(other.digest).toBe(one.digest);+ });++ test("building over a non-existent index throws rather than digesting zeroes", () => {+ expect(() => buildCoverageReceipt(snapshot({ exists: false }), scope())).toThrow(+ NegativeRecallError,+ );+ });++ test("carries the embedding census, so a keyword-only index is visible", () => {+ const receipt = buildCoverageReceipt(snapshot({ embeddings: 0 }), scope());+ expect(receipt.embeddings).toBe(0);+ expect(receipt.chunks).toBe(311);+ });++ test("the digest moves when the embedding census moves", () => {+ const before = buildCoverageReceipt(snapshot(), scope()).digest;+ const after = buildCoverageReceipt(snapshot({ embeddings: 0 }), scope()).digest;+ expect(after).not.toBe(before);+ });++ test("every digested field is named in the ordered field tuple", () => {+ // The tuple IS the encoding, so the assertion has to be made against+ // the RECEIPT rather than against a second copy of the tuple: a field+ // added to the receipt and forgotten in the tuple is exactly the+ // mistake this case exists to catch, and comparing the tuple to a+ // literal transcription of itself cannot catch it.+ const receipt = buildCoverageReceipt(snapshot(), scope());+ const digestable = Object.keys(receipt)+ .filter((key) => !(NON_DIGESTED_RECEIPT_FIELDS as ReadonlyArray<string>).includes(key))+ .toSorted();+ expect(digestable).toEqual([...COVERAGE_DIGEST_FIELDS].toSorted());+ });++ test("the digest is a known answer over a fixed snapshot and scope", () => {+ // Order inside the tuple is load-bearing and no membership assertion+ // can see it, so one frozen hex pins the encoding end to end. A+ // deliberate field or ordering change updates this literal; an+ // accidental one fails here.+ expect(buildCoverageReceipt(snapshot(), scope()).digest).toBe(KNOWN_ANSWER_DIGEST);+ });+});++describe("classifyNegativeRecall", () => {+ test("zero results over a healthy index is a complete not_found with a digest", () => {+ const verdict = classifyNegativeRecall({ snapshot: snapshot(), scope: scope() });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.notFound);+ expect(verdict.complete).toBe(true);+ expect(verdict.unknown_reason).toBeUndefined();+ expect(verdict.coverage?.digest).toMatch(/^[0-9a-f]{64}$/);+ });++ test("no index at all is unknown / index-absent with no coverage", () => {+ const verdict = classifyNegativeRecall({+ snapshot: snapshot({ exists: false }),+ scope: scope(),+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.unknown);+ expect(verdict.complete).toBe(false);+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.indexAbsent);+ expect(verdict.coverage).toBeUndefined();+ });++ test("unreadable index facts are unknown / coverage-unavailable, never not_found", () => {+ const verdict = classifyNegativeRecall({ snapshot: null, scope: scope() });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.unknown);+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.coverageUnavailable);+ expect(verdict.coverage).toBeUndefined();+ });++ test("stale embeddings are unknown / index-stale with the receipt still attached", () => {+ const verdict = classifyNegativeRecall({+ snapshot: snapshot({ staleEmbeddings: 7 }),+ scope: scope(),+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.unknown);+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.indexStale);+ expect(verdict.coverage?.documents).toBe(42);+ expect(verdict.reason).toContain("7");+ });++ test("an index that never recorded a run is unknown / index-stale", () => {+ const verdict = classifyNegativeRecall({+ snapshot: snapshot({ lastIndexedAt: null }),+ scope: scope(),+ });+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.indexStale);+ });++ test("an index instant the store cannot date is unknown / index-instant-unusable", () => {+ // The value is a raw SQLite text cell, so a corrupt one is a fact+ // about the store rather than a caller error - but no comparison+ // against it can succeed, so nothing downstream may be claimed.+ const verdict = classifyNegativeRecall({+ snapshot: snapshot({ lastIndexedAt: "whenever-o-clock" }),+ scope: scope(),+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.unknown);+ expect(verdict.complete).toBe(false);+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.indexInstantUnusable);+ expect(verdict.coverage?.last_indexed_at).toBe("whenever-o-clock");+ });++ test("an index whose recorded model never finished embedding is unknown", () => {+ // A model IS recorded here, so its run is unfinished: part of the+ // corpus is reachable by keyword and part both ways, and no negative+ // over a half-converted index is well-founded. `staleEmbeddings`+ // cannot tell this apart - a chunk with no embedding row at all is+ // never counted stale.+ const verdict = classifyNegativeRecall({+ snapshot: snapshot({ embeddings: 0, staleEmbeddings: 0 }),+ scope: scope(),+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.unknown);+ expect(verdict.complete).toBe(false);+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.embeddingsIncomplete);+ expect(verdict.coverage?.embeddings).toBe(0);+ expect(verdict.reason).toContain("311");+ });++ test("a partially embedded index is unknown too, not a complete not_found", () => {+ const verdict = classifyNegativeRecall({+ snapshot: snapshot({ embeddings: 310 }),+ scope: scope(),+ });+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.embeddingsIncomplete);+ });++ test("a vault that never configured a model still receives a not_found", () => {+ // Running without embeddings is a supported configuration, not an+ // unfinished job: semantic search needs a key an operator may not+ // have. Refusing it would leave such a vault permanently unable to+ // receive this module's main answer, which is how a verdict stops+ // being read.+ const verdict = classifyNegativeRecall({+ snapshot: snapshot({ embeddings: 0, staleEmbeddings: 0, embeddingSignature: null }),+ scope: scope(),+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.notFound);+ expect(verdict.complete).toBe(true);+ });++ test("the keyword-only negative is visible in the receipt rather than implied", () => {+ // The narrower claim is not hidden by admitting it: the vector count+ // and the absent signature are both on the receipt and both inside the+ // digest, so a consumer can tell a keyword-only negative from a fully+ // embedded one and the digest moves when that changes.+ const keywordOnly = classifyNegativeRecall({+ snapshot: snapshot({ embeddings: 0, staleEmbeddings: 0, embeddingSignature: null }),+ scope: scope(),+ });+ expect(keywordOnly.coverage?.embeddings).toBe(0);+ expect(keywordOnly.coverage?.embedding_signature).toBeNull();++ const fullyEmbedded = classifyNegativeRecall({+ snapshot: snapshot({ embeddings: 311, staleEmbeddings: 0 }),+ scope: scope(),+ });+ expect(fullyEmbedded.state).toBe(NEGATIVE_RECALL_STATE.notFound);+ expect(fullyEmbedded.coverage?.digest).not.toBe(keywordOnly.coverage?.digest);+ });++ test("a configured root the index does not cover is unknown / coverage-divergent", () => {+ const verdict = classifyNegativeRecall({+ snapshot: snapshot(),+ scope: scope({ authorizedRoots: ["notes", "journal"], indexedRoots: ["notes"] }),+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.unknown);+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.coverageDivergent);+ expect(verdict.coverage?.unindexed_roots).toEqual(["journal"]);+ expect(verdict.coverage?.scope).toEqual(["notes"]);+ expect(verdict.reason).toContain("journal");+ });++ test("an empty authorized set is not a divergence", () => {+ // `notes.read_paths` defaults to empty: the operator has authorized+ // no note folders, so there is no root the index can fail to cover.+ const verdict = classifyNegativeRecall({+ snapshot: snapshot(),+ scope: scope({ authorizedRoots: [], indexedRoots: [] }),+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.notFound);+ expect(verdict.coverage?.scope).toEqual([]);+ });+});++describe("did_not_happen is grounded, never inferred", () => {+ const evidence = {+ subject: "pref-coolant",+ kind: RETRACTION_EVIDENCE_KIND.tombstone,+ recorded_at: "2026-07-01T00:00:00.000Z",+ } as const;++ test("asserting it with no evidence at all throws", () => {+ expect(() =>+ classifyNegativeRecall({+ snapshot: snapshot(),+ scope: scope(),+ assertDidNotHappen: true,+ }),+ ).toThrow(NegativeRecallError);+ });++ test("the refusal message names the outcome dropping the assertion really gives", () => {+ // The thrown message is advice a caller acts on, so it has to name the+ // state the advised input actually produces - see the `not_found`+ // assertion below, which is that same input.+ let message = "";+ try {+ classifyNegativeRecall({ snapshot: snapshot(), scope: scope(), assertDidNotHappen: true });+ } catch (e) {+ message = e instanceof Error ? e.message : "";+ }+ expect(message).toContain(NEGATIVE_RECALL_STATE.notFound);+ expect(message).not.toContain(NEGATIVE_RECALL_STATE.unknown);+ const advised = classifyNegativeRecall({ snapshot: snapshot(), scope: scope() });+ expect(advised.state).toBe(NEGATIVE_RECALL_STATE.notFound);+ });++ test("evidence without the assertion is context, never an escalation", () => {+ // A caller that hands over retraction evidence while merely asking+ // what the corpus supports has claimed nothing, so it must not be+ // handed the strongest state in the vocabulary.+ const verdict = classifyNegativeRecall({+ snapshot: snapshot(),+ scope: scope(),+ retraction: evidence,+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.notFound);+ expect(verdict.complete).toBe(true);+ });++ test("an unusable index instant never yields a complete negative", () => {+ // The reviewer's reproduction: `Date.parse` of a corrupt cell is NaN,+ // and every comparison against NaN is false, so an unguarded+ // fall-through admitted the strongest claim in the module over an+ // index nobody could date.+ const verdict = classifyNegativeRecall({+ snapshot: snapshot({ lastIndexedAt: "whenever-o-clock" }),+ scope: scope(),+ retraction: evidence,+ assertDidNotHappen: true,+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.unknown);+ expect(verdict.complete).toBe(false);+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.indexInstantUnusable);+ });++ test("a tombstoned claim carrying an instant gives did_not_happen with coverage", () => {+ const retraction = retractionEvidenceFromClaim(+ claim({ tombstoned: true, valid_until: "2026-07-01T00:00:00.000Z" }),+ );+ expect(retraction?.kind).toBe(RETRACTION_EVIDENCE_KIND.tombstone);+ const verdict = classifyNegativeRecall({+ snapshot: snapshot(),+ scope: scope(),+ retraction,+ assertDidNotHappen: true,+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.didNotHappen);+ expect(verdict.complete).toBe(true);+ expect(verdict.coverage?.digest).toMatch(/^[0-9a-f]{64}$/);+ });++ test("a superseded claim gives did_not_happen and names the successor edge", () => {+ const retraction = retractionEvidenceFromClaim(+ claim({+ tombstoned: true,+ superseded_by: "pref-coolant-v2",+ valid_until: "2026-07-02T00:00:00.000Z",+ }),+ );+ expect(retraction?.kind).toBe(RETRACTION_EVIDENCE_KIND.supersededBy);+ expect(retraction?.replaced_by).toBe("pref-coolant-v2");+ const verdict = classifyNegativeRecall({+ snapshot: snapshot(),+ scope: scope(),+ retraction,+ assertDidNotHappen: true,+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.didNotHappen);+ });++ test("a claim closed by valid_until alone is evidence too", () => {+ const retraction = retractionEvidenceFromClaim(+ claim({ valid_until: "2026-06-01T00:00:00.000Z" }),+ );+ expect(retraction?.kind).toBe(RETRACTION_EVIDENCE_KIND.validUntil);+ });++ test("a live claim yields no evidence", () => {+ expect(retractionEvidenceFromClaim(claim())).toBeNull();+ });++ test("a tombstone with no comparable instant yields no evidence", () => {+ // `ClaimNode` projects `tombstoned` as a boolean and does NOT carry+ // `tombstoned_at`, so a tombstone with no `valid_until` exposes no+ // instant to compare against the receipt. That is `unknown`, not a+ // fabricated non-occurrence.+ expect(retractionEvidenceFromClaim(claim({ tombstoned: true }))).toBeNull();+ });++ test("evidence with no coverage degrades to unknown rather than throwing", () => {+ const verdict = classifyNegativeRecall({+ snapshot: snapshot({ exists: false }),+ scope: scope(),+ retraction: evidence,+ assertDidNotHappen: true,+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.unknown);+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.indexAbsent);+ });++ test("a retraction newer than the index the search ran over is unknown / index-stale", () => {+ const verdict = classifyNegativeRecall({+ snapshot: snapshot(),+ scope: scope(),+ retraction: { ...evidence, recorded_at: "2026-09-01T00:00:00.000Z" },+ });+ expect(verdict.state).toBe(NEGATIVE_RECALL_STATE.unknown);+ expect(verdict.unknown_reason).toBe(NEGATIVE_RECALL_UNKNOWN_REASON.indexStale);+ });++ test("evidence carrying an unusable instant is a programming error", () => {+ expect(() =>+ classifyNegativeRecall({+ snapshot: snapshot(),+ scope: scope(),+ retraction: { ...evidence, recorded_at: "not-an-instant" },+ }),+ ).toThrow(NegativeRecallError);+ });+});++describe("vocabulary guards", () => {+ test("the state guard accepts members and rejects a near miss", () => {+ expect(isNegativeRecallState(NEGATIVE_RECALL_STATE.didNotHappen)).toBe(true);+ expect(isNegativeRecallState("did-not-happen")).toBe(false);+ expect(isNegativeRecallState(null)).toBe(false);+ });++ test("the unknown-reason guard accepts members and rejects a near miss", () => {+ expect(isNegativeRecallUnknownReason(NEGATIVE_RECALL_UNKNOWN_REASON.indexStale)).toBe(true);+ expect(isNegativeRecallUnknownReason("index_stale")).toBe(false);+ });++ test("the evidence-kind guard accepts members and rejects a near miss", () => {+ expect(isRetractionEvidenceKind(RETRACTION_EVIDENCE_KIND.supersededBy)).toBe(true);+ expect(isRetractionEvidenceKind("superseded")).toBe(false);+ });+});diff --git a/tests/core/brain/policy-active.test.ts b/tests/core/brain/policy-active.test.tsindex bd9c17b7..37ec4662 100644--- a/tests/core/brain/policy-active.test.ts+++ b/tests/core/brain/policy-active.test.ts@@ -116,3 +116,41 @@ describe("active.inject_budget_chars (token-diet, t_40eb1de7)", () => {);});});++describe("active.standing_rules_max_chars (silence-is-not-an-answer, U8)", () => {+ test("absent โ undefined; the reader falls back to its own default", () => {+ const { config } = validate(HEAD + `active:\n inject_budget_chars: 4000\n`);+ expect(config.active?.standing_rules_max_chars).toBeUndefined();+ });++ test("present โ loaded, and independent of the injection budget", () => {+ const { config } = validate(+ HEAD + `active:\n inject_budget_chars: 500\n standing_rules_max_chars: 12000\n`,+ );+ expect(config.active?.standing_rules_max_chars).toBe(12_000);+ expect(config.active?.inject_budget_chars).toBe(500);+ });++ test("below minimum rejected", () => {+ expect(() => validate(HEAD + `active:\n standing_rules_max_chars: 10\n`)).toThrow(+ BrainConfigError,+ );+ });++ test("above maximum rejected", () => {+ expect(() => validate(HEAD + `active:\n standing_rules_max_chars: 1000000\n`)).toThrow(+ BrainConfigError,+ );+ });++ test("non-integer rejected", () => {+ expect(() => validate(HEAD + `active:\n standing_rules_max_chars: lots\n`)).toThrow(+ BrainConfigError,+ );+ });++ test("the key is known: it does not warn as unrecognised", () => {+ const { warnings } = validate(HEAD + `active:\n standing_rules_max_chars: 4000\n`);+ expect(warnings.find((w) => w.message.includes("standing_rules_max_chars"))).toBeUndefined();+ });+});diff --git a/tests/core/brain/policy-safe-loaders.test.ts b/tests/core/brain/policy-safe-loaders.test.tsindex 73e36019..062aa69c 100644--- a/tests/core/brain/policy-safe-loaders.test.ts+++ b/tests/core/brain/policy-safe-loaders.test.ts@@ -38,6 +38,7 @@ import {loadGuardrailsConfigSafe,loadIntegrityConfigSafe,loadNotesConfigSafe,+ loadSnapshotDerivedStorePolicySafe,loadSnapshotRetentionSafe,loadTemporalConfigSafe,} from "../../../src/core/brain/policy.ts";@@ -82,6 +83,17 @@ const SAFE_LOADERS = [load: loadActiveMostAppliedSafe as (vault: string) => unknown,absentValue: BRAIN_MOST_APPLIED_DEFAULTS as unknown,},+ {+ // Coverage is what an operator turned ON, so answering `false` from+ // the defaults on a config that merely has a typo would silently+ // strip the derived store out of every recovery point.+ name: "loadSnapshotDerivedStorePolicySafe",+ load: loadSnapshotDerivedStorePolicySafe as (vault: string) => unknown,+ absentValue: {+ include: DEFAULT_BRAIN_CONFIG.snapshots.include_derived_store,+ maxBytes: DEFAULT_BRAIN_CONFIG.snapshots.derived_store_max_bytes,+ } as unknown,+ },] as const;// ----- Reverse census: the table must account for every reader ---------------diff --git a/tests/core/brain/research/external-fetch.test.ts b/tests/core/brain/research/external-fetch.test.tsindex 27fc2e2a..d0323312 100644--- a/tests/core/brain/research/external-fetch.test.ts+++ b/tests/core/brain/research/external-fetch.test.ts@@ -167,6 +167,26 @@ describe("keyedFetch cache", () => {expect(a).toBe(b);});+ test("the body is keyed by the shared canonical encoding, sorted and undefined-free", () => {+ // This module used to carry its own sorted-key stringifier. The shared+ // one differs in exactly one place - an object entry whose value is+ // `undefined` is omitted rather than rendered as null - and omitting it+ // is what the body actually sent does, so two requests that go out as+ // identical bytes now share one cache entry instead of two.+ const withUndefined = normalizeRequestKey({+ url: "https://x/y",+ method: "POST",+ body: { b: 2, a: 1, absent: undefined },+ });+ const without = normalizeRequestKey({+ url: "https://x/y",+ method: "POST",+ body: { a: 1, b: 2 },+ });+ expect(withUndefined).toBe(without);+ expect(withUndefined).toContain('{"a":1,"b":2}');+ });+test("the accept type is part of the cache key so json and text never collide", () => {const base = { url: "https://x/y", query: { q: "z" } } as const;const asJson = normalizeRequestKey({ ...base, accept: "json" });diff --git a/tests/core/brain/schema-integrity.test.ts b/tests/core/brain/schema-integrity.test.tsnew file mode 100644index 00000000..ac57d03a--- /dev/null+++ b/tests/core/brain/schema-integrity.test.ts@@ -0,0 +1,304 @@+import { afterEach, beforeEach, describe, 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 {+ buildSchemaSyncResult,+ getActiveSchemaPack,+ listSchemaPacks,+ SchemaSyncUnavailableError,+} from "../../../src/core/brain/schema-admin.ts";+import {+ assessSchemaPackIntegrity,+ computeSchemaPackDigest,+ isSchemaPackIntegrityStatus,+ isSchemaPackUnverifiedReason,+ readRecordedSchemaPackDigest,+ SCHEMA_MUTATION_AUDIT_DIR,+ SCHEMA_PACK_DIGEST_FIELD,+ SCHEMA_PACK_INTEGRITY,+ SCHEMA_PACK_INTEGRITY_STATUSES,+ SCHEMA_PACK_UNVERIFIED_REASON,+ SCHEMA_PACK_UNVERIFIED_REASONS,+} from "../../../src/core/brain/schema-integrity.ts";+import { applySchemaMutations } from "../../../src/core/brain/schema-mutate.ts";+import { parseSchemaPack, readSchemaPackSource } from "../../../src/core/brain/schema-pack.ts";++let vault: string;++const CONFIG_LINES: ReadonlyArray<string> = Object.freeze([+ "schema_version: 1",+ "primary_agent: tester",+ "schema:",+ " preference_types: [research]",+ " signal_types: [observation]",+ " page_types: [paper]",+ " log_event_kinds: [milestone]",+]);++function configPath(): string {+ return join(vault, "Brain", "_brain.yaml");+}++function auditDir(): string {+ return join(vault, "Brain", "log", SCHEMA_MUTATION_AUDIT_DIR);+}++function readConfig(): string {+ return readFileSync(configPath(), "utf8");+}++function writeConfig(text: string): void {+ writeFileSync(configPath(), text, "utf8");+}++/** Apply one harmless mutation so the vault carries a recorded expectation. */+async function seal(): Promise<void> {+ await applySchemaMutations(vault, [{ op: "add_link_type", token: "supports" }], {+ actor: "tester",+ });+}++/** The single audit shard the seal above wrote. */+function soleShardPath(): string {+ const entries = readdirSync(auditDir());+ expect(entries).toHaveLength(1);+ return join(auditDir(), entries[0]!);+}++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-schema-integrity-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeConfig(CONFIG_LINES.join("\n") + "\n");+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++describe("schema pack integrity vocabularies", () => {+ test("every status and reason is a member of its own list", () => {+ for (const status of Object.values(SCHEMA_PACK_INTEGRITY)) {+ expect(SCHEMA_PACK_INTEGRITY_STATUSES).toContain(status);+ expect(isSchemaPackIntegrityStatus(status)).toBe(true);+ }+ for (const reason of Object.values(SCHEMA_PACK_UNVERIFIED_REASON)) {+ expect(SCHEMA_PACK_UNVERIFIED_REASONS).toContain(reason);+ expect(isSchemaPackUnverifiedReason(reason)).toBe(true);+ }+ });+});++describe("computeSchemaPackDigest", () => {+ test("is deterministic across two independent parses of the same text", () => {+ const text = readConfig();+ expect(computeSchemaPackDigest(parseSchemaPack(text))).toBe(+ computeSchemaPackDigest(parseSchemaPack(text)),+ );+ });++ test("moves when the ontology moves and not when the surrounding file churns", () => {+ const base = computeSchemaPackDigest(parseSchemaPack(readConfig()));++ // Comment and blank-line churn outside the schema block: same ontology.+ writeConfig(`# operator note\n\n${CONFIG_LINES.join("\n")}\n\n`);+ expect(computeSchemaPackDigest(parseSchemaPack(readConfig()))).toBe(base);++ // One declared token more: a different ontology.+ writeConfig(CONFIG_LINES.join("\n").replace("[research]", "[research, decision]") + "\n");+ expect(computeSchemaPackDigest(parseSchemaPack(readConfig()))).not.toBe(base);+ });+});++describe("assessSchemaPackIntegrity", () => {+ test("apply then read reports ok with no mismatches", async () => {+ await seal();++ const integrity = assessSchemaPackIntegrity(vault);++ expect(integrity.status).toBe(SCHEMA_PACK_INTEGRITY.ok);+ expect(integrity.mismatches).toEqual([]);+ expect(integrity.unverified_reason).toBeUndefined();+ expect(integrity.digest).not.toBeNull();+ expect(integrity.expected).toBe(integrity.digest!);+ expect(typeof integrity.recorded_at).toBe("string");+ expect(integrity.audit_path).toBe(soleShardPath());+ });++ test("the apply result carries the digest that was recorded", async () => {+ const applied = await applySchemaMutations(+ vault,+ [{ op: "add_link_type", token: "supports" }],+ { actor: "tester" },+ );++ expect(applied.pack_digest).toBe(computeSchemaPackDigest(applied.pack));+ expect(assessSchemaPackIntegrity(vault).digest).toBe(applied.pack_digest);+ });++ test("a hand-edited schema block reports modified with both sides populated", async () => {+ await seal();+ const sealed = assessSchemaPackIntegrity(vault).digest;+ writeConfig(readConfig().replace(" - supports", " - supports\n - refutes"));++ const integrity = assessSchemaPackIntegrity(vault);++ expect(integrity.status).toBe(SCHEMA_PACK_INTEGRITY.modified);+ expect(integrity.mismatches).toHaveLength(1);+ const [mismatch] = integrity.mismatches;+ expect(mismatch?.field).toBe(SCHEMA_PACK_DIGEST_FIELD);+ expect(mismatch?.expected).toBe(sealed);+ expect(mismatch?.actual).toBe(integrity.digest);+ expect(mismatch?.expected).not.toBe(mismatch?.actual);+ });++ test("editing an unrelated comment in the same file still reports ok", async () => {+ await seal();+ writeConfig(`# an operator comment that is not ontology\n${readConfig()}\n`);++ expect(assessSchemaPackIntegrity(vault).status).toBe(SCHEMA_PACK_INTEGRITY.ok);+ });++ test("a missing audit directory is unverified with no apply recorded, never ok", () => {+ const integrity = assessSchemaPackIntegrity(vault);++ expect(integrity.status).toBe(SCHEMA_PACK_INTEGRITY.unverified);+ expect(integrity.status).not.toBe(SCHEMA_PACK_INTEGRITY.ok);+ expect(integrity.unverified_reason).toBe(SCHEMA_PACK_UNVERIFIED_REASON.noApplyRecorded);+ expect(integrity.expected).toBeUndefined();+ expect(integrity.mismatches).toEqual([]);+ // The live digest is still reported: the pack is readable, the+ // expectation is what is missing.+ expect(typeof integrity.digest).toBe("string");+ });++ test("an audit directory holding no apply record is unverified, not ok", () => {+ mkdirSync(auditDir(), { recursive: true });+ writeFileSync(+ join(auditDir(), "2026-W01.jsonl"),+ JSON.stringify({+ timestamp: "2026-01-01T00:00:00.000Z",+ actor: "tester",+ action: "some_other_action",+ target: "Brain/_brain.yaml",+ ok: true,+ }) + "\n",+ "utf8",+ );++ const integrity = assessSchemaPackIntegrity(vault);++ expect(integrity.status).toBe(SCHEMA_PACK_INTEGRITY.unverified);+ expect(integrity.unverified_reason).toBe(SCHEMA_PACK_UNVERIFIED_REASON.noApplyRecorded);+ });++ test("an unparseable audit shard is unverified with the audit-unreadable reason", async () => {+ await seal();+ writeFileSync(soleShardPath(), "{not json at all\n", "utf8");++ const integrity = assessSchemaPackIntegrity(vault);++ expect(integrity.status).toBe(SCHEMA_PACK_INTEGRITY.unverified);+ expect(integrity.unverified_reason).toBe(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);+ });++ test("an apply record carrying no digest is unverified, never ok", async () => {+ await seal();+ const shard = soleShardPath();+ const record = JSON.parse(readFileSync(shard, "utf8").trim()) as {+ details: Record<string, unknown>;+ };+ delete record.details[SCHEMA_PACK_DIGEST_FIELD];+ writeFileSync(shard, JSON.stringify(record) + "\n", "utf8");++ const integrity = assessSchemaPackIntegrity(vault);++ expect(integrity.status).toBe(SCHEMA_PACK_INTEGRITY.unverified);+ expect(integrity.unverified_reason).toBe(SCHEMA_PACK_UNVERIFIED_REASON.auditUnreadable);+ });++ test("the newest apply record wins over an older one", async () => {+ await seal();+ const shard = soleShardPath();+ const sealed = JSON.parse(readFileSync(shard, "utf8").trim()) as {+ timestamp: string;+ details: Record<string, unknown>;+ };+ const stale = {+ ...sealed,+ timestamp: "2020-01-01T00:00:00.000Z",+ details: { ...sealed.details, [SCHEMA_PACK_DIGEST_FIELD]: "deadbeef" },+ };+ // The stale record is written LAST, so line order alone would pick it.+ writeFileSync(shard, `${JSON.stringify(sealed)}\n${JSON.stringify(stale)}\n`, "utf8");++ const recorded = readRecordedSchemaPackDigest(vault);++ expect(recorded.found).toBe(true);+ expect(recorded.found && recorded.recorded_at).toBe(sealed.timestamp);+ expect(assessSchemaPackIntegrity(vault).status).toBe(SCHEMA_PACK_INTEGRITY.ok);+ });++ test("a deleted config file is unverified with the config-absent reason", async () => {+ await seal();+ rmSync(configPath());++ const integrity = assessSchemaPackIntegrity(vault);++ expect(integrity.status).toBe(SCHEMA_PACK_INTEGRITY.unverified);+ expect(integrity.unverified_reason).toBe(SCHEMA_PACK_UNVERIFIED_REASON.configAbsent);+ // Nothing on disk to digest, and no digest is invented for it.+ expect(integrity.digest).toBeNull();+ expect(integrity.expected).toBeUndefined();+ expect(integrity.mismatches).toEqual([]);+ });+});++describe("readSchemaPackSource", () => {+ test("distinguishes an absent config from one that declares nothing", () => {+ const declared = readSchemaPackSource(vault);+ expect(declared.present).toBe(true);++ rmSync(configPath());+ const absent = readSchemaPackSource(vault);++ expect(absent.present).toBe(false);+ expect(absent.path).toBe(configPath());+ // The substituted default still parses to an empty pack, so callers+ // that legitimately want a default are unaffected.+ expect(absent.pack.declarations.preference_types).toBeUndefined();+ });+});++describe("schema read surfaces", () => {+ test("the active pack reports whether the path it names exists", async () => {+ await seal();++ const active = getActiveSchemaPack(vault);+ expect(active.exists).toBe(true);+ expect(active.integrity.status).toBe(SCHEMA_PACK_INTEGRITY.ok);++ rmSync(configPath());+ const gone = getActiveSchemaPack(vault);+ expect(gone.exists).toBe(false);+ expect(gone.integrity.unverified_reason).toBe(SCHEMA_PACK_UNVERIFIED_REASON.configAbsent);+ });++ test("every listed pack carries its own existence and integrity", async () => {+ await seal();++ const listed = listSchemaPacks(vault);++ expect(listed.packs).toHaveLength(1);+ expect(listed.packs[0]?.exists).toBe(true);+ expect(listed.packs[0]?.integrity.status).toBe(SCHEMA_PACK_INTEGRITY.ok);+ });+});++describe("buildSchemaSyncResult", () => {+ test("refuses instead of reporting a backfill it never performed", () => {+ expect(() => buildSchemaSyncResult(vault)).toThrow(SchemaSyncUnavailableError);+ expect(() => buildSchemaSyncResult(vault)).toThrow(/not implemented/);+ });+});diff --git a/tests/core/brain/schema-mutate.test.ts b/tests/core/brain/schema-mutate.test.tsindex e81b3736..bce12953 100644--- a/tests/core/brain/schema-mutate.test.ts+++ b/tests/core/brain/schema-mutate.test.ts@@ -12,6 +12,12 @@ import {import { tmpdir } from "node:os";import { join } from "node:path";+import {+ computeSchemaPackDigest,+ SCHEMA_MUTATION_AUDIT_ACTION,+ SCHEMA_MUTATION_AUDIT_DIR,+ SCHEMA_PACK_DIGEST_FIELD,+} from "../../../src/core/brain/schema-integrity.ts";import {applySchemaMutations,previewSchemaMutations,@@ -177,6 +183,38 @@ describe("applySchemaMutations", () => {expect(audit).toContain("***REDACTED***");expect(audit).not.toContain("secret-value");});++ test("records the resulting pack digest into the audit record it writes", async () => {+ const result = await applySchemaMutations(+ vault,+ [{ op: "add_type", category: "preference_types", token: "decision" }],+ { actor: "tester", now: new Date("2026-05-30T12:00:00.000Z") },+ );++ // The record said which mutations were requested and nothing about the+ // pack they produced, so no later read had an expectation to compare+ // the file against.+ const record = JSON.parse(readFileSync(result.audit_path, "utf8").trim()) as {+ action: string;+ details: Record<string, unknown>;+ };+ expect(record.action).toBe(SCHEMA_MUTATION_AUDIT_ACTION);+ expect(record.details[SCHEMA_PACK_DIGEST_FIELD]).toBe(result.pack_digest);+ expect(result.pack_digest).toBe(computeSchemaPackDigest(result.pack));+ expect(result.pack_digest).toBe(computeSchemaPackDigest(loadSchemaPack(vault)));+ });++ test("writes its audit shard under the shared audit-directory constant", async () => {+ const result = await applySchemaMutations(+ vault,+ [{ op: "add_type", category: "preference_types", token: "decision" }],+ { actor: "tester" },+ );++ expect(+ result.audit_path.startsWith(join(vault, "Brain", "log", SCHEMA_MUTATION_AUDIT_DIR)),+ ).toBe(true);+ });});describe("previewSchemaMutations", () => {diff --git a/tests/core/brain/snapshot-derived-store.test.ts b/tests/core/brain/snapshot-derived-store.test.tsnew file mode 100644index 00000000..b281b677--- /dev/null+++ b/tests/core/brain/snapshot-derived-store.test.ts@@ -0,0 +1,569 @@+/**+ * U6: derived-store coverage in the snapshot archive.+ *+ * The unit under test is a refusal discipline as much as a feature, so+ * the cases below are weighted towards what must NOT happen: no partial+ * archive after a refusal, no store touched by a restore that has no+ * record of one, no silent overwrite of an existing archive on a host+ * without zstd, and no `unknown` rendered as `excluded`.+ *+ * The fixture is a REAL index built by `indexVault` over a seeded vault,+ * through the same search-fixture helpers the search tests use. A+ * hand-written sqlite file would pass `PRAGMA quick_check` just as well,+ * but it would not exercise the writer lock the archiver takes on the+ * live store path, and that lock is the whole reason the copy is+ * consistent.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { Database } from "bun:sqlite";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ symlinkSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { execFileSync } from "node:child_process";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import {+ BrainSnapshotError,+ BrainSnapshotStoreError,+ createSnapshot,+ listSnapshots,+ pruneSnapshots,+ restoreSnapshot,+} from "../../../src/core/brain/snapshot.ts";+import {+ manifestSidecarPath,+ readManifestSidecar,+ SNAPSHOT_STORE_EXCLUSION,+} from "../../../src/core/brain/manifest.ts";+import { brainDirs, snapshotPath, snapshotStorePath } from "../../../src/core/brain/paths.ts";+import { BRAIN_SNAPSHOT_REASON } from "../../../src/core/brain/types.ts";+import { BRAIN_ARTIFACTS_DIR } from "../../../src/core/brain/path-constants.ts";+import { sha256Hex } from "../../../src/core/integrity/digest.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { resolveIndexPath } from "../../../src/core/search/paths.ts";+import { makeConfig } from "../../helpers/search-fixtures.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++let vault: string;+let configHome: string;+let configPath: string;++/** Coverage on, ceiling high enough that only the explicit cases trip it. */+const COVERED = { include: true, maxBytes: 1024 * 1024 * 1024 } as const;++/**+ * The reason every fixture here takes its snapshot for. `createSnapshot`+ * requires one; these cases are about derived-store coverage, and the+ * provenance axis is covered in `snapshot-reason.test.ts`.+ */+const DREAM = BRAIN_SNAPSHOT_REASON.dream;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-snap-store-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-snap-store-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });++ const dirs = brainDirs(vault);+ writeFileSync(+ join(dirs.preferences, "pref-foo.md"),+ "---\nkind: brain-preference\n---\n\n## Principle\n\nseed\n",+ );+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++/** Build a real derived store for `vault` and return its path. */+async function seedDerivedStore(): Promise<string> {+ const dbPath = resolveIndexPath(vault, null);+ const notes = join(vault, "Notes");+ mkdirSync(notes, { recursive: true });+ writeFileSync(+ join(notes, "seed.md"),+ "# Seed\n\nA paragraph long enough to be chunked and indexed by the walker.\n",+ );+ await indexVault(makeConfig({ vault, dbPath }));+ return dbPath;+}++describe("createSnapshot โ derived-store coverage off (the default)", () => {+ test("writes no store archive and records not-requested with a live size", async () => {+ const dbPath = await seedDerivedStore();+ const runId = "dream-store-off";++ const res = createSnapshot(vault, runId, { reason: DREAM });++ expect(existsSync(snapshotStorePath(vault, runId))).toBe(false);+ expect(res.derived_store.included).toBe(false);+ expect(res.derived_store.exclusion_reason).toBe(SNAPSHOT_STORE_EXCLUSION.not_requested);+ // The whole point of measuring it even when nothing is archived: an+ // operator who has never enabled coverage still sees the cost.+ expect(res.derived_store.live_size).toBe(statSync(dbPath).size);+ expect(res.derived_store.live_size).not.toBeNull();++ const manifest = readManifestSidecar(vault, runId);+ expect(manifest?.derived_store).toEqual(res.derived_store);+ });++ test("records a null live size when there is no store to measure", () => {+ const res = createSnapshot(vault, "dream-store-off-absent", { reason: DREAM });+ expect(res.derived_store.live_size).toBeNull();+ expect(res.derived_store.exclusion_reason).toBe(SNAPSHOT_STORE_EXCLUSION.not_requested);+ });+});++describe("createSnapshot โ derived-store coverage on", () => {+ test("writes the archive and the manifest digest matches its bytes", async () => {+ const dbPath = await seedDerivedStore();+ const runId = "dream-store-on";++ const res = createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });++ const archive = snapshotStorePath(vault, runId);+ expect(existsSync(archive)).toBe(true);+ expect(res.derived_store.included).toBe(true);+ expect(res.derived_store.exclusion_reason).toBeNull();+ expect(res.derived_store.source_path).toBe(dbPath);+ expect(res.derived_store.archive_sha256).toBe(sha256Hex(readFileSync(archive)));+ expect(res.derived_store.archive_size).toBe(statSync(archive).size);+ expect(res.derived_store.live_size).toBe(statSync(dbPath).size);++ const manifest = readManifestSidecar(vault, runId);+ expect(manifest?.derived_store).toEqual(res.derived_store);+ });++ test("the archive is a sibling of the tar, never a member of it", async () => {+ await seedDerivedStore();+ const runId = "dream-store-sibling";+ createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });++ const listing = execFileSync("tar", ["-tf", snapshotPath(vault, runId)], {+ encoding: "utf8",+ });+ // Every member starts at `Brain/`; the extractor and the restore+ // both depend on that being the only top-level name in the tar.+ for (const line of listing.split("\n").filter((l) => l.trim() !== "")) {+ expect(line.startsWith("Brain/")).toBe(true);+ }+ });++ test("refuses an absent store and leaves no tar behind", () => {+ const runId = "dream-store-absent";+ try {+ createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });+ throw new Error("expected a refusal");+ } catch (err) {+ expect(err).toBeInstanceOf(BrainSnapshotStoreError);+ expect((err as BrainSnapshotStoreError).reason).toBe(SNAPSHOT_STORE_EXCLUSION.absent);+ }+ expect(existsSync(snapshotPath(vault, runId))).toBe(false);+ expect(existsSync(snapshotStorePath(vault, runId))).toBe(false);+ expect(existsSync(manifestSidecarPath(vault, runId))).toBe(false);+ });++ test("refuses a condemned store and leaves no tar behind", async () => {+ const dbPath = await seedDerivedStore();+ // Not a SQLite database any more. `new Database` is lazy, so this is+ // caught by the integrity scanner rather than by the open.+ writeFileSync(dbPath, "this is not a database");++ const runId = "dream-store-faulted";+ try {+ createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });+ throw new Error("expected a refusal");+ } catch (err) {+ expect(err).toBeInstanceOf(BrainSnapshotStoreError);+ expect((err as BrainSnapshotStoreError).reason).toBe(+ SNAPSHOT_STORE_EXCLUSION.integrity_fault,+ );+ }+ expect(existsSync(snapshotPath(vault, runId))).toBe(false);+ expect(existsSync(snapshotStorePath(vault, runId))).toBe(false);+ });++ test("refuses a store over the ceiling, naming the measured size", async () => {+ const dbPath = await seedDerivedStore();+ const liveSize = statSync(dbPath).size;+ const runId = "dream-store-too-big";++ try {+ createSnapshot(vault, runId, { reason: DREAM, derivedStore: { include: true, maxBytes: 1 } });+ throw new Error("expected a refusal");+ } catch (err) {+ expect(err).toBeInstanceOf(BrainSnapshotStoreError);+ expect((err as BrainSnapshotStoreError).reason).toBe(+ SNAPSHOT_STORE_EXCLUSION.over_size_ceiling,+ );+ // The measured size, not a vague "too large": it is the number the+ // operator sets the ceiling against.+ expect((err as Error).message).toContain(String(liveSize));+ }+ expect(existsSync(snapshotPath(vault, runId))).toBe(false);+ expect(existsSync(snapshotStorePath(vault, runId))).toBe(false);+ });++ test("refuses an existing store archive rather than overwriting it", async () => {+ await seedDerivedStore();+ const runId = "dream-store-collide";+ createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });+ // Remove only the tar, so the second attempt reaches the store step+ // with the store archive already in place.+ rmSync(snapshotPath(vault, runId), { force: true });+ const archive = snapshotStorePath(vault, runId);+ const before = readFileSync(archive);++ expect(() => createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED })).toThrow(+ /refusing to overwrite/,+ );+ // And the refusal does not then clean up the file it refused to+ // overwrite. That archive belongs to another snapshot; removing it+ // while tidying after our own failure would reintroduce the+ // data-loss path through the back door.+ expect(readFileSync(archive).equals(before)).toBe(true);+ });+});++describe("listSnapshots and pruneSnapshots over a covered snapshot", () => {+ test("the listing carries the sidecar's derived-store record", async () => {+ await seedDerivedStore();+ createSnapshot(vault, "dream-list-covered", { reason: DREAM, derivedStore: COVERED });++ const [info] = listSnapshots(vault);+ expect(info?.derived_store?.included).toBe(true);+ expect(info?.store_archive_path).toBe(snapshotStorePath(vault, "dream-list-covered"));+ });++ test("a sidecar written before this feature renders as unknown, not excluded", () => {+ const runId = "dream-legacy-sidecar";+ createSnapshot(vault, runId, { reason: DREAM });+ // Exactly the shape a pre-feature peer wrote: schema version 1, no+ // derived-store key at all.+ const sidecar = manifestSidecarPath(vault, runId);+ const parsed = JSON.parse(readFileSync(sidecar, "utf8")) as Record<string, unknown>;+ delete parsed["derived_store"];+ writeFileSync(sidecar, JSON.stringify(parsed, null, 2) + "\n");++ const [info] = listSnapshots(vault);+ // `null` is UNKNOWN. An `excluded` record would claim a check ran.+ expect(info?.derived_store).toBeNull();+ expect(readManifestSidecar(vault, runId)).not.toBeNull();+ });++ test("retention removes the store archive alongside the tar and the sidecar", async () => {+ await seedDerivedStore();+ const old = "dream-prune-covered-old";+ const fresh = "dream-prune-covered-new";+ createSnapshot(vault, old, { reason: DREAM, derivedStore: COVERED });+ const t = new Date("2026-05-09T00:00:00Z");+ utimesSync(snapshotPath(vault, old), t, t);+ createSnapshot(vault, fresh, { reason: DREAM, derivedStore: COVERED });++ pruneSnapshots(vault, 1);++ expect(existsSync(snapshotPath(vault, old))).toBe(false);+ expect(existsSync(snapshotStorePath(vault, old))).toBe(false);+ expect(existsSync(manifestSidecarPath(vault, old))).toBe(false);+ expect(existsSync(snapshotStorePath(vault, fresh))).toBe(true);+ });++ test("a snapshot without a store archive still prunes cleanly", () => {+ const old = "dream-prune-bare-old";+ createSnapshot(vault, old, { reason: DREAM });+ const t = new Date("2026-05-09T00:00:00Z");+ utimesSync(snapshotPath(vault, old), t, t);+ createSnapshot(vault, "dream-prune-bare-new", { reason: DREAM });++ const res = pruneSnapshots(vault, 1);+ expect(res.deleted).toContain(snapshotPath(vault, old));+ expect(existsSync(snapshotPath(vault, old))).toBe(false);+ });+});++describe("restoreSnapshot โ the derived store", () => {+ test("a missing store archive refuses before the Brain tree is touched", async () => {+ // The store step used to run after the Markdown tree had been deleted+ // and re-copied, so this threw over work that had in fact completed:+ // the caller reported a failed rollback, logged nothing, and the vault+ // was rolled back anyway. Reachable whenever the sidecar survives+ // without its companion archive - partial replication, a sync rule+ // excluding large binaries, an operator reclaiming disk.+ await seedDerivedStore();+ const runId = "dream-archive-gone";+ createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });++ // A marker the restore would have removed, so its survival proves the+ // tree was never touched rather than merely that the call threw.+ const marker = join(vault, "Brain", "post-snapshot-marker.md");+ writeFileSync(marker, "# only in the live tree\n");++ rmSync(snapshotStorePath(vault, runId), { force: true });++ expect(() => restoreSnapshot(vault, runId)).toThrow(/refusing before the Brain tree/u);+ expect(existsSync(marker)).toBe(true);+ });++ test("a derived-store record this build cannot read refuses rather than guessing", async () => {+ // Coverage is indeterminate here, so neither replacing the live store+ // nor leaving it can be justified - and the Markdown tree must not be+ // spent finding that out.+ await seedDerivedStore();+ const runId = "dream-record-unreadable";+ createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });++ const marker = join(vault, "Brain", "post-snapshot-marker.md");+ writeFileSync(marker, "# only in the live tree\n");++ const sidecar = manifestSidecarPath(vault, runId);+ const parsed = JSON.parse(readFileSync(sidecar, "utf8")) as Record<string, unknown>;+ writeFileSync(sidecar, JSON.stringify({ ...parsed, derived_store: "included" }));++ expect(() => restoreSnapshot(vault, runId)).toThrow(/indeterminate/u);+ expect(existsSync(marker)).toBe(true);+ });++ test("swaps the store and says so when the manifest recorded one", async () => {+ const dbPath = await seedDerivedStore();+ const runId = "dream-restore-covered";+ createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });++ // Move the live store on: a row nothing in the archive knows about.+ const live = new Database(dbPath);+ live.exec("CREATE TABLE post_snapshot_marker (id INTEGER PRIMARY KEY)");+ live.close();+ expect(markerTableExists(dbPath)).toBe(true);++ const result = restoreSnapshot(vault, runId);++ expect(result.derived_store.replaced).toBe(true);+ expect(result.derived_store.coverage_known).toBe(true);+ expect(result.derived_store.path).toBe(dbPath);+ expect(result.derived_store.exclusion_reason).toBeNull();+ // The swap really happened: the post-snapshot table is gone.+ expect(markerTableExists(dbPath)).toBe(false);+ // No orphan WAL siblings of the file that was replaced.+ expect(existsSync(`${dbPath}-wal`)).toBe(false);+ expect(existsSync(`${dbPath}-shm`)).toBe(false);+ });++ test("reports a non-included snapshot and leaves the live store alone", async () => {+ const dbPath = await seedDerivedStore();+ const runId = "dream-restore-uncovered";+ createSnapshot(vault, runId, { reason: DREAM });++ const live = new Database(dbPath);+ live.exec("CREATE TABLE post_snapshot_marker (id INTEGER PRIMARY KEY)");+ live.close();++ const result = restoreSnapshot(vault, runId);++ expect(result.derived_store.replaced).toBe(false);+ expect(result.derived_store.coverage_known).toBe(true);+ expect(result.derived_store.exclusion_reason).toBe(SNAPSHOT_STORE_EXCLUSION.not_requested);+ expect(markerTableExists(dbPath)).toBe(true);+ });++ test("reports unknown for a snapshot taken before coverage existed", async () => {+ const dbPath = await seedDerivedStore();+ const runId = "dream-restore-unknown";+ createSnapshot(vault, runId, { reason: DREAM });+ rmSync(manifestSidecarPath(vault, runId), { force: true });++ const result = restoreSnapshot(vault, runId);++ expect(result.derived_store.coverage_known).toBe(false);+ expect(result.derived_store.replaced).toBe(false);+ // Unknown must never be reported as an exclusion.+ expect(result.derived_store.exclusion_reason).toBeNull();+ // Nothing was archived, so there is no archive to contradict the+ // "no record" reading.+ expect(result.derived_store.store_archive_present).toBe(false);+ expect(existsSync(dbPath)).toBe(true);+ });++ test("a lost record with the archive still on disk is a missing record, not a missing feature", async () => {+ // The sidecar write is non-fatal in `createSnapshot`, so coverage can+ // run to completion and leave no record of itself. The archive sitting+ // beside the tar is the proof, and reporting this as "the snapshot+ // predates derived-store coverage" states something the disk refutes.+ await seedDerivedStore();+ const runId = "dream-restore-record-lost";+ createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });+ expect(existsSync(snapshotStorePath(vault, runId))).toBe(true);++ const sidecar = manifestSidecarPath(vault, runId);+ const parsed = JSON.parse(readFileSync(sidecar, "utf8")) as Record<string, unknown>;+ delete parsed["derived_store"];+ writeFileSync(sidecar, JSON.stringify(parsed, null, 2) + "\n");++ const result = restoreSnapshot(vault, runId);++ expect(result.derived_store.coverage_known).toBe(false);+ expect(result.derived_store.replaced).toBe(false);+ expect(result.derived_store.exclusion_reason).toBeNull();+ // The one fact that separates this from a pre-feature snapshot.+ expect(result.derived_store.store_archive_present).toBe(true);+ });+});++describe("the artifact directory documented as never backed up", () => {+ test("is neither archived nor hashed into the manifest", () => {+ const dirs = brainDirs(vault);+ const artifacts = join(dirs.brain, BRAIN_ARTIFACTS_DIR);+ mkdirSync(artifacts, { recursive: true });+ writeFileSync(join(artifacts, "run-1.json"), '{"ephemeral":true}');++ const runId = "dream-artifacts-excluded";+ createSnapshot(vault, runId, { reason: DREAM });++ const listing = execFileSync("tar", ["-tf", snapshotPath(vault, runId)], {+ encoding: "utf8",+ });+ expect(listing).not.toContain(BRAIN_ARTIFACTS_DIR);++ const manifest = readManifestSidecar(vault, runId);+ const hashed = Object.keys(manifest?.files ?? {});+ expect(hashed.some((p) => p.startsWith(`${BRAIN_ARTIFACTS_DIR}/`))).toBe(false);+ });++ test("survives a restore rather than being deleted by it", () => {+ const dirs = brainDirs(vault);+ const runId = "dream-artifacts-survive";+ createSnapshot(vault, runId, { reason: DREAM });++ const artifacts = join(dirs.brain, BRAIN_ARTIFACTS_DIR);+ mkdirSync(artifacts, { recursive: true });+ const cached = join(artifacts, "run-2.json");+ writeFileSync(cached, '{"ephemeral":true}');++ restoreSnapshot(vault, runId);++ // The archive holds no `.artifacts/`, so deleting the live copy+ // would restore nothing over it - a net loss for no benefit.+ expect(existsSync(cached)).toBe(true);+ });+});++describe("a host with gzip but no zstd", () => {+ test("refuses an existing archive exactly as the zstd path does", () => {+ const runId = "dream-gzip-collision";+ const originalPath = process.env["PATH"];+ const bin = gzipOnlyPath();+ process.env["PATH"] = bin.dir;+ try {+ createSnapshot(vault, runId, { reason: DREAM });+ const archive = snapshotPath(vault, runId);+ expect(existsSync(archive)).toBe(true);+ // Proves the fallback really was gzip: gzip's magic, not zstd's.+ const magic = readFileSync(archive).subarray(0, 2);+ expect([magic[0], magic[1]]).toEqual([0x1f, 0x8b]);+ const before = readFileSync(archive);++ // The run-id collision resolution in `snapshot-gate.ts` RETRIES on+ // exactly this failure. Without it, two concurrent destructive+ // operations on a gzip-only host destroy each other's recovery+ // point with no error at all.+ expect(() => createSnapshot(vault, runId, { reason: DREAM })).toThrow(BrainSnapshotError);+ expect(readFileSync(archive).equals(before)).toBe(true);+ } finally {+ process.env["PATH"] = originalPath;+ bin.cleanup();+ }+ });+});++/** A PATH directory holding `tar` and `gzip` but deliberately not `zstd`. */+function gzipOnlyPath(): { dir: string; cleanup: () => void } {+ const dir = mkdtempSync(join(tmpdir(), "o2b-gzip-only-bin-"));+ for (const tool of ["tar", "gzip"]) {+ symlinkSync(which(tool), join(dir, tool));+ }+ return { dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) };+}++function which(tool: string): string {+ return execFileSync("which", [tool], { encoding: "utf8" }).trim();+}++/** Whether the post-snapshot marker table is present in the store. */+function markerTableExists(dbPath: string): boolean {+ const db = new Database(dbPath, { readonly: true });+ try {+ return (+ db+ .query<{ name: string }, [string]>(+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",+ )+ .get("post_snapshot_marker") !== null+ );+ } finally {+ db.close();+ }+}++describe("createSnapshot โ which file is the store", () => {+ // The archiver used to answer this question with the default location+ // alone. On a vault that moved its store, that names a file the search+ // layer never reads: absent, if nothing is there, and - worse - a stale+ // database archived and reported as a success if something is. The pack+ // stamp shipped the same bug against the same config key.+ test("honours a search_db_path override and ignores a decoy at the default location", async () => {+ const moved = join(configHome, "moved-store.sqlite");+ const notes = join(vault, "Notes");+ mkdirSync(notes, { recursive: true });+ writeFileSync(join(notes, "seed.md"), "# Seed\n\nA paragraph long enough to be chunked.\n");+ await indexVault(makeConfig({ vault, dbPath: moved }));++ // A decoy where the archiver used to look. If it wins, the archive+ // describes a database nothing queries.+ const decoyPath = resolveIndexPath(vault, null);+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ const decoy = new Database(decoyPath);+ decoy.run("CREATE TABLE decoy (id INTEGER PRIMARY KEY)");+ decoy.close();++ atomicWriteFileSync(configPath, `vault: ${vault}\nsearch_db_path: ${moved}\n`);+ const savedConfigEnv = process.env["OPEN_SECOND_BRAIN_CONFIG"];+ const savedDbEnv = process.env["OPEN_SECOND_BRAIN_SEARCH_DB"];+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ delete process.env["OPEN_SECOND_BRAIN_SEARCH_DB"];+ try {+ const res = createSnapshot(vault, "dream-store-moved", {+ reason: DREAM,+ derivedStore: COVERED,+ });+ expect(res.derived_store.included).toBe(true);+ expect(res.derived_store.source_path).toBe(moved);+ expect(res.derived_store.source_path).not.toBe(decoyPath);+ expect(res.derived_store.live_size).toBe(statSync(moved).size);+ } finally {+ if (savedConfigEnv === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfigEnv;+ if (savedDbEnv !== undefined) process.env["OPEN_SECOND_BRAIN_SEARCH_DB"] = savedDbEnv;+ }+ });++ test("an explicit derivedStorePath still wins over the resolved one", async () => {+ const dbPath = await seedDerivedStore();+ const res = createSnapshot(vault, "dream-store-explicit", {+ reason: DREAM,+ derivedStore: COVERED,+ derivedStorePath: dbPath,+ });+ expect(res.derived_store.source_path).toBe(dbPath);+ });+});diff --git a/tests/core/brain/snapshot-gate.test.ts b/tests/core/brain/snapshot-gate.test.tsindex cc5fbe51..6531f818 100644--- a/tests/core/brain/snapshot-gate.test.ts+++ b/tests/core/brain/snapshot-gate.test.ts@@ -1,28 +1,44 @@/*** D1 (t_7965b04b): snapshot-before-destructive-write gate.*- * `withDestructiveSnapshot(vault, label, op)` is the thin wrapper that+ * `withDestructiveSnapshot(vault, reason, op)` is the thin wrapper that* guarantees no destructive brain mutation runs without a recovery* point on disk first. The contract:*- * - it mints a valid, unique run id of the shape `<label>-<stamp>`;- * - it calls `createSnapshot` BEFORE `op`, so a snapshot failure+ * - it mints a valid, unique run id of the shape `<reason>-<stamp>`;+ * - it calls `takeSnapshot` BEFORE `op`, so a snapshot failure* aborts the operation (the destructive work never runs);* - if `op` throws, the error propagates but the snapshot stays put* (that IS the recovery point);- * - after a successful `op` it prunes to the configured retention.+ * - retention is enforced around the recovery point it just wrote.+ *+ * U7 adds one structural assertion to that list: the standalone+ * `takeSnapshot` entry point and the wrapper must produce byte-identical+ * archives for the same input, because the wrapper delegates to it rather+ * than carrying a second copy of the snapshot path.*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import {+ cpSync,+ existsSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ statSync,+ utimesSync,+ writeFileSync,+} from "node:fs";import { spawnSync } from "node:child_process";import { tmpdir } from "node:os";import { join } from "node:path";-import { withDestructiveSnapshot } from "../../../src/core/brain/snapshot-gate.ts";-import { listSnapshots } from "../../../src/core/brain/snapshot.ts";+import { takeSnapshot, withDestructiveSnapshot } from "../../../src/core/brain/snapshot-gate.ts";+import { BrainSnapshotStoreError, listSnapshots } from "../../../src/core/brain/snapshot.ts";import { brainDirs, validateRunId } from "../../../src/core/brain/paths.ts";import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { BRAIN_SNAPSHOT_REASON } from "../../../src/core/brain/types.ts";import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";let vault: string;@@ -53,7 +69,7 @@ describe("withDestructiveSnapshot", () => {let archiveCountWhenOpRan = -1;const out = withDestructiveSnapshot(vault,- "delete-by-source",+ BRAIN_SNAPSHOT_REASON.deleteBySource,() => {// The snapshot archive must already exist by the time op runs.archiveCountWhenOpRan = listSnapshots(vault).length;@@ -72,7 +88,7 @@ describe("withDestructiveSnapshot", () => {test("op runs after the snapshot exists (order proven)", () => {let order: string[] = [];const before = listSnapshots(vault).length;- withDestructiveSnapshot(vault, "prune-entities", () => {+ withDestructiveSnapshot(vault, BRAIN_SNAPSHOT_REASON.entityPrune, () => {order.push(`snapshots=${listSnapshots(vault).length}`);});expect(order).toEqual([`snapshots=${before + 1}`]);@@ -87,7 +103,7 @@ describe("withDestructiveSnapshot", () => {let opRan = false;try {expect(() =>- withDestructiveSnapshot(vault, "delete-by-source", () => {+ withDestructiveSnapshot(vault, BRAIN_SNAPSHOT_REASON.deleteBySource, () => {opRan = true;}),).toThrow();@@ -98,10 +114,31 @@ describe("withDestructiveSnapshot", () => {}});+ test("aborts the operation when derived-store coverage cannot be honoured", () => {+ // Coverage on, and no derived store in this vault. `createSnapshot`+ // refuses rather than downgrading to a snapshot that omits what it+ // was asked to protect - and because the gate snapshots FIRST, the+ // destructive operation simply never runs. No new plumbing: the+ // property follows from refusing in the right place.+ const brainYaml = join(brainDirs(vault).brain, "_brain.yaml");+ atomicWriteFileSync(+ brainYaml,+ "schema_version: 1\nsnapshots:\n include_derived_store: true\n",+ );+ let opRan = false;+ expect(() =>+ withDestructiveSnapshot(vault, BRAIN_SNAPSHOT_REASON.deleteBySource, () => {+ opRan = true;+ }),+ ).toThrow(BrainSnapshotStoreError);+ expect(opRan).toBe(false);+ expect(listSnapshots(vault)).toHaveLength(0);+ });+test("op error propagates but the snapshot is retained as recovery point", () => {const before = listSnapshots(vault).length;expect(() =>- withDestructiveSnapshot(vault, "delete-by-source", () => {+ withDestructiveSnapshot(vault, BRAIN_SNAPSHOT_REASON.deleteBySource, () => {throw new Error("op blew up");}),).toThrow("op blew up");@@ -116,7 +153,7 @@ describe("withDestructiveSnapshot", () => {// Create three snapshots through the gate; only the two newest survive.for (let i = 0; i < 3; i++) {- withDestructiveSnapshot(vault, "delete-by-source", () => undefined, {+ withDestructiveSnapshot(vault, BRAIN_SNAPSHOT_REASON.deleteBySource, () => undefined, {now: new Date(`2026-06-0${i + 1}T00:00:00Z`),});}@@ -125,14 +162,28 @@ describe("withDestructiveSnapshot", () => {test("mints unique run ids when the base id already exists", () => {const now = new Date("2026-06-01T00:00:00Z");- const a = withDestructiveSnapshot(vault, "delete-by-source", () => undefined, { now });- const b = withDestructiveSnapshot(vault, "delete-by-source", () => undefined, { now });+ const a = withDestructiveSnapshot(+ vault,+ BRAIN_SNAPSHOT_REASON.deleteBySource,+ () => undefined,+ { now },+ );+ const b = withDestructiveSnapshot(+ vault,+ BRAIN_SNAPSHOT_REASON.deleteBySource,+ () => undefined,+ { now },+ );expect(a.snapshot.runId).not.toBe(b.snapshot.runId);expect(b.snapshot.runId).toBe(`${a.snapshot.runId}-2`);});test("the minted snapshot archive contains the seeded Brain content", () => {- const out = withDestructiveSnapshot(vault, "delete-by-source", () => undefined);+ const out = withDestructiveSnapshot(+ vault,+ BRAIN_SNAPSHOT_REASON.deleteBySource,+ () => undefined,+ );// Extract and confirm the seeded signal is present.const tmp = mkdtempSync(join(tmpdir(), "o2b-gate-verify-"));try {@@ -151,4 +202,96 @@ describe("withDestructiveSnapshot", () => {rmSync(tmp, { recursive: true, force: true });}});++ test("stamps the reason it was given into the snapshot's sidecar", () => {+ const out = withDestructiveSnapshot(vault, BRAIN_SNAPSHOT_REASON.entityPrune, () => undefined);+ const listed = listSnapshots(vault).find((s) => s.run_id === out.snapshot.runId);+ expect(listed?.reason).toBe(BRAIN_SNAPSHOT_REASON.entityPrune);+ });+});++/**+ * U7: the extraction must not have forked the snapshot path.+ *+ * `takeSnapshot` exists so a caller that wants a recovery point WITHOUT+ * an operation behind it has somewhere to go other than a second copy of+ * the id-minting and archiving logic. The proof that it is not a second+ * copy is that the wrapper's archive and its own are byte-identical over+ * the same tree.+ *+ * The comparison runs over two vaults rather than two snapshots of one,+ * because a snapshot appends its own log event into `Brain/log/` - so a+ * second archive of the SAME vault legitimately differs, and comparing+ * them would prove nothing about the code path. Both trees are stamped to+ * one fixed mtime first: tar records per-entry mtimes, and the copy's are+ * otherwise the moment it was made.+ */+describe("takeSnapshot and withDestructiveSnapshot share one archive path", () => {+ /** Stamp every entry under `root` to one instant, deepest-last. */+ function stampTree(root: string, when: Date): void {+ const stack = [root];+ const seen: string[] = [];+ while (stack.length > 0) {+ const dir = stack.pop()!;+ seen.push(dir);+ for (const name of readdirSync(dir)) {+ const abs = join(dir, name);+ if (statSync(abs).isDirectory()) stack.push(abs);+ else utimesSync(abs, when, when);+ }+ }+ // Directories last: touching a child rewrites its parent's mtime.+ for (const dir of seen.toReversed()) utimesSync(dir, when, when);+ }++ test("both entry points produce byte-identical archives for the same input", () => {+ const twin = mkdtempSync(join(tmpdir(), "o2b-snap-gate-twin-"));+ try {+ // Copy BEFORE either vault has a `.snapshots/` directory, so the two+ // trees under `Brain/` are identical in content and in structure.+ cpSync(join(vault, "Brain"), join(twin, "Brain"), { recursive: true });+ const fixed = new Date("2026-06-01T00:00:00Z");+ stampTree(join(vault, "Brain"), fixed);+ stampTree(join(twin, "Brain"), fixed);++ const viaEntryPoint = takeSnapshot(vault, BRAIN_SNAPSHOT_REASON.manual, { now: fixed });+ const viaWrapper = withDestructiveSnapshot(+ twin,+ BRAIN_SNAPSHOT_REASON.manual,+ () => undefined,+ { now: fixed },+ );++ // Same minting rule, so the same id from the same reason and clock.+ expect(viaWrapper.snapshot.runId).toBe(viaEntryPoint.runId);+ expect(readFileSync(viaWrapper.snapshot.path)).toEqual(readFileSync(viaEntryPoint.path));+ } finally {+ rmSync(twin, { recursive: true, force: true });+ }+ });++ test("the standalone entry point requires a reason and records it", () => {+ const snap = takeSnapshot(vault, BRAIN_SNAPSHOT_REASON.manual);+ expect(snap.runId).toMatch(/^manual-/);+ expect(existsSync(snap.path)).toBe(true);+ expect(listSnapshots(vault).find((s) => s.run_id === snap.runId)?.reason).toBe(+ BRAIN_SNAPSHOT_REASON.manual,+ );+ });++ test("the standalone entry point refuses when the snapshot cannot be created", () => {+ // Same refusal as the wrapper's: an entry point that returned a+ // plausible-looking result on a host without tar would hand back a+ // recovery point that does not exist.+ const emptyDir = mkdtempSync(join(tmpdir(), "o2b-empty-path-take-"));+ const savedPath = process.env["PATH"];+ process.env["PATH"] = emptyDir;+ try {+ expect(() => takeSnapshot(vault, BRAIN_SNAPSHOT_REASON.manual)).toThrow();+ expect(listSnapshots(vault)).toHaveLength(0);+ } finally {+ process.env["PATH"] = savedPath;+ rmSync(emptyDir, { recursive: true, force: true });+ }+ });});diff --git a/tests/core/brain/snapshot-reason.test.ts b/tests/core/brain/snapshot-reason.test.tsnew file mode 100644index 00000000..9395dcb7--- /dev/null+++ b/tests/core/brain/snapshot-reason.test.ts@@ -0,0 +1,167 @@+/**+ * U7: the typed snapshot reason and the log event that records it.+ *+ * Two histories existed in this codebase and did not join. The Brain+ * event log is richly typed and records a `rollback`; the snapshot family+ * is the only revertible history and every entry in it was an opaque run+ * id plus an mtime. This file pins the join: the reason reaches the+ * sidecar, one `snapshot` event per created recovery point carries it, and+ * the two failure modes that would quietly re-open the gap are refused -+ * a log failure must not cost a recovery point, and an absent reason must+ * not be reconstructed from the run-id prefix that happens to spell it.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ statSync,+ unlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { createSnapshot, listSnapshots } from "../../../src/core/brain/snapshot.ts";+import { manifestSidecarPath, readManifestSidecar } from "../../../src/core/brain/manifest.ts";+import { readLogDay } from "../../../src/core/brain/log-jsonl.ts";+import { brainDirs } from "../../../src/core/brain/paths.ts";+import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "../../../src/core/brain/types.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";++let vault: string;+let configHome: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-snap-reason-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-snap-reason-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });++ writeFileSync(+ join(brainDirs(vault).preferences, "pref-foo.md"),+ "---\nkind: brain-preference\n---\n\n## Principle\n\nseed\n",+ );+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++/** Every `snapshot` event logged today, across every device shard. */+function loggedSnapshotEvents(): ReadonlyArray<Record<string, unknown>> {+ const today = new Date().toISOString().slice(0, 10);+ return readLogDay(vault, today)+ .entries.filter((e) => e.eventType === BRAIN_LOG_EVENT_KIND.snapshot)+ .map((e) => e.body as Record<string, unknown>);+}++describe("createSnapshot stamps the reason into the sidecar", () => {+ test("the reason reaches the manifest and the listing reads it back", () => {+ const runId = "entity-prune-2026-08-10-070000";+ createSnapshot(vault, runId, { reason: BRAIN_SNAPSHOT_REASON.entityPrune });++ expect(readManifestSidecar(vault, runId)?.snapshot_reason).toBe(+ BRAIN_SNAPSHOT_REASON.entityPrune,+ );+ const listed = listSnapshots(vault).find((s) => s.run_id === runId);+ expect(listed?.reason).toBe(BRAIN_SNAPSHOT_REASON.entityPrune);+ });++ test("every registered reason survives the round trip", () => {+ // Including the three with no producer in this release: the manifest+ // has to be able to read a reason a later release writes, because the+ // snapshots directory replicates to peers running older builds.+ for (const reason of Object.values(BRAIN_SNAPSHOT_REASON)) {+ const runId = `${reason}-roundtrip`;+ createSnapshot(vault, runId, { reason });+ expect(`${reason}: ${readManifestSidecar(vault, runId)?.snapshot_reason}`).toBe(+ `${reason}: ${reason}`,+ );+ }+ });++ test("a sidecar with no reason reads as null, not as the run-id prefix", () => {+ const runId = "dream-2026-08-10-070000";+ createSnapshot(vault, runId, { reason: BRAIN_SNAPSHOT_REASON.dream });+ // Remove the sidecar entirely: the archive now looks exactly like one+ // written before the reason existed, and its run id still begins with+ // a registered reason. Guessing from that prefix would report `dream`+ // for provenance nothing recorded.+ unlinkSync(manifestSidecarPath(vault, runId));++ const listed = listSnapshots(vault).find((s) => s.run_id === runId);+ expect(listed).toBeDefined();+ expect(listed!.reason).toBeNull();+ expect(listed!.manifest_path).toBeNull();+ });++ test("an unregistered reason keeps the record that drift detection needs", () => {+ const runId = "dream-tampered";+ createSnapshot(vault, runId, { reason: BRAIN_SNAPSHOT_REASON.dream });+ const sidecar = manifestSidecarPath(vault, runId);+ const parsed = JSON.parse(readFileSync(sidecar, "utf8")) as Record<string, unknown>;+ writeFileSync(sidecar, JSON.stringify({ ...parsed, snapshot_reason: "spring-cleaning" }));++ // A reason this build does not register is what a LATER build writes,+ // and the vault replicates between machines that need not run the same+ // one. Refusing the whole record would discard the file map with it and+ // send rollback down its no-drift-check path - the silent-overwrite+ // route, reached by a different door. The provenance is unusable and+ // says so; the comparison the rest of the record supports is intact.+ const manifest = readManifestSidecar(vault, runId);+ expect(manifest).not.toBeNull();+ expect(manifest!.snapshot_reason).toBeUndefined();+ expect(manifest!.snapshot_reason_unreadable).toBe(true);+ expect(Object.keys(manifest!.files).length).toBeGreaterThan(0);+ // The listing still refuses to name a provenance it cannot read.+ expect(listSnapshots(vault).find((s) => s.run_id === runId)!.reason).toBeNull();+ });+});++describe("createSnapshot emits exactly one snapshot log event", () => {+ test("the event carries the run id, the reason and the archive size", () => {+ const runId = "upgrade-2026-08-10-070000";+ const res = createSnapshot(vault, runId, { reason: BRAIN_SNAPSHOT_REASON.upgrade });++ const events = loggedSnapshotEvents();+ expect(events).toHaveLength(1);+ expect(events[0]!["run_id"]).toBe(runId);+ expect(events[0]!["reason"]).toBe(BRAIN_SNAPSHOT_REASON.upgrade);+ expect(events[0]!["size_bytes"]).toBe(String(statSync(res.path).size));+ });++ test("two snapshots produce two events, one each", () => {+ createSnapshot(vault, "dream-one", { reason: BRAIN_SNAPSHOT_REASON.dream });+ createSnapshot(vault, "manual-two", { reason: BRAIN_SNAPSHOT_REASON.manual });+ const events = loggedSnapshotEvents();+ expect(events.map((e) => e["run_id"]).toSorted()).toEqual(["dream-one", "manual-two"]);+ expect(events.map((e) => e["reason"]).toSorted()).toEqual(["dream", "manual"]);+ });++ test("a failing log append does not fail the snapshot", () => {+ // Replace the log directory with a regular file so the append cannot+ // create it. The recovery point is the load-bearing artifact and the+ // destructive operation it guards must not be aborted over an audit+ // line, so the failure is a warning and the archive stands.+ const dirs = brainDirs(vault);+ rmSync(dirs.log, { recursive: true, force: true });+ writeFileSync(dirs.log, "not a directory\n");++ const runId = "delete-by-source-logless";+ const res = createSnapshot(vault, runId, { reason: BRAIN_SNAPSHOT_REASON.deleteBySource });++ expect(existsSync(res.path)).toBe(true);+ // The reason still made it into the sidecar: only the audit line was+ // lost, and the manifest is written on its own best-effort path.+ expect(readManifestSidecar(vault, runId)?.snapshot_reason).toBe(+ BRAIN_SNAPSHOT_REASON.deleteBySource,+ );+ });+});diff --git a/tests/core/brain/standing-rules.test.ts b/tests/core/brain/standing-rules.test.tsnew file mode 100644index 00000000..e8f4ba23--- /dev/null+++ b/tests/core/brain/standing-rules.test.ts@@ -0,0 +1,223 @@+/**+ * Operator standing rules (silence-is-not-an-answer, U8).+ *+ * The one lane of the session preamble the operator authors. Three+ * properties are load-bearing and each has a case here:+ *+ * - ABSENCE IS NULL, FAILURE IS A THROW. A file that is not there and+ * a file the process cannot read are different answers. The second+ * one may never quietly become the first, because a constitution+ * that vanishes without a word is worse than one that is missing.+ * - OPACITY. The reader performs exactly three operations on the+ * operator's bytes: read, trim, and line-boundary trimming at a+ * character cap. A non-Latin body must round-trip byte-identically+ * and count identically to a Latin body of the same length - the+ * guard against any future word list, heading split, or classifier+ * creeping into the reader.+ * - LOUD TRUNCATION. A capped block says how much it kept, out of how+ * much, in lines and characters, and where the whole text lives.+ */++import { afterEach, beforeEach, describe, 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 { brainStandingRulesPath } from "../../../src/core/brain/paths.ts";+import {+ STANDING_RULES_HEADER,+ STANDING_RULES_MAX_CHARS_DEFAULT,+ STANDING_RULES_MAX_CHARS_MAX,+ STANDING_RULES_MAX_CHARS_MIN,+ readStandingRules,+ renderStandingRules,+ renderStandingRulesFailure,+} from "../../../src/core/brain/standing-rules.ts";++let vault: string;++/** A mode change cannot make a file unreadable to uid 0. */+const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-standing-rules-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function writeRules(body: string): string {+ const path = brainStandingRulesPath(vault);+ writeFileSync(path, body, "utf8");+ return path;+}++/** `n` lines of `char` repeated `width` times: a body of known char/line counts. */+function bodyOf(char: string, lines: number, width: number): string {+ return Array.from({ length: lines }, () => char.repeat(width)).join("\n");+}++describe("readStandingRules: absence and emptiness are null", () => {+ test("absent file returns null", () => {+ expect(readStandingRules(vault)).toBeNull();+ });++ test("whitespace-only file returns null", () => {+ writeRules(" \n\n\t\n ");+ expect(readStandingRules(vault)).toBeNull();+ });+});++describe("readStandingRules: a present file", () => {+ const BODY = "Never force-push.\nAsk before deleting anything under Archive/.";++ test("carries the operator text verbatim and reports no truncation", () => {+ const path = writeRules(`\n${BODY}\n\n`);+ const rules = readStandingRules(vault);+ expect(rules).not.toBeNull();+ expect(rules!.path).toBe(path);+ expect(rules!.text).toBe(BODY);+ expect(rules!.truncated).toBe(false);+ expect(rules!.totalLines).toBe(2);+ expect(rules!.keptLines).toBe(2);+ expect(rules!.totalChars).toBe(BODY.length);+ expect(rules!.keptChars).toBe(BODY.length);+ });++ test("renders the header first, then the operator text unchanged", () => {+ writeRules(BODY);+ const block = renderStandingRules(readStandingRules(vault)!);+ expect(block.startsWith(STANDING_RULES_HEADER)).toBe(true);+ expect(block).toContain(BODY);+ // Nothing rides along when the body fits: the block is exactly the+ // header, the separator and the operator's own bytes.+ expect(block).toBe(`${STANDING_RULES_HEADER}\n\n${BODY}`);+ });+});++describe("readStandingRules: operator bytes are opaque", () => {+ // Equal LINE and CHARACTER counts, different scripts. Any reader that+ // inspected words, split on headings, or classified content would make+ // these two diverge; the counts and the round-trip say it does not.+ const LINES = 6;+ const WIDTH = 20;+ const LATIN = bodyOf("a", LINES, WIDTH);+ const NON_LATIN = bodyOf("ั", LINES, WIDTH);+ const IDEOGRAPHIC = bodyOf("ๆน", LINES, WIDTH);++ test("a non-Latin body round-trips byte-identically", () => {+ writeRules(NON_LATIN);+ expect(readStandingRules(vault)!.text).toBe(NON_LATIN);+ });++ test("scripts of equal length produce identical counts", () => {+ const counts = (body: string): Record<string, unknown> => {+ writeRules(body);+ const { text: _text, path: _path, ...rest } = readStandingRules(vault)!;+ return rest;+ };+ const latin = counts(LATIN);+ expect(counts(NON_LATIN)).toEqual(latin);+ expect(counts(IDEOGRAPHIC)).toEqual(latin);+ });++ test("a capped non-Latin body is cut identically to a Latin one", () => {+ const cap = STANDING_RULES_MAX_CHARS_MIN;+ const wide = (char: string): string => bodyOf(char, 200, WIDTH);+ writeRules(wide("a"));+ const latin = readStandingRules(vault, { maxChars: cap })!;+ writeRules(wide("ั"));+ const nonLatin = readStandingRules(vault, { maxChars: cap })!;+ expect(nonLatin.keptLines).toBe(latin.keptLines);+ expect(nonLatin.keptChars).toBe(latin.keptChars);+ expect(nonLatin.text).toBe(bodyOf("ั", latin.keptLines, WIDTH));+ });+});++describe("readStandingRules: capping is loud and cut on a line boundary", () => {+ const LINES = 400;+ const WIDTH = 30;++ test("an over-cap body is cut at a line boundary", () => {+ writeRules(bodyOf("r", LINES, WIDTH));+ const rules = readStandingRules(vault, { maxChars: STANDING_RULES_MAX_CHARS_MIN })!;+ expect(rules.truncated).toBe(true);+ expect(rules.totalLines).toBe(LINES);+ expect(rules.keptLines).toBeLessThan(LINES);+ expect(rules.keptChars).toBeLessThanOrEqual(STANDING_RULES_MAX_CHARS_MIN);+ // Every kept line is a whole line of the original.+ for (const line of rules.text.split("\n")) expect(line).toBe("r".repeat(WIDTH));+ });++ test("the notice names kept and total lines, kept and total characters, and the path", () => {+ const path = writeRules(bodyOf("r", LINES, WIDTH));+ const rules = readStandingRules(vault, { maxChars: STANDING_RULES_MAX_CHARS_MIN })!;+ const block = renderStandingRules(rules);+ const notice = block.slice(block.indexOf(rules.text) + rules.text.length);+ for (const n of [rules.keptLines, rules.totalLines, rules.keptChars, rules.totalChars]) {+ expect(notice).toContain(String(n));+ }+ expect(notice).toContain(path);+ // The operator's own bytes still lead the block, header aside.+ expect(block.startsWith(`${STANDING_RULES_HEADER}\n\n${rules.text}`)).toBe(true);+ });++ test("the default cap applies when the caller names none", () => {+ writeRules(bodyOf("r", LINES, WIDTH));+ const rules = readStandingRules(vault)!;+ expect(rules.keptChars).toBeLessThanOrEqual(STANDING_RULES_MAX_CHARS_DEFAULT);+ });++ test("a cap above the body length keeps everything", () => {+ const body = bodyOf("r", LINES, WIDTH);+ writeRules(body);+ const rules = readStandingRules(vault, { maxChars: STANDING_RULES_MAX_CHARS_MAX })!;+ expect(rules.truncated).toBe(false);+ expect(rules.text).toBe(body);+ });+});++describe("readStandingRules: an unreadable file throws rather than returning null", () => {+ test.skipIf(RUNNING_AS_ROOT)("the throw names the path and the reason", () => {+ const path = writeRules("Never force-push.\n");+ chmodSync(path, 0o000);+ try {+ let thrown: unknown;+ try {+ readStandingRules(vault);+ } catch (err) {+ thrown = err;+ }+ // Stated as two separate claims: it threw, AND what it did not do+ // was return the same null an absent file returns.+ expect(thrown).toBeInstanceOf(Error);+ expect((thrown as Error).message).toContain(path);+ expect((thrown as Error).message.toLowerCase()).toContain("permission denied");+ } finally {+ chmodSync(path, 0o600);+ }+ });++ test("a directory at the rules path is a failure, not an absence", () => {+ mkdirSync(brainStandingRulesPath(vault));+ expect(() => readStandingRules(vault)).toThrow(brainStandingRulesPath(vault));+ });+});++describe("renderStandingRulesFailure", () => {+ test("names the path, the reason, and that no rules are in force", () => {+ const path = brainStandingRulesPath(vault);+ const block = renderStandingRulesFailure(path, new Error("EACCES: permission denied"));+ expect(block).toContain(path);+ expect(block).toContain("EACCES: permission denied");+ expect(block.toLowerCase()).toContain("unavailable");+ expect(block.toLowerCase()).toContain("no standing rules are in force");+ });++ test("a non-Error reason is still reported", () => {+ const block = renderStandingRulesFailure("/v/Brain/standing-rules.md", "disk went away");+ expect(block).toContain("disk went away");+ });+});diff --git a/tests/core/brain/text-budget.test.ts b/tests/core/brain/text-budget.test.tsindex 69ee838b..75adc38c 100644--- a/tests/core/brain/text-budget.test.ts+++ b/tests/core/brain/text-budget.test.ts@@ -11,6 +11,7 @@ import { describe, expect, test } from "bun:test";import {applySectionBudget,type BudgetSection,+ type SectionTruncationReport,} from "../../../src/core/brain/text/text-budget.ts";const NOTICE = "_Truncated to fit the injection budget. Call `brain_context` for the full view._";@@ -103,3 +104,74 @@ describe("applySectionBudget", () => {expect(out.body).toContain("## Confirmed");});});++/**+ * The notice may be a function of the truncation report, which is what+ * lets a caller say WHICH sections went and by how much rather than+ * emitting a fixed sentence that names nothing. The report carries+ * integers and section keys only - no text of the sections themselves -+ * so a notice built from it is safe to show whatever the sections hold.+ */+describe("applySectionBudget: the notice as a function of the truncation report", () => {+ function reportFor(budget: number): SectionTruncationReport {+ let seen: SectionTruncationReport | null = null;+ applySectionBudget(sections(), budget, {+ notice: (report) => {+ seen = report;+ return "";+ },+ });+ if (seen === null) throw new Error("the notice function was never called");+ return seen;+ }++ test("the function receives droppedKeys in drop order", () => {+ const full = applySectionBudget(sections(), 10_000).body.length;+ expect(reportFor(full - 20).droppedKeys).toEqual(["retired"]);+ expect(reportFor(30).droppedKeys).toEqual(["retired", "quarantine", "most-applied"]);+ });++ test("the function receives kept and total characters and the trimmed flag", () => {+ const full = applySectionBudget(sections(), 10_000).body.length;+ // A whole-section drop with no tail trim.+ const dropped = reportFor(full - 20);+ expect(dropped.totalChars).toBe(full);+ expect(dropped.keptChars).toBeLessThan(full);+ expect(dropped.trimmed).toBe(false);+ // A budget tight enough that the last kept section is tail-trimmed.+ expect(reportFor(30).trimmed).toBe(true);+ });++ test("the returned string is appended verbatim", () => {+ const out = applySectionBudget(sections(), 30, {+ notice: (report) => `dropped ${report.droppedKeys.length}`,+ });+ expect(out.body.endsWith("\n\ndropped 3")).toBe(true);+ });++ test("a function returning the empty string appends nothing", () => {+ const out = applySectionBudget(sections(), 30, { notice: () => "" });+ expect(out.truncated).toBe(true);+ expect(out.body.length).toBeLessThanOrEqual(30);+ });++ test("the function is not called when nothing was truncated", () => {+ let calls = 0;+ const out = applySectionBudget(sections(), 10_000, {+ notice: () => {+ calls++;+ return NOTICE;+ },+ });+ expect(calls).toBe(0);+ expect(out.body).not.toContain(NOTICE);+ });++ test("the string form still behaves identically to a function returning it", () => {+ for (const budget of [0, 30, 90, 200, 10_000]) {+ const asString = applySectionBudget(sections(), budget, { notice: NOTICE });+ const asFunction = applySectionBudget(sections(), budget, { notice: () => NOTICE });+ expect(asFunction).toEqual(asString);+ }+ });+});diff --git a/tests/core/brain/trigger-store.test.ts b/tests/core/brain/trigger-store.test.tsindex 9bbe43a4..eea880df 100644--- a/tests/core/brain/trigger-store.test.ts+++ b/tests/core/brain/trigger-store.test.ts@@ -6,19 +6,33 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";+import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import lockfile from "proper-lockfile";+import {briefTriggers,createTriggers,listTriggers,markTriggersDelivered,+ readTriggers,+ recordRecurrence,transitionTrigger,+ triggersDir,+ TriggerSourceArtifactsError,+ TriggerFieldError,+ TRIGGER_LOCK_STALE_MS,TRIGGER_TTL_DAYS,} from "../../../src/core/brain/triggers/store.ts";-import type { InsightCandidate } from "../../../src/core/brain/triggers/types.ts";+import {+ TRIGGER_OPEN_STATUSES,+ TRIGGER_STATUS,+ TRIGGER_STATUSES,+ TRIGGER_TERMINAL_STATUSES,+ type InsightCandidate,+} from "../../../src/core/brain/triggers/types.ts";let vault: string;const NOW = new Date("2026-06-03T10:00:00Z");@@ -153,3 +167,426 @@ test("briefTriggers ranks by urgency then recency and respects the cap", () => {expect(listed).toHaveLength(2);expect(listed.map((t) => t.urgency)).toEqual(["high", "medium"]);});++// โโ Suppression (silence-is-not-an-answer, U5) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ++test("the two status partitions exactly cover the status vocabulary", () => {+ const union = [...TRIGGER_OPEN_STATUSES, ...TRIGGER_TERMINAL_STATUSES].toSorted();+ expect(union).toEqual([...TRIGGER_STATUSES].toSorted());+ // Disjoint: a status in both partitions would make the terminal+ // rejection and the open-status expiry rule contradict each other.+ for (const status of TRIGGER_OPEN_STATUSES) {+ expect(TRIGGER_TERMINAL_STATUSES.has(status)).toBe(false);+ }+});++test("a suppressed twin blocks recreation indefinitely with the suppressed reason", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ transitionTrigger(vault, created[0]!.id, "suppress", { now: NOW });++ const aYearLater = new Date(NOW.getTime() + 365 * DAY_MS);+ const again = createTriggers(vault, [candidate()], { now: aYearLater, cooldownDays: 7 });+ expect(again.created).toHaveLength(0);+ expect(again.skipped[0]!.reason).toBe("suppressed");+ expect(listTriggers(vault, { now: aYearLater })).toHaveLength(1);+});++test("every blocked scan records one recurrence and the instant it fired", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ transitionTrigger(vault, created[0]!.id, "suppress", { now: NOW });+ expect(listTriggers(vault, { now: NOW })[0]!.occurrences).toBe(1);++ let last = NOW;+ for (const day of [1, 2, 3]) {+ last = new Date(NOW.getTime() + day * DAY_MS);+ createTriggers(vault, [candidate()], { now: last });+ }+ const record = listTriggers(vault, { now: last })[0]!;+ expect(record.occurrences).toBe(4);+ expect(record.lastSeenAt).toBe(last.toISOString());+});++test("a cooldown-blocked twin records a recurrence too, not only a suppressed one", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ transitionTrigger(vault, created[0]!.id, "dismiss", { now: NOW });+ const during = new Date(NOW.getTime() + 3 * DAY_MS);+ const blocked = createTriggers(vault, [candidate()], { now: during, cooldownDays: 7 });+ expect(blocked.skipped[0]!.reason).toBe("cooldown");+ expect(listTriggers(vault, { now: during })[0]!.occurrences).toBe(2);+});++test("a materially different cooldown key is created while the twin is suppressed", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ transitionTrigger(vault, created[0]!.id, "suppress", { now: NOW });+ const other = createTriggers(vault, [candidate({ cooldownKey: "contradiction:pref-c:pref-d" })], {+ now: NOW,+ });+ expect(other.created).toHaveLength(1);+ expect(other.created[0]!.status).toBe("pending");+});++test("dismiss then suppress then unsuppress restores the state and its cooldown", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const id = created[0]!.id;+ const dismissed = transitionTrigger(vault, id, "dismiss", { now: NOW });+ const resolvedAt = dismissed.resolvedAt;+ expect(resolvedAt).toBe(NOW.toISOString());++ const suppressed = transitionTrigger(vault, id, "suppress", {+ now: new Date(NOW.getTime() + DAY_MS),+ });+ expect(suppressed.status).toBe("suppressed");+ expect(suppressed.suppressedFrom).toBe("dismissed");+ // The resolution instant is untouched, which is what makes the restore+ // exact rather than reconstructed.+ expect(suppressed.resolvedAt).toBe(resolvedAt);++ const restored = transitionTrigger(vault, id, "unsuppress", {+ now: new Date(NOW.getTime() + 2 * DAY_MS),+ });+ expect(restored.status).toBe("dismissed");+ expect(restored.resolvedAt).toBe(resolvedAt);+ expect(restored.suppressedAt).toBeNull();+ expect(restored.suppressedFrom).toBeNull();++ // The original seven-day cooldown still measures from the original+ // resolution instant, not from the unsuppress.+ const during = createTriggers(vault, [candidate()], {+ now: new Date(NOW.getTime() + 3 * DAY_MS),+ cooldownDays: 7,+ });+ expect(during.created).toHaveLength(0);+ expect(during.skipped[0]!.reason).toBe("cooldown");+ const after = createTriggers(vault, [candidate()], {+ now: new Date(NOW.getTime() + 8 * DAY_MS),+ cooldownDays: 7,+ });+ expect(after.created).toHaveLength(1);+});++test("suppress is legal from a terminal state and is idempotent", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const id = created[0]!.id;+ transitionTrigger(vault, id, "act", { now: NOW });+ const first = transitionTrigger(vault, id, "suppress", { now: NOW });+ expect(first.suppressedFrom).toBe("acted");+ const second = transitionTrigger(vault, id, "suppress", {+ now: new Date(NOW.getTime() + DAY_MS),+ });+ expect(second.status).toBe("suppressed");+ expect(second.suppressedAt).toBe(first.suppressedAt);+ expect(second.suppressedFrom).toBe("acted");+});++test("suppress is legal from an expired trigger and unsuppress restores the stored status", () => {+ createTriggers(vault, [candidate()], { now: NOW });+ const later = new Date(NOW.getTime() + (TRIGGER_TTL_DAYS + 1) * DAY_MS);+ const expired = listTriggers(vault, { now: later })[0]!;+ expect(expired.effectiveStatus).toBe("expired");++ const suppressed = transitionTrigger(vault, expired.id, "suppress", { now: later });+ expect(suppressed.effectiveStatus).toBe("suppressed");+ // The stored status was still pending; that is what is restored, and+ // expiry is re-applied on read exactly as before.+ expect(suppressed.suppressedFrom).toBe("pending");+ const restored = transitionTrigger(vault, expired.id, "unsuppress", { now: later });+ expect(restored.status).toBe("pending");+ expect(restored.effectiveStatus).toBe("expired");+});++test("unsuppressing something that is not suppressed throws naming its status", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const id = created[0]!.id;+ expect(() => transitionTrigger(vault, id, "unsuppress", { now: NOW })).toThrow("pending");+ transitionTrigger(vault, id, "dismiss", { now: NOW });+ expect(() => transitionTrigger(vault, id, "unsuppress", { now: NOW })).toThrow("dismissed");+});++test("unsuppressing an unknown id throws", () => {+ expect(() => transitionTrigger(vault, "tr-nope", "unsuppress", { now: NOW })).toThrow("unknown");+ expect(() => transitionTrigger(vault, "tr-nope", "suppress", { now: NOW })).toThrow("unknown");+});++test("a hand-edited suppressed record with no prior status throws naming the field", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const id = created[0]!.id;+ const path = created[0]!.path;+ transitionTrigger(vault, id, "suppress", { now: NOW });+ writeFileSync(path, readFileSync(path, "utf8").replace(/^suppressed_from: .*$\n/mu, ""), "utf8");+ expect(() => transitionTrigger(vault, id, "unsuppress", { now: NOW })).toThrow("suppressed_from");+});++test("a suppressed trigger is hidden from the brief and stays out of it forever", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ transitionTrigger(vault, created[0]!.id, "suppress", { now: NOW });+ expect(briefTriggers(vault, { now: NOW, cap: 5, cooldownDays: 7 })).toHaveLength(0);+ const aYearLater = new Date(NOW.getTime() + 365 * DAY_MS);+ expect(briefTriggers(vault, { now: aYearLater, cap: 5, cooldownDays: 7 })).toHaveLength(0);+});++test("markTriggersDelivered never revives a suppressed trigger", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const id = created[0]!.id;+ transitionTrigger(vault, id, "suppress", { now: NOW });+ markTriggersDelivered(vault, [id], { now: NOW });+ expect(listTriggers(vault, { now: NOW })[0]!.status).toBe("suppressed");+});++test("suppression state round-trips through the Markdown file", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const suppressed = transitionTrigger(vault, created[0]!.id, "suppress", { now: NOW });+ const raw = readFileSync(suppressed.path, "utf8");+ expect(raw).toContain(`status: ${TRIGGER_STATUS.suppressed}`);+ expect(raw).toContain(`suppressed_at: ${NOW.toISOString()}`);+ expect(raw).toContain("suppressed_from: pending");+ expect(raw).toContain("occurrences: 1");+ expect(raw).toContain(`last_seen_at: ${NOW.toISOString()}`);+});++test("a record written before this change reads as one recorded occurrence", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const path = created[0]!.path;+ writeFileSync(+ path,+ readFileSync(path, "utf8")+ .replace(/^occurrences: .*$\n/mu, "")+ .replace(/^last_seen_at: .*$\n/mu, ""),+ "utf8",+ );+ const record = listTriggers(vault, { now: NOW })[0]!;+ expect(record.occurrences).toBe(1);+ expect(record.lastSeenAt).toBe(record.createdAt);+});++test("recordRecurrence increments the ledger and persists it", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const later = new Date(NOW.getTime() + DAY_MS);+ const next = recordRecurrence(created[0]!, later);+ expect(next.occurrences).toBe(2);+ expect(next.lastSeenAt).toBe(later.toISOString());+ expect(listTriggers(vault, { now: later })[0]!.occurrences).toBe(2);+});++// โโ Defect: a malformed grounding list must not read as an ungrounded one โโโ++test("an unparseable source-artifact list refuses instead of reading as empty", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const path = created[0]!.path;+ writeFileSync(+ path,+ readFileSync(path, "utf8").replace(/^source_artifacts: .*$/mu, 'source_artifacts: "[[pref-a"'),+ "utf8",+ );+ expect(() => listTriggers(vault, { now: NOW })).toThrow(TriggerSourceArtifactsError);+ expect(() => listTriggers(vault, { now: NOW })).toThrow("source_artifacts");+});++test("a record naming no grounding artifacts still reads as an empty list", () => {+ const result = createTriggers(vault, [candidate({ sourceArtifacts: [] })], { now: NOW });+ expect(result.created[0]!.sourceArtifacts).toEqual([]);+ expect(listTriggers(vault, { now: NOW })[0]!.sourceArtifacts).toEqual([]);+});++// โโ Defect: a corrupt recurrence field must not read as a pre-ledger record โโ+//+// Absent recurrence keys mean the record predates the ledger, and reading+// them as "one occurrence, last seen when it was created" is the true count+// of what anybody recorded. A key that is PRESENT and unreadable is a+// different claim: silently crediting it the same one occurrence would state+// a number nothing supports, and would understate a finding that has fired+// forty times. Absent and corrupt are told apart.++test("an unreadable occurrence count refuses instead of reading as a fresh record", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const path = created[0]!.path;+ writeFileSync(+ path,+ readFileSync(path, "utf8").replace(/^occurrences: .*$/mu, "occurrences: many"),+ "utf8",+ );+ expect(() => listTriggers(vault, { now: NOW })).toThrow(TriggerFieldError);+ expect(() => listTriggers(vault, { now: NOW })).toThrow("occurrences");+});++test("a negative or zero occurrence count refuses", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const path = created[0]!.path;+ writeFileSync(+ path,+ readFileSync(path, "utf8").replace(/^occurrences: .*$/mu, "occurrences: 0"),+ "utf8",+ );+ expect(() => listTriggers(vault, { now: NOW })).toThrow("occurrences");+});++test("an unreadable last-seen instant refuses instead of reading as the creation instant", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const path = created[0]!.path;+ writeFileSync(+ path,+ readFileSync(path, "utf8").replace(/^last_seen_at: .*$/mu, "last_seen_at: whenever"),+ "utf8",+ );+ expect(() => listTriggers(vault, { now: NOW })).toThrow(TriggerFieldError);+ expect(() => listTriggers(vault, { now: NOW })).toThrow("last_seen_at");+});++// โโ Defect: one corrupt record must not take the whole queue down โโโโโโโโโโโโ+//+// The field refusals above are right, but they used to leave `listTriggers` -+// which every surface reads through - and so one hand-edited file made+// `list`, `history`, the brief, delivery, creation AND every transition fail+// together. The operator could not even dismiss or suppress a healthy record+// to get out of it. A refusal now names the record it belongs to and stops+// there, and the surfaces report the naming instead of omitting the record.++const SECOND_KEY = "contradiction:pref-c:pref-d";++/** Overwrite one frontmatter line of a stored trigger. */+function rewriteLine(path: string, line: RegExp, replacement: string): void {+ writeFileSync(path, readFileSync(path, "utf8").replace(line, replacement), "utf8");+}++/** A two-record vault in which only the SECOND record is unreadable. */+function vaultWithOneCorruptSibling(): { healthyId: string; brokenPath: string } {+ const { created } = createTriggers(vault, [candidate(), candidate({ cooldownKey: SECOND_KEY })], {+ now: NOW,+ });+ expect(created).toHaveLength(2);+ const brokenPath = created[1]!.path;+ rewriteLine(brokenPath, /^occurrences: .*$/mu, "occurrences: many");+ return { healthyId: created[0]!.id, brokenPath };+}++test("a corrupt record is named and reported next to its readable siblings", () => {+ const { healthyId, brokenPath } = vaultWithOneCorruptSibling();+ const scan = readTriggers(vault, { now: NOW });+ expect(scan.records.map((r) => r.id)).toEqual([healthyId]);+ expect(scan.unreadable).toHaveLength(1);+ expect(scan.unreadable[0]!.path).toBe(brokenPath);+ expect(scan.unreadable[0]!.key).toBe("occurrences");+ expect(scan.unreadable[0]!.error.message).toContain(brokenPath);+});++test("a corrupt record leaves its healthy sibling transitionable", () => {+ const { healthyId } = vaultWithOneCorruptSibling();+ const suppressed = transitionTrigger(vault, healthyId, "suppress", { now: NOW });+ expect(suppressed.status).toBe("suppressed");+});++test("a corrupt record neither hides the brief nor blocks its delivery", () => {+ const { healthyId } = vaultWithOneCorruptSibling();+ expect(briefTriggers(vault, { now: NOW, cap: 5, cooldownDays: 7 }).map((t) => t.id)).toEqual([+ healthyId,+ ]);+ markTriggersDelivered(vault, [healthyId], { now: NOW });+ const delivered = readTriggers(vault, { now: NOW }).records.find((r) => r.id === healthyId)!;+ expect(delivered.status).toBe("delivered");+});++test("a corrupt record does not stop a scan from recording new findings", () => {+ const { brokenPath } = vaultWithOneCorruptSibling();+ const result = createTriggers(+ vault,+ [candidate({ cooldownKey: "contradiction:pref-e:pref-f" })],+ {+ now: NOW,+ },+ );+ expect(result.created).toHaveLength(1);+ expect(result.unreadable.map((u) => u.path)).toEqual([brokenPath]);+});++test("an unknown id names the records that could not be read", () => {+ vaultWithOneCorruptSibling();+ // The id may well belong to the record nobody could parse, so "unknown"+ // on its own would be a claim the store cannot support.+ expect(() => transitionTrigger(vault, "tr-nope", "dismiss", { now: NOW })).toThrow("occurrences");+});++test("the strict reader still refuses a partial view of the queue", () => {+ vaultWithOneCorruptSibling();+ expect(() => listTriggers(vault, { now: NOW })).toThrow(TriggerFieldError);+});++// โโ Defect: a missing creation instant must be refused where it originates โโ++test("a record with no creation instant is refused rather than corrupted", () => {+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const path = created[0]!.path;+ rewriteLine(path, /^created_at: .*$\n/mu, "");++ const first = readTriggers(vault, { now: NOW });+ expect(first.records).toHaveLength(0);+ expect(first.unreadable.map((u) => u.key)).toEqual(["created_at"]);++ // The old reading substituted "" and wrote it straight back as an empty+ // `last_seen_at` on the first recurrence; the next read refused THAT+ // field, so the record blamed a line the operator never touched.+ createTriggers(vault, [candidate()], { now: new Date(NOW.getTime() + DAY_MS) });+ expect(readTriggers(vault, { now: NOW }).unreadable.map((u) => u.key)).toEqual(["created_at"]);+ expect(readFileSync(path, "utf8")).toContain(`last_seen_at: ${NOW.toISOString()}`);+});++// โโ Defect: the ledger must count exactly what the documentation claims โโโโโ++test("a candidate the per-kind cap drops records a recurrence on its own record", () => {+ createTriggers(vault, [candidate()], { now: NOW });+ const later = new Date(NOW.getTime() + (TRIGGER_TTL_DAYS + 1) * DAY_MS);+ // The twin has expired, so nothing blocks recreation: the cap is what+ // silenced this candidate, and the finding did fire again.+ const result = createTriggers(+ vault,+ [candidate({ cooldownKey: "contradiction:fresh" }), candidate()],+ { now: later, maxPerKind: 1 },+ );+ expect(result.created).toHaveLength(1);+ expect(result.skipped.map((s) => s.reason)).toEqual(["kind-cap"]);+ const record = readTriggers(vault, { now: later }).records.find(+ (r) => r.cooldownKey === candidate().cooldownKey,+ )!;+ expect(record.occurrences).toBe(2);+ expect(record.lastSeenAt).toBe(later.toISOString());+});++test("one scan seeing the same finding twice is one occurrence, not two", () => {+ createTriggers(vault, [candidate()], { now: NOW });+ const later = new Date(NOW.getTime() + DAY_MS);+ const blocked = createTriggers(vault, [candidate(), candidate()], { now: later });+ expect(blocked.created).toHaveLength(0);+ expect(blocked.skipped.map((s) => s.reason)).toEqual(["active", "duplicate"]);+ expect(readTriggers(vault, { now: later }).records[0]!.occurrences).toBe(2);+});++test("the transition and delivery writers serialize on the trigger-directory lock", () => {+ // The counter used to be race-free against scans only: both of these+ // write the full record - occurrences included - from a snapshot read+ // earlier, so a scan interleaving with a suppress lost one of the two.+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const id = created[0]!.id;+ const release = lockfile.lockSync(triggersDir(vault), {+ stale: TRIGGER_LOCK_STALE_MS,+ realpath: false,+ });+ try {+ expect(() => transitionTrigger(vault, id, "dismiss", { now: NOW })).toThrow();+ expect(() => markTriggersDelivered(vault, [id], { now: NOW })).toThrow();+ } finally {+ release();+ }+ expect(readTriggers(vault, { now: NOW }).records[0]!.status).toBe("pending");+});++test("a recorded occurrence count survives a read whatever the frontmatter yields", () => {+ // Guards the number-versus-string trap: the count is written as a bare+ // integer, so a parser that materializes it as a number must not fall+ // through to the pre-ledger reading and quietly discard a real count.+ const { created } = createTriggers(vault, [candidate()], { now: NOW });+ const path = created[0]!.path;+ writeFileSync(+ path,+ readFileSync(path, "utf8").replace(/^occurrences: .*$/mu, "occurrences: 7"),+ "utf8",+ );+ expect(listTriggers(vault, { now: NOW })[0]!.occurrences).toBe(7);+});diff --git a/tests/core/brain/vault-instruction-file.test.ts b/tests/core/brain/vault-instruction-file.test.tsindex 60d75dff..03c30261 100644--- a/tests/core/brain/vault-instruction-file.test.ts+++ b/tests/core/brain/vault-instruction-file.test.ts@@ -7,7 +7,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -23,6 +23,35 @@ afterEach(() => {rmSync(vault, { recursive: true, force: true });});+/**+ * An instruction file that EXISTS and cannot be read used to answer+ * `null`, which is the same answer a vault with no instruction file+ * gives - so `brain_context` dropped the field and the operator was told+ * nothing. Absence and failure are different answers.+ */+describe("readVaultInstructionFile - an unreadable file is a failure, not an absence", () => {+ const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;++ test.skipIf(RUNNING_AS_ROOT)("throws naming the path and the reason", () => {+ const path = join(vault, "VAULT.md");+ writeFileSync(path, "# Vault\n");+ chmodSync(path, 0o000);+ try {+ let thrown: unknown;+ try {+ readVaultInstructionFile(vault);+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(Error);+ expect((thrown as Error).message).toContain(path);+ expect((thrown as Error).message.toLowerCase()).toContain("permission denied");+ } finally {+ chmodSync(path, 0o600);+ }+ });+});+describe("readVaultInstructionFile - default name", () => {test("returns null when VAULT.md is absent", () => {const r = readVaultInstructionFile(vault);diff --git a/tests/core/integrity/digest.test.ts b/tests/core/integrity/digest.test.tsnew file mode 100644index 00000000..df7f4043--- /dev/null+++ b/tests/core/integrity/digest.test.ts@@ -0,0 +1,124 @@+/**+ * The one digest encoding.+ *+ * Ten modules carried a byte-identical private SHA-256 helper and two+ * reimplemented canonical JSON serialization independently. Two units of+ * the silence-is-not-an-answer wave persist a digest into a vault that is+ * replicated peer-to-peer, and persisted formats in this project are+ * additive-only - so two encodings shipped in one release could never be+ * reconciled afterwards.+ *+ * These tests pin the encoding rather than describe it: the expected hex+ * values are the ones the absorbed helpers already produced, so a change+ * to this module that would have silently re-keyed existing records fails+ * here instead.+ */++import { createHash } from "node:crypto";++import { describe, expect, test } from "bun:test";++import { canonicalJson, sha256Hex } from "../../../src/core/integrity/digest.ts";++/** Independently recomputed, so the test does not restate the implementation. */+function referenceSha256(input: string | Uint8Array): string {+ return createHash("sha256").update(input).digest("hex");+}++describe("sha256Hex", () => {+ test("pins the empty-string digest", () => {+ expect(sha256Hex("")).toBe("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");+ });++ test("agrees with the absorbed helpers, which passed an explicit utf8 encoding", () => {+ // Seven of the ten call sites wrote `.update(text, "utf8")` and three+ // wrote `.update(text)`. For a string argument those are the same call;+ // this asserts it rather than assuming it, because the two spellings are+ // now one function and a divergence would re-key persisted records.+ for (const sample of ["", "a", "schema_version: 1\n", " leading and trailing "]) {+ expect(sha256Hex(sample)).toBe(createHash("sha256").update(sample, "utf8").digest("hex"));+ expect(sha256Hex(sample)).toBe(createHash("sha256").update(sample).digest("hex"));+ }+ });++ test("hashes a string and its utf8 bytes identically", () => {+ const text = "one pack, two states";+ expect(sha256Hex(text)).toBe(sha256Hex(new TextEncoder().encode(text)));+ });++ test("is stable over non-Latin text and treats it as opaque bytes", () => {+ // No natural-language handling anywhere in the digest path: the only+ // property asserted is that the same bytes give the same digest and+ // different bytes do not.+ const samples = ["ะฟัะฐะฒะธะปะพ ะพะฟะตัะฐัะพัะฐ", "้็จ่ ใฎ่ฆๅ", "ูุงุนุฏุฉ ุงูู ุดุบู", "rรจgle de l'opรฉrateur"];+ for (const sample of samples) {+ expect(sha256Hex(sample)).toBe(referenceSha256(sample));+ expect(sha256Hex(sample)).toHaveLength(64);+ }+ expect(new Set(samples.map((s) => sha256Hex(s))).size).toBe(samples.length);+ });++ test("distinguishes inputs that differ only in trailing whitespace", () => {+ expect(sha256Hex("body")).not.toBe(sha256Hex("body\n"));+ });++ test("accepts bytes that are not valid utf8", () => {+ const bytes = new Uint8Array([0xff, 0xfe, 0x00, 0x01]);+ expect(sha256Hex(bytes)).toBe(referenceSha256(bytes));+ });+});++describe("canonicalJson", () => {+ test("sorts object keys recursively", () => {+ expect(canonicalJson({ b: 1, a: { d: 2, c: 3 } })).toBe('{"a":{"c":3,"d":2},"b":1}');+ });++ test("is insensitive to key order and sensitive to content", () => {+ expect(canonicalJson({ x: 1, y: 2 })).toBe(canonicalJson({ y: 2, x: 1 }));+ expect(canonicalJson({ x: 1, y: 2 })).not.toBe(canonicalJson({ x: 1, y: 3 }));+ });++ test("keeps array order", () => {+ expect(canonicalJson([3, 1, 2])).toBe("[3,1,2]");+ expect(canonicalJson([1, 2])).not.toBe(canonicalJson([2, 1]));+ });++ test("omits object entries whose value is undefined", () => {+ // This is the semantic the persisted-ledger copy already had, and it is+ // the one that matches how JSON.stringify treats an object entry.+ expect(canonicalJson({ a: 1, b: undefined })).toBe('{"a":1}');+ expect(canonicalJson({ a: 1, b: undefined })).toBe(canonicalJson({ a: 1 }));+ });++ test("renders undefined inside an array as null, as JSON does", () => {+ expect(canonicalJson([1, undefined, 2])).toBe("[1,null,2]");+ });++ test("renders a bare undefined as null rather than returning undefined", () => {+ expect(canonicalJson(undefined)).toBe("null");+ expect(canonicalJson(null)).toBe("null");+ });++ test("escapes keys and values through JSON.stringify", () => {+ expect(canonicalJson({ 'a"b': "c\nd" })).toBe('{"a\\"b":"c\\nd"}');+ });++ test("agrees with the two absorbed copies on inputs both could reach", () => {+ // The bench-fixture copy rendered an undefined entry as null and the+ // ledger copy omitted it. Every parser feeding the bench copy builds its+ // objects with a conditional spread, so no undefined entry was reachable+ // and the two copies agreed on everything they were ever given.+ const reachable = {+ name: "fixture",+ questions: [{ id: "q1", category: "recall" }],+ notes: [{ path: "a.md", body: "x" }],+ };+ expect(canonicalJson(reachable)).toBe(+ '{"name":"fixture","notes":[{"body":"x","path":"a.md"}],"questions":[{"category":"recall","id":"q1"}]}',+ );+ });++ test("is a stable hash input across key order", () => {+ expect(sha256Hex(canonicalJson({ b: 1, a: 2 }))).toBe(sha256Hex(canonicalJson({ a: 2, b: 1 })));+ });+});diff --git a/tests/fixtures/cron-recipe/search-reindex-30m.txt b/tests/fixtures/cron-recipe/search-reindex-30m.txtnew file mode 100644index 00000000..2a411d30--- /dev/null+++ b/tests/fixtures/cron-recipe/search-reindex-30m.txt@@ -0,0 +1,57 @@+# ----------------------------------------------------------------------+# Open Second Brain - periodic reindex template+# interval: 30 minutes+#+# Pick ONE of the three paths below. The watchdog script is the+# common piece; both crontab and Hermes-cron rely on it.+# ----------------------------------------------------------------------+++## 1. Watchdog script - save to ~/.local/bin/osb-reindex.sh+## (then chmod +x). Sources ~/.hermes/.env if present so the+## embedding API key lands in the environment.++cat >~/.local/bin/osb-reindex.sh <<'OSBEOF'+#!/usr/bin/env bash+set -euo pipefail++# Pick up OPEN_SECOND_BRAIN_EMBEDDING_* from the Hermes env file+# if it exists. Other env files can be appended below.+if [[ -f "$HOME/.hermes/.env" ]]; then+ set -a; . "$HOME/.hermes/.env"; set +a+fi++out=$(o2b search reindex --embeddings --json)+# Emit the JSON line only when the reindex actually changed+# something. jq is preferred; fall back to grep when missing.+if command -v jq >/dev/null 2>&1; then+ changed=$(printf "%s" "$out" | jq -r ".stats.added + .stats.updated + .stats.deleted")+ if [ "$changed" != "0" ] && [ -n "$changed" ]; then+ printf "%s\n" "$out"+ fi+else+ if printf "%s" "$out" | grep -Eq '"(added|updated|deleted)"[[:space:]]*:[[:space:]]*[1-9]'; then+ printf "%s\n" "$out"+ fi+fi+OSBEOF+chmod +x ~/.local/bin/osb-reindex.sh+++## 2. Native crontab - open 'crontab -e' and append:++*/30 * * * * ~/.local/bin/osb-reindex.sh+++## 3. Hermes cron (preferred when Hermes is the embedding owner):++hermes cron create \+ --name osb-reindex \+ --schedule '*/30 * * * *' \+ --command "$HOME/.local/bin/osb-reindex.sh" \+ --no-agent+++# ----------------------------------------------------------------------+# After install, verify with: o2b search status+# ----------------------------------------------------------------------diff --git a/tests/helpers/run-cli.ts b/tests/helpers/run-cli.tsindex 1a6adedf..486ac22d 100644--- a/tests/helpers/run-cli.ts+++ b/tests/helpers/run-cli.ts@@ -81,6 +81,23 @@ function resolveEnv(callerEnv: Record<string, string>): {return { env, cleanupDir };}+/**+ * The current directory, or null when the process no longer has one.+ *+ * `process.cwd()` throws ENOENT once the directory it names is deleted,+ * which happens routinely in a suite that chdirs into temp vaults and+ * removes them. A run does not need to know where it started to work; only+ * the restore does, and it can honestly do nothing when there is nowhere+ * to return to.+ */+function currentDirectoryOrNull(): string | null {+ try {+ return process.cwd();+ } catch {+ return null;+ }+}+/** A `process.stdout.write`-shaped sink that appends decoded chunks to `sink`. */function captureWrite(sink: (s: string) => void) {return (chunk: unknown, ...rest: unknown[]): boolean => {@@ -128,43 +145,95 @@ async function runCliSubprocess(* uncaught throw is mapped to code 1 with the message on stderr, matching how a* crashing child process would surface.*/+/**+ * In-process runs mutate process-wide state - the environment, the working+ * directory, and both output streams - and restore it in a `finally`. Two+ * overlapping runs therefore capture each otherโs swapped state as their+ * "saved" state and restore the wrong thing, which leaves a test-scoped+ * config path installed for the rest of the process and misroutes captured+ * output. The corruption surfaces far away, in an unrelated later file, as+ * a vault that cannot be found.+ *+ * So overlapping is refused rather than survived. A caller that genuinely+ * needs concurrency passes `subprocess: true`, which owns none of this+ * state.+ */+let inProcessRunActive = false;++/** Thrown when a second in-process CLI run starts while one is still open. */+export class ConcurrentInProcessRunError extends Error {+ constructor(args: ReadonlyArray<string>) {+ super(+ `runCli(${JSON.stringify(args)}) started while another in-process run was ` ++ "still open. In-process runs swap process.env, the working directory and " ++ "both output streams, so they cannot overlap: await each run, or pass " ++ "{ subprocess: true } for the ones that must run concurrently.",+ );+ this.name = "ConcurrentInProcessRunError";+ }+}+async function runCliInProcess(args: ReadonlyArray<string>,opts: RunCliOptions,): Promise<RunResult> {- const { env, cleanupDir } = resolveEnv(opts.env ?? {});- const savedEnv = process.env;- const savedCwd = process.cwd();+ if (inProcessRunActive) throw new ConcurrentInProcessRunError(args);+ inProcessRunActive = true;+ // Everything from here to the outer `finally` runs under the flag,+ // setup included. An earlier version claimed the flag only while the CLI+ // itself ran, which left `resolveEnv` and `process.cwd()` outside it -+ // and `process.cwd()` throws ENOENT when the directory a test removed is+ // still the process's own, which is routine in a suite that builds and+ // deletes temp vaults. A throw there left the flag raised for the rest of+ // the process and every later run failed blaming a concurrency that never+ // happened, which is the same misdirected report this guard exists to+ // stop.+ let savedEnv: NodeJS.ProcessEnv | null = null;+ let savedCwd: string | null = null;+ let realOut: typeof process.stdout.write | null = null;+ let realErr: typeof process.stderr.write | null = null;+ let cleanupDir: string | null = null;let stdout = "";let stderr = "";- const realOut = process.stdout.write.bind(process.stdout);- const realErr = process.stderr.write.bind(process.stderr);- process.env = env;- try {- process.chdir(opts.cwd ?? ROOT);- } catch {- // A caller cwd that does not exist would also fail a subprocess spawn.- }- process.stdout.write = captureWrite((s) => (stdout += s)) as typeof process.stdout.write;- process.stderr.write = captureWrite((s) => (stderr += s)) as typeof process.stderr.write;- let returncode: number;try {- returncode = await main(args);- } catch (err) {- stderr += `${(err as Error)?.stack ?? String(err)}\n`;- returncode = 1;- } finally {- process.stdout.write = realOut;- process.stderr.write = realErr;- process.env = savedEnv;+ const resolved = resolveEnv(opts.env ?? {});+ cleanupDir = resolved.cleanupDir;+ savedEnv = process.env;+ // A cwd that no longer exists is not an error here: the run is about to+ // chdir anyway, and only the restore needs somewhere to go back to.+ savedCwd = currentDirectoryOrNull();+ realOut = process.stdout.write.bind(process.stdout);+ realErr = process.stderr.write.bind(process.stderr);+ process.env = resolved.env;try {- process.chdir(savedCwd);+ process.chdir(opts.cwd ?? ROOT);} catch {- /* restore best-effort */+ // A caller cwd that does not exist would also fail a subprocess spawn.+ }+ process.stdout.write = captureWrite((s) => (stdout += s)) as typeof process.stdout.write;+ process.stderr.write = captureWrite((s) => (stderr += s)) as typeof process.stderr.write;+ let returncode: number;+ try {+ returncode = await main(args);+ } catch (err) {+ stderr += `${(err as Error)?.stack ?? String(err)}\n`;+ returncode = 1;+ }+ return { stdout, stderr, returncode };+ } finally {+ if (realOut !== null) process.stdout.write = realOut;+ if (realErr !== null) process.stderr.write = realErr;+ if (savedEnv !== null) process.env = savedEnv;+ if (savedCwd !== null) {+ try {+ process.chdir(savedCwd);+ } catch {+ /* restore best-effort */+ }}if (cleanupDir !== null) rmSync(cleanupDir, { recursive: true, force: true });+ inProcessRunActive = false;}- return { stdout, stderr, returncode };}export async function runCli(diff --git a/tests/hooks/active-inject.test.ts b/tests/hooks/active-inject.test.tsindex f871b621..20afe636 100644--- a/tests/hooks/active-inject.test.ts+++ b/tests/hooks/active-inject.test.ts@@ -67,6 +67,12 @@ function writeLessons(body: string): void {writeFileSync(join(vault, "Brain", "lessons.md"), body, "utf8");}+function writeStandingRules(body: string): string {+ const path = join(vault, "Brain", "standing-rules.md");+ writeFileSync(path, body, "utf8");+ return path;+}+describe("active-inject hook", () => {test("injects active.md content as SessionStart additionalContext", async () => {writeActive(@@ -399,3 +405,148 @@ describe("active-inject hook: _brain.yaml absent vs. unreadable", () => {expect(injected).not.toContain(CONFIG_NOTICE);});});++/**+ * Operator standing rules at the head of the preamble+ * (silence-is-not-an-answer, U8).+ *+ * The block is read OUTSIDE the fail-open memory load and before it, and+ * that one placement is what gives it every property asserted here: it+ * leads the payload, it is never charged against the injection budget, a+ * memory-layer failure cannot take it down, and - because it never+ * enters the inject cache - a stale constitution can never be served+ * from disk in place of the live one.+ */+describe("active-inject hook: operator standing rules", () => {+ const ACTIVE_DOC =+ "---\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 RULES = "Never force-push to main.\nAsk before deleting anything under Archive/.";+ const HEADER = "## Operator standing rules";+ const CAP_NOTICE = "Standing rules truncated";++ async function inject(env: Record<string, string> = {}): Promise<string> {+ const r = await runHook({ hook_event_name: "SessionStart" }, { VAULT_DIR: vault, ...env });+ expect(r.exit).toBe(0);+ expect(r.stderr).toBe("");+ return JSON.parse(r.stdout).hookSpecificOutput.additionalContext as string;+ }++ test("the preamble starts with the standing-rules header and the operator text", async () => {+ writeActive(ACTIVE_DOC);+ writeStandingRules(RULES);+ const injected = await inject();+ expect(injected.startsWith(HEADER)).toBe(true);+ expect(injected).toContain(RULES);+ expect(injected.indexOf(RULES)).toBeLessThan(injected.indexOf("pref-foo"));+ });++ test("absent rules file leaves the payload exactly as it was", async () => {+ writeActive(ACTIVE_DOC);+ const injected = await inject();+ expect(injected).not.toContain(HEADER);+ expect(injected).toContain("pref-foo");+ });++ test("with no active memory file the block is still emitted", async () => {+ writeStandingRules(RULES);+ const injected = await inject();+ expect(injected.startsWith(HEADER)).toBe(true);+ expect(injected.endsWith(RULES)).toBe(true);+ });++ test("memory assembly throwing with no cache still emits the block, exit zero", async () => {+ // A directory where active.md belongs makes the assembly throw, and+ // this vault has never injected successfully, so the fail-open loader+ // has nothing to degrade to. The constitution must survive that.+ mkdirSync(join(vault, "Brain", "active.md"));+ writeStandingRules(RULES);+ const r = await runHook({ hook_event_name: "SessionStart" }, { VAULT_DIR: vault });+ expect(r.exit).toBe(0);+ const injected: string = JSON.parse(r.stdout).hookSpecificOutput.additionalContext;+ expect(injected.startsWith(HEADER)).toBe(true);+ expect(injected.endsWith(RULES)).toBe(true);+ expect(injected).not.toContain("pref-foo");+ });++ test("neither standing rules nor memory keeps the hook silent", async () => {+ const r = await runHook({ hook_event_name: "SessionStart" }, { VAULT_DIR: vault });+ expect(r.exit).toBe(0);+ expect(r.stdout).toBe("");+ });++ test("the block is exempt from the injection budget at its minimum", async () => {+ // Budget pinned at its floor and a rules file far larger than it: the+ // operator's block is emitted whole and only the memory body carries+ // a truncation notice.+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\nactive:\n inject_budget_chars: 500\n standing_rules_max_chars: 100000\n",+ "utf8",+ );+ const bigRules = Array.from({ length: 200 }, (_, i) => `Standing rule number ${i}.`).join("\n");+ writeStandingRules(bigRules);+ const rules = Array.from(+ { length: 60 },+ (_, i) => `- \`pref-rule-${i}\` โ Rule ${i} body`,+ ).join("\n");+ writeActive(+ `---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (60)\n\n${rules}\n`,+ );++ const injected = await inject();+ // Whole, byte for byte, despite being far over the 500-char budget.+ expect(injected).toContain(bigRules);+ expect(injected).not.toContain(CAP_NOTICE);+ // The memory body is the only thing that was cut.+ expect(injected).toContain("Injection truncated to budget");+ const memory = injected.slice(injected.indexOf("# Active Brain Preferences"));+ expect(memory.length).toBeLessThanOrEqual(800);+ });++ test("an over-cap rules file is capped loudly and still leads the payload", async () => {+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\nactive:\n standing_rules_max_chars: 200\n",+ "utf8",+ );+ const path = writeStandingRules(+ Array.from({ length: 100 }, (_, i) => `Standing rule number ${i}.`).join("\n"),+ );+ writeActive(ACTIVE_DOC);+ const injected = await inject();+ expect(injected.startsWith(HEADER)).toBe(true);+ expect(injected).toContain(CAP_NOTICE);+ expect(injected).toContain(path);+ expect(injected).toContain("pref-foo");+ });++ test("standing rules precede the runtime notices", async () => {+ writeActive(ACTIVE_DOC);+ writeStandingRules(RULES);+ const injected = await inject({ OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "true" });+ expect(injected.startsWith(HEADER)).toBe(true);+ expect(injected).toContain("Runtime notices:");+ expect(injected.indexOf(HEADER)).toBeLessThan(injected.indexOf("Runtime notices:"));+ expect(injected.indexOf("Runtime notices:")).toBeLessThan(injected.indexOf("pref-foo"));+ });++ test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(+ "an unreadable rules file is announced, never silently dropped",+ async () => {+ writeActive(ACTIVE_DOC);+ const path = writeStandingRules(RULES);+ chmodSync(path, 0o000);+ try {+ const injected = await inject();+ expect(injected.startsWith(HEADER)).toBe(true);+ expect(injected).toContain(path);+ expect(injected).toContain("No standing rules are in force this session");+ // Not fatal: the memory layer still reaches the session.+ expect(injected).toContain("pref-foo");+ } finally {+ chmodSync(path, 0o600);+ }+ },+ );+});diff --git a/tests/mcp/brain-context-standing-rules.test.ts b/tests/mcp/brain-context-standing-rules.test.tsnew file mode 100644index 00000000..b9d90558--- /dev/null+++ b/tests/mcp/brain-context-standing-rules.test.ts@@ -0,0 +1,229 @@+/**+ * `brain_context` is the second return path for the operator's standing+ * rules (silence-is-not-an-answer, U8): runtimes without a SessionStart+ * hook pull the same preamble through this tool, so the constitution has+ * to lead the content here exactly as it leads the injected payload.+ *+ * The envelope extension follows the `vault_instruction` precedent -+ * absent file means the field is omitted so hosts that strip unknown+ * fields stay byte-identical.+ *+ * The suite also pins the vault-instruction defect this unit closed: a+ * configuration error in the instruction-file setting used to be+ * swallowed into `null`, so the field simply vanished and the operator+ * was told nothing at all.+ */++import { afterEach, beforeEach, describe, 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 { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { STANDING_RULES_HEADER } from "../../src/core/brain/standing-rules.ts";++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;+const savedEnv: Record<string, string | undefined> = {};++const RULES = "Never force-push to main.\nAsk before deleting anything under Archive/.";+const RULES_REL = "Brain/standing-rules.md";++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-standing-"));+ vault = join(tmp, "vault");+ for (const dir of ["preferences", "retired", "inbox", "log"]) {+ mkdirSync(join(vault, "Brain", dir), { recursive: true });+ }+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-standing-cfg-"));+ configPath = join(configHome, "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;+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "standing-rules-test", version: "0" },+ },+ });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ });+}++async function callContext(): Promise<Record<string, unknown>> {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 9,+ method: "tools/call",+ params: { name: "brain_context", arguments: {} },+ })) as { result: { content: ReadonlyArray<{ type: string; text: string }> } };+ return JSON.parse(r.result.content[0]!.text);+}++function writeRules(body: string): void {+ writeFileSync(join(vault, "Brain", "standing-rules.md"), body, "utf8");+}++interface StandingRulesField {+ readonly path: string;+ readonly content: string;+ readonly truncated: boolean;+}++describe("brain_context standing_rules field", () => {+ test("absent file: the envelope OMITS standing_rules and the content is untouched", async () => {+ const out = await callContext();+ expect("standing_rules" in out).toBe(false);+ expect(out["content"]).not.toContain(STANDING_RULES_HEADER);+ });++ test("present file: path, content and truncated are reported", async () => {+ writeRules(RULES);+ const out = await callContext();+ const field = out["standing_rules"] as StandingRulesField;+ expect(field.path).toBe(RULES_REL);+ expect(field.content).toBe(RULES);+ expect(field.truncated).toBe(false);+ });++ test("present file: the block leads the returned content", async () => {+ writeRules(RULES);+ const content = (await callContext())["content"] as string;+ expect(content.startsWith(STANDING_RULES_HEADER)).toBe(true);+ expect(content).toContain(RULES);+ expect(content.indexOf(RULES)).toBeLessThan(content.indexOf("Active Brain Preferences"));+ });++ test("the block precedes the pinned-context append", async () => {+ writeRules(RULES);+ writeFileSync(join(vault, "Brain", "pinned.md"), "Deploy window is Tuesday.\n", "utf8");+ const content = (await callContext())["content"] as string;+ expect(content.startsWith(STANDING_RULES_HEADER)).toBe(true);+ expect(content.indexOf(RULES)).toBeLessThan(content.indexOf("Pinned context"));+ });++ test("an over-cap file reports truncated and carries the loud notice", async () => {+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\nactive:\n standing_rules_max_chars: 200\n",+ );+ writeRules(Array.from({ length: 100 }, (_, i) => `Standing rule number ${i}.`).join("\n"));+ const out = await callContext();+ const field = out["standing_rules"] as StandingRulesField;+ expect(field.truncated).toBe(true);+ expect(field.content.length).toBeLessThanOrEqual(200);+ expect(out["content"]).toContain("Standing rules truncated");+ });++ test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(+ "the branch that reports Brain/ as absent still says why the rules are unavailable",+ async () => {+ // A vault directory the process cannot traverse makes `existsSync`+ // answer false for `Brain/`, which is the one return path that used+ // to fire before the standing-rules read: it handed back+ // `present: false` and an empty body with nothing saying that the+ // constitution had not been consulted.+ writeRules(RULES);+ chmodSync(vault, 0o000);+ try {+ const out = await callContext();+ expect(out["present"]).toBe(false);+ const content = out["content"] as string;+ expect(content).toContain(STANDING_RULES_HEADER);+ expect(content).toContain("UNAVAILABLE");+ // No record to report for bytes nobody could read.+ expect("standing_rules" in out).toBe(false);+ } finally {+ chmodSync(vault, 0o755);+ }+ },+ );++ test("the prefix survives the branch that zeroes the content", async () => {+ // A directory where active.md belongs makes the regenerate/read arm+ // fail, which is the branch that used to hand back an empty body.+ // The constitution must still reach the caller.+ writeRules(RULES);+ mkdirSync(join(vault, "Brain", "active.md"));+ const out = await callContext();+ expect(out["error"]).toBeDefined();+ const content = out["content"] as string;+ expect(content.startsWith(STANDING_RULES_HEADER)).toBe(true);+ expect(content).toContain(RULES);+ expect((out["standing_rules"] as StandingRulesField).content).toBe(RULES);+ });+});++/**+ * Defect closed alongside U8: `brain_context` swallowed every throw out+ * of `readVaultInstructionFile` into `null`, so the field simply+ * vanished from the response and the operator was told nothing. The+ * reachable case is an instruction file that EXISTS and cannot be read -+ * the reader itself used to answer that with `null` too, which put a+ * permission error and a vault with no instruction file on the same+ * wire. Both layers now speak.+ */+describe("brain_context surfaces vault-instruction read failures", () => {+ const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;++ test("a healthy vault reports no instruction error", async () => {+ writeFileSync(join(vault, "VAULT.md"), "# Project context\n");+ const out = await callContext();+ expect("vault_instruction_error" in out).toBe(false);+ expect(out["vault_instruction"]).toBeDefined();+ });++ test("an absent instruction file reports neither the field nor an error", async () => {+ const out = await callContext();+ expect("vault_instruction" in out).toBe(false);+ expect("vault_instruction_error" in out).toBe(false);+ });++ test.skipIf(RUNNING_AS_ROOT)(+ "an unreadable instruction file is named, not reported as absent",+ async () => {+ const path = join(vault, "VAULT.md");+ writeFileSync(path, "# Project context\n");+ chmodSync(path, 0o000);+ try {+ const out = await callContext();+ expect("vault_instruction" in out).toBe(false);+ const message = out["vault_instruction_error"] as string;+ expect(message).toContain(path);+ expect(message.toLowerCase()).toContain("permission denied");+ // Best-effort enrichment: the rest of the envelope still resolves.+ expect(out["present"]).toBe(true);+ expect(out["content"]).toContain("Active Brain Preferences");+ } finally {+ chmodSync(path, 0o600);+ }+ },+ );+});diff --git a/tests/mcp/brain-standing-rules-uneditable.test.ts b/tests/mcp/brain-standing-rules-uneditable.test.tsnew file mode 100644index 00000000..87522a26--- /dev/null+++ b/tests/mcp/brain-standing-rules-uneditable.test.ts@@ -0,0 +1,240 @@+/**+ * `Brain/standing-rules.md` is uneditable by inheritance, and this suite+ * is the assertion rather than the mechanism.+ *+ * The file lives under the Brain machinery root, whose first path+ * segment {@link resolveNoteTarget} refuses outright, and all four+ * caller-named write tools - `brain_create_note`, `brain_update_note`,+ * `brain_append_note`, `brain_write_batch` - resolve their target+ * through that one envelope. Choosing the directory was the entire+ * enforcement decision; what is left to prove is that the four really do+ * share the envelope and that the on-disk bytes survive the attempt.+ *+ * The scope of the claim is stated honestly in `standing-rules.ts`: this+ * is the caller-named write class, which is the boundary the write-site+ * census maintains. It is not a claim that no module in this process can+ * open the file.+ *+ * The last case is the other half of the property: a tool table that+ * NAMED the file - in a tool name, a description, or an input-schema+ * property description - would be advertising a target the envelope then+ * refuses, which is how an agent learns to keep trying.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { buildToolTable } from "../../src/mcp/tools.ts";+import { CreateNoteError, resolveNoteTarget } from "../../src/core/brain/notes/create-note.ts";+import {+ assertStandingRulesNotTargeted,+ StandingRulesWriteRefusedError,+} from "../../src/core/brain/standing-rules.ts";+import { BRAIN_STANDING_RULES_FILE } from "../../src/core/brain/path-constants.ts";++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;+const savedEnv: Record<string, string | undefined> = {};++const RULES_REL = `Brain/${BRAIN_STANDING_RULES_FILE}`;+const RULES_BYTES = "Never force-push to main.\nAsk before deleting anything under Archive/.\n";++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-standing-uneditable-"));+ vault = join(tmp, "vault");+ for (const dir of ["preferences", "retired", "inbox", "log"]) {+ mkdirSync(join(vault, "Brain", dir), { recursive: true });+ }+ writeFileSync(join(vault, "Brain", "_brain.yaml"), "schema_version: 1\n");+ writeFileSync(join(vault, RULES_REL), RULES_BYTES, "utf8");+ configHome = mkdtempSync(join(tmpdir(), "o2b-standing-uneditable-cfg-"));+ configPath = join(configHome, "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;+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++interface CallOutcome {+ readonly error?: { readonly message?: string };+ readonly result?: { readonly isError?: boolean; readonly content?: ReadonlyArray<unknown> };+}++async function callTool(name: string, args: Record<string, unknown>): Promise<CallOutcome> {+ const server = new MCPServer({ vault, configPath });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "uneditable-test", version: "0" },+ },+ });+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });+ return (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/call",+ params: { name, arguments: args },+ })) as CallOutcome;+}++/** Serialized response text, whichever channel the refusal came back on. */+function outcomeText(out: CallOutcome): string {+ return JSON.stringify(out);+}++function onDiskBytes(): string {+ return readFileSync(join(vault, RULES_REL), "utf8");+}++/** The four tools that address a note by a path the caller names. */+const CALLER_NAMED_WRITE_TOOLS: ReadonlyArray<{+ readonly tool: string;+ readonly args: Record<string, unknown>;+}> = Object.freeze([+ { tool: "brain_create_note", args: { path: RULES_REL, content: "OVERWRITTEN" } },+ { tool: "brain_update_note", args: { path: RULES_REL, content: "OVERWRITTEN" } },+ { tool: "brain_append_note", args: { path: RULES_REL, content: "OVERWRITTEN" } },+ {+ tool: "brain_write_batch",+ args: { operations: [{ op: "update_note", path: RULES_REL, content: "OVERWRITTEN" }] },+ },+]);++describe("Brain/standing-rules.md is uneditable through every caller-named write tool", () => {+ for (const { tool, args } of CALLER_NAMED_WRITE_TOOLS) {+ test(`${tool} refuses the path and leaves the bytes unchanged`, async () => {+ const out = await callTool(tool, args);+ const text = outcomeText(out);+ // Refused, however this tool reports refusals, and refused for the+ // REASON that makes the file safe rather than for an incidental one.+ expect(text).not.toContain("OVERWRITTEN");+ expect(text).toContain(RULES_REL);+ expect(text).toContain("Brain machinery root");+ // And the file the operator wrote is byte-for-byte what it was.+ expect(onDiskBytes()).toBe(RULES_BYTES);+ });+ }++ test("the note-target resolver refuses the path with the excluded code", () => {+ let thrown: unknown;+ try {+ resolveNoteTarget(vault, RULES_REL);+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(CreateNoteError);+ expect((thrown as CreateNoteError).code).toBe("excluded");+ expect((thrown as CreateNoteError).message).toContain(RULES_REL);+ });++ test("no tool name, description, or schema property description mentions the file", () => {+ const offenders: string[] = [];+ for (const tool of buildToolTable("full")) {+ const places: Array<[string, string]> = [+ [`${tool.name} (name)`, tool.name],+ [`${tool.name} (description)`, tool.description],+ ];+ for (const [label, text] of places) {+ if (text.includes(BRAIN_STANDING_RULES_FILE)) offenders.push(label);+ }+ for (const [prop, description] of schemaDescriptions(tool.inputSchema)) {+ if (description.includes(BRAIN_STANDING_RULES_FILE)) {+ offenders.push(`${tool.name}.${prop}`);+ }+ }+ }+ expect(offenders).toEqual([]);+ });+});++/**+ * The one caller-named write surface that does NOT go through+ * `resolveNoteTarget`: `brain_labels` resolves its path with+ * `resolveNotePath`, which checks containment and symlinks and nothing+ * else, and `assignNoteLabel` then rewrites frontmatter with overwrite -+ * so the inherited refusal did not cover it and an agent could mint the+ * dimension it needed itself. The guard below is named and narrow: it+ * refuses this one path, and it says which file it is protecting.+ */+describe("brain_labels cannot rewrite the standing-rules file", () => {+ const LABEL_ATTEMPTS: ReadonlyArray<Record<string, unknown>> = Object.freeze([+ { operation: "assign", path: RULES_REL, dimension: "status", value: "draft" },+ { operation: "remove", path: RULES_REL, dimension: "status" },+ ]);++ for (const args of LABEL_ATTEMPTS) {+ test(`${String(args["operation"])} is refused and the bytes survive`, async () => {+ const out = await callTool("brain_labels", args);+ // An ERROR, not a result: `remove` used to succeed vacuously on a+ // file with no labels, which reported the path back as if the tool+ // had operated on it. And the message has to NAME the file, so a+ // vocabulary complaint cannot pass for this refusal.+ expect(out.result).toBeUndefined();+ expect(out.error?.message ?? "").toContain(BRAIN_STANDING_RULES_FILE);+ expect(onDiskBytes()).toBe(RULES_BYTES);+ });+ }++ test("the guard refuses the path directly and names the file", () => {+ let thrown: unknown;+ try {+ assertStandingRulesNotTargeted(vault, RULES_REL, "test surface");+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(StandingRulesWriteRefusedError);+ expect((thrown as Error).message).toContain(BRAIN_STANDING_RULES_FILE);+ });++ test("the guard lets every other note through", () => {+ // Narrow by construction: several legitimate callers write into+ // `Brain/` through the same resolver (marker write-back, tombstones,+ // temporal replace), so this guard names one file and no directory.+ expect(() =>+ assertStandingRulesNotTargeted(vault, "Brain/preferences/pref-x.md", "test surface"),+ ).not.toThrow();+ });+});++/**+ * Every `description` string reachable from an input schema, paired with+ * the property path that carries it. Walks nested objects and array+ * items rather than only the top level, because a batch tool hides its+ * per-operation properties one level down.+ */+function schemaDescriptions(schema: unknown, path = ""): Array<[string, string]> {+ if (typeof schema !== "object" || schema === null) return [];+ const out: Array<[string, string]> = [];+ const node = schema as Record<string, unknown>;+ const description = node["description"];+ if (typeof description === "string" && path.length > 0) out.push([path, description]);+ const properties = node["properties"];+ if (typeof properties === "object" && properties !== null) {+ for (const [key, value] of Object.entries(properties)) {+ out.push(...schemaDescriptions(value, path.length > 0 ? `${path}.${key}` : key));+ }+ }+ out.push(...schemaDescriptions(node["items"], path.length > 0 ? `${path}[]` : "[]"));+ return out;+}diff --git a/tests/mcp/brain-trigger-tool.test.ts b/tests/mcp/brain-trigger-tool.test.tsindex 528d190c..54c0463d 100644--- a/tests/mcp/brain-trigger-tool.test.ts+++ b/tests/mcp/brain-trigger-tool.test.ts@@ -4,12 +4,12 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { createTriggers } from "../../src/core/brain/triggers/store.ts";-import type { InsightCandidate } from "../../src/core/brain/triggers/types.ts";+import { TRIGGER_STATUSES, type InsightCandidate } from "../../src/core/brain/triggers/types.ts";import { buildToolTable, findTool } from "../../src/mcp/tools.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";@@ -106,6 +106,105 @@ test("brain_brief view=morning surfaces pending triggers once per cooldown", asyexpect(second.text).not.toContain("Pending triggers");});+test("the tool's status enum is the shared status list, not a copy of it", () => {+ // The literal copy this replaces let a new status be accepted by the+ // handler's guard and rejected by the schema, with nothing failing.+ const schema = tool("brain_trigger").inputSchema as {+ properties: {+ status: { enum: string[] };+ operation: { enum: string[] };+ };+ };+ expect(schema.properties.status.enum).toEqual([...TRIGGER_STATUSES]);+ expect(schema.properties.operation.enum).toContain("suppress");+ expect(schema.properties.operation.enum).toContain("unsuppress");+});++test("brain_trigger suppress hides the trigger from list and shows it in history", async () => {+ const { created } = createTriggers(vault, [CANDIDATE], { now: NOW });+ const id = created[0]!.id;++ const suppressed = (await tool("brain_trigger").handler(ctx, {+ operation: "suppress",+ id,+ })) as { trigger: Record<string, unknown> };+ expect(suppressed.trigger["status"]).toBe("suppressed");+ expect(suppressed.trigger["suppressed_from"]).toBe("pending");+ expect(suppressed.trigger["occurrences"]).toBe(1);+ expect(suppressed.trigger["last_seen_at"]).toEqual(expect.any(String));++ const listed = (await tool("brain_trigger").handler(ctx, { operation: "list" })) as {+ triggers: Array<{ id: string }>;+ };+ expect(listed.triggers).toHaveLength(0);++ const history = (await tool("brain_trigger").handler(ctx, { operation: "history" })) as {+ triggers: Array<{ id: string }>;+ };+ expect(history.triggers.map((t) => t.id)).toEqual([id]);++ const restored = (await tool("brain_trigger").handler(ctx, {+ operation: "unsuppress",+ id,+ })) as { trigger: Record<string, unknown> };+ expect(restored.trigger["status"]).toBe("pending");+ expect(restored.trigger["suppressed_at"]).toBeNull();+});++test("brain_trigger unsuppress on a trigger that is not suppressed is an invalid request", async () => {+ const { created } = createTriggers(vault, [CANDIDATE], { now: NOW });+ expect(() =>+ tool("brain_trigger").handler(ctx, { operation: "unsuppress", id: created[0]!.id }),+ ).toThrow("not suppressed");+});++test("brain_trigger names every operation when it rejects one", async () => {+ expect(() => tool("brain_trigger").handler(ctx, { operation: "explode" })).toThrow("unsuppress");+});++// โโ One corrupt record must not silence the whole surface โโโโโโโโโโโโโโโโโโโ++/** Seed one record and make a field of it unreadable, as a hand-edit would. */+function seedUnreadable(overrides: Partial<InsightCandidate> = {}): string {+ const { created } = createTriggers(vault, [{ ...CANDIDATE, ...overrides }], { now: NOW });+ const { path } = created[0]!;+ writeFileSync(+ path,+ readFileSync(path, "utf8").replace(/^occurrences: .*$/mu, "occurrences: many"),+ "utf8",+ );+ return path;+}++test("brain_trigger list names an unreadable record beside the readable ones", async () => {+ const { created } = createTriggers(vault, [CANDIDATE], { now: NOW });+ const brokenPath = seedUnreadable({ cooldownKey: "contradiction:pref-c:pref-d" });++ const listed = (await tool("brain_trigger").handler(ctx, { operation: "list" })) as {+ triggers: Array<{ id: string }>;+ unreadable: Array<{ path: string; key: string | null; error: string }>;+ };+ expect(listed.triggers.map((t) => t.id)).toEqual([created[0]!.id]);+ expect(listed.unreadable).toHaveLength(1);+ expect(listed.unreadable[0]!.path).toBe(brokenPath);+ expect(listed.unreadable[0]!.key).toBe("occurrences");+});++test("brain_brief view=morning reports an unreadable queue rather than an empty one", async () => {+ // The bare catch this replaces turned a refusal into an absent trigger+ // section, which reads exactly like a queue with nothing in it.+ seedUnreadable();+ const brief = (await tool("brain_brief").handler(ctx, { view: "morning" })) as {+ text: string;+ triggers?: unknown[];+ triggers_unreadable?: Array<{ key: string | null }>;+ };+ expect(brief.triggers).toBeUndefined();+ expect(brief.triggers_unreadable).toHaveLength(1);+ expect(brief.triggers_unreadable![0]!.key).toBe("occurrences");+ expect(brief.text).toContain("Unreadable triggers");+});+test("brain_brief view=morning without triggers keeps the legacy shape", async () => {const brief = (await tool("brain_brief").handler(ctx, { view: "morning" })) as Record<string,diff --git a/tests/mcp/recall-adequacy-tool.test.ts b/tests/mcp/recall-adequacy-tool.test.tsindex e96ff158..73e5acab 100644--- a/tests/mcp/recall-adequacy-tool.test.ts+++ b/tests/mcp/recall-adequacy-tool.test.ts@@ -8,9 +8,17 @@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 { dirname, join } from "node:path";import { aggregateUnmetRecall } from "../../src/core/brain/query-demand.ts";+import {+ NEGATIVE_RECALL_STATE,+ NEGATIVE_RECALL_STATES,+} from "../../src/core/brain/negative-recall.ts";+import { assertOutputContract } from "../../src/mcp/output-contract.ts";+import { RECALL_GATE_NEGATIVE_STATES } from "../../src/mcp/search-tools.ts";+import { resolveSearchConfig } from "../../src/core/search/index.ts";+import { indexVault } from "../../src/core/search/indexer.ts";import { buildToolTable, findTool } from "../../src/mcp/tools.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";@@ -84,6 +92,124 @@ test("gate honours configurable thresholds", async () => {expect(out.adequacy["level"]).toBe("weak");});+// ----- typed negative recall (U2) -------------------------------------------+//+// The adequacy verdict says the hits were too weak; the negative block+// says what the corpus behind them was. It rides only on the+// zero-usable-result path, where a "no" is otherwise indistinguishable+// from a "no" over an index that was never built.++test("gate attaches a negative block when the query yields no usable result", async () => {+ const gate = tool("brain_recall_gate");+ const out = (await gate.handler(ctx(), {+ prompt: "reactor coolant",+ scores: [],+ })) as { negative?: Record<string, unknown> };+ // The server enforces the declared output schema on every call, so the+ // block and its declaration have to agree here rather than in+ // production. Handler-level tests otherwise never see that check.+ assertOutputContract(gate.name, gate.outputSchema, out);+ expect(out.negative).toBeDefined();+ // No index exists in this temp vault, so the honest answer is that+ // nothing is known about the corpus - never a silent not_found.+ expect(out.negative!["state"]).toBe("unknown");+ expect(out.negative!["unknown_reason"]).toBe("index-absent");+ expect(out.negative!["complete"]).toBe(false);+ expect(out.negative!["coverage"]).toBeUndefined();+});++test("gate omits the negative block entirely when scores are usable", async () => {+ const out = (await tool("brain_recall_gate").handler(ctx(), {+ prompt: "reactor coolant",+ scores: [0.83],+ })) as Record<string, unknown>;+ expect(out["adequacy"]).toBeDefined();+ // Absent, never null - the convention the explain trace already sets.+ expect("negative" in out).toBe(false);+});++test("gate omits the negative block when no scores are supplied at all", async () => {+ const out = (await tool("brain_recall_gate").handler(ctx(), {+ prompt: "reactor coolant",+ })) as Record<string, unknown>;+ expect("negative" in out).toBe(false);+});++function writeMd(rel: string, body: string): void {+ const abs = join(vault, rel);+ mkdirSync(dirname(abs), { recursive: true });+ writeFileSync(abs, body);+}++async function buildIndex(): Promise<void> {+ await indexVault(resolveSearchConfig({ vault, configPath }));+}++test("over a keyword-only index a zero-result attempt is a not_found the receipt qualifies", async () => {+ writeMd("notes/coolant.md", "# Coolant\n\nThe reactor coolant loop was replaced in March.\n");+ await buildIndex();+ const gate = tool("brain_recall_gate");+ const out = (await gate.handler(ctx(), {+ prompt: "reactor coolant",+ scores: [],+ })) as { negative: Record<string, unknown> };+ // The populated-receipt shape has to clear the contract too.+ assertOutputContract(gate.name, gate.outputSchema, out);+ // No embedding provider is configured here, so the run built chunks and+ // recorded no model. That is a supported way to run this system, not an+ // unfinished job, so the negative is admitted rather than refused - a+ // vault without an embedding key would otherwise never be able to+ // receive this answer at all.+ expect(out.negative["state"]).toBe("not_found");+ expect(out.negative["complete"]).toBe(true);+ // What makes admitting it honest: the receipt says the search was+ // keyword-only, and the digest binds that, so the narrower claim is+ // visible to whoever reads the negative rather than implied by silence.+ const coverage = out.negative["coverage"] as Record<string, unknown>;+ expect(coverage["digest"]).toMatch(/^[0-9a-f]{64}$/);+ expect(coverage["documents"]).toBe(1);+ expect(coverage["embeddings"]).toBe(0);+ expect(coverage["embedding_signature"]).toBeNull();+ expect(coverage["chunks"]).toBeGreaterThan(0);+ expect(coverage["unindexed_roots"]).toEqual([]);+});++test("the gate declares only the negative states its handler can produce", async () => {+ // The gate reads no claim graph, so it supplies neither retraction+ // evidence nor the assertion, so `did_not_happen` is unreachable here.+ // Advertising it would leave a client unable to tell "this surface+ // cannot say that" from "it did not happen this time".+ const gate = tool("brain_recall_gate");+ const negative = gate.outputSchema?.properties?.["negative"];+ const declared = negative?.properties?.["state"]?.enum;+ expect(declared).toEqual([...RECALL_GATE_NEGATIVE_STATES]);+ expect(declared).not.toContain(NEGATIVE_RECALL_STATE.didNotHappen);+ // Not merely documentary: the server validates every response against+ // this schema, so a future producer of the third state fails loudly+ // here rather than emitting an undeclared value.+ expect([...NEGATIVE_RECALL_STATES]).toContain(NEGATIVE_RECALL_STATE.didNotHappen);+});++test("an authorized note root the index never reached forces unknown and names it", async () => {+ writeMd("notes/coolant.md", "# Coolant\n\nThe reactor coolant loop was replaced in March.\n");+ await buildIndex();+ // Declared AFTER the index run and holding no indexed document: the+ // authorized universe and the searched universe now disagree.+ writeFileSync(+ join(vault, "Brain", "_brain.yaml"),+ "schema_version: 1\nnotes:\n read_paths:\n - notes\n - archive\n",+ );+ const out = (await tool("brain_recall_gate").handler(ctx(), {+ prompt: "reactor coolant",+ scores: [],+ })) as { negative: Record<string, unknown> };+ expect(out.negative["state"]).toBe("unknown");+ expect(out.negative["unknown_reason"]).toBe("coverage-divergent");+ const coverage = out.negative["coverage"] as Record<string, unknown>;+ expect(coverage["scope"]).toEqual(["notes"]);+ expect(coverage["unindexed_roots"]).toEqual(["archive"]);+});+test("gate rejects a malformed scores argument", async () => {await expect(tool("brain_recall_gate").handler(ctx(), { prompt: "x", scores: ["nope"] }),diff --git a/tests/mcp/recall-gate-telemetry.test.ts b/tests/mcp/recall-gate-telemetry.test.tsindex d3149f3d..f5a586a9 100644--- a/tests/mcp/recall-gate-telemetry.test.ts+++ b/tests/mcp/recall-gate-telemetry.test.ts@@ -8,6 +8,7 @@ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSynimport { tmpdir } from "node:os";import { join } from "node:path";+import { listContinuityRecords } from "../../src/core/brain/continuity/store.ts";import { listGateTelemetry } from "../../src/core/brain/gate-telemetry.ts";import { buildToolTable, findTool } from "../../src/mcp/tools.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";@@ -99,4 +100,53 @@ test("fail-open: a broken continuity store never breaks the gate decision", asyn})) as { retrieve: boolean; reason: string };expect(typeof decision.retrieve).toBe("boolean");expect(typeof decision.reason).toBe("string");++ // The same contract on the negative-recall path, whose record is the+ // third write this one handler makes.+ const negative = (await tool("brain_recall_gate").handler(ctx(), {+ prompt: "what did we decide about the index?",+ scores: [],+ })) as { retrieve: boolean; negative?: Record<string, unknown> };+ expect(typeof negative.retrieve).toBe("boolean");+ expect(negative.negative?.["state"]).toBe("unknown");+});++// ----- typed negative recall (U2) -------------------------------------------+//+// Persisted behind the SAME `recall_gate_telemetry` opt-in as the gate+// record and the unmet-demand stamp: one config decision per feature, not+// one per surface.++function negativeRecallRecords() {+ return listContinuityRecords(vault, { kind: "negative_recall" });+}++test("default off: a negative verdict writes no continuity record", async () => {+ const out = (await tool("brain_recall_gate").handler(ctx(), {+ prompt: "reactor coolant",+ scores: [],+ })) as { negative?: unknown };+ expect(out.negative).toBeDefined();+ expect(negativeRecallRecords()).toHaveLength(0);+});++test("with the opt-in on, a negative verdict lands as a continuity record", async () => {+ writeFileSync(configPath, `vault: "${vault}"\nrecall_gate_telemetry: "true"\n`);+ await tool("brain_recall_gate").handler(ctx(), { prompt: "reactor coolant", scores: [] });+ const records = negativeRecallRecords();+ expect(records).toHaveLength(1);+ expect(records[0]!.payload["state"]).toBe("unknown");+ expect(records[0]!.payload["unknown_reason"]).toBe("index-absent");+ expect(records[0]!.payload["complete"]).toBe(false);+ // The prompt privacy invariant holds here too: only a hash lands.+ expect(JSON.stringify(records[0]!.payload)).not.toContain("reactor coolant");+ expect(typeof records[0]!.payload["prompt_hash"]).toBe("string");+ // A host filesystem path is not vault content and must not replicate.+ expect(JSON.stringify(records[0]!.payload)).not.toContain(tmp);+});++test("a usable-score call writes no negative record even with the opt-in on", async () => {+ writeFileSync(configPath, `vault: "${vault}"\nrecall_gate_telemetry: "true"\n`);+ await tool("brain_recall_gate").handler(ctx(), { prompt: "reactor coolant", scores: [0.9] });+ expect(negativeRecallRecords()).toHaveLength(0);});diff --git a/tests/mcp/schema-tools.test.ts b/tests/mcp/schema-tools.test.tsindex 86d8b807..7dda5410 100644--- a/tests/mcp/schema-tools.test.ts+++ b/tests/mcp/schema-tools.test.ts@@ -190,6 +190,62 @@ describe("schema MCP tools", () => {);});+ test("active_pack and packs forward the integrity verdict unchanged", async () => {+ const server = makeServer();+ await initialize(server);++ // A freshly bootstrapped vault has no audited apply behind it, so the+ // pack it reports is unverified rather than intact.+ const fresh = await call(server, "schema_inspect", { view: "active_pack" });+ expect((fresh as any).result.structuredContent.exists).toBe(true);+ expect((fresh as any).result.structuredContent.integrity.status).toBe("unverified");+ expect((fresh as any).result.structuredContent.integrity.unverified_reason).toBe(+ "no-apply-recorded",+ );++ const applied = await call(server, "schema_apply_mutations", {+ mutations: [{ op: "add_type", category: "preference_types", token: "decision" }],+ });+ const digest = (applied as any).result.structuredContent.pack_digest;+ expect(typeof digest).toBe("string");++ const sealed = await call(server, "schema_inspect", { view: "active_pack" });+ expect((sealed as any).result.structuredContent.integrity.status).toBe("ok");+ expect((sealed as any).result.structuredContent.integrity.digest).toBe(digest);++ const packs = await call(server, "schema_inspect", { view: "packs" });+ const listed = (packs as any).result.structuredContent.packs as ReadonlyArray<{+ exists: boolean;+ integrity: { status: string; digest: string };+ }>;+ expect(listed).toHaveLength(1);+ expect(listed[0]?.exists).toBe(true);+ expect(listed[0]?.integrity.status).toBe("ok");+ expect(listed[0]?.integrity.digest).toBe(digest);+ });++ test("active_pack reports a hand-edited pack as modified", async () => {+ const server = makeServer();+ await initialize(server);+ await call(server, "schema_apply_mutations", {+ mutations: [{ op: "add_type", category: "preference_types", token: "decision" }],+ });++ const brainConfig = join(vault, "Brain", "_brain.yaml");+ atomicWriteFileSync(+ brainConfig,+ readFileSync(brainConfig, "utf8").replace(" - decision", " - decision\n - tactic"),+ );++ const pack = await call(server, "schema_inspect", { view: "active_pack" });+ const integrity = (pack as any).result.structuredContent.integrity;++ expect(integrity.status).toBe("modified");+ expect(integrity.mismatches).toHaveLength(1);+ expect(integrity.mismatches[0].field).toBe("pack_digest");+ expect(integrity.mismatches[0].expected).not.toBe(integrity.mismatches[0].actual);+ });+test("a rejected preview returns the same error envelope the apply returns", async () => {const server = makeServer();await initialize(server);