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
refactor: module boundaries and the fallbacks behind them (v1.42.0) (#153)
Sol Aitken7e6a56726eaf
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 250ab83e..06d94157 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.41.0",+ "version": "1.42.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 0b001b1a..4309f8a1 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.41.0",+ "version": "1.42.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 1ef0458c..67fe4eb8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,51 @@ 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.42.0] - 2026-07-27++A structural wave with no new capability: the six modules that cost the most to change, plus the two import cycles in the graph, plus the silent fallbacks the split uncovered on the way. The targets were chosen by measurement rather than by impression - a maintainability index, a cognitive-complexity count and a fan-in count per file - and the six worst were a config validator with a single twelve-hundred-line function, the SQLite store as one class holding fourteen tables, the recall pipeline as one function running twelve stages, every search subcommand in one file, the vault doctor as twenty-six unrelated diagnostics in one body, and the dream pass with its orchestration fused into the mechanics it orchestrates.++The rule for the refactoring commits was that behaviour is byte-identical, and the existing suite is what proves it, so no test may be edited to make one pass. Where that guarantee was load-bearing it was checked directly rather than left to the suite: the config validator was run against its predecessor over 3135 generated configs comparing resolved values, key order, warnings and thrown errors; the search command line was run through 92 invocations on identical fresh vaults with stdout, stderr and exit code diffed byte for byte; the store's schema statements and the recall pipeline's cache-key composition were diffed line for line against their previous versions, because either one changing would strand data already on disk without failing a test.++Three ratchets grew rather than being excused. The terminal-state census followed the code out of the file it used to read, and three exclusions that predate this wave turned out to be detectable once it did. The doctor's code census now enumerates its check modules from disk. A new census walks the static import graph and fails on any cycle at all.++Independent review of the finished branch - four reviewers given the diff and the claims, with no knowledge of how the work was done, one of them tasked with treating every changed test as guilty until proven innocent - found fourteen further defects, four of them regressions this wave introduced. Two are worth naming here because they are the shape this exercise is supposed to catch. Narrowing a swallowed database error to the one condition it documented turned a lane that only ADDS search candidates into one that could fail the whole query. And the new import-cycle ratchet was proved to pass on an empty set twice over - with its source root pointed at an empty directory, and with its patterns altered to match nothing - so it would have reported an acyclic graph over a fully cyclic one, permanently and silently. Every finding is fixed and named below; each ratchet now carries a demonstration that it can fail.++The silent fallbacks are the part with user-visible behaviour, and review turned one correction into a theme: absence and inability to look are not the same answer, and nearly everywhere this code conflated them the result was not imprecision but destructive advice. An unreadable vault root was told to run `brain init` over a populated Brain layer; an unreadable index was told to re-initialise an index that already existed; a manifest behind an untraversable parent was told to run an update that regenerates the file and leaves the permission fault in place. Nine such sites across six subsystems are closed.++### Changed++- The vault config validator is one module per `_brain.yaml` block, each owning its default table, its read-side resolver and its parser together, above a shared constraint vocabulary and key index. The public path and all fifty-five exports are unchanged, so none of the seventy importing modules moved. Nine duplications and dead branches went with the split: a YAML-safety loop written three times, an array guard written at five sites, two bound checks with one message, a dead `Set` branch, a ternary whose arms were identical repeated across six blocks, a default parameter no call site overrode, a boolean check split out of the loop handling its four siblings, validation sitting a thousand lines from the construction it guarded, and three parameters threaded loose through twenty call sites.+- The search index store keeps its class and its full method surface - twenty-five modules hold that abstraction - and the bodies moved into seventeen modules, one per table or lifecycle concern, each taking the database handle as an explicit parameter. The on-disk format is untouched: the schema module has an empty diff, the version is still 10, and no table-creating statement exists anywhere in the split.+- The recall pipeline reads as the stages it runs. Each stage is a module with an explicit input and output type, and the gate deciding whether a stage runs is visible at the call site rather than buried inside it. Warning order is preserved exactly, because it is observable: each stage returns its own list and the coordinator drains them in the original sequence.+- Every `o2b search` verb is its own module under the layout the brain verbs already established, rather than a second layout invented for it. Six duplications went with it, including the vault, config and database flag schema written out fourteen times and the whole report-emission block copy-pasted between `index` and `reindex`, comment included.+- The vault doctor is a registry: a twenty-six entry array a new check joins by being appended to, over one module per check family. Each check declares its own fail-soft flag beside its implementation, encoding exactly the guard placement the single body had. The forty-one diagnostic codes are unchanged, verified by running the census's own patterns over both trees.+- The dream pass separates deciding from writing. The apply module owns the order of writes that keeps the on-disk invariants true and decides nothing; the planning modules decide and write nothing. Moving the rename out made the new module write-capable and the vault-guard census correctly failed on it - the fix was to make the guard honest by asserting write identity on entry, not to add an exclusion.+- The two import cycles are gone. Both existed because one large module played two roles at once: declaring a value everyone needs, and aggregating types from its own dependents. The search error vocabulary, the ranked-row shape and the vault-relative path constants now live in leaf modules that import nothing, re-exported from the modules that used to declare them. Both export surfaces were compared symbol by symbol against the previous commit through the TypeScript checker rather than by eye.++### Fixed++- A `_brain.yaml` that is present but malformed no longer reads as one that is absent. Five config readers shared a blanket catch that collapsed the two, so an operator whose configuration had a typo was served the documented defaults while every surface reported healthy. Absent stays byte-identical and no longer even opens the file; malformed, structurally invalid and unreadable each raise with the path named. No new diagnostic code or configuration key was needed, because every call site already had a visible channel: the feedback scope raises before the durable write, since a signal recorded under a silently wrong scope is a record no later fix reaches, and the snapshot retention read raises inside the gate's existing best-effort catch so the destructive prune is skipped rather than run at a guessed retention. The one reader that still resolves rather than raises is the integrity gate, which now documents why - the search layer reads it on every store open inside a fail-soft path, and its strict fallback means an unreadable config can only close a gate, never open one. A test pins that asymmetry so the two shapes are not later unified by someone tidying.+- The doctor now says when it could not look. Two sweeps caught every read failure and returned nothing, and for a diagnostic no findings renders as a clean bill of health - the operator was told the vault was fine exactly when the check was unable to examine it. A missing path stays silent, since a path that is not there was never a subtree to sweep; a permission failure, an I/O error or a file standing where a directory was expected now names the path, the reason and the specific claim the sweep can no longer make, through the doctor's existing uncertainty stream rather than by raising, because a doctor that dies on the first odd directory reports less than one that continues. Two further catches of the same shape were found in the removed-tool scan and fixed with it.+- One of those guards could never have fired. The vault walk beneath it swallowed every directory failure internally, while accepting a notices sink in its own options type and dropping it - so the guard above was inert and the real silence was one level down. The walk now honours the sink its sibling branch already did.+- An unreadable search index no longer narrows recall while looking healthy, and no longer fails the query either. The trigram candidate lookup caught every database error and returned an empty candidate list; narrowing that to the one condition it documented then raised for everything else, which review showed could kill a query the keyword and semantic lanes had already answered - an indexing pass holding the write lock past the busy timeout is enough, and so is an index whose trigram tokenizer the running build does not have. The lane only ever ADDS candidates, so it degrades and the query carries the reason, from a closed vocabulary that never forwards the database message: the full-text engine reports a rejected match by echoing the expression, which is built from the caller's own query terms. The absence predicate is also anchored now - a missing shadow table means the index has lost one, which is corruption, and it used to read as the table never having been built.+- A neutral fold of the learned recall weights could attach a ranking reason to itself. Two booleans were derived separately from one read, one gating the composition and the other gating its explanation, so using the wrong one credited a fold that did not move the ranking. They are one nullable value that is non-null exactly when the fold applied.+- A `void parseFrontmatter;` statement in the doctor claimed in its comment to prevent a dependency being stripped, while the import was genuinely used the whole time; a `void basename` in the dream pass claimed a barrel re-export that never existed; and a planning function there was a pure stub. All three deleted.+- A vault that cannot be examined is no longer reported as one that was never set up. An unreadable root made the doctor advise `brain init` over a populated Brain layer; an unreadable index made the code-graph partner advise re-initialising an index that already existed; a manifest behind an untraversable parent was reported missing under a fix that regenerates the file and leaves the permission fault. The status payload's `vault_exists` field, which also gated three blocks, answered `false` for a vault it could not stat, so an operator saw four confident negatives for one missing execute bit. The field carries a named reason on that branch only - both answerable cases stay byte-identical - and the blocks it gates degrade themselves rather than being omitted, since an omitted block reads as the same confident negative. The second runtime publishes the same field from its own payload and now shares one formulation of the condition rather than a second copy of it.+- The plugin config read failure had nowhere to land. The command-line dispatcher formats two error classes and rethrows the rest, so an unreadable config printed a source excerpt and eight stack frames with zero checks reported - worst on `doctor`, which prints the correct diagnosis the moment the crash is out of the way - and the JSON surface produced empty output plus a trace. It refuses with a formatted message now, both JSON surfaces stay parseable, and the remedy travels in the error because it escapes through four unrelated channels. Two tool surfaces computed their whole payload and then threw on the one field that reads the config, discarding the report that names the broken file; both report it in the field instead. The server resolved the agent identity from that same config before any handler ran, which made those repairs unreachable - including in the handshake, so a real client would never have issued a call at all. The identity is resolved where it is used now, still raising, still never substituting a placeholder name.+- An existence check in front of the config read returned false for every errno, so a readable config behind an untraversable parent silently reverted every setting - in the commit that claimed to have fixed exactly that. It is one stat now, which makes the split free: the absent case pays the syscall it always did and constructs no error. Invalid UTF-8 was never really read as missing either; it produced an empty config that every resolver reads as "the operator set nothing", while the write path would have persisted the file with each undecodable byte replaced.+- The pre-compaction memory pack died on a broken config instead of degrading. The integrity gate's strict fallback resolves owner-scope delivery to `fail`, which takes the scoped branch, which renders the active head, which now raises - so one bad line cost a scoped agent the whole pack. Compaction happens whether or not the tool answered, so a refusal deletes the memory at the one moment it cannot be re-fetched: the pack is delivered, the scope-narrowed head is withheld, and the reason rides on the payload.+- One uncapped, undeduplicated uncertainty entry per sweep meant four identical lines for one unreadable subtree, and an existence check in front of every sweep sent parent-directory failures past the classifier entirely. Three ordinary broken-vault shapes also made the whole diagnostic pass throw with zero findings, which the hoisted shared context had made the first thing it did.+- The `pref|ret|sig` artifact id grammar had two homes and could drift. It is now a predicate on the module that already declares itself the one place the wikilink grammar lives - the other direction would have closed an import cycle, which the new ratchet catches.++### Notes++- Three things were found and deliberately not changed, because fixing them alters output and that belongs in its own release: the same constraint renders two different messages depending on which config block declares it; the same command-line flag is refused with different wording by different subcommands; and several reads in the recall pipeline swallow a failure to keep a single unreadable file ranking neutrally rather than failing the query.+- The measured effect: no file in the repository now scores worse than the seventh-worst did before, the worst cognitive-complexity count in the touched set falls from 441 to 32, mean cognitive complexity across the tree falls from 34.9 to 30.7, and the import graph is acyclic.+- Three ratchets can now be shown to fail. The import-cycle census pins the size of the graph it searched, with separate floors for the two narrow declaration kinds, since the total is dominated by plain imports and either could stop matching without moving it; a type-only import stays an edge and a deferred dynamic import stays excluded, both asserted rather than left as comments, because counting the deferred ones closes two cycles on this tree - which is to say those deferrals exist to break them. The terminal-state census applies the same reason, class and cap gates to both of its inventories, so a state rescued by the widened module walk can no longer be excused without a written argument. Its hop limit was measured inert beyond one and is one now.+- One gap is stated rather than closed: seven degradation codes reach the doctor's uncertainty stream with neither a registered command nor a written exclusion. Closing it needs a judgement per condition.+- The next tier by the same measurement, untouched here: the preference parser, the skill proposal store, the search and recall tool surfaces, the indexer, the digest and the command-line entry point.+## [1.41.0] - 2026-07-27A signals-that-survive wave: eight units that carry a signal the kernel already computes the last few metres, to the decision it should have changed. A repository declared which files it considers noise and the ingest planner ignored the declaration, while the hygiene scan beside it had honoured git for releases. A recall attempt was graded weak and the grade evaporated when the call returned, so nothing could tell that the same question had come back insufficient four times. A query named a period and the ranker went on applying a freshness prior pointing the other way. A parse error carried its file path in prose and as a field, so the doctor printed it twice. Three write paths accepted model-authored payloads and parsed them loosely, straight into the vault.@@ -6755,6 +6800,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.42.0]: https://github.com/itechmeat/open-second-brain/compare/v1.41.0...v1.42.0[1.41.0]: https://github.com/itechmeat/open-second-brain/compare/v1.40.0...v1.41.0[1.40.0]: https://github.com/itechmeat/open-second-brain/compare/v1.39.0...v1.40.0[1.39.0]: https://github.com/itechmeat/open-second-brain/compare/v1.38.0...v1.39.0diff --git a/README.md b/README.mdindex 6d771eb5..7f1ea368 100644--- a/README.md+++ b/README.md@@ -8,7 +8,9 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm## What is new-Open Second Brain 1.41.0 is a signals-that-survive wave: eight units that carry a signal the system already computes the last few metres, to the decision it should have changed. Ingest now honours the repository's own `.gitignore`, nested ignore files, `.git/info/exclude` and submodule boundaries, through the same discovery module the hygiene scan uses - so a repo path stops pulling in the build artifacts it already declares as noise. A recall graded weak no longer evaporates when the call returns: repeated weak recall on the same question becomes a tracked, self-closing gap task. A query that names a period is ranked for that period instead of against it, detected from ISO and `since:`/`until:` tokens only so it behaves the same in every language. A scope-less capture says which routing signal it was missing and which scopes the vault actually has. Model-authored payloads are checked against a declared shape before they become knowledge, unconditionally - a validator that can be switched off is one the write path cannot rely on. Plain text can now seed a fact or a skill, not only a taste signal. And resumed work is recognised by a declared identity rather than by a fifteen-minute clock, so a branch or worktree switch stops breaking the chain. A ninth unit was built, reviewed, and reverted rather than shipped, because proving it inert was easier than pretending it was not - the [CHANGELOG](CHANGELOG.md) says why.+Open Second Brain 1.42.0 is a structural wave with no new capability, and one behavioural correction worth knowing about: a `_brain.yaml` that is present but malformed no longer reads as one that is absent, so a typo in your config stops being served back as the documented defaults while every surface reports healthy, and a diagnostic that could not read a directory now says so instead of rendering as a clean bill of health. The rest is the six modules that cost the most to change, chosen by measurement rather than impression - a config validator with a single twelve-hundred-line function, the search store as one class over fourteen tables, the recall pipeline as one function running twelve stages, every `o2b search` verb in one file, the vault doctor as twenty-six unrelated checks in one body, and the dream pass with its orchestration fused into the mechanics it orchestrates. Both import cycles in the graph are gone, and a ratchet now fails the build on any new one - after review proved that ratchet could pass on an empty set, which is fixed and demonstrated. Behaviour is byte-identical everywhere it is claimed to be, and where that guarantee is load-bearing it was measured rather than asserted: the validator against its predecessor over 3135 generated configs, the command line over 92 invocations with stdout, stderr and exit code diffed byte for byte, and the store's schema statements and the pipeline's cache-key composition diffed line for line, since either changing would strand data already on disk without failing a test. The [CHANGELOG](CHANGELOG.md) has the detail.++Previous release, 1.41.0, was a signals-that-survive wave: eight units that carry a signal the system already computes the last few metres, to the decision it should have changed. Ingest now honours the repository's own `.gitignore`, nested ignore files, `.git/info/exclude` and submodule boundaries, through the same discovery module the hygiene scan uses - so a repo path stops pulling in the build artifacts it already declares as noise. A recall graded weak no longer evaporates when the call returns: repeated weak recall on the same question becomes a tracked, self-closing gap task. A query that names a period is ranked for that period instead of against it, detected from ISO and `since:`/`until:` tokens only so it behaves the same in every language. A scope-less capture says which routing signal it was missing and which scopes the vault actually has. Model-authored payloads are checked against a declared shape before they become knowledge, unconditionally - a validator that can be switched off is one the write path cannot rely on. Plain text can now seed a fact or a skill, not only a taste signal. And resumed work is recognised by a declared identity rather than by a fifteen-minute clock, so a branch or worktree switch stops breaking the chain. A ninth unit was built, reviewed, and reverted rather than shipped, because proving it inert was easier than pretending it was not - the [CHANGELOG](CHANGELOG.md) says why.Previous release, 1.40.0, was a no-dead-ends wave: every issue `o2b brain doctor` reports carries the exact command that acts on it, terminal states name their next move through one rail a ratchet keeps singular, and where no command resolves a class the doctor gives the reason rather than falling silent. Details live in the [CHANGELOG](CHANGELOG.md).diff --git a/hooks/active-inject.ts b/hooks/active-inject.tsindex a6a9c9a1..a151cf3d 100644--- a/hooks/active-inject.ts+++ b/hooks/active-inject.ts@@ -316,8 +316,26 @@ function readActiveBody(vault: string, activePath: string, meter: InjectionMeterif (trimmed.length === 0) return "";// Injection budget (token-diet): a large preference set must not- // flood the session preamble. Config errors fall back to the- // default budget - the hook is fail-soft by contract.+ // 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);@@ -325,7 +343,7 @@ function readActiveBody(vault: string, activePath: string, meter: InjectionMeterbudget = cfg.active.inject_budget_chars;}} catch {- // intentional fallback - a corrupted _brain.yaml is doctor's job+ // absorbed deliberately - see the budget note above}meter.budgetChars = budget;diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex ec13315c..3cf19f0b 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.41.0",+ "version": "1.42.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 29c4ac41..f05c2b11 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.41.0",+ "version": "1.42.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 35e8e1b2..22b2df8c 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.41.0"+version: "1.42.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 1c09daa6..70fa7a53 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.41.0",+ "version": "1.42.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 35e8e1b2..22b2df8c 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.41.0"+version: "1.42.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 bf2a716c..a7a15380 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.41.0"+version = "1.42.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/verbs/anticipate.ts b/src/cli/brain/verbs/anticipate.tsindex 1275c216..5e17bd2a 100644--- a/src/cli/brain/verbs/anticipate.ts+++ b/src/cli/brain/verbs/anticipate.ts@@ -50,12 +50,22 @@ export async function cmdBrainAnticipate(argv: string[]): Promise<number> {...(maxTokens !== undefined ? { maxTokens } : {}),});}- const result = readAnticipatoryContext(vault, {- sessionId,- now,- ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),- ...(maxTokens !== undefined ? { maxTokens } : {}),- });+ // The live-bundle fallback builds a context pack, which reads the+ // guardrail block and raises on a `_brain.yaml` the operator wrote and+ // broke. Without this boundary that raise left the verb as a stack+ // trace naming this repo's files instead of theirs; every sibling verb+ // on the same path already reports `<verb> failed: <cause>`.+ let result;+ try {+ result = readAnticipatoryContext(vault, {+ sessionId,+ now,+ ...(ttlSeconds !== undefined ? { ttlSeconds } : {}),+ ...(maxTokens !== undefined ? { maxTokens } : {}),+ });+ } catch (exc) {+ return fail(`anticipate failed: ${(exc as Error).message ?? exc}`);+ }if (flags["json"]) {process.stdout.write(JSON.stringify(result, null, 2) + "\n");diff --git a/src/cli/brain/verbs/context-pack.ts b/src/cli/brain/verbs/context-pack.tsindex 628b483b..c8300244 100644--- a/src/cli/brain/verbs/context-pack.ts+++ b/src/cli/brain/verbs/context-pack.ts@@ -38,46 +38,56 @@ export async function cmdBrainContextPack(argv: string[]): Promise<number> {return fail(`brain context-pack: --max-tokens must be a positive integer; got ${maxTokensRaw}`);}- const report = packContext(vault, {- maxTokens,- ...(flags["query"] ? { query: flags["query"] as string } : {}),- ...(flags["lanes"] === true ? { includeLanes: true } : {}),- ...(flags["receipt"] === true- ? {- receipt: {- host: trimOrDefault(flags["receipt-host"], "cli"),- trigger: "context_pack" as const,- ...(trimOrUndefined(flags["session-id"]) !== undefined- ? { sessionId: trimOrUndefined(flags["session-id"]) }- : {}),- ...(trimOrUndefined(flags["turn-id"]) !== undefined- ? { turnId: trimOrUndefined(flags["turn-id"]) }- : {}),- },- }- : {}),- ...(flags["cache-stable"] === true || flags["dedup-repeated"] === true- ? {- transforms: {- ...(flags["cache-stable"] === true ? { cacheStableOrdering: true } : {}),- ...(flags["dedup-repeated"] === true ? { deduplicateRepeatedContext: true } : {}),- },- }- : {}),- ...(flags["telemetry"] === true- ? {- telemetry: {- host: trimOrDefault(flags["telemetry-host"], "cli"),- ...(trimOrUndefined(flags["session-id"]) !== undefined- ? { sessionId: trimOrUndefined(flags["session-id"]) }- : {}),- ...(trimOrUndefined(flags["turn-id"]) !== undefined- ? { turnId: trimOrUndefined(flags["turn-id"]) }- : {}),- },- }- : {}),- });+ // `packContext` reads the guardrail block and raises on a `_brain.yaml`+ // the operator wrote and broke. Without this boundary that raise left+ // the verb as a stack trace naming this repo's files instead of theirs;+ // every sibling verb on the same path already reports+ // `<verb> failed: <cause>`.+ let report;+ try {+ report = packContext(vault, {+ maxTokens,+ ...(flags["query"] ? { query: flags["query"] as string } : {}),+ ...(flags["lanes"] === true ? { includeLanes: true } : {}),+ ...(flags["receipt"] === true+ ? {+ receipt: {+ host: trimOrDefault(flags["receipt-host"], "cli"),+ trigger: "context_pack" as const,+ ...(trimOrUndefined(flags["session-id"]) !== undefined+ ? { sessionId: trimOrUndefined(flags["session-id"]) }+ : {}),+ ...(trimOrUndefined(flags["turn-id"]) !== undefined+ ? { turnId: trimOrUndefined(flags["turn-id"]) }+ : {}),+ },+ }+ : {}),+ ...(flags["cache-stable"] === true || flags["dedup-repeated"] === true+ ? {+ transforms: {+ ...(flags["cache-stable"] === true ? { cacheStableOrdering: true } : {}),+ ...(flags["dedup-repeated"] === true ? { deduplicateRepeatedContext: true } : {}),+ },+ }+ : {}),+ ...(flags["telemetry"] === true+ ? {+ telemetry: {+ host: trimOrDefault(flags["telemetry-host"], "cli"),+ ...(trimOrUndefined(flags["session-id"]) !== undefined+ ? { sessionId: trimOrUndefined(flags["session-id"]) }+ : {}),+ ...(trimOrUndefined(flags["turn-id"]) !== undefined+ ? { turnId: trimOrUndefined(flags["turn-id"]) }+ : {}),+ },+ }+ : {}),+ });+ } catch (exc) {+ return fail(`context-pack failed: ${(exc as Error).message ?? exc}`);+ }if (flags["json"]) {okJson({diff --git a/src/cli/brain/verbs/mcp-landscape.ts b/src/cli/brain/verbs/mcp-landscape.tsindex a3bca73b..efe495c4 100644--- a/src/cli/brain/verbs/mcp-landscape.ts+++ b/src/cli/brain/verbs/mcp-landscape.ts@@ -15,6 +15,10 @@ export async function cmdBrainMcpLandscape(argv: string[]): Promise<number> {return 0;}+ // An empty landscape names no forward exit, deliberately. This lists the+ // MCP servers declared in runtime configuration files this tool never+ // writes, so the way out of "none" is editing another runtime's config -+ // there is no `o2b` command to point at.process.stdout.write(`MCP servers configured in vault: ${landscape.servers.length}\n`);for (const s of landscape.servers) {process.stdout.write(` ${s.name} (${s.source})\n`);diff --git a/src/cli/brain/verbs/semantics-backfill.ts b/src/cli/brain/verbs/semantics-backfill.tsindex b5604479..983856f0 100644--- a/src/cli/brain/verbs/semantics-backfill.ts+++ b/src/cli/brain/verbs/semantics-backfill.ts@@ -18,6 +18,10 @@ export async function cmdBrainSemanticsBackfill(argv: string[]): Promise<number>return 0;}+ // An empty proposal list names no forward exit, deliberately. This verb is+ // dry-run only and has no apply path, so there is no command to name; and+ // no proposals means the inverse-edge invariant it previews already holds,+ // which is an answer rather than a degraded state.info(`Semantics backfill dry-run proposals: ${plan.proposals.length}`);for (const proposal of plan.proposals) {info(diff --git a/src/cli/brain/verbs/temporal-stale.ts b/src/cli/brain/verbs/temporal-stale.tsindex f727603e..357dec86 100644--- a/src/cli/brain/verbs/temporal-stale.ts+++ b/src/cli/brain/verbs/temporal-stale.ts@@ -26,6 +26,11 @@ export async function cmdBrainStale(argv: string[]): Promise<number> {return 0;}+ // An empty report names no forward exit, deliberately. This verb IS the+ // exit other surfaces name - the `stale-notes` registry entry resolves to+ // it - and what to do with a stale entry (pin it, retire it, refresh its+ // evidence) is a judgement over content, so naming any one of them would+ // be a guess dressed as an instruction.process.stdout.write(`Stale entries (pref >= ${cfg.stale_pref_days}d, signal >= ${cfg.stale_signal_days}d, log >= ${cfg.stale_log_days}d):\n`,);diff --git a/src/cli/main.ts b/src/cli/main.tsindex 31e66eee..a59d5ff8 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -12,6 +12,7 @@ import { mkdirSync, writeFileSync } from "node:fs";import { resolve } from "node:path";import {+ ConfigReadError,defaultConfigPath,discoverConfig,redactMapping,@@ -925,10 +926,43 @@ async function dispatchCommand(command: string, rest: string[]): Promise<number>process.stderr.write(exc.message + "\n");return 1;}+ if (exc instanceof ConfigReadError) {+ return reportConfigReadError(exc, command, rest);+ }throw exc;}}+/**+ * Refusal for a plugin config that is present but unreadable.+ *+ * Exit 1, joining `NoVaultConfiguredError` rather than `CliError`: this+ * command line reserves 2 for a mistake in the argv and 1 for a machine+ * that cannot answer the question. Nothing about the invocation is wrong+ * here - the same argv works the moment the file mode does.+ *+ * The message needs no assembly. {@link ConfigReadError} carries its own+ * remedy so that every surface it escapes through (here, an MCP error+ * envelope, a subcommand's own wrapper) says the same thing.+ *+ * A `--json` caller additionally gets a parseable object on stdout. For+ * every other command the {@link withJsonFallback} envelope already carries+ * the refusal - it could not before, because a THROWN error escaped the+ * envelope entirely and left stdout empty. A command that renders its own+ * JSON is not wrapped, so it would still be the one surface where a machine+ * consumer sees a non-zero exit and nothing to parse. The keys are the ones+ * `o2b status --json` and its MCP twin already use for this condition.+ */+function reportConfigReadError(exc: ConfigReadError, command: string, rest: string[]): number {+ process.stderr.write(`error: ${exc.message}\n`);+ if (wantsJsonFlag(rest) && ownsInternalJson(command, rest)) {+ process.stdout.write(+ JSON.stringify({ config_path: exc.path, error: exc.message }, sortedReplacer, 2) + "\n",+ );+ }+ return 1;+}+if (import.meta.main) {// O1 (t_2ed754d1): an early-closed stdout pipe (`o2b <listing> | head -1`)// must exit clean. The listener catches Bun's asynchronous closed-pipediff --git a/src/cli/search.ts b/src/cli/search.tsindex 8109b018..653dcec6 100644--- a/src/cli/search.ts+++ b/src/cli/search.ts@@ -1,90 +1,30 @@/*** `o2b search` subcommand dispatcher.*- * Routes the five Brain Search verbs (design doc Β§8) to thin wrappers- * over `src/core/search/*`. The core modules own all I/O; this file- * only parses flags, resolves the vault, shapes exit codes, and renders- * either human-readable or JSON output.+ * Routes the Brain Search verbs (design doc Β§8) to thin wrappers over+ * `src/core/search/*`. The core modules own all I/O; each verb handler+ * lives in `./search/verbs/<name>.ts` and only parses flags, resolves the+ * vault, shapes exit codes, and renders either human-readable or JSON+ * output. This file dispatches and maps thrown errors onto exit codes.*- * o2b search "<query>" β cmdSearchQuery (default verb)- * o2b search index β cmdSearchIndex- * o2b search reindex β cmdSearchReindex- * o2b search status β cmdSearchStatus- * o2b search check β cmdSearchCheck+ * Shared parse/validate/config plumbing lives in `./search/helpers.ts`,+ * which is the single barrel every verb imports it through.*/-import { defaultConfigPath, resolveVault } from "../core/config.ts";-import { formatDegradationNotice } from "../core/integrity/degradation.ts";-import { formatStampMismatch } from "../core/integrity/stamp.ts";-import {- createSafeguard,- resolveSafeguardTimeoutMs,- SafeguardTimeoutError,-} from "../core/brain/safeguard.ts";-import {- captureRecallFeedback,- expandHit,- indexCheck,- indexStatus,- indexVault,- loadFeedbackEvents,- readLearnedWeights,- reindexVault,- resetLearnedWeights,- resolveSearchConfig,- search,- SearchError,- clearSessionFocus,- normalizeSessionFocus,- parseStructuredRecallQueryDocument,- readSessionFocus,- structuredRecallQueryText,- writeSessionFocus,- LEARNED_WEIGHT_MIN,- LEARNED_WEIGHT_MAX,- type LearnedWeights,- loadProviderRegistry,- addProviderProfile,- removeProviderProfile,- getProviderProfile,- loadRerankRegistry,- addRerankProviderProfile,- removeRerankProviderProfile,- getRerankProviderProfile,- planRead,- serializeEvidencePack,- serializeSearchCard,- serializeIndexStatus,- serializeStampMismatches,- SEARCH_LIMIT_MIN,- SEARCH_LIMIT_MAX,-} from "../core/search/index.ts";-import { parseDegreePredicate, type DegreePredicate } from "../core/search/property-filter.ts";-import type {- IndexCheckReport,- IndexProgressEvent,- IndexStats,- IndexStatusSnapshot,- ResolvedSearchConfig,- SearchSessionFocus,- SearchOutcome,-} from "../core/search/index.ts";-import {- EMBEDDING_MODEL_PRESETS,- RECOMMENDED_EMBEDDING_MODEL,- type EmbeddingModelPreset,-} from "../core/search/embeddings/presets.ts";-import { searchAcrossVaults } from "../core/search/cross-vault.ts";-import { rerankFitCheck } from "../core/search/rerank-fit-check.ts";-import { IndexWatchPlanner } from "../core/search/index-watch.ts";-import { IndexWatchRunner } from "../core/search/watch-runner.ts";-import { SafeguardAbortError } from "../core/brain/safeguard.ts";-import { canonicalNotePath } from "../core/path-safety.ts";-import { watch, type FSWatcher } from "node:fs";-import { nextCommandField } from "../core/brain/next-step.ts";-import { emitNextStep, type AdvisoryStream } from "./advisory-rail.ts";-import { CliError, parseFlags } from "./argparse.ts";-import { CronTemplateError, renderCronTemplate } from "./search-cron-template.ts";+import { SafeguardTimeoutError } from "../core/brain/safeguard.ts";+import { SearchError } from "../core/search/index.ts";+import { CliError } from "./argparse.ts";+import { cmdSearchCheck } from "./search/verbs/check.ts";+import { cmdSearchExpand } from "./search/verbs/expand.ts";+import { cmdSearchFocus } from "./search/verbs/focus.ts";+import { cmdSearchIndex, cmdSearchReindex } from "./search/verbs/indexing.ts";+import { cmdSearchFeedback, cmdSearchWeights } from "./search/verbs/learned-weights.ts";+import { cmdSearchPlan } from "./search/verbs/plan.ts";+import { cmdSearchProvider, cmdSearchRerankProvider } from "./search/verbs/provider-registry.ts";+import { cmdSearchQuery } from "./search/verbs/query.ts";+import { cmdSearchRerankFit } from "./search/verbs/rerank-fit.ts";+import { cmdSearchStatus } from "./search/verbs/status.ts";+import { cmdSearchWatch } from "./search/verbs/watch.ts";const KNOWN_VERBS = new Set(["query",@@ -168,1286 +108,3 @@ export async function handleSearchSubcommand(argv: ReadonlyArray<string>): Promireturn 1;}}--function resolveConfig(- flags: Record<string, string | boolean | string[] | undefined>,-): ResolvedSearchConfig {- const flagVault = typeof flags["vault"] === "string" ? (flags["vault"] as string) : undefined;- const configPath =- typeof flags["config"] === "string" ? (flags["config"] as string) : defaultConfigPath();- const vault = flagVault ?? resolveVault(configPath) ?? null;- if (!vault) {- throw new CliError(- "no vault configured. Pass --vault <path> or run `o2b init --vault <path> ...` first.",- );- }- const dbFlag = typeof flags["db"] === "string" ? (flags["db"] as string) : undefined;- const kwFlag =- typeof flags["keyword-weight"] === "string" ? Number(flags["keyword-weight"]) : undefined;- const semFlag =- typeof flags["semantic-weight"] === "string" ? Number(flags["semantic-weight"]) : undefined;- const concurrencyFlag =- typeof flags["concurrency"] === "string" ? Number(flags["concurrency"]) : undefined;- const overrides = {- ...(dbFlag !== undefined ? { dbPath: dbFlag } : {}),- ...(kwFlag !== undefined ? { keywordWeight: kwFlag } : {}),- ...(semFlag !== undefined ? { semanticWeight: semFlag } : {}),- ...(concurrencyFlag !== undefined ? { semantic: { concurrency: concurrencyFlag } } : {}),- };- return resolveSearchConfig({ vault, configPath, overrides });-}--// βββ focus βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--async function cmdSearchFocus(argv: ReadonlyArray<string>): Promise<number> {- const action = argv[0];- if (!action || !["set", "status", "clear"].includes(action)) {- throw new CliError(- "usage: o2b search focus <set|status|clear> [--query Q] [--path P] [--session S]",- );- }- const { flags } = parseFlags(argv.slice(1), {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- query: { type: "string" },- path: { type: "string" },- session: { type: "string" },- "ttl-minutes": { type: "string", default: "120" },- json: { type: "boolean" },- });- const cfg = resolveConfig(flags);- // Session-scoped focus (t_5b478e47): --session binds the focus to- // one session's file under search-focus/ instead of the global file.- const session = typeof flags["session"] === "string" ? (flags["session"] as string) : undefined;-- if (action === "set") {- const ttlMinutes = Number(flags["ttl-minutes"] ?? "120");- const focus = normalizeSessionFocus(- {- query: typeof flags["query"] === "string" ? (flags["query"] as string) : null,- pathPrefix: typeof flags["path"] === "string" ? (flags["path"] as string) : null,- ttlMinutes,- },- Date.now(),- );- writeSessionFocus(cfg, focus, session);- writeFocusResponse(focus, flags["json"] === true);- return 0;- }-- if (action === "clear") {- clearSessionFocus(cfg, session);- writeFocusResponse(null, flags["json"] === true);- return 0;- }-- writeFocusResponse(readSessionFocus(cfg, Date.now(), session), flags["json"] === true);- return 0;-}--function focusJson(focus: SearchSessionFocus | null): Record<string, unknown> {- return { active: focus !== null, focus };-}--function writeFocusResponse(focus: SearchSessionFocus | null, json: boolean): void {- if (json) {- process.stdout.write(JSON.stringify(focusJson(focus)) + "\n");- return;- }- if (!focus) {- process.stdout.write("search focus: inactive\n");- return;- }- const parts = [- focus.query !== null ? `query=${JSON.stringify(focus.query)}` : null,- focus.pathPrefix !== null ? `path=${JSON.stringify(focus.pathPrefix)}` : null,- focus.expiresAt !== null ? `expires_at=${new Date(focus.expiresAt).toISOString()}` : null,- ].filter((part): part is string => part !== null);- process.stdout.write(`search focus: active ${parts.join(" ")}\n`);-}--// βββ feedback / weights (recall-trust-suite) βββββββββββββββββββββββββββββββββ--async function cmdSearchFeedback(argv: ReadonlyArray<string>): Promise<number> {- const { flags } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- query: { type: "string" },- result: { type: "string" },- verdict: { type: "string" },- json: { type: "boolean" },- });- const query = typeof flags["query"] === "string" ? (flags["query"] as string) : "";- const resultPath = typeof flags["result"] === "string" ? (flags["result"] as string) : "";- const verdict = typeof flags["verdict"] === "string" ? (flags["verdict"] as string) : "";- if (!query || !resultPath) {- throw new CliError("usage: o2b search feedback --query <q> --result <path> --verdict up|down");- }- if (verdict !== "up" && verdict !== "down") {- throw new CliError("--verdict must be 'up' or 'down'");- }- const cfg = resolveConfig(flags);- const outcome = await captureRecallFeedback(cfg, { query, resultPath, verdict });- if (flags["json"] === true) {- process.stdout.write(- JSON.stringify({- recorded: true,- result_found: outcome.resultFound,- file: outcome.file,- learned: outcome.learned,- }) + "\n",- );- return 0;- }- const found = outcome.resultFound- ? ""- : " (result not in current top-50; recorded with zero contributions)";- process.stdout.write(- `recorded ${verdict} for ${resultPath}${found}\n` +- `learned weights now: ${formatLearnedWeights(outcome.learned)}\n`,- );- return 0;-}--async function cmdSearchWeights(argv: ReadonlyArray<string>): Promise<number> {- const { flags } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- reset: { type: "boolean" },- json: { type: "boolean" },- });- const cfg = resolveConfig(flags);- if (flags["reset"] === true) {- resetLearnedWeights(cfg.vault);- if (flags["json"] === true) {- process.stdout.write(JSON.stringify({ reset: true }) + "\n");- } else {- process.stdout.write("learned weights reset (feedback events kept)\n");- }- return 0;- }- const learned = readLearnedWeights(cfg.vault);- const payload = {- enabled: cfg.recall.learnedWeightsEnabled,- base: {- keywordWeight: cfg.keywordWeight,- semanticWeight: cfg.semanticWeight,- },- learned,- events: loadFeedbackEvents(cfg.vault).length,- bounds: { min: LEARNED_WEIGHT_MIN, max: LEARNED_WEIGHT_MAX },- };- if (flags["json"] === true) {- process.stdout.write(JSON.stringify(payload) + "\n");- return 0;- }- const lines = [- `learned weights: ${payload.enabled ? "enabled" : "disabled (search_learned_weights_enabled)"}`,- `base: kw=${cfg.keywordWeight} sem=${cfg.semanticWeight}`,- learned === null- ? "learned: none (no feedback recorded)"- : `learned: ${formatLearnedWeights(learned)} from ${learned.events} event(s)`,- `bounds: [${LEARNED_WEIGHT_MIN}, ${LEARNED_WEIGHT_MAX}]`,- ];- process.stdout.write(lines.join("\n") + "\n");- return 0;-}--function formatLearnedWeights(w: LearnedWeights): string {- return (- `kw=${w.keywordMul.toFixed(3)} sem=${w.semanticMul.toFixed(3)} ` +- `ent=${w.entityMul.toFixed(3)} rec=${w.recencyMul.toFixed(3)}`- );-}--// βββ provider registry (Embedding Provider Suite) ββββββββββββββββββββββββββββ--/** Structural shape shared by `ProviderProfile` and `RerankProviderProfile`. */-interface CliRegistryProfile {- readonly name: string;- readonly baseUrl: string;- readonly defaultModel: string;- readonly envKey: string | ReadonlyArray<string>;-}--/** Render an env-key that may be a single name or an ordered probe list. */-function formatEnvKey(envKey: string | ReadonlyArray<string>): string {- return typeof envKey === "string" ? envKey : envKey.join(",");-}--/**- * Parse a `--env-key` flag into a single name or an ordered probe list.- * Accepts a comma-separated list so multi-key failover is CLI-registrable;- * a single name stays a plain string (byte-identical single-key profile).- */-function parseEnvKeyFlag(raw: string): string | string[] {- const parts = raw- .split(",")- .map((k) => k.trim())- .filter((k) => k !== "");- return parts.length <= 1 ? (parts[0] ?? "") : parts;-}--/**- * CRUD operations a provider-style registry exposes to the CLI, plus the- * naming used in usage/output strings. `verb` is the CLI subcommand name- * (`provider` / `rerank-provider`); `kind` is the human noun used in prose- * (`provider` / `rerank provider`).- */-interface ProviderRegistryOps<T extends CliRegistryProfile> {- readonly verb: string;- readonly kind: string;- readonly load: (vault: string) => ReadonlyArray<T>;- readonly get: (vault: string, name: string) => T | null;- readonly add: (vault: string, profile: CliRegistryProfile) => ReadonlyArray<T>;- readonly remove: (vault: string, name: string) => { removed: boolean };- /**- * When true, `--env-key` accepts a comma-separated probe list for- * multi-key failover (embedding provider only). Rerank stays single-key.- */- readonly multiKey?: boolean;- /**- * Curated model catalog surfaced via the `presets` action and used as the- * `--model` default when omitted (embedding provider only). Advisory.- */- readonly presets?: ReadonlyArray<EmbeddingModelPreset>;- /** Recommended default model string when `--model` is omitted. */- readonly recommendedModel?: string;-}--/**- * Shared `add|list|show|remove` dispatch for the provider and rerank-provider- * registries (retrieval-precision-quality-loop, card A) - identical CRUD- * shape over two structurally identical profile registries.- */-async function runProviderRegistryCommand<T extends CliRegistryProfile>(- argv: ReadonlyArray<string>,- ops: ProviderRegistryOps<T>,-): Promise<number> {- const { verb, kind } = ops;- const action = argv[0];- const allowed = ops.presets- ? ["add", "list", "show", "remove", "presets"]- : ["add", "list", "show", "remove"];- if (!action || !allowed.includes(action)) {- throw new CliError(- `usage: o2b search ${verb} <add NAME --base-url U [--model M] --env-key K | list | show NAME | remove NAME${ops.presets ? " | presets" : ""}> [--json]`,- );- }- const { flags, positional } = parseFlags(argv.slice(1), {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- "base-url": { type: "string" },- model: { type: "string" },- "env-key": { type: "string" },- json: { type: "boolean" },- });- const json = flags["json"] === true;-- // `presets` is a static catalog listing; it needs no vault/config.- if (action === "presets" && ops.presets) {- if (json) {- process.stdout.write(JSON.stringify(ops.presets) + "\n");- return 0;- }- process.stdout.write(`curated embedding models (recommended: ${ops.recommendedModel}):\n`);- for (const p of ops.presets) {- const tag = p.multilingual ? "multilingual" : "monolingual";- process.stdout.write(` ${p.model}\n dim=${p.dimension} ${tag} - ${p.note}\n`);- }- return 0;- }-- const cfg = resolveConfig(flags);- const name = typeof positional[0] === "string" ? positional[0] : undefined;-- if (action === "list") {- const registry = ops.load(cfg.vault);- if (json) {- process.stdout.write(JSON.stringify(registry) + "\n");- return 0;- }- if (registry.length === 0) {- process.stdout.write(`no registered ${kind}s\n`);- return 0;- }- for (const p of registry) {- process.stdout.write(- `${p.name} ${p.baseUrl} model=${p.defaultModel} env=${formatEnvKey(p.envKey)}\n`,- );- }- return 0;- }-- if (action === "show") {- if (!name) throw new CliError(`usage: o2b search ${verb} show NAME`);- const profile = ops.get(cfg.vault, name);- if (!profile) {- process.stderr.write(`error: no registered ${kind} named '${name}'\n`);- return 1;- }- process.stdout.write(- json- ? JSON.stringify(profile) + "\n"- : `${profile.name}\n base-url: ${profile.baseUrl}\n model: ${profile.defaultModel}\n env-key: ${formatEnvKey(profile.envKey)}\n`,- );- return 0;- }-- if (action === "remove") {- if (!name) throw new CliError(`usage: o2b search ${verb} remove NAME`);- const { removed } = ops.remove(cfg.vault, name);- if (json) {- process.stdout.write(JSON.stringify({ removed, name }) + "\n");- } else {- process.stdout.write(removed ? `removed ${kind} '${name}'\n` : `no such ${kind} '${name}'\n`);- }- return removed ? 0 : 1;- }-- // add- if (!name)- throw new CliError(`usage: o2b search ${verb} add NAME --base-url U --model M --env-key K`);- const baseUrl = typeof flags["base-url"] === "string" ? (flags["base-url"] as string) : undefined;- const flagModel = typeof flags["model"] === "string" ? (flags["model"] as string) : undefined;- const envKey = typeof flags["env-key"] === "string" ? (flags["env-key"] as string) : undefined;- // `--model` may be omitted when the registry has a recommended default- // (embedding provider); custom models remain first-class and verbatim.- const model = flagModel ?? ops.recommendedModel;- const modelHint = ops.recommendedModel ? "[--model M]" : "--model M";- if (!baseUrl || !model || !envKey) {- throw new CliError(- `${verb} add requires --base-url, ${modelHint}, and --env-key (the env var NAME holding the API key)`,- );- }- const envKeyValue = ops.multiKey ? parseEnvKeyFlag(envKey) : envKey;- const registry = ops.add(cfg.vault, { name, baseUrl, defaultModel: model, envKey: envKeyValue });- const added = registry.find((p) => p.name === name)!;- if (json) {- process.stdout.write(JSON.stringify(added) + "\n");- } else {- const envHint = Array.isArray(envKeyValue) ? envKeyValue.join(" or ") : envKeyValue;- const modelNote = flagModel ? "" : ` (defaulted --model to recommended '${model}')`;- process.stdout.write(- `added ${kind} '${name}'${modelNote} (set ${envHint} in the environment to supply its key)\n`,- );- }- return 0;-}--async function cmdSearchProvider(argv: ReadonlyArray<string>): Promise<number> {- return runProviderRegistryCommand(argv, {- verb: "provider",- kind: "provider",- load: loadProviderRegistry,- get: getProviderProfile,- add: addProviderProfile,- remove: removeProviderProfile,- multiKey: true,- presets: EMBEDDING_MODEL_PRESETS,- recommendedModel: RECOMMENDED_EMBEDDING_MODEL,- });-}--// βββ rerank provider registry (retrieval-precision-quality-loop, card A) βββββ--async function cmdSearchRerankProvider(argv: ReadonlyArray<string>): Promise<number> {- return runProviderRegistryCommand(argv, {- verb: "rerank-provider",- kind: "rerank provider",- load: loadRerankRegistry,- get: getRerankProviderProfile,- // Rerank stays single-key; coerce any probe-list shape back to a string.- add: (vault, profile) =>- addRerankProviderProfile(vault, { ...profile, envKey: formatEnvKey(profile.envKey) }),- remove: removeRerankProviderProfile,- });-}--// βββ rerank-fit (per-store reranker fit check diagnostic) ββββββββββββββββββββ--async function cmdSearchRerankFit(argv: ReadonlyArray<string>): Promise<number> {- const { flags } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- "max-queries": { type: "string" },- "top-k": { type: "string" },- json: { type: "boolean" },- });- const cfg = resolveConfig(flags);- const maxQueries =- typeof flags["max-queries"] === "string" ? Number(flags["max-queries"]) : undefined;- const topK = typeof flags["top-k"] === "string" ? Number(flags["top-k"]) : undefined;- if (maxQueries !== undefined && (!Number.isInteger(maxQueries) || maxQueries < 1)) {- throw new CliError(`--max-queries must be a positive integer, got '${flags["max-queries"]}'`);- }- if (topK !== undefined && (!Number.isInteger(topK) || topK < 2)) {- throw new CliError(`--top-k must be an integer >= 2, got '${flags["top-k"]}'`);- }- const report = await rerankFitCheck(cfg, {- ...(maxQueries !== undefined ? { maxQueries } : {}),- ...(topK !== undefined ? { topK } : {}),- });- if (flags["json"] === true) {- process.stdout.write(- JSON.stringify({- ok: true,- applicable: report.applicable,- verdict: report.verdict,- correlation: report.correlation,- sampled_queries: report.sampledQueries,- recommendation: report.recommendation,- reason: report.reason,- }) + "\n",- );- return 0;- }- process.stdout.write(`rerank fit: ${report.verdict}\n`);- process.stdout.write(` ${report.reason}\n`);- if (report.correlation !== null) {- process.stdout.write(- ` correlation: ${report.correlation.toFixed(3)} over ${report.sampledQueries} query(ies)\n`,- );- }- if (report.verdict !== "fits" && report.verdict !== "inapplicable") {- process.stdout.write(` recommendation: ${report.recommendation}\n`);- }- return 0;-}--// βββ plan (graph-index query pre-pass) βββββββββββββββββββββββββββββββββββββββ--async function cmdSearchPlan(argv: ReadonlyArray<string>): Promise<number> {- const { flags, positional } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- hops: { type: "string", default: "2" },- limit: { type: "string", default: "10" },- "index-only": { type: "boolean" },- json: { type: "boolean" },- });- const query = positional.join(" ").trim();- if (query === "")- throw new CliError('usage: o2b search plan "<query>" [--index-only] [--hops N]');- const cfg = resolveConfig(flags);- const maxHops = Number(flags["hops"] ?? "2");- const shortlistLimit = Number(flags["limit"] ?? "10");- if (!Number.isInteger(maxHops) || maxHops < 0) {- throw new CliError(`--hops must be a non-negative integer, got '${flags["hops"]}'`);- }- if (!Number.isInteger(shortlistLimit) || shortlistLimit < 1) {- throw new CliError(`--limit must be a positive integer, got '${flags["limit"]}'`);- }- const plan = await planRead(cfg, query, {- indexOnly: flags["index-only"] === true,- maxHops,- shortlistLimit,- });- if (flags["json"] === true) {- process.stdout.write(JSON.stringify(plan) + "\n");- return 0;- }- process.stdout.write(`${plan.mode} (notes read: ${plan.notesRead})\n`);- if (plan.shortlist.length === 0) {- process.stdout.write(" no candidates\n");- return 0;- }- for (const e of plan.shortlist) {- const title = e.title ?? "(untitled)";- process.stdout.write(- ` ${e.path} "${title}" hops=${e.hops} degree=${e.degree} [${e.reasons.join(",")}]\n`,- );- }- return 0;-}--// βββ query ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {- const { flags, positional } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- limit: { type: "string", default: "10" },- semantic: { type: "boolean" },- "keyword-only": { type: "boolean" },- path: { type: "string" },- "keyword-weight": { type: "string" },- "semantic-weight": { type: "string" },- "auto-refresh": { type: "boolean" },- property: { type: "string-array" },- degree: { type: "string-array" },- visibility: { type: "string-array" },- "agent-scope": { type: "string" },- "query-doc": { type: "string" },- expand: { type: "boolean" },- disclosure: { type: "string" },- profile: { type: "string" },- "evidence-pack": { type: "boolean" },- "include-superseded": { type: "boolean" },- since: { type: "string" },- until: { type: "string" },- global: { type: "boolean" },- "no-record-access": { type: "boolean" },- json: { type: "boolean" },- verbose: { type: "boolean" },- });-- const rawQueryDocument =- typeof flags["query-doc"] === "string" ? (flags["query-doc"] as string) : undefined;- const structuredQuery =- rawQueryDocument !== undefined- ? parseStructuredRecallQueryDocument(rawQueryDocument)- : undefined;-- if (positional.length === 0 && structuredQuery === undefined) {- throw new CliError("query string is required");- }- if (flags["semantic"] === true && flags["keyword-only"] === true) {- throw new CliError("--semantic and --keyword-only are mutually exclusive");- }- const query =- positional.length > 0 ? positional.join(" ") : structuredRecallQueryText(structuredQuery!);- if (query.trim().length === 0) {- throw new CliError("query string is required when --query-doc has no searchable lanes");- }- const limitNum = Number(flags["limit"] ?? "10");- if (!Number.isInteger(limitNum) || limitNum < SEARCH_LIMIT_MIN || limitNum > SEARCH_LIMIT_MAX) {- throw new CliError(`--limit must be an integer in ${SEARCH_LIMIT_MIN}..${SEARCH_LIMIT_MAX}`);- }- const disclosureRaw = typeof flags["disclosure"] === "string" ? flags["disclosure"] : undefined;- if (disclosureRaw !== undefined && disclosureRaw !== "full" && disclosureRaw !== "cards") {- throw new CliError("--disclosure must be 'full' or 'cards'");- }-- const cfg = resolveConfig(flags);-- if (flags["auto-refresh"]) {- try {- await indexVault(cfg);- } catch (e) {- const msg = e instanceof Error ? e.message : String(e);- process.stderr.write(`auto-refresh failed: ${msg}\n`);- }- }-- // Pass `undefined` when no explicit flag is set so `search()` falls back- // to the config default. Passing `null` works by accident today but blurs- // the implicit/explicit policy boundary in Β§7 of the search design.- const semanticOverride: boolean | undefined =- flags["semantic"] === true ? true : flags["keyword-only"] === true ? false : undefined;-- const properties = parsePropertyFlags(flags["property"] as string[] | undefined);- const degreeFilters = parseDegreeFlags(flags["degree"] as string[] | undefined);- const visibility = flags["visibility"] as string[] | undefined;-- const searchOpts = {- query,- limit: limitNum,- semantic: semanticOverride,- keywordOnly: flags["keyword-only"] === true,- pathPrefix: typeof flags["path"] === "string" ? (flags["path"] as string) : undefined,- ...(properties !== undefined ? { properties } : {}),- ...(degreeFilters !== undefined ? { degreeFilters } : {}),- ...(visibility !== undefined && visibility.length > 0 ? { visibility } : {}),- // Owner-scope isolation (context-integrity-gates, Unit A): an- // owner-private page is returned only to its own scope. Omitting the- // flag applies no ownership filtering at all.- ...(typeof flags["agent-scope"] === "string"- ? { agentScope: flags["agent-scope"] as string }- : {}),- ...(structuredQuery !== undefined ? { structuredQuery } : {}),- ...(flags["expand"] === true ? { expand: true } : {}),- ...(disclosureRaw === "cards" ? { disclosure: "cards" as const } : {}),- ...(typeof flags["profile"] === "string" ? { profile: flags["profile"] as string } : {}),- ...(flags["evidence-pack"] === true ? { evidencePack: true } : {}),- ...(flags["include-superseded"] === true ? { includeSuperseded: true } : {}),- ...(typeof flags["since"] === "string" ? { since: flags["since"] as string } : {}),- ...(typeof flags["until"] === "string" ? { until: flags["until"] as string } : {}),- // Access recording (Time-Aware Recall & Activation Suite): the CLI- // surface opts in by default; --no-record-access suppresses it, and- // cross-vault union never records (results span foreign vaults).- ...(flags["global"] !== true && flags["no-record-access"] !== true- ? { recordAccess: true }- : {}),- };- // Cross-vault union (t_72a22658): explicit per-call opt-in fans the- // query out over profiles and read-only sources with origin labels.- const outcome =- flags["global"] === true- ? await searchAcrossVaults(- typeof flags["config"] === "string" ? (flags["config"] as string) : defaultConfigPath(),- cfg.vault,- searchOpts,- cfg,- )- : await search(cfg, searchOpts);-- if (flags["json"]) {- process.stdout.write(JSON.stringify(jsonForOutcome(outcome)) + "\n");- return 0;- }- process.stdout.write(renderOutcomeHuman(outcome, flags["verbose"] === true));- return 0;-}--/**- * Parse the repeatable `--property KEY=VALUE` flag into the- * `properties` map shape that `search()` consumes. Multiple- * `--property KEY=...` entries for the same KEY accumulate (OR).- * Different KEYs accumulate as separate entries (AND).- */-function parsePropertyFlags(- raw: ReadonlyArray<string> | undefined,-): ReadonlyMap<string, ReadonlyArray<string>> | undefined {- if (!raw || raw.length === 0) return undefined;- const acc = new Map<string, string[]>();- for (const entry of raw) {- const eq = entry.indexOf("=");- if (eq <= 0) {- throw new CliError(`--property must be KEY=VALUE, got: ${entry}`);- }- const key = entry.slice(0, eq).trim();- const value = entry.slice(eq + 1).trim();- if (key.length === 0 || value.length === 0) {- throw new CliError(`--property must be KEY=VALUE, got: ${entry}`);- }- const arr = acc.get(key) ?? [];- arr.push(value);- acc.set(key, arr);- }- const frozen = new Map<string, ReadonlyArray<string>>();- for (const [k, v] of acc) frozen.set(k, Object.freeze(v));- return frozen;-}--/**- * Parse the repeatable `--degree <field><op><count>` flag into the- * `degreeFilters` predicate list that `search()` consumes, e.g.- * `--degree backlinks=0` (orphans) or `--degree outlinks>=5` (hubs).- * Invalid syntax throws a typed `SearchError` from- * {@link parseDegreePredicate}, surfaced by the search verb's error- * handler as exit 2.- */-function parseDegreeFlags(raw: ReadonlyArray<string> | undefined): DegreePredicate[] | undefined {- if (!raw || raw.length === 0) return undefined;- return raw.map((entry) => parseDegreePredicate(entry));-}--function jsonForOutcome(o: SearchOutcome): unknown {- return {- results: o.results.map((r) => ({- path: r.path,- title: r.title,- content: r.content,- score: r.score,- keyword_score: r.keywordScore,- semantic_score: r.semanticScore,- link_boost: r.linkBoost,- recency_boost: r.recencyBoost,- start_line: r.startLine,- end_line: r.endLine,- search_type: r.searchType,- reasons: r.reasons,- // Conversation chronology (S1): present only for a note carrying an- // authored_at instant, so the shape stays byte-identical otherwise.- ...(r.authoredAt !== undefined ? { authored_at: r.authoredAt } : {}),- ...(r.origin !== undefined ? { origin: r.origin } : {}),- ...(o.evidencePack ? { why_retrieved: r.reasons } : {}),- document_id: r.documentId,- chunk_id: r.chunkId,- ...(r.relations && r.relations.length > 0 ? { relations: r.relations } : {}),- })),- warnings: o.warnings,- total: o.total,- ...(o.cards ? { cards: o.cards.map(serializeSearchCard) } : {}),- ...(o.evidencePack ? { evidence_pack: serializeEvidencePack(o.evidencePack) } : {}),- ...(o.surface !== undefined ? { surface: o.surface } : {}),- };-}--function renderOutcomeHuman(o: SearchOutcome, verbose: boolean): string {- // Progressive disclosure layer 1: render compact cards. The agent- // drills a hit with `o2b search expand --chunk <chunk_id>`.- if (o.cards !== undefined) {- const lines: string[] = [];- if (o.cards.length === 0) lines.push("(no results)");- o.cards.forEach((c, i) => {- const originSuffix = c.origin !== undefined ? ` β’ ${c.origin}` : "";- lines.push(`[${i + 1}] ${c.pointer} β’ ${c.score.toFixed(2)}${originSuffix}`);- lines.push(` ${c.snippet}`);- lines.push(` expand: o2b search expand --chunk ${c.chunkId}`);- if (verbose && c.reasons.length > 0) lines.push(` why: ${c.reasons.join(", ")}`);- lines.push("");- });- for (const w of o.warnings) lines.push(`warning: ${w}`);- return lines.join("\n") + (lines.length > 0 ? "" : "\n");- }- const lines: string[] = [];- if (o.results.length === 0) {- lines.push("(no results)");- }- o.results.forEach((r, i) => {- const score = r.score.toFixed(2);- const originSuffix = r.origin !== undefined ? ` β’ ${r.origin}` : "";- lines.push(`[${i + 1}] ${r.path} β’ ${score}${originSuffix}`);- // Conversation chronology (S1): show the authoring instant only for a- // note that carries one; a note without stays byte-identical.- const authoredSuffix =- r.authoredAt !== undefined- ? ` β’ authored ${new Date(r.authoredAt * 1000).toISOString()}`- : "";- lines.push(- ` line ${r.startLine}-${r.endLine} β’ ${r.searchType}${authoredSuffix}` +- (verbose- ? ` β’ kw=${r.keywordScore.toFixed(2)} sem=${r.semanticScore.toFixed(2)} link=${r.linkBoost.toFixed(2)} rec=${r.recencyBoost.toFixed(2)}`- : ""),- );- const snippet = r.content.trim().replace(/\s+/g, " ").slice(0, 140);- lines.push(` ${snippet}${r.content.length > 140 ? "β¦" : ""}`);- if (verbose && r.reasons.length > 0) {- lines.push(` why: ${r.reasons.join(", ")}`);- }- if (r.relations && r.relations.length > 0) {- const rel = r.relations.map((x) => `${x.relation} ${x.target}`).join(", ");- lines.push(` relations: ${rel}`);- }- lines.push("");- });- for (const w of o.warnings) lines.push(`warning: ${w}`);- return lines.join("\n") + (lines.length > 0 ? "" : "\n");-}--// βββ expand βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--/**- * Progressive disclosure layers 2 + 3: drill a layer-1 card (from- * `o2b search --disclosure cards`) into the fuller note and the paginated- * raw chunk transcript. Read-only; never rebuilds the index.- */-async function cmdSearchExpand(argv: ReadonlyArray<string>): Promise<number> {- const { flags } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- chunk: { type: "string" },- "raw-limit": { type: "string" },- cursor: { type: "string" },- "agent-scope": { type: "string" },- json: { type: "boolean" },- });- const chunkId = Number(flags["chunk"]);- if (!Number.isInteger(chunkId) || chunkId < 1) {- throw new CliError("--chunk must be a positive integer chunk id (from a card)");- }- let rawLimit: number | undefined;- if (typeof flags["raw-limit"] === "string") {- rawLimit = Number(flags["raw-limit"]);- if (!Number.isInteger(rawLimit) || rawLimit < 1) {- throw new CliError("--raw-limit must be a positive integer");- }- }- const cfg = resolveConfig(flags);- let result;- try {- result = await expandHit(cfg, {- chunkId,- ...(rawLimit !== undefined ? { rawLimit } : {}),- ...(typeof flags["cursor"] === "string" ? { cursor: flags["cursor"] as string } : {}),- ...(typeof flags["agent-scope"] === "string"- ? { agentScope: flags["agent-scope"] as string }- : {}),- });- } catch (e) {- if (e instanceof SearchError) {- process.stderr.write(`error: ${e.message}\n`);- return 2;- }- throw e;- }- if (flags["json"]) {- process.stdout.write(- JSON.stringify({- chunk_id: result.chunkId,- note: {- document_id: result.note.documentId,- path: result.note.path,- title: result.note.title,- line_start: result.note.lineStart,- line_end: result.note.lineEnd,- pointer: result.note.pointer,- content: result.note.content,- },- raw_content: result.raw_content.map((c) => ({- chunk_id: c.chunkId,- chunk_index: c.chunkIndex,- start_line: c.startLine,- end_line: c.endLine,- pointer: c.pointer,- content: c.content,- })),- next_cursor: result.next_cursor,- }) + "\n",- );- return 0;- }- const lines: string[] = [];- lines.push(`note: ${result.note.pointer}`);- if (result.note.title !== null) lines.push(`title: ${result.note.title}`);- lines.push("");- lines.push(result.note.content);- lines.push("");- lines.push(`ββ raw chunks (${result.raw_content.length}) ββ`);- for (const c of result.raw_content) {- lines.push(`[${c.pointer}]`);- lines.push(c.content);- lines.push("");- }- if (result.next_cursor !== null) {- lines.push(`more: o2b search expand --chunk ${result.chunkId} --cursor ${result.next_cursor}`);- }- process.stdout.write(lines.join("\n") + "\n");- return 0;-}--// βββ index ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--/**- * Advisory stream for the two index builders (no-dead-ends, task 5).- * `index` and `reindex` reach the same terminal state - an index that- * now exists and has not been queried - so they name the same exit- * through the same registry code.- *- * The read path is deliberately NOT covered: `search query` self-heals a- * missing index by building it, and pointing an operator at the indexer- * there would describe a world that self-heal removed.- */-function indexAdvisoryStream(argv: ReadonlyArray<string>, jsonRequested: boolean): AdvisoryStream {- return { command: "search", argv, jsonRequested };-}--/**- * True when the run this `stats` describes left the index covering every- * document, which is what the `search-index-built` class ("search index- * up to date") asserts.- *- * `stats.errors` means, per its own declaration, "this file did not- * index". Emitting the class with entries in it would tell the operator- * the index is current while the tool knows documents are missing from- * it, and would point at `o2b search query` as though a query over it- * were complete. Re-labelling the class instead was considered and- * rejected: a truthful label for the failed case would have to be- * vacuous, and it would leave the misleading COMMAND in place.- *- * A run with errors is left deliberately without a rail line. The errors- * block already names every affected path and message, and what repairs- * an unreadable or malformed note is a judgement over that file's- * content - there is no `o2b` command that performs it, and naming the- * indexer again would advise repeating the run that just failed.- */-function indexIsComplete(stats: IndexStats): boolean {- return stats.errors.length === 0;-}--async function cmdSearchIndex(argv: ReadonlyArray<string>): Promise<number> {- const { flags } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- embeddings: { type: "boolean" },- force: { type: "boolean" },- "force-cost": { type: "boolean" },- concurrency: { type: "string" },- verbose: { type: "boolean" },- json: { type: "boolean" },- });- const cfg = resolveConfig(flags);-- const events: IndexProgressEvent[] = [];- const safeguard = createSafeguard({- operation: "reindex",- timeoutMs: resolveSafeguardTimeoutMs("reindex", flags["config"] as string | undefined),- });- const stats = await indexVault(cfg, {- safeguard,- embeddings: flags["embeddings"] === true,- force: flags["force"] === true,- forceCost: flags["force-cost"] === true,- onFile: (e) => {- events.push(e);- if (flags["verbose"]) {- const msg = e.message ? ` ${e.message}` : "";- process.stderr.write(`${e.kind}\t${e.path}${msg}\n`);- }- },- });-- const complete = indexIsComplete(stats);- if (flags["json"]) {- // no-dead-ends, phase 3: the rail suppresses its line on this stream- // and returns the resolved step precisely so the payload can carry- // it. Absent whenever the run left the index incomplete.- process.stdout.write(- JSON.stringify({- ...(jsonForStats(stats, cfg) as Record<string, unknown>),- ...(complete ? nextCommandField("search-index-built") : {}),- }) + "\n",- );- } else {- process.stdout.write(renderStatsHuman(stats, cfg));- }- if (complete) {- emitNextStep("search-index-built", indexAdvisoryStream(argv, flags["json"] === true));- }- return 0;-}--// βββ watch ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--/**- * Long-running file-watcher (Unit 3): watch the vault for `.md` edits and- * incrementally re-index after a quiet window. Reuses the existing- * incremental `indexVault` (mtime/hash fastpath skips unchanged files),- * so a debounced flush only does work for the files that actually- * changed. A single-flight guard prevents overlapping passes; the- * command runs until SIGINT/SIGTERM and shuts the watcher down cleanly.- */-async function cmdSearchWatch(argv: ReadonlyArray<string>): Promise<number> {- const { flags } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- embeddings: { type: "boolean" },- "debounce-ms": { type: "string", default: "800" },- });- const cfg = resolveConfig(flags);- const debounceMs = Number(flags["debounce-ms"]);- if (!Number.isFinite(debounceMs) || debounceMs < 0) {- throw new CliError(`--debounce-ms must be a non-negative number, got ${flags["debounce-ms"]}`);- }- const planner = new IndexWatchPlanner({ debounceMs });-- let watcher: FSWatcher;- try {- watcher = watch(cfg.vault, { recursive: true, persistent: true });- } catch (e) {- // Fail loudly, not as a silent no-op: recursive fs.watch is not- // available on every platform/filesystem.- throw new CliError(- `cannot start a recursive watch on ${cfg.vault}: ${e instanceof Error ? e.message : String(e)}. ` +- "Recursive fs.watch is unsupported here; schedule `o2b search index` on a timer instead.",- );- }-- // Single-flight + graceful-shutdown coordinator (Indexer Durability- // suite). A SIGINT/SIGTERM aborts the in-flight pass at its next file- // boundary and waits for it to settle (bounded by the configured- // grace window) before exiting, so a signal never kills a run- // mid-write. indexInto closes its store in a finally, so the aborted- // pass still consolidates the WAL and releases the writer lock.- const runner = new IndexWatchRunner({- graceMs: cfg.shutdownGraceMs,- index: async (signal): Promise<void> => {- const due = planner.take(Date.now());- if (due.length === 0) return;- try {- const stats = await indexVault(cfg, { embeddings: flags["embeddings"] === true, signal });- process.stderr.write(- `synced ${due.length} change(s): +${stats.added} ~${stats.updated} =${stats.unchanged}` +- (stats.errors.length > 0 ? ` (${stats.errors.length} error(s))` : "") +- "\n",- );- } catch (e) {- // An abort is the expected stop on shutdown - let the runner- // observe it. Any other failure must not kill the watcher.- if (e instanceof SafeguardAbortError) throw e;- process.stderr.write(`index sync failed: ${e instanceof Error ? e.message : String(e)}\n`);- }- },- });-- watcher.on("error", (e) => {- process.stderr.write(`watch error: ${e instanceof Error ? e.message : String(e)}\n`);- });- watcher.on("change", (_eventType, filename) => {- if (typeof filename !== "string") return;- if (!filename.toLowerCase().endsWith(".md")) return;- planner.record(canonicalNotePath(filename), Date.now());- });-- const timer = setInterval(- () => {- void runner.flush();- },- Math.max(50, debounceMs),- );-- return await new Promise<number>((resolve) => {- const shutdown = async (): Promise<void> => {- if (runner.isStopped) return;- clearInterval(timer);- watcher.close();- // Drain the in-flight pass (aborted) within the grace window.- // A second SIGINT/SIGTERM bypasses this (process.once consumed- // the first), falling back to the default terminate = force exit.- await runner.shutdown();- process.stderr.write("watch stopped\n");- resolve(0);- };- process.once("SIGINT", () => void shutdown());- process.once("SIGTERM", () => void shutdown());- process.stderr.write(- `watching ${cfg.vault} for .md changes (debounce ${debounceMs}ms); Ctrl-C to stop\n`,- );- });-}--function jsonForStats(stats: IndexStats, cfg: ResolvedSearchConfig): unknown {- return {- stats: {- added: stats.added,- updated: stats.updated,- unchanged: stats.unchanged,- deleted: stats.deleted,- chunks_total: stats.chunksTotal,- embeddings_computed: stats.embeddingsComputed,- embeddings_retries: stats.embeddingsRetries,- },- errors: stats.errors.map((e) => ({ path: e.path, message: e.message })),- // Unit F. Conditional so a vault with no malformed frontmatter emits- // exactly the payload it emitted before this field existed.- ...(stats.frontmatterNotices.length > 0- ? {- frontmatter_notices: stats.frontmatterNotices.map((n) => ({- code: n.code,- site: n.site,- ...(n.path !== undefined ? { path: n.path } : {}),- detail: n.detail,- })),- }- : {}),- duration_ms: stats.durationMs,- vault: cfg.vault,- db_path: cfg.dbPath,- };-}--function renderStatsHuman(stats: IndexStats, cfg: ResolvedSearchConfig): string {- const lines: string[] = [];- lines.push(`indexing vault: ${cfg.vault}`);- lines.push(` added: ${stats.added} files, ${stats.chunksTotal} chunks`);- lines.push(` updated: ${stats.updated} files`);- lines.push(` unchanged: ${stats.unchanged} files`);- lines.push(` deleted: ${stats.deleted} files`);- if (stats.embeddingsComputed > 0 || stats.embeddingsRetries > 0) {- lines.push(- ` embeddings: ${stats.embeddingsComputed} computed (${stats.embeddingsRetries} retries)`,- );- }- if (stats.errors.length > 0) {- lines.push(` errors:`);- for (const e of stats.errors) lines.push(` - ${e.path}: ${e.message}`);- }- // Unit F. Below the errors block and only when non-empty: these files- // indexed successfully, they just lost a frontmatter field.- if (stats.frontmatterNotices.length > 0) {- lines.push(` frontmatter:`);- for (const n of stats.frontmatterNotices) {- lines.push(` - ${formatDegradationNotice(n)}`);- }- }- lines.push(`done in ${(stats.durationMs / 1000).toFixed(1)}s`);- return lines.join("\n") + "\n";-}--// βββ reindex ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<number> {- const { flags } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- embeddings: { type: "boolean" },- "force-cost": { type: "boolean" },- concurrency: { type: "string" },- json: { type: "boolean" },- verbose: { type: "boolean" },- "cron-template": { type: "boolean" },- interval: { type: "string" },- });- if (flags["cron-template"] === true) {- const intervalRaw = (flags["interval"] as string | undefined) ?? "30m";- try {- const body = renderCronTemplate(intervalRaw);- process.stdout.write(body);- return 0;- } catch (err) {- if (err instanceof CronTemplateError) {- process.stderr.write(`error: ${err.message}\n`);- return 1;- }- throw err;- }- }- const cfg = resolveConfig(flags);- const stats = await reindexVault(cfg, {- safeguard: createSafeguard({- operation: "reindex",- timeoutMs: resolveSafeguardTimeoutMs("reindex", flags["config"] as string | undefined),- }),- embeddings: flags["embeddings"] === true,- forceCost: flags["force-cost"] === true,- onFile: flags["verbose"] ? (e) => process.stderr.write(`${e.kind}\t${e.path}\n`) : undefined,- });- const complete = indexIsComplete(stats);- if (flags["json"]) {- // no-dead-ends, phase 3: the rail suppresses its line on this stream- // and returns the resolved step precisely so the payload can carry- // it. Absent whenever the run left the index incomplete.- process.stdout.write(- JSON.stringify({- ...(jsonForStats(stats, cfg) as Record<string, unknown>),- ...(complete ? nextCommandField("search-index-built") : {}),- }) + "\n",- );- } else {- process.stdout.write(renderStatsHuman(stats, cfg));- }- if (complete) {- emitNextStep("search-index-built", indexAdvisoryStream(argv, flags["json"] === true));- }- return 0;-}--// βββ status βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--async function cmdSearchStatus(argv: ReadonlyArray<string>): Promise<number> {- const { flags } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- json: { type: "boolean" },- });- const cfg = resolveConfig(flags);- const status = await indexStatus(cfg);- if (flags["json"]) {- process.stdout.write(- JSON.stringify({- ...(serializeIndexStatus(status) as Record<string, unknown>),- // Same polarity as the human twin below, so the two conditions- // read as one rule rather than as each other's negation.- ...(!status.exists ? nextCommandField("search-index-missing") : {}),- }) + "\n",- );- return 0;- }- process.stdout.write(renderStatusHuman(status));- // no-dead-ends, phase 3: the pointer used to be spliced into the- // renderer's first line, which is a second emission mechanism AND- // beyond the reach of a scan over writer call sites. The rail decides- // the format; the condition is the one the claim rests on.- if (!status.exists) {- // The `--json` branch above returned, so this stream is provably a- // human one; the JSON payload carries the same exit as a field.- emitNextStep("search-index-missing", indexAdvisoryStream(argv, false));- }- return 0;-}--function renderStatusHuman(s: IndexStatusSnapshot): string {- if (!s.exists) {- return `index: not initialised\n path: ${s.indexPath}\n`;- }- const lines: string[] = [];- lines.push(`index: ${s.indexPath}`);- lines.push(`schema_version: ${s.schemaVersion}`);- lines.push(`documents: ${s.documents}`);- lines.push(`chunks: ${s.chunks}`);- lines.push(`embeddings: ${s.embeddings} (stale: ${s.staleEmbeddings})`);- lines.push(`embedding_model: ${s.embeddingModel ?? "(none)"}`);- lines.push(`embedding_dimension: ${s.embeddingDimension ?? "(none)"}`);- lines.push(`embedding_signature: ${s.embeddingSignature ?? "(disabled)"}`);- if (s.estimatedRefreshCostUsd > 0) {- lines.push(`refresh_cost_est: $${s.estimatedRefreshCostUsd.toFixed(4)}`);- }- lines.push(`vec_extension: ${s.vecExtension}`);- lines.push(`semantic_enabled: ${s.semanticEnabled}`);- lines.push(`embedding_key: ${s.embeddingKeyPresent ? "present" : "missing"}`);- lines.push(`last_indexed_at: ${s.lastIndexedAt ?? "(never)"}`);- lines.push(`last_full_index_at: ${s.lastFullIndexAt ?? "(never)"}`);- for (const w of s.warnings) lines.push(`warning: ${w}`);- return lines.join("\n") + "\n";-}--// βββ check ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--async function cmdSearchCheck(argv: ReadonlyArray<string>): Promise<number> {- const { flags } = parseFlags(argv, {- vault: { type: "string" },- config: { type: "string" },- db: { type: "string" },- json: { type: "boolean" },- });- const cfg = resolveConfig(flags);- const report = await indexCheck(cfg);- if (flags["json"]) {- process.stdout.write(JSON.stringify(jsonForCheck(report)) + "\n");- } else {- process.stdout.write(renderCheckHuman(report));- }- return report.fatal.length > 0 ? 1 : 0;-}--function jsonForCheck(r: IndexCheckReport): unknown {- return {- vault_readable: r.vaultReadable,- index_dir_writable: r.indexDirWritable,- sqlite_ok: r.sqliteOk,- fts5_ok: r.fts5Ok,- vec_extension: r.vecExtension,- embedding_key_resolved: r.embeddingKeyResolved,- provider_reachable: r.providerReachable,- provider_reason: r.providerReason,- // Emitted only on drift, so a matching store's JSON is byte-identical- // to the pre-gate output (context-integrity-gates, Unit E).- ...(r.embeddingAbi.length > 0- ? { embedding_abi: serializeStampMismatches(r.embeddingAbi) }- : {}),- warnings: r.warnings,- fatal: r.fatal,- recommendations: r.recommendations,- };-}--function renderCheckHuman(r: IndexCheckReport): string {- const lines: string[] = [];- const ok = (b: boolean) => (b ? "OK" : "MISSING");- lines.push(`vault_readable: ${ok(r.vaultReadable)}`);- lines.push(`index_dir_writable: ${ok(r.indexDirWritable)}`);- lines.push(`sqlite_ok: ${ok(r.sqliteOk)}`);- lines.push(`fts5_ok: ${ok(r.fts5Ok)}`);- lines.push(`vec_extension: ${r.vecExtension}`);- lines.push(`embedding_key: ${ok(r.embeddingKeyResolved)}`);- // Only on drift: a matching store renders exactly as before.- for (const m of r.embeddingAbi) {- lines.push(`embedding_abi: ${formatStampMismatch(m)}`);- }- if (r.providerReachable !== null) {- lines.push(`provider_reachable: ${r.providerReachable ? "OK" : "FAIL"}`);- if (r.providerReason) lines.push(`provider_reason: ${r.providerReason}`);- }- for (const w of r.warnings) lines.push(`warning: ${w}`);- for (const f of r.fatal) lines.push(`fatal: ${f}`);- if (r.recommendations.length > 0) {- lines.push("");- lines.push("recommendations:");- for (const rec of r.recommendations) lines.push(` - ${rec}`);- }- return lines.join("\n") + "\n";-}diff --git a/src/cli/search/helpers.ts b/src/cli/search/helpers.tsnew file mode 100644index 00000000..33ed43ab--- /dev/null+++ b/src/cli/search/helpers.ts@@ -0,0 +1,114 @@+/**+ * Shared plumbing for the `o2b search` verbs.+ *+ * # Import convention (load-bearing)+ *+ * Every file under `src/cli/search/verbs/` MUST import shared helpers+ * through this module β never directly from `../../argparse.ts`. The+ * barrel keeps one source of truth for "what is available to a search+ * verb" and lets the helper bodies move between submodules without a+ * cross-cutting import sweep. It mirrors the convention+ * `src/cli/brain/helpers.ts` already establishes for the Brain verbs.+ */++import { defaultConfigPath, resolveVault } from "../../core/config.ts";+import { resolveSearchConfig, type ResolvedSearchConfig } from "../../core/search/index.ts";+import { CliError, type FlagsSchema } from "../argparse.ts";+import type { AdvisoryStream } from "../advisory-rail.ts";++/** Parsed flags shape every search verb receives from `parseFlags`. */+export type SearchVerbFlags = Record<string, string | boolean | string[] | undefined>;++/**+ * The vault-addressing triple every search verb accepts. Spread first in+ * each verb's schema so the declaration order β and therefore the parse β+ * stays what it was when each verb spelled the three out itself.+ */+export const VAULT_FLAGS: FlagsSchema = Object.freeze({+ vault: { type: "string" },+ config: { type: "string" },+ db: { type: "string" },+});++/** A flag's value when it was supplied as a string, `undefined` otherwise. */+export function flagString(flags: SearchVerbFlags, name: string): string | undefined {+ const value = flags[name];+ return typeof value === "string" ? value : undefined;+}++/** True when the flag was passed; every boolean flag is opt-in. */+export function flagBoolean(flags: SearchVerbFlags, name: string): boolean {+ return flags[name] === true;+}++/**+ * Whether a numeric flag parsed to an integer inside `bounds`.+ *+ * Only the predicate is shared. Each verb words its own bound differently+ * (`--raw-limit must be a positive integer` vs `--limit must be a positive+ * integer, got '<raw>'`) and every one of those strings is part of the CLI+ * contract, so both the message and the `throw` stay at the call site β+ * which is also what keeps each verb's refusal visible where it is made.+ */+export function isIntegerWithin(+ value: number,+ bounds: { readonly min: number; readonly max?: number },+): boolean {+ return (+ Number.isInteger(value) &&+ value >= bounds.min &&+ (bounds.max === undefined || value <= bounds.max)+ );+}++/** The config file this invocation reads: an explicit `--config`, else the default. */+export function resolveConfigPath(flags: SearchVerbFlags): string {+ return flagString(flags, "config") ?? defaultConfigPath();+}++export function resolveConfig(flags: SearchVerbFlags): ResolvedSearchConfig {+ const flagVault = flagString(flags, "vault");+ const configPath = resolveConfigPath(flags);+ const vault = flagVault ?? resolveVault(configPath) ?? null;+ if (!vault) {+ throw new CliError(+ "no vault configured. Pass --vault <path> or run `o2b init --vault <path> ...` first.",+ );+ }+ const dbFlag = flagString(flags, "db");+ const kwFlag = flagString(flags, "keyword-weight");+ const semFlag = flagString(flags, "semantic-weight");+ const concurrencyFlag = flagString(flags, "concurrency");+ const overrides = {+ ...(dbFlag !== undefined ? { dbPath: dbFlag } : {}),+ ...(kwFlag !== undefined ? { keywordWeight: Number(kwFlag) } : {}),+ ...(semFlag !== undefined ? { semanticWeight: Number(semFlag) } : {}),+ ...(concurrencyFlag !== undefined+ ? { semantic: { concurrency: Number(concurrencyFlag) } }+ : {}),+ };+ return resolveSearchConfig({ vault, configPath, overrides });+}++/**+ * Advisory stream for the search verbs that name an exit (no-dead-ends,+ * task 5). `index` and `reindex` reach the same terminal state β an index+ * that now exists and has not been queried β so they name the same exit+ * through the same registry code; `status` names the indexer from the+ * opposite state.+ *+ * The read path is deliberately NOT covered: `search query` self-heals a+ * missing index by building it, and pointing an operator at the indexer+ * there would describe a world that self-heal removed.+ */+export function searchAdvisoryStream(+ argv: ReadonlyArray<string>,+ jsonRequested: boolean,+): AdvisoryStream {+ return { command: "search", argv, jsonRequested };+}++// ββ Re-exports (the barrel that verb handlers import from) ββββββββββββββββββ++export { CliError, parseFlags } from "../argparse.ts";+export type { ResolvedSearchConfig };diff --git a/src/cli/search/outcome-render.ts b/src/cli/search/outcome-render.tsnew file mode 100644index 00000000..0c347b3f--- /dev/null+++ b/src/cli/search/outcome-render.ts@@ -0,0 +1,112 @@+/**+ * Presentation of a {@link SearchOutcome} for `o2b search <query>`: the+ * `--json` payload and the human transcript. Every byte either function+ * produces is a CLI contract.+ */++import { serializeEvidencePack, serializeSearchCard } from "../../core/search/index.ts";+import type { SearchOutcome } from "../../core/search/index.ts";++/** Field separator in the human transcript's header lines. */+const BULLET = " β’ ";++/** What an empty result set renders as, in both disclosure modes. */+const NO_RESULTS = "(no results)";++/** Longest snippet body shown per hit before it is elided. */+const SNIPPET_MAX_CHARS = 140;++/** Cross-vault origin label, appended only when the hit carries one. */+function originSuffix(origin: string | undefined): string {+ return origin !== undefined ? `${BULLET}${origin}` : "";+}++/**+ * A rendered transcript ends with a newline exactly once: the lines are+ * newline-joined, and an empty transcript contributes the newline itself.+ */+function joinLines(lines: ReadonlyArray<string>): string {+ return lines.join("\n") + (lines.length > 0 ? "" : "\n");+}++export function jsonForOutcome(o: SearchOutcome): unknown {+ return {+ results: o.results.map((r) => ({+ path: r.path,+ title: r.title,+ content: r.content,+ score: r.score,+ keyword_score: r.keywordScore,+ semantic_score: r.semanticScore,+ link_boost: r.linkBoost,+ recency_boost: r.recencyBoost,+ start_line: r.startLine,+ end_line: r.endLine,+ search_type: r.searchType,+ reasons: r.reasons,+ // Conversation chronology (S1): present only for a note carrying an+ // authored_at instant, so the shape stays byte-identical otherwise.+ ...(r.authoredAt !== undefined ? { authored_at: r.authoredAt } : {}),+ ...(r.origin !== undefined ? { origin: r.origin } : {}),+ ...(o.evidencePack ? { why_retrieved: r.reasons } : {}),+ document_id: r.documentId,+ chunk_id: r.chunkId,+ ...(r.relations && r.relations.length > 0 ? { relations: r.relations } : {}),+ })),+ warnings: o.warnings,+ total: o.total,+ ...(o.cards ? { cards: o.cards.map(serializeSearchCard) } : {}),+ ...(o.evidencePack ? { evidence_pack: serializeEvidencePack(o.evidencePack) } : {}),+ ...(o.surface !== undefined ? { surface: o.surface } : {}),+ };+}++export function renderOutcomeHuman(o: SearchOutcome, verbose: boolean): string {+ // Progressive disclosure layer 1: render compact cards. The agent+ // drills a hit with `o2b search expand --chunk <chunk_id>`.+ if (o.cards !== undefined) {+ const lines: string[] = [];+ if (o.cards.length === 0) lines.push(NO_RESULTS);+ o.cards.forEach((c, i) => {+ lines.push(`[${i + 1}] ${c.pointer}${BULLET}${c.score.toFixed(2)}${originSuffix(c.origin)}`);+ lines.push(` ${c.snippet}`);+ lines.push(` expand: o2b search expand --chunk ${c.chunkId}`);+ if (verbose && c.reasons.length > 0) lines.push(` why: ${c.reasons.join(", ")}`);+ lines.push("");+ });+ for (const w of o.warnings) lines.push(`warning: ${w}`);+ return joinLines(lines);+ }+ const lines: string[] = [];+ if (o.results.length === 0) {+ lines.push(NO_RESULTS);+ }+ o.results.forEach((r, i) => {+ const score = r.score.toFixed(2);+ lines.push(`[${i + 1}] ${r.path}${BULLET}${score}${originSuffix(r.origin)}`);+ // Conversation chronology (S1): show the authoring instant only for a+ // note that carries one; a note without stays byte-identical.+ const authoredSuffix =+ r.authoredAt !== undefined+ ? `${BULLET}authored ${new Date(r.authoredAt * 1000).toISOString()}`+ : "";+ lines.push(+ ` line ${r.startLine}-${r.endLine}${BULLET}${r.searchType}${authoredSuffix}` ++ (verbose+ ? `${BULLET}kw=${r.keywordScore.toFixed(2)} sem=${r.semanticScore.toFixed(2)} link=${r.linkBoost.toFixed(2)} rec=${r.recencyBoost.toFixed(2)}`+ : ""),+ );+ const snippet = r.content.trim().replace(/\s+/g, " ").slice(0, SNIPPET_MAX_CHARS);+ lines.push(` ${snippet}${r.content.length > SNIPPET_MAX_CHARS ? "β¦" : ""}`);+ if (verbose && r.reasons.length > 0) {+ lines.push(` why: ${r.reasons.join(", ")}`);+ }+ if (r.relations && r.relations.length > 0) {+ const rel = r.relations.map((x) => `${x.relation} ${x.target}`).join(", ");+ lines.push(` relations: ${rel}`);+ }+ lines.push("");+ });+ for (const w of o.warnings) lines.push(`warning: ${w}`);+ return joinLines(lines);+}diff --git a/src/cli/search/verbs/check.ts b/src/cli/search/verbs/check.tsnew file mode 100644index 00000000..3255311d--- /dev/null+++ b/src/cli/search/verbs/check.ts@@ -0,0 +1,77 @@+/**+ * `o2b search check` β pre-flight diagnostics over everything search needs+ * (vault, index directory, SQLite/FTS5, the vector extension, the+ * embedding key, the provider) plus the ABI stamp of the stored vectors.+ */++import { formatStampMismatch } from "../../../core/integrity/stamp.ts";+import { indexCheck, serializeStampMismatches } from "../../../core/search/index.ts";+import type { IndexCheckReport } from "../../../core/search/index.ts";+import { flagBoolean, parseFlags, resolveConfig, VAULT_FLAGS } from "../helpers.ts";++export async function cmdSearchCheck(argv: ReadonlyArray<string>): Promise<number> {+ const { flags } = parseFlags(argv, {+ ...VAULT_FLAGS,+ json: { type: "boolean" },+ });+ const cfg = resolveConfig(flags);+ const report = await indexCheck(cfg);+ if (flagBoolean(flags, "json")) {+ process.stdout.write(JSON.stringify(jsonForCheck(report)) + "\n");+ } else {+ process.stdout.write(renderCheckHuman(report));+ }+ return report.fatal.length > 0 ? 1 : 0;+}++function jsonForCheck(r: IndexCheckReport): unknown {+ return {+ vault_readable: r.vaultReadable,+ index_dir_writable: r.indexDirWritable,+ sqlite_ok: r.sqliteOk,+ fts5_ok: r.fts5Ok,+ vec_extension: r.vecExtension,+ embedding_key_resolved: r.embeddingKeyResolved,+ provider_reachable: r.providerReachable,+ provider_reason: r.providerReason,+ // Emitted only on drift, so a matching store's JSON is byte-identical+ // to the pre-gate output (context-integrity-gates, Unit E).+ ...(r.embeddingAbi.length > 0+ ? { embedding_abi: serializeStampMismatches(r.embeddingAbi) }+ : {}),+ warnings: r.warnings,+ fatal: r.fatal,+ recommendations: r.recommendations,+ };+}++/** Render one pre-flight probe's verdict, in the wording the check has always used. */+function ok(passed: boolean): string {+ return passed ? "OK" : "MISSING";+}++function renderCheckHuman(r: IndexCheckReport): string {+ const lines: string[] = [];+ lines.push(`vault_readable: ${ok(r.vaultReadable)}`);+ lines.push(`index_dir_writable: ${ok(r.indexDirWritable)}`);+ lines.push(`sqlite_ok: ${ok(r.sqliteOk)}`);+ lines.push(`fts5_ok: ${ok(r.fts5Ok)}`);+ lines.push(`vec_extension: ${r.vecExtension}`);+ lines.push(`embedding_key: ${ok(r.embeddingKeyResolved)}`);+ // Only on drift: a matching store renders exactly as before.+ for (const m of r.embeddingAbi) {+ lines.push(`embedding_abi: ${formatStampMismatch(m)}`);+ }+ if (r.providerReachable !== null) {+ lines.push(`provider_reachable: ${r.providerReachable ? "OK" : "FAIL"}`);+ if (r.providerReason) lines.push(`provider_reason: ${r.providerReason}`);+ }+ for (const w of r.warnings) lines.push(`warning: ${w}`);+ for (const f of r.fatal) lines.push(`fatal: ${f}`);+ if (r.recommendations.length > 0) {+ lines.push("");+ lines.push("recommendations:");+ for (const rec of r.recommendations) lines.push(` - ${rec}`);+ }+ return lines.join("\n") + "\n";+}diff --git a/src/cli/search/verbs/expand.ts b/src/cli/search/verbs/expand.tsnew file mode 100644index 00000000..eeec8123--- /dev/null+++ b/src/cli/search/verbs/expand.ts@@ -0,0 +1,101 @@+/**+ * `o2b search expand` β progressive disclosure layers 2 + 3: drill a+ * layer-1 card (from `o2b search --disclosure cards`) into the fuller note+ * and the paginated raw chunk transcript. Read-only; never rebuilds the+ * index.+ */++import { expandHit, SearchError } from "../../../core/search/index.ts";+import {+ CliError,+ flagBoolean,+ flagString,+ isIntegerWithin,+ parseFlags,+ resolveConfig,+ VAULT_FLAGS,+} from "../helpers.ts";++export async function cmdSearchExpand(argv: ReadonlyArray<string>): Promise<number> {+ const { flags } = parseFlags(argv, {+ ...VAULT_FLAGS,+ chunk: { type: "string" },+ "raw-limit": { type: "string" },+ cursor: { type: "string" },+ "agent-scope": { type: "string" },+ json: { type: "boolean" },+ });+ const chunkId = Number(flags["chunk"]);+ if (!isIntegerWithin(chunkId, { min: 1 })) {+ throw new CliError("--chunk must be a positive integer chunk id (from a card)");+ }+ let rawLimit: number | undefined;+ const rawLimitFlag = flagString(flags, "raw-limit");+ if (rawLimitFlag !== undefined) {+ rawLimit = Number(rawLimitFlag);+ if (!isIntegerWithin(rawLimit, { min: 1 })) {+ throw new CliError("--raw-limit must be a positive integer");+ }+ }+ const cfg = resolveConfig(flags);+ const cursor = flagString(flags, "cursor");+ const agentScope = flagString(flags, "agent-scope");+ let result;+ try {+ result = await expandHit(cfg, {+ chunkId,+ ...(rawLimit !== undefined ? { rawLimit } : {}),+ ...(cursor !== undefined ? { cursor } : {}),+ ...(agentScope !== undefined ? { agentScope } : {}),+ });+ } catch (e) {+ if (e instanceof SearchError) {+ process.stderr.write(`error: ${e.message}\n`);+ return 2;+ }+ throw e;+ }+ if (flagBoolean(flags, "json")) {+ process.stdout.write(+ JSON.stringify({+ chunk_id: result.chunkId,+ note: {+ document_id: result.note.documentId,+ path: result.note.path,+ title: result.note.title,+ line_start: result.note.lineStart,+ line_end: result.note.lineEnd,+ pointer: result.note.pointer,+ content: result.note.content,+ },+ raw_content: result.raw_content.map((c) => ({+ chunk_id: c.chunkId,+ chunk_index: c.chunkIndex,+ start_line: c.startLine,+ end_line: c.endLine,+ pointer: c.pointer,+ content: c.content,+ })),+ next_cursor: result.next_cursor,+ }) + "\n",+ );+ return 0;+ }+ const lines: string[] = [];+ lines.push(`note: ${result.note.pointer}`);+ if (result.note.title !== null) lines.push(`title: ${result.note.title}`);+ lines.push("");+ lines.push(result.note.content);+ lines.push("");+ lines.push(`ββ raw chunks (${result.raw_content.length}) ββ`);+ for (const c of result.raw_content) {+ lines.push(`[${c.pointer}]`);+ lines.push(c.content);+ lines.push("");+ }+ if (result.next_cursor !== null) {+ lines.push(`more: o2b search expand --chunk ${result.chunkId} --cursor ${result.next_cursor}`);+ }+ process.stdout.write(lines.join("\n") + "\n");+ return 0;+}diff --git a/src/cli/search/verbs/focus.ts b/src/cli/search/verbs/focus.tsnew file mode 100644index 00000000..35eb922a--- /dev/null+++ b/src/cli/search/verbs/focus.ts@@ -0,0 +1,93 @@+/**+ * `o2b search focus <set|status|clear>` β the session-scoped recall focus+ * that biases subsequent queries towards a query/path pair until its TTL+ * expires.+ */++import {+ clearSessionFocus,+ normalizeSessionFocus,+ readSessionFocus,+ writeSessionFocus,+} from "../../../core/search/index.ts";+import type { SearchSessionFocus } from "../../../core/search/index.ts";+import {+ CliError,+ flagBoolean,+ flagString,+ parseFlags,+ resolveConfig,+ VAULT_FLAGS,+} from "../helpers.ts";++const ACTIONS = new Set(["set", "status", "clear"]);++/** Focus lifetime when `--ttl-minutes` is omitted. */+const DEFAULT_TTL_MINUTES = "120";++export async function cmdSearchFocus(argv: ReadonlyArray<string>): Promise<number> {+ const action = argv[0];+ if (!action || !ACTIONS.has(action)) {+ throw new CliError(+ "usage: o2b search focus <set|status|clear> [--query Q] [--path P] [--session S]",+ );+ }+ const { flags } = parseFlags(argv.slice(1), {+ ...VAULT_FLAGS,+ query: { type: "string" },+ path: { type: "string" },+ session: { type: "string" },+ "ttl-minutes": { type: "string", default: DEFAULT_TTL_MINUTES },+ json: { type: "boolean" },+ });+ const cfg = resolveConfig(flags);+ // Session-scoped focus (t_5b478e47): --session binds the focus to+ // one session's file under search-focus/ instead of the global file.+ const session = flagString(flags, "session");+ const json = flagBoolean(flags, "json");++ if (action === "set") {+ const ttlMinutes = Number(flags["ttl-minutes"] ?? DEFAULT_TTL_MINUTES);+ const focus = normalizeSessionFocus(+ {+ query: flagString(flags, "query") ?? null,+ pathPrefix: flagString(flags, "path") ?? null,+ ttlMinutes,+ },+ Date.now(),+ );+ writeSessionFocus(cfg, focus, session);+ writeFocusResponse(focus, json);+ return 0;+ }++ if (action === "clear") {+ clearSessionFocus(cfg, session);+ writeFocusResponse(null, json);+ return 0;+ }++ writeFocusResponse(readSessionFocus(cfg, Date.now(), session), json);+ return 0;+}++function focusJson(focus: SearchSessionFocus | null): Record<string, unknown> {+ return { active: focus !== null, focus };+}++function writeFocusResponse(focus: SearchSessionFocus | null, json: boolean): void {+ if (json) {+ process.stdout.write(JSON.stringify(focusJson(focus)) + "\n");+ return;+ }+ if (!focus) {+ process.stdout.write("search focus: inactive\n");+ return;+ }+ const parts = [+ focus.query !== null ? `query=${JSON.stringify(focus.query)}` : null,+ focus.pathPrefix !== null ? `path=${JSON.stringify(focus.pathPrefix)}` : null,+ focus.expiresAt !== null ? `expires_at=${new Date(focus.expiresAt).toISOString()}` : null,+ ].filter((part): part is string => part !== null);+ process.stdout.write(`search focus: active ${parts.join(" ")}\n`);+}diff --git a/src/cli/search/verbs/indexing.ts b/src/cli/search/verbs/indexing.tsnew file mode 100644index 00000000..1055d740--- /dev/null+++ b/src/cli/search/verbs/indexing.ts@@ -0,0 +1,223 @@+/**+ * `o2b search index` and `o2b search reindex` β the two index builders.+ *+ * They differ only in whether the existing index is reused, so they share+ * the safeguard, the run report (JSON + human) and the terminal state they+ * name once the index covers every document.+ */++import { formatDegradationNotice } from "../../../core/integrity/degradation.ts";+import { createSafeguard, resolveSafeguardTimeoutMs } from "../../../core/brain/safeguard.ts";+import { indexVault, reindexVault } from "../../../core/search/index.ts";+import type { IndexStats } from "../../../core/search/index.ts";+import { nextCommandField } from "../../../core/brain/next-step.ts";+import { emitNextStep } from "../../advisory-rail.ts";+import { CronTemplateError, renderCronTemplate } from "../../search-cron-template.ts";+import {+ flagBoolean,+ flagString,+ parseFlags,+ resolveConfig,+ searchAdvisoryStream,+ VAULT_FLAGS,+ type ResolvedSearchConfig,+ type SearchVerbFlags,+} from "../helpers.ts";++/**+ * Both builders run under the `reindex` safeguard budget: an incremental+ * pass over a large vault is the same class of long write as a rebuild, so+ * one configurable deadline covers both.+ */+const SAFEGUARD_OPERATION = "reindex";++/** Terminal state both builders reach when the index covers every document. */+const INDEX_BUILT = "search-index-built";++/** Default flush cadence for the generated `reindex --cron-template`. */+const DEFAULT_CRON_INTERVAL = "30m";++function reindexSafeguard(flags: SearchVerbFlags): ReturnType<typeof createSafeguard> {+ return createSafeguard({+ operation: SAFEGUARD_OPERATION,+ timeoutMs: resolveSafeguardTimeoutMs(SAFEGUARD_OPERATION, flagString(flags, "config")),+ });+}++/**+ * True when the run this `stats` describes left the index covering every+ * document, which is what the `search-index-built` class ("search index+ * up to date") asserts.+ *+ * `stats.errors` means, per its own declaration, "this file did not+ * index". Emitting the class with entries in it would tell the operator+ * the index is current while the tool knows documents are missing from+ * it, and would point at `o2b search query` as though a query over it+ * were complete. Re-labelling the class instead was considered and+ * rejected: a truthful label for the failed case would have to be+ * vacuous, and it would leave the misleading COMMAND in place.+ *+ * A run with errors is left deliberately without a rail line. The errors+ * block already names every affected path and message, and what repairs+ * an unreadable or malformed note is a judgement over that file's+ * content - there is no `o2b` command that performs it, and naming the+ * indexer again would advise repeating the run that just failed.+ */+function indexIsComplete(stats: IndexStats): boolean {+ return stats.errors.length === 0;+}++/**+ * Write one builder's run report and name the terminal state it reached.+ * Identical for `index` and `reindex` because they reach the same state.+ */+function reportIndexRun(+ stats: IndexStats,+ cfg: ResolvedSearchConfig,+ argv: ReadonlyArray<string>,+ jsonRequested: boolean,+): void {+ const complete = indexIsComplete(stats);+ if (jsonRequested) {+ // no-dead-ends, phase 3: the rail suppresses its line on this stream+ // and returns the resolved step precisely so the payload can carry+ // it. Absent whenever the run left the index incomplete.+ process.stdout.write(+ JSON.stringify({+ ...(jsonForStats(stats, cfg) as Record<string, unknown>),+ ...(complete ? nextCommandField(INDEX_BUILT) : {}),+ }) + "\n",+ );+ } else {+ process.stdout.write(renderStatsHuman(stats, cfg));+ }+ if (complete) {+ emitNextStep(INDEX_BUILT, searchAdvisoryStream(argv, jsonRequested));+ }+}++export async function cmdSearchIndex(argv: ReadonlyArray<string>): Promise<number> {+ const { flags } = parseFlags(argv, {+ ...VAULT_FLAGS,+ embeddings: { type: "boolean" },+ force: { type: "boolean" },+ "force-cost": { type: "boolean" },+ concurrency: { type: "string" },+ verbose: { type: "boolean" },+ json: { type: "boolean" },+ });+ const cfg = resolveConfig(flags);++ const verbose = flagBoolean(flags, "verbose");+ const stats = await indexVault(cfg, {+ safeguard: reindexSafeguard(flags),+ embeddings: flagBoolean(flags, "embeddings"),+ force: flagBoolean(flags, "force"),+ forceCost: flagBoolean(flags, "force-cost"),+ onFile: (e) => {+ if (verbose) {+ const msg = e.message ? ` ${e.message}` : "";+ process.stderr.write(`${e.kind}\t${e.path}${msg}\n`);+ }+ },+ });++ reportIndexRun(stats, cfg, argv, flagBoolean(flags, "json"));+ return 0;+}++export async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<number> {+ const { flags } = parseFlags(argv, {+ ...VAULT_FLAGS,+ embeddings: { type: "boolean" },+ "force-cost": { type: "boolean" },+ concurrency: { type: "string" },+ json: { type: "boolean" },+ verbose: { type: "boolean" },+ "cron-template": { type: "boolean" },+ interval: { type: "string" },+ });+ if (flagBoolean(flags, "cron-template")) {+ const intervalRaw = flagString(flags, "interval") ?? DEFAULT_CRON_INTERVAL;+ try {+ const body = renderCronTemplate(intervalRaw);+ process.stdout.write(body);+ return 0;+ } catch (err) {+ if (err instanceof CronTemplateError) {+ process.stderr.write(`error: ${err.message}\n`);+ return 1;+ }+ throw err;+ }+ }+ const cfg = resolveConfig(flags);+ const stats = await reindexVault(cfg, {+ safeguard: reindexSafeguard(flags),+ embeddings: flagBoolean(flags, "embeddings"),+ forceCost: flagBoolean(flags, "force-cost"),+ onFile: flagBoolean(flags, "verbose")+ ? (e) => process.stderr.write(`${e.kind}\t${e.path}\n`)+ : undefined,+ });+ reportIndexRun(stats, cfg, argv, flagBoolean(flags, "json"));+ return 0;+}++function jsonForStats(stats: IndexStats, cfg: ResolvedSearchConfig): unknown {+ return {+ stats: {+ added: stats.added,+ updated: stats.updated,+ unchanged: stats.unchanged,+ deleted: stats.deleted,+ chunks_total: stats.chunksTotal,+ embeddings_computed: stats.embeddingsComputed,+ embeddings_retries: stats.embeddingsRetries,+ },+ errors: stats.errors.map((e) => ({ path: e.path, message: e.message })),+ // Unit F. Conditional so a vault with no malformed frontmatter emits+ // exactly the payload it emitted before this field existed.+ ...(stats.frontmatterNotices.length > 0+ ? {+ frontmatter_notices: stats.frontmatterNotices.map((n) => ({+ code: n.code,+ site: n.site,+ ...(n.path !== undefined ? { path: n.path } : {}),+ detail: n.detail,+ })),+ }+ : {}),+ duration_ms: stats.durationMs,+ vault: cfg.vault,+ db_path: cfg.dbPath,+ };+}++function renderStatsHuman(stats: IndexStats, cfg: ResolvedSearchConfig): string {+ const lines: string[] = [];+ lines.push(`indexing vault: ${cfg.vault}`);+ lines.push(` added: ${stats.added} files, ${stats.chunksTotal} chunks`);+ lines.push(` updated: ${stats.updated} files`);+ lines.push(` unchanged: ${stats.unchanged} files`);+ lines.push(` deleted: ${stats.deleted} files`);+ if (stats.embeddingsComputed > 0 || stats.embeddingsRetries > 0) {+ lines.push(+ ` embeddings: ${stats.embeddingsComputed} computed (${stats.embeddingsRetries} retries)`,+ );+ }+ if (stats.errors.length > 0) {+ lines.push(` errors:`);+ for (const e of stats.errors) lines.push(` - ${e.path}: ${e.message}`);+ }+ // Unit F. Below the errors block and only when non-empty: these files+ // indexed successfully, they just lost a frontmatter field.+ if (stats.frontmatterNotices.length > 0) {+ lines.push(` frontmatter:`);+ for (const n of stats.frontmatterNotices) {+ lines.push(` - ${formatDegradationNotice(n)}`);+ }+ }+ lines.push(`done in ${(stats.durationMs / 1000).toFixed(1)}s`);+ return lines.join("\n") + "\n";+}diff --git a/src/cli/search/verbs/learned-weights.ts b/src/cli/search/verbs/learned-weights.tsnew file mode 100644index 00000000..62186fff--- /dev/null+++ b/src/cli/search/verbs/learned-weights.ts@@ -0,0 +1,115 @@+/**+ * `o2b search feedback` and `o2b search weights` (recall-trust-suite) β+ * the two ends of the learned-weight loop: recording an up/down verdict on+ * a result, and inspecting or resetting the multipliers those verdicts+ * produced.+ */++import {+ captureRecallFeedback,+ loadFeedbackEvents,+ readLearnedWeights,+ resetLearnedWeights,+ LEARNED_WEIGHT_MIN,+ LEARNED_WEIGHT_MAX,+ type LearnedWeights,+} from "../../../core/search/index.ts";+import {+ CliError,+ flagBoolean,+ flagString,+ parseFlags,+ resolveConfig,+ VAULT_FLAGS,+} from "../helpers.ts";++export async function cmdSearchFeedback(argv: ReadonlyArray<string>): Promise<number> {+ const { flags } = parseFlags(argv, {+ ...VAULT_FLAGS,+ query: { type: "string" },+ result: { type: "string" },+ verdict: { type: "string" },+ json: { type: "boolean" },+ });+ const query = flagString(flags, "query") ?? "";+ const resultPath = flagString(flags, "result") ?? "";+ const verdict = flagString(flags, "verdict") ?? "";+ if (!query || !resultPath) {+ throw new CliError("usage: o2b search feedback --query <q> --result <path> --verdict up|down");+ }+ if (verdict !== "up" && verdict !== "down") {+ throw new CliError("--verdict must be 'up' or 'down'");+ }+ const cfg = resolveConfig(flags);+ const outcome = await captureRecallFeedback(cfg, { query, resultPath, verdict });+ if (flagBoolean(flags, "json")) {+ process.stdout.write(+ JSON.stringify({+ recorded: true,+ result_found: outcome.resultFound,+ file: outcome.file,+ learned: outcome.learned,+ }) + "\n",+ );+ return 0;+ }+ const found = outcome.resultFound+ ? ""+ : " (result not in current top-50; recorded with zero contributions)";+ process.stdout.write(+ `recorded ${verdict} for ${resultPath}${found}\n` ++ `learned weights now: ${formatLearnedWeights(outcome.learned)}\n`,+ );+ return 0;+}++export async function cmdSearchWeights(argv: ReadonlyArray<string>): Promise<number> {+ const { flags } = parseFlags(argv, {+ ...VAULT_FLAGS,+ reset: { type: "boolean" },+ json: { type: "boolean" },+ });+ const cfg = resolveConfig(flags);+ const json = flagBoolean(flags, "json");+ if (flagBoolean(flags, "reset")) {+ resetLearnedWeights(cfg.vault);+ if (json) {+ process.stdout.write(JSON.stringify({ reset: true }) + "\n");+ } else {+ process.stdout.write("learned weights reset (feedback events kept)\n");+ }+ return 0;+ }+ const learned = readLearnedWeights(cfg.vault);+ const payload = {+ enabled: cfg.recall.learnedWeightsEnabled,+ base: {+ keywordWeight: cfg.keywordWeight,+ semanticWeight: cfg.semanticWeight,+ },+ learned,+ events: loadFeedbackEvents(cfg.vault).length,+ bounds: { min: LEARNED_WEIGHT_MIN, max: LEARNED_WEIGHT_MAX },+ };+ if (json) {+ process.stdout.write(JSON.stringify(payload) + "\n");+ return 0;+ }+ const lines = [+ `learned weights: ${payload.enabled ? "enabled" : "disabled (search_learned_weights_enabled)"}`,+ `base: kw=${cfg.keywordWeight} sem=${cfg.semanticWeight}`,+ learned === null+ ? "learned: none (no feedback recorded)"+ : `learned: ${formatLearnedWeights(learned)} from ${learned.events} event(s)`,+ `bounds: [${LEARNED_WEIGHT_MIN}, ${LEARNED_WEIGHT_MAX}]`,+ ];+ process.stdout.write(lines.join("\n") + "\n");+ return 0;+}++function formatLearnedWeights(w: LearnedWeights): string {+ return (+ `kw=${w.keywordMul.toFixed(3)} sem=${w.semanticMul.toFixed(3)} ` ++ `ent=${w.entityMul.toFixed(3)} rec=${w.recencyMul.toFixed(3)}`+ );+}diff --git a/src/cli/search/verbs/plan.ts b/src/cli/search/verbs/plan.tsnew file mode 100644index 00000000..3aff559e--- /dev/null+++ b/src/cli/search/verbs/plan.ts@@ -0,0 +1,61 @@+/**+ * `o2b search plan` β the graph-index query pre-pass: which notes a read+ * would touch, how many hops away they are, and why they were shortlisted,+ * without reading them.+ */++import { planRead } from "../../../core/search/index.ts";+import {+ CliError,+ flagBoolean,+ isIntegerWithin,+ parseFlags,+ resolveConfig,+ VAULT_FLAGS,+} from "../helpers.ts";++const DEFAULT_MAX_HOPS = "2";+const DEFAULT_SHORTLIST_LIMIT = "10";++export async function cmdSearchPlan(argv: ReadonlyArray<string>): Promise<number> {+ const { flags, positional } = parseFlags(argv, {+ ...VAULT_FLAGS,+ hops: { type: "string", default: DEFAULT_MAX_HOPS },+ limit: { type: "string", default: DEFAULT_SHORTLIST_LIMIT },+ "index-only": { type: "boolean" },+ json: { type: "boolean" },+ });+ const query = positional.join(" ").trim();+ if (query === "")+ throw new CliError('usage: o2b search plan "<query>" [--index-only] [--hops N]');+ const cfg = resolveConfig(flags);+ const maxHops = Number(flags["hops"] ?? DEFAULT_MAX_HOPS);+ const shortlistLimit = Number(flags["limit"] ?? DEFAULT_SHORTLIST_LIMIT);+ if (!isIntegerWithin(maxHops, { min: 0 })) {+ throw new CliError(`--hops must be a non-negative integer, got '${flags["hops"]}'`);+ }+ if (!isIntegerWithin(shortlistLimit, { min: 1 })) {+ throw new CliError(`--limit must be a positive integer, got '${flags["limit"]}'`);+ }+ const plan = await planRead(cfg, query, {+ indexOnly: flagBoolean(flags, "index-only"),+ maxHops,+ shortlistLimit,+ });+ if (flagBoolean(flags, "json")) {+ process.stdout.write(JSON.stringify(plan) + "\n");+ return 0;+ }+ process.stdout.write(`${plan.mode} (notes read: ${plan.notesRead})\n`);+ if (plan.shortlist.length === 0) {+ process.stdout.write(" no candidates\n");+ return 0;+ }+ for (const e of plan.shortlist) {+ const title = e.title ?? "(untitled)";+ process.stdout.write(+ ` ${e.path} "${title}" hops=${e.hops} degree=${e.degree} [${e.reasons.join(",")}]\n`,+ );+ }+ return 0;+}diff --git a/src/cli/search/verbs/provider-registry.ts b/src/cli/search/verbs/provider-registry.tsnew file mode 100644index 00000000..26ea7d33--- /dev/null+++ b/src/cli/search/verbs/provider-registry.ts@@ -0,0 +1,231 @@+/**+ * `o2b search provider` and `o2b search rerank-provider` (Embedding+ * Provider Suite / retrieval-precision-quality-loop, card A).+ *+ * Two structurally identical profile registries with one `add|list|show|+ * remove` CRUD shape between them, so the dispatch lives once and each+ * verb supplies its registry's operations and its nouns.+ */++import {+ addProviderProfile,+ addRerankProviderProfile,+ getProviderProfile,+ getRerankProviderProfile,+ loadProviderRegistry,+ loadRerankRegistry,+ removeProviderProfile,+ removeRerankProviderProfile,+} from "../../../core/search/index.ts";+import {+ EMBEDDING_MODEL_PRESETS,+ RECOMMENDED_EMBEDDING_MODEL,+ type EmbeddingModelPreset,+} from "../../../core/search/embeddings/presets.ts";+import {+ CliError,+ flagBoolean,+ flagString,+ parseFlags,+ resolveConfig,+ VAULT_FLAGS,+} from "../helpers.ts";++/** Structural shape shared by `ProviderProfile` and `RerankProviderProfile`. */+interface CliRegistryProfile {+ readonly name: string;+ readonly baseUrl: string;+ readonly defaultModel: string;+ readonly envKey: string | ReadonlyArray<string>;+}++/** Render an env-key that may be a single name or an ordered probe list. */+function formatEnvKey(envKey: string | ReadonlyArray<string>): string {+ return typeof envKey === "string" ? envKey : envKey.join(",");+}++/**+ * Parse a `--env-key` flag into a single name or an ordered probe list.+ * Accepts a comma-separated list so multi-key failover is CLI-registrable;+ * a single name stays a plain string (byte-identical single-key profile).+ */+function parseEnvKeyFlag(raw: string): string | string[] {+ const parts = raw+ .split(",")+ .map((k) => k.trim())+ .filter((k) => k !== "");+ return parts.length <= 1 ? (parts[0] ?? "") : parts;+}++/**+ * CRUD operations a provider-style registry exposes to the CLI, plus the+ * naming used in usage/output strings. `verb` is the CLI subcommand name+ * (`provider` / `rerank-provider`); `kind` is the human noun used in prose+ * (`provider` / `rerank provider`).+ */+interface ProviderRegistryOps<T extends CliRegistryProfile> {+ readonly verb: string;+ readonly kind: string;+ readonly load: (vault: string) => ReadonlyArray<T>;+ readonly get: (vault: string, name: string) => T | null;+ readonly add: (vault: string, profile: CliRegistryProfile) => ReadonlyArray<T>;+ readonly remove: (vault: string, name: string) => { removed: boolean };+ /**+ * When true, `--env-key` accepts a comma-separated probe list for+ * multi-key failover (embedding provider only). Rerank stays single-key.+ */+ readonly multiKey?: boolean;+ /**+ * Curated model catalog surfaced via the `presets` action and used as the+ * `--model` default when omitted (embedding provider only). Advisory.+ */+ readonly presets?: ReadonlyArray<EmbeddingModelPreset>;+ /** Recommended default model string when `--model` is omitted. */+ readonly recommendedModel?: string;+}++/**+ * Shared `add|list|show|remove` dispatch for the provider and rerank-provider+ * registries (retrieval-precision-quality-loop, card A) - identical CRUD+ * shape over two structurally identical profile registries.+ */+async function runProviderRegistryCommand<T extends CliRegistryProfile>(+ argv: ReadonlyArray<string>,+ ops: ProviderRegistryOps<T>,+): Promise<number> {+ const { verb, kind } = ops;+ const action = argv[0];+ const allowed = ops.presets+ ? ["add", "list", "show", "remove", "presets"]+ : ["add", "list", "show", "remove"];+ if (!action || !allowed.includes(action)) {+ throw new CliError(+ `usage: o2b search ${verb} <add NAME --base-url U [--model M] --env-key K | list | show NAME | remove NAME${ops.presets ? " | presets" : ""}> [--json]`,+ );+ }+ const { flags, positional } = parseFlags(argv.slice(1), {+ ...VAULT_FLAGS,+ "base-url": { type: "string" },+ model: { type: "string" },+ "env-key": { type: "string" },+ json: { type: "boolean" },+ });+ const json = flagBoolean(flags, "json");++ // `presets` is a static catalog listing; it needs no vault/config.+ if (action === "presets" && ops.presets) {+ if (json) {+ process.stdout.write(JSON.stringify(ops.presets) + "\n");+ return 0;+ }+ process.stdout.write(`curated embedding models (recommended: ${ops.recommendedModel}):\n`);+ for (const p of ops.presets) {+ const tag = p.multilingual ? "multilingual" : "monolingual";+ process.stdout.write(` ${p.model}\n dim=${p.dimension} ${tag} - ${p.note}\n`);+ }+ return 0;+ }++ const cfg = resolveConfig(flags);+ const name = typeof positional[0] === "string" ? positional[0] : undefined;++ if (action === "list") {+ const registry = ops.load(cfg.vault);+ if (json) {+ process.stdout.write(JSON.stringify(registry) + "\n");+ return 0;+ }+ if (registry.length === 0) {+ process.stdout.write(`no registered ${kind}s\n`);+ return 0;+ }+ for (const p of registry) {+ process.stdout.write(+ `${p.name} ${p.baseUrl} model=${p.defaultModel} env=${formatEnvKey(p.envKey)}\n`,+ );+ }+ return 0;+ }++ if (action === "show") {+ if (!name) throw new CliError(`usage: o2b search ${verb} show NAME`);+ const profile = ops.get(cfg.vault, name);+ if (!profile) {+ process.stderr.write(`error: no registered ${kind} named '${name}'\n`);+ return 1;+ }+ process.stdout.write(+ json+ ? JSON.stringify(profile) + "\n"+ : `${profile.name}\n base-url: ${profile.baseUrl}\n model: ${profile.defaultModel}\n env-key: ${formatEnvKey(profile.envKey)}\n`,+ );+ return 0;+ }++ if (action === "remove") {+ if (!name) throw new CliError(`usage: o2b search ${verb} remove NAME`);+ const { removed } = ops.remove(cfg.vault, name);+ if (json) {+ process.stdout.write(JSON.stringify({ removed, name }) + "\n");+ } else {+ process.stdout.write(removed ? `removed ${kind} '${name}'\n` : `no such ${kind} '${name}'\n`);+ }+ return removed ? 0 : 1;+ }++ // add+ if (!name)+ throw new CliError(`usage: o2b search ${verb} add NAME --base-url U --model M --env-key K`);+ const baseUrl = flagString(flags, "base-url");+ const flagModel = flagString(flags, "model");+ const envKey = flagString(flags, "env-key");+ // `--model` may be omitted when the registry has a recommended default+ // (embedding provider); custom models remain first-class and verbatim.+ const model = flagModel ?? ops.recommendedModel;+ const modelHint = ops.recommendedModel ? "[--model M]" : "--model M";+ if (!baseUrl || !model || !envKey) {+ throw new CliError(+ `${verb} add requires --base-url, ${modelHint}, and --env-key (the env var NAME holding the API key)`,+ );+ }+ const envKeyValue = ops.multiKey ? parseEnvKeyFlag(envKey) : envKey;+ const registry = ops.add(cfg.vault, { name, baseUrl, defaultModel: model, envKey: envKeyValue });+ const added = registry.find((p) => p.name === name)!;+ if (json) {+ process.stdout.write(JSON.stringify(added) + "\n");+ } else {+ const envHint = Array.isArray(envKeyValue) ? envKeyValue.join(" or ") : envKeyValue;+ const modelNote = flagModel ? "" : ` (defaulted --model to recommended '${model}')`;+ process.stdout.write(+ `added ${kind} '${name}'${modelNote} (set ${envHint} in the environment to supply its key)\n`,+ );+ }+ return 0;+}++export async function cmdSearchProvider(argv: ReadonlyArray<string>): Promise<number> {+ return runProviderRegistryCommand(argv, {+ verb: "provider",+ kind: "provider",+ load: loadProviderRegistry,+ get: getProviderProfile,+ add: addProviderProfile,+ remove: removeProviderProfile,+ multiKey: true,+ presets: EMBEDDING_MODEL_PRESETS,+ recommendedModel: RECOMMENDED_EMBEDDING_MODEL,+ });+}++export async function cmdSearchRerankProvider(argv: ReadonlyArray<string>): Promise<number> {+ return runProviderRegistryCommand(argv, {+ verb: "rerank-provider",+ kind: "rerank provider",+ load: loadRerankRegistry,+ get: getRerankProviderProfile,+ // Rerank stays single-key; coerce any probe-list shape back to a string.+ add: (vault, profile) =>+ addRerankProviderProfile(vault, { ...profile, envKey: formatEnvKey(profile.envKey) }),+ remove: removeRerankProviderProfile,+ });+}diff --git a/src/cli/search/verbs/query.ts b/src/cli/search/verbs/query.tsnew file mode 100644index 00000000..49aac748--- /dev/null+++ b/src/cli/search/verbs/query.ts@@ -0,0 +1,201 @@+/**+ * `o2b search "<query>"` β the default verb: flags to `SearchOptions`,+ * one call into the core search (or the cross-vault union), and the+ * rendered outcome.+ */++import {+ indexVault,+ parseStructuredRecallQueryDocument,+ search,+ structuredRecallQueryText,+ SEARCH_LIMIT_MIN,+ SEARCH_LIMIT_MAX,+} from "../../../core/search/index.ts";+import { searchAcrossVaults } from "../../../core/search/cross-vault.ts";+import {+ parseDegreePredicate,+ type DegreePredicate,+} from "../../../core/search/property-filter.ts";+import { jsonForOutcome, renderOutcomeHuman } from "../outcome-render.ts";+import {+ CliError,+ flagBoolean,+ flagString,+ isIntegerWithin,+ parseFlags,+ resolveConfig,+ resolveConfigPath,+ VAULT_FLAGS,+} from "../helpers.ts";++/** Both malformed `--property` shapes report the same way. */+function propertyFormatError(entry: string): CliError {+ return new CliError(`--property must be KEY=VALUE, got: ${entry}`);+}++export async function cmdSearchQuery(argv: ReadonlyArray<string>): Promise<number> {+ const { flags, positional } = parseFlags(argv, {+ ...VAULT_FLAGS,+ limit: { type: "string", default: "10" },+ semantic: { type: "boolean" },+ "keyword-only": { type: "boolean" },+ path: { type: "string" },+ "keyword-weight": { type: "string" },+ "semantic-weight": { type: "string" },+ "auto-refresh": { type: "boolean" },+ property: { type: "string-array" },+ degree: { type: "string-array" },+ visibility: { type: "string-array" },+ "agent-scope": { type: "string" },+ "query-doc": { type: "string" },+ expand: { type: "boolean" },+ disclosure: { type: "string" },+ profile: { type: "string" },+ "evidence-pack": { type: "boolean" },+ "include-superseded": { type: "boolean" },+ since: { type: "string" },+ until: { type: "string" },+ global: { type: "boolean" },+ "no-record-access": { type: "boolean" },+ json: { type: "boolean" },+ verbose: { type: "boolean" },+ });++ const rawQueryDocument = flagString(flags, "query-doc");+ const structuredQuery =+ rawQueryDocument !== undefined+ ? parseStructuredRecallQueryDocument(rawQueryDocument)+ : undefined;++ if (positional.length === 0 && structuredQuery === undefined) {+ throw new CliError("query string is required");+ }+ if (flagBoolean(flags, "semantic") && flagBoolean(flags, "keyword-only")) {+ throw new CliError("--semantic and --keyword-only are mutually exclusive");+ }+ const query =+ positional.length > 0 ? positional.join(" ") : structuredRecallQueryText(structuredQuery!);+ if (query.trim().length === 0) {+ throw new CliError("query string is required when --query-doc has no searchable lanes");+ }+ const limitNum = Number(flags["limit"] ?? "10");+ if (!isIntegerWithin(limitNum, { min: SEARCH_LIMIT_MIN, max: SEARCH_LIMIT_MAX })) {+ throw new CliError(`--limit must be an integer in ${SEARCH_LIMIT_MIN}..${SEARCH_LIMIT_MAX}`);+ }+ const disclosureRaw = flagString(flags, "disclosure");+ if (disclosureRaw !== undefined && disclosureRaw !== "full" && disclosureRaw !== "cards") {+ throw new CliError("--disclosure must be 'full' or 'cards'");+ }++ const cfg = resolveConfig(flags);++ if (flagBoolean(flags, "auto-refresh")) {+ try {+ await indexVault(cfg);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ process.stderr.write(`auto-refresh failed: ${msg}\n`);+ }+ }++ // Pass `undefined` when no explicit flag is set so `search()` falls back+ // to the config default. Passing `null` works by accident today but blurs+ // the implicit/explicit policy boundary in Β§7 of the search design.+ const semanticOverride: boolean | undefined = flagBoolean(flags, "semantic")+ ? true+ : flagBoolean(flags, "keyword-only")+ ? false+ : undefined;++ const properties = parsePropertyFlags(flags["property"] as string[] | undefined);+ const degreeFilters = parseDegreeFlags(flags["degree"] as string[] | undefined);+ const visibility = flags["visibility"] as string[] | undefined;+ const agentScope = flagString(flags, "agent-scope");+ const profile = flagString(flags, "profile");+ const since = flagString(flags, "since");+ const until = flagString(flags, "until");+ const isGlobal = flagBoolean(flags, "global");++ const searchOpts = {+ query,+ limit: limitNum,+ semantic: semanticOverride,+ keywordOnly: flagBoolean(flags, "keyword-only"),+ pathPrefix: flagString(flags, "path"),+ ...(properties !== undefined ? { properties } : {}),+ ...(degreeFilters !== undefined ? { degreeFilters } : {}),+ ...(visibility !== undefined && visibility.length > 0 ? { visibility } : {}),+ // Owner-scope isolation (context-integrity-gates, Unit A): an+ // owner-private page is returned only to its own scope. Omitting the+ // flag applies no ownership filtering at all.+ ...(agentScope !== undefined ? { agentScope } : {}),+ ...(structuredQuery !== undefined ? { structuredQuery } : {}),+ ...(flagBoolean(flags, "expand") ? { expand: true } : {}),+ ...(disclosureRaw === "cards" ? { disclosure: "cards" as const } : {}),+ ...(profile !== undefined ? { profile } : {}),+ ...(flagBoolean(flags, "evidence-pack") ? { evidencePack: true } : {}),+ ...(flagBoolean(flags, "include-superseded") ? { includeSuperseded: true } : {}),+ ...(since !== undefined ? { since } : {}),+ ...(until !== undefined ? { until } : {}),+ // Access recording (Time-Aware Recall & Activation Suite): the CLI+ // surface opts in by default; --no-record-access suppresses it, and+ // cross-vault union never records (results span foreign vaults).+ ...(!isGlobal && !flagBoolean(flags, "no-record-access") ? { recordAccess: true } : {}),+ };+ // Cross-vault union (t_72a22658): explicit per-call opt-in fans the+ // query out over profiles and read-only sources with origin labels.+ const outcome = isGlobal+ ? await searchAcrossVaults(resolveConfigPath(flags), cfg.vault, searchOpts, cfg)+ : await search(cfg, searchOpts);++ if (flagBoolean(flags, "json")) {+ process.stdout.write(JSON.stringify(jsonForOutcome(outcome)) + "\n");+ return 0;+ }+ process.stdout.write(renderOutcomeHuman(outcome, flagBoolean(flags, "verbose")));+ return 0;+}++/**+ * Parse the repeatable `--property KEY=VALUE` flag into the+ * `properties` map shape that `search()` consumes. Multiple+ * `--property KEY=...` entries for the same KEY accumulate (OR).+ * Different KEYs accumulate as separate entries (AND).+ */+function parsePropertyFlags(+ raw: ReadonlyArray<string> | undefined,+): ReadonlyMap<string, ReadonlyArray<string>> | undefined {+ if (!raw || raw.length === 0) return undefined;+ const acc = new Map<string, string[]>();+ for (const entry of raw) {+ const eq = entry.indexOf("=");+ if (eq <= 0) {+ throw propertyFormatError(entry);+ }+ const key = entry.slice(0, eq).trim();+ const value = entry.slice(eq + 1).trim();+ if (key.length === 0 || value.length === 0) {+ throw propertyFormatError(entry);+ }+ const arr = acc.get(key) ?? [];+ arr.push(value);+ acc.set(key, arr);+ }+ const frozen = new Map<string, ReadonlyArray<string>>();+ for (const [k, v] of acc) frozen.set(k, Object.freeze(v));+ return frozen;+}++/**+ * Parse the repeatable `--degree <field><op><count>` flag into the+ * `degreeFilters` predicate list that `search()` consumes, e.g.+ * `--degree backlinks=0` (orphans) or `--degree outlinks>=5` (hubs).+ * Invalid syntax throws a typed `SearchError` from+ * {@link parseDegreePredicate}, surfaced by the search verb's error+ * handler as exit 2.+ */+function parseDegreeFlags(raw: ReadonlyArray<string> | undefined): DegreePredicate[] | undefined {+ if (!raw || raw.length === 0) return undefined;+ return raw.map((entry) => parseDegreePredicate(entry));+}diff --git a/src/cli/search/verbs/rerank-fit.ts b/src/cli/search/verbs/rerank-fit.tsnew file mode 100644index 00000000..316e0d82--- /dev/null+++ b/src/cli/search/verbs/rerank-fit.ts@@ -0,0 +1,65 @@+/**+ * `o2b search rerank-fit` β per-store diagnostic: does the configured+ * cross-encoder actually re-order this vault's results, or is it paying+ * for a permutation the base ranker already had right?+ */++import { rerankFitCheck } from "../../../core/search/rerank-fit-check.ts";+import {+ CliError,+ flagBoolean,+ flagString,+ isIntegerWithin,+ parseFlags,+ resolveConfig,+ VAULT_FLAGS,+} from "../helpers.ts";++export async function cmdSearchRerankFit(argv: ReadonlyArray<string>): Promise<number> {+ const { flags } = parseFlags(argv, {+ ...VAULT_FLAGS,+ "max-queries": { type: "string" },+ "top-k": { type: "string" },+ json: { type: "boolean" },+ });+ const cfg = resolveConfig(flags);+ const maxQueriesFlag = flagString(flags, "max-queries");+ const topKFlag = flagString(flags, "top-k");+ const maxQueries = maxQueriesFlag !== undefined ? Number(maxQueriesFlag) : undefined;+ const topK = topKFlag !== undefined ? Number(topKFlag) : undefined;+ if (maxQueries !== undefined && !isIntegerWithin(maxQueries, { min: 1 })) {+ throw new CliError(`--max-queries must be a positive integer, got '${maxQueriesFlag}'`);+ }+ if (topK !== undefined && !isIntegerWithin(topK, { min: 2 })) {+ throw new CliError(`--top-k must be an integer >= 2, got '${topKFlag}'`);+ }+ const report = await rerankFitCheck(cfg, {+ ...(maxQueries !== undefined ? { maxQueries } : {}),+ ...(topK !== undefined ? { topK } : {}),+ });+ if (flagBoolean(flags, "json")) {+ process.stdout.write(+ JSON.stringify({+ ok: true,+ applicable: report.applicable,+ verdict: report.verdict,+ correlation: report.correlation,+ sampled_queries: report.sampledQueries,+ recommendation: report.recommendation,+ reason: report.reason,+ }) + "\n",+ );+ return 0;+ }+ process.stdout.write(`rerank fit: ${report.verdict}\n`);+ process.stdout.write(` ${report.reason}\n`);+ if (report.correlation !== null) {+ process.stdout.write(+ ` correlation: ${report.correlation.toFixed(3)} over ${report.sampledQueries} query(ies)\n`,+ );+ }+ if (report.verdict !== "fits" && report.verdict !== "inapplicable") {+ process.stdout.write(` recommendation: ${report.recommendation}\n`);+ }+ return 0;+}diff --git a/src/cli/search/verbs/status.ts b/src/cli/search/verbs/status.tsnew file mode 100644index 00000000..273994b9--- /dev/null+++ b/src/cli/search/verbs/status.ts@@ -0,0 +1,72 @@+/**+ * `o2b search status` β what the on-disk index currently holds, and the+ * indexer named as the exit when there is no index at all.+ */++import { indexStatus, serializeIndexStatus } from "../../../core/search/index.ts";+import type { IndexStatusSnapshot } from "../../../core/search/index.ts";+import { nextCommandField } from "../../../core/brain/next-step.ts";+import { emitNextStep } from "../../advisory-rail.ts";+import {+ flagBoolean,+ parseFlags,+ resolveConfig,+ searchAdvisoryStream,+ VAULT_FLAGS,+} from "../helpers.ts";++export async function cmdSearchStatus(argv: ReadonlyArray<string>): Promise<number> {+ const { flags } = parseFlags(argv, {+ ...VAULT_FLAGS,+ json: { type: "boolean" },+ });+ const cfg = resolveConfig(flags);+ const status = await indexStatus(cfg);+ if (flagBoolean(flags, "json")) {+ process.stdout.write(+ JSON.stringify({+ ...(serializeIndexStatus(status) as Record<string, unknown>),+ // Same polarity as the human twin below, so the two conditions+ // read as one rule rather than as each other's negation.+ ...(!status.exists ? nextCommandField("search-index-missing") : {}),+ }) + "\n",+ );+ return 0;+ }+ process.stdout.write(renderStatusHuman(status));+ // no-dead-ends, phase 3: the pointer used to be spliced into the+ // renderer's first line, which is a second emission mechanism AND+ // beyond the reach of a scan over writer call sites. The rail decides+ // the format; the condition is the one the claim rests on.+ if (!status.exists) {+ // The `--json` branch above returned, so this stream is provably a+ // human one; the JSON payload carries the same exit as a field.+ emitNextStep("search-index-missing", searchAdvisoryStream(argv, false));+ }+ return 0;+}++function renderStatusHuman(s: IndexStatusSnapshot): string {+ if (!s.exists) {+ return `index: not initialised\n path: ${s.indexPath}\n`;+ }+ const lines: string[] = [];+ lines.push(`index: ${s.indexPath}`);+ lines.push(`schema_version: ${s.schemaVersion}`);+ lines.push(`documents: ${s.documents}`);+ lines.push(`chunks: ${s.chunks}`);+ lines.push(`embeddings: ${s.embeddings} (stale: ${s.staleEmbeddings})`);+ lines.push(`embedding_model: ${s.embeddingModel ?? "(none)"}`);+ lines.push(`embedding_dimension: ${s.embeddingDimension ?? "(none)"}`);+ lines.push(`embedding_signature: ${s.embeddingSignature ?? "(disabled)"}`);+ if (s.estimatedRefreshCostUsd > 0) {+ lines.push(`refresh_cost_est: $${s.estimatedRefreshCostUsd.toFixed(4)}`);+ }+ lines.push(`vec_extension: ${s.vecExtension}`);+ lines.push(`semantic_enabled: ${s.semanticEnabled}`);+ lines.push(`embedding_key: ${s.embeddingKeyPresent ? "present" : "missing"}`);+ lines.push(`last_indexed_at: ${s.lastIndexedAt ?? "(never)"}`);+ lines.push(`last_full_index_at: ${s.lastFullIndexAt ?? "(never)"}`);+ for (const w of s.warnings) lines.push(`warning: ${w}`);+ return lines.join("\n") + "\n";+}diff --git a/src/cli/search/verbs/watch.ts b/src/cli/search/verbs/watch.tsnew file mode 100644index 00000000..e0d70184--- /dev/null+++ b/src/cli/search/verbs/watch.ts@@ -0,0 +1,111 @@+/**+ * `o2b search watch` β long-running file-watcher (Unit 3): watch the vault+ * for `.md` edits and incrementally re-index after a quiet window. Reuses+ * the existing incremental `indexVault` (mtime/hash fastpath skips+ * unchanged files), so a debounced flush only does work for the files that+ * actually changed. A single-flight guard prevents overlapping passes; the+ * command runs until SIGINT/SIGTERM and shuts the watcher down cleanly.+ */++import { watch, type FSWatcher } from "node:fs";++import { SafeguardAbortError } from "../../../core/brain/safeguard.ts";+import { indexVault } from "../../../core/search/index.ts";+import { IndexWatchPlanner } from "../../../core/search/index-watch.ts";+import { IndexWatchRunner } from "../../../core/search/watch-runner.ts";+import { canonicalNotePath } from "../../../core/path-safety.ts";+import { CliError, flagBoolean, parseFlags, resolveConfig, VAULT_FLAGS } from "../helpers.ts";++/** Floor on the flush timer so a zero debounce still yields to the loop. */+const MIN_FLUSH_INTERVAL_MS = 50;++export async function cmdSearchWatch(argv: ReadonlyArray<string>): Promise<number> {+ const { flags } = parseFlags(argv, {+ ...VAULT_FLAGS,+ embeddings: { type: "boolean" },+ "debounce-ms": { type: "string", default: "800" },+ });+ const cfg = resolveConfig(flags);+ const debounceMs = Number(flags["debounce-ms"]);+ if (!Number.isFinite(debounceMs) || debounceMs < 0) {+ throw new CliError(`--debounce-ms must be a non-negative number, got ${flags["debounce-ms"]}`);+ }+ const planner = new IndexWatchPlanner({ debounceMs });++ let watcher: FSWatcher;+ try {+ watcher = watch(cfg.vault, { recursive: true, persistent: true });+ } catch (e) {+ // Fail loudly, not as a silent no-op: recursive fs.watch is not+ // available on every platform/filesystem.+ throw new CliError(+ `cannot start a recursive watch on ${cfg.vault}: ${e instanceof Error ? e.message : String(e)}. ` ++ "Recursive fs.watch is unsupported here; schedule `o2b search index` on a timer instead.",+ );+ }++ // Single-flight + graceful-shutdown coordinator (Indexer Durability+ // suite). A SIGINT/SIGTERM aborts the in-flight pass at its next file+ // boundary and waits for it to settle (bounded by the configured+ // grace window) before exiting, so a signal never kills a run+ // mid-write. indexInto closes its store in a finally, so the aborted+ // pass still consolidates the WAL and releases the writer lock.+ const runner = new IndexWatchRunner({+ graceMs: cfg.shutdownGraceMs,+ index: async (signal): Promise<void> => {+ const due = planner.take(Date.now());+ if (due.length === 0) return;+ try {+ const stats = await indexVault(cfg, {+ embeddings: flagBoolean(flags, "embeddings"),+ signal,+ });+ process.stderr.write(+ `synced ${due.length} change(s): +${stats.added} ~${stats.updated} =${stats.unchanged}` ++ (stats.errors.length > 0 ? ` (${stats.errors.length} error(s))` : "") ++ "\n",+ );+ } catch (e) {+ // An abort is the expected stop on shutdown - let the runner+ // observe it. Any other failure must not kill the watcher.+ if (e instanceof SafeguardAbortError) throw e;+ process.stderr.write(`index sync failed: ${e instanceof Error ? e.message : String(e)}\n`);+ }+ },+ });++ watcher.on("error", (e) => {+ process.stderr.write(`watch error: ${e instanceof Error ? e.message : String(e)}\n`);+ });+ watcher.on("change", (_eventType, filename) => {+ if (typeof filename !== "string") return;+ if (!filename.toLowerCase().endsWith(".md")) return;+ planner.record(canonicalNotePath(filename), Date.now());+ });++ const timer = setInterval(+ () => {+ void runner.flush();+ },+ Math.max(MIN_FLUSH_INTERVAL_MS, debounceMs),+ );++ return await new Promise<number>((resolve) => {+ const shutdown = async (): Promise<void> => {+ if (runner.isStopped) return;+ clearInterval(timer);+ watcher.close();+ // Drain the in-flight pass (aborted) within the grace window.+ // A second SIGINT/SIGTERM bypasses this (process.once consumed+ // the first), falling back to the default terminate = force exit.+ await runner.shutdown();+ process.stderr.write("watch stopped\n");+ resolve(0);+ };+ process.once("SIGINT", () => void shutdown());+ process.once("SIGTERM", () => void shutdown());+ process.stderr.write(+ `watching ${cfg.vault} for .md changes (debounce ${debounceMs}ms); Ctrl-C to stop\n`,+ );+ });+}diff --git a/src/core/brain/active.ts b/src/core/brain/active.tsindex 5e2c7c44..dea4128b 100644--- a/src/core/brain/active.ts+++ b/src/core/brain/active.ts@@ -157,8 +157,14 @@ export function renderActive(vault: string, opts: RenderActiveOptions = {}): Act.toSorted(sortByIdAscending);// Read window/limit from `_brain.yaml:active.most_applied_*`. The- // loader throws on a malformed `_brain.yaml`; we fall back to- // defaults so a corrupted config never blocks the active digest.+ // strict loader throws when the file is ABSENT too, and a vault that+ // has never run `brain init` must still get its digest, so that case+ // lands on the defaults here.+ //+ // The catch only ever sees that case: an unreadable `_brain.yaml`+ // already raised out of `loadGuardrailsConfigSafe` above, which is+ // deliberate - a config the operator wrote but broke must not quietly+ // resolve to defaults on a surface the agent reads as its rule set.let windowDays = MOST_APPLIED_WINDOW_DAYS_DEFAULT;let limit = MOST_APPLIED_LIMIT_DEFAULT;try {@@ -168,7 +174,7 @@ export function renderActive(vault: string, opts: RenderActiveOptions = {}): Actlimit = cfg.active.most_applied.limit;}} catch {- // intentional fallback β config error is doctor's job to surface+ // intentional fallback β an uninitialised vault has no config to read}// Most-applied draws from the active candidates (confirmed +diff --git a/src/core/brain/anticipatory-cache.ts b/src/core/brain/anticipatory-cache.tsindex 030fb4bf..5a06010b 100644--- a/src/core/brain/anticipatory-cache.ts+++ b/src/core/brain/anticipatory-cache.ts@@ -357,7 +357,16 @@ export function refreshAnticipatoryCache(/*** Read the warm cache for the session's lineage root, falling back to- * a live bundle on miss or staleness. Never throws.+ * a live bundle on miss or staleness.+ *+ * A corrupt cache file reads as a miss, so nothing about the CACHE can+ * fail this call. The live fallback can: it builds a context pack, and+ * an unreadable `_brain.yaml` raises out of that deliberately rather+ * than serving a pack under guardrails the operator did not choose. Both+ * callers report it - the CLI verb as `anticipate failed: β¦`, the MCP+ * tool as its error envelope. This said "Never throws" until the+ * absent-versus-broken config split gave the pack a raise; the promise+ * was the stale half.*/export function readAnticipatoryContext(vault: string,diff --git a/src/core/brain/decisions/receipts.ts b/src/core/brain/decisions/receipts.tsindex 1559e206..756583c3 100644--- a/src/core/brain/decisions/receipts.ts+++ b/src/core/brain/decisions/receipts.ts@@ -148,7 +148,18 @@ export function receiptsDir(vault: string): string {return join(vault, "Brain", "truth");}-/** The receipt shard this device appends to. */+/**+ * The receipt shard this device appends to.+ *+ * @throws {@link ConfigReadError} when the device-local config naming this+ * device cannot be read. Propagated rather than falling back to the+ * legacy un-sharded `decision-change.jsonl`: `resolveDeviceId` would+ * otherwise mint and persist a fresh id over a config it could not read+ * (see its docblock), and a silent shard switch would scatter one+ * device's receipts across two files with nothing recording why. The+ * error names the file and the way out; the CLI verb wrapping this call+ * prints it, and `O2B_DEVICE_ID` resolves the append without the file.+ */export function receiptShardPath(vault: string, configPath?: string): string {const deviceId = resolveDeviceId(configPath);const name = deviceId === "" ? "decision-change.jsonl" : `decision-change.${deviceId}.jsonl`;diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.tsindex 8091f869..1a0c20e1 100644--- a/src/core/brain/diagnostics.ts+++ b/src/core/brain/diagnostics.ts@@ -59,7 +59,7 @@ import { appendLogEvent } from "./log.ts";import { acquireLockSync } from "./sync-lockfile.ts";import { isoSecond } from "./time.ts";import { BRAIN_LOG_EVENT_KIND, type DoctorIssue } from "./types.ts";-import { normaliseWikilinkTarget } from "./wikilink.ts";+import { isBrainArtifactId, normaliseWikilinkTarget } from "./wikilink.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";// ----- Diagnostics-signal model --------------------------------------------@@ -370,6 +370,24 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new MapnextCommand: "o2b brain entity prune",autoRepairable: false,},+ {+ // A subtree the doctor could not enter, reported into the+ // `uncertain` stream by every sweep that walks the store by+ // hand. The CLI folds that stream into the codes it resolves+ // exits for, so an unregistered code printed the finding and+ // nothing after it - the dead end this release removes.+ //+ // The exit is the RE-READ, as with `skill-accept-locked`: no+ // command changes a mode or a mount, and the one thing an+ // operator needs after restoring access is the pass over the+ // subtree that was skipped. Registering it here rather than+ // spelling a sentence beside the notice is what keeps the+ // structural command in one place.+ code: "vault-walk-entry-skipped",+ issueClass: "subtree the doctor could not read",+ nextCommand: "o2b brain doctor",+ autoRepairable: false,+ },// --- Skill-accept transaction refusals (no-dead-ends, phase 3) ---// Both are states the accept transaction itself can leave an// operator in, and both used to refuse without naming a way out.@@ -550,13 +568,11 @@ const DOCTOR_EVIDENCE_FIELD = "evidenced_by";const TARGET_SEP = "::";/** Raw frontmatter key for the derived evidence list. */const EVIDENCED_BY_KEY = "_evidenced_by";-/** Brain-managed id prefixes: only these are pruned as orphaned. */-const BRAIN_ID_RE = /^(pref|ret|sig)-/;function isBrokenBrainRef(raw: string, known: ReadonlySet<string>): string | null {const target = normaliseWikilinkTarget(raw);if (!target) return null;- if (!BRAIN_ID_RE.test(target)) return null; // external / non-Brain link: leave it+ if (!isBrainArtifactId(target)) return null; // external / non-Brain link: leave itif (known.has(target)) return null;return target;}@@ -624,7 +640,7 @@ const orphanedReferenceFixer: Fixer = {// The doctor reports every unresolvable basename; only Brain-managed// ids are this fixer's business. An external / non-Brain link is// left exactly where it is, as it always was.- if (!BRAIN_ID_RE.test(issue.target)) continue;+ if (!isBrainArtifactId(issue.target)) continue;const rel = vaultRelative(issue.path, vault);items.push(issue.field === DOCTOR_EVIDENCE_FIELDdiff --git a/src/core/brain/digest.ts b/src/core/brain/digest.tsindex 4d57ee7c..56fad156 100644--- a/src/core/brain/digest.ts+++ b/src/core/brain/digest.ts@@ -45,11 +45,7 @@ import { computeMostApplied } from "./most-applied.ts";import { brainDirs, vaultRelative } from "./paths.ts";import { collectMaintenanceActions } from "./maintenance/collect.ts";import type { ActionItem } from "./maintenance/action-scorer.ts";-import {- MOST_APPLIED_LIMIT_DEFAULT,- MOST_APPLIED_WINDOW_DAYS_DEFAULT,- loadBrainConfig,-} from "./policy.ts";+import { loadActiveMostAppliedSafe } from "./policy.ts";import { normaliseWikilinkTarget, renderPrefLink, type LinkOutputFormat } from "./wikilink.ts";import { parseRetired } from "./preference.ts";import {@@ -543,20 +539,18 @@ function collectDigestData(const agent_summary = computeAgentSummary(vault, since, until);// Most-applied (Nd) β mirrors the section in `Brain/active.md`.- // The window length / limit come from `_brain.yaml`; a corrupted- // config falls back to defaults so the digest never breaks on- // operator-side schema drift.- let mostAppliedWindowDays = MOST_APPLIED_WINDOW_DAYS_DEFAULT;- let mostAppliedLimit = MOST_APPLIED_LIMIT_DEFAULT;- try {- const cfg = loadBrainConfig(vault);- if (cfg.active?.most_applied) {- mostAppliedWindowDays = cfg.active.most_applied.window_days;- mostAppliedLimit = cfg.active.most_applied.limit;- }- } catch {- // fall through to defaults- }+ // The window length / limit come from `_brain.yaml`. A vault that has+ // never run `brain init` has no window to read and lands on the+ // documented defaults; a config that is PRESENT but unreadable raises,+ // because re-windowing this section silently changes which rules it+ // names while the digest still reports as healthy.+ //+ // Unlike `active.md`, nothing earlier on this path raises for us: the+ // owner-scope gate consulted by `readAllPreferences` above is the+ // integrity reader, which resolves to its strict fallback rather than+ // throwing. The split has to happen at this read.+ const { window_days: mostAppliedWindowDays, limit: mostAppliedLimit } =+ loadActiveMostAppliedSafe(vault);const activePrefs = preferences.filter(({ pref }) =>diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex b510bdf9..97f5fd2c 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -6,6 +6,13 @@* indicate a corrupt state. The CLI (`o2b brain doctor [--strict]`)* wraps the result; this module ships the structured object.*+ * The checks themselves have nothing to do with one another, so each+ * lives in its own module under `doctor/` and this file is the registry:+ * it resolves the one context they read, runs {@link DOCTOR_CHECKS} in+ * order, and assembles the report. A new check joins the pass by being+ * added to that array - the order of the array is the order findings are+ * reported in, which several tests assert on.+ ** Invariants checked:** 1. **Schema version.** `Brain/_brain.yaml schema_version` is known@@ -36,45 +43,52 @@* the existing `doctor` legacy command on an empty vault.*/-import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";-import { join, relative } from "node:path";+import { statSync } from "node:fs";-import { realpathInsideVault, vaultRelative } from "../path-safety.ts";-import { REMOVED_TOOLS } from "../removed-surfaces.ts";-import type { DegradationNotice } from "../integrity/degradation.ts";+import { activeBudgetPressureCheck } from "./doctor/active-budget-check.ts";+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./doctor/check.ts";+import { capturePatternCheck, configCheck, vaultIgnoreCheck } from "./doctor/config-checks.ts";+import { entityRegistryCheck } from "./doctor/entity-checks.ts";+import { brokenBacklinkCheck } from "./doctor/link-checks.ts";+import { evidenceRangeCheck, logShardCheck, orphanEvidenceCheck } from "./doctor/log-checks.ts";+import {+ contentHashDriftCheck,+ duplicatePreferenceCheck,+ lowEvidenceConfirmedCheck,+ pinnedWithoutRecentEvidenceCheck,+} from "./doctor/preference-hygiene.ts";import {- extractWikilinks,- listVaultBasenames,- listVaultPages,- parseFrontmatter,-} from "../vault.ts";-import { computeActiveBudgetPressure } from "./active-budget-pressure.ts";-import { resolveVaultScope } from "../vault-scope/index.ts";-import { buildBacklinkIndex } from "./backlinks.ts";-import { buildEntityIndex } from "./entities/index-builder.ts";+ duplicateIdCheck,+ preferenceCheck,+ retiredCheck,+ signalCheck,+} from "./doctor/record-checks.ts";import {- entityLexicalAliasCandidates,- resolveEntitySemanticDedupConfig,-} from "./entities/semantic-dedup.ts";-import { findMalformedEntityLabels } from "./entities/label-hygiene.ts";-import { buildCaptureBoundary } from "./capture-boundary.ts";-import { verifyLineageLedger } from "./lineage/verify.ts";-import { verifyContentHash } from "./content-hash.ts";-import { readTierDriftCount } from "./frontmatter-tiers.ts";-import { scanDanglingWorkruns } from "./dream-workrun.ts";-import { parseLogDayFile } from "./log.ts";+ collectAllBasenames,+ readAllLogRecords,+ readAllPreferenceRecords,+} from "./doctor/records.ts";+import { removedToolReferenceCheck } from "./doctor/removed-tool-checks.ts";+import { checkSemanticHealth } from "./doctor/semantic-health-check.ts";import {- listLogDates,- listLogMarkdownFiles,- listLogSyncConflicts,- readLogDay,-} from "./log-jsonl.ts";+ danglingWorkrunCheck,+ symlinkEscapeCheck,+ syncConflictLogCheck,+ tierDriftCheck,+} from "./doctor/store-integrity.ts";+import {+ frontmatterUncertaintyProbe,+ lineageLedgerProbe,+ staleLockProbe,+ vaultMarkerProbe,+} from "./doctor/uncertainty-probes.ts";+import type { DoctorUncertainEntry, RunDoctorOptions, RunDoctorResult } from "./doctor/report.ts";+import { reportSweptSkip, sweptFailureReason, sweptPathWarning } from "./doctor/unreadable-path.ts";+import type { SemanticHealthReport } from "./health/reconcile.ts";+import { brainDirs } from "./paths.ts";import {- BRAIN_CONFIG_SUPPORTED_VERSIONS,BRAIN_GUARDRAIL_DEFAULTS,BRAIN_HEALTH_DEFAULTS,- BrainConfigError,- INJECT_BUDGET_CHARS_DEFAULT,loadBrainConfigDetailed,resolveHealth,} from "./policy.ts";@@ -84,143 +98,119 @@ import {type VerificationDeltaSummaryCounts,} from "./trust/compute-verification-delta.ts";import { checkInstructionFileCeiling } from "./trust/instruction-file-ceiling.ts";-import { BrainParseError } from "./parse-error.ts";-import { brainActivePath, brainConfigPath, brainDirs } from "./paths.ts";-import { BrainStatusFolderMismatchError, parsePreference, parseRetired } from "./preference.ts";-import {- reconcileSemanticHealth,- type PreferenceForHealth,- type SemanticHealthReport,-} from "./health/reconcile.ts";-import { parseSignal } from "./signal.ts";-import { principleNeedsRepair } from "./text/sanitize-principle.ts";-import { findSimilarPairs, tokenise } from "./similarity.ts";-import {- BRAIN_LOG_EVENT_KIND,- BRAIN_PREFERENCE_STATUS,- type BrainConfig,- type DoctorIssue,- type InstructionFileCeilingWarning,- type ResolvedBrainHealthConfig,- type TrustVerdict,-} from "./types.ts";-import { scanStaleLocks } from "./sync-lockfile.ts";-import { vaultMarkerAbsentNotice } from "./vault-identity.ts";-import { normaliseWikilinkTarget, parseArtifactRef } from "./wikilink.ts";+import type { DoctorIssue, InstructionFileCeilingWarning, TrustVerdict } from "./types.ts";-// ----- Public types ---------------------------------------------------------+// ----- Public surface -------------------------------------------------------//// `DoctorSeverity`, `DoctorIssue`, `TrustVerdict`, and// `InstructionFileCeilingWarning` live in `./types.ts` β a leaf module// with no imports of its own β so the `trust/` helpers below can depend// on those shapes without importing this file.-export interface RunDoctorOptions {- /**- * Reserved for future per-check toggles. Today the doctor reports- * every check it knows; CLI `--strict` only changes the exit code,- * not the contents of the report.- */- readonly strict?: boolean;- /**- * Wall clock used by age-based lints (`low-evidence-confirmed`,- * `pinned-without-recent-evidence`). Defaults to `new Date()`.- * Tests pin this for determinism.- */- readonly now?: Date;- /**- * Search-index path for index-backed checks- * (write-time-integrity-governance: staged tier-drift findings).- * Fail-soft: a missing index or pre-v6 schema simply skips them.- */- readonly dbPath?: string;- /**- * Optional precomputed dream summary (v0.10.16). When supplied,- * the doctor runs the verification-delta helper and folds the- * counts into the trust verdict. When omitted, verification- * defaults to all-zero counts and the trust verdict is computed- * against doctor signals alone.- */- readonly dreamSummary?: import("./dream.ts").DreamRunSummary;- /**- * Optional resolved guardrail config (v0.10.16). When omitted,- * `BRAIN_GUARDRAIL_DEFAULTS` are used. Drives the- * instruction-file-ceiling check.- */- readonly guardrails?: import("./types.ts").ResolvedBrainGuardrailConfig;-}+export { collectAllBasenames } from "./doctor/records.ts";+export { computeSemanticHealth } from "./doctor/semantic-health-check.ts";+export type {+ DoctorUncertainEntry,+ RunDoctorOptions,+ RunDoctorResult,+ VerificationDeltaSummary,+} from "./doctor/report.ts";-/**- * Compact counts attached to a `RunDoctorResult` so callers can render- * a one-line "verification delta: X drift, Y regression, Z missing"- * summary without re-walking the vault. Full per-entry detail lives- * on the trust-layer `operator_summary` composer.- */-export interface VerificationDeltaSummary {- readonly confirmed: number;- readonly drift: number;- readonly regression: number;- readonly missing_evidence: number;-}+// ----- The registry ---------------------------------------------------------/**- * Per-check uncertainty entry. Distinct from `warnings` / `errors`:- * these are sub-operations the doctor attempted but cannot claim- * completed cleanly (e.g. an instruction-file the doctor could not- * read, a verification step that timed out). Empty on every clean- * run. v0.10.16 extension point.+ * Every check the pass runs, in report order.+ *+ * The order is part of the contract: findings are reported in discovery+ * order and the id index the record checks fill is what+ * {@link duplicateIdCheck} reads, so it has to follow them.*/-export interface DoctorUncertainEntry {- readonly code: string;- readonly path?: string;- readonly message: string;-}--export interface RunDoctorResult {- readonly warnings: ReadonlyArray<DoctorIssue>;- readonly errors: ReadonlyArray<DoctorIssue>;- /**- * Aggregate trust verdict (v0.10.16). Absent when the trust helper- * was not invoked; consumers of `runDoctor` that only need the- * legacy warning / error stream can ignore the field.- */- readonly trust_verdict?: TrustVerdict;- /**- * Counts of verification-delta states for the most recent dream- * cycle. Absent when verification did not run.- */- readonly verification_delta_summary?: VerificationDeltaSummary;- /**- * Warnings emitted by the instruction-file-ceiling helper. Empty- * when the helper did not run or no tracked file exceeded the- * configured ceiling.- */- readonly instruction_file_warnings?: ReadonlyArray<InstructionFileCeilingWarning>;- /**- * Sub-operations the doctor attempted but could not fully verify.- * Empty on every clean run; populated when an uncertainty-surfacing- * helper is invoked.- */- readonly uncertain?: ReadonlyArray<DoctorUncertainEntry>;- /**- * Semantic-health report (v0.14.0): contradiction / concept-gap /- * stale-claim findings plus an escalating verdict. Absent only when- * the vault has no Brain layer; otherwise present even on a clean- * run (with empty domains and a `clean` verdict).- */- readonly semantic_health?: SemanticHealthReport;-}+const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([+ configCheck,+ vaultIgnoreCheck,+ signalCheck,+ preferenceCheck,+ retiredCheck,+ tierDriftCheck,+ duplicateIdCheck,+ logShardCheck,+ brokenBacklinkCheck,+ removedToolReferenceCheck,+ duplicatePreferenceCheck,+ lowEvidenceConfirmedCheck,+ pinnedWithoutRecentEvidenceCheck,+ contentHashDriftCheck,+ danglingWorkrunCheck,+ activeBudgetPressureCheck,+ evidenceRangeCheck,+ orphanEvidenceCheck,+ entityRegistryCheck,+ capturePatternCheck,+ syncConflictLogCheck,+ symlinkEscapeCheck,+ frontmatterUncertaintyProbe,+ lineageLedgerProbe,+ vaultMarkerProbe,+ staleLockProbe,+]);// ----- Entry point ----------------------------------------------------------/** Issue code for a resolved root that carries no Brain layer. */const BRAIN_ROOT_ABSENT_CODE = "brain-root-absent";-export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctorResult {- const issues: DoctorIssue[] = [];+/** Subsystem name the pass reports a Brain layer it could not reach under. */+const BRAIN_ROOT_SITE = "brain.doctor.root";+/**+ * Whether the Brain layer is there, is not, or could not be reached.+ *+ * `existsSync` used to stand here, and it answers false for a permission+ * denial on any parent component exactly as it does for a root nobody+ * has initialized. The two then produced the same report - and that+ * report advises `o2b brain init`, which on a populated vault whose root+ * an operator locked down is advice to write into a store this pass+ * never managed to look at.+ */+function brainRootProbe(brain: string): BrainRootProbe {+ try {+ statSync(brain);+ return { kind: "present" };+ } catch (err) {+ const reason = sweptFailureReason(err);+ return reason === null ? { kind: "absent" } : { kind: "unreadable", reason };+ }+}++/** The three answers, kept apart because two of them used to be one. */+type BrainRootProbe =+ | { readonly kind: "present" }+ | { readonly kind: "absent" }+ | { readonly kind: "unreadable"; readonly reason: string };++export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctorResult {const dirs = brainDirs(vault);- if (!existsSync(dirs.brain)) {+ const root = brainRootProbe(dirs.brain);+ if (root.kind === "unreadable") {+ // The layer is there and was not read. Every check below would have+ // reported the same denial for its own subtree, so the pass stops+ // here and says so once - under the code the sweeps already use for+ // a subtree they could not enter.+ const uncertain: DoctorUncertainEntry[] = [];+ const message = reportSweptSkip(dirs.brain, `Brain layer could not be read: ${root.reason}`, {+ site: BRAIN_ROOT_SITE,+ consequence: "every Brain check was skipped, so nothing about this root has been verified",+ uncertain,+ });+ return Object.freeze({+ warnings: Object.freeze([sweptPathWarning(dirs.brain, message)]),+ errors: Object.freeze([]),+ trust_verdict: "watch" as TrustVerdict,+ instruction_file_warnings: Object.freeze([]),+ uncertain: Object.freeze(uncertain),+ });+ }+ if (root.kind === "absent") {// A root with no Brain layer is NOT clean (context-integrity-gates,// Unit J). It is exactly the shape a mis-resolved vault takes, and// reporting it as clean is what let a wrong root pass the one@@ -254,260 +244,45 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor});}- // 1. Config schema check.- checkConfig(vault, issues);- // 1b (v0.10.9). Vault scope hygiene: path-style entries that point at- // nothing on disk are typically typos. Only fires when the operator- // actually declared the `vault.ignore_paths` block (we never warn- // about defaults β a built-in entry like `.git` may legitimately be- // absent in a fresh vault).- checkVaultIgnore(vault, issues);-- // 2-6. Frontmatter checks across signals / preferences / retired.- const knownBasenames = collectAllBasenames(vault);- const idIndex = new Map<string, string[]>();-- checkSignals(vault, issues, idIndex);- checkPreferences(vault, issues, idIndex, knownBasenames);- checkRetired(vault, issues, idIndex, knownBasenames);-- // Tier guard (write-time-integrity-governance): staged identity- // hand-edits the index post-pass detected. Fail-soft index read.- if (opts.dbPath !== undefined) {- const driftCount = readTierDriftCount(opts.dbPath);- if (driftCount > 0) {- issues.push({- severity: "warning",- code: "tier-drift",- message:- `${driftCount} identity-field hand-edit(s) staged - ` +- "review with: o2b brain tiers check",- });- }- }-- // Duplicate-id reporting after every file has been indexed.- for (const [id, paths] of idIndex.entries()) {- if (paths.length > 1) {- issues.push({- severity: "error",- code: "duplicate-id",- message: `duplicate id '${id}' across files: ${paths.join(", ")}`,- });- }- }-- // 7. Log header parsing β surface warnings from every markdown shard.- checkLogs(vault, issues);-- // 8. Broken-backlinks lint β any preference / retired / log entry- // that wikilinks to a Brain artifact id (`pref-...`, `ret-...`,- // `sig-...`) whose file no longer exists. Surfaces at warning- // severity: a dangling reference is a real data-hygiene problem- // but doesn't block the dream loop, so the digest / cron want- // to see it without failing the run.- checkBrokenBacklinks(vault, issues, knownBasenames);-- // 8b (1.0.0). Removed-surface references β Brain notes, root- // instruction files, and installed skill files that still name- // an MCP tool deleted in the 1.0.0 deprecation sweep. One- // warning per file, naming each replacement, so an operator- // upgrading an old vault learns the migration from the doctor- // output. Best-effort and fail-soft like every other lint.- try {- checkRemovedToolReferences(vault, issues);- } catch {- /* doctor never throws */- }-- // 9. Hygiene lints β duplicate prefs, low-evidence confirmed, pinned- // without recent evidence, malformed apply-evidence ranges,- // orphan apply-evidence artifacts. Each is non-blocking (warning- // severity) and config/clock dependent. We swallow per-lint- // failures so one broken scan doesn't mask the others.- const now = opts.now ?? new Date();- let cfg;- try {- cfg = loadBrainConfigDetailed(vault).config;- } catch {- cfg = undefined;- }- // Build snapshots once and feed every new lint that needs them.- // Each `try` boundary is per-lint so one broken read doesn't mask- // others, but we don't re-parse the same files five times anymore.- const prefRecords = readAllPreferenceRecords(vault);- const logRecords = readAllLogRecords(vault);- if (cfg) {- try {- checkDuplicatePreferences(prefRecords, issues);- } catch {- /* doctor never throws */- }- try {- checkLowEvidenceConfirmed(prefRecords, issues, cfg, now);- } catch {- /* doctor never throws */+ // The findings first, because the context is itself read from disk and+ // its three directory reads have to be able to report. Resolved before+ // any check runs, an unreadable `Brain/preferences` or a `Brain/log`+ // that is a regular file ended the pass with no findings at all.+ const findings: DoctorFindings = { issues: [], uncertain: [] };+ const ctx = resolveContext(vault, opts, findings.uncertain);+ for (const check of DOCTOR_CHECKS) {+ if (!check.failSoft) {+ check.run(ctx, findings);+ continue;}+ // A fail-soft check that throws must not mask the findings of the+ // ones after it: the doctor's whole job is to report the condition+ // it can see, and one broken scan is not a reason to report nothing.try {- checkPinnedWithoutRecentEvidence(prefRecords, issues, cfg, now);+ check.run(ctx, findings);} catch {/* doctor never throws */}}- // v0.12.0 Brain Integrity Suite: surface preferences whose live- // (principle, scope) does not hash to the value stored in- // `_content_hash`. Hand-edits remain legal; the warning makes them- // observable.- try {- checkContentHashDrift(prefRecords, issues);- } catch {- /* doctor never throws */- }- // v0.12.0 Brain Integrity Suite: surface every dream workrun file- // whose last phase is neither `finalized` nor `interrupted`. A- // dangling workrun is forensic evidence that a previous dream- // invocation crashed - the operator can inspect the file to see- // how far the run got.- try {- checkDanglingWorkruns(vault, issues);- } catch {- /* doctor never throws */- }- // Proactive active-memory budget-pressure watermark (C4). When the- // rendered active.md is crossing its injection byte budget, warn- // BEFORE the reactive truncation silently drops content and list the- // sections an operator could archive to relieve pressure. Quiet on- // healthy vaults (empty output = healthy); suggestions only.- try {- checkActiveBudgetPressure(vault, issues, cfg?.active?.inject_budget_chars);- } catch {- /* doctor never throws */- }- try {- checkMalformedEvidenceRange(logRecords, issues);- } catch {- /* doctor never throws */- }- try {- checkOrphanEvidence(vault, logRecords, issues);- } catch {- /* doctor never throws */- }- // Memory Integrity Suite: canonical entity registry hygiene. Write- // seams refuse duplicates, so anything reported here arrived through- // hand edits or sync merges - observable, never auto-deleted.- try {- checkEntities(vault, issues);- } catch {- /* doctor never throws */- }- // Memory Integrity Suite: capture-boundary patterns that failed to- // compile (invalid regex in sessions.ignore_message_patterns or the- // machine-local additions). Capture itself degrades gracefully; the- // doctor makes the skipped pattern visible.- try {- for (const warning of buildCaptureBoundary(vault).warnings) {- issues.push({- severity: "warning",- code: "invalid-capture-pattern",- message: warning,- });- }- } catch {- /* doctor never throws */- }- // Memory Integrity Suite: leftover Syncthing conflict copies under- // Brain/log/. The per-device shard layout prevents new ones; old- // copies need a manual union+dedup merge into the day's log.- try {- for (const path of listLogSyncConflicts(vault)) {- issues.push({- severity: "warning",- code: "sync-conflict-log",- path,- message:- `Syncthing sync-conflict copy under Brain/log/: ${path}. ` +- "Merge its rows into the day's log (union + dedup by ts and content), then delete it.",- });- }- } catch {- /* doctor never throws */- }- // Store hardening (D2): a symlink inside Brain/ whose realpath resolves- // OUTSIDE the vault root is an exfiltration/clobber hazard. Lint only -- // never auto-fixed, because removing an operator-created link is a- // judgment call.- try {- checkSymlinkEscape(vault, issues);- } catch {- /* doctor never throws */- }-- // Unit F: frontmatter lines the scanner dropped anywhere under- // Brain/. Reported as UNCERTAINTY, not as a warning or an error: the- // note is still on disk and still indexes, but the doctor cannot- // claim it verified every field it declared, because a field it- // could not read is indistinguishable from a field that is absent.- // (That ambiguity is exactly what produced the spurious- // `missing field: tags` errors fixed in 426d06f8.)- const uncertain: DoctorUncertainEntry[] = [];- try {- collectFrontmatterUncertainty(vault, uncertain);- } catch {- /* doctor never throws */- }-- // Unit D: session-lineage ledger integrity - a line edited after it- // was written, a line removed from the middle, or an observation the- // writer could not append. Uncertainty rather than an error for the- // same reason as above: continuity still resolves from this ledger,- // but the doctor cannot claim the history it read is the history that- // was written.- try {- collectLineageLedgerUncertainty(vault, uncertain);- } catch {- /* doctor never throws */- }-- // Unit J: a resolved root with no identity marker. An absent marker- // cannot tell an old vault from a wrong one, so it is uncertainty- // rather than a warning - but it is the exact shape a mis-resolved- // root takes, and the doctor reporting such a root clean is what let- // one pass the single command an operator runs to check the store.- try {- collectVaultMarkerUncertainty(vault, uncertain);- } catch {- /* doctor never throws */- }-- // Lock files left behind by a crashed writer. `scanStaleLocks` has- // documented itself as "the brain doctor surfaces these" since it was- // written and had no caller: a SIGKILLed process leaves a `.lock` that- // no breaker may safely remove, so the ONLY recovery is an operator- // deleting it, and the only way that happens is if something names it.- try {- collectStaleLockUncertainty(vault, uncertain);- } catch {- /* doctor never throws */- }// v0.14.0 semantic-health pass. Best-effort like every other lint:// a failure here must not poison the structural warning / error// stream. The report is attached to the result even on a clean run// (empty domains, `clean` verdict); it stays `undefined` only when- // the pass threw.+ // the pass threw. It sits outside the registry because it is the one+ // check that also RETURNS something the report carries.let semanticReport: SemanticHealthReport | undefined;try {- const health = cfg ? resolveHealth(cfg) : BRAIN_HEALTH_DEFAULTS;- semanticReport = checkSemanticHealth(vault, prefRecords, issues, health, now);+ const health = ctx.config ? resolveHealth(ctx.config) : BRAIN_HEALTH_DEFAULTS;+ semanticReport = checkSemanticHealth(vault, ctx.preferences, findings.issues, health, ctx.now);} catch {/* doctor never throws */}// Partition by severity. Stable sort preserves discovery order which// is convenient for tests asserting on `path`+`code`.- const warnings = issues.filter((i) => i.severity === "warning");- const errors = issues.filter((i) => i.severity === "error");+ const warnings = findings.issues.filter((i) => i.severity === "warning");+ const errors = findings.issues.filter((i) => i.severity === "error");// v0.10.16 trust layer. Each computation is best-effort: a failure// in a helper must not poison the legacy warning / error stream.@@ -552,1268 +327,65 @@ export function runDoctor(vault: string, opts: RunDoctorOptions = {}): RunDoctor// Conditional so a clean vault's result - and therefore the CLI's// `--json` payload - is byte-identical to the shape it had before// this field had a producer.- ...(uncertain.length > 0 ? { uncertain: Object.freeze(uncertain) } : {}),+ ...(findings.uncertain.length > 0 ? { uncertain: Object.freeze(findings.uncertain) } : {}),...(semanticReport !== undefined ? { semantic_health: semanticReport } : {}),});}-/** Site recorded on the notices the doctor's Brain-tree sweep collects. */-const DOCTOR_FRONTMATTER_SITE = "brain.doctor";-/**- * Sweep every Markdown file under `Brain/` for frontmatter the line- * scanner could not express, and fold each notice into the doctor's- * `uncertain` stream.+ * Resolve everything the checks read, once.*- * One walk, through the same shared helper every other converted site- * uses ({@link listVaultPages} with its opt-in notice sink), so there is- * no second definition of "what counts as a dropped line".+ * The config load is the only step that may legitimately fail here: an+ * unreadable `_brain.yaml` is itself a finding {@link configCheck}+ * reports, and the config-dependent lints simply do not run without one.*- * Unlike an index run - which reads only the files whose mtime or size- * moved - this sweep is unconditional, which is what makes the doctor- * the complete view of the condition.+ * The three directory reads run outside the pass's fail-soft loop, so+ * each is handed the uncertainty stream: a directory they cannot read+ * shrinks what every check downstream sees, and that has to be a finding+ * rather than a throw before the first check or a silently smaller set.*/-function collectFrontmatterUncertainty(vault: string, out: DoctorUncertainEntry[]): void {- const dirs = brainDirs(vault);- if (!existsSync(dirs.brain)) return;- const notices: DegradationNotice[] = [];- listVaultPages(dirs.brain, { notices, site: DOCTOR_FRONTMATTER_SITE });- for (const notice of notices) {- out.push({- code: notice.code,- ...(notice.path !== undefined ? { path: notice.path } : {}),- message: notice.detail,- });- }-}--/**- * Fold every session-lineage ledger finding into the doctor's- * `uncertain` stream. The verifier is read-only and never throws, so- * this needs no guard of its own beyond the doctor's blanket one.- */-function collectLineageLedgerUncertainty(vault: string, out: DoctorUncertainEntry[]): void {- const report = verifyLineageLedger(vault);- for (const notice of report.notices) {- out.push({- code: notice.code,- path: notice.path ?? report.path,- message: notice.detail,- });- }-}--/**- * Report a resolved root that carries no vault identity marker.- *- * The producer is pure, throws nothing, and treats a corrupt marker as- * absent - the same collapse `readVaultIdentity` performs, because a- * truncated sync must not be reported as a wrong vault.- */-function collectVaultMarkerUncertainty(vault: string, out: DoctorUncertainEntry[]): void {- const notice = vaultMarkerAbsentNotice(vault);- if (notice === null) return;- out.push({- code: notice.code,- ...(notice.path !== undefined ? { path: notice.path } : {}),- message: notice.detail,- });-}--/** Code for a `.lock` file the doctor found under the Brain tree. */-const STALE_LOCK_CODE = "stale-lock";--/**- * Report every `.lock` file under `Brain/`.- *- * Deliberately NOT age-filtered and deliberately not removed. The lock- * primitive is a single-attempt exclusive create with no breaker, by- * design: no timeout can distinguish a crashed writer from a slow live- * one, and killing a live writer's lock corrupts what it protects. So- * this reports the condition and leaves the judgment to the operator -- * which is the whole reason a lock a crash left behind must be nameable- * at all. A lock held by a healthy concurrent writer shows up here too,- * and is uncertainty rather than a warning for exactly that reason.- */-function collectStaleLockUncertainty(vault: string, out: DoctorUncertainEntry[]): void {- const dirs = brainDirs(vault);- if (!existsSync(dirs.brain)) return;- for (const lockPath of scanStaleLocks(dirs.brain)) {- out.push({- code: STALE_LOCK_CODE,- path: lockPath,- message:- "a writer lock is present; while it is held every write it guards is refused. " +- "If no process owns it (a crash leaves one behind) remove the file by hand - " +- "nothing breaks it automatically, because a live writer cannot be told from a dead one",- });- }-}--// ----- Semantic health (v0.14.0) ----------------------------------------------/**- * Compute only the semantic-health report, skipping the structural- * doctor sweep. {@link runDoctor} attaches the identical report via its- * inline pass; a caller that needs nothing but the semantic findings- * (e.g. vault vitals reading `conceptGaps` for gap pressure) can call- * this directly instead of paying for the full config / signals /- * backlinks / logs / entities sweep. Both paths route through the same- * {@link checkSemanticHealth} detector over the same inputs- * (`readAllPreferenceRecords`, `resolveHealth(cfg)` or the defaults, and- * `now`), so the findings are byte-for-byte identical.- *- * Best-effort and never throws: returns `undefined` only when the pass- * itself throws, mirroring `runDoctor`'s attach-on-success contract. Any- * lint issues the pass would emit into the doctor stream are discarded- * here, which is exactly what a report-only caller wants.- */-export function computeSemanticHealth(+function resolveContext(vault: string,- opts: { readonly now?: Date } = {},-): SemanticHealthReport | undefined {- const now = opts.now ?? new Date();- let cfg;+ opts: RunDoctorOptions,+ uncertain: DoctorUncertainEntry[],+): DoctorCheckContext {+ let config;try {- cfg = loadBrainConfigDetailed(vault).config;+ config = loadBrainConfigDetailed(vault).config;} catch {- cfg = undefined;- }- try {- const prefRecords = readAllPreferenceRecords(vault);- const health = cfg ? resolveHealth(cfg) : BRAIN_HEALTH_DEFAULTS;- return checkSemanticHealth(vault, prefRecords, [], health, now);- } catch {- return undefined;- }-}--/** Minimal signal projection the semantic-health pass needs. */-interface SignalSignRecord {- readonly id: string;- readonly sign: import("./types.ts").BrainSignalSign;- readonly principle: string;- readonly created_at: string;-}--/**- * Read every `sig-*.md` across `inbox/` and `processed/`, projecting- * each to its id, sign, and principle. Files that fail to parse are- * skipped (their schema errors surface through {@link checkSignals}).- */-function readAllSignalRecords(vault: string): ReadonlyArray<SignalSignRecord> {- const dirs = brainDirs(vault);- const out: SignalSignRecord[] = [];- for (const dir of [dirs.inbox, dirs.processed]) {- if (!existsSync(dir)) continue;- for (const name of readdirSync(dir)) {- if (!name.endsWith(".md") || !name.startsWith("sig-")) continue;- try {- const sig = parseSignal(join(dir, name));- out.push({- id: sig.id,- sign: sig.signal,- principle: sig.principle,- created_at: sig.created_at,- });- } catch {- // schema error - reported by checkSignals- }- }- }- return out;-}--/**- * Run the semantic-health detectors, merge their findings into the- * shared `issues` array as warnings, and return the structured report.- * Confirmed preferences feed the contradiction and stale-claim passes;- * signal + preference principles feed the concept-gap pass.- */-function checkSemanticHealth(- vault: string,- prefRecords: ReadonlyArray<PreferenceRecord>,- issues: DoctorIssue[],- health: ResolvedBrainHealthConfig,- now: Date,-): SemanticHealthReport {- const signals = readAllSignalRecords(vault);- const signSignById = new Map(signals.map((s) => [s.id, s.sign]));- const preferences: PreferenceForHealth[] = prefRecords.map(({ pref }) => pref);- const corpusPrinciples = [- ...signals.map((s) => s.principle),- ...prefRecords.map((r) => r.pref.principle),- ];- // Aligned index-for-index with corpusPrinciples: the authored date of- // each entry, so the baseline watermark can tell a concept gap that is- // entirely old from one still mentioned in fresh memory.- const corpusPrincipleDates: (string | null)[] = [- ...signals.map((s) => s.created_at),- ...prefRecords.map((r) => r.pref.created_at),- ];- const coveredTopics = prefRecords.map((r) => r.pref.topic);-- const report = reconcileSemanticHealth(- { preferences, signSignById, corpusPrinciples, corpusPrincipleDates, coveredTopics },- {- contradictionJaccard: health.contradiction_jaccard,- conceptGapMinFrequency: health.concept_gap_min_frequency,- staleClaimMaxAgeDays: health.stale_claim_max_age_days,- ...(health.silence_before !== null ? { silenceBefore: health.silence_before } : {}),- now,- },- );-- for (const c of report.contradictions) {- issues.push({- severity: "warning",- code: "contradictory-preferences",- message:- `[[${c.aId}]] (${c.aSign}) and [[${c.bId}]] (${c.bSign})` +- `${c.scope ? ` in scope '${c.scope}'` : ""}` +- ` look like contradictions (jaccard ${c.jaccard.toFixed(2)} of principle tokens,` +- " opposite sign of record). Reconcile or retire one.",- });- }- for (const g of report.conceptGaps) {- issues.push({- severity: "warning",- code: "concept-gap",- message:- `term '${g.term}' recurs across ${g.frequency} entries but no preference topic covers it.` +- " Consider capturing a dedicated preference.",- });- }- for (const s of report.staleClaims) {- issues.push({- severity: "warning",- code: "stale-claim",- message:- `[[${s.id}]] last saw evidence ${s.ageDays} days ago (${s.lastEvidenceAt}).` +- " Re-confirm or retire it.",- });- }- for (const b of report.batchInflation) {- issues.push({- severity: "warning",- code: "batch-concept-inflation",- message:- `${b.count} preferences confirmed within one window (${b.windowStart} to ${b.windowEnd}): ` +- `${b.ids.map((id) => `[[${id}]]`).join(", ")} across topics ${b.topics.join(", ")}. ` +- "A batch this size confirmed together usually means dedup/consolidation was skipped - " +- "review for near-duplicates or preferences that should merge before the next dream pass.",- });- }-- return report;-}--// ----- Config check -----------------------------------------------------------function checkConfig(vault: string, issues: DoctorIssue[]): void {- const cfgPath = brainConfigPath(vault);- if (!existsSync(cfgPath)) {- issues.push({- severity: "error",- code: "config-missing",- path: cfgPath,- message: "_brain.yaml is missing; run `o2b brain init` to bootstrap the Brain layer",- });- return;- }- try {- const { config, warnings } = loadBrainConfigDetailed(vault);- if (!BRAIN_CONFIG_SUPPORTED_VERSIONS.includes(config.schema_version)) {- issues.push({- severity: "error",- code: "schema-version-unknown",- path: cfgPath,- message:- `_brain.yaml schema_version ${config.schema_version} is not in the supported set ` +- `(${BRAIN_CONFIG_SUPPORTED_VERSIONS.join(", ")})`,- });- }- for (const w of warnings) {- issues.push({- severity: "warning",- code: "config-warning",- path: cfgPath,- message: w.message,- });- }- } catch (err) {- if (err instanceof BrainConfigError) {- issues.push({- severity: "error",- code: "config-invalid",- path: cfgPath,- message: err.message,- });- } else {- issues.push({- severity: "error",- code: "config-invalid",- path: cfgPath,- message: `_brain.yaml could not be loaded: ${(err as Error).message ?? String(err)}`,- });- }- }-}--// ----- Vault-scope check -----------------------------------------------------/**- * v0.10.9 hygiene lint: surface path-style entries in- * `vault.ignore_paths` that do not resolve to anything on disk. Such- * entries are typically typos β they look like exclusions but cannot- * fire. Bare-name rules are skipped (a missing `.git` directory is- * not an error).- *- * Only runs when the operator declared the block themselves; the- * built-in default set may legitimately list paths that do not exist- * in a given vault.- */-function checkVaultIgnore(vault: string, issues: DoctorIssue[]): void {- let scope;- try {- scope = resolveVaultScope(vault);- } catch {- // `checkConfig` already reports the malformed/unreadable _brain.yaml.- // Do not let this follow-on lint mask the primary config issue.- return;- }- if (scope.source !== "_brain.yaml") return;- for (const rule of scope.rules) {- if (rule.kind !== "path") continue;- if (existsSync(join(vault, rule.raw))) continue;- issues.push({- severity: "warning",- code: "vault-ignore-missing-path",- message: `vault.ignore_paths entry '${rule.raw}' does not exist in this vault`,- });- }-}--// ----- Signal check -----------------------------------------------------------function checkSignals(vault: string, issues: DoctorIssue[], idIndex: Map<string, string[]>): void {- const dirs = brainDirs(vault);- for (const dir of [dirs.inbox, dirs.processed]) {- forEachBrainFile(dir, "sig-", (path, filename) => {- try {- const sig = parseSignal(path);- registerId(idIndex, sig.id, path);- checkIso(path, "created_at", sig.created_at, issues);- const expectedId = filename.slice(0, -".md".length);- if (sig.id !== expectedId) {- issues.push({- severity: "warning",- code: "id-filename-mismatch",- path,- message: `signal id '${sig.id}' differs from filename basename '${expectedId}'`,- });- }- } catch (err) {- issues.push({- severity: "error",- code: "signal-invalid",- path,- message: (err as Error).message ?? String(err),- });- }- });- }-}--// ----- Preference check -------------------------------------------------------function checkPreferences(- vault: string,- issues: DoctorIssue[],- idIndex: Map<string, string[]>,- knownBasenames: ReadonlySet<string>,-): void {- const dirs = brainDirs(vault);- forEachBrainFile(dirs.preferences, "pref-", (path) => {- try {- const pref = parsePreference(path);- registerId(idIndex, pref.id, path);- checkIso(path, "created_at", pref.created_at, issues);- checkIso(path, "unconfirmed_until", pref.unconfirmed_until, issues);- if (pref.confirmed_at !== null) {- checkIso(path, "confirmed_at", pref.confirmed_at, issues);- }- if (pref.last_evidence_at !== null) {- checkIso(path, "last_evidence_at", pref.last_evidence_at, issues);- }- // Status invariant β the parser already enforces the canonical- // values via the enum; a non-canonical value would have thrown- // BrainStatusFolderMismatchError, caught below. Reaching here- // means the status is valid; nothing more to check.- checkWikilinks(path, "evidenced_by", pref.evidenced_by, knownBasenames, issues);- if (pref.supersedes) {- checkWikilinks(path, "supersedes", [pref.supersedes], knownBasenames, issues);- }- // Principle corruption (token-diet, t_40eb1de7): leaked tool-call- // fragments or escape-amplified quote chains written before the- // sanitizing write seam shipped. `o2b brain upgrade --apply`- // repairs these in place.- if (principleNeedsRepair(pref.principle)) {- issues.push({- severity: "warning",- code: "principle-corrupted",- path,- message:- "principle carries leaked tool-call fragments or escape-amplified quotes; run `o2b brain upgrade --apply` to repair",- });- }- } catch (err) {- classifyParseError(err, path, "preference", issues);- }- });-}--// ----- Retired check ----------------------------------------------------------function checkRetired(- vault: string,- issues: DoctorIssue[],- idIndex: Map<string, string[]>,- knownBasenames: ReadonlySet<string>,-): void {- const dirs = brainDirs(vault);- forEachBrainFile(dirs.retired, "ret-", (path) => {- try {- const ret = parseRetired(path);- registerId(idIndex, ret.id, path);- checkIso(path, "created_at", ret.created_at, issues);- checkIso(path, "retired_at", ret.retired_at, issues);- if (ret.last_evidence_at !== null) {- checkIso(path, "last_evidence_at", ret.last_evidence_at, issues);- }- checkWikilinks(path, "evidenced_by", ret.evidenced_by, knownBasenames, issues);- checkWikilinks(path, "retired_by", [ret.retired_by], knownBasenames, issues);- if (ret.superseded_by) {- checkWikilinks(path, "superseded_by", [ret.superseded_by], knownBasenames, issues);- }- } catch (err) {- classifyParseError(err, path, "retired", issues);- }- });-}--// ----- Log check --------------------------------------------------------------function checkLogs(vault: string, issues: DoctorIssue[]): void {- // Per-device shards (Memory Integrity Suite): lint every markdown- // log file - legacy `<date>.md` and sharded `<date>.<deviceId>.md` -- // so warnings keep their exact file paths and line numbers.- for (const { date, path } of listLogMarkdownFiles(vault)) {- const { warnings } = parseLogDayFile(vault, date, path);- for (const w of warnings) {- issues.push({- severity: "warning",- code: "log-malformed",- path: w.path,- message: `line ${w.lineNumber}: ${w.message}`,- });- }- }-}--// ----- Symlink-escape lint (D2) -----------------------------------------------/**- * Walk `Brain/` and report every symlink whose realpath resolves outside- * the vault root. Reuses {@link realpathInsideVault} (the same two-step- * check `ensureInsideVault` performs) so a symlink pointing at an- * in-vault target never flags. Directory symlinks are reported but NOT- * descended into - following them would leave the vault.- */-function checkSymlinkEscape(vault: string, issues: DoctorIssue[]): void {- const root = brainDirs(vault).brain;- if (!existsSync(root)) return;- const visit = (dir: string): void => {- let entries;- try {- entries = readdirSync(dir, { withFileTypes: true });- } catch {- return;- }- for (const entry of entries) {- const full = join(dir, entry.name);- if (entry.isSymbolicLink()) {- if (!realpathInsideVault(full, vault)) {- issues.push({- severity: "error",- code: "symlink-escape",- path: vaultRelative(full, vault),- message:- `symlink '${vaultRelative(full, vault)}' resolves outside the vault root. ` +- "A reader following it leaves the vault; remove or repoint the link.",- });- }- continue; // never descend through a symlink- }- if (entry.isDirectory()) visit(full);- }+ config = undefined;+ }+ return {+ vault,+ now: opts.now ?? new Date(),+ config,+ dbPath: opts.dbPath,+ knownBasenames: collectAllBasenames(vault, {+ site: CONTEXT_SITE,+ consequence:+ "its files are absent from the basename universe every link check resolves against, so " ++ "a wikilink that resolves under it reads as broken here",+ uncertain,+ }),+ idIndex: new Map<string, string[]>(),+ // Built once and fed to every lint that needs them, rather than+ // re-parsing the same files five times.+ preferences: readAllPreferenceRecords(vault, {+ site: CONTEXT_SITE,+ consequence:+ "no preference in it was loaded, so every preference-hygiene lint below reports on a " ++ "subset of the store",+ uncertain,+ }),+ logs: readAllLogRecords(vault, {+ site: CONTEXT_SITE,+ consequence:+ "no log day in it was loaded, so the evidence and orphan lints below report on a subset " ++ "of the store",+ uncertain,+ }),};- visit(root);}-// ----- Helpers ----------------------------------------------------------------function registerId(idIndex: Map<string, string[]>, id: string, path: string): void {- const list = idIndex.get(id);- if (list) list.push(path);- else idIndex.set(id, [path]);-}--/**- * Iterate the `<prefix>*.md` files directly inside `dir` (non-recursive),- * invoking `cb(path, filename)` for each. Absent `dir` is a no-op - the- * per-kind checks (`checkPreferences`, `checkRetired`, `checkSignals`) all- * treat a missing Brain subdirectory as "nothing to check", not an error.- */-function forEachBrainFile(- dir: string,- prefix: string,- cb: (path: string, filename: string) => void,-): void {- if (!existsSync(dir)) return;- for (const entry of readdirSync(dir, { withFileTypes: true })) {- if (!entry.isFile() || !entry.name.endsWith(".md")) continue;- if (!entry.name.startsWith(prefix)) continue;- cb(join(dir, entry.name), entry.name);- }-}--/** Record kinds whose parse failures this module classifies. */-type ParsedRecordKind = "preference" | "retired";--const PREFERENCE_MISSING_FIELD_CODE = "preference-missing-field";-const PREFERENCE_INVALID_CODE = "preference-invalid";-const RETIRED_MISSING_FIELD_CODE = "retired-missing-field";-const RETIRED_INVALID_CODE = "retired-invalid";-const ISO_INVALID_CODE = "iso-invalid";--/**- * The parse-failure codes, per record kind, written out.- *- * These four used to be built by concatenating the kind onto a suffix,- * which meant they appeared nowhere in this module as readable strings -- * so the doctor's own code population could not be enumerated from its- * source, and the exit census (`tests/core/brain/doctor-exit-census.test.ts`)- * could not see them to demand a classification.- */-const PARSE_ERROR_CODES: Readonly<- Record<ParsedRecordKind, { readonly missingField: string; readonly invalid: string }>-> = Object.freeze({- preference: Object.freeze({- missingField: PREFERENCE_MISSING_FIELD_CODE,- invalid: PREFERENCE_INVALID_CODE,- }),- retired: Object.freeze({- missingField: RETIRED_MISSING_FIELD_CODE,- invalid: RETIRED_INVALID_CODE,- }),-});--/** Which of the three parse-failure codes `msg` from `kind` reports. */-function parseErrorCode(kind: ParsedRecordKind, msg: string): string {- if (/missing field/.test(msg)) return PARSE_ERROR_CODES[kind].missingField;- if (/ISO-8601/i.test(msg)) return ISO_INVALID_CODE;- return PARSE_ERROR_CODES[kind].invalid;-}--/**- * Classify a parse-time error into a `DoctorIssue` and push it. Shared by- * `checkPreferences` and `checkRetired`, which previously carried- * byte-identical copies of this regex-based classification - a change to- * a parser's error wording would otherwise reclassify issues in one path- * without the other noticing.- *- * A {@link BrainParseError} - which both parsers now raise, and which- * `BrainStatusFolderMismatchError` extends - reports its location from- * the `path` field and its prose from `detail`, which carries none. The- * human renderer appends ` (<path>)` from the issue's own field, so a- * message that embedded the path as well named the file twice on every- * parse-error line: prose carrying data the record already holds. An- * untyped throw (a frontmatter read, a vocabulary guard owned by another- * module) keeps its message verbatim against the walked path - that- * message is not ours to shorten.- *- * What changed for a caller that prints `(exc as Error).message` bare,- * stated exactly: a throw site whose message already carried the path- * composes the same sentence as before, the status-folder mismatch- * included (it supplies its own composition, keeping the location inside- * the `(path=β¦, status=β¦, folder=β¦)` group). The four optional-field- * helpers in `preference.ts` carried no location at all and now do -- * a gain, and the only wording change in the set.- */-function classifyParseError(- err: unknown,- path: string,- kindPrefix: ParsedRecordKind,- issues: DoctorIssue[],-): void {- if (err instanceof BrainStatusFolderMismatchError) {- issues.push({- severity: "warning",- code: "status-folder-mismatch",- path: err.path,- message: err.detail,- });- return;- }- const typed = err instanceof BrainParseError ? err : null;- const msg = typed ? typed.detail : ((err as Error).message ?? String(err));- issues.push({- severity: "error",- code: parseErrorCode(kindPrefix, msg),- path: typed ? typed.path : path,- message: msg,- });-}--// ISO-8601 UTC: YYYY-MM-DDTHH:MM:SS(.fff)?Z. Lenient β we accept the-// shorter date-only form too (created_at is sometimes a date-only string-// in hand-authored signals).-const ISO_RE = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?$/;--function checkIso(path: string, field: string, value: string, issues: DoctorIssue[]): void {- if (!ISO_RE.test(value)) {- issues.push({- severity: "error",- code: ISO_INVALID_CODE,- path,- message: `field '${field}' is not a valid ISO-8601 timestamp: ${JSON.stringify(value)}`,- });- return;- }- // Confirm the calendar date is real (Date.parse accepts garbage on- // some engines β but verifying via Date round-trip catches it).- const ts = Date.parse(value);- if (!Number.isFinite(ts)) {- issues.push({- severity: "error",- code: "iso-invalid",- path,- message: `field '${field}' could not be parsed as a date: ${JSON.stringify(value)}`,- });- }-}--function checkWikilinks(- path: string,- field: string,- values: ReadonlyArray<string>,- knownBasenames: ReadonlySet<string>,- issues: DoctorIssue[],-): void {- for (const raw of values) {- if (!raw) continue;- // Extract any wikilinks via the shared parser. A bare `[[target]]`- // produces one match; an already-stripped basename produces zero,- // in which case we treat the raw string itself as the candidate.- const matches = extractWikilinks(raw);- const candidates = matches.length > 0 ? matches : [raw];- for (const candidate of candidates) {- const target = normaliseWikilinkTarget(candidate);- if (!target) continue;- if (!knownBasenames.has(target)) {- issues.push({- severity: "warning",- code: "broken-wikilink",- path,- // no-dead-ends, task 12: the field and the target ride as- // fields as well as inside the sentence, so a consumer acts on- // values rather than on a regex over prose. The message is- // unchanged - the human surface still reads it.- field,- target,- message: `field '${field}' references missing basename '${target}'`,- });- }- }- }-}--/**- * Build the universe of valid wikilink targets inside `Brain/`. The- * doctor pass is scoped to Brain content; cross-layer wikilinks- * pointing at user-authored notes outside Brain/ are out of scope- * and stay accepted.- *- * Set is keyed by basename (without `.md`) so Obsidian's basename- * match works.- */-function checkBrokenBacklinks(- vault: string,- issues: DoctorIssue[],- knownBasenames: ReadonlySet<string>,-): void {- // Only attempt the check when there's something to scan β an empty- // Brain layer naturally has no backlinks, and `buildBacklinkIndex`- // would already return an empty map, but we save the parse pass.- if (knownBasenames.size === 0) return;- const index = buildBacklinkIndex(vault);- for (const [target, refs] of index) {- // We only flag references whose target *should* live in this- // Brain (i.e. an artifact id we manage). Wikilinks pointing- // outside the Brain layer are user prose and not our concern.- if (!/^(pref|ret|sig)-/.test(target)) continue;- if (knownBasenames.has(target)) continue;- const sources = Array.from(new Set(refs.map((r) => r.source))).toSorted();- issues.push({- severity: "warning",- code: "broken-backlinks",- // no-dead-ends, task 12. This issue has no `path` - the whole- // finding is that no file with this basename exists - so before- // these fields the referencing sources were reachable only by- // splitting the tail of the sentence on ", ". The message keeps- // them too; the human surface is unchanged.- target,- sources,- message:- `[[${target}]] is referenced by ${sources.length} source(s) but no file with that ` +- `basename exists under Brain/: ${sources.join(", ")}`,- });- }-}--// ----- Hygiene lints (Β§11) ---------------------------------------------------const JACCARD_DUPLICATE_THRESHOLD = 0.7;--interface PreferenceRecord {- readonly path: string;- readonly pref: import("./types.ts").BrainPreference;-}--interface LogRecord {- readonly date: string;- readonly entries: ReadonlyArray<import("./log.ts").BrainLogEntry>;-}--/**- * Build a single pre-parsed snapshot of `Brain/preferences/` so the- * three pref-walking lints don't each re-parse the directory.- * Files that fail to parse are silently omitted β schema errors are- * already reported by {@link checkPreferences}.- */-function readAllPreferenceRecords(vault: string): ReadonlyArray<PreferenceRecord> {- const dirs = brainDirs(vault);- if (!existsSync(dirs.preferences)) return [];- const out: PreferenceRecord[] = [];- for (const name of readdirSync(dirs.preferences)) {- if (!name.endsWith(".md") || !name.startsWith("pref-")) continue;- const path = join(dirs.preferences, name);- try {- out.push({ path, pref: parsePreference(path) });- } catch {- // schema error β reported by checkPreferences- }- }- return out;-}--/**- * Build a single pre-parsed snapshot of `Brain/log/` so the two- * log-walking lints don't each re-parse the directory.- */-function readAllLogRecords(vault: string): ReadonlyArray<LogRecord> {- // Shard-aware (Memory Integrity Suite): dates come from the single- // discovery helper and entries arrive merged across device shards.- const out: LogRecord[] = [];- for (const date of listLogDates(vault)) {- try {- out.push({ date, entries: readLogDay(vault, date).entries });- } catch {- // parse error β surfaced separately by checkLogs- }- }- return out;-}--/**- * `duplicate-preferences`: pairwise jaccard similarity of `principle`- * tokens within each `(topic, scope)` bucket of confirmed/quarantine- * prefs. Pairs with similarity β₯ `JACCARD_DUPLICATE_THRESHOLD` are- * flagged. Unconfirmed and retired prefs are excluded β they're- * meant to be replaced or already are.- */-function checkDuplicatePreferences(- records: ReadonlyArray<PreferenceRecord>,- issues: DoctorIssue[],-): void {- const entries = [];- for (const { pref } of records) {- if (- pref.status !== BRAIN_PREFERENCE_STATUS.confirmed &&- pref.status !== BRAIN_PREFERENCE_STATUS.quarantine- )- continue;- entries.push({- id: pref.id,- // Same-scope-undefined falls in its own bucket. Mirrors the- // Β§12 merge-candidate detector exactly β both surfaces stay- // in sync via the shared walker.- bucketKey: `${pref.topic}\x00${pref.scope ?? ""}`,- tokens: tokenise(pref.principle),- source: pref,- });- }- const pairs = findSimilarPairs(entries, { threshold: JACCARD_DUPLICATE_THRESHOLD });- for (const pair of pairs) {- const a = pair.a.source;- issues.push({- severity: "warning",- code: "duplicate-preferences",- message:- `[[${pair.a.id}]] and [[${pair.b.id}]] in topic '${a.topic}'` +- `${a.scope ? ` (scope: ${a.scope})` : ""}` +- ` look like duplicates (jaccard ${pair.jaccard.toFixed(2)} of principle tokens).` +- " Consider merging.",- });- }-}--/**- * `low-evidence-confirmed`: a confirmed pref whose `applied_count` is- * still at or below `low_max_applied` long after its trial window- * (`unconfirmed_window_days`). Catches prefs that promoted on the- * minimum evidence but never saw real use β candidates for review.- */-function checkLowEvidenceConfirmed(- records: ReadonlyArray<PreferenceRecord>,- issues: DoctorIssue[],- cfg: BrainConfig,- now: Date,-): void {- const cutoffMs = now.getTime() - cfg.dream.unconfirmed_window_days * 24 * 3600 * 1000;- for (const { pref } of records) {- if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;- if (pref.applied_count > cfg.confidence.low_max_applied) continue;- if (!pref.confirmed_at) continue;- const confirmedMs = Date.parse(pref.confirmed_at);- if (!Number.isFinite(confirmedMs)) continue;- if (confirmedMs >= cutoffMs) continue;- issues.push({- severity: "warning",- code: "low-evidence-confirmed",- message:- `[[${pref.id}]] is confirmed but applied_count=${pref.applied_count} β€ ` +- `low_max_applied=${cfg.confidence.low_max_applied} after ${cfg.dream.unconfirmed_window_days}+ days.` +- " The rule hasn't seen real use β review or retire.",- });- }-}--/**- * `pinned-without-recent-evidence`: a pinned pref whose- * `last_evidence_at` is null or older than `stale_evidence_days`. The- * pin protects the rule from automatic retire, but the data shows it- * isn't actively backed β alert the user.- */-function checkPinnedWithoutRecentEvidence(- records: ReadonlyArray<PreferenceRecord>,- issues: DoctorIssue[],- cfg: BrainConfig,- now: Date,-): void {- const cutoffMs = now.getTime() - cfg.retire.stale_evidence_days * 24 * 3600 * 1000;- for (const { pref } of records) {- if (!pref.pinned) continue;- if (!pref.last_evidence_at) {- issues.push({- severity: "warning",- code: "pinned-without-recent-evidence",- message:- `[[${pref.id}]] is pinned but has never received apply-evidence.` +- " Confirm the pin is intentional.",- });- continue;- }- const lastMs = Date.parse(pref.last_evidence_at);- if (!Number.isFinite(lastMs)) continue;- if (lastMs >= cutoffMs) continue;- issues.push({- severity: "warning",- code: "pinned-without-recent-evidence",- message:- `[[${pref.id}]] is pinned but last_evidence_at=${pref.last_evidence_at} is older than ` +- `stale_evidence_days=${cfg.retire.stale_evidence_days}. Pin may be outdated.`,- });- }-}--/**- * `content-hash-drift` (v0.12.0, Brain Integrity Suite): walks every- * confirmed preference, recomputes the content hash from the live- * `(principle, scope)`, and surfaces a warning whenever the stored- * `_content_hash` no longer matches. Legacy preferences without a- * stored hash are silent - drift detection is opt-in via the- * promotion-time hash write.- *- * Hand-edits stay legal: this is observability, not enforcement. The- * operator sees the divergence and decides whether to re-promote the- * preference (which writes a fresh hash) or accept the drift.- */-function checkContentHashDrift(- prefs: ReadonlyArray<PreferenceRecord>,- issues: DoctorIssue[],-): void {- for (const { path, pref } of prefs) {- if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;- if (!pref.content_hash) continue;- const v = verifyContentHash({- principle: pref.principle,- scope: pref.scope,- content_hash: pref.content_hash,- });- if (!v.ok) {- issues.push({- severity: "warning",- code: "content-hash-drift",- path,- message:- `content-hash drift on ${pref.id}: stored ${v.observed} ` +- `does not match recomputed ${v.expected}`,- });- }- }-}--/**- * `dangling-workrun` (v0.12.0, Brain Integrity Suite): surfaces every- * dream-pass workrun JSONL whose last event is neither `finalized`- * nor `interrupted`. A non-empty result means at least one previous- * dream invocation died before it could declare a terminal phase,- * usually because the host process was killed mid-run. The next- * dream pass starts fresh - this check is purely observational so- * the operator notices the failed run.- */-function checkDanglingWorkruns(vault: string, issues: DoctorIssue[]): void {- for (const path of scanDanglingWorkruns(vault)) {- issues.push({- severity: "warning",- code: "dangling-workrun",- path,- message:- `dream-pass workrun did not reach a terminal phase: ${path}. ` +- "A previous dream run was likely killed mid-execution; " +- "subsequent dream invocations will continue normally.",- });- }-}--/**- * `active-budget-pressure` (C4, context-pack-economics-observability):- * proactive watermark over `Brain/active.md`. Reads the rendered body,- * measures its fill-rate against the SessionStart injection byte budget- * (`active.inject_budget_chars`, else the default), and - only when- * pressure crosses the warn threshold - emits ONE warning naming the- * ranked eviction candidates an operator could archive to relieve it.- *- * "Empty output = healthy": a healthy or missing active.md produces no- * warning. The candidates are SUGGESTIONS surfaced for the operator /- * dream; nothing here mutates the vault - the reactive truncation in- * `active-budget.ts` is the only thing that ever drops content, and it- * does so at render time, not here.- */-function checkActiveBudgetPressure(- vault: string,- issues: DoctorIssue[],- injectBudgetChars: number | undefined,-): void {- const path = brainActivePath(vault);- if (!existsSync(path)) return;- let body: string;- try {- [, body] = parseFrontmatter(path);- } catch {- // A corrupted active.md is a derived-view problem the dream loop- // rewrites; not this probe's concern.- return;- }- const budget = injectBudgetChars ?? INJECT_BUDGET_CHARS_DEFAULT;- const pressure = computeActiveBudgetPressure(body.trim(), budget);- if (pressure.status === "healthy") return; // quiet on healthy vaults-- const pct = Math.round(pressure.fillRate * 100);- const ranked = pressure.candidates- .map((c) => `${c.sectionKey.replace(/^## /, "")} (${c.bytes}B)`)- .join(", ");- const suggestion =- pressure.candidates.length > 0- ? ` Archive candidates, highest-priority-to-drop first: ${ranked}.`- : " No stale sections to archive - trim the confirmed rule set instead.";- issues.push({- severity: "warning",- code: "active-budget-pressure",- path,- message:- `active.md is at ${pct}% of the ${budget}-char injection budget (${pressure.status}).` +- " Content will be dropped at inject time once it overflows." +- suggestion,- });-}--/**- * `malformed-evidence-range`: walks every `apply-evidence` event,- * runs the artifact wikilink through {@link parseArtifactRef}, and- * flags any malformed range suffix (`:abc-def`, `:120-100`, etc.).- * The event itself remains valid β only the range is malformed.- */-function checkMalformedEvidenceRange(- records: ReadonlyArray<LogRecord>,- issues: DoctorIssue[],-): void {- for (const { entries } of records) {- for (const e of entries) {- if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;- const artifact = e.body["artifact"];- if (typeof artifact !== "string") continue;- const parsed = parseArtifactRef(artifact);- if (parsed.malformedRange) {- issues.push({- severity: "warning",- code: "malformed-evidence-range",- message:- `apply-evidence at ${e.timestamp} references artifact ${parsed.raw}` +- ` with malformed range '${parsed.rangeText}'.` +- " Use `[[file:N-N]]` (inclusive, 1-based) or `[[file:N]]`.",- });- }- }- }-}--/**- * `orphan-evidence`: walks every `apply-evidence` event and verifies- * the artifact wikilink resolves to some file in the vault. Obsidian- * wikilinks resolve by basename; we use the cheap basename-only- * walker from `vault.ts` (no frontmatter parse).- *- * This is the only doctor lint that walks the entire vault (not just- * `Brain/`). It's an on-demand check; doctor isn't called per-turn.- */-function checkOrphanEvidence(- vault: string,- records: ReadonlyArray<LogRecord>,- issues: DoctorIssue[],-): void {- let basenames: ReadonlySet<string>;- try {- basenames = listVaultBasenames(vault);- } catch {- return;- }- for (const { entries } of records) {- for (const e of entries) {- if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;- const artifact = e.body["artifact"];- if (typeof artifact !== "string") continue;- const target = parseArtifactRef(artifact).target;- if (!target) continue;- if (basenames.has(target)) continue;- issues.push({- severity: "warning",- code: "orphan-evidence",- message:- `apply-evidence at ${e.timestamp} references artifact [[${target}]]` +- " but no file with that basename exists in the vault.",- });- }- }-}--/**- * `duplicate-entity` / `broken-entity-relation`: canonical entity- * registry hygiene (Memory Integrity Suite). Duplicates come straight- * from the index builder's conflict report; broken relations are edges- * whose target resolves to no entity id in the registry.- */-function checkEntities(vault: string, issues: DoctorIssue[]): void {- const index = buildEntityIndex(vault);- if (index.entities.length === 0 && index.conflicts.length === 0) return;-- for (const conflict of index.conflicts) {- issues.push({- severity: "warning",- code: "duplicate-entity",- message:- `${conflict.kind === "duplicate-name" ? "identity" : "alias"} '${conflict.key}' is ` +- `claimed by ${conflict.paths.length} entity files: ${conflict.paths.join(", ")}. ` +- "Merge them or archive the duplicates - lookups resolve to the first claimant only.",- });- }-- const knownIds = new Set(index.entities.map((e) => e.id));- for (const entity of index.entities) {- for (const edge of entity.relations) {- if (knownIds.has(edge.target)) continue;- issues.push({- severity: "warning",- code: "broken-entity-relation",- path: entity.path,- message:- `${entity.id} declares '${edge.relation}: [[${edge.target}]]' but no entity ` +- "with that id exists in the registry.",- });- }- }-- // A1 (t_657b365e): surface stored nodes whose labels fail the quality- // gate (structurally junk after decoration stripping, or operator-- // denylisted) as prune candidates. Warning severity - the operator runs- // `o2b brain entity prune` (dry-run default) to review and remove them.- for (const malformed of findMalformedEntityLabels(vault)) {- issues.push({- severity: "warning",- code: "entity-label-malformed",- path: malformed.path,- message:- `${malformed.id} has a malformed label ${JSON.stringify(malformed.name)} ` +- `(${malformed.reason}). Review with 'o2b brain entity prune' and re-run with ` +- "--confirm to remove the node and its edges behind a snapshot.",- });- }-- // semantic-retrieval-precision (t_47fd9523): opt-in, proposal-only- // alias-merge candidates. Off by default β this block is a no-op and- // the report is byte-identical to the baseline. The doctor is- // synchronous and embeds nothing, so it uses the deterministic lexical- // (jaccard-over-names) layer; the embedding layer lives on the CLI/MCP- // reader. Candidates are NOMINATIONS β never an auto-merge.- const dedupCfg = resolveEntitySemanticDedupConfig();- if (dedupCfg.enabled) {- for (const c of entityLexicalAliasCandidates(vault, { threshold: dedupCfg.lexicalThreshold })) {- issues.push({- severity: "warning",- code: "entity-alias-candidate",- message:- `possible alias-merge: '${c.name_a}' (${c.a}) ~ '${c.name_b}' (${c.b}) ` +- `[${c.method} ${c.similarity}]. Review and add an alias to merge β never auto-merged.`,- });- }- }-}--export function collectAllBasenames(vault: string): ReadonlySet<string> {- const out = new Set<string>();- const dirs = brainDirs(vault);- for (const d of [- dirs.brain,- dirs.inbox,- dirs.processed,- dirs.preferences,- dirs.retired,- dirs.log,- ]) {- if (!existsSync(d)) continue;- for (const entry of readdirSync(d, { withFileTypes: true })) {- if (!entry.isFile()) continue;- if (!entry.name.endsWith(".md")) continue;- out.add(entry.name.slice(0, -".md".length));- }- }- return out;-}--// Force a runtime touch of parseFrontmatter so importers don't strip-// the dependency on the shared frontmatter parser β used implicitly by-// the parsers we delegate to. Kept here for clarity that doctor's-// invariants ultimately bottom out in the same parse pipeline as the-// dream loop.-void parseFrontmatter;--// ----------------------------------------------------------------------------// Removed-surface references (1.0.0 deprecation sweep)-// -----------------------------------------------------------------------------/** Word-boundary regex per removed tool name, compiled once. */-const REMOVED_TOOL_PATTERNS: ReadonlyArray<{ name: string; pattern: RegExp }> = Object.freeze(- Object.keys(REMOVED_TOOLS).map((name) => ({- name,- // \b treats `_` as a word character, so `my_brain_digestion` does- // not match `brain_digest` but `call brain_digest.` does.- pattern: new RegExp(`\\b${name}\\b`),- })),-);--/** Hard cap so a pathological vault cannot flood the doctor report. */-const REMOVED_TOOL_MAX_WARNINGS = 50;--/**- * Scan vault-side text surfaces for references to MCP tools removed- * in 1.0.0. Scope is exactly what the doctor can see locally:- *- * - every Markdown file under `Brain/` (recursive),- * - root instruction files (`CLAUDE.md`, `AGENTS.md`),- * - installed skills under `.claude/skills/` (recursive `.md`).- *- * One warning per file lists every removed name it mentions with the- * replacement spelling, mirroring the server-side tombstone error.- */-function checkRemovedToolReferences(vault: string, issues: DoctorIssue[]): void {- const candidates: string[] = [];- const dirs = brainDirs(vault);- collectMarkdownFiles(dirs.brain, candidates);- for (const name of ["CLAUDE.md", "AGENTS.md"]) {- const p = join(vault, name);- try {- if (existsSync(p) && statSync(p).isFile()) candidates.push(p);- } catch {- // One unreadable root file must not disable the whole scan.- }- }- collectMarkdownFiles(join(vault, ".claude", "skills"), candidates);-- let emitted = 0;- for (const path of candidates) {- if (emitted >= REMOVED_TOOL_MAX_WARNINGS) return;- let body: string;- try {- body = readFileSync(path, "utf8");- } catch {- continue;- }- const hits: string[] = [];- for (const { name, pattern } of REMOVED_TOOL_PATTERNS) {- if (pattern.test(body)) hits.push(name);- }- if (hits.length === 0) continue;- const replacements = hits- .map((name) => {- const record = REMOVED_TOOLS[name]!;- return `${name} -> ${record.target} view="${record.view}"`;- })- .join("; ");- issues.push({- severity: "warning",- code: "removed-tool-reference",- message:- `${relative(vault, path)} references tool(s) removed in 1.0.0: ` +- `${replacements} (see docs/updating.md)`,- });- emitted += 1;- }-}--/** Recursive `.md` collection, fail-soft on unreadable directories. */-function collectMarkdownFiles(dir: string, out: string[]): void {- if (!existsSync(dir)) return;- let entries;- try {- entries = readdirSync(dir, { withFileTypes: true });- } catch {- return;- }- for (const entry of entries) {- const p = join(dir, entry.name);- if (entry.isDirectory()) collectMarkdownFiles(p, out);- else if (entry.isFile() && entry.name.endsWith(".md")) out.push(p);- }-}+/** Subsystem name the shared context reports an unreadable path under. */+const CONTEXT_SITE = "brain.doctor.context";diff --git a/src/core/brain/doctor/active-budget-check.ts b/src/core/brain/doctor/active-budget-check.tsnew file mode 100644index 00000000..54cc9210--- /dev/null+++ b/src/core/brain/doctor/active-budget-check.ts@@ -0,0 +1,65 @@+/**+ * The injection-budget watermark over `Brain/active.md`.+ *+ * One question: is the rendered active memory about to lose content at+ * inject time, and which sections would relieve it.+ */++import { existsSync } from "node:fs";++import { parseFrontmatter } from "../../vault.ts";+import { computeActiveBudgetPressure } from "../active-budget-pressure.ts";+import { brainActivePath } from "../paths.ts";+import { INJECT_BUDGET_CHARS_DEFAULT } from "../policy.ts";+import type { DoctorCheck } from "./check.ts";++/**+ * `active-budget-pressure` (C4, context-pack-economics-observability):+ * proactive watermark over `Brain/active.md`. Reads the rendered body,+ * measures its fill-rate against the SessionStart injection byte budget+ * (`active.inject_budget_chars`, else the default), and - only when+ * pressure crosses the warn threshold - emits ONE warning naming the+ * ranked eviction candidates an operator could archive to relieve it.+ *+ * "Empty output = healthy": a healthy or missing active.md produces no+ * warning. The candidates are SUGGESTIONS surfaced for the operator /+ * dream; nothing here mutates the vault - the reactive truncation in+ * `active-budget.ts` is the only thing that ever drops content, and it+ * does so at render time, not here.+ */+export const activeBudgetPressureCheck: DoctorCheck = {+ failSoft: true,+ run({ vault, config }, { issues }) {+ const path = brainActivePath(vault);+ if (!existsSync(path)) return;+ let body: string;+ try {+ [, body] = parseFrontmatter(path);+ } catch {+ // A corrupted active.md is a derived-view problem the dream loop+ // rewrites; not this probe's concern.+ return;+ }+ const budget = config?.active?.inject_budget_chars ?? INJECT_BUDGET_CHARS_DEFAULT;+ const pressure = computeActiveBudgetPressure(body.trim(), budget);+ if (pressure.status === "healthy") return; // quiet on healthy vaults++ const pct = Math.round(pressure.fillRate * 100);+ const ranked = pressure.candidates+ .map((c) => `${c.sectionKey.replace(/^## /, "")} (${c.bytes}B)`)+ .join(", ");+ const suggestion =+ pressure.candidates.length > 0+ ? ` Archive candidates, highest-priority-to-drop first: ${ranked}.`+ : " No stale sections to archive - trim the confirmed rule set instead.";+ issues.push({+ severity: "warning",+ code: "active-budget-pressure",+ path,+ message:+ `active.md is at ${pct}% of the ${budget}-char injection budget (${pressure.status}).` ++ " Content will be dropped at inject time once it overflows." ++ suggestion,+ });+ },+};diff --git a/src/core/brain/doctor/check.ts b/src/core/brain/doctor/check.tsnew file mode 100644index 00000000..3e64af5a--- /dev/null+++ b/src/core/brain/doctor/check.ts@@ -0,0 +1,66 @@+/**+ * The shape every doctor check shares.+ *+ * The checks have nothing to do with one another - a malformed+ * timestamp and an escaping symlink are unrelated conditions - so what+ * holds the pass together is this contract rather than any shared logic:+ * each check reads the one context the pass built and writes findings+ * into the two streams the report is partitioned from. A new check joins+ * the pass by being added to the registry array in `doctor.ts`.+ */++import type { BrainConfig, DoctorIssue } from "../types.ts";+import type { LogRecord, PreferenceRecord } from "./records.ts";+import type { DoctorUncertainEntry } from "./report.ts";++/**+ * Everything the checks read, resolved once per pass.+ *+ * The two record snapshots and the basename universe are built up-front+ * rather than per check: several checks walk the same directories, and+ * re-parsing them once per lint is what this context exists to prevent.+ */+export interface DoctorCheckContext {+ readonly vault: string;+ /** Wall clock for the age-based lints, so tests can pin it. */+ readonly now: Date;+ /** Resolved `_brain.yaml`, or absent when it could not be loaded. */+ readonly config: BrainConfig | undefined;+ /** Search-index path for index-backed checks; absent skips them. */+ readonly dbPath: string | undefined;+ /** Every valid wikilink target inside `Brain/`, keyed by basename. */+ readonly knownBasenames: ReadonlySet<string>;+ /**+ * Frontmatter ids to the files that declare them. The record checks+ * fill it as they walk and the duplicate-id check reads it once they+ * are done, which is why it is the one mutable member here - the+ * ordering that makes it work is the registry's ordering.+ */+ readonly idIndex: Map<string, string[]>;+ readonly preferences: ReadonlyArray<PreferenceRecord>;+ readonly logs: ReadonlyArray<LogRecord>;+}++/**+ * The two streams a check writes into. `issues` is partitioned by+ * severity into the report's warnings and errors; `uncertain` carries+ * sub-operations the doctor attempted but cannot claim it verified.+ */+export interface DoctorFindings {+ readonly issues: DoctorIssue[];+ readonly uncertain: DoctorUncertainEntry[];+}++export interface DoctorCheck {+ /**+ * True when a throw from `run` is swallowed by the pass, so one+ * broken scan cannot mask the findings of every check after it.+ *+ * False for the checks over the store's structural core - the config,+ * the record frontmatter, the id index, the logs, the backlinks. A+ * failure there does not leave the report incomplete, it leaves it+ * wrong, so the throw propagates out of `runDoctor` instead.+ */+ readonly failSoft: boolean;+ run(ctx: DoctorCheckContext, out: DoctorFindings): void;+}diff --git a/src/core/brain/doctor/config-checks.ts b/src/core/brain/doctor/config-checks.tsnew file mode 100644index 00000000..c9b504f7--- /dev/null+++ b/src/core/brain/doctor/config-checks.ts@@ -0,0 +1,164 @@+/**+ * Operator-declared configuration that cannot do what it says.+ *+ * `_brain.yaml` itself, the `vault.ignore_paths` block, and the capture+ * boundary's message patterns are all things the operator wrote down and+ * the runtime then has to honour. When one of them is unreadable, names a+ * schema this build does not know, points at nothing, or fails to+ * compile, the declaration and the behaviour have silently diverged -+ * which is the single condition this module reports.+ */++import { existsSync, statSync } from "node:fs";+import { join } from "node:path";++import { resolveVaultScope } from "../../vault-scope/index.ts";+import { buildCaptureBoundary } from "../capture-boundary.ts";+import { brainConfigPath } from "../paths.ts";+import {+ BRAIN_CONFIG_SUPPORTED_VERSIONS,+ BrainConfigError,+ loadBrainConfigDetailed,+} from "../policy.ts";+import type { DoctorCheck } from "./check.ts";+import { sweptFailureReason } from "./unreadable-path.ts";+import type { DoctorIssue } from "../types.ts";++export const configCheck: DoctorCheck = {+ failSoft: false,+ run({ vault }, { issues }) {+ const cfgPath = brainConfigPath(vault);+ // Not `existsSync`: it answers false for a permission denial on the+ // file or on any parent component exactly as it does for a config+ // nobody has written, and this branch advises `o2b brain init` -+ // which on a populated store the doctor merely could not read is+ // advice to bootstrap over it. A read failure is the same finding+ // the catch arm below reports for a file that opens and does not+ // parse: the declaration could not be honoured, for a stated reason.+ const absence = configAbsence(cfgPath);+ if (absence !== null) {+ issues.push(absence);+ return;+ }+ try {+ const { config, warnings } = loadBrainConfigDetailed(vault);+ if (!BRAIN_CONFIG_SUPPORTED_VERSIONS.includes(config.schema_version)) {+ issues.push({+ severity: "error",+ code: "schema-version-unknown",+ path: cfgPath,+ message:+ `_brain.yaml schema_version ${config.schema_version} is not in the supported set ` ++ `(${BRAIN_CONFIG_SUPPORTED_VERSIONS.join(", ")})`,+ });+ }+ for (const w of warnings) {+ issues.push({+ severity: "warning",+ code: "config-warning",+ path: cfgPath,+ message: w.message,+ });+ }+ } catch (err) {+ if (err instanceof BrainConfigError) {+ issues.push({+ severity: "error",+ code: "config-invalid",+ path: cfgPath,+ message: err.message,+ });+ } else {+ issues.push({+ severity: "error",+ code: "config-invalid",+ path: cfgPath,+ message: `_brain.yaml could not be loaded: ${(err as Error).message ?? String(err)}`,+ });+ }+ }+ },+};++/**+ * The finding for a `_brain.yaml` that could not be opened at all, or+ * `null` when it is there to be loaded. Absence keeps its own code and+ * its own message, byte for byte; every other failure reports the same+ * `config-invalid` the load path already reports, naming the errno.+ */+function configAbsence(cfgPath: string): DoctorIssue | null {+ try {+ statSync(cfgPath);+ return null;+ } catch (err) {+ const reason = sweptFailureReason(err);+ if (reason === null) {+ return {+ severity: "error",+ code: "config-missing",+ path: cfgPath,+ message: "_brain.yaml is missing; run `o2b brain init` to bootstrap the Brain layer",+ };+ }+ return {+ severity: "error",+ code: "config-invalid",+ path: cfgPath,+ message: `_brain.yaml could not be read: ${reason}`,+ };+ }+}++/**+ * v0.10.9 hygiene lint: surface path-style entries in+ * `vault.ignore_paths` that do not resolve to anything on disk. Such+ * entries are typically typos β they look like exclusions but cannot+ * fire. Bare-name rules are skipped (a missing `.git` directory is+ * not an error).+ *+ * Only runs when the operator declared the block themselves; the+ * built-in default set may legitimately list paths that do not exist+ * in a given vault.+ */+export const vaultIgnoreCheck: DoctorCheck = {+ failSoft: false,+ run({ vault }, { issues }) {+ let scope;+ try {+ scope = resolveVaultScope(vault);+ } catch {+ // `configCheck` already reports the malformed/unreadable _brain.yaml.+ // Do not let this follow-on lint mask the primary config issue.+ return;+ }+ if (scope.source !== "_brain.yaml") return;+ for (const rule of scope.rules) {+ if (rule.kind !== "path") continue;+ if (existsSync(join(vault, rule.raw))) continue;+ issues.push({+ severity: "warning",+ code: "vault-ignore-missing-path",+ message: `vault.ignore_paths entry '${rule.raw}' does not exist in this vault`,+ });+ }+ },+};++/**+ * Memory Integrity Suite: capture-boundary patterns that failed to+ * compile (invalid regex in sessions.ignore_message_patterns or the+ * machine-local additions). Capture itself degrades gracefully; the+ * doctor makes the skipped pattern visible.+ */+export const capturePatternCheck: DoctorCheck = {+ failSoft: true,+ run({ vault }, { issues }) {+ for (const warning of buildCaptureBoundary(vault).warnings) {+ issues.push({+ severity: "warning",+ code: "invalid-capture-pattern",+ message: warning,+ });+ }+ },+};diff --git a/src/core/brain/doctor/entity-checks.ts b/src/core/brain/doctor/entity-checks.tsnew file mode 100644index 00000000..e31fd0cc--- /dev/null+++ b/src/core/brain/doctor/entity-checks.ts@@ -0,0 +1,90 @@+/**+ * Canonical entity registry hygiene (Memory Integrity Suite).+ *+ * Write seams refuse duplicates, so anything reported here arrived+ * through hand edits or sync merges - observable, never auto-deleted.+ */++import {+ entityLexicalAliasCandidates,+ resolveEntitySemanticDedupConfig,+} from "../entities/semantic-dedup.ts";+import { buildEntityIndex } from "../entities/index-builder.ts";+import { findMalformedEntityLabels } from "../entities/label-hygiene.ts";+import type { DoctorCheck } from "./check.ts";++/**+ * `duplicate-entity` / `broken-entity-relation`: duplicates come+ * straight from the index builder's conflict report; broken relations+ * are edges whose target resolves to no entity id in the registry.+ */+export const entityRegistryCheck: DoctorCheck = {+ failSoft: true,+ run({ vault }, { issues }) {+ const index = buildEntityIndex(vault);+ if (index.entities.length === 0 && index.conflicts.length === 0) return;++ for (const conflict of index.conflicts) {+ issues.push({+ severity: "warning",+ code: "duplicate-entity",+ message:+ `${conflict.kind === "duplicate-name" ? "identity" : "alias"} '${conflict.key}' is ` ++ `claimed by ${conflict.paths.length} entity files: ${conflict.paths.join(", ")}. ` ++ "Merge them or archive the duplicates - lookups resolve to the first claimant only.",+ });+ }++ const knownIds = new Set(index.entities.map((e) => e.id));+ for (const entity of index.entities) {+ for (const edge of entity.relations) {+ if (knownIds.has(edge.target)) continue;+ issues.push({+ severity: "warning",+ code: "broken-entity-relation",+ path: entity.path,+ message:+ `${entity.id} declares '${edge.relation}: [[${edge.target}]]' but no entity ` ++ "with that id exists in the registry.",+ });+ }+ }++ // A1 (t_657b365e): surface stored nodes whose labels fail the quality+ // gate (structurally junk after decoration stripping, or operator-+ // denylisted) as prune candidates. Warning severity - the operator runs+ // `o2b brain entity prune` (dry-run default) to review and remove them.+ for (const malformed of findMalformedEntityLabels(vault)) {+ issues.push({+ severity: "warning",+ code: "entity-label-malformed",+ path: malformed.path,+ message:+ `${malformed.id} has a malformed label ${JSON.stringify(malformed.name)} ` ++ `(${malformed.reason}). Review with 'o2b brain entity prune' and re-run with ` ++ "--confirm to remove the node and its edges behind a snapshot.",+ });+ }++ // semantic-retrieval-precision (t_47fd9523): opt-in, proposal-only+ // alias-merge candidates. Off by default β this block is a no-op and+ // the report is byte-identical to the baseline. The doctor is+ // synchronous and embeds nothing, so it uses the deterministic lexical+ // (jaccard-over-names) layer; the embedding layer lives on the CLI/MCP+ // reader. Candidates are NOMINATIONS β never an auto-merge.+ const dedupCfg = resolveEntitySemanticDedupConfig();+ if (dedupCfg.enabled) {+ for (const c of entityLexicalAliasCandidates(vault, {+ threshold: dedupCfg.lexicalThreshold,+ })) {+ issues.push({+ severity: "warning",+ code: "entity-alias-candidate",+ message:+ `possible alias-merge: '${c.name_a}' (${c.a}) ~ '${c.name_b}' (${c.b}) ` ++ `[${c.method} ${c.similarity}]. Review and add an alias to merge β never auto-merged.`,+ });+ }+ }+ },+};diff --git a/src/core/brain/doctor/link-checks.ts b/src/core/brain/doctor/link-checks.tsnew file mode 100644index 00000000..a98967e7--- /dev/null+++ b/src/core/brain/doctor/link-checks.ts@@ -0,0 +1,94 @@+/**+ * Brain-managed wikilink targets that resolve to no file.+ *+ * The record checks validate the links a record DECLARES in its+ * frontmatter; this one reads the backlink index, so it also sees the+ * references buried in body prose and in the log.+ */++import { buildBacklinkIndex } from "../backlinks.ts";+import { brainDirs } from "../paths.ts";+import { isBrainArtifactId } from "../wikilink.ts";+import type { DoctorCheck } from "./check.ts";+import type { DoctorUncertainEntry } from "./report.ts";+import { reportSweptFailure, sweptFailurePath, SWEEP_ORIGIN } from "./unreadable-path.ts";++/**+ * 8. Broken-backlinks lint β any preference / retired / log entry+ * that wikilinks to a Brain artifact id (`pref-...`, `ret-...`,+ * `sig-...`) whose file no longer exists. Surfaces at warning+ * severity: a dangling reference is a real data-hygiene problem+ * but doesn't block the dream loop, so the digest / cron want+ * to see it without failing the run.+ */+export const brokenBacklinkCheck: DoctorCheck = {+ failSoft: false,+ run({ vault, knownBasenames }, { issues, uncertain }) {+ // Only attempt the check when there's something to scan β an empty+ // Brain layer naturally has no backlinks, and `buildBacklinkIndex`+ // would already return an empty map, but we save the parse pass.+ if (knownBasenames.size === 0) return;+ const index = buildIndex(vault, uncertain);+ if (index === null) return;+ for (const [target, refs] of index) {+ // We only flag references whose target *should* live in this+ // Brain (i.e. an artifact id we manage). Wikilinks pointing+ // outside the Brain layer are user prose and not our concern.+ if (!isBrainArtifactId(target)) continue;+ if (knownBasenames.has(target)) continue;+ const sources = Array.from(new Set(refs.map((r) => r.source))).toSorted();+ issues.push({+ severity: "warning",+ code: "broken-backlinks",+ // no-dead-ends, task 12. This issue has no `path` - the whole+ // finding is that no file with this basename exists - so before+ // these fields the referencing sources were reachable only by+ // splitting the tail of the sentence on ", ". The message keeps+ // them too; the human surface is unchanged.+ target,+ sources,+ message:+ `[[${target}]] is referenced by ${sources.length} source(s) but no file with that ` ++ `basename exists under Brain/: ${sources.join(", ")}`,+ });+ }+ },+};++/** Subsystem name the backlink index reports an unreadable path under. */+const BACKLINK_SITE = "brain.doctor.brokenBacklinks";++/**+ * The backlink index, or `null` plus the reason there is none.+ *+ * The index walks the record directories and the log through a shared+ * builder, so a directory it cannot read arrives here as a throw. This+ * check does not fail soft - a backlink index the doctor mis-reads+ * leaves the report wrong rather than incomplete - so before this the+ * throw ended the pass, with every finding already collected lost with+ * it. A directory that was not read is a different statement from a+ * store whose links are all resolvable, and it is the one this makes.+ */+function buildIndex(+ vault: string,+ uncertain: DoctorUncertainEntry[],+): ReturnType<typeof buildBacklinkIndex> | null {+ try {+ return buildBacklinkIndex(vault);+ } catch (err) {+ reportSweptFailure(+ sweptFailurePath(err, brainDirs(vault).brain),+ "backlink index build failed",+ err,+ {+ site: BACKLINK_SITE,+ consequence:+ "no backlink in the store was resolved, so a reference to a deleted artifact is " ++ "missing from this report",+ uncertain,+ },+ SWEEP_ORIGIN.root,+ );+ return null;+ }+}diff --git a/src/core/brain/doctor/log-checks.ts b/src/core/brain/doctor/log-checks.tsnew file mode 100644index 00000000..11e2f114--- /dev/null+++ b/src/core/brain/doctor/log-checks.ts@@ -0,0 +1,160 @@+/**+ * The event log: its shard structure and the artifact references its+ * apply-evidence events carry.+ *+ * One reason to change: the log format. A malformed header is a defect+ * in the file itself; a malformed or unresolvable artifact reference is+ * a defect in what an event points at.+ */++import type { DegradationNotice } from "../../integrity/degradation.ts";+import { listVaultBasenames } from "../../vault.ts";+import { listLogMarkdownFiles } from "../log-jsonl.ts";+import { parseLogDayFile } from "../log.ts";+import { brainDirs } from "../paths.ts";+import { BRAIN_LOG_EVENT_KIND } from "../types.ts";+import { parseArtifactRef } from "../wikilink.ts";+import type { DoctorCheck } from "./check.ts";+import type { DoctorUncertainEntry } from "./report.ts";+import { forwardSweepNotices, reportSweptFailure, SWEEP_ORIGIN } from "./unreadable-path.ts";++/** Subsystem name the shard discovery reports an unreadable path under. */+const LOG_SHARD_SITE = "brain.doctor.logShard";++/**+ * 7. Log header parsing β surface warnings from every markdown shard.+ */+export const logShardCheck: DoctorCheck = {+ failSoft: false,+ run({ vault }, { issues, uncertain }) {+ // Per-device shards (Memory Integrity Suite): lint every markdown+ // log file - legacy `<date>.md` and sharded `<date>.<deviceId>.md` -+ // so warnings keep their exact file paths and line numbers.+ //+ // The discovery itself is behind a shared helper: a `Brain/log` that+ // is a regular file arrives as a throw, and this check does not fail+ // soft, so it took the whole pass down with it. The read is now+ // classified like every other; a parse failure below still throws,+ // because a log the doctor mis-parses leaves the report wrong rather+ // than incomplete.+ for (const { date, path } of listShards(vault, uncertain)) {+ const { warnings } = parseLogDayFile(vault, date, path);+ for (const w of warnings) {+ issues.push({+ severity: "warning",+ code: "log-malformed",+ path: w.path,+ message: `line ${w.lineNumber}: ${w.message}`,+ });+ }+ }+ },+};++/** The markdown log shards, or none plus the reason there are none to lint. */+function listShards(+ vault: string,+ uncertain: DoctorUncertainEntry[],+): ReadonlyArray<{ date: string; path: string }> {+ try {+ return listLogMarkdownFiles(vault);+ } catch (err) {+ reportSweptFailure(+ brainDirs(vault).log,+ "log shard discovery failed",+ err,+ {+ site: LOG_SHARD_SITE,+ consequence:+ "no log shard under it was linted, so a malformed header in this vault's history is " ++ "missing from this report",+ uncertain,+ },+ SWEEP_ORIGIN.root,+ );+ return [];+ }+}++/**+ * `malformed-evidence-range`: walks every `apply-evidence` event,+ * runs the artifact wikilink through {@link parseArtifactRef}, and+ * flags any malformed range suffix (`:abc-def`, `:120-100`, etc.).+ * The event itself remains valid β only the range is malformed.+ */+export const evidenceRangeCheck: DoctorCheck = {+ failSoft: true,+ run({ logs }, { issues }) {+ for (const { entries } of logs) {+ for (const e of entries) {+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;+ const artifact = e.body["artifact"];+ if (typeof artifact !== "string") continue;+ const parsed = parseArtifactRef(artifact);+ if (parsed.malformedRange) {+ issues.push({+ severity: "warning",+ code: "malformed-evidence-range",+ message:+ `apply-evidence at ${e.timestamp} references artifact ${parsed.raw}` ++ ` with malformed range '${parsed.rangeText}'.` ++ " Use `[[file:N-N]]` (inclusive, 1-based) or `[[file:N]]`.",+ });+ }+ }+ }+ },+};++/** Subsystem name the basename sweep reports an unreadable path under. */+const ORPHAN_EVIDENCE_SITE = "brain.doctor.orphanEvidence";++/**+ * `orphan-evidence`: walks every `apply-evidence` event and verifies+ * the artifact wikilink resolves to some file in the vault. Obsidian+ * wikilinks resolve by basename; we use the cheap basename-only+ * walker from `vault.ts` (no frontmatter parse).+ *+ * This is the only doctor lint that walks the entire vault (not just+ * `Brain/`). It's an on-demand check; doctor isn't called per-turn.+ *+ * The walker is fail-soft over a directory it cannot list, so an+ * unreadable subtree silently shrank the universe every reference here+ * is resolved against - and a reference into that subtree then reads as+ * orphaned. Those directories now arrive on the walker's notice sink and+ * are reported as uncertainty; the findings below are unchanged.+ */+export const orphanEvidenceCheck: DoctorCheck = {+ failSoft: true,+ run({ vault, logs }, { issues, uncertain }) {+ const notices: DegradationNotice[] = [];+ const basenames: ReadonlySet<string> = listVaultBasenames(vault, {+ notices,+ site: ORPHAN_EVIDENCE_SITE,+ });+ forwardSweepNotices(notices, {+ site: ORPHAN_EVIDENCE_SITE,+ consequence:+ "its pages are absent from the basename universe this lint resolves artifact " ++ "references against, so a reference that resolves under it reads as orphaned here",+ uncertain,+ });+ for (const { entries } of logs) {+ for (const e of entries) {+ if (e.eventType !== BRAIN_LOG_EVENT_KIND.applyEvidence) continue;+ const artifact = e.body["artifact"];+ if (typeof artifact !== "string") continue;+ const target = parseArtifactRef(artifact).target;+ if (!target) continue;+ if (basenames.has(target)) continue;+ issues.push({+ severity: "warning",+ code: "orphan-evidence",+ message:+ `apply-evidence at ${e.timestamp} references artifact [[${target}]]` ++ " but no file with that basename exists in the vault.",+ });+ }+ }+ },+};diff --git a/src/core/brain/doctor/preference-hygiene.ts b/src/core/brain/doctor/preference-hygiene.tsnew file mode 100644index 00000000..fe4cbd13--- /dev/null+++ b/src/core/brain/doctor/preference-hygiene.ts@@ -0,0 +1,166 @@+/**+ * Hygiene of the rule set itself (Β§11).+ *+ * Every check here reads the preference snapshot and asks the same kind+ * of question: is this rule still earning its place? Near-duplicates,+ * confirmations no use ever backed, pins nothing keeps warm, and stored+ * hashes the live text no longer produces.+ */++import { verifyContentHash } from "../content-hash.ts";+import { findSimilarPairs, tokenise } from "../similarity.ts";+import { BRAIN_PREFERENCE_STATUS } from "../types.ts";+import type { DoctorCheck } from "./check.ts";++const JACCARD_DUPLICATE_THRESHOLD = 0.7;++/** Milliseconds in a day, for the two age cutoffs below. */+const DAY_MS = 24 * 3600 * 1000;++/**+ * `duplicate-preferences`: pairwise jaccard similarity of `principle`+ * tokens within each `(topic, scope)` bucket of confirmed/quarantine+ * prefs. Pairs with similarity β₯ `JACCARD_DUPLICATE_THRESHOLD` are+ * flagged. Unconfirmed and retired prefs are excluded β they're+ * meant to be replaced or already are.+ */+export const duplicatePreferenceCheck: DoctorCheck = {+ failSoft: true,+ run({ config, preferences }, { issues }) {+ if (config === undefined) return;+ const entries = [];+ for (const { pref } of preferences) {+ if (+ pref.status !== BRAIN_PREFERENCE_STATUS.confirmed &&+ pref.status !== BRAIN_PREFERENCE_STATUS.quarantine+ )+ continue;+ entries.push({+ id: pref.id,+ // Same-scope-undefined falls in its own bucket. Mirrors the+ // Β§12 merge-candidate detector exactly β both surfaces stay+ // in sync via the shared walker.+ bucketKey: `${pref.topic}\x00${pref.scope ?? ""}`,+ tokens: tokenise(pref.principle),+ source: pref,+ });+ }+ const pairs = findSimilarPairs(entries, { threshold: JACCARD_DUPLICATE_THRESHOLD });+ for (const pair of pairs) {+ const a = pair.a.source;+ issues.push({+ severity: "warning",+ code: "duplicate-preferences",+ message:+ `[[${pair.a.id}]] and [[${pair.b.id}]] in topic '${a.topic}'` ++ `${a.scope ? ` (scope: ${a.scope})` : ""}` ++ ` look like duplicates (jaccard ${pair.jaccard.toFixed(2)} of principle tokens).` ++ " Consider merging.",+ });+ }+ },+};++/**+ * `low-evidence-confirmed`: a confirmed pref whose `applied_count` is+ * still at or below `low_max_applied` long after its trial window+ * (`unconfirmed_window_days`). Catches prefs that promoted on the+ * minimum evidence but never saw real use β candidates for review.+ */+export const lowEvidenceConfirmedCheck: DoctorCheck = {+ failSoft: true,+ run({ config, preferences, now }, { issues }) {+ if (config === undefined) return;+ const cutoffMs = now.getTime() - config.dream.unconfirmed_window_days * DAY_MS;+ for (const { pref } of preferences) {+ if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;+ if (pref.applied_count > config.confidence.low_max_applied) continue;+ if (!pref.confirmed_at) continue;+ const confirmedMs = Date.parse(pref.confirmed_at);+ if (!Number.isFinite(confirmedMs)) continue;+ if (confirmedMs >= cutoffMs) continue;+ issues.push({+ severity: "warning",+ code: "low-evidence-confirmed",+ message:+ `[[${pref.id}]] is confirmed but applied_count=${pref.applied_count} β€ ` ++ `low_max_applied=${config.confidence.low_max_applied} after ${config.dream.unconfirmed_window_days}+ days.` ++ " The rule hasn't seen real use β review or retire.",+ });+ }+ },+};++/**+ * `pinned-without-recent-evidence`: a pinned pref whose+ * `last_evidence_at` is null or older than `stale_evidence_days`. The+ * pin protects the rule from automatic retire, but the data shows it+ * isn't actively backed β alert the user.+ */+export const pinnedWithoutRecentEvidenceCheck: DoctorCheck = {+ failSoft: true,+ run({ config, preferences, now }, { issues }) {+ if (config === undefined) return;+ const cutoffMs = now.getTime() - config.retire.stale_evidence_days * DAY_MS;+ for (const { pref } of preferences) {+ if (!pref.pinned) continue;+ if (!pref.last_evidence_at) {+ issues.push({+ severity: "warning",+ code: "pinned-without-recent-evidence",+ message:+ `[[${pref.id}]] is pinned but has never received apply-evidence.` ++ " Confirm the pin is intentional.",+ });+ continue;+ }+ const lastMs = Date.parse(pref.last_evidence_at);+ if (!Number.isFinite(lastMs)) continue;+ if (lastMs >= cutoffMs) continue;+ issues.push({+ severity: "warning",+ code: "pinned-without-recent-evidence",+ message:+ `[[${pref.id}]] is pinned but last_evidence_at=${pref.last_evidence_at} is older than ` ++ `stale_evidence_days=${config.retire.stale_evidence_days}. Pin may be outdated.`,+ });+ }+ },+};++/**+ * `content-hash-drift` (v0.12.0, Brain Integrity Suite): walks every+ * confirmed preference, recomputes the content hash from the live+ * `(principle, scope)`, and surfaces a warning whenever the stored+ * `_content_hash` no longer matches. Legacy preferences without a+ * stored hash are silent - drift detection is opt-in via the+ * promotion-time hash write.+ *+ * Hand-edits stay legal: this is observability, not enforcement. The+ * operator sees the divergence and decides whether to re-promote the+ * preference (which writes a fresh hash) or accept the drift.+ */+export const contentHashDriftCheck: DoctorCheck = {+ failSoft: true,+ run({ preferences }, { issues }) {+ for (const { path, pref } of preferences) {+ if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;+ if (!pref.content_hash) continue;+ const v = verifyContentHash({+ principle: pref.principle,+ scope: pref.scope,+ content_hash: pref.content_hash,+ });+ if (!v.ok) {+ issues.push({+ severity: "warning",+ code: "content-hash-drift",+ path,+ message:+ `content-hash drift on ${pref.id}: stored ${v.observed} ` ++ `does not match recomputed ${v.expected}`,+ });+ }+ }+ },+};diff --git a/src/core/brain/doctor/record-checks.ts b/src/core/brain/doctor/record-checks.tsnew file mode 100644index 00000000..4479a68e--- /dev/null+++ b/src/core/brain/doctor/record-checks.ts@@ -0,0 +1,350 @@+/**+ * Frontmatter invariants of the three Brain record kinds.+ *+ * One reason to change: the record schema. Required fields, ISO-8601+ * timestamps, wikilink targets, the id-to-filename agreement, id+ * uniqueness across the store, and the classification of a parse+ * failure into a doctor code all follow from it.+ */++import { join } from "node:path";++import { extractWikilinks } from "../../vault.ts";+import { BrainParseError } from "../parse-error.ts";+import { brainDirs } from "../paths.ts";+import { BrainStatusFolderMismatchError, parsePreference, parseRetired } from "../preference.ts";+import { parseSignal } from "../signal.ts";+import { principleNeedsRepair } from "../text/sanitize-principle.ts";+import type { DoctorIssue } from "../types.ts";+import { normaliseWikilinkTarget } from "../wikilink.ts";+import type { DoctorCheck } from "./check.ts";+import type { DoctorUncertainEntry } from "./report.ts";+import { readSweptDir, SWEEP_ORIGIN, type SweptPath } from "./unreadable-path.ts";++// ----- Signal check ---------------------------------------------------------++export const signalCheck: DoctorCheck = {+ failSoft: false,+ run({ vault, idIndex }, { issues, uncertain }) {+ const dirs = brainDirs(vault);+ const swept = recordSweep("signal", uncertain);+ for (const dir of [dirs.inbox, dirs.processed]) {+ forEachBrainFile(dir, "sig-", swept, (path, filename) => {+ try {+ const sig = parseSignal(path);+ registerId(idIndex, sig.id, path);+ checkIso(path, "created_at", sig.created_at, issues);+ const expectedId = filename.slice(0, -".md".length);+ if (sig.id !== expectedId) {+ issues.push({+ severity: "warning",+ code: "id-filename-mismatch",+ path,+ message: `signal id '${sig.id}' differs from filename basename '${expectedId}'`,+ });+ }+ } catch (err) {+ issues.push({+ severity: "error",+ code: "signal-invalid",+ path,+ message: (err as Error).message ?? String(err),+ });+ }+ });+ }+ },+};++// ----- Preference check -----------------------------------------------------++export const preferenceCheck: DoctorCheck = {+ failSoft: false,+ run({ vault, idIndex, knownBasenames }, { issues, uncertain }) {+ const dirs = brainDirs(vault);+ forEachBrainFile(dirs.preferences, "pref-", recordSweep("preference", uncertain), (path) => {+ try {+ const pref = parsePreference(path);+ registerId(idIndex, pref.id, path);+ checkIso(path, "created_at", pref.created_at, issues);+ checkIso(path, "unconfirmed_until", pref.unconfirmed_until, issues);+ if (pref.confirmed_at !== null) {+ checkIso(path, "confirmed_at", pref.confirmed_at, issues);+ }+ if (pref.last_evidence_at !== null) {+ checkIso(path, "last_evidence_at", pref.last_evidence_at, issues);+ }+ // Status invariant β the parser already enforces the canonical+ // values via the enum; a non-canonical value would have thrown+ // BrainStatusFolderMismatchError, caught below. Reaching here+ // means the status is valid; nothing more to check.+ checkWikilinks(path, "evidenced_by", pref.evidenced_by, knownBasenames, issues);+ if (pref.supersedes) {+ checkWikilinks(path, "supersedes", [pref.supersedes], knownBasenames, issues);+ }+ // Principle corruption (token-diet, t_40eb1de7): leaked tool-call+ // fragments or escape-amplified quote chains written before the+ // sanitizing write seam shipped. `o2b brain upgrade --apply`+ // repairs these in place.+ if (principleNeedsRepair(pref.principle)) {+ issues.push({+ severity: "warning",+ code: "principle-corrupted",+ path,+ message:+ "principle carries leaked tool-call fragments or escape-amplified quotes; run `o2b brain upgrade --apply` to repair",+ });+ }+ } catch (err) {+ classifyParseError(err, path, "preference", issues);+ }+ });+ },+};++// ----- Retired check --------------------------------------------------------++export const retiredCheck: DoctorCheck = {+ failSoft: false,+ run({ vault, idIndex, knownBasenames }, { issues, uncertain }) {+ const dirs = brainDirs(vault);+ forEachBrainFile(dirs.retired, "ret-", recordSweep("retired", uncertain), (path) => {+ try {+ const ret = parseRetired(path);+ registerId(idIndex, ret.id, path);+ checkIso(path, "created_at", ret.created_at, issues);+ checkIso(path, "retired_at", ret.retired_at, issues);+ if (ret.last_evidence_at !== null) {+ checkIso(path, "last_evidence_at", ret.last_evidence_at, issues);+ }+ checkWikilinks(path, "evidenced_by", ret.evidenced_by, knownBasenames, issues);+ checkWikilinks(path, "retired_by", [ret.retired_by], knownBasenames, issues);+ if (ret.superseded_by) {+ checkWikilinks(path, "superseded_by", [ret.superseded_by], knownBasenames, issues);+ }+ } catch (err) {+ classifyParseError(err, path, "retired", issues);+ }+ });+ },+};++// ----- Duplicate id ---------------------------------------------------------++/**+ * Two distinct files claiming one frontmatter id. Reads the index the+ * three record checks filled, so it has to run after them.+ */+export const duplicateIdCheck: DoctorCheck = {+ failSoft: false,+ run({ idIndex }, { issues }) {+ for (const [id, paths] of idIndex.entries()) {+ if (paths.length > 1) {+ issues.push({+ severity: "error",+ code: "duplicate-id",+ message: `duplicate id '${id}' across files: ${paths.join(", ")}`,+ });+ }+ }+ },+};++// ----- Helpers --------------------------------------------------------------++function registerId(idIndex: Map<string, string[]>, id: string, path: string): void {+ const list = idIndex.get(id);+ if (list) list.push(path);+ else idIndex.set(id, [path]);+}++/** Subsystem name a record sweep reports an unreadable directory under. */+const RECORD_SITE = "brain.doctor.records";++/** What a record kind's checks can no longer claim, as one clause. */+function recordSweep(kind: string, uncertain: DoctorUncertainEntry[]): SweptPath {+ return {+ site: RECORD_SITE,+ consequence:+ `no ${kind} record in it was validated, so a malformed one - or an id it duplicates - ` ++ "is missing from this report",+ uncertain,+ };+}++/**+ * Iterate the `<prefix>*.md` files directly inside `dir` (non-recursive),+ * invoking `cb(path, filename)` for each. Absent `dir` is a no-op - the+ * per-kind checks all treat a missing Brain subdirectory as "nothing to+ * check", not an error.+ *+ * A directory that exists and cannot be listed is neither: these checks+ * are the pass's structural core and do not fail soft, so an unreadable+ * `Brain/preferences` used to end the run with no findings whatsoever.+ * It is now the same uncertainty every other sweep reports.+ */+function forEachBrainFile(+ dir: string,+ prefix: string,+ swept: SweptPath,+ cb: (path: string, filename: string) => void,+): void {+ const entries = readSweptDir(dir, swept, SWEEP_ORIGIN.root);+ if (entries === null) return;+ for (const entry of entries) {+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;+ if (!entry.name.startsWith(prefix)) continue;+ cb(join(dir, entry.name), entry.name);+ }+}++/** Record kinds whose parse failures this module classifies. */+type ParsedRecordKind = "preference" | "retired";++const PREFERENCE_MISSING_FIELD_CODE = "preference-missing-field";+const PREFERENCE_INVALID_CODE = "preference-invalid";+const RETIRED_MISSING_FIELD_CODE = "retired-missing-field";+const RETIRED_INVALID_CODE = "retired-invalid";+const ISO_INVALID_CODE = "iso-invalid";++/**+ * The parse-failure codes, per record kind, written out.+ *+ * These four used to be built by concatenating the kind onto a suffix,+ * which meant they appeared nowhere in this module as readable strings -+ * so the doctor's own code population could not be enumerated from its+ * source, and the exit census (`tests/core/brain/doctor-exit-census.test.ts`)+ * could not see them to demand a classification.+ */+const PARSE_ERROR_CODES: Readonly<+ Record<ParsedRecordKind, { readonly missingField: string; readonly invalid: string }>+> = Object.freeze({+ preference: Object.freeze({+ missingField: PREFERENCE_MISSING_FIELD_CODE,+ invalid: PREFERENCE_INVALID_CODE,+ }),+ retired: Object.freeze({+ missingField: RETIRED_MISSING_FIELD_CODE,+ invalid: RETIRED_INVALID_CODE,+ }),+});++/** Which of the three parse-failure codes `msg` from `kind` reports. */+function parseErrorCode(kind: ParsedRecordKind, msg: string): string {+ if (/missing field/.test(msg)) return PARSE_ERROR_CODES[kind].missingField;+ if (/ISO-8601/i.test(msg)) return ISO_INVALID_CODE;+ return PARSE_ERROR_CODES[kind].invalid;+}++/**+ * Classify a parse-time error into a `DoctorIssue` and push it. Shared by+ * the preference and retired checks, which previously carried+ * byte-identical copies of this regex-based classification - a change to+ * a parser's error wording would otherwise reclassify issues in one path+ * without the other noticing.+ *+ * A {@link BrainParseError} - which both parsers now raise, and which+ * `BrainStatusFolderMismatchError` extends - reports its location from+ * the `path` field and its prose from `detail`, which carries none. The+ * human renderer appends ` (<path>)` from the issue's own field, so a+ * message that embedded the path as well named the file twice on every+ * parse-error line: prose carrying data the record already holds. An+ * untyped throw (a frontmatter read, a vocabulary guard owned by another+ * module) keeps its message verbatim against the walked path - that+ * message is not ours to shorten.+ *+ * What changed for a caller that prints `(exc as Error).message` bare,+ * stated exactly: a throw site whose message already carried the path+ * composes the same sentence as before, the status-folder mismatch+ * included (it supplies its own composition, keeping the location inside+ * the `(path=β¦, status=β¦, folder=β¦)` group). The four optional-field+ * helpers in `preference.ts` carried no location at all and now do -+ * a gain, and the only wording change in the set.+ */+function classifyParseError(+ err: unknown,+ path: string,+ kindPrefix: ParsedRecordKind,+ issues: DoctorIssue[],+): void {+ if (err instanceof BrainStatusFolderMismatchError) {+ issues.push({+ severity: "warning",+ code: "status-folder-mismatch",+ path: err.path,+ message: err.detail,+ });+ return;+ }+ const typed = err instanceof BrainParseError ? err : null;+ const msg = typed ? typed.detail : ((err as Error).message ?? String(err));+ issues.push({+ severity: "error",+ code: parseErrorCode(kindPrefix, msg),+ path: typed ? typed.path : path,+ message: msg,+ });+}++// ISO-8601 UTC: YYYY-MM-DDTHH:MM:SS(.fff)?Z. Lenient β we accept the+// shorter date-only form too (created_at is sometimes a date-only string+// in hand-authored signals).+const ISO_RE = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z)?$/;++function checkIso(path: string, field: string, value: string, issues: DoctorIssue[]): void {+ if (!ISO_RE.test(value)) {+ issues.push({+ severity: "error",+ code: ISO_INVALID_CODE,+ path,+ message: `field '${field}' is not a valid ISO-8601 timestamp: ${JSON.stringify(value)}`,+ });+ return;+ }+ // Confirm the calendar date is real (Date.parse accepts garbage on+ // some engines β but verifying via Date round-trip catches it).+ const ts = Date.parse(value);+ if (!Number.isFinite(ts)) {+ issues.push({+ severity: "error",+ code: ISO_INVALID_CODE,+ path,+ message: `field '${field}' could not be parsed as a date: ${JSON.stringify(value)}`,+ });+ }+}++function checkWikilinks(+ path: string,+ field: string,+ values: ReadonlyArray<string>,+ knownBasenames: ReadonlySet<string>,+ issues: DoctorIssue[],+): void {+ for (const raw of values) {+ if (!raw) continue;+ // Extract any wikilinks via the shared parser. A bare `[[target]]`+ // produces one match; an already-stripped basename produces zero,+ // in which case we treat the raw string itself as the candidate.+ const matches = extractWikilinks(raw);+ const candidates = matches.length > 0 ? matches : [raw];+ for (const candidate of candidates) {+ const target = normaliseWikilinkTarget(candidate);+ if (!target) continue;+ if (!knownBasenames.has(target)) {+ issues.push({+ severity: "warning",+ code: "broken-wikilink",+ path,+ // no-dead-ends, task 12: the field and the target ride as+ // fields as well as inside the sentence, so a consumer acts on+ // values rather than on a regex over prose. The message is+ // unchanged - the human surface still reads it.+ field,+ target,+ message: `field '${field}' references missing basename '${target}'`,+ });+ }+ }+ }+}diff --git a/src/core/brain/doctor/records.ts b/src/core/brain/doctor/records.tsnew file mode 100644index 00000000..1516b15d--- /dev/null+++ b/src/core/brain/doctor/records.ts@@ -0,0 +1,151 @@+/**+ * The pre-parsed views of the Brain store the checks read.+ *+ * 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/`.+ *+ * Each reader takes an optional sweep sink. WITH one - the doctor pass,+ * which resolves this context before any check runs and therefore before+ * anything can report - a directory it cannot read is named in the+ * uncertainty stream and the pass continues; without one, the failure+ * propagates to the caller exactly as it always has. There is no third+ * behaviour: nothing here turns an unread directory into an empty one.+ */++import { existsSync, readdirSync, type Dirent } from "node:fs";+import { join } from "node:path";++import { listLogDates, readLogDay } from "../log-jsonl.ts";+import { brainDirs } from "../paths.ts";+import { parsePreference } from "../preference.ts";+import {+ readSweptDir,+ reportSweptFailure,+ SWEEP_ORIGIN,+ type SweptPath,+} from "./unreadable-path.ts";++export interface PreferenceRecord {+ readonly path: string;+ readonly pref: import("../types.ts").BrainPreference;+}++export interface LogRecord {+ readonly date: string;+ readonly entries: ReadonlyArray<import("../log.ts").BrainLogEntry>;+}++/**+ * The entries of `dir`, or `null` when there are none to read.+ *+ * The `existsSync` gate lives only on the sink-less path, where "absent"+ * is the only fail-soft answer the caller ever had. With a sink the same+ * question is asked of the failure itself, because `existsSync` answers+ * false for a permission denial on a parent component as readily as for+ * a directory nobody created - and those are different findings.+ */+function listRecordDir(dir: string, swept: SweptPath | undefined): Dirent[] | null {+ if (swept !== undefined) return readSweptDir(dir, swept, SWEEP_ORIGIN.root);+ if (!existsSync(dir)) return null;+ return readdirSync(dir, { withFileTypes: true });+}++/**+ * Build a single pre-parsed snapshot of `Brain/preferences/` so the+ * three pref-walking lints don't each re-parse the directory.+ * Files that fail to parse are silently omitted β schema errors are+ * already reported by the preference record check.+ */+export function readAllPreferenceRecords(+ vault: string,+ swept?: SweptPath,+): ReadonlyArray<PreferenceRecord> {+ const dirs = brainDirs(vault);+ const entries = listRecordDir(dirs.preferences, swept);+ if (entries === null) return [];+ const out: PreferenceRecord[] = [];+ for (const entry of entries) {+ const name = entry.name;+ if (!name.endsWith(".md") || !name.startsWith("pref-")) continue;+ const path = join(dirs.preferences, name);+ try {+ out.push({ path, pref: parsePreference(path) });+ } catch {+ // schema error β reported by the preference 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.+ */+export function readAllLogRecords(vault: string, swept?: SweptPath): ReadonlyArray<LogRecord> {+ // Shard-aware (Memory Integrity Suite): dates come from the single+ // discovery helper and entries arrive merged across device shards.+ const out: LogRecord[] = [];+ for (const date of listLogDatesSwept(vault, swept)) {+ try {+ out.push({ date, entries: readLogDay(vault, date).entries });+ } catch {+ // parse error β surfaced separately by the log shard check+ }+ }+ return out;+}++/**+ * The dates the log directory holds. Discovery is behind a shared+ * helper, so a `Brain/log` that is a regular file arrives here as a+ * throw - which, resolved before any check runs, ended the whole pass+ * with no findings at all.+ */+function listLogDatesSwept(vault: string, swept: SweptPath | undefined): ReadonlyArray<string> {+ if (swept === undefined) return listLogDates(vault);+ try {+ return listLogDates(vault);+ } catch (err) {+ reportSweptFailure(+ brainDirs(vault).log,+ "log date discovery failed",+ err,+ swept,+ SWEEP_ORIGIN.root,+ );+ return [];+ }+}++/**+ * Build the universe of valid wikilink targets inside `Brain/`. The+ * doctor pass is scoped to Brain content; cross-layer wikilinks+ * pointing at user-authored notes outside Brain/ are out of scope+ * and stay accepted.+ *+ * Set is keyed by basename (without `.md`) so Obsidian's basename+ * match works.+ */+export function collectAllBasenames(vault: string, swept?: SweptPath): ReadonlySet<string> {+ const out = new Set<string>();+ const dirs = brainDirs(vault);+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ ]) {+ const entries = listRecordDir(d, swept);+ if (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));+ }+ }+ return out;+}diff --git a/src/core/brain/doctor/removed-tool-checks.ts b/src/core/brain/doctor/removed-tool-checks.tsnew file mode 100644index 00000000..c090501f--- /dev/null+++ b/src/core/brain/doctor/removed-tool-checks.ts@@ -0,0 +1,156 @@+/**+ * References to MCP tools removed in the 1.0.0 deprecation sweep.+ *+ * One reason to change: the removed-surface table. The scan exists so an+ * operator upgrading an old vault learns each migration from the doctor+ * output rather than from a tombstone error at call time.+ */++import { statSync } from "node:fs";+import { join, relative } from "node:path";++import { REMOVED_TOOLS } from "../../removed-surfaces.ts";+import { brainDirs } from "../paths.ts";+import type { DoctorCheck } from "./check.ts";+import {+ readSweptDir,+ readSweptFile,+ reportSweptFailure,+ reportSweptSkip,+ SWEEP_ORIGIN,+ type SweepOrigin,+ type SweptPath,+} from "./unreadable-path.ts";++/** Word-boundary regex per removed tool name, compiled once. */+const REMOVED_TOOL_PATTERNS: ReadonlyArray<{ name: string; pattern: RegExp }> = Object.freeze(+ Object.keys(REMOVED_TOOLS).map((name) => ({+ name,+ // \b treats `_` as a word character, so `my_brain_digestion` does+ // not match `brain_digest` but `call brain_digest.` does.+ pattern: new RegExp(`\\b${name}\\b`),+ })),+);++/** Hard cap so a pathological vault cannot flood the doctor report. */+const REMOVED_TOOL_MAX_WARNINGS = 50;++/** Subsystem name the scan reports an unreadable path under. */+const REMOVED_TOOL_SITE = "brain.doctor.removedToolReference";++/** Root instruction files the scan reads beside the Brain tree. */+const ROOT_INSTRUCTION_FILES: ReadonlyArray<string> = Object.freeze(["CLAUDE.md", "AGENTS.md"]);++/**+ * Scan vault-side text surfaces for references to MCP tools removed+ * in 1.0.0. Scope is exactly what the doctor can see locally:+ *+ * - every Markdown file under `Brain/` (recursive),+ * - root instruction files (`CLAUDE.md`, `AGENTS.md`),+ * - installed skills under `.claude/skills/` (recursive `.md`).+ *+ * One warning per file lists every removed name it mentions with the+ * replacement spelling, mirroring the server-side tombstone error.+ *+ * A directory it cannot list and a file it cannot open are reported as+ * uncertainty rather than skipped: an unscanned surface produces no+ * warning, which is the same output as a surface that mentions nothing+ * removed, and only one of those means the vault has no migration left+ * to do.+ */+export const removedToolReferenceCheck: DoctorCheck = {+ failSoft: true,+ run({ vault }, { issues, uncertain }) {+ const candidates: string[] = [];+ const dirs = brainDirs(vault);+ const swept: SweptPath = {+ site: REMOVED_TOOL_SITE,+ consequence:+ "it was not scanned for references to tools removed in 1.0.0, so any migration it " ++ "still needs is missing from this report",+ uncertain,+ };+ collectMarkdownFiles(dirs.brain, candidates, swept, SWEEP_ORIGIN.root);+ for (const name of ROOT_INSTRUCTION_FILES) {+ const p = join(vault, name);+ try {+ if (statSync(p).isFile()) candidates.push(p);+ } catch (err) {+ // One unreadable root file must not disable the whole scan - but+ // it is not the same answer as a vault that has no CLAUDE.md.+ reportSweptFailure(p, "instruction file stat failed", err, swept, SWEEP_ORIGIN.root);+ }+ }+ collectMarkdownFiles(join(vault, ".claude", "skills"), candidates, swept, SWEEP_ORIGIN.root);++ let emitted = 0;+ for (const path of candidates) {+ if (emitted >= REMOVED_TOOL_MAX_WARNINGS) return;+ // Every candidate was listed by the walk a moment ago, so an+ // ENOENT here is a file that vanished under it.+ const body = readSweptFile(path, swept, SWEEP_ORIGIN.discovered);+ if (body === null) continue;+ const hits: string[] = [];+ for (const { name, pattern } of REMOVED_TOOL_PATTERNS) {+ if (pattern.test(body)) hits.push(name);+ }+ if (hits.length === 0) continue;+ const replacements = hits+ .map((name) => {+ const record = REMOVED_TOOLS[name]!;+ return `${name} -> ${record.target} view="${record.view}"`;+ })+ .join("; ");+ issues.push({+ severity: "warning",+ code: "removed-tool-reference",+ message:+ `${relative(vault, path)} references tool(s) removed in 1.0.0: ` ++ `${replacements} (see docs/updating.md)`,+ });+ emitted += 1;+ }+ },+};++/**+ * Recursive `.md` collection; an unreadable directory is reported, not+ * dropped. No `existsSync` gate stands in front of the listing: that+ * call returns false for a permission denial on a PARENT component+ * exactly as it does for an absent directory, so it answered the+ * absent-or-unreadable question the sweep is here to ask - and answered+ * it wrong for the vault whose `.claude/` an operator locked down.+ *+ * An entry that is neither a regular file nor a directory - a symlink,+ * which `Dirent` reports as neither - is named rather than skipped. The+ * link is deliberately not followed (the store's rule: a reader that+ * follows a link has already left it), so its Markdown is content this+ * scan did not read, which is what the uncertainty stream is for.+ */+function collectMarkdownFiles(+ dir: string,+ out: string[],+ swept: SweptPath,+ origin: SweepOrigin,+): void {+ const entries = readSweptDir(dir, swept, origin);+ if (entries === null) return;+ for (const entry of entries) {+ const p = join(dir, entry.name);+ if (entry.isDirectory()) {+ collectMarkdownFiles(p, out, swept, SWEEP_ORIGIN.discovered);+ continue;+ }+ if (entry.isFile()) {+ if (entry.name.endsWith(".md")) out.push(p);+ continue;+ }+ reportSweptSkip(+ p,+ entry.isSymbolicLink()+ ? "entry is a symbolic link, which no sweep follows out of the store"+ : "entry is neither a regular file nor a directory",+ swept,+ );+ }+}diff --git a/src/core/brain/doctor/report.ts b/src/core/brain/doctor/report.tsnew file mode 100644index 00000000..14d33b7a--- /dev/null+++ b/src/core/brain/doctor/report.ts@@ -0,0 +1,106 @@+/**+ * The public result shapes of the Brain doctor pass.+ *+ * A leaf: the checks push into these streams and the assembler in+ * `doctor.ts` composes the result out of them, so neither can own the+ * shapes without the other importing it back.+ */++import type { SemanticHealthReport } from "../health/reconcile.ts";+import type { DoctorIssue, InstructionFileCeilingWarning, TrustVerdict } from "../types.ts";++export interface RunDoctorOptions {+ /**+ * Reserved for future per-check toggles. Today the doctor reports+ * every check it knows; CLI `--strict` only changes the exit code,+ * not the contents of the report.+ */+ readonly strict?: boolean;+ /**+ * Wall clock used by age-based lints (`low-evidence-confirmed`,+ * `pinned-without-recent-evidence`). Defaults to `new Date()`.+ * Tests pin this for determinism.+ */+ readonly now?: Date;+ /**+ * Search-index path for index-backed checks+ * (write-time-integrity-governance: staged tier-drift findings).+ * Fail-soft: a missing index or pre-v6 schema simply skips them.+ */+ readonly dbPath?: string;+ /**+ * Optional precomputed dream summary (v0.10.16). When supplied,+ * the doctor runs the verification-delta helper and folds the+ * counts into the trust verdict. When omitted, verification+ * defaults to all-zero counts and the trust verdict is computed+ * against doctor signals alone.+ */+ readonly dreamSummary?: import("../dream.ts").DreamRunSummary;+ /**+ * Optional resolved guardrail config (v0.10.16). When omitted,+ * `BRAIN_GUARDRAIL_DEFAULTS` are used. Drives the+ * instruction-file-ceiling check.+ */+ readonly guardrails?: import("../types.ts").ResolvedBrainGuardrailConfig;+}++/**+ * Compact counts attached to a `RunDoctorResult` so callers can render+ * a one-line "verification delta: X drift, Y regression, Z missing"+ * summary without re-walking the vault. Full per-entry detail lives+ * on the trust-layer `operator_summary` composer.+ */+export interface VerificationDeltaSummary {+ readonly confirmed: number;+ readonly drift: number;+ readonly regression: number;+ readonly missing_evidence: number;+}++/**+ * Per-check uncertainty entry. Distinct from `warnings` / `errors`:+ * these are sub-operations the doctor attempted but cannot claim+ * completed cleanly (e.g. an instruction-file the doctor could not+ * read, a verification step that timed out). Empty on every clean+ * run. v0.10.16 extension point.+ */+export interface DoctorUncertainEntry {+ readonly code: string;+ readonly path?: string;+ readonly message: string;+}++export interface RunDoctorResult {+ readonly warnings: ReadonlyArray<DoctorIssue>;+ readonly errors: ReadonlyArray<DoctorIssue>;+ /**+ * Aggregate trust verdict (v0.10.16). Absent when the trust helper+ * was not invoked; consumers of `runDoctor` that only need the+ * legacy warning / error stream can ignore the field.+ */+ readonly trust_verdict?: TrustVerdict;+ /**+ * Counts of verification-delta states for the most recent dream+ * cycle. Absent when verification did not run.+ */+ readonly verification_delta_summary?: VerificationDeltaSummary;+ /**+ * Warnings emitted by the instruction-file-ceiling helper. Empty+ * when the helper did not run or no tracked file exceeded the+ * configured ceiling.+ */+ readonly instruction_file_warnings?: ReadonlyArray<InstructionFileCeilingWarning>;+ /**+ * Sub-operations the doctor attempted but could not fully verify.+ * Empty on every clean run; populated when an uncertainty-surfacing+ * helper is invoked.+ */+ readonly uncertain?: ReadonlyArray<DoctorUncertainEntry>;+ /**+ * Semantic-health report (v0.14.0): contradiction / concept-gap /+ * stale-claim findings plus an escalating verdict. Absent only when+ * the vault has no Brain layer; otherwise present even on a clean+ * run (with empty domains and a `clean` verdict).+ */+ readonly semantic_health?: SemanticHealthReport;+}diff --git a/src/core/brain/doctor/semantic-health-check.ts b/src/core/brain/doctor/semantic-health-check.tsnew file mode 100644index 00000000..e4745ec1--- /dev/null+++ b/src/core/brain/doctor/semantic-health-check.ts@@ -0,0 +1,179 @@+/**+ * Semantic health (v0.14.0): what the rule set MEANS, rather than+ * whether it parses.+ *+ * Contradictions, uncovered recurring concepts, claims nothing has+ * re-confirmed, and batches confirmed together without dedup. The+ * detectors live in `health/reconcile.ts`; this module supplies them+ * their corpus and turns their findings into doctor warnings.+ */++import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import {+ reconcileSemanticHealth,+ type PreferenceForHealth,+ type SemanticHealthReport,+} from "../health/reconcile.ts";+import { brainDirs } from "../paths.ts";+import { BRAIN_HEALTH_DEFAULTS, loadBrainConfigDetailed, resolveHealth } from "../policy.ts";+import { parseSignal } from "../signal.ts";+import type { DoctorIssue, ResolvedBrainHealthConfig } from "../types.ts";+import { readAllPreferenceRecords, type PreferenceRecord } from "./records.ts";++/**+ * Compute only the semantic-health report, skipping the structural+ * doctor sweep. `runDoctor` attaches the identical report via its inline+ * pass; a caller that needs nothing but the semantic findings (e.g.+ * vault vitals reading `conceptGaps` for gap pressure) can call this+ * directly instead of paying for the full config / signals / backlinks /+ * logs / entities sweep. Both paths route through the same+ * {@link checkSemanticHealth} detector over the same inputs+ * ({@link readAllPreferenceRecords}, `resolveHealth(cfg)` or the+ * defaults, and `now`), so the findings are byte-for-byte identical.+ *+ * Best-effort and never throws: returns `undefined` only when the pass+ * itself throws, mirroring `runDoctor`'s attach-on-success contract. Any+ * lint issues the pass would emit into the doctor stream are discarded+ * here, which is exactly what a report-only caller wants.+ */+export function computeSemanticHealth(+ vault: string,+ opts: { readonly now?: Date } = {},+): SemanticHealthReport | undefined {+ const now = opts.now ?? new Date();+ let cfg;+ try {+ cfg = loadBrainConfigDetailed(vault).config;+ } catch {+ cfg = undefined;+ }+ try {+ const prefRecords = readAllPreferenceRecords(vault);+ const health = cfg ? resolveHealth(cfg) : BRAIN_HEALTH_DEFAULTS;+ return checkSemanticHealth(vault, prefRecords, [], health, now);+ } catch {+ return undefined;+ }+}++/** Minimal signal projection the semantic-health pass needs. */+interface SignalSignRecord {+ readonly id: string;+ readonly sign: import("../types.ts").BrainSignalSign;+ readonly principle: string;+ readonly created_at: string;+}++/**+ * Read every `sig-*.md` across `inbox/` and `processed/`, projecting+ * each to its id, sign, and principle. Files that fail to parse are+ * skipped (their schema errors surface through the signal record check).+ */+function readAllSignalRecords(vault: string): ReadonlyArray<SignalSignRecord> {+ const dirs = brainDirs(vault);+ const out: SignalSignRecord[] = [];+ for (const dir of [dirs.inbox, dirs.processed]) {+ if (!existsSync(dir)) continue;+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".md") || !name.startsWith("sig-")) continue;+ try {+ const sig = parseSignal(join(dir, name));+ out.push({+ id: sig.id,+ sign: sig.signal,+ principle: sig.principle,+ created_at: sig.created_at,+ });+ } catch {+ // schema error - reported by the signal record check+ }+ }+ }+ return out;+}++/**+ * Run the semantic-health detectors, merge their findings into the+ * shared `issues` array as warnings, and return the structured report.+ * Confirmed preferences feed the contradiction and stale-claim passes;+ * signal + preference principles feed the concept-gap pass.+ */+export function checkSemanticHealth(+ vault: string,+ prefRecords: ReadonlyArray<PreferenceRecord>,+ issues: DoctorIssue[],+ health: ResolvedBrainHealthConfig,+ now: Date,+): SemanticHealthReport {+ const signals = readAllSignalRecords(vault);+ const signSignById = new Map(signals.map((s) => [s.id, s.sign]));+ const preferences: PreferenceForHealth[] = prefRecords.map(({ pref }) => pref);+ const corpusPrinciples = [+ ...signals.map((s) => s.principle),+ ...prefRecords.map((r) => r.pref.principle),+ ];+ // Aligned index-for-index with corpusPrinciples: the authored date of+ // each entry, so the baseline watermark can tell a concept gap that is+ // entirely old from one still mentioned in fresh memory.+ const corpusPrincipleDates: (string | null)[] = [+ ...signals.map((s) => s.created_at),+ ...prefRecords.map((r) => r.pref.created_at),+ ];+ const coveredTopics = prefRecords.map((r) => r.pref.topic);++ const report = reconcileSemanticHealth(+ { preferences, signSignById, corpusPrinciples, corpusPrincipleDates, coveredTopics },+ {+ contradictionJaccard: health.contradiction_jaccard,+ conceptGapMinFrequency: health.concept_gap_min_frequency,+ staleClaimMaxAgeDays: health.stale_claim_max_age_days,+ ...(health.silence_before !== null ? { silenceBefore: health.silence_before } : {}),+ now,+ },+ );++ for (const c of report.contradictions) {+ issues.push({+ severity: "warning",+ code: "contradictory-preferences",+ message:+ `[[${c.aId}]] (${c.aSign}) and [[${c.bId}]] (${c.bSign})` ++ `${c.scope ? ` in scope '${c.scope}'` : ""}` ++ ` look like contradictions (jaccard ${c.jaccard.toFixed(2)} of principle tokens,` ++ " opposite sign of record). Reconcile or retire one.",+ });+ }+ for (const g of report.conceptGaps) {+ issues.push({+ severity: "warning",+ code: "concept-gap",+ message:+ `term '${g.term}' recurs across ${g.frequency} entries but no preference topic covers it.` ++ " Consider capturing a dedicated preference.",+ });+ }+ for (const s of report.staleClaims) {+ issues.push({+ severity: "warning",+ code: "stale-claim",+ message:+ `[[${s.id}]] last saw evidence ${s.ageDays} days ago (${s.lastEvidenceAt}).` ++ " Re-confirm or retire it.",+ });+ }+ for (const b of report.batchInflation) {+ issues.push({+ severity: "warning",+ code: "batch-concept-inflation",+ message:+ `${b.count} preferences confirmed within one window (${b.windowStart} to ${b.windowEnd}): ` ++ `${b.ids.map((id) => `[[${id}]]`).join(", ")} across topics ${b.topics.join(", ")}. ` ++ "A batch this size confirmed together usually means dedup/consolidation was skipped - " ++ "review for near-duplicates or preferences that should merge before the next dream pass.",+ });+ }++ return report;+}diff --git a/src/core/brain/doctor/store-integrity.ts b/src/core/brain/doctor/store-integrity.tsnew file mode 100644index 00000000..5daa5d8a--- /dev/null+++ b/src/core/brain/doctor/store-integrity.ts@@ -0,0 +1,182 @@+/**+ * The state of the store as a set of files, independent of what any+ * record says.+ *+ * A symlink that leaves the vault, a sync-conflict copy no writer made,+ * a workrun that never reached a terminal phase, an identity field+ * hand-edited into the index: none of these is a schema violation, and+ * all of them are conditions only a walk of the tree can see.+ */++import { join } from "node:path";++import { realpathInsideVault, vaultRelative } from "../../path-safety.ts";+import { scanDanglingWorkruns } from "../dream-workrun.ts";+import { readTierDriftCount } from "../frontmatter-tiers.ts";+import { listLogSyncConflicts } from "../log-jsonl.ts";+import { brainDirs } from "../paths.ts";+import type { DoctorCheck } from "./check.ts";+import type { DoctorUncertainEntry } from "./report.ts";+import {+ readSweptDir,+ reportSweptFailure,+ SWEEP_ORIGIN,+ type SweepOrigin,+} from "./unreadable-path.ts";++/**+ * Tier guard (write-time-integrity-governance): staged identity+ * hand-edits the index post-pass detected. Fail-soft index read - a+ * missing index or pre-v6 schema simply skips the check.+ */+export const tierDriftCheck: DoctorCheck = {+ failSoft: false,+ run({ dbPath }, { issues }) {+ if (dbPath === undefined) return;+ const driftCount = readTierDriftCount(dbPath);+ if (driftCount > 0) {+ issues.push({+ severity: "warning",+ code: "tier-drift",+ message:+ `${driftCount} identity-field hand-edit(s) staged - ` ++ "review with: o2b brain tiers check",+ });+ }+ },+};++/**+ * `dangling-workrun` (v0.12.0, Brain Integrity Suite): surfaces every+ * dream-pass workrun JSONL whose last event is neither `finalized`+ * nor `interrupted`. A non-empty result means at least one previous+ * dream invocation died before it could declare a terminal phase,+ * usually because the host process was killed mid-run. The next+ * dream pass starts fresh - this check is purely observational so+ * the operator notices the failed run.+ */+export const danglingWorkrunCheck: DoctorCheck = {+ failSoft: true,+ run({ vault }, { issues }) {+ for (const path of scanDanglingWorkruns(vault)) {+ issues.push({+ severity: "warning",+ code: "dangling-workrun",+ path,+ message:+ `dream-pass workrun did not reach a terminal phase: ${path}. ` ++ "A previous dream run was likely killed mid-execution; " ++ "subsequent dream invocations will continue normally.",+ });+ }+ },+};++/**+ * Memory Integrity Suite: leftover Syncthing conflict copies under+ * Brain/log/. The per-device shard layout prevents new ones; old+ * copies need a manual union+dedup merge into the day's log.+ */+export const syncConflictLogCheck: DoctorCheck = {+ failSoft: true,+ run({ vault }, { issues, uncertain }) {+ const conflicts = listSyncConflicts(vault, uncertain);+ for (const path of conflicts) {+ issues.push({+ severity: "warning",+ code: "sync-conflict-log",+ path,+ message:+ `Syncthing sync-conflict copy under Brain/log/: ${path}. ` ++ "Merge its rows into the day's log (union + dedup by ts and content), then delete it.",+ });+ }+ },+};++/** Subsystem name the sync-conflict listing reports an unreadable path under. */+const SYNC_CONFLICT_SITE = "brain.doctor.syncConflictLog";++/**+ * The conflict copies under `Brain/log/`, or none plus a named reason.+ *+ * The listing is behind a shared helper, so the failure arrives here as+ * a throw. Swallowed by the pass's fail-soft arm it produced no finding+ * at all, which reads as "no conflict copies" - the answer this check+ * exists to distinguish from "the directory was not read".+ */+function listSyncConflicts(vault: string, uncertain: DoctorUncertainEntry[]): string[] {+ try {+ return listLogSyncConflicts(vault);+ } catch (err) {+ reportSweptFailure(+ brainDirs(vault).log,+ "sync-conflict listing failed",+ err,+ {+ site: SYNC_CONFLICT_SITE,+ consequence:+ "it was not listed for Syncthing conflict copies, so a leftover copy waiting to be " ++ "merged is missing from this report",+ uncertain,+ },+ SWEEP_ORIGIN.root,+ );+ return [];+ }+}++/** Subsystem name the symlink walk reports an unreadable path under. */+const SYMLINK_ESCAPE_SITE = "brain.doctor.symlinkEscape";++/**+ * Store hardening (D2): a symlink inside Brain/ whose realpath resolves+ * OUTSIDE the vault root is an exfiltration/clobber hazard. Lint only -+ * never auto-fixed, because removing an operator-created link is a+ * judgment call.+ *+ * Reuses {@link realpathInsideVault} (the same two-step check+ * `ensureInsideVault` performs) so a symlink pointing at an in-vault+ * target never flags. Directory symlinks are reported but NOT descended+ * into - following them would leave the vault.+ *+ * A subtree the walk cannot list is reported as uncertainty rather than+ * skipped in silence: "no escaping symlink found" and "no symlink+ * examined" are the same empty result, and only one of them means the+ * store is safe to read.+ */+export const symlinkEscapeCheck: DoctorCheck = {+ failSoft: true,+ run({ vault }, { issues, uncertain }) {+ const root = brainDirs(vault).brain;+ const swept = {+ site: SYMLINK_ESCAPE_SITE,+ consequence:+ "no symlink under it was examined, so this subtree is not certified free of links " ++ "resolving outside the vault root",+ uncertain,+ };+ const visit = (dir: string, origin: SweepOrigin): void => {+ const entries = readSweptDir(dir, swept, origin);+ if (entries === null) return;+ for (const entry of entries) {+ const full = join(dir, entry.name);+ if (entry.isSymbolicLink()) {+ if (!realpathInsideVault(full, vault)) {+ issues.push({+ severity: "error",+ code: "symlink-escape",+ path: vaultRelative(full, vault),+ message:+ `symlink '${vaultRelative(full, vault)}' resolves outside the vault root. ` ++ "A reader following it leaves the vault; remove or repoint the link.",+ });+ }+ continue; // never descend through a symlink+ }+ if (entry.isDirectory()) visit(full, SWEEP_ORIGIN.discovered);+ }+ };+ visit(root, SWEEP_ORIGIN.root);+ },+};diff --git a/src/core/brain/doctor/uncertain-stream.ts b/src/core/brain/doctor/uncertain-stream.tsnew file mode 100644index 00000000..d970d766--- /dev/null+++ b/src/core/brain/doctor/uncertain-stream.ts@@ -0,0 +1,77 @@+/**+ * The doctor's uncertainty stream, as a stream rather than as an array+ * every check appends to.+ *+ * Several checks walk overlapping trees, so one unreadable directory is+ * observed by four of them - the symlink walk, the removed-tool scan,+ * the basename sweep and the frontmatter probe all descend through+ * `Brain/`. Appended raw, that is four entries carrying the same code+ * and the same path, differing only in the clause each sweep writes+ * about what it could therefore not claim. On a vault synced with+ * preserved ownership - a shape this project designs for - the operator+ * reads four identical lines per affected subtree, and the same array+ * reaches the MCP payload with nothing bounding it.+ *+ * Two rules, both applied here rather than at any call site:+ *+ * - ONE entry per (code, path). The pair identifies the observation;+ * the clauses are four readings of it, and they are MERGED onto the+ * one entry. Keeping only one of them - the first, or the longest -+ * would drop the questions the other sweeps left unanswered, which+ * is the entire content of an uncertainty finding.+ * - A CAP per code, following the removed-tool scan's convention. Per+ * code rather than over the whole stream, so a tree the walk cannot+ * enter cannot crowd out the lineage, marker and lock findings -+ * the ones an operator cannot rediscover by looking at the+ * filesystem.+ */++import type { DoctorUncertainEntry } from "./report.ts";++/**+ * Hard cap per code, matching `REMOVED_TOOL_MAX_WARNINGS`: past fifty+ * instances of one condition the operator is reading the same sentence,+ * and the remaining budget is better spent on the other conditions.+ */+export const UNCERTAIN_MAX_PER_CODE = 50;++/**+ * Between the observation and what it cost, and between two such costs.+ * A semicolon rather than a full stop because every clause is about the+ * same failure, and the operator reads them as one `[UNSURE]` line.+ */+export const CLAUSE_SEP = "; ";++/**+ * Record one uncertainty about (code, path), and return the message the+ * stream now holds for it.+ *+ * `clause` is what the reporting sweep can no longer claim. Omitted -+ * the probes that forward a notice whose detail is already complete -+ * the entry stands on its own detail. A clause the entry already+ * carries is not repeated: two sweeps can share one consequence.+ */+export function pushUncertain(+ uncertain: DoctorUncertainEntry[],+ entry: DoctorUncertainEntry,+ clause?: string,+): string {+ const at = uncertain.findIndex((e) => e.code === entry.code && e.path === entry.path);+ if (at < 0) {+ const message = clause === undefined ? entry.message : `${entry.message}${CLAUSE_SEP}${clause}`;+ if (countFor(uncertain, entry.code) >= UNCERTAIN_MAX_PER_CODE) return message;+ uncertain.push({ ...entry, message });+ return message;+ }+ const held = uncertain[at]!;+ if (clause === undefined || held.message.includes(clause)) return held.message;+ const message = `${held.message}${CLAUSE_SEP}${clause}`;+ uncertain[at] = { ...held, message };+ return message;+}++function countFor(uncertain: ReadonlyArray<DoctorUncertainEntry>, code: string): number {+ let n = 0;+ for (const entry of uncertain) if (entry.code === code) n += 1;+ return n;+}diff --git a/src/core/brain/doctor/uncertainty-probes.ts b/src/core/brain/doctor/uncertainty-probes.tsnew file mode 100644index 00000000..19685e63--- /dev/null+++ b/src/core/brain/doctor/uncertainty-probes.ts@@ -0,0 +1,149 @@+/**+ * What the doctor attempted but cannot claim it verified.+ *+ * These four write into the `uncertain` stream rather than into+ * warnings or errors, and for one shared reason: each names a place+ * where the doctor's own reading of the store may be incomplete. A+ * frontmatter line the scanner dropped, a ledger that no longer hashes+ * to what was written, a root with no identity marker, a lock whose+ * owner cannot be established - none is a defect in the data, and every+ * one of them makes a clean report mean less than it says.+ */++import { existsSync } from "node:fs";++import type { DegradationNotice } from "../../integrity/degradation.ts";+import { listVaultPages } from "../../vault.ts";+import { verifyLineageLedger } from "../lineage/verify.ts";+import { brainDirs } from "../paths.ts";+import { scanStaleLocks } from "../sync-lockfile.ts";+import { vaultMarkerAbsentNotice } from "../vault-identity.ts";+import type { DoctorCheck } from "./check.ts";+import { pushUncertain } from "./uncertain-stream.ts";++/** Site recorded on the notices the doctor's Brain-tree sweep collects. */+const DOCTOR_FRONTMATTER_SITE = "brain.doctor";++/**+ * Sweep every Markdown file under `Brain/` for frontmatter the line+ * scanner could not express, and fold each notice into the doctor's+ * `uncertain` stream.+ *+ * Unit F: reported as UNCERTAINTY, not as a warning or an error: the+ * note is still on disk and still indexes, but the doctor cannot claim+ * it verified every field it declared, because a field it could not read+ * is indistinguishable from a field that is absent. (That ambiguity is+ * exactly what produced the spurious `missing field: tags` errors fixed+ * in 426d06f8.)+ *+ * One walk, through the same shared helper every other converted site+ * uses ({@link listVaultPages} with its opt-in notice sink), so there is+ * no second definition of "what counts as a dropped line".+ *+ * Unlike an index run - which reads only the files whose mtime or size+ * moved - this sweep is unconditional, which is what makes the doctor+ * the complete view of the condition.+ */+export const frontmatterUncertaintyProbe: DoctorCheck = {+ failSoft: true,+ run({ vault }, { uncertain }) {+ const dirs = brainDirs(vault);+ if (!existsSync(dirs.brain)) return;+ const notices: DegradationNotice[] = [];+ listVaultPages(dirs.brain, { notices, site: DOCTOR_FRONTMATTER_SITE });+ for (const notice of notices) {+ // Through the shared stream, not straight onto the array: this+ // walk covers the same Brain/ subtrees the hand-written sweeps do,+ // so an unreadable directory is observed here AND by each of them.+ pushUncertain(uncertain, {+ code: notice.code,+ ...(notice.path !== undefined ? { path: notice.path } : {}),+ message: notice.detail,+ });+ }+ },+};++/**+ * Fold every session-lineage ledger finding into the doctor's+ * `uncertain` stream: a line edited after it was written, a line removed+ * from the middle, or an observation the writer could not append.+ *+ * Unit D: uncertainty rather than an error because continuity still+ * resolves from this ledger, but the doctor cannot claim the history it+ * read is the history that was written. The verifier is read-only and+ * never throws, so this needs no guard of its own beyond the pass's+ * blanket one.+ */+export const lineageLedgerProbe: DoctorCheck = {+ failSoft: true,+ run({ vault }, { uncertain }) {+ const report = verifyLineageLedger(vault);+ for (const notice of report.notices) {+ pushUncertain(uncertain, {+ code: notice.code,+ path: notice.path ?? report.path,+ message: notice.detail,+ });+ }+ },+};++/**+ * Report a resolved root that carries no vault identity marker.+ *+ * Unit J: an absent marker cannot tell an old vault from a wrong one, so+ * it is uncertainty rather than a warning - but it is the exact shape a+ * mis-resolved root takes, and the doctor reporting such a root clean is+ * what let one pass the single command an operator runs to check the+ * store.+ *+ * The producer is pure, throws nothing, and treats a corrupt marker as+ * absent - the same collapse `readVaultIdentity` performs, because a+ * truncated sync must not be reported as a wrong vault.+ */+export const vaultMarkerProbe: DoctorCheck = {+ failSoft: true,+ run({ vault }, { uncertain }) {+ const notice = vaultMarkerAbsentNotice(vault);+ if (notice === null) return;+ pushUncertain(uncertain, {+ code: notice.code,+ ...(notice.path !== undefined ? { path: notice.path } : {}),+ message: notice.detail,+ });+ },+};++/** Code for a `.lock` file the doctor found under the Brain tree. */+const STALE_LOCK_CODE = "stale-lock";++/**+ * Report every `.lock` file under `Brain/`.+ *+ * Deliberately NOT age-filtered and deliberately not removed. The lock+ * primitive is a single-attempt exclusive create with no breaker, by+ * design: no timeout can distinguish a crashed writer from a slow live+ * one, and killing a live writer's lock corrupts what it protects. So+ * this reports the condition and leaves the judgment to the operator -+ * which is the whole reason a lock a crash left behind must be nameable+ * at all. A lock held by a healthy concurrent writer shows up here too,+ * and is uncertainty rather than a warning for exactly that reason.+ */+export const staleLockProbe: DoctorCheck = {+ failSoft: true,+ run({ vault }, { uncertain }) {+ const dirs = brainDirs(vault);+ if (!existsSync(dirs.brain)) return;+ for (const lockPath of scanStaleLocks(dirs.brain)) {+ pushUncertain(uncertain, {+ code: STALE_LOCK_CODE,+ path: lockPath,+ message:+ "a writer lock is present; while it is held every write it guards is refused. " ++ "If no process owns it (a crash leaves one behind) remove the file by hand - " ++ "nothing breaks it automatically, because a live writer cannot be told from a dead one",+ });+ }+ },+};diff --git a/src/core/brain/doctor/unreadable-path.ts b/src/core/brain/doctor/unreadable-path.tsnew file mode 100644index 00000000..7bd33b14--- /dev/null+++ b/src/core/brain/doctor/unreadable-path.ts@@ -0,0 +1,211 @@+/**+ * A path one of the doctor's own sweeps could not read.+ *+ * The sweeps that walk the store by hand each used to swallow a failed+ * read in a bare `catch` and return. That produces no findings, and no+ * findings is what every surface renders as a clean bill of health - so+ * the operator was told the vault was fine exactly where the doctor had+ * been unable to look. This module is the one place that answer is+ * replaced: the read still fails soft, and the branch is named in the+ * `uncertain` stream instead of vanishing.+ *+ * One distinction is drawn here rather than at each call site, because+ * getting it wrong in either direction is a defect. A path that is+ * ABSENT was never a subtree to sweep - the common case is a vault whose+ * optional directory has not been created, and it stays as quiet as it+ * always was. Every other failure - a permission denial, a file standing+ * where a directory was expected, an I/O error - is a subtree that+ * exists and was not read, which is precisely what uncertainty means.+ *+ * That reading of `ENOENT` holds only where absence was POSSIBLE, which+ * is why every read here declares where its path came from. At a sweep's+ * own root, absence is the ordinary case. A path the walk DISCOVERED+ * existed a moment earlier, when its parent listed it, so an `ENOENT` on+ * it is a race - something removed the entry under the walk - and a+ * subtree that was skipped like any other.+ *+ * The code is `vault-walk-entry-skipped` from the closed+ * {@link DEGRADATION_CODE} vocabulary, which already names this exact+ * condition for the shared vault walker. It is SPELLED here rather than+ * referenced through the constant so the doctor's exit census can read+ * the doctor's own code population out of its source; the two cannot+ * drift, because {@link degradationNotice} takes the closed union and a+ * spelling the vocabulary does not hold fails the build.+ */++import { readdirSync, readFileSync, type Dirent } from "node:fs";++import { degradationNotice, type DegradationNotice } from "../../integrity/degradation.ts";+import type { DoctorIssue } from "../types.ts";+import type { DoctorUncertainEntry } from "./report.ts";+import { pushUncertain } from "./uncertain-stream.ts";++/** See the module docblock: spelled, and pinned to the vocabulary by its type. */+const VAULT_WALK_ENTRY_SKIPPED_CODE = "vault-walk-entry-skipped";++/**+ * What a sweep reports under, and what it consequently cannot claim.+ *+ * `consequence` is written by the sweep because only the sweep knows+ * which question went unanswered: the operator reads it directly under+ * `[UNSURE]`, and "a directory could not be read" on its own does not+ * say what was therefore left unverified.+ */+export interface SweptPath {+ /** Subsystem name recorded on the notice, e.g. `brain.doctor.symlinkEscape`. */+ readonly site: string;+ /** What this sweep can no longer claim, as one clause. */+ readonly consequence: string;+ /** The doctor's uncertainty stream for the running pass. */+ readonly uncertain: DoctorUncertainEntry[];+}++/**+ * Where the path a read failed on came from, which is what decides+ * whether `ENOENT` means "nothing was ever here" or "it went away under+ * the walk". See the module docblock.+ */+export const SWEEP_ORIGIN = Object.freeze({+ root: "root",+ discovered: "discovered",+} as const);++export type SweepOrigin = (typeof SWEEP_ORIGIN)[keyof typeof SWEEP_ORIGIN];++/** `errno` values meaning nothing is there - not a failure to verify. */+const ABSENT_ERRNO: ReadonlySet<string> = new Set(["ENOENT"]);++/**+ * List `dir`, or report why it could not be listed and return `null`.+ * The caller's control flow is unchanged: `null` means "skip this+ * subtree", exactly as the bare `catch { return; }` it replaces did.+ */+export function readSweptDir(dir: string, swept: SweptPath, origin: SweepOrigin): Dirent[] | null {+ try {+ return readdirSync(dir, { withFileTypes: true });+ } catch (err) {+ return reportSweptFailure(dir, "directory listing failed", err, swept, origin);+ }+}++/** Read `path` as UTF-8, or report why it could not be read. */+export function readSweptFile(path: string, swept: SweptPath, origin: SweepOrigin): string | null {+ try {+ return readFileSync(path, "utf8");+ } catch (err) {+ return reportSweptFailure(path, "file read failed", err, swept, origin);+ }+}++/**+ * Report a read this module did not itself perform - a listing behind a+ * shared helper, a discovery pass that throws its own error - under the+ * same code and the same absent/failed split. `action` names what was+ * attempted; the errno text and the sweep's consequence are appended.+ *+ * Always returns `null` so a caller can `return reportSweptFailure(...)`+ * from the branch that skips the subtree.+ */+export function reportSweptFailure(+ path: string,+ action: string,+ err: unknown,+ swept: SweptPath,+ origin: SweepOrigin,+): null {+ if (origin === SWEEP_ORIGIN.root && isAbsent(err)) return null;+ reportSweptSkip(path, `${action}: ${describe(err)}`, swept);+ return null;+}++/**+ * Report a path the sweep declined to read for a reason that is not an+ * error - an entry that is neither a regular file nor a directory, so+ * neither branch of the walk consumes it. Skipping it silently is the+ * same false clean bill of health as swallowing a failed read.+ *+ * Returns the composed sentence, for the one caller that must carry the+ * same statement on a warning as well; the walks ignore it.+ */+export function reportSweptSkip(path: string, detail: string, swept: SweptPath): string {+ const notice = degradationNotice({+ code: VAULT_WALK_ENTRY_SKIPPED_CODE,+ site: swept.site,+ path,+ detail,+ });+ return pushUncertain(+ swept.uncertain,+ {+ code: notice.code,+ ...(notice.path !== undefined ? { path: notice.path } : {}),+ message: notice.detail,+ },+ swept.consequence,+ );+}++/**+ * The same condition as a reportable issue, for a path whose failure+ * stops a whole pass rather than one subtree. Built here so the code is+ * written down once, beside the vocabulary member it is pinned to.+ */+export function sweptPathWarning(path: string, message: string): DoctorIssue {+ return { severity: "warning", code: VAULT_WALK_ENTRY_SKIPPED_CODE, path, message };+}++/**+ * Fold notices a shared walker collected into the same stream, under the+ * same consequence. Used where the sweep does not perform the read+ * itself and the walker reports through the degradation channel.+ */+export function forwardSweepNotices(+ notices: ReadonlyArray<DegradationNotice>,+ swept: SweptPath,+): void {+ for (const notice of notices) {+ pushUncertain(+ swept.uncertain,+ {+ code: notice.code,+ ...(notice.path !== undefined ? { path: notice.path } : {}),+ message: notice.detail,+ },+ swept.consequence,+ );+ }+}++/**+ * Why a path could not be reached, or `null` when the failure means it+ * is not there at all.+ *+ * The same split {@link readSweptDir} applies, exposed for the one+ * caller that must act on the answer rather than report it: the pass+ * entry point, which reports an ABSENT Brain layer as an un-initialized+ * vault and must never say that about one it merely could not read.+ */+export function sweptFailureReason(err: unknown): string | null {+ return isAbsent(err) ? null : describe(err);+}++/**+ * The path an `errno` failure names, or `fallback` when it names none.+ * A shared builder reports the exact directory it stumbled on inside the+ * error, and that is a better answer than the root the caller handed it.+ */+export function sweptFailurePath(err: unknown, fallback: string): string {+ if (typeof err !== "object" || err === null) return fallback;+ const path = (err as { path?: unknown }).path;+ return typeof path === "string" && path.length > 0 ? path : fallback;+}++function isAbsent(err: unknown): boolean {+ if (typeof err !== "object" || err === null) return false;+ const code = (err as { code?: unknown }).code;+ return typeof code === "string" && ABSENT_ERRNO.has(code);+}++function describe(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}diff --git a/src/core/brain/dream-apply.ts b/src/core/brain/dream-apply.tsnew file mode 100644index 00000000..a0431d2a--- /dev/null+++ b/src/core/brain/dream-apply.ts@@ -0,0 +1,396 @@+/**+ * The dream pass's mutation stage: turn a decided plan into disk state.+ *+ * One reason to change: the ORDER and mechanics of the writes. Nothing+ * here decides anything about the vault's contents β every choice was+ * already made by the planning stages. What this module owns is the+ * sequence that keeps the on-disk invariants true:+ *+ * 1. Write new unconfirmed preferences (so signal moves can find+ * them).+ * 2. Apply refresh (counters, confidence, promotion) to existing+ * preferences.+ * 3. Move retiring preferences out (after the refresh has had a+ * chance to surface the most recent counters in the retired+ * file). NOTE: refresh skips entries that will retire.+ * 4. Move consumed signals into `processed/`.+ *+ * Log emission is stage 5 and lives in `dream-report.ts`.+ *+ * Workrun checkpoints are emitted here rather than by the orchestrator+ * because a marker must mean "every durable effect attributed to that+ * phase is already on disk" β only the code that performs the writes+ * knows where that point is.+ */++import { existsSync, renameSync } from "node:fs";++import { appendDecisionChangeReceipt } from "./decisions/receipts.ts";+import { preferenceSlug, type PlanState } from "./dream-plan.ts";+import type { RefreshResult } from "./dream-refresh.ts";+import type { DreamGatedRetireEntry } from "./dream-types.ts";+import { WORKRUN_PHASE, type WorkrunHandle } from "./dream-workrun.ts";+import { collectEvidenceForSlug } from "./evidence.ts";+import { runHealEnrichment } from "./heal-run.ts";+import { CHAIN_DECAY_STALE_DAYS } from "./inject-governor.ts";+import { appendLogEvent } from "./log.ts";+import { preferencePath, processedSignalPath } from "./paths.ts";+import { moveToRetired, parsePreference } from "./preference.ts";+import { writePreferenceTxn } from "./preference-txn.ts";+import { isoSecond } from "./time.ts";+import { assertVaultIdentityForWrite } from "./vault-identity.ts";+import {+ BRAIN_LOG_EVENT_KIND,+ BRAIN_PREFERENCE_STATUS,+ BRAIN_RETIRED_REASON,+ type BrainConfig,+ type BrainPreference,+ type BrainRetiredReason,+} from "./types.ts";++const DAY_MS = 24 * 3600 * 1000;++/** Agent of record when the caller declared no name. */+const DEFAULT_DREAM_AGENT = "dream";++export interface DreamApplyInput {+ readonly vault: string;+ readonly cfg: BrainConfig;+ readonly now: Date;+ readonly plan: PlanState;+ readonly refresh: RefreshResult;+ /** Identity threaded into edit-history and decision receipts. */+ readonly agentName: string | undefined;+ /** `[[Brain/log/<date>]]`, stamped as `retired_by` on each move. */+ readonly wikilinkToRun: string;+ /** Resolved `dream.heal_enrich` gate for this run. */+ readonly healEnrichEnabled: boolean;+ readonly workrun: WorkrunHandle | null;+}++export interface DreamApplyResult {+ /** Signal ids actually moved into `processed/`. */+ readonly moved: string[];+ /** Retires the destructive-from-confirmed gate declined. */+ readonly gatedRetires: DreamGatedRetireEntry[];+ /** User pages the opt-in heal phase enriched. */+ readonly healEnriched: number;+}++/**+ * Signal ids a dry run WOULD move. Reported so the caller's summary is+ * accurate without touching disk.+ */+export function plannedSignalMoveIds(plan: PlanState): string[] {+ return Array.from(plan.signalsToMove.values(), (sig) => sig.id);+}++export function applyDreamPlan(input: DreamApplyInput): DreamApplyResult {+ const { vault, cfg, now, plan, refresh, wikilinkToRun, workrun } = input;+ const agent = input.agentName ?? DEFAULT_DREAM_AGENT;++ // This module renames signal files directly, so it owes the vault-identity+ // assertion on its own entry rather than trusting whoever called it. The+ // check is an idempotent in-memory pin and the caller's `openWorkrun` has+ // already satisfied it for this root, so it never fires twice in anger.+ assertVaultIdentityForWrite(vault);++ writePreferences(input, agent);+ writeConfidenceReceipts(vault, refresh, agent, now);++ // Synthesize is durable here and nowhere earlier: every new+ // unconfirmed preference, every refreshed preference and every+ // confidence receipt has landed. `promote_complete` is the pre-F2+ // name for the same writes, so it moves with it rather than being+ // left behind claiming a batch that had not started.+ workrun?.checkpoint(WORKRUN_PHASE.promoteComplete);+ workrun?.checkpoint(WORKRUN_PHASE.synthesizeComplete);++ const gatedRetires = executeRetires(vault, cfg, now, plan, wikilinkToRun);++ // Every planned retire has been moved (or explicitly gated) by here.+ workrun?.checkpoint(WORKRUN_PHASE.retireComplete);++ const moved = moveConsumedSignals(vault, plan);+ const healEnriched = input.healEnrichEnabled ? runHealEnrichmentSafely(vault) : 0;++ // Heal's second half (the optional enrichment) is durable here; its+ // first half was the retire loop above. The marker sits at the later+ // of the two, so it is never a claim about work still to come.+ workrun?.checkpoint(WORKRUN_PHASE.healComplete);++ return { moved, gatedRetires, healEnriched };+}++/**+ * Steps 1 and 2: create the freshly-promoted preferences, then rewrite+ * the refreshed ones.+ *+ * Edit-history (F4): every dream-pass write records its content+ * before/after so a preference's evolution stays auditable. The agent of+ * record is whoever invoked the dream run.+ *+ * v0.12.0 Brain Integrity Suite: both loops route through+ * `writePreferenceTxn` so `_revision` auto-stamps and `_content_hash`+ * lands automatically on confirmed promotions. The empty expectations+ * array is deliberate - dream's plan-time logic has already decided to+ * proceed; the txn just owns the bookkeeping.+ */+function writePreferences(input: DreamApplyInput, agent: string): void {+ const { vault, cfg, now, plan, refresh } = input;+ const historyOpts = { agent, now: () => now };++ for (const np of plan.newUnconfirmed) {+ // Fresh pref has no apply-evidence yet; recentApplied/recentViolated+ // start empty and stay so until the next dream pass after the+ // first `brain_apply_evidence` event.+ writePreferenceTxn(+ vault,+ {+ slug: np.slug,+ topic: np.topic,+ principle: np.principle,+ created_at: isoSecond(now),+ unconfirmed_until: isoSecond(addDays(now, cfg.dream.unconfirmed_window_days)),+ status: BRAIN_PREFERENCE_STATUS.unconfirmed,+ evidenced_by: np.evidencedBy,+ // No evidence yet β Wilson lower bound on (0, 0) is 0. Pre-+ // seed the field so refresh on the next pass does not have+ // to treat `null` as "needs update" (which would lift+ // `changed: false` no-ops into spurious rewrites).+ confidence_value: 0,+ recentApplied: [],+ recentViolated: [],+ ...(np.scope ? { scope: np.scope } : {}),+ ...(np.supersedes ? { supersedes: np.supersedes } : {}),+ // F5: bi-temporal validity extracted from the source signal.+ ...(np.valid_from ? { valid_from: np.valid_from } : {}),+ ...(np.valid_until ? { valid_until: np.valid_until } : {}),+ },+ [],+ { overwrite: false },+ historyOpts,+ );+ }++ for (const update of refresh.updated.values()) {+ // Rebuild the evidence slice from the log on every pass so the+ // pref body stays in sync with the counters even when the+ // counters themselves stayed put (e.g. dropping the+ // v0.9.x placeholder body during a no-counter-change run).+ const ev = collectEvidenceForSlug(vault, update.slug, {+ sinceIso: update.created_at,+ });+ // The freshness trend was classified at PLAN time (planRefresh)+ // so the no-op pre-flight rendered these exact bytes.+ writePreferenceTxn(+ vault,+ {+ slug: update.slug,+ topic: update.topic,+ principle: update.principle,+ created_at: update.created_at,+ unconfirmed_until: update.unconfirmed_until,+ status: update.status,+ evidenced_by: update.evidenced_by,+ confirmed_at: update.confirmed_at,+ applied_count: update.applied_count,+ violated_count: update.violated_count,+ last_evidence_at: update.last_evidence_at,+ confidence: update.confidence,+ confidence_value: update.confidence_value,+ pinned: update.pinned,+ recentApplied: ev.applied,+ recentViolated: ev.violated,+ ...(update.freshness_trend !== undefined+ ? { freshness_trend: update.freshness_trend }+ : {}),+ ...(update.scope ? { scope: update.scope } : {}),+ },+ [],+ { overwrite: true },+ historyOpts,+ );+ }+}++/**+ * Belief lifecycle suite (B4): the preference-confidence update path+ * emits a decision-change receipt for each material confidence band+ * change captured this pass. `bandDrops` is the existing, already-+ * computed set of material weakenings (a band actually dropped), so+ * this rides on data the refresh already produced without touching its+ * byte-identical no-op guarantees. The receipt's idempotency key+ * (subject + before + after) makes a re-run a no-op. Fail-soft.+ */+function writeConfidenceReceipts(+ vault: string,+ refresh: RefreshResult,+ agent: string,+ now: Date,+): void {+ for (const d of refresh.bandDrops) {+ const before = `confidence:${d.previous}${d.previous_value !== null ? `(${d.previous_value.toFixed(2)})` : ""}`;+ const after = `confidence:${d.next}(${d.next_value.toFixed(2)})`;+ try {+ appendDecisionChangeReceipt(vault, {+ subject: d.id,+ before,+ after,+ confidenceDelta: d.previous_value !== null ? d.next_value - d.previous_value : null,+ actor: agent,+ rationale: `applied ${d.applied} / violated ${d.violated}`,+ reasonCode: "confidence-refresh",+ ts: now.toISOString(),+ });+ } catch {+ // Accountability mirror is best-effort; the refreshed preference+ // bytes remain authoritative.+ }+ }+}++/** Step 3: move each planned retire into `retired/`, honouring the evidence gate. */+function executeRetires(+ vault: string,+ cfg: BrainConfig,+ now: Date,+ plan: PlanState,+ wikilinkToRun: string,+): DreamGatedRetireEntry[] {+ // v0.12.0 Brain Integrity Suite: declined retires accumulate here.+ // Always an array (even when no gate is configured) so the eventual+ // DreamRunSummary.gated_retires field is consistently shaped.+ const gatedRetires: DreamGatedRetireEntry[] = [];+ const gateThreshold = cfg.retire.confirmed_evidence_min_threshold;++ for (const r of plan.retires) {+ const fromPath = preferencePath(vault, r.slug);+ if (!existsSync(fromPath)) continue;+ // v0.12.0 Brain Integrity Suite: destructive-from-confirmed gate.+ // When the operator has set retire.confirmed_evidence_min_threshold,+ // refuse to retire a confirmed (unpinned) pref whose accumulated+ // evidence count is below the configured floor. Operator-initiated+ // retires bypass.+ if (gateThreshold !== undefined && gateThreshold > 0) {+ try {+ const existing = parsePreference(fromPath);+ if (shouldGateRetireFromConfirmed(existing, r.reason, gateThreshold)) {+ gatedRetires.push({+ pref_id: existing.id,+ topic: existing.topic,+ applied_count: existing.applied_count,+ violated_count: existing.violated_count,+ threshold: gateThreshold,+ attempted_reason: r.reason,+ });+ continue;+ }+ } catch {+ // Parse failure - fall through to the normal retire path+ // (moveToRetired will surface the error through stderr below).+ }+ }+ try {+ moveToRetired(vault, fromPath, r.reason, {+ now,+ retired_by: wikilinkToRun,+ ...(r.supersededBy ? { superseded_by: r.supersededBy } : {}),+ });+ // Belief lifecycle suite (A4): record the accelerated retirement of+ // a low-recall superseded ancestor as a dedicated audit event.+ if (r.chainDecay) {+ appendLogEvent(vault, {+ timestamp: isoSecond(now),+ eventType: BRAIN_LOG_EVENT_KIND.chainDecay,+ body: {+ preference: `[[ret-${r.slug}]]`,+ reason: r.reason,+ stale_days: String(CHAIN_DECAY_STALE_DAYS),+ },+ });+ }+ } catch (err) {+ // A retire failure is logged via the `skip-corrupted-frontmatter`+ // pathway only if it stemmed from a parse error during the+ // plan; here the file may have been moved already (rare race).+ // Surface the cause so an operator chasing a missing retire can+ // see which slug tripped.+ process.stderr.write(+ `warning: retire stale pref ${r.slug} failed: ${(err as Error).message}\n`,+ );+ }+ }+ return gatedRetires;+}++/** Step 4: move every consumed signal out of `inbox/`. */+function moveConsumedSignals(vault: string, plan: PlanState): string[] {+ const moved: string[] = [];+ for (const sig of plan.signalsToMove.values()) {+ const dest = processedSignalPath(vault, sig.date, sig.slug);+ try {+ renameSync(sig.path, dest);+ moved.push(sig.id);+ } catch (err) {+ // Best-effort: a missing source signal (already moved) is+ // benign on rerun. Still surface so a real I/O issue is visible.+ process.stderr.write(+ `warning: move signal ${sig.id} to processed/ failed: ${(err as Error).message}\n`,+ );+ }+ }+ return moved;+}++/**+ * Heal phase (F6): opt-in deterministic vault enrichment, run after the+ * retire/move mutations (heal-after-mutations). Off by default so the+ * default install stays byte-identical; a failure is a warning, never+ * fatal to the dream pass.+ */+function runHealEnrichmentSafely(vault: string): number {+ try {+ return runHealEnrichment(vault).enriched;+ } catch (err) {+ process.stderr.write(`warning: heal enrichment failed: ${(err as Error).message}\n`);+ return 0;+ }+}++/**+ * Brain Integrity Suite (v0.12.0). Pure decision function for the+ * destructive-from-confirmed gate. Exported so the gate logic can be+ * unit-tested without driving a full dream run.+ *+ * Returns `true` when the candidate retire MUST be held back. The+ * caller is responsible for recording a {@link DreamGatedRetireEntry}+ * and skipping the actual `moveToRetired` call.+ */+export function shouldGateRetireFromConfirmed(+ existing: BrainPreference,+ reason: BrainRetiredReason,+ threshold: number | undefined,+): boolean {+ if (threshold === undefined || threshold <= 0) return false;+ if (reason === BRAIN_RETIRED_REASON.userRejected) return false;+ if (reason === BRAIN_RETIRED_REASON.mergedInto) return false;+ if (existing.status !== BRAIN_PREFERENCE_STATUS.confirmed) return false;+ if (existing.pinned) return false;+ const evidenceCount = (existing.applied_count ?? 0) + (existing.violated_count ?? 0);+ return evidenceCount < threshold;+}++/**+ * Slugs whose retire the gate declined. The log body and the+ * DreamRunSummary must agree on this set, or the next dream pass would+ * parse a `pref-foo` log claiming the pref was retired while the file is+ * still in `preferences/`.+ */+export function gatedRetireSlugs(gatedRetires: ReadonlyArray<DreamGatedRetireEntry>): Set<string> {+ return new Set(gatedRetires.map((g) => preferenceSlug(g.pref_id)));+}++function addDays(d: Date, days: number): Date {+ return new Date(d.getTime() + days * DAY_MS);+}diff --git a/src/core/brain/dream-plan-retires.ts b/src/core/brain/dream-plan-retires.tsnew file mode 100644index 00000000..79dc6668--- /dev/null+++ b/src/core/brain/dream-plan-retires.ts@@ -0,0 +1,136 @@+/**+ * The dream pass's time-based retire decision.+ *+ * One reason to change: when a preference has outlived its usefulness.+ * Two clocks drive it β an unconfirmed pref that ran past+ * `unconfirmed_until`, and a confirmed/quarantine pref whose last evidence+ * is older than the stale window. A pinned pref never actually retires;+ * it records a `retain-pinned` decision instead.+ *+ * Reads the post-refresh shape where one exists, so a pref promoted in+ * THIS run is judged on the counters this run is about to write, not the+ * stale ones on disk.+ *+ * Pure: no I/O. It mutates the plan it is handed, and prunes any refresh+ * update made pointless by a retire.+ */++import { effectiveStaleThresholdDays, isLowRecallSupersededAncestor } from "./inject-governor.ts";+import { preferenceSlug, type PlanState, type ScanResult } from "./dream-plan.ts";+import type { RefreshResult } from "./dream-refresh.ts";+import { isPinned } from "./pin.ts";+import { renderPrefLink } from "./wikilink.ts";+import {+ BRAIN_PREFERENCE_STATUS,+ BRAIN_RETIRED_REASON,+ type BrainConfig,+ type BrainPreference,+ type BrainRetiredReason,+} from "./types.ts";++const DAY_MS = 24 * 3600 * 1000;++export function planAutoRetires(+ scan: ScanResult,+ cfg: BrainConfig,+ now: Date,+ plan: PlanState,+ refresh: RefreshResult,+): void {+ for (const rec of scan.preferences) {+ const slug = preferenceSlug(rec.pref.id);+ // Already planned to retire (rebutted)? Skip.+ if (plan.retires.some((r) => r.slug === slug)) continue;++ // Use the refreshed status/confirmed_at if available β a pref+ // promoted to confirmed in THIS run should be eligible for stale+ // retire only if its (yet-to-be-refreshed) last_evidence_at is+ // actually old. We branch on the post-refresh shape.+ const refreshed = refresh.updated.get(slug);+ const effectiveStatus = refreshed ? refreshed.status : rec.pref.status;++ if (effectiveStatus === BRAIN_PREFERENCE_STATUS.unconfirmed) {+ const deadline = Date.parse(rec.pref.unconfirmed_until);+ if (Number.isFinite(deadline) && now.getTime() > deadline) {+ recordRetire(plan, refresh, rec.pref, slug, BRAIN_RETIRED_REASON.expiredUnconfirmed, false);+ }+ continue;+ }++ // Confirmed/quarantine β stale-no-evidence check. Quarantine+ // is "still active" (design summary Β§20) so the time-based decay+ // applies to it identically β a pref sitting idle with no+ // evidence eventually retires whether confidence was healthy or+ // probationary at the time the clock ran out.+ if (+ effectiveStatus !== BRAIN_PREFERENCE_STATUS.confirmed &&+ effectiveStatus !== BRAIN_PREFERENCE_STATUS.quarantine+ ) {+ continue;+ }++ // Belief lifecycle suite (A4): a low-recall superseded ancestor+ // decays on the accelerated window so it leaves the working set+ // faster than a live memory. Non-superseded / well-used prefs keep+ // the normal window, so a vault with no chains is byte-identical.+ const chainDecay = isLowRecallSupersededAncestor({+ supersededBy: rec.supersededBy,+ appliedCount: refreshed ? refreshed.applied_count : rec.pref.applied_count,+ });+ const staleDays = effectiveStaleThresholdDays(chainDecay, cfg.retire.stale_evidence_days);++ // Confirmed with no evidence at all? Shouldn't happen, but+ // gate on the same staleness rule using `confirmed_at`. We+ // measure from confirmation in that case (cheaper than a+ // hand-crafted invariant check). An empty string counts as absent,+ // same as a missing field.+ const effectiveLastEvidence = refreshed+ ? refreshed.last_evidence_at+ : rec.pref.last_evidence_at;+ const effectiveConfirmedAt = refreshed ? refreshed.confirmed_at : rec.pref.confirmed_at;+ const since = effectiveLastEvidence ? effectiveLastEvidence : effectiveConfirmedAt;+ if (!since) continue;++ if (daysBetween(Date.parse(since), now.getTime()) > staleDays) {+ recordRetire(plan, refresh, rec.pref, slug, BRAIN_RETIRED_REASON.staleNoEvidence, chainDecay);+ }+ }+}++/**+ * Record the decision for one due preference. A pinned pref yields a+ * `retain-pinned` entry and stays put; anything else retires and drops its+ * pending refresh update β there is no point writing a file immediately+ * before moving it to `retired/`.+ */+function recordRetire(+ plan: PlanState,+ refresh: RefreshResult,+ pref: BrainPreference,+ slug: string,+ reason: BrainRetiredReason,+ chainDecay: boolean,+): void {+ if (isPinned(pref)) {+ plan.retainPinned.push({+ preference: renderPrefLink({+ id: pref.id,+ principle: pref.principle,+ }),+ reason,+ });+ return;+ }+ plan.retires.push({+ slug,+ principle: pref.principle,+ reason,+ ...(chainDecay ? { chainDecay: true } : {}),+ });+ refresh.updated.delete(slug);+}++function daysBetween(thenMs: number, nowMs: number): number {+ if (!Number.isFinite(thenMs)) return 0;+ return (nowMs - thenMs) / DAY_MS;+}diff --git a/src/core/brain/dream-plan-topics.ts b/src/core/brain/dream-plan-topics.tsnew file mode 100644index 00000000..559e7be7--- /dev/null+++ b/src/core/brain/dream-plan-topics.ts@@ -0,0 +1,439 @@+/**+ * The dream pass's per-topic transition decision.+ *+ * One reason to change: what a cluster of active signals on a topic+ * *means*. Everything else about the pass - retire timing, disk writes,+ * log shape - lives elsewhere. Given a scan and the config, this module+ * decides, for each topic with active signals, exactly one of:+ *+ * - suppress the signals (a user-rejected retired pref covers them),+ * - quarantine the cluster (self-approval guardrail not satisfied),+ * - create a new unconfirmed preference,+ * - note them redundant against the active preference of record,+ * - accumulate them as a rebuttal (retiring the active pref, or+ * logging a retain-pinned when it is pinned),+ * - or record the topic as an unresolved contradiction.+ *+ * Pure: no I/O, no clock beyond the `now` it is handed.+ */++import { applySelfApprovalGuardrail } from "./trust/self-approval-guardrail.ts";+import {+ emptyPlan,+ filterWithinWindow,+ PREF_ID_PREFIX,+ preferenceSlug,+ recordSignalMove,+ RETIRED_ID_PREFIX,+ type PlanState,+ type PreferenceRecord,+ type RetiredRecord,+ type ScanResult,+ type SignalRecord,+} from "./dream-plan.ts";+import { resolveGuardrails } from "./policy.ts";+import { isPinned } from "./pin.ts";+import { countSigns, dominantSignOf } from "./sign.ts";+import { extractTemporalConstraints } from "./temporal-extract.ts";+import { renderPrefLink } from "./wikilink.ts";+import {+ BRAIN_RETIRED_REASON,+ BRAIN_SIGNAL_SIGN,+ type BrainConfig,+ type BrainSignal,+ type BrainSignalSign,+} from "./types.ts";++const DAY_MS = 24 * 60 * 60 * 1000;++/** Suffix that keeps a rebuttal's new pref from colliding with the pref it retires. */+const REBUT_SLUG_SUFFIX = "-rebut";++export function planTopics(scan: ScanResult, cfg: BrainConfig, now: Date): PlanState {+ const plan = emptyPlan();+ const reservedSlugs = collectReservedPreferenceSlugs(scan);++ // Group active signals by topic. We only consider active signals for+ // the create/rebut decisions; processed signals stay in the global+ // log via `evidenced_by` already.+ const byTopic = new Map<string, SignalRecord[]>();+ for (const rec of scan.signals) {+ if (!rec.active) continue;+ const topic = rec.signal.topic;+ const arr = byTopic.get(topic);+ if (arr) arr.push(rec);+ else byTopic.set(topic, [rec]);+ }++ // Index existing active preferences by topic.+ const prefByTopic = new Map<string, PreferenceRecord>();+ for (const p of scan.preferences) {+ // The first wins; design doc Β§7.4 invariant says "one preference per+ // topic", so a duplicate would be a doctor-level issue, not a dream+ // concern.+ if (!prefByTopic.has(p.pref.topic)) prefByTopic.set(p.pref.topic, p);+ }++ // Index retired by topic for supersede bookkeeping.+ const retiredByTopic = new Map<string, RetiredRecord[]>();+ for (const r of scan.retired) {+ const arr = retiredByTopic.get(r.topic);+ if (arr) arr.push(r);+ else retiredByTopic.set(r.topic, [r]);+ }++ for (const [topic, sigs] of byTopic) {+ const active = prefByTopic.get(topic);+ if (active) {+ handleSignalsOnActivePref(active, sigs, plan, cfg, now, scan.signals, reservedSlugs);+ continue;+ }+ const candidateSigs = applySignalSuppression(topic, sigs, retiredByTopic.get(topic), plan);+ if (candidateSigs.length === 0) continue;+ planTopicWithoutActivePref(topic, candidateSigs, plan, cfg, now, retiredByTopic, reservedSlugs);+ }+ return plan;+}++/**+ * v0.10.1 _summary Β§6: when a retired pref for this topic carries a+ * `user_rejected_reason`, the user explicitly rejected the rule β re-growing+ * it from fresh signals is exactly what they were asking us not to do.+ * Suppress every matching signal, emit one `signal-suppressed` event per+ * signal pointing at the retired pref + the reason, and move them straight+ * to processed.+ *+ * Per-signal scope match: an unscoped suppressor swallows every signal on+ * the topic; a scoped suppressor only swallows signals sharing its scope (a+ * signal without scope still matches an unscoped suppressor but never a+ * scoped one). Multiple retired prefs on the same topic are tried in order β+ * the first matching suppressor wins. Non-matching signals fall through and+ * remain eligible for candidate-pref planning.+ */+function applySignalSuppression(+ topic: string,+ sigs: SignalRecord[],+ retiredForTopic: RetiredRecord[] | undefined,+ plan: PlanState,+): SignalRecord[] {+ const suppressors = (retiredForTopic ?? []).filter((r) => !!r.user_rejected_reason);+ if (suppressors.length === 0) return sigs;++ const remaining: SignalRecord[] = [];+ for (const sig of sigs) {+ const suppressor = suppressors.find((r) => {+ if (!r.scope) return true;+ if (!sig.signal.scope) return false;+ return r.scope === sig.signal.scope;+ });+ if (!suppressor) {+ remaining.push(sig);+ continue;+ }+ plan.signalsSuppressed.push({+ signal: `[[${sig.signal.id}]]`,+ retired: renderPrefLink({+ id: suppressor.id,+ principle: suppressor.principle,+ }),+ reason: suppressor.user_rejected_reason!,+ topic,+ });+ recordSignalMove(plan, sig);+ }+ return remaining;+}++/** No active pref for this topic β either promote, quarantine, or note a contradiction. */+function planTopicWithoutActivePref(+ topic: string,+ candidateSigs: SignalRecord[],+ plan: PlanState,+ cfg: BrainConfig,+ now: Date,+ retiredByTopic: Map<string, RetiredRecord[]>,+ reservedSlugs: Set<string>,+): void {+ const windowedSigs = filterWithinWindow(candidateSigs, cfg.dream.contradiction_window_days, now);+ const positives = windowedSigs.filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.positive);+ const negatives = windowedSigs.filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.negative);+ const dominant = positives.length >= negatives.length ? positives : negatives;+ const minoritySize = Math.min(positives.length, negatives.length);+ const dominantSize = dominant.length - minoritySize; // cancellation++ if (dominantSize < cfg.dream.candidate_threshold) {+ if (positives.length > 0 && negatives.length > 0) plan.contradictionTopics.add(topic);+ return;+ }++ if (quarantineIfGuarded(topic, dominant, dominantSize, plan, cfg, now)) return;++ // Decide supersede: if a retired pref for the same topic exists,+ // wire it through.+ const retiredForTopic = retiredByTopic.get(topic);+ const supersedesRecord =+ retiredForTopic && retiredForTopic.length > 0 ? retiredForTopic[0]! : undefined;+ const source = dominant[0]!.signal;+ // Slug from topic for the canonical filename, but reserve slugs+ // already present in retired/. Otherwise a superseding preference+ // can be created as `pref-topic` while `ret-topic` already exists;+ // its later retirement would fail trying to overwrite that retired+ // file.+ const slug = allocatePreferencePlanSlug(topic, reservedSlugs);+ // evidencedBy = wikilinks to ALL active signals (dominant + minority)+ // that contributed to this topic in the window. We deliberately+ // include the minority signals so the audit trail preserves the+ // contradiction story even after the file moves to processed/.+ const evidencedBy = windowedSigs.map((s) => `[[${s.signal.id}]]`);+ plan.newUnconfirmed.push({+ slug,+ topic,+ scope: source.scope,+ principle: source.principle,+ evidencedBy,+ sign: source.signal,+ ...deriveSignalTemporal(source, now),+ ...(supersedesRecord+ ? {+ supersedes: renderPrefLink({+ id: supersedesRecord.id,+ principle: supersedesRecord.principle,+ }),+ }+ : {}),+ });+ // Every contributing signal in the window gets moved.+ for (const s of windowedSigs) {+ recordSignalMove(plan, s);+ }+}++/**+ * v0.10.16: extra self-approval guardrail. Defaults (min_signals=2,+ * min_distinct_agents=1, min_age_days=0) make this check a no-op for+ * clusters that already passed `candidate_threshold`. Operators may opt+ * into stricter thresholds via `_brain.yaml:guardrails:*`. A failed gate+ * routes the cluster to `quarantined` instead of creating a new+ * unconfirmed preference; the contributing signals stay in inbox/ so the+ * cluster naturally re-evaluates on the next pass once more evidence+ * accumulates.+ *+ * Returns true when the cluster was quarantined and must not promote.+ */+function quarantineIfGuarded(+ topic: string,+ dominant: ReadonlyArray<SignalRecord>,+ dominantSize: number,+ plan: PlanState,+ cfg: BrainConfig,+ now: Date,+): boolean {+ const distinctAgents = new Set(dominant.map((s) => s.signal.agent)).size;+ let earliestSignalMs = Number.POSITIVE_INFINITY;+ for (const s of dominant) {+ const t = Date.parse(s.signal.created_at);+ if (Number.isFinite(t) && t < earliestSignalMs) earliestSignalMs = t;+ }+ const ageDays = Number.isFinite(earliestSignalMs)+ ? Math.max(0, Math.floor((now.getTime() - earliestSignalMs) / DAY_MS))+ : 0;+ const verdict = applySelfApprovalGuardrail(+ {+ signal_count: dominantSize,+ distinct_agents: distinctAgents,+ age_days: ageDays,+ },+ resolveGuardrails(cfg),+ );+ if (verdict.decision !== "quarantine") return false;+ plan.quarantined.push({+ topic,+ signal_count: dominantSize,+ distinct_agents: distinctAgents,+ age_days: ageDays,+ failed_gates: verdict.failed_gates,+ });+ return true;+}++/**+ * Determine the active preference's sign. Order of preference:+ *+ * 1. Walk `evidenced_by` wikilinks and look up each referenced+ * signal in the global scan; the dominant sign among them is+ * the pref's "sign of record". This is the design-correct+ * derivation since the writer baked those evidence pointers in.+ *+ * 2. If no `evidenced_by` resolves (e.g. a hand-crafted pref or a+ * pref whose source signals were manually pruned), look at all+ * historical signals on the same topic in the global scan.+ *+ * 3. If still nothing, assume the active pref is on the OPPOSITE+ * sign of the incoming dominant sign. This makes a unanimous+ * flood of new signals always count as rebuttal β which is the+ * conservative, fail-loud choice: the operator gets a clear+ * rebut/retire signal and can manually intervene if the system+ * misread their intent.+ */+function deriveActiveSign(+ active: PreferenceRecord,+ sigs: SignalRecord[],+ allSignals: ReadonlyArray<SignalRecord>,+): BrainSignalSign {+ const signCounts = (records: ReadonlyArray<SignalRecord>): { pos: number; neg: number } =>+ countSigns(records.map((r) => r.signal.signal));++ // Tier-1 derivation now lives in the shared `sign.ts` helper so the+ // semantic-health contradiction detector and this pass agree on one+ // definition. `dominantSignOf` returning a concrete sign is exactly+ // the old `evidenceRecords.length > 0` branch (every signal carries a+ // polarity, so a resolved evidence link always counts); `"unknown"`+ // is the old "no evidenced signal resolved" fall-through.+ const signSignById = new Map(allSignals.map((r) => [r.signal.id, r.signal.signal]));+ const evidenceSign = dominantSignOf(active.pref.evidenced_by, signSignById);+ if (evidenceSign !== "unknown") return evidenceSign;++ const topicRecords = allSignals.filter((r) => r.signal.topic === active.pref.topic);+ if (topicRecords.length > sigs.length) {+ // There are processed signals for this topic that are NOT among+ // the active inbox set β use them.+ const c = signCounts(topicRecords.filter((r) => !sigs.includes(r)));+ return c.pos >= c.neg ? BRAIN_SIGNAL_SIGN.positive : BRAIN_SIGNAL_SIGN.negative;+ }+ // Fallback: assume the active pref is OPPOSITE to the incoming+ // dominant sign. A unanimous flood thus reads as rebuttal.+ const c = signCounts(sigs);+ return c.pos > c.neg ? BRAIN_SIGNAL_SIGN.negative : BRAIN_SIGNAL_SIGN.positive;+}++function handleSignalsOnActivePref(+ active: PreferenceRecord,+ sigs: SignalRecord[],+ plan: PlanState,+ cfg: BrainConfig,+ now: Date,+ allSignals: ReadonlyArray<SignalRecord>,+ reservedSlugs: Set<string>,+): void {+ const activeSign = deriveActiveSign(active, sigs, allSignals);+ const oppositeSign: BrainSignalSign =+ activeSign === BRAIN_SIGNAL_SIGN.positive+ ? BRAIN_SIGNAL_SIGN.negative+ : BRAIN_SIGNAL_SIGN.positive;++ const windowed = filterWithinWindow(sigs, cfg.dream.contradiction_window_days, now);+ const sameSign = windowed.filter((s) => s.signal.signal === activeSign);+ const opposing = windowed.filter((s) => s.signal.signal === oppositeSign);++ const activeLink = renderPrefLink({+ id: active.pref.id,+ principle: active.pref.principle,+ });++ // Same-sign β note redundant + move to processed.+ for (const s of sameSign) {+ plan.notedRedundant.push({+ preference: activeLink,+ signal: `[[${s.signal.id}]]`,+ });+ recordSignalMove(plan, s);+ }++ // Opposite-sign β accumulate toward rebuttal.+ if (opposing.length < cfg.dream.candidate_threshold) {+ if (opposing.length > 0) plan.contradictionTopics.add(active.pref.topic);+ return;+ }++ if (isPinned(active.pref)) {+ plan.retainPinned.push({+ preference: activeLink,+ reason: BRAIN_RETIRED_REASON.rebutted,+ });+ // Rebuttal signals on a pinned pref still get moved out β they+ // were addressed (the system saw them) and clogging the inbox+ // doesn't help.+ for (const s of opposing) recordSignalMove(plan, s);+ return;+ }++ const slug = preferenceSlug(active.pref.id);+ plan.retires.push({+ slug,+ principle: active.pref.principle,+ reason: BRAIN_RETIRED_REASON.rebutted,+ });+ for (const s of opposing) recordSignalMove(plan, s);+ // Create a new unconfirmed pref for the new direction.+ // Build a fresh slug to avoid filename collision with the+ // retiring pref (which lives under preferences/<slug>.md and+ // will move to retired/<slug>.md). The simplest scheme: the+ // same slug, since `moveToRetired` unlinks the source first.+ // For safety against a half-completed move, we suffix with+ // `-rebut`.+ const source = opposing[0]!.signal;+ plan.newUnconfirmed.push({+ slug: allocatePreferencePlanSlug(`${slug}${REBUT_SLUG_SUFFIX}`, reservedSlugs),+ topic: active.pref.topic,+ scope: source.scope,+ principle: source.principle,+ evidencedBy: opposing.map((s) => `[[${s.signal.id}]]`),+ sign: oppositeSign,+ ...deriveSignalTemporal(source, now),+ supersedes: activeLink,+ });+}++function collectReservedPreferenceSlugs(scan: ScanResult): Set<string> {+ const out = new Set<string>();+ for (const p of scan.preferences) {+ const slug = strictSlugFromId(p.pref.id, PREF_ID_PREFIX);+ if (slug) out.add(slug);+ }+ for (const r of scan.retired) {+ const slug = strictSlugFromId(r.id, RETIRED_ID_PREFIX);+ if (slug) out.add(slug);+ }+ return out;+}++/**+ * Strict counterpart to `preferenceSlug`: an id that does not carry the+ * expected prefix reserves nothing, because it names no file the writer+ * would ever produce.+ */+function strictSlugFromId(id: string, prefix: string): string | null {+ return id.startsWith(prefix) && id.length > prefix.length ? id.slice(prefix.length) : null;+}++function allocatePreferencePlanSlug(base: string, reserved: Set<string>): string {+ let candidate = base;+ let suffix = 2;+ while (reserved.has(candidate)) {+ candidate = `${base}-${suffix}`;+ suffix++;+ }+ reserved.add(candidate);+ return candidate;+}++/**+ * Brain lifecycle suite (F5). Derive a preference's bi-temporal validity+ * from the source signal: prefer the signal's explicit `valid_from` /+ * `valid_until`, otherwise extract formal ISO temporal tokens from the+ * signal's principle + raw text. Returns `{}` when neither yields a+ * constraint, so callers spread it without changing byte output.+ */+function deriveSignalTemporal(+ sig: BrainSignal,+ now: Date,+): { valid_from?: string; valid_until?: string } {+ if (sig.valid_from || sig.valid_until) {+ return {+ ...(sig.valid_from ? { valid_from: sig.valid_from } : {}),+ ...(sig.valid_until ? { valid_until: sig.valid_until } : {}),+ };+ }+ const text = `${sig.principle ?? ""}\n${sig.raw ?? ""}`;+ return extractTemporalConstraints(text, { now });+}diff --git a/src/core/brain/dream-plan.ts b/src/core/brain/dream-plan.tsindex 11a95f22..eff0cd06 100644--- a/src/core/brain/dream-plan.ts+++ b/src/core/brain/dream-plan.ts@@ -9,6 +9,24 @@import type { BrainPreference, BrainRetiredReason, BrainSignal, BrainSignalSign } from "./types.ts";+/** Id prefix the preference writer stamps on every live rule. */+export const PREF_ID_PREFIX = "pref-";++/** Id prefix a preference carries once it has moved into `retired/`. */+export const RETIRED_ID_PREFIX = "ret-";++/**+ * The filename slug behind a preference id.+ *+ * Every writer emits `pref-<slug>`, but the on-disk artifacts are+ * user-editable and a hand-authored file may carry a bare id. The dream+ * pass has always read such an id as being its own slug, so the strip is+ * tolerant rather than strict.+ */+export function preferenceSlug(id: string): string {+ return id.startsWith(PREF_ID_PREFIX) ? id.slice(PREF_ID_PREFIX.length) : id;+}+export interface SignalRecord {readonly path: string;readonly signal: BrainSignal;diff --git a/src/core/brain/dream-report.ts b/src/core/brain/dream-report.tsnew file mode 100644index 00000000..4bc51d4d--- /dev/null+++ b/src/core/brain/dream-report.ts@@ -0,0 +1,245 @@+/**+ * The dream pass's audit trail: everything the run says about itself in+ * `Brain/log/<today>.md`.+ *+ * One reason to change: what an operator (or the digest parser, or the+ * next dream pass) must be able to read back about a run. This module+ * owns the event ORDER, the per-event timestamp cursor and the summary+ * payload's shape. It decides nothing about the vault's contents.+ *+ * Only ever invoked on the changed, non-dry-run path β a no-op run+ * writes no events at all, which is what keeps an idempotent rerun+ * byte-identical.+ */++import { preferenceSlug, type PlanState, type ScanResult } from "./dream-plan.ts";+import type { RefreshResult } from "./dream-refresh.ts";+import { WORKRUN_PHASE, type WorkrunHandle } from "./dream-workrun.ts";+import { appendLogEvent } from "./log.ts";+import { vaultRelative } from "./paths.ts";+import type { ReconcileOutcomes } from "./reconcile-outcomes.ts";+import { writeRollupLedger, type RollupLadderPlan } from "./rollup-ladder.ts";+import { isoSecond } from "./time.ts";+import { renderPrefLink } from "./wikilink.ts";+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";++/** Spacing between consecutive events so their log headings stay distinct. */+const EVENT_STAMP_STEP_MS = 1000;++/** Marks a retain-pinned event as an attempted-but-blocked retire. */+const RETIRE_BLOCKED_PINNED = "pinned";++export interface DreamReportInput {+ readonly vault: string;+ readonly now: Date;+ readonly runId: string;+ readonly scan: ScanResult;+ readonly plan: PlanState;+ readonly refresh: RefreshResult;+ readonly reconcile: ReconcileOutcomes;+ readonly rollupPlan: RollupLadderPlan;+ /** Signal ids that actually reached `processed/`. */+ readonly moved: ReadonlyArray<string>;+ /** Retires the evidence gate declined; excluded from the `retired` row. */+ readonly gatedSlugs: ReadonlySet<string>;+ /** True when the invoking agent differs from the vault's declared primary. */+ readonly isNonPrimary: boolean;+ readonly callerAgent: string;+ readonly workrun: WorkrunHandle | null;+}++/**+ * Emit the run's log entries: skip-corrupted-frontmatter first+ * (chronological sense: corruption was detected during planning), then+ * per-topic events, then the run summary last.+ */+export function writeDreamLog(input: DreamReportInput): void {+ const { vault, plan, reconcile, workrun } = input;+ const nextStamp = createStampCursor(input.now);++ for (const corrupt of input.scan.corrupted) {+ appendLogEvent(vault, {+ timestamp: nextStamp(),+ eventType: BRAIN_LOG_EVENT_KIND.skipCorruptedFrontmatter,+ body: {+ path: vaultRelative(corrupt.path, vault),+ },+ });+ }++ for (const noted of plan.notedRedundant) {+ appendLogEvent(vault, {+ timestamp: nextStamp(),+ eventType: BRAIN_LOG_EVENT_KIND.notedRedundant,+ body: {+ preference: noted.preference,+ signal: noted.signal,+ },+ });+ }++ // Reconcile phase (F3): one event per open question + per+ // auto-resolution. Persisted only on this changed path so a no-op+ // run stays byte-identical.+ for (const q of reconcile.openQuestions) {+ appendLogEvent(vault, {+ timestamp: nextStamp(),+ eventType: BRAIN_LOG_EVENT_KIND.reconcile,+ body: {+ topic: q.topic,+ domain: q.domain,+ reason: q.reason,+ ...(q.scope ? { scope: q.scope } : {}),+ positives: String(q.positive_count),+ negatives: String(q.negative_count),+ },+ });+ }+ for (const r of reconcile.autoResolved) {+ appendLogEvent(vault, {+ timestamp: nextStamp(),+ eventType: BRAIN_LOG_EVENT_KIND.reconcile,+ body: {+ topic: r.topic,+ domain: r.domain,+ resolution: "auto-resolved",+ winner_sign: r.winner_sign,+ margin_days: String(r.margin_days),+ },+ });+ }+ // Reconcile's only durable artifact is the pair of event loops just+ // above: the classification itself is in-memory and vanishes with the+ // process. The pre-mutation burst used to claim this phase complete+ // before a single preference had been written, which is precisely the+ // journal-lies failure this release removes. The marker therefore+ // trails `heal_complete` in the file - emission order is execution+ // order, not the reporting order of DREAM_PHASE_ORDER.+ workrun?.checkpoint(WORKRUN_PHASE.reconcileComplete);++ for (const suppressed of plan.signalsSuppressed) {+ appendLogEvent(vault, {+ timestamp: nextStamp(),+ eventType: BRAIN_LOG_EVENT_KIND.signalSuppressed,+ body: {+ signal: suppressed.signal,+ retired: suppressed.retired,+ topic: suppressed.topic,+ reason: suppressed.reason,+ },+ });+ }++ for (const retain of plan.retainPinned) {+ // `retain-pinned` is not in the strict BrainLogEventKind enum+ // (the design doc names a generic `retire` event with an+ // attempted-but-blocked reason). We log it as a `retire` event+ // with a `blocked: pinned` payload field so the parser+ // round-trips cleanly and the doctor command can flag it.+ appendLogEvent(vault, {+ timestamp: nextStamp(),+ eventType: BRAIN_LOG_EVENT_KIND.retire,+ body: {+ preference: retain.preference,+ reason: retain.reason,+ blocked: RETIRE_BLOCKED_PINNED,+ },+ });+ }++ appendLogEvent(vault, {+ timestamp: nextStamp(),+ eventType: BRAIN_LOG_EVENT_KIND.dream,+ body: buildSummaryBody(input),+ });++ // S3: persist the advanced rollup-ladder counters only when a rung+ // fired. A below-threshold run never touches the ledger, so its+ // absence is the byte-identical opt-out.+ if (input.rollupPlan.fired) writeRollupLedger(vault, input.rollupPlan.ledger);+}++/**+ * Monotonic per-emission timestamp source. Each event advances the cursor+ * so two events in the same run never share a log heading.+ */+function createStampCursor(now: Date): () => string {+ let cursorMs = now.getTime();+ return () => {+ const ts = new Date(cursorMs);+ cursorMs += EVENT_STAMP_STEP_MS;+ return isoSecond(ts);+ };+}++/**+ * The `dream` summary event's payload. Every row is conditional: a key+ * that would carry an empty list is omitted entirely, which is what keeps+ * a minimal run's event byte-identical to earlier releases.+ *+ * Link rendering threads the in-memory principle alongside the id so the+ * digest / Obsidian view can hover-preview the rule without an extra file+ * open.+ */+function buildSummaryBody(input: DreamReportInput): Record<string, string | ReadonlyArray<string>> {+ const { plan, refresh, rollupPlan, gatedSlugs } = input;++ const slugToPrefPrinciple = new Map<string, string>();+ for (const rec of input.scan.preferences) {+ slugToPrefPrinciple.set(preferenceSlug(rec.pref.id), rec.pref.principle);+ }+ const newUnconfirmedIds = plan.newUnconfirmed.map((p) =>+ renderPrefLink({ id: `pref-${p.slug}`, principle: p.principle }),+ );+ const confirmedIds = Array.from(refresh.confirmed.values()).map((slug) =>+ renderPrefLink({+ id: `pref-${slug}`,+ principle: refresh.updated.get(slug)?.principle ?? slugToPrefPrinciple.get(slug) ?? "",+ }),+ );+ const retiredEntries = plan.retires+ .filter((r) => !gatedSlugs.has(r.slug))+ .map((r) => `${renderPrefLink({ id: `ret-${r.slug}`, principle: r.principle })} (${r.reason})`);++ const body: Record<string, string | ReadonlyArray<string>> = {+ run_id: input.runId,+ };+ if (newUnconfirmedIds.length > 0) body["new_unconfirmed"] = newUnconfirmedIds;+ if (confirmedIds.length > 0) body["confirmed"] = confirmedIds;+ if (retiredEntries.length > 0) body["retired"] = retiredEntries;+ if (input.moved.length > 0) body["moved_to_processed"] = input.moved;+ if (plan.contradictionTopics.size > 0) {+ body["contradictions"] = Array.from(plan.contradictionTopics);+ }+ if (plan.signalsSuppressed.length > 0) {+ body["suppressed"] = plan.signalsSuppressed.map((s) => `${s.signal} β ${s.retired}`);+ }+ if (refresh.bandDrops.length > 0) {+ // Format matches the digest's tolerant `parseShiftLine` parser:+ // `[[pref-β¦|principle]] <from> -> <to> (applied: N, violated: M)`.+ body["confidence_shifts"] = refresh.bandDrops.map((d) =>+ [+ renderPrefLink({ id: d.id, principle: d.principle }),+ d.previous,+ "->",+ d.next,+ `(applied: ${d.applied}, violated: ${d.violated})`,+ ].join(" "),+ );+ }+ if (input.isNonPrimary) {+ // Audit-trail row matching the structured warning. Stored+ // alongside `run_id` so a non-primary dream pass is greppable in+ // the log without parsing the structured warnings array.+ body["non_primary_agent"] = input.callerAgent;+ }+ // S3: record each fired rollup rung's counter reset in the dream+ // report. Absent below threshold, so a non-firing run's summary event+ // is byte-identical to the pre-rollup behaviour.+ if (rollupPlan.fired) {+ body["rollups"] = rollupPlan.entries.map(+ (e) => `${e.tier} -> ${e.produces} (${e.fromCount} -> ${e.toCount})`,+ );+ }+ return body;+}diff --git a/src/core/brain/dream-scan.ts b/src/core/brain/dream-scan.tsnew file mode 100644index 00000000..0d8732d6--- /dev/null+++ b/src/core/brain/dream-scan.ts@@ -0,0 +1,137 @@+/**+ * Stage 0 of the dream pass: read the whole `Brain/` tree into memory.+ *+ * Pure with respect to the vault: it opens no writer, takes no clock and+ * touches nothing on disk, which is why it is the one part of the pass+ * that is provably runnable on its own (see `dream-step.ts`).+ *+ * A file whose frontmatter will not parse is collected into `corrupted`+ * rather than aborting the scan; the planning phase turns each entry into+ * a `skip-corrupted-frontmatter` log event.+ */++import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { parseFrontmatter } from "../vault.ts";+import type {+ CorruptedEntry,+ PreferenceRecord,+ RetiredRecord,+ ScanResult,+ SignalRecord,+} from "./dream-plan.ts";+import { isTombstoned } from "./lifecycle/tombstone.ts";+import { brainDirs } from "./paths.ts";+import { parsePreference } from "./preference.ts";+import { parseSignal } from "./signal.ts";++const MARKDOWN_EXT = ".md";++/** Absolute paths of the `.md` files directly inside `dir`, or nothing when it does not exist. */+function markdownFilesIn(dir: string): string[] {+ if (!existsSync(dir)) return [];+ const out: string[] = [];+ for (const name of readdirSync(dir)) {+ if (name.endsWith(MARKDOWN_EXT)) out.push(join(dir, name));+ }+ return out;+}++/**+ * Signals from one directory. `inbox/` and `processed/` differ only in+ * the `active` flag they stamp on each record, so they share this walk.+ */+function collectSignals(+ dir: string,+ active: boolean,+ signals: SignalRecord[],+ corrupted: CorruptedEntry[],+): void {+ for (const full of markdownFilesIn(dir)) {+ // Belief lifecycle suite (t_7d5a3589): a tombstoned signal is+ // excluded from the dream pass so it is never re-clustered.+ if (isTombstoned(parseFrontmatter(full)[0])) continue;+ try {+ signals.push({ path: full, signal: parseSignal(full), active });+ } catch {+ corrupted.push({ path: full });+ }+ }+}++function collectPreferences(+ dir: string,+ preferences: PreferenceRecord[],+ corrupted: CorruptedEntry[],+): void {+ for (const full of markdownFilesIn(dir)) {+ const rawMeta = parseFrontmatter(full)[0];+ if (isTombstoned(rawMeta)) continue;+ // Belief lifecycle suite (A4): capture the raw superseded_by pointer+ // (the typed parser drops it) so accelerated chain decay can see a+ // temporally-superseded ancestor.+ const supersededBy =+ typeof rawMeta["superseded_by"] === "string" && rawMeta["superseded_by"] !== ""+ ? (rawMeta["superseded_by"] as string)+ : null;+ try {+ preferences.push({ path: full, pref: parsePreference(full), supersededBy });+ } catch {+ corrupted.push({ path: full });+ }+ }+}++function collectRetired(dir: string, retired: RetiredRecord[], corrupted: CorruptedEntry[]): void {+ for (const full of markdownFilesIn(dir)) {+ // Retired files we only need for topic + id (for supersede+ // bookkeeping) plus the optional `user_rejected_reason` that+ // drives signal-suppression (v0.10.1, _summary Β§6). We do a+ // lightweight frontmatter parse to avoid the strict folder+ // invariant check failing on permissive setups.+ try {+ const [meta] = parseFrontmatter(full);+ const topic = typeof meta["topic"] === "string" ? meta["topic"] : "";+ const id = typeof meta["id"] === "string" ? meta["id"] : "";+ const principle = typeof meta["principle"] === "string" ? meta["principle"] : "";+ const scope = typeof meta["scope"] === "string" ? meta["scope"] : undefined;+ const userReason =+ typeof meta["user_rejected_reason"] === "string"+ ? (meta["user_rejected_reason"] as string).trim()+ : "";+ if (topic && id) {+ retired.push({+ path: full,+ topic,+ id,+ principle,+ ...(scope ? { scope } : {}),+ ...(userReason ? { user_rejected_reason: userReason } : {}),+ });+ }+ } catch {+ corrupted.push({ path: full });+ }+ }+}++/**+ * Read the whole `Brain/` tree into memory. Pure: it opens no writer, takes+ * no clock and touches nothing on disk, which is why it is the one part of+ * the pass that is provably runnable on its own (see `dream-step.ts`).+ */+export function scanBrain(vault: string): ScanResult {+ const dirs = brainDirs(vault);+ const signals: SignalRecord[] = [];+ const preferences: PreferenceRecord[] = [];+ const retired: RetiredRecord[] = [];+ const corrupted: CorruptedEntry[] = [];++ collectSignals(dirs.inbox, true, signals, corrupted);+ collectSignals(dirs.processed, false, signals, corrupted);+ collectPreferences(dirs.preferences, preferences, corrupted);+ collectRetired(dirs.retired, retired, corrupted);++ return { signals, preferences, retired, corrupted };+}diff --git a/src/core/brain/dream-summary.ts b/src/core/brain/dream-summary.tsnew file mode 100644index 00000000..e066e77f--- /dev/null+++ b/src/core/brain/dream-summary.ts@@ -0,0 +1,164 @@+/**+ * The dream pass's return value: what a caller (CLI, MCP, trust verdict)+ * sees after a run.+ *+ * One reason to change: the public {@link DreamRunSummary} contract.+ * Two constructors, because a run ends in exactly one of two shapes and+ * they carry different guarantees:+ *+ * - {@link buildNoOpSummary} β nothing changed. No snapshot, no log+ * path, no phases, no rollups; the fields that only a mutation can+ * populate are frozen empty rather than omitted, so consumers never+ * branch on presence.+ * - {@link buildChangedSummary} β the run mutated the vault, so the+ * snapshot and log paths are real and the per-phase counters exist.+ *+ * Pure: no I/O, no clock. Every value is derived from state the earlier+ * stages already produced.+ */++import { DREAM_PHASE, type DreamPhase, type DreamPhaseSummary } from "./dream-phases.ts";+import type { PlanState, ScanResult } from "./dream-plan.ts";+import type { RefreshResult } from "./dream-refresh.ts";+import type {+ DreamGatedRetireEntry,+ DreamRunSummary,+ DreamUncertainEntry,+ DreamWarning,+} from "./dream-types.ts";+import type { BrainIntentReviewEntry } from "./intent-review.ts";+import type { ReconcileOutcomes } from "./reconcile-outcomes.ts";+import type { RollupLadderEntry, RollupLadderPlan } from "./rollup-ladder.ts";++/** Empty, frozen views for the fields a no-op run cannot populate. */+const NO_UNCERTAIN = Object.freeze([] as ReadonlyArray<DreamUncertainEntry>);+const NO_GATED_RETIRES = Object.freeze([] as ReadonlyArray<DreamGatedRetireEntry>);+const NO_PHASES = Object.freeze([] as ReadonlyArray<DreamPhaseSummary>);+const NO_ROLLUPS = Object.freeze([] as ReadonlyArray<RollupLadderEntry>);++export interface DreamNoOpSummaryInput {+ readonly runId: string;+ readonly dryRun: boolean;+ readonly plan: PlanState;+ readonly refresh: RefreshResult;+ readonly reconcile: ReconcileOutcomes;+ readonly intentReviews: ReadonlyArray<BrainIntentReviewEntry>;+ readonly warnings: ReadonlyArray<DreamWarning>;+}++export function buildNoOpSummary(input: DreamNoOpSummaryInput): DreamRunSummary {+ const { plan, refresh, reconcile } = input;+ return Object.freeze({+ run_id: input.runId,+ changed: false,+ new_unconfirmed: [],+ confirmed: [],+ retired: [],+ contradictions: [...plan.contradictionTopics],+ moved_to_processed: [],+ suppressed: [],+ warnings: Object.freeze([...input.warnings]),+ uncertain: NO_UNCERTAIN,+ quarantined: Object.freeze([...plan.quarantined]),+ intent_reviews: Object.freeze([...input.intentReviews]),+ gated_retires: NO_GATED_RETIRES,+ outcome_regressions: Object.freeze([...refresh.outcomeRegressions]),+ phases: NO_PHASES,+ rollups: NO_ROLLUPS,+ open_questions: Object.freeze([...reconcile.openQuestions]),+ ...(input.dryRun ? { dry_run: true } : {}),+ } satisfies DreamRunSummary);+}++export interface DreamChangedSummaryInput {+ readonly runId: string;+ /**+ * The mutually-exclusive tail of the summary: a dry run reports+ * `dry_run: true` and wrote nothing, a real run reports the day file+ * its summary event landed in. The caller builds it so the write-path+ * vault-identity assertion behind that path is never reached on a dry+ * run.+ */+ readonly runTail: { readonly dry_run: true } | { readonly log_path: string };+ readonly scan: ScanResult;+ readonly plan: PlanState;+ readonly refresh: RefreshResult;+ readonly reconcile: ReconcileOutcomes;+ readonly rollupPlan: RollupLadderPlan;+ readonly intentReviews: ReadonlyArray<BrainIntentReviewEntry>;+ readonly warnings: ReadonlyArray<DreamWarning>;+ readonly gatedRetires: ReadonlyArray<DreamGatedRetireEntry>;+ /** Slugs the evidence gate held back; excluded from `retired`. */+ readonly gatedSlugs: ReadonlySet<string>;+ readonly moved: ReadonlyArray<string>;+ readonly healEnriched: number;+ /** Absent on a dry run, which writes no snapshot. */+ readonly snapshotPath: string | undefined;+}++export function buildChangedSummary(input: DreamChangedSummaryInput): DreamRunSummary {+ const { plan, refresh, reconcile, gatedSlugs } = input;+ return Object.freeze({+ run_id: input.runId,+ changed: true,+ phases: buildPhaseSummaries(input),+ rollups: Object.freeze([...input.rollupPlan.entries]),+ open_questions: Object.freeze([...reconcile.openQuestions]),+ new_unconfirmed: plan.newUnconfirmed.map((p) => `pref-${p.slug}`),+ confirmed: Array.from(refresh.confirmed.values()).map((s) => `pref-${s}`),+ retired: plan.retires+ .filter((r) => !gatedSlugs.has(r.slug))+ .map((r) => ({ id: `ret-${r.slug}`, reason: r.reason })),+ contradictions: Array.from(plan.contradictionTopics),+ moved_to_processed: input.moved,+ suppressed: plan.signalsSuppressed.map((s) =>+ s.signal.replace(/^\[\[/, "").replace(/\]\]$/, ""),+ ),+ warnings: Object.freeze([...input.warnings]),+ uncertain: NO_UNCERTAIN,+ quarantined: Object.freeze([...plan.quarantined]),+ intent_reviews: Object.freeze([...input.intentReviews]),+ gated_retires: Object.freeze([...input.gatedRetires]),+ outcome_regressions: Object.freeze([...refresh.outcomeRegressions]),+ ...(input.snapshotPath ? { snapshot_path: input.snapshotPath } : {}),+ ...input.runTail,+ } satisfies DreamRunSummary);+}++/**+ * Multi-phase dream (F2): structured per-phase summaries for a changed+ * run. Metrics are integer counters derived from the plan/refresh that+ * already ran; additive keys may appear in later versions.+ */+function buildPhaseSummaries(input: DreamChangedSummaryInput): ReadonlyArray<DreamPhaseSummary> {+ const { scan, plan, refresh, reconcile, gatedSlugs } = input;+ return Object.freeze([+ phaseSummary(DREAM_PHASE.close, {+ active_signals: scan.signals.filter((s) => s.active).length,+ preferences: scan.preferences.length,+ retired_files: scan.retired.length,+ }),+ phaseSummary(DREAM_PHASE.reconcile, {+ contradictions: plan.contradictionTopics.size,+ open_questions: reconcile.openQuestions.length,+ auto_resolved: reconcile.autoResolved.length,+ }),+ phaseSummary(DREAM_PHASE.synthesize, {+ new_unconfirmed: plan.newUnconfirmed.length,+ confirmed: refresh.confirmed.size,+ }),+ phaseSummary(DREAM_PHASE.heal, {+ retired: plan.retires.filter((r) => !gatedSlugs.has(r.slug)).length,+ enriched: input.healEnriched,+ }),+ phaseSummary(DREAM_PHASE.log, {+ moved: input.moved.length,+ suppressed: plan.signalsSuppressed.length,+ }),+ ]);+}++/** Build one phase summary (module-scoped: captures nothing). */+function phaseSummary(phase: DreamPhase, metrics: Record<string, number>): DreamPhaseSummary {+ return { phase, metrics };+}diff --git a/src/core/brain/dream-types.ts b/src/core/brain/dream-types.tsnew file mode 100644index 00000000..dbd71f77--- /dev/null+++ b/src/core/brain/dream-types.ts@@ -0,0 +1,218 @@+/**+ * The input and output contract of one dream run.+ *+ * Separated from the orchestrator so every stage module (scan, plan,+ * apply, report, summary) can speak the same vocabulary without+ * importing `dream.ts` and closing a cycle back onto it. Pure type+ * declarations; no runtime code, no I/O.+ *+ * The plan-state shapes the stages exchange *between* themselves live in+ * `dream-plan.ts`; this module is only what a CALLER of `dream()` sees.+ */++import type { DreamPhaseSummary } from "./dream-phases.ts";+import type { DreamQuarantinedEntry } from "./dream-plan.ts";+import type { DreamOutcomeRegression } from "./dream-refresh.ts";+import type { BrainIntentReviewEntry } from "./intent-review.ts";+import type { RollupLadderEntry } from "./rollup-ladder.ts";+import type { BrainRetiredReason, DreamOpenQuestion } from "./types.ts";++/**+ * Structured non-fatal warning emitted alongside a dream summary. The+ * dream pass still completes when warnings are present; callers+ * (CLI / MCP) decide whether to surface them.+ */+export interface DreamWarning {+ readonly code: string;+ readonly message: string;+}++/**+ * Entry surfacing a step the dream pass attempted but could not+ * fully verify. Distinct from a `DreamWarning` (which flags+ * configuration smells): an `uncertain` entry means "I tried, no+ * hard error, but I cannot claim the operation completed". Consumed+ * by the trust verdict + operator summary (v0.10.16).+ */+export interface DreamUncertainEntry {+ /** Stable code identifying which sub-operation could not confirm. */+ readonly code: string;+ /** Optional topic slug or preference id this uncertainty concerns. */+ readonly topic?: string;+ /** Human-readable explanation. */+ readonly message: string;+}++/**+ * Brain Integrity Suite (v0.12.0). Entry for a retire that the dream+ * pass declined because `retire.confirmed_evidence_min_threshold` was+ * set and the source preference's accumulated evidence count fell+ * below it. The pref stays in `preferences/`; the operator can lift+ * the gate by raising the evidence count, lowering the threshold, or+ * running `o2b brain reject` explicitly.+ */+export interface DreamGatedRetireEntry {+ readonly pref_id: string;+ readonly topic: string;+ readonly applied_count: number;+ readonly violated_count: number;+ /** Configured threshold the pref's evidence count fell below. */+ readonly threshold: number;+ /** The retire reason the plan computed before the gate fired. */+ readonly attempted_reason: BrainRetiredReason;+}++export interface DreamRunSummary {+ /** `dream-YYYY-MM-DD-HHMMSS`. */+ readonly run_id: string;+ /** False on a true no-op run (no signals, no transitions, no retires). */+ readonly changed: boolean;+ /** Preference ids newly created in `unconfirmed` state. */+ readonly new_unconfirmed: ReadonlyArray<string>;+ /** Preference ids transitioning `unconfirmed β confirmed`. */+ readonly confirmed: ReadonlyArray<string>;+ /** Preferences moved to `retired/` and the reason for each. */+ readonly retired: ReadonlyArray<{ id: string; reason: BrainRetiredReason }>;+ /** Topic slugs where opposite-sign signals are accumulating but no+ * state change happened yet (window not exceeded, or pinned). */+ readonly contradictions: ReadonlyArray<string>;+ /** Signal ids moved from inbox/ into inbox/processed/. */+ readonly moved_to_processed: ReadonlyArray<string>;+ /**+ * Signal ids dropped by Β§6 signal-suppression β a user-rejected+ * retired pref with the same topic blocked them from re-promotion.+ * Each entry is just the signal id (the retired wikilink + reason+ * land in the `signal-suppressed` log event).+ */+ readonly suppressed: ReadonlyArray<string>;+ /**+ * Non-fatal warnings raised during the run. Currently emitted only+ * for `non-primary-dream-run` (the runtime running dream differs+ * from `Brain/_brain.yaml.primary_agent`); the list is the+ * extension point for future advisory checks.+ */+ readonly warnings: ReadonlyArray<DreamWarning>;+ /**+ * Sub-operations the dream pass attempted but could not fully+ * verify. Empty on every clean run; populated by future+ * uncertainty-surfacing paths (v0.10.16).+ */+ readonly uncertain: ReadonlyArray<DreamUncertainEntry>;+ /**+ * Signal clusters held back from promotion by the self-approval+ * guardrail (v0.10.16). Empty when no cluster missed a threshold,+ * or when the guardrail is configured at default values that+ * match pre-v0.10.16 behaviour.+ */+ readonly quarantined: ReadonlyArray<DreamQuarantinedEntry>;+ /**+ * Deterministic pre-dream intent review over active signal clusters.+ * This is audit data for the two-stage gate: intent review explains+ * whether a cluster is ready for the existing main dream review,+ * needs more evidence, or is blocked by conflicting signals.+ */+ readonly intent_reviews: ReadonlyArray<BrainIntentReviewEntry>;+ /**+ * Brain Integrity Suite (v0.12.0). Retires the dream pass planned+ * but declined to execute because the source preference's evidence+ * count fell below `retire.confirmed_evidence_min_threshold`. Empty+ * when the config field is absent (the default).+ */+ readonly gated_retires: ReadonlyArray<DreamGatedRetireEntry>;+ /**+ * Outcome-regression findings (t_d478df53): confirmed preferences+ * whose recent applied events co-occur with failure outcomes. The+ * confidence penalty is already applied in this run's refresh; the+ * list is the explainable staging surface. Empty on outcome-free+ * vaults.+ */+ readonly outcome_regressions: ReadonlyArray<DreamOutcomeRegression>;+ /**+ * Multi-phase dream pipeline (Brain lifecycle suite, Feature 2).+ * Ordered per-phase summaries (close, reconcile, synthesize, heal,+ * log) for a changed run; empty on a no-op run. Additive: existing+ * fields are unchanged.+ */+ readonly phases: ReadonlyArray<DreamPhaseSummary>;+ /**+ * Count-triggered fact rollup ladder (knowledge-intake-and-+ * consolidation, S3). Fired rungs this run, each carrying its counter+ * reset and one needs-llm-step rollup envelope. Empty when no rung+ * crossed its threshold, keeping a below-threshold run byte-identical.+ */+ readonly rollups: ReadonlyArray<RollupLadderEntry>;+ /**+ * Reconcile-phase domain classification (Brain lifecycle suite,+ * Feature 3). Contradictions that stayed unresolved, each tagged with+ * a domain. Source-freshness contradictions that auto-resolved are+ * NOT listed here (they are recorded as `reconcile` log events on a+ * changed run). The legacy `contradictions` field remains a derived+ * topic-only view for back-compat.+ */+ readonly open_questions: ReadonlyArray<DreamOpenQuestion>;+ /** Snapshot file (absent on a no-op run). */+ readonly snapshot_path?: string;+ /** Log file the run summary landed in (absent on a no-op run). */+ readonly log_path?: string;+ /** True iff the run was a dry-run (no on-disk mutations performed). */+ readonly dry_run?: boolean;+}++/**+ * Per-run overrides for the dream gates that otherwise live in+ * `Brain/_brain.yaml` (no-dead-ends, Unit E). An override applies to the+ * one run it is passed to and is NEVER written back, so a targeted pass+ * needs no config edit and no remembering to revert: the stored+ * configuration is byte-identical after a run that overrode it.+ *+ * Deliberately a named field per gate rather than a general config+ * overlay. An audit of the `dream:` and `retire:` blocks found exactly one+ * boolean gate an operator flips to steer a pass+ * (`dream.heal_enrich_enabled`); `retire.confirmed_evidence_min_threshold`+ * is a numeric evidence floor, not a phase switch, and is deliberately+ * absent. A general overlay would let any resolved key be replaced for one+ * run - far more surface than the one switch that motivated this - and the+ * design doc records the narrow form as the default choice.+ */+export interface DreamGateOverrides {+ /**+ * Overrides `dream.heal_enrich_enabled` for this run only. `true` runs+ * the opt-in heal enrichment on a vault whose config leaves it off;+ * `false` skips it on a vault whose config turns it on. Omitted: the+ * configured value decides, exactly as before.+ */+ readonly heal_enrich?: boolean;+}++export interface DreamOptions {+ /** Wall clock for the run. Defaults to `new Date()`. */+ readonly now?: Date;+ /** When true, compute the plan but make no writes. */+ readonly dryRun?: boolean;+ /**+ * Identity of the agent invoking dream. Compared against+ * `Brain/_brain.yaml.primary_agent`; mismatch emits a+ * `non-primary-dream-run` warning and tags the dream summary log+ * event with `non_primary_agent: <name>`. When unset, the warning+ * never fires (back-compat with callers that have not been+ * threaded yet); the CLI always provides the value.+ */+ readonly agentName?: string;+ /**+ * Cooperative deadline (t_06784b8d). Checkpointed at exactly five+ * points, in order: entry, before the pre-run snapshot, before the+ * first mutation, after the mutation writes, and immediately before+ * the workrun is finalised. The last one (no-dead-ends, Unit E) covers+ * the tail that used to run unguarded - the log events, the rollup+ * ledger write, snapshot pruning and the active/lessons regeneration.+ * A tripped guard on the mutation path leaves the durable workrun+ * dangling, which is exactly the integrity contract - the next+ * pass spots and reports it.+ */+ readonly safeguard?: import("./safeguard.ts").Safeguard;+ /**+ * Per-run gate overrides (no-dead-ends, Unit E). Additive: omitted, the+ * run reads every gate from `Brain/_brain.yaml` exactly as before.+ */+ readonly gates?: DreamGateOverrides;+}diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex 0948eb8c..5babb636 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -6,6 +6,20 @@* time (the `--now` parameter). The algorithm is anchored in design* doc Β§7.3 and the per-rule clarifications in Β§7.4.*+ * This module is the ORCHESTRATOR: it sequences the stages and owns the+ * decisions that only make sense with the whole run in view β the run id,+ * the `changed` gate, the snapshot, the workrun lifecycle and the+ * safeguard checkpoints. Each stage's mechanics live in its own module:+ *+ * - `dream-scan.ts` read the `Brain/` tree into memory+ * - `dream-plan-topics.ts` what a cluster of signals on a topic means+ * - `dream-refresh.ts` counters, confidence, unconfirmed β confirmed+ * - `dream-plan-retires.ts` when a preference has outlived its usefulness+ * - `reconcile-outcomes.ts` domain classification of contradictions+ * - `dream-apply.ts` the plan turned into disk state, in order+ * - `dream-report.ts` the run's audit trail in `Brain/log/`+ * - `dream-summary.ts` the {@link DreamRunSummary} the caller sees+ ** Outputs (high level):** - Pre-run snapshot under `Brain/.snapshots/<run_id>.tar.zst`,@@ -34,287 +48,52 @@* - dryRun mode returns the planned summary but performs no writes.*/-import { existsSync, readdirSync, renameSync } from "node:fs";-import { basename, join } from "node:path";+import { existsSync } from "node:fs";+import { join } from "node:path";-import { parseFrontmatter } from "../vault.ts";import { regenerateActiveQuiet } from "./active.ts";-import { regenerateLessonsQuiet } from "./lessons.ts";+import {+ applyDreamPlan,+ gatedRetireSlugs,+ plannedSignalMoveIds,+ type DreamApplyResult,+} from "./dream-apply.ts";+import { planAutoRetires } from "./dream-plan-retires.ts";+import { planTopics } from "./dream-plan-topics.ts";+import type { PlanState } from "./dream-plan.ts";+import { planRefresh, scanApplyEvidence, type RefreshResult } from "./dream-refresh.ts";+import { writeDreamLog } from "./dream-report.ts";+import { scanBrain } from "./dream-scan.ts";+import { buildChangedSummary, buildNoOpSummary } from "./dream-summary.ts";+import type { DreamOptions, DreamRunSummary, DreamWarning } from "./dream-types.ts";import { openWorkrun, WORKRUN_PHASE, type WorkrunHandle } from "./dream-workrun.ts";-import { DREAM_PHASE, type DreamPhase, type DreamPhaseSummary } from "./dream-phases.ts";+import { buildIntentReview } from "./intent-review.ts";+import { regenerateLessonsQuiet } from "./lessons.ts";+import { brainDirsForWrite, dreamWorkrunPath, snapshotPath } from "./paths.ts";+import { loadBrainConfig } from "./policy.ts";+import { buildReconcileOutcomes } from "./reconcile-outcomes.ts";import {planRollupLadder,readRollupLedger,resolveRollupThresholds,- writeRollupLedger,- type RollupLadderEntry,+ type RollupLadderPlan,} from "./rollup-ladder.ts";-import { extractTemporalConstraints } from "./temporal-extract.ts";-import { runHealEnrichment } from "./heal-run.ts";-import { collectEvidenceForSlug } from "./evidence.ts";-import { buildIntentReview, type BrainIntentReviewEntry } from "./intent-review.ts";-import { writePreferenceTxn } from "./preference-txn.ts";-import { appendLogEvent, type BrainLogEntry } from "./log.ts";-import { moveToRetired, parsePreference } from "./preference.ts";-import { parseSignal } from "./signal.ts";-import { isTombstoned } from "./lifecycle/tombstone.ts";-import { appendDecisionChangeReceipt } from "./decisions/receipts.ts";-import {- CHAIN_DECAY_STALE_DAYS,- effectiveStaleThresholdDays,- isLowRecallSupersededAncestor,-} from "./inject-governor.ts";-import { isPinned } from "./pin.ts";import { createSnapshot, pruneSnapshots } from "./snapshot.ts";-import { loadBrainConfig, resolveGuardrails } from "./policy.ts";-import { applySelfApprovalGuardrail } from "./trust/self-approval-guardrail.ts";-import {- brainDirs,- brainDirsForWrite,- dreamWorkrunPath,- preferencePath,- processedSignalPath,- snapshotPath,- vaultRelative,-} from "./paths.ts";-import { countSigns, dominantSignOf } from "./sign.ts";-import { compactRunStamp, isoDate, isoSecond } from "./time.ts";-import {- emptyPlan,- filterWithinWindow,- recordSignalMove,- type CorruptedEntry,- type PlanState,- type PreferenceRecord,- type RetiredRecord,- type DreamQuarantinedEntry,- type ScanResult,- type SignalRecord,-} from "./dream-plan.ts";-import {- planRefresh,- scanApplyEvidence,- type DreamOutcomeRegression,- type RefreshResult,-} from "./dream-refresh.ts";-import { buildReconcileOutcomes } from "./reconcile-outcomes.ts";-import { renderPrefLink } from "./wikilink.ts";-import {- BRAIN_LOG_EVENT_KIND,- BRAIN_PREFERENCE_STATUS,- BRAIN_RETIRED_REASON,- BRAIN_SIGNAL_SIGN,- type BrainConfig,- type BrainPreference,- type BrainRetiredReason,- type BrainSignal,- type BrainSignalSign,- type DreamOpenQuestion,-} from "./types.ts";--// ----- Public types ----------------------------------------------------------/**- * Structured non-fatal warning emitted alongside a dream summary. The- * dream pass still completes when warnings are present; callers- * (CLI / MCP) decide whether to surface them.- */-export interface DreamWarning {- readonly code: string;- readonly message: string;-}--/**- * Entry surfacing a step the dream pass attempted but could not- * fully verify. Distinct from a `DreamWarning` (which flags- * configuration smells): an `uncertain` entry means "I tried, no- * hard error, but I cannot claim the operation completed". Consumed- * by the trust verdict + operator summary (v0.10.16).- */-export interface DreamUncertainEntry {- /** Stable code identifying which sub-operation could not confirm. */- readonly code: string;- /** Optional topic slug or preference id this uncertainty concerns. */- readonly topic?: string;- /** Human-readable explanation. */- readonly message: string;-}--/**- * Brain Integrity Suite (v0.12.0). Entry for a retire that the dream- * pass declined because `retire.confirmed_evidence_min_threshold` was- * set and the source preference's accumulated evidence count fell- * below it. The pref stays in `preferences/`; the operator can lift- * the gate by raising the evidence count, lowering the threshold, or- * running `o2b brain reject` explicitly.- */-export interface DreamGatedRetireEntry {- readonly pref_id: string;- readonly topic: string;- readonly applied_count: number;- readonly violated_count: number;- /** Configured threshold the pref's evidence count fell below. */- readonly threshold: number;- /** The retire reason the plan computed before the gate fired. */- readonly attempted_reason: BrainRetiredReason;-}--export interface DreamRunSummary {- /** `dream-YYYY-MM-DD-HHMMSS`. */- readonly run_id: string;- /** False on a true no-op run (no signals, no transitions, no retires). */- readonly changed: boolean;- /** Preference ids newly created in `unconfirmed` state. */- readonly new_unconfirmed: ReadonlyArray<string>;- /** Preference ids transitioning `unconfirmed β confirmed`. */- readonly confirmed: ReadonlyArray<string>;- /** Preferences moved to `retired/` and the reason for each. */- readonly retired: ReadonlyArray<{ id: string; reason: BrainRetiredReason }>;- /** Topic slugs where opposite-sign signals are accumulating but no- * state change happened yet (window not exceeded, or pinned). */- readonly contradictions: ReadonlyArray<string>;- /** Signal ids moved from inbox/ into inbox/processed/. */- readonly moved_to_processed: ReadonlyArray<string>;- /**- * Signal ids dropped by Β§6 signal-suppression β a user-rejected- * retired pref with the same topic blocked them from re-promotion.- * Each entry is just the signal id (the retired wikilink + reason- * land in the `signal-suppressed` log event).- */- readonly suppressed: ReadonlyArray<string>;- /**- * Non-fatal warnings raised during the run. Currently emitted only- * for `non-primary-dream-run` (the runtime running dream differs- * from `Brain/_brain.yaml.primary_agent`); the list is the- * extension point for future advisory checks.- */- readonly warnings: ReadonlyArray<DreamWarning>;- /**- * Sub-operations the dream pass attempted but could not fully- * verify. Empty on every clean run; populated by future- * uncertainty-surfacing paths (v0.10.16).- */- readonly uncertain: ReadonlyArray<DreamUncertainEntry>;- /**- * Signal clusters held back from promotion by the self-approval- * guardrail (v0.10.16). Empty when no cluster missed a threshold,- * or when the guardrail is configured at default values that- * match pre-v0.10.16 behaviour.- */- readonly quarantined: ReadonlyArray<DreamQuarantinedEntry>;- /**- * Deterministic pre-dream intent review over active signal clusters.- * This is audit data for the two-stage gate: intent review explains- * whether a cluster is ready for the existing main dream review,- * needs more evidence, or is blocked by conflicting signals.- */- readonly intent_reviews: ReadonlyArray<BrainIntentReviewEntry>;- /**- * Brain Integrity Suite (v0.12.0). Retires the dream pass planned- * but declined to execute because the source preference's evidence- * count fell below `retire.confirmed_evidence_min_threshold`. Empty- * when the config field is absent (the default).- */- readonly gated_retires: ReadonlyArray<DreamGatedRetireEntry>;- /**- * Outcome-regression findings (t_d478df53): confirmed preferences- * whose recent applied events co-occur with failure outcomes. The- * confidence penalty is already applied in this run's refresh; the- * list is the explainable staging surface. Empty on outcome-free- * vaults.- */- readonly outcome_regressions: ReadonlyArray<DreamOutcomeRegression>;- /**- * Multi-phase dream pipeline (Brain lifecycle suite, Feature 2).- * Ordered per-phase summaries (close, reconcile, synthesize, heal,- * log) for a changed run; empty on a no-op run. Additive: existing- * fields are unchanged.- */- readonly phases: ReadonlyArray<DreamPhaseSummary>;- /**- * Count-triggered fact rollup ladder (knowledge-intake-and-- * consolidation, S3). Fired rungs this run, each carrying its counter- * reset and one needs-llm-step rollup envelope. Empty when no rung- * crossed its threshold, keeping a below-threshold run byte-identical.- */- readonly rollups: ReadonlyArray<RollupLadderEntry>;- /**- * Reconcile-phase domain classification (Brain lifecycle suite,- * Feature 3). Contradictions that stayed unresolved, each tagged with- * a domain. Source-freshness contradictions that auto-resolved are- * NOT listed here (they are recorded as `reconcile` log events on a- * changed run). The legacy `contradictions` field remains a derived- * topic-only view for back-compat.- */- readonly open_questions: ReadonlyArray<DreamOpenQuestion>;- /** Snapshot file (absent on a no-op run). */- readonly snapshot_path?: string;- /** Log file the run summary landed in (absent on a no-op run). */- readonly log_path?: string;- /** True iff the run was a dry-run (no on-disk mutations performed). */- readonly dry_run?: boolean;-}--/**- * Per-run overrides for the dream gates that otherwise live in- * `Brain/_brain.yaml` (no-dead-ends, Unit E). An override applies to the- * one run it is passed to and is NEVER written back, so a targeted pass- * needs no config edit and no remembering to revert: the stored- * configuration is byte-identical after a run that overrode it.- *- * Deliberately a named field per gate rather than a general config- * overlay. An audit of the `dream:` and `retire:` blocks found exactly one- * boolean gate an operator flips to steer a pass- * (`dream.heal_enrich_enabled`); `retire.confirmed_evidence_min_threshold`- * is a numeric evidence floor, not a phase switch, and is deliberately- * absent. A general overlay would let any resolved key be replaced for one- * run - far more surface than the one switch that motivated this - and the- * design doc records the narrow form as the default choice.- */-export interface DreamGateOverrides {- /**- * Overrides `dream.heal_enrich_enabled` for this run only. `true` runs- * the opt-in heal enrichment on a vault whose config leaves it off;- * `false` skips it on a vault whose config turns it on. Omitted: the- * configured value decides, exactly as before.- */- readonly heal_enrich?: boolean;-}--export interface DreamOptions {- /** Wall clock for the run. Defaults to `new Date()`. */- readonly now?: Date;- /** When true, compute the plan but make no writes. */- readonly dryRun?: boolean;- /**- * Identity of the agent invoking dream. Compared against- * `Brain/_brain.yaml.primary_agent`; mismatch emits a- * `non-primary-dream-run` warning and tags the dream summary log- * event with `non_primary_agent: <name>`. When unset, the warning- * never fires (back-compat with callers that have not been- * threaded yet); the CLI always provides the value.- */- readonly agentName?: string;- /**- * Cooperative deadline (t_06784b8d). Checkpointed at exactly five- * points, in order: entry, before the pre-run snapshot, before the- * first mutation, after the mutation writes, and immediately before- * the workrun is finalised. The last one (no-dead-ends, Unit E) covers- * the tail that used to run unguarded - the log events, the rollup- * ledger write, snapshot pruning and the active/lessons regeneration.- * A tripped guard on the mutation path leaves the durable workrun- * dangling, which is exactly the integrity contract - the next- * pass spots and reports it.- */- readonly safeguard?: import("./safeguard.ts").Safeguard;- /**- * Per-run gate overrides (no-dead-ends, Unit E). Additive: omitted, the- * run reads every gate from `Brain/_brain.yaml` exactly as before.- */- readonly gates?: DreamGateOverrides;-}--// ----- Internal scan types ------------------------------------------------+import { compactRunStamp, isoDate } from "./time.ts";+import type { BrainConfig } from "./types.ts";++// ----- Public surface ------------------------------------------------------++export type {+ DreamGateOverrides,+ DreamGatedRetireEntry,+ DreamOptions,+ DreamRunSummary,+ DreamUncertainEntry,+ DreamWarning,+} from "./dream-types.ts";+export { shouldGateRetireFromConfirmed } from "./dream-apply.ts";+export { scanBrain } from "./dream-scan.ts";// ----- Main entry ----------------------------------------------------------@@ -331,23 +110,10 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {let runId = formatRunId(now);const wikilinkToRun = `[[Brain/log/${isoDate(now)}]]`;- // Collect non-fatal warnings raised during the run. The- // non-primary-dream-run check is the first one: when the caller- // declares an agent name and it differs from the vault's declared- // primary, surface a structured warning. We do NOT abort β the- // declaration is observability, not access control.- const warnings: DreamWarning[] = [];const callerAgent = opts.agentName?.trim() ?? "";const isNonPrimary =cfg.primary_agent !== null && callerAgent.length > 0 && callerAgent !== cfg.primary_agent;- if (isNonPrimary) {- warnings.push({- code: "non-primary-dream-run",- message:- `dream run from agent '${callerAgent}', but primary is ` +- `'${cfg.primary_agent}'. Convention violation, run proceeds.`,- });- }+ const warnings = collectWarnings(isNonPrimary, callerAgent, cfg.primary_agent);// 0. Scan the whole Brain/ tree. Corrupted files (frontmatter// parse-errors) are surfaced separately so the planning phase@@ -358,7 +124,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// 1-2. Plan per-topic transitions: new unconfirmed preferences,// same-sign noted-redundant moves, rebuttal accumulation.- const plan = planTopics(scan, cfg, now, wikilinkToRun);+ const plan = planTopics(scan, cfg, now);// 3. Plan refresh: applied / violated / last_evidence / confidence,// and unconfirmed β confirmed promotion. We need the log of all@@ -373,8 +139,10 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// retire.planAutoRetires(scan, cfg, now, plan, refresh);- // 5. Plan signal moves (inbox/ β processed/).- planSignalMoves(scan, plan);+ // 5. Β§7.3 step "move consumed signals out of inbox/" needs no pass of+ // its own: both routes that consume a signal - the topic loop and+ // the active-pref handler - already enqueued it into+ // `plan.signalsToMove` at the moment they decided to consume it.// Reconcile phase (F3): classify each contradiction topic into a// domain. Source-freshness with a clear gap auto-resolves (recorded,@@ -390,63 +158,22 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// effect is a rollup still counts as changed; below threshold it fires// nothing and the ledger is never written, so the run stays// byte-identical.- let rollupPlan = planRollupLadder({- factCount: scan.preferences.length,- ledger: readRollupLedger(vault),- thresholds: resolveRollupThresholds(cfg),- runId,- });+ let rollupPlan = buildRollupPlan(vault, cfg, scan.preferences.length, runId);- // Decide if anything is going to change. We treat any of the- // following as a state change:- // - a new unconfirmed pref- // - a refreshed pref (counters/confidence/status changed)- // - a retire- // - a same-sign signal noted on an active pref (move + log)- // - a corrupted frontmatter (we want the skip event recorded)- // - any pinned-rebut-attempt warning- // - a fired rollup-ladder rung (S3)- const changed =- plan.newUnconfirmed.length > 0 ||- refresh.confirmed.size > 0 ||- refresh.updated.size > 0 ||- plan.retires.length > 0 ||- plan.notedRedundant.length > 0 ||- plan.signalsToMove.size > 0 ||- plan.retainPinned.length > 0 ||- plan.signalsSuppressed.length > 0 ||- // v0.10.16: quarantine is a recorded decision (deferred-but-noted),- // so a run that produces only quarantine entries is still a- // meaningful run from the operator's perspective.- plan.quarantined.length > 0 ||- rollupPlan.fired ||- scan.corrupted.length > 0;-- if (!changed) {+ if (!hasStateChange(plan, refresh, scan.corrupted.length, rollupPlan)) {if (!dryRun) {regenerateActiveQuiet(vault, { now });regenerateLessonsQuiet(vault, { now });}- return Object.freeze({- run_id: runId,- changed: false,- new_unconfirmed: [],- confirmed: [],- retired: [],- contradictions: [...plan.contradictionTopics],- moved_to_processed: [],- suppressed: [],- warnings: Object.freeze([...warnings]),- uncertain: Object.freeze([] as ReadonlyArray<DreamUncertainEntry>),- quarantined: Object.freeze([...plan.quarantined]),- intent_reviews: Object.freeze([...intentReview.reviews]),- gated_retires: Object.freeze([] as ReadonlyArray<DreamGatedRetireEntry>),- outcome_regressions: Object.freeze([...refresh.outcomeRegressions]),- phases: Object.freeze([] as ReadonlyArray<DreamPhaseSummary>),- rollups: Object.freeze([] as ReadonlyArray<RollupLadderEntry>),- open_questions: Object.freeze([...reconcile.openQuestions]),- ...(dryRun ? { dry_run: true } : {}),- } satisfies DreamRunSummary);+ return buildNoOpSummary({+ runId,+ dryRun,+ plan,+ refresh,+ reconcile,+ intentReviews: intentReview.reviews,+ warnings,+ });}// ---- Execute --------------------------------------------------------@@ -463,44 +190,23 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// pre-collision runId; if the collision check corrected it, rebuild the// plan so every target_path embeds the final run_id.if (rollupPlan.fired && runId !== baseRunId) {- rollupPlan = planRollupLadder({- factCount: scan.preferences.length,- ledger: readRollupLedger(vault),- thresholds: resolveRollupThresholds(cfg),- runId,- });+ rollupPlan = buildRollupPlan(vault, cfg, scan.preferences.length, runId);}- const snap = createSnapshot(vault, runId);- snapshotPathStr = snap.path;+ snapshotPathStr = createSnapshot(vault, runId).path;}- // Order of operations matters for the on-disk invariants:- // 1. Write new unconfirmed preferences (so signal moves can find- // them).- // 2. Apply refresh (counters, confidence, promotion) to existing- // preferences.- // 3. Move retiring preferences out (after the refresh has had a- // chance to surface the most recent counters in the retired- // file). NOTE: refresh skips entries that will retire.- // 4. Move consumed signals into `processed/`.- // 5. Emit log entries (noted-redundant, retain-pinned,- // skip-corrupted-frontmatter, dream summary).- const moved: string[] = [];- // F6: count of user pages the opt-in heal phase enriched (0 unless- // the heal gate resolved on - see `healEnrichEnabled`).- let healEnriched = 0;- // v0.12.0 Brain Integrity Suite: declined retires accumulate here.- // Always declared (even when no gate is configured) so the eventual- // DreamRunSummary.gated_retires field is consistently an array.- const gatedRetires: DreamGatedRetireEntry[] = [];-// v0.12.0 Brain Integrity Suite: durable workrun for the dream pass.// Opened lazily on the mutation path (no workrun on dry-run or// no-op early-return). The handle is null until the exec branch- // claims it; `finally` finalises if non-null.+ // claims it; it is finalised immediately before the summary is built.let workrun: WorkrunHandle | null = null;opts.safeguard?.checkpoint();- if (!dryRun) {+ let exec: DreamApplyResult;+ if (dryRun) {+ // Dry-run still reports the move list so the caller's summary is+ // accurate, but it does not touch disk.+ exec = { moved: plannedSignalMoveIds(plan), gatedRetires: [], healEnriched: 0 };+ } else {workrun = openWorkrun(vault, runId);// Truthful checkpoints (no-dead-ends, Unit E). A marker means every// durable effect attributed to that phase is already on disk, so a@@ -512,223 +218,17 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// where that phase's writes land; see the emission notes there.workrun.checkpoint(WORKRUN_PHASE.clusterComplete);workrun.checkpoint(WORKRUN_PHASE.closeComplete);- }-- if (!dryRun) {- // Edit-history (F4): every dream-pass write records its content- // before/after so a preference's evolution stays auditable. The- // agent of record is whoever invoked the dream run.- const historyOpts = { agent: opts.agentName ?? "dream", now: () => now };- for (const np of plan.newUnconfirmed) {- // Fresh pref has no apply-evidence yet; recentApplied/recentViolated- // start empty and stay so until the next dream pass after the- // first `brain_apply_evidence` event.- // v0.12.0 Brain Integrity Suite: route every dream-pass write- // through writePreferenceTxn so _revision auto-stamps and- // _content_hash lands automatically on confirmed promotions.- // Empty expectations array - dream's plan-time logic has- // already decided to proceed; the txn just owns the bookkeeping.- writePreferenceTxn(- vault,- {- slug: np.slug,- topic: np.topic,- principle: np.principle,- created_at: isoSecond(now),- unconfirmed_until: isoSecond(addDays(now, cfg.dream.unconfirmed_window_days)),- status: BRAIN_PREFERENCE_STATUS.unconfirmed,- evidenced_by: np.evidencedBy,- // No evidence yet β Wilson lower bound on (0, 0) is 0. Pre-- // seed the field so refresh on the next pass does not have- // to treat `null` as "needs update" (which would lift- // `changed: false` no-ops into spurious rewrites).- confidence_value: 0,- recentApplied: [],- recentViolated: [],- ...(np.scope ? { scope: np.scope } : {}),- ...(np.supersedes ? { supersedes: np.supersedes } : {}),- // F5: bi-temporal validity extracted from the source signal.- ...(np.valid_from ? { valid_from: np.valid_from } : {}),- ...(np.valid_until ? { valid_until: np.valid_until } : {}),- },- [],- { overwrite: false },- historyOpts,- );- }-- for (const update of refresh.updated.values()) {- // Rebuild the evidence slice from the log on every pass so the- // pref body stays in sync with the counters even when the- // counters themselves stayed put (e.g. dropping the- // v0.9.x placeholder body during a no-counter-change run).- const ev = collectEvidenceForSlug(vault, update.slug, {- sinceIso: update.created_at,- });- // Same txn route as the newUnconfirmed loop: auto-stamps- // _revision (existing+1) and _content_hash on confirmed status.- // The freshness trend was classified at PLAN time (planRefresh)- // so the no-op pre-flight rendered these exact bytes.- writePreferenceTxn(- vault,- {- slug: update.slug,- topic: update.topic,- principle: update.principle,- created_at: update.created_at,- unconfirmed_until: update.unconfirmed_until,- status: update.status,- evidenced_by: update.evidenced_by,- confirmed_at: update.confirmed_at,- applied_count: update.applied_count,- violated_count: update.violated_count,- last_evidence_at: update.last_evidence_at,- confidence: update.confidence,- confidence_value: update.confidence_value,- pinned: update.pinned,- recentApplied: ev.applied,- recentViolated: ev.violated,- ...(update.freshness_trend !== undefined- ? { freshness_trend: update.freshness_trend }- : {}),- ...(update.scope ? { scope: update.scope } : {}),- },- [],- { overwrite: true },- historyOpts,- );- }-- // Belief lifecycle suite (B4): the preference-confidence update path- // emits a decision-change receipt for each material confidence band- // change captured this pass. `bandDrops` is the existing, already-- // computed set of material weakenings (a band actually dropped), so- // this rides on data the refresh already produced without touching its- // byte-identical no-op guarantees. The receipt's idempotency key- // (subject + before + after) makes a re-run a no-op. Fail-soft.- for (const d of refresh.bandDrops) {- const before = `confidence:${d.previous}${d.previous_value !== null ? `(${d.previous_value.toFixed(2)})` : ""}`;- const after = `confidence:${d.next}(${d.next_value.toFixed(2)})`;- try {- appendDecisionChangeReceipt(vault, {- subject: d.id,- before,- after,- confidenceDelta: d.previous_value !== null ? d.next_value - d.previous_value : null,- actor: opts.agentName ?? "dream",- rationale: `applied ${d.applied} / violated ${d.violated}`,- reasonCode: "confidence-refresh",- ts: now.toISOString(),- });- } catch {- // Accountability mirror is best-effort; the refreshed preference- // bytes remain authoritative.- }- }-- // Synthesize is durable here and nowhere earlier: every new- // unconfirmed preference, every refreshed preference and every- // confidence receipt has landed. `promote_complete` is the pre-F2- // name for the same writes, so it moves with it rather than being- // left behind claiming a batch that had not started.- workrun?.checkpoint(WORKRUN_PHASE.promoteComplete);- workrun?.checkpoint(WORKRUN_PHASE.synthesizeComplete);-- for (const r of plan.retires) {- const fromPath = preferencePath(vault, r.slug);- if (!existsSync(fromPath)) continue;- // v0.12.0 Brain Integrity Suite: destructive-from-confirmed gate.- // When the operator has set retire.confirmed_evidence_min_threshold,- // refuse to retire a confirmed (unpinned) pref whose accumulated- // evidence count is below the configured floor. Operator-initiated- // retires bypass.- const gateThreshold = cfg.retire.confirmed_evidence_min_threshold;- if (gateThreshold !== undefined && gateThreshold > 0) {- try {- const existing = parsePreference(fromPath);- if (shouldGateRetireFromConfirmed(existing, r.reason, gateThreshold)) {- gatedRetires.push({- pref_id: existing.id,- topic: existing.topic,- applied_count: existing.applied_count,- violated_count: existing.violated_count,- threshold: gateThreshold,- attempted_reason: r.reason,- });- continue;- }- } catch {- // Parse failure - fall through to the normal retire path- // (moveToRetired will surface the error through stderr below).- }- }- try {- moveToRetired(vault, fromPath, r.reason, {- now,- retired_by: wikilinkToRun,- ...(r.supersededBy ? { superseded_by: r.supersededBy } : {}),- });- // Belief lifecycle suite (A4): record the accelerated retirement of- // a low-recall superseded ancestor as a dedicated audit event.- if (r.chainDecay) {- appendLogEvent(vault, {- timestamp: isoSecond(now),- eventType: BRAIN_LOG_EVENT_KIND.chainDecay,- body: {- preference: `[[ret-${r.slug}]]`,- reason: r.reason,- stale_days: String(CHAIN_DECAY_STALE_DAYS),- },- });- }- } catch (err) {- // A retire failure is logged via the `skip-corrupted-frontmatter`- // pathway only if it stemmed from a parse error during the- // plan; here the file may have been moved already (rare race).- // Surface the cause so an operator chasing a missing retire can- // see which slug tripped.- process.stderr.write(- `warning: retire stale pref ${r.slug} failed: ${(err as Error).message}\n`,- );- }- }-- // Every planned retire has been moved (or explicitly gated) by here.- workrun?.checkpoint(WORKRUN_PHASE.retireComplete);-- for (const sig of plan.signalsToMove.values()) {- const dest = processedSignalPath(vault, sig.date, sig.slug);- try {- renameSync(sig.path, dest);- moved.push(sig.id);- } catch (err) {- // Best-effort: a missing source signal (already moved) is- // benign on rerun. Still surface so a real I/O issue is visible.- process.stderr.write(- `warning: move signal ${sig.id} to processed/ failed: ${(err as Error).message}\n`,- );- }- }-- // Heal phase (F6): opt-in deterministic vault enrichment, run after- // the retire/move mutations (heal-after-mutations). Off by default so- // the default install stays byte-identical; a failure is a warning,- // never fatal to the dream pass.- if (healEnrichEnabled) {- try {- healEnriched = runHealEnrichment(vault).enriched;- } catch (err) {- process.stderr.write(`warning: heal enrichment failed: ${(err as Error).message}\n`);- }- }- // Heal's second half (the optional enrichment) is durable here; its- // first half was the retire loop above. The marker sits at the later- // of the two, so it is never a claim about work still to come.- workrun?.checkpoint(WORKRUN_PHASE.healComplete);- } else {- // Dry-run still reports the move list so the caller's summary is- // accurate, but it does not touch disk.- for (const sig of plan.signalsToMove.values()) moved.push(sig.id);+ exec = applyDreamPlan({+ vault,+ cfg,+ now,+ plan,+ refresh,+ agentName: opts.agentName,+ wikilinkToRun,+ healEnrichEnabled,+ workrun,+ });}// Post-mutation safeguard checkpoint: every state-changing write for@@ -741,189 +241,27 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// exclude retires the destructive-from-confirmed gate skipped, or// the next dream pass would parse a `pref-foo` log claiming the// pref was retired while the file is still in `preferences/`.- const gatedSlugs = new Set(gatedRetires.map((g) => g.pref_id.replace(/^pref-/, "")));+ const gatedSlugs = gatedRetireSlugs(exec.gatedRetires);- // Emit log entries: skip-corrupted-frontmatter first (chronological- // sense: corruption was detected during planning), then per-topic- // events (noted-redundant), then run summary last.if (!dryRun) {- let logCursorMs = now.getTime();- const nextStamp = (): string => {- const ts = new Date(logCursorMs);- logCursorMs += 1000; // increment per emission so headings stay distinct- return isoSecond(ts);- };-- for (const corrupt of scan.corrupted) {- writeEvent(vault, {- timestamp: nextStamp(),- eventType: BRAIN_LOG_EVENT_KIND.skipCorruptedFrontmatter,- body: {- path: vaultRelative(corrupt.path, vault),- },- });- }-- for (const noted of plan.notedRedundant) {- writeEvent(vault, {- timestamp: nextStamp(),- eventType: BRAIN_LOG_EVENT_KIND.notedRedundant,- body: {- preference: noted.preference,- signal: noted.signal,- },- });- }-- // Reconcile phase (F3): one event per open question + per- // auto-resolution. Persisted only on this changed path so a no-op- // run stays byte-identical.- for (const q of reconcile.openQuestions) {- writeEvent(vault, {- timestamp: nextStamp(),- eventType: BRAIN_LOG_EVENT_KIND.reconcile,- body: {- topic: q.topic,- domain: q.domain,- reason: q.reason,- ...(q.scope ? { scope: q.scope } : {}),- positives: String(q.positive_count),- negatives: String(q.negative_count),- },- });- }- for (const r of reconcile.autoResolved) {- writeEvent(vault, {- timestamp: nextStamp(),- eventType: BRAIN_LOG_EVENT_KIND.reconcile,- body: {- topic: r.topic,- domain: r.domain,- resolution: "auto-resolved",- winner_sign: r.winner_sign,- margin_days: String(r.margin_days),- },- });- }- // Reconcile's only durable artifact is the pair of event loops just- // above: the classification itself is in-memory and vanishes with the- // process. The pre-mutation burst used to claim this phase complete- // before a single preference had been written, which is precisely the- // journal-lies failure this release removes. The marker therefore- // trails `heal_complete` in the file - emission order is execution- // order, not the reporting order of DREAM_PHASE_ORDER.- workrun?.checkpoint(WORKRUN_PHASE.reconcileComplete);-- for (const suppressed of plan.signalsSuppressed) {- writeEvent(vault, {- timestamp: nextStamp(),- eventType: BRAIN_LOG_EVENT_KIND.signalSuppressed,- body: {- signal: suppressed.signal,- retired: suppressed.retired,- topic: suppressed.topic,- reason: suppressed.reason,- },- });- }-- for (const retain of plan.retainPinned) {- // `retain-pinned` is not in the strict BrainLogEventKind enum- // (the design doc names a generic `retire` event with an- // attempted-but-blocked reason). We log it as a `retire` event- // with a `blocked: pinned` payload field so the parser- // round-trips cleanly and the doctor command can flag it.- writeEvent(vault, {- timestamp: nextStamp(),- eventType: BRAIN_LOG_EVENT_KIND.retire,- body: {- preference: retain.preference,- reason: retain.reason,- blocked: "pinned",- },- });- }-- // Summary event last. Link rendering threads the in-memory- // principle alongside the id so the digest / Obsidian view can- // hover-preview the rule without an extra file open.- const slugToPrefPrinciple = new Map<string, string>();- for (const rec of scan.preferences) {- const recSlug = rec.pref.id.startsWith("pref-")- ? rec.pref.id.slice("pref-".length)- : rec.pref.id;- slugToPrefPrinciple.set(recSlug, rec.pref.principle);- }- const newUnconfirmedIds = plan.newUnconfirmed.map((p) =>- renderPrefLink({ id: `pref-${p.slug}`, principle: p.principle }),- );- const confirmedIds = Array.from(refresh.confirmed.values()).map((slug) =>- renderPrefLink({- id: `pref-${slug}`,- principle: refresh.updated.get(slug)?.principle ?? slugToPrefPrinciple.get(slug) ?? "",- }),- );- const retiredEntries = plan.retires- .filter((r) => !gatedSlugs.has(r.slug))- .map(- (r) => `${renderPrefLink({ id: `ret-${r.slug}`, principle: r.principle })} (${r.reason})`,- );- const summaryBody: Record<string, string | ReadonlyArray<string>> = {- run_id: runId,- };- if (newUnconfirmedIds.length > 0) summaryBody["new_unconfirmed"] = newUnconfirmedIds;- if (confirmedIds.length > 0) summaryBody["confirmed"] = confirmedIds;- if (retiredEntries.length > 0) summaryBody["retired"] = retiredEntries;- if (moved.length > 0) summaryBody["moved_to_processed"] = moved;- if (plan.contradictionTopics.size > 0) {- summaryBody["contradictions"] = Array.from(plan.contradictionTopics);- }- if (plan.signalsSuppressed.length > 0) {- summaryBody["suppressed"] = plan.signalsSuppressed.map((s) => `${s.signal} β ${s.retired}`);- }- if (refresh.bandDrops.length > 0) {- // Format matches the digest's tolerant `parseShiftLine` parser:- // `[[pref-β¦|principle]] <from> -> <to> (applied: N, violated: M)`.- summaryBody["confidence_shifts"] = refresh.bandDrops.map((d) =>- [- renderPrefLink({ id: d.id, principle: d.principle }),- d.previous,- "->",- d.next,- `(applied: ${d.applied}, violated: ${d.violated})`,- ].join(" "),- );- }- if (isNonPrimary) {- // Audit-trail row matching the structured warning. Stored- // alongside `run_id` so a non-primary dream pass is greppable in- // the log without parsing the structured warnings array.- summaryBody["non_primary_agent"] = callerAgent;- }- // S3: record each fired rollup rung's counter reset in the dream- // report. Absent below threshold, so a non-firing run's summary event- // is byte-identical to the pre-rollup behaviour.- if (rollupPlan.fired) {- summaryBody["rollups"] = rollupPlan.entries.map(- (e) => `${e.tier} -> ${e.produces} (${e.fromCount} -> ${e.toCount})`,- );- }-- writeEvent(vault, {- timestamp: nextStamp(),- eventType: BRAIN_LOG_EVENT_KIND.dream,- body: summaryBody,+ writeDreamLog({+ vault,+ now,+ runId,+ scan,+ plan,+ refresh,+ reconcile,+ rollupPlan,+ moved: exec.moved,+ gatedSlugs,+ isNonPrimary,+ callerAgent,+ workrun,});- // S3: persist the advanced rollup-ladder counters only when a rung- // fired. A below-threshold run never touches the ledger, so its- // absence is the byte-identical opt-out.- if (rollupPlan.fired) writeRollupLedger(vault, rollupPlan.ledger);- }-- // Prune snapshots after the run so the new archive itself counts- // toward retention.- if (!dryRun) {+ // Prune snapshots after the run so the new archive itself counts+ // toward retention.try {pruneSnapshots(vault, cfg.snapshots.retention_count);} catch (err) {@@ -951,712 +289,98 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// spot. `workrun` is null on dry-run / pre-mutation paths.workrun?.finalize();- // Multi-phase dream (F2): structured per-phase summaries for a changed- // run. Metrics are integer counters derived from the plan/refresh that- // already ran; additive keys may appear in later versions.- const activeSignalCount = scan.signals.filter((s) => s.active).length;- const retiredThisRun = plan.retires.filter((r) => !gatedSlugs.has(r.slug)).length;- const phases: ReadonlyArray<DreamPhaseSummary> = Object.freeze([- phaseSummary(DREAM_PHASE.close, {- active_signals: activeSignalCount,- preferences: scan.preferences.length,- retired_files: scan.retired.length,- }),- phaseSummary(DREAM_PHASE.reconcile, {- contradictions: plan.contradictionTopics.size,- open_questions: reconcile.openQuestions.length,- auto_resolved: reconcile.autoResolved.length,- }),- phaseSummary(DREAM_PHASE.synthesize, {- new_unconfirmed: plan.newUnconfirmed.length,- confirmed: refresh.confirmed.size,- }),- phaseSummary(DREAM_PHASE.heal, {- retired: retiredThisRun,- enriched: healEnriched,- }),- phaseSummary(DREAM_PHASE.log, {- moved: moved.length,- suppressed: plan.signalsSuppressed.length,- }),- ]);-- return Object.freeze({- run_id: runId,- changed: true,- phases,- rollups: Object.freeze([...rollupPlan.entries]),- open_questions: Object.freeze([...reconcile.openQuestions]),- new_unconfirmed: plan.newUnconfirmed.map((p) => `pref-${p.slug}`),- confirmed: Array.from(refresh.confirmed.values()).map((s) => `pref-${s}`),- retired: plan.retires- .filter((r) => !gatedSlugs.has(r.slug))- .map((r) => ({ id: `ret-${r.slug}`, reason: r.reason })),- contradictions: Array.from(plan.contradictionTopics),- moved_to_processed: moved,- suppressed: plan.signalsSuppressed.map((s) =>- s.signal.replace(/^\[\[/, "").replace(/\]\]$/, ""),- ),- warnings: Object.freeze([...warnings]),- uncertain: Object.freeze([] as ReadonlyArray<DreamUncertainEntry>),- quarantined: Object.freeze([...plan.quarantined]),- intent_reviews: Object.freeze([...intentReview.reviews]),- gated_retires: Object.freeze([...gatedRetires]),- outcome_regressions: Object.freeze([...refresh.outcomeRegressions]),- ...(snapshotPathStr ? { snapshot_path: snapshotPathStr } : {}),- ...(dryRun+ return buildChangedSummary({+ runId,+ // `brainDirsForWrite` asserts the vault is writable, so the log path+ // is resolved only on the branch that actually wrote to it.+ runTail: dryRun? { dry_run: true }- : { log_path: join(brainDirsForWrite(vault).log, `${isoDate(now)}.md`) }),- } satisfies DreamRunSummary);-}--/**- * Brain Integrity Suite (v0.12.0). Pure decision function for the- * destructive-from-confirmed gate. Exported so the gate logic can be- * unit-tested without driving a full dream run.- *- * Returns `true` when the candidate retire MUST be held back. The- * caller is responsible for recording a {@link DreamGatedRetireEntry}- * and skipping the actual `moveToRetired` call.- */-export function shouldGateRetireFromConfirmed(- existing: BrainPreference,- reason: BrainRetiredReason,- threshold: number | undefined,-): boolean {- if (threshold === undefined || threshold <= 0) return false;- if (reason === BRAIN_RETIRED_REASON.userRejected) return false;- if (reason === BRAIN_RETIRED_REASON.mergedInto) return false;- if (existing.status !== BRAIN_PREFERENCE_STATUS.confirmed) return false;- if (existing.pinned) return false;- const evidenceCount = (existing.applied_count ?? 0) + (existing.violated_count ?? 0);- return evidenceCount < threshold;+ : { log_path: join(brainDirsForWrite(vault).log, `${isoDate(now)}.md`) },+ scan,+ plan,+ refresh,+ reconcile,+ rollupPlan,+ intentReviews: intentReview.reviews,+ warnings,+ gatedRetires: exec.gatedRetires,+ gatedSlugs,+ moved: exec.moved,+ healEnriched: exec.healEnriched,+ snapshotPath: snapshotPathStr,+ });}-// ----- Scan ----------------------------------------------------------------/**- * Read the whole `Brain/` tree into memory. Pure: it opens no writer, takes- * no clock and touches nothing on disk, which is why it is the one part of- * the pass that is provably runnable on its own (see `dream-step.ts`).+ * Non-fatal warnings raised during the run. The non-primary-dream-run+ * check is the first one: when the caller declares an agent name and it+ * differs from the vault's declared primary, surface a structured+ * warning. We do NOT abort β the declaration is observability, not+ * access control.*/-export function scanBrain(vault: string): ScanResult {- const dirs = brainDirs(vault);- const signals: SignalRecord[] = [];- const preferences: PreferenceRecord[] = [];- const retired: RetiredRecord[] = [];- const corrupted: CorruptedEntry[] = [];-- if (existsSync(dirs.inbox)) {- for (const name of readdirSync(dirs.inbox)) {- if (!name.endsWith(".md")) continue;- const full = join(dirs.inbox, name);- // Belief lifecycle suite (t_7d5a3589): a tombstoned signal is- // excluded from the dream pass so it is never re-clustered.- if (isTombstoned(parseFrontmatter(full)[0])) continue;- try {- const sig = parseSignal(full);- signals.push({ path: full, signal: sig, active: true });- } catch {- corrupted.push({ path: full });- }- }- }- if (existsSync(dirs.processed)) {- for (const name of readdirSync(dirs.processed)) {- if (!name.endsWith(".md")) continue;- const full = join(dirs.processed, name);- if (isTombstoned(parseFrontmatter(full)[0])) continue;- try {- const sig = parseSignal(full);- signals.push({ path: full, signal: sig, active: false });- } catch {- corrupted.push({ path: full });- }- }- }- if (existsSync(dirs.preferences)) {- for (const name of readdirSync(dirs.preferences)) {- if (!name.endsWith(".md")) continue;- const full = join(dirs.preferences, name);- const rawMeta = parseFrontmatter(full)[0];- if (isTombstoned(rawMeta)) continue;- // Belief lifecycle suite (A4): capture the raw superseded_by pointer- // (the typed parser drops it) so accelerated chain decay can see a- // temporally-superseded ancestor.- const supersededBy =- typeof rawMeta["superseded_by"] === "string" && rawMeta["superseded_by"] !== ""- ? (rawMeta["superseded_by"] as string)- : null;- try {- const pref = parsePreference(full);- preferences.push({ path: full, pref, supersededBy });- } catch {- corrupted.push({ path: full });- }- }- }- if (existsSync(dirs.retired)) {- for (const name of readdirSync(dirs.retired)) {- if (!name.endsWith(".md")) continue;- const full = join(dirs.retired, name);- // Retired files we only need for topic + id (for supersede- // bookkeeping) plus the optional `user_rejected_reason` that- // drives signal-suppression (v0.10.1, _summary Β§6). We do a- // lightweight frontmatter parse to avoid the strict folder- // invariant check failing on permissive setups.- try {- const [meta] = parseFrontmatter(full);- const topic = typeof meta["topic"] === "string" ? meta["topic"] : "";- const id = typeof meta["id"] === "string" ? meta["id"] : "";- const principle = typeof meta["principle"] === "string" ? meta["principle"] : "";- const scope = typeof meta["scope"] === "string" ? meta["scope"] : undefined;- const userReason =- typeof meta["user_rejected_reason"] === "string"- ? (meta["user_rejected_reason"] as string).trim()- : "";- if (topic && id) {- retired.push({- path: full,- topic,- id,- principle,- ...(scope ? { scope } : {}),- ...(userReason ? { user_rejected_reason: userReason } : {}),- });- }- } catch {- corrupted.push({ path: full });- }- }- }- return { signals, preferences, retired, corrupted };-}--// ----- Planning -------------------------------------------------------------function planTopics(- scan: ScanResult,- cfg: BrainConfig,- now: Date,- _wikilinkToRun: string,-): PlanState {- void _wikilinkToRun;- const plan = emptyPlan();- const reservedSlugs = collectReservedPreferenceSlugs(scan);-- // Group active signals by topic. We only consider active signals for- // the create/rebut decisions; processed signals stay in the global- // log via `evidenced_by` already.- const byTopic = new Map<string, SignalRecord[]>();- for (const rec of scan.signals) {- if (!rec.active) continue;- const topic = rec.signal.topic;- const arr = byTopic.get(topic);- if (arr) arr.push(rec);- else byTopic.set(topic, [rec]);- }-- // Index existing active preferences by topic.- const prefByTopic = new Map<string, PreferenceRecord>();- for (const p of scan.preferences) {- // The first wins; design doc Β§7.4 invariant says "one preference per- // topic", so a duplicate would be a doctor-level issue, not a dream- // concern.- if (!prefByTopic.has(p.pref.topic)) prefByTopic.set(p.pref.topic, p);- }-- // Index retired by topic for supersede bookkeeping.- const retiredByTopic = new Map<string, RetiredRecord[]>();- for (const r of scan.retired) {- const arr = retiredByTopic.get(r.topic);- if (arr) arr.push(r);- else retiredByTopic.set(r.topic, [r]);- }-- for (const [topic, sigs] of byTopic) {- const active = prefByTopic.get(topic);- if (active) {- handleSignalsOnActivePref(active, sigs, plan, cfg, now, scan.signals, reservedSlugs);- continue;- }- // v0.10.1 _summary Β§6: when a retired pref for this topic carries- // a `user_rejected_reason`, the user explicitly rejected the rule- // β re-growing it from fresh signals is exactly what they were- // asking us not to do. Suppress every matching signal, emit one- // `signal-suppressed` event per signal pointing at the retired- // pref + the reason, and move them straight to processed.- //- // Per-signal scope match: an unscoped suppressor swallows every- // signal on the topic; a scoped suppressor only swallows signals- // sharing its scope (a signal without scope still matches an- // unscoped suppressor but never a scoped one). Multiple retired- // prefs on the same topic are tried in order β the first matching- // suppressor wins. Non-matching signals fall through and remain- // eligible for candidate-pref planning below.- const suppressors = (retiredByTopic.get(topic) ?? []).filter((r) => !!r.user_rejected_reason);- let candidateSigs: SignalRecord[] = sigs;- if (suppressors.length > 0) {- const remaining: SignalRecord[] = [];- for (const sig of sigs) {- const suppressor = suppressors.find((r) => {- if (!r.scope) return true;- if (!sig.signal.scope) return false;- return r.scope === sig.signal.scope;- });- if (!suppressor) {- remaining.push(sig);- continue;- }- plan.signalsSuppressed.push({- signal: `[[${sig.signal.id}]]`,- retired: renderPrefLink({- id: suppressor.id,- principle: suppressor.principle,- }),- reason: suppressor.user_rejected_reason!,- topic,- });- recordSignalMove(plan, sig);- }- if (remaining.length === 0) continue;- candidateSigs = remaining;- }- // No active pref for this topic β either promote or note- // contradiction.- const windowedSigs = filterWithinWindow(- candidateSigs,- cfg.dream.contradiction_window_days,- now,- );- const positives = windowedSigs.filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.positive);- const negatives = windowedSigs.filter((s) => s.signal.signal === BRAIN_SIGNAL_SIGN.negative);- const dominant = positives.length >= negatives.length ? positives : negatives;- const minoritySize = Math.min(positives.length, negatives.length);- const dominantSize = dominant.length - minoritySize; // cancellation- if (dominantSize >= cfg.dream.candidate_threshold) {- // v0.10.16: extra self-approval guardrail. Defaults- // (min_signals=2, min_distinct_agents=1, min_age_days=0) make- // this check a no-op for clusters that already passed- // candidate_threshold. Operators may opt into stricter- // thresholds via `_brain.yaml:guardrails:*`. A failed gate- // routes the cluster to `quarantined` instead of creating a- // new unconfirmed preference; the contributing signals stay- // in inbox/ so the cluster naturally re-evaluates on the next- // pass once more evidence accumulates.- const guardrails = resolveGuardrails(cfg);- const distinctAgents = new Set(dominant.map((s) => s.signal.agent)).size;- let earliestSignalMs = Number.POSITIVE_INFINITY;- for (const s of dominant) {- const t = Date.parse(s.signal.created_at);- if (Number.isFinite(t) && t < earliestSignalMs) earliestSignalMs = t;- }- const ageDays = Number.isFinite(earliestSignalMs)- ? Math.max(0, Math.floor((now.getTime() - earliestSignalMs) / (24 * 60 * 60 * 1000)))- : 0;- const verdict = applySelfApprovalGuardrail(- {- signal_count: dominantSize,- distinct_agents: distinctAgents,- age_days: ageDays,- },- guardrails,- );- if (verdict.decision === "quarantine") {- plan.quarantined.push({- topic,- signal_count: dominantSize,- distinct_agents: distinctAgents,- age_days: ageDays,- failed_gates: verdict.failed_gates,- });- continue;- }- // Decide supersede: if a retired pref for the same topic exists,- // wire it through.- const retiredForTopic = retiredByTopic.get(topic);- const supersedes =- retiredForTopic && retiredForTopic.length > 0 ? retiredForTopic[0]!.id : undefined;- const sign = dominant[0]!.signal.signal;- // Slug from topic for the canonical filename, but reserve slugs- // already present in retired/. Otherwise a superseding preference- // can be created as `pref-topic` while `ret-topic` already exists;- // its later retirement would fail trying to overwrite that retired- // file.- const slug = allocatePreferencePlanSlug(topic, reservedSlugs);- const principle = dominant[0]!.signal.principle;- const scope = dominant[0]!.signal.scope;- // evidencedBy = wikilinks to ALL active signals (dominant + minority)- // that contributed to this topic in the window. We deliberately- // include the minority signals so the audit trail preserves the- // contradiction story even after the file moves to processed/.- const evidencedBy = windowedSigs.map((s) => `[[${s.signal.id}]]`);- const supersedesRecord = supersedes- ? retiredForTopic!.find((r) => r.id === supersedes)- : undefined;- plan.newUnconfirmed.push({- slug,- topic,- scope,- principle,- evidencedBy,- sign,- ...deriveSignalTemporal(dominant[0]!.signal, now),- ...(supersedesRecord- ? {- supersedes: renderPrefLink({- id: supersedesRecord.id,- principle: supersedesRecord.principle,- }),- }- : {}),- });- // Every contributing signal in the window gets moved.- for (const s of windowedSigs) {- recordSignalMove(plan, s);- }- } else if (positives.length > 0 && negatives.length > 0) {- plan.contradictionTopics.add(topic);- }- }- return plan;-}--function handleSignalsOnActivePref(- active: PreferenceRecord,- sigs: SignalRecord[],- plan: PlanState,- cfg: BrainConfig,- now: Date,- allSignals: ReadonlyArray<SignalRecord>,- reservedSlugs: Set<string>,-): void {- // Determine the active preference's sign. Order of preference:- //- // 1. Walk `evidenced_by` wikilinks and look up each referenced- // signal in the global scan; the dominant sign among them is- // the pref's "sign of record". This is the design-correct- // derivation since the writer baked those evidence pointers in.- //- // 2. If no `evidenced_by` resolves (e.g. a hand-crafted pref or a- // pref whose source signals were manually pruned), look at all- // historical signals on the same topic in the global scan.- //- // 3. If still nothing, assume the active pref is on the OPPOSITE- // sign of the incoming dominant sign. This makes a unanimous- // flood of new signals always count as rebuttal β which is the- // conservative, fail-loud choice: the operator gets a clear- // rebut/retire signal and can manually intervene if the system- // misread their intent.- const signCounts = (records: ReadonlyArray<SignalRecord>): { pos: number; neg: number } =>- countSigns(records.map((r) => r.signal.signal));-- // Tier-1 derivation now lives in the shared `sign.ts` helper so the- // semantic-health contradiction detector and this pass agree on one- // definition. `dominantSignOf` returning a concrete sign is exactly- // the old `evidenceRecords.length > 0` branch (every signal carries a- // polarity, so a resolved evidence link always counts); `"unknown"`- // is the old "no evidenced signal resolved" fall-through.- const signSignById = new Map(allSignals.map((r) => [r.signal.id, r.signal.signal]));- const topicRecords = allSignals.filter((r) => r.signal.topic === active.pref.topic);-- const evidenceSign = dominantSignOf(active.pref.evidenced_by, signSignById);- let activeSign: BrainSignalSign;- if (evidenceSign !== "unknown") {- activeSign = evidenceSign;- } else if (topicRecords.length > sigs.length) {- // There are processed signals for this topic that are NOT among- // the active inbox set β use them.- const historical = topicRecords.filter((r) => !sigs.includes(r));- const c = signCounts(historical);- activeSign = c.pos >= c.neg ? BRAIN_SIGNAL_SIGN.positive : BRAIN_SIGNAL_SIGN.negative;- } else {- // Fallback: assume the active pref is OPPOSITE to the incoming- // dominant sign. A unanimous flood thus reads as rebuttal.- const c = signCounts(sigs);- activeSign = c.pos > c.neg ? BRAIN_SIGNAL_SIGN.negative : BRAIN_SIGNAL_SIGN.positive;- }-- const oppositeSign: BrainSignalSign =- activeSign === BRAIN_SIGNAL_SIGN.positive- ? BRAIN_SIGNAL_SIGN.negative- : BRAIN_SIGNAL_SIGN.positive;-- const windowed = filterWithinWindow(sigs, cfg.dream.contradiction_window_days, now);- const sameSign = windowed.filter((s) => s.signal.signal === activeSign);- const opposing = windowed.filter((s) => s.signal.signal === oppositeSign);-- // Same-sign β note redundant + move to processed.- for (const s of sameSign) {- plan.notedRedundant.push({- preference: renderPrefLink({- id: active.pref.id,- principle: active.pref.principle,- }),- signal: `[[${s.signal.id}]]`,- });- recordSignalMove(plan, s);- }-- // Opposite-sign β accumulate toward rebuttal.- if (opposing.length >= cfg.dream.candidate_threshold) {- const slug = active.pref.id.startsWith("pref-")- ? active.pref.id.slice("pref-".length)- : active.pref.id;- if (isPinned(active.pref)) {- plan.retainPinned.push({- preference: renderPrefLink({- id: active.pref.id,- principle: active.pref.principle,- }),- reason: BRAIN_RETIRED_REASON.rebutted,- });- // Rebuttal signals on a pinned pref still get moved out β they- // were addressed (the system saw them) and clogging the inbox- // doesn't help.- for (const s of opposing) recordSignalMove(plan, s);- } else {- plan.retires.push({- slug,- principle: active.pref.principle,- reason: BRAIN_RETIRED_REASON.rebutted,- });- for (const s of opposing) recordSignalMove(plan, s);- // Create a new unconfirmed pref for the new direction.- // Build a fresh slug to avoid filename collision with the- // retiring pref (which lives under preferences/<slug>.md and- // will move to retired/<slug>.md). The simplest scheme: the- // same slug, since `moveToRetired` unlinks the source first.- // For safety against a half-completed move, we suffix with- // `-rebut`.- const newSlug = allocatePreferencePlanSlug(`${slug}-rebut`, reservedSlugs);- const principle = opposing[0]!.signal.principle;- const scope = opposing[0]!.signal.scope;- const evidencedBy = opposing.map((s) => `[[${s.signal.id}]]`);- plan.newUnconfirmed.push({- slug: newSlug,- topic: active.pref.topic,- scope,- principle,- evidencedBy,- sign: oppositeSign,- ...deriveSignalTemporal(opposing[0]!.signal, now),- supersedes: renderPrefLink({- id: active.pref.id,- principle: active.pref.principle,- }),- });- }- } else if (opposing.length > 0) {- plan.contradictionTopics.add(active.pref.topic);- }-}--function collectReservedPreferenceSlugs(scan: ScanResult): Set<string> {- const out = new Set<string>();- for (const p of scan.preferences) {- const slug = preferenceSlugFromId(p.pref.id, "pref-");- if (slug) out.add(slug);- }- for (const r of scan.retired) {- const slug = preferenceSlugFromId(r.id, "ret-");- if (slug) out.add(slug);- }- return out;-}--function preferenceSlugFromId(id: string, prefix: "pref-" | "ret-"): string | null {- return id.startsWith(prefix) && id.length > prefix.length ? id.slice(prefix.length) : null;-}--function allocatePreferencePlanSlug(base: string, reserved: Set<string>): string {- let candidate = base;- let suffix = 2;- while (reserved.has(candidate)) {- candidate = `${base}-${suffix}`;- suffix++;- }- reserved.add(candidate);- return candidate;+function collectWarnings(+ isNonPrimary: boolean,+ callerAgent: string,+ primaryAgent: string | null,+): DreamWarning[] {+ if (!isNonPrimary) return [];+ return [+ {+ code: "non-primary-dream-run",+ message:+ `dream run from agent '${callerAgent}', but primary is ` ++ `'${primaryAgent}'. Convention violation, run proceeds.`,+ },+ ];}/**- * Brain lifecycle suite (F5). Derive a preference's bi-temporal validity- * from the source signal: prefer the signal's explicit `valid_from` /- * `valid_until`, otherwise extract formal ISO temporal tokens from the- * signal's principle + raw text. Returns `{}` when neither yields a- * constraint, so callers spread it without changing byte output.+ * Decide if anything is going to change. We treat any of the following+ * as a state change:+ * - a new unconfirmed pref+ * - a refreshed pref (counters/confidence/status changed)+ * - a retire+ * - a same-sign signal noted on an active pref (move + log)+ * - a corrupted frontmatter (we want the skip event recorded)+ * - any pinned-rebut-attempt warning+ * - a fired rollup-ladder rung (S3)*/-function deriveSignalTemporal(- sig: BrainSignal,- now: Date,-): { valid_from?: string; valid_until?: string } {- if (sig.valid_from || sig.valid_until) {- return {- ...(sig.valid_from ? { valid_from: sig.valid_from } : {}),- ...(sig.valid_until ? { valid_until: sig.valid_until } : {}),- };- }- const text = `${sig.principle ?? ""}\n${sig.raw ?? ""}`;- return extractTemporalConstraints(text, { now });-}--/** Build one phase summary (module-scoped: captures nothing). */-function phaseSummary(phase: DreamPhase, metrics: Record<string, number>): DreamPhaseSummary {- return { phase, metrics };-}--// ----- Refresh + promote ----------------------------------------------------// ----- Auto-retires (expired-unconfirmed, stale-no-evidence) ----------------function planAutoRetires(- scan: ScanResult,- cfg: BrainConfig,- now: Date,+function hasStateChange(plan: PlanState,refresh: RefreshResult,-): void {- for (const rec of scan.preferences) {- const slug = rec.pref.id.startsWith("pref-") ? rec.pref.id.slice("pref-".length) : rec.pref.id;- // Already planned to retire (rebutted)? Skip.- if (plan.retires.some((r) => r.slug === slug)) continue;-- // Use the refreshed status/confirmed_at if available β a pref- // promoted to confirmed in THIS run should be eligible for stale- // retire only if its (yet-to-be-refreshed) last_evidence_at is- // actually old. We branch on the post-refresh shape.- const refreshed = refresh.updated.get(slug);- const effectiveStatus = refreshed ? refreshed.status : rec.pref.status;- const effectiveLastEvidence = refreshed- ? refreshed.last_evidence_at- : rec.pref.last_evidence_at;-- if (effectiveStatus === BRAIN_PREFERENCE_STATUS.unconfirmed) {- const deadline = Date.parse(rec.pref.unconfirmed_until);- if (Number.isFinite(deadline) && now.getTime() > deadline) {- if (isPinned(rec.pref)) {- plan.retainPinned.push({- preference: renderPrefLink({- id: rec.pref.id,- principle: rec.pref.principle,- }),- reason: BRAIN_RETIRED_REASON.expiredUnconfirmed,- });- } else {- plan.retires.push({- slug,- principle: rec.pref.principle,- reason: BRAIN_RETIRED_REASON.expiredUnconfirmed,- });- // Remove the refresh update β no point writing immediately- // before moving to retired/.- refresh.updated.delete(slug);- }- }- continue;- }-- // Confirmed/quarantine β stale-no-evidence check. Quarantine- // is "still active" (design summary Β§20) so the time-based decay- // applies to it identically β a pref sitting idle with no- // evidence eventually retires whether confidence was healthy or- // probationary at the time the clock ran out.- if (- effectiveStatus === BRAIN_PREFERENCE_STATUS.confirmed ||- effectiveStatus === BRAIN_PREFERENCE_STATUS.quarantine- ) {- // Belief lifecycle suite (A4): a low-recall superseded ancestor- // decays on the accelerated window so it leaves the working set- // faster than a live memory. Non-superseded / well-used prefs keep- // the normal window, so a vault with no chains is byte-identical.- const effectiveApplied = refreshed ? refreshed.applied_count : rec.pref.applied_count;- const chainDecay = isLowRecallSupersededAncestor({- supersededBy: rec.supersededBy,- appliedCount: effectiveApplied,- });- const staleDays = effectiveStaleThresholdDays(chainDecay, cfg.retire.stale_evidence_days);- if (!effectiveLastEvidence) {- // Confirmed with no evidence at all? Shouldn't happen, but- // gate on the same staleness rule using `confirmed_at`. We- // measure from confirmation in that case (cheaper than a- // hand-crafted invariant check).- const confirmedAt = refreshed ? refreshed.confirmed_at : rec.pref.confirmed_at;- if (!confirmedAt) continue;- const days = daysBetween(Date.parse(confirmedAt), now.getTime());- if (days > staleDays) {- if (isPinned(rec.pref)) {- plan.retainPinned.push({- preference: renderPrefLink({- id: rec.pref.id,- principle: rec.pref.principle,- }),- reason: BRAIN_RETIRED_REASON.staleNoEvidence,- });- } else {- plan.retires.push({- slug,- principle: rec.pref.principle,- reason: BRAIN_RETIRED_REASON.staleNoEvidence,- ...(chainDecay ? { chainDecay: true } : {}),- });- refresh.updated.delete(slug);- }- }- continue;- }- const days = daysBetween(Date.parse(effectiveLastEvidence), now.getTime());- if (days > staleDays) {- if (isPinned(rec.pref)) {- plan.retainPinned.push({- preference: renderPrefLink({- id: rec.pref.id,- principle: rec.pref.principle,- }),- reason: BRAIN_RETIRED_REASON.staleNoEvidence,- });- } else {- plan.retires.push({- slug,- principle: rec.pref.principle,- reason: BRAIN_RETIRED_REASON.staleNoEvidence,- ...(chainDecay ? { chainDecay: true } : {}),- });- refresh.updated.delete(slug);- }- }- }- }-}--// ----- Signal moves ---------------------------------------------------------function planSignalMoves(scan: ScanResult, plan: PlanState): void {- // All active signals whose topic now corresponds to a planned new- // pref or an active pref were already enqueued by the topic-loop /- // active-pref handler. This function exists for the Β§7.3 step that- // says "Move consumed signals out of inbox/": we cover the case- // where a signal references a preference that already exists (the- // active-pref path), and the case where a signal is part of a fresh- // new_unconfirmed (the topic-loop path). Both already populated- // `plan.signalsToMove`. Nothing additional needed here today.- void scan;- void plan;-}--// ----- Helpers --------------------------------------------------------------function writeEvent(vault: string, event: BrainLogEntry): void {- appendLogEvent(vault, event);-}--function addDays(d: Date, days: number): Date {- return new Date(d.getTime() + days * 24 * 3600 * 1000);+ corruptedCount: number,+ rollupPlan: RollupLadderPlan,+): boolean {+ return (+ plan.newUnconfirmed.length > 0 ||+ refresh.confirmed.size > 0 ||+ refresh.updated.size > 0 ||+ plan.retires.length > 0 ||+ plan.notedRedundant.length > 0 ||+ plan.signalsToMove.size > 0 ||+ plan.retainPinned.length > 0 ||+ plan.signalsSuppressed.length > 0 ||+ // v0.10.16: quarantine is a recorded decision (deferred-but-noted),+ // so a run that produces only quarantine entries is still a+ // meaningful run from the operator's perspective.+ plan.quarantined.length > 0 ||+ rollupPlan.fired ||+ corruptedCount > 0+ );}-function daysBetween(thenMs: number, nowMs: number): number {- if (!Number.isFinite(thenMs)) return 0;- return (nowMs - thenMs) / (24 * 3600 * 1000);+function buildRollupPlan(+ vault: string,+ cfg: BrainConfig,+ factCount: number,+ runId: string,+): RollupLadderPlan {+ return planRollupLadder({+ factCount,+ ledger: readRollupLedger(vault),+ thresholds: resolveRollupThresholds(cfg),+ runId,+ });}function formatRunId(d: Date): string {@@ -1675,6 +399,3 @@ function nextAvailableDreamRunId(vault: string, baseRunId: string): string {}return candidate;}--// Silence "unused" warnings for symbols exported only via barrel.-void basename;diff --git a/src/core/brain/log.ts b/src/core/brain/log.tsindex 7d523eac..4586821e 100644--- a/src/core/brain/log.ts+++ b/src/core/brain/log.ts@@ -256,8 +256,18 @@ export interface AppendLogEventOptions {* Per-device shard id (Memory Integrity Suite). Defaults to* `resolveDeviceId()` from the device-local config; the empty string* forces the legacy un-sharded `<date>.jsonl` / `<date>.md` pair.- * Resolution failure (read-only config home, missing HOME) falls back- * to the legacy pair too - an append must never fail on identity.+ *+ * ANY resolution failure falls back to the legacy pair - a missing HOME,+ * an unwritable config home, or a config file that is present but cannot+ * be read (`ConfigReadError`). This caller is the one that absorbs that+ * error, and it is deliberate rather than an oversight: appending is the+ * always-on write path behind every hook and every session-capture+ * event, so failing it turns one bad file mode into a dead session. The+ * fallback is also not a neutral value invented to look healthy - it is+ * the documented shard shape the `O2B_DEVICE_ID=""` opt-out selects, it+ * loses no data, and the log-dir lock still orders concurrent writers.+ * The condition itself is not swallowed anywhere: every OTHER caller of+ * `resolveDeviceId` propagates it, and the CLI reports it by name.*/readonly deviceId?: string;}@@ -287,7 +297,9 @@ export function appendLogEvent(try {deviceId = resolveDeviceId();} catch {- deviceId = ""; // fail-soft: legacy un-sharded pair+ // Legacy un-sharded pair. See AppendLogEventOptions.deviceId for why+ // this one caller absorbs what every other caller propagates.+ deviceId = "";}}// Parse the timestamp once to extract date + HHMMSS deterministically.diff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.tsnew file mode 100644index 00000000..ed53627e--- /dev/null+++ b/src/core/brain/path-constants.ts@@ -0,0 +1,101 @@+/**+ * Canonical vault-relative layout of the Brain tree: every directory and+ * artefact filename under `<vault>/Brain/`, and nothing else.+ *+ * Single source of truth. Every module that builds a path inside the+ * Brain layer imports these instead of repeating the literal. A future+ * rename ("Brain" β something else) is a one-line change here.+ *+ * A LEAF by construction β it imports nothing from the Brain layer. The+ * builders in `paths.ts` compose absolute paths from these names AND+ * carry the write-intent guard, so they depend on `vault-identity.ts`;+ * `vault-identity.ts` in turn only needs to know where the marker lives,+ * which is a name, not a builder. Keeping the names here is what lets+ * both sides reach them without pointing at each other. `paths.ts`+ * re-exports the whole module, so no importer changes.+ */++import { posix } from "node:path";++/** Vault-relative root of the Brain layer. */+export const BRAIN_ROOT_REL = "Brain";++/** Vault-relative Brain subdirectory names. */+export const BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");+export const BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");+/** Write-approval staging area: `Brain/pending/sig-*.md` (A3, t_e540b093). */+export const BRAIN_PENDING_REL = posix.join(BRAIN_ROOT_REL, "pending");+export const BRAIN_PREFERENCES_REL = posix.join(BRAIN_ROOT_REL, "preferences");+export const BRAIN_RETIRED_REL = posix.join(BRAIN_ROOT_REL, "retired");+export const BRAIN_SKILL_PROPOSALS_REL = posix.join(BRAIN_ROOT_REL, "skill-proposals");+export const BRAIN_SKILL_PROPOSALS_PENDING_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "pending");+export const BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");+export const BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");+/** Write-ahead journal of in-flight skill-proposal accepts (no-dead-ends, Unit I). */+export const BRAIN_SKILL_ACCEPT_JOURNAL_REL = posix.join(+ BRAIN_SKILL_PROPOSALS_REL,+ "accept-journal",+);+export const BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");+export const BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");+export const BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");+export const BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");+/** Declared-thesis register pages: `Brain/theses/thesis-<slug>.md` (D3). */+export const BRAIN_THESES_REL = posix.join(BRAIN_ROOT_REL, "theses");+export const BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");+/**+ * Knowledge-gap task notes: `Brain/gap-tasks/gap-<hash>.md` (A3 /+ * t_67d38036). Plain durable note files - never on the Hermes kanban board.+ */+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");+/**+ * Inbound-capture staging + archive (Knowledge intake suite, seam 1,+ * t_f8f5ef6a). Mirrors the inbox-versus-processed distinction: a capture+ * lands in `Brain/captures/` (staging) and moves to+ * `Brain/captures/processed/` (archive) once drained. Kept in its own+ * subtree so the signal inbox and the dream pass stay untouched.+ */+export const BRAIN_CAPTURES_REL = posix.join(BRAIN_ROOT_REL, "captures");+export const BRAIN_CAPTURES_PROCESSED_REL = posix.join(BRAIN_CAPTURES_REL, "processed");+export const BRAIN_ENTITIES_REL = posix.join(BRAIN_ROOT_REL, "entities");+/**+ * Overwrite-only exact-state lane: `Brain/state/<aspect>.md` (t_b0c9d0a3).+ * A structured operational-state store keyed by aspect; each write replaces+ * the aspect's canonical value with no history. The lane is excluded from+ * the search index by the index-admission predicate so a stale "current"+ * value can never resurface through semantic recall.+ */+export const BRAIN_STATE_REL = posix.join(BRAIN_ROOT_REL, "state");+/** Obsidian Bases view definitions: `Brain/bases/<view>.base` (v1.15.0). */+export const BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");+/** Ingested source summary pages: `Brain/sources/src-<slug>.md` (v1.7.0). */+export const BRAIN_SOURCES_REL = posix.join(BRAIN_ROOT_REL, "sources");+/** Cited research report pages: `Brain/reports/<date>-<slug>.md` (v1.7.0). */+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");+/**+ * 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");++/** 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";+export const BRAIN_PINNED_FILE = "pinned.md";+export const BRAIN_INDEX_FILE = "_INDEX.md";+/** Persisted claim-graph projection artifact (Belief lifecycle suite, A3). */+export const BRAIN_CLAIM_GRAPH_FILE = "claim-graph.json";+/** Persisted rollup-ladder counter ledger (knowledge-intake-and-consolidation, S3). */+export const BRAIN_ROLLUP_LEDGER_FILE = "rollup-ladder.json";++/** Vault-relative path of the `o2b index` output file. */+export const BRAIN_INDEX_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.tsindex 2fca971f..b209151a 100644--- a/src/core/brain/paths.ts+++ b/src/core/brain/paths.ts@@ -24,109 +24,63 @@*/import { existsSync } from "node:fs";-import { join, posix } from "node:path";+import { join } from "node:path";import { ensureInsideVault, vaultRelative } from "../path-safety.ts";import type { DegradationNotice } from "../integrity/degradation.ts";+import {+ BRAIN_ARTIFACTS_REL,+ BRAIN_ACTIVE_FILE,+ BRAIN_ATTENTION_REL,+ BRAIN_BASES_REL,+ BRAIN_CAPTURES_PROCESSED_REL,+ BRAIN_CAPTURES_REL,+ BRAIN_CLAIM_GRAPH_FILE,+ BRAIN_CONFIG_FILE,+ BRAIN_DECISIONS_REL,+ BRAIN_DISTILLATIONS_REL,+ BRAIN_ENTITIES_REL,+ BRAIN_GAP_TASKS_REL,+ BRAIN_INBOX_REL,+ BRAIN_LESSONS_FILE,+ BRAIN_LOG_REL,+ BRAIN_MANUAL_FILE,+ BRAIN_OBLIGATIONS_REL,+ BRAIN_PENDING_REL,+ BRAIN_PINNED_FILE,+ BRAIN_PREFERENCES_REL,+ BRAIN_PROCEDURAL_MEMORY_REL,+ BRAIN_PROCEDURES_REL,+ BRAIN_PROCESSED_REL,+ BRAIN_REPORTS_REL,+ BRAIN_RETIRED_REL,+ BRAIN_ROLLUP_LEDGER_FILE,+ BRAIN_ROOT_REL,+ BRAIN_SKILL_ACCEPT_JOURNAL_REL,+ BRAIN_SKILL_PROPOSALS_ACCEPTED_REL,+ BRAIN_SKILL_PROPOSALS_PENDING_REL,+ BRAIN_SKILL_PROPOSALS_REJECTED_REL,+ BRAIN_SNAPSHOTS_REL,+ BRAIN_SOURCES_REL,+ BRAIN_STATE_REL,+ BRAIN_TENSIONS_REL,+ BRAIN_THESES_REL,+} from "./path-constants.ts";import { assertVaultIdentityForWrite } from "./vault-identity.ts";export { ensureInsideVault, vaultRelative } from "../path-safety.ts";-// ----- Canonical vault-relative path constants -------------------------------//-// Single source of truth. Every module that builds a path inside the-// Brain layer imports these instead of repeating the literal. A-// future rename ("Brain" β something else) is a one-line change here.--/** Vault-relative root of the Brain layer. */-export const BRAIN_ROOT_REL = "Brain";--/** Vault-relative Brain subdirectory names. */-export const BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");-export const BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");-/** Write-approval staging area: `Brain/pending/sig-*.md` (A3, t_e540b093). */-export const BRAIN_PENDING_REL = posix.join(BRAIN_ROOT_REL, "pending");-export const BRAIN_PREFERENCES_REL = posix.join(BRAIN_ROOT_REL, "preferences");-export const BRAIN_RETIRED_REL = posix.join(BRAIN_ROOT_REL, "retired");-export const BRAIN_SKILL_PROPOSALS_REL = posix.join(BRAIN_ROOT_REL, "skill-proposals");-export const BRAIN_SKILL_PROPOSALS_PENDING_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "pending");-export const BRAIN_SKILL_PROPOSALS_ACCEPTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "accepted");-export const BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix.join(BRAIN_SKILL_PROPOSALS_REL, "rejected");-/** Write-ahead journal of in-flight skill-proposal accepts (no-dead-ends, Unit I). */-export const BRAIN_SKILL_ACCEPT_JOURNAL_REL = posix.join(- BRAIN_SKILL_PROPOSALS_REL,- "accept-journal",-);-export const BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");-export const BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");-export const BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");-export const BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");-/** Declared-thesis register pages: `Brain/theses/thesis-<slug>.md` (D3). */-export const BRAIN_THESES_REL = posix.join(BRAIN_ROOT_REL, "theses");-export const BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");-/**- * Knowledge-gap task notes: `Brain/gap-tasks/gap-<hash>.md` (A3 /- * t_67d38036). Plain durable note files - never on the Hermes kanban board.- */-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");-/**- * Inbound-capture staging + archive (Knowledge intake suite, seam 1,- * t_f8f5ef6a). Mirrors the inbox-versus-processed distinction: a capture- * lands in `Brain/captures/` (staging) and moves to- * `Brain/captures/processed/` (archive) once drained. Kept in its own- * subtree so the signal inbox and the dream pass stay untouched.- */-export const BRAIN_CAPTURES_REL = posix.join(BRAIN_ROOT_REL, "captures");-export const BRAIN_CAPTURES_PROCESSED_REL = posix.join(BRAIN_CAPTURES_REL, "processed");-export const BRAIN_ENTITIES_REL = posix.join(BRAIN_ROOT_REL, "entities");-/**- * Overwrite-only exact-state lane: `Brain/state/<aspect>.md` (t_b0c9d0a3).- * A structured operational-state store keyed by aspect; each write replaces- * the aspect's canonical value with no history. The lane is excluded from- * the search index by the index-admission predicate so a stale "current"- * value can never resurface through semantic recall.- */-export const BRAIN_STATE_REL = posix.join(BRAIN_ROOT_REL, "state");-/** Obsidian Bases view definitions: `Brain/bases/<view>.base` (v1.15.0). */-export const BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");-/** Ingested source summary pages: `Brain/sources/src-<slug>.md` (v1.7.0). */-export const BRAIN_SOURCES_REL = posix.join(BRAIN_ROOT_REL, "sources");-/** Cited research report pages: `Brain/reports/<date>-<slug>.md` (v1.7.0). */-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");-/**- * 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");--/** 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";-export const BRAIN_PINNED_FILE = "pinned.md";-export const BRAIN_INDEX_FILE = "_INDEX.md";-/** Persisted claim-graph projection artifact (Belief lifecycle suite, A3). */-export const BRAIN_CLAIM_GRAPH_FILE = "claim-graph.json";--/** Vault-relative path of the `o2b index` output file. */-export const BRAIN_INDEX_REL = posix.join(BRAIN_ROOT_REL, BRAIN_INDEX_FILE);+// The canonical vault-relative names live in their own leaf module so+// `vault-identity.ts` can locate the marker without importing the+// builders that guard on it. Re-exported wholesale: every constant this+// module used to declare is still reachable from this path.+export * from "./path-constants.ts";/** Path of the persisted claim-graph projection: `Brain/claim-graph.json`. */export function claimGraphPath(vault: string): string {return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_CLAIM_GRAPH_FILE), vault);}-/** Persisted rollup-ladder counter ledger (knowledge-intake-and-consolidation, S3). */-export const BRAIN_ROLLUP_LEDGER_FILE = "rollup-ladder.json";-/** Path of the rollup-ladder ledger: `Brain/rollup-ladder.json`. */export function rollupLedgerPath(vault: string): string {return ensureInsideVault(join(brainDirs(vault).brain, BRAIN_ROLLUP_LEDGER_FILE), vault);diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex 7250a67c..f9726adb 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -17,2188 +17,83 @@* dependency, no eval, no surprise.** Anchored in design doc Β§10.- */--import { existsSync, readFileSync } from "node:fs";-import { parseBrainYaml, type ParsedBlock } from "./yaml-parse.ts";-import { isValidIsoInstant } from "./health/iso-time.ts";--import type {- BrainActiveConfig,- BrainAnticipatoryConfig,- BrainConfig,- BrainFeedbackConfig,- BrainGuardrailConfig,- BrainRollupConfig,- BrainHealthConfig,- BrainHygieneConfig,- BrainIntegrityConfig,- BrainLessonsConfig,- BrainRecallConfig,- BrainLinkGraphConfig,- BrainNotesConfig,- BrainSessionsConfig,- BrainSchemaConfig,- BrainMostAppliedConfig,- BrainTemporalConfig,- BrainVaultConfig,- DisciplineReportConfig,- ResolvedBrainGuardrailConfig,- ResolvedBrainHealthConfig,- ResolvedBrainIntegrityConfig,- ResolvedBrainLinkGraphConfig,- ResolvedBrainNotesConfig,- ResolvedBrainSessionsConfig,- ResolvedBrainTemporalConfig,-} from "./types.ts";-import {- SCHEMA_VOCAB_CATEGORIES,- SchemaVocabularyError,- validateSchemaDeclarations,-} from "./schema-vocab.ts";-import { SCOPE_MAX_LEN } from "./signal.ts";-import { GATE_MODE, GATE_MODES, isGateMode } from "../integrity/stamp.ts";-// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to-// break the module-init cycle: the resolver lives in `index.ts` and-// itself imports `loadBrainConfig` from this file. See the-// `defaults.ts` header for the rationale.-import { classifyVaultIgnoreRule, DEFAULT_VAULT_IGNORE_PATHS } from "../vault-scope/defaults.ts";-import { brainConfigPath } from "./paths.ts";--/** Schema versions this build understands. Bump on incompatible changes. */-export const BRAIN_CONFIG_SUPPORTED_VERSIONS: ReadonlyArray<number> = [1];--/**- * Bounds applied to `active.most_applied.{window_days, limit}` at load- * time. Values outside these ranges are hard errors β clamping silently- * would mask the operator's intent.- */-export const MOST_APPLIED_WINDOW_DAYS_MIN = 1;-export const MOST_APPLIED_WINDOW_DAYS_MAX = 365;-export const MOST_APPLIED_LIMIT_MIN = 1;-export const MOST_APPLIED_LIMIT_MAX = 50;-/** Default window when `_brain.yaml` lacks `active.most_applied.window_days`. */-export const MOST_APPLIED_WINDOW_DAYS_DEFAULT = 30;--/**- * Character budget for the active.md body injected at SessionStart- * (token-diet, t_40eb1de7). ~2K tokens - enough for every confirmed- * rule on a typical vault, small enough that a runaway preference set- * cannot flood the session preamble. Override via- * `active.inject_budget_chars`.- */-export const INJECT_BUDGET_CHARS_DEFAULT = 8000;-export const INJECT_BUDGET_CHARS_MIN = 500;-export const INJECT_BUDGET_CHARS_MAX = 200_000;-/** Default top-N limit when `_brain.yaml` lacks `active.most_applied.limit`. */-export const MOST_APPLIED_LIMIT_DEFAULT = 10;--/**- * Bounds and defaults for the `lessons:` block (t_62363378) that tunes- * the signed, recency-scored lessons digest (`Brain/lessons.md`).- * Out-of-range values are hard errors β an operator-tunable knob must- * never silently clamp. The half-life default matches the working-memory- * continuity decay (30 days); the corroboration floor (2 distinct- * results) keeps a one-off application from promoting straight to- * `preferred`.- */-export const LESSONS_HALF_LIFE_DAYS_DEFAULT = 30;-export const LESSONS_HALF_LIFE_DAYS_MIN = 1;-export const LESSONS_HALF_LIFE_DAYS_MAX = 365;-export const LESSONS_CORROBORATION_MIN_DEFAULT = 2;-export const LESSONS_CORROBORATION_MIN_MIN = 1;-export const LESSONS_CORROBORATION_MIN_MAX = 100;-export const LESSONS_LIMIT_DEFAULT = 20;-export const LESSONS_LIMIT_MIN = 1;-export const LESSONS_LIMIT_MAX = 200;--/**- * Hard upper bound on `guardrails.instruction_file_max_lines`. Any- * value above this is a misconfiguration - vault-root instruction- * files are intended to stay small for compliance reasons, so a- * ceiling like 100000 lines silently disables the warning.- */-export const INSTRUCTION_FILE_MAX_LINES_CEILING = 10000;--/**- * Default `guardrails` block (v0.10.16). When `_brain.yaml` omits- * `guardrails` (or omits individual fields), `resolveGuardrails`- * returns these values so consumers can rely on a fully-populated- * struct.- *- * Defaults are chosen to be strictly looser than every existing- * dream-pass gate so adding the guardrail cannot block a promotion- * that previously succeeded:- * - `promotion_min_signals: 1` is below any sane- * `dream.candidate_threshold` (default 3). When an operator- * tunes `candidate_threshold` below 2, the guardrail still- * cannot block them by default - explicit opt-in is required- * via the `_brain.yaml:guardrails:promotion_min_signals` field.- * - `promotion_min_distinct_agents: 1` imposes no cross-agent- * requirement.- * - `promotion_min_age_days: 0` disables the age gate.- * - `instruction_file_max_lines: 200` matches the documented- * compliance ceiling.- */-export const BRAIN_GUARDRAIL_DEFAULTS: ResolvedBrainGuardrailConfig = Object.freeze({- promotion_min_signals: 1,- promotion_min_distinct_agents: 1,- promotion_min_age_days: 0,- instruction_file_max_lines: 200,- untrusted_source_delimiting: false,- derived_fact_synthesis: false,- provenance_trust_ordering: false,- owner_scoped_facts: false,- marker_writeback: false,-}) as ResolvedBrainGuardrailConfig;--/**- * Merge a parsed `guardrails` block (or `undefined`) with- * `BRAIN_GUARDRAIL_DEFAULTS`. Returns a fully-populated struct so- * consumers do not branch on optional fields.- */-export function resolveGuardrails(cfg: BrainConfig): ResolvedBrainGuardrailConfig {- const g = cfg.guardrails;- if (g === undefined) return BRAIN_GUARDRAIL_DEFAULTS;- return {- promotion_min_signals:- g.promotion_min_signals ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_signals,- promotion_min_distinct_agents:- g.promotion_min_distinct_agents ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_distinct_agents,- promotion_min_age_days:- g.promotion_min_age_days ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_age_days,- instruction_file_max_lines:- g.instruction_file_max_lines ?? BRAIN_GUARDRAIL_DEFAULTS.instruction_file_max_lines,- untrusted_source_delimiting:- g.untrusted_source_delimiting ?? BRAIN_GUARDRAIL_DEFAULTS.untrusted_source_delimiting,- derived_fact_synthesis:- g.derived_fact_synthesis ?? BRAIN_GUARDRAIL_DEFAULTS.derived_fact_synthesis,- provenance_trust_ordering:- g.provenance_trust_ordering ?? BRAIN_GUARDRAIL_DEFAULTS.provenance_trust_ordering,- owner_scoped_facts: g.owner_scoped_facts ?? BRAIN_GUARDRAIL_DEFAULTS.owner_scoped_facts,- marker_writeback: g.marker_writeback ?? BRAIN_GUARDRAIL_DEFAULTS.marker_writeback,- };-}--/**- * Default `link_graph` block (v0.10.17). Absent from `_brain.yaml`- * (or with absent individual keys) falls back here via- * `resolveLinkGraph`. Both knobs are purely structural - no- * vocabulary detection of "this looks like a MOC".- *- * Defaults:- * - `moc_min_outbound_links: 5` - the heuristic floor for "this- * is a hub note", chosen to filter out prose notes with a few- * inline references.- * - `moc_min_link_ratio: 0.3` - 30 % of the body's non-whitespace- * characters must sit inside `[[β¦]]` for the audit to accept- * the note as a MOC. Prose notes typically score below 0.1.- * - `vault_instruction_file: "VAULT.md"` - the user-authored- * vault-root instruction file `brain_context` surfaces when- * present. Configurable per vault.- */-export const BRAIN_LINK_GRAPH_DEFAULTS: ResolvedBrainLinkGraphConfig = Object.freeze({- moc_min_outbound_links: 5,- moc_min_link_ratio: 0.3,- vault_instruction_file: "VAULT.md",-}) as ResolvedBrainLinkGraphConfig;--/**- * Merge a parsed `link_graph` block (or `undefined`) with- * `BRAIN_LINK_GRAPH_DEFAULTS`.- */-export function resolveLinkGraph(cfg: BrainConfig): ResolvedBrainLinkGraphConfig {- const lg = cfg.link_graph;- if (lg === undefined) return BRAIN_LINK_GRAPH_DEFAULTS;- return {- moc_min_outbound_links:- lg.moc_min_outbound_links ?? BRAIN_LINK_GRAPH_DEFAULTS.moc_min_outbound_links,- moc_min_link_ratio: lg.moc_min_link_ratio ?? BRAIN_LINK_GRAPH_DEFAULTS.moc_min_link_ratio,- vault_instruction_file:- lg.vault_instruction_file ?? BRAIN_LINK_GRAPH_DEFAULTS.vault_instruction_file,- };-}--/**- * Default `temporal:` block (v0.10.18). Drives the temporal +- * synthesis subsystem. Absent block falls back here via- * `resolveTemporal`. All knobs are purely structural:- *- * - `stale_pref_days: 90` - 3 months without activity before a- * preference is reported as stale.- * - `stale_signal_days: 30` - 1 month without activity for signals.- * - `stale_log_days: 180` - 6 months for Brain/log files.- * - `weekly_start_dow: 1` - ISO-8601 weekday number (1 = Monday,- * 7 = Sunday). Configurable for vaults that prefer Sunday-start- * weeks without any language-specific detection.- * - `daily_window_offset_hours: 0` - daily-brief windows align- * with UTC midnight by default.- */-export const BRAIN_TEMPORAL_DEFAULTS: ResolvedBrainTemporalConfig = Object.freeze({- stale_pref_days: 90,- stale_signal_days: 30,- stale_log_days: 180,- weekly_start_dow: 1,- daily_window_offset_hours: 0,-}) as ResolvedBrainTemporalConfig;--/**- * Merge a parsed `temporal` block (or `undefined`) with- * `BRAIN_TEMPORAL_DEFAULTS`.- */-export function resolveTemporal(cfg: BrainConfig): ResolvedBrainTemporalConfig {- const tp = cfg.temporal;- if (tp === undefined) return BRAIN_TEMPORAL_DEFAULTS;- return {- stale_pref_days: tp.stale_pref_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_pref_days,- stale_signal_days: tp.stale_signal_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_signal_days,- stale_log_days: tp.stale_log_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_log_days,- weekly_start_dow: tp.weekly_start_dow ?? BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow,- daily_window_offset_hours:- tp.daily_window_offset_hours ?? BRAIN_TEMPORAL_DEFAULTS.daily_window_offset_hours,- };-}--/**- * Default `health:` block (v0.14.0). Drives the semantic-health- * detectors and the remediation step cap. Absent block falls back here- * via `resolveHealth`:- *- * - `contradiction_jaccard: 0.5` - two confirmed preferences must- * share at least half their principle tokens (and carry opposite- * signs) to count as a contradiction.- * - `concept_gap_min_frequency: 3` - an entity must recur across 3- * distinct corpus entries before an uncovered-concept gap fires.- * - `stale_claim_max_age_days: 180` - 6 months without fresh- * evidence before a confirmed preference is flagged stale.- * - `remediation_step_cap: 20` - a single `doctor --remediate` run- * applies at most 20 auto-safe repairs.- */-export const BRAIN_HEALTH_DEFAULTS: ResolvedBrainHealthConfig = Object.freeze({- contradiction_jaccard: 0.5,- concept_gap_min_frequency: 3,- stale_claim_max_age_days: 180,- remediation_step_cap: 20,- silence_before: null,-}) as ResolvedBrainHealthConfig;--/**- * Merge a parsed `health` block (or `undefined`) with- * `BRAIN_HEALTH_DEFAULTS`.- */-export function resolveHealth(cfg: BrainConfig): ResolvedBrainHealthConfig {- const h = cfg.health;- if (h === undefined) return BRAIN_HEALTH_DEFAULTS;- return {- contradiction_jaccard: h.contradiction_jaccard ?? BRAIN_HEALTH_DEFAULTS.contradiction_jaccard,- concept_gap_min_frequency:- h.concept_gap_min_frequency ?? BRAIN_HEALTH_DEFAULTS.concept_gap_min_frequency,- stale_claim_max_age_days:- h.stale_claim_max_age_days ?? BRAIN_HEALTH_DEFAULTS.stale_claim_max_age_days,- remediation_step_cap: h.remediation_step_cap ?? BRAIN_HEALTH_DEFAULTS.remediation_step_cap,- silence_before: h.silence_before ?? BRAIN_HEALTH_DEFAULTS.silence_before,- };-}--/**- * Sub-keys of the `integrity:` block whose value is a gate mode. Named- * once and reused by the validator, the unknown-key list, and the- * resolver so the three can never disagree about what the block holds.- */-const INTEGRITY_GATE_KEYS = ["owner_scope_delivery", "embedding_abi"] as const;--/**- * Sub-key vocabularies for the blocks whose validator branch does not- * derive them from a default table. Named once so the parser, the- * forward-compat unknown-key warning and the configuration-template- * ratchet all read the same list.- */-const DISCIPLINE_REPORT_KEYS = ["enabled", "timezone", "watched_paths", "known_agents"] as const;-const HYGIENE_KEYS = ["resolver_cmd", "dedup_threshold"] as const;-const ANTICIPATORY_KEYS = ["ttl_seconds", "max_tokens"] as const;-const RECALL_KEYS = ["degradation"] as const;--/**- * Optional `retire:` sub-key with no default. Declared here because- * `mergeBlock` derives a block's vocabulary from its default table, and- * a key whose default is "absent" has no entry there.- */-const RETIRE_OPTIONAL_KEYS = ["confirmed_evidence_min_threshold"] as const;--/**- * How long a context pack stays servable after it was built, when- * `_brain.yaml` omits `integrity.pack_validity_seconds`.- *- * 900 seconds (15 minutes) is the same bound `CRUTCH_LINK_WINDOW_MS`- * already uses for "still the same working session", so the pack's outer- * staleness bound and the session-continuity bound agree on what a- * session is rather than inventing a second, conflicting answer.- *- * It is deliberately much longer than the anticipatory cache's 120 s TTL:- * the provenance stamp is the PRIMARY invalidator (it observes the vault- * edits that matter), and this window is the backstop for the changes a- * stamp cannot observe. A short window here would duplicate the TTL and- * mask which mechanism actually did the invalidating.- *- * The value is unbounded above on purpose - unlike the instruction-file- * ceiling, a large window does not silently disable anything, because- * the stamp still refuses a drifted pack.- */-export const PACK_VALIDITY_SECONDS_DEFAULT = 900;--/**- * Default `integrity:` block (context-integrity-gates). Absent block (or- * absent individual keys) falls back here via `resolveIntegrity`.- *- * Both gate defaults are the modes that leave every existing vault- * byte-identical:- * - `owner_scope_delivery: off` - the delivery path documents a "null- * scope is byte-identical" contract throughout, so defaulting a- * scope would silently narrow vaults that never opted in. There is- * no writer surface for `owner` yet, so nothing would be gained.- * - `embedding_abi: warn` - `vec_version()` is not stable across- * environments, so two peers on different sqlite-vec builds would- * each see a mismatch. Refusing by default risks a rebuild loop on a- * synced vault; reporting cannot.- */-export const BRAIN_INTEGRITY_DEFAULTS: ResolvedBrainIntegrityConfig = Object.freeze({- owner_scope_delivery: GATE_MODE.off,- embedding_abi: GATE_MODE.warn,- pack_validity_seconds: PACK_VALIDITY_SECONDS_DEFAULT,-}) as ResolvedBrainIntegrityConfig;--/**- * Merge a parsed `integrity` block (or `undefined`) with- * `BRAIN_INTEGRITY_DEFAULTS`. Resolution happens on the READ side, not- * at parse time, so `cfg.integrity` keeps recording exactly what the- * operator wrote and "absent" stays distinguishable from "explicitly set- * to the default".- */-export function resolveIntegrity(cfg: BrainConfig): ResolvedBrainIntegrityConfig {- const it = cfg.integrity;- if (it === undefined) return BRAIN_INTEGRITY_DEFAULTS;- return {- owner_scope_delivery: it.owner_scope_delivery ?? BRAIN_INTEGRITY_DEFAULTS.owner_scope_delivery,- embedding_abi: it.embedding_abi ?? BRAIN_INTEGRITY_DEFAULTS.embedding_abi,- pack_validity_seconds:- it.pack_validity_seconds ?? BRAIN_INTEGRITY_DEFAULTS.pack_validity_seconds,- };-}--/**- * Default `notes:` block (v0.11.0). Empty `read_paths` list means- * the agent does not scan any user-authored notes. The operator- * opts in by listing folders in `_brain.yaml`.- */-export const BRAIN_NOTES_DEFAULTS: ResolvedBrainNotesConfig = Object.freeze({- read_paths: Object.freeze([]) as ReadonlyArray<string>,-}) as ResolvedBrainNotesConfig;--/**- * Merge a parsed `notes` block (or `undefined`) with- * `BRAIN_NOTES_DEFAULTS`. The resulting struct (and its inner array)- * are frozen so consumers can pass the slice around without copying.- */-export function resolveNotes(cfg: BrainConfig): ResolvedBrainNotesConfig {- const block = cfg.notes;- if (block === undefined || block.read_paths === undefined) {- return BRAIN_NOTES_DEFAULTS;- }- return Object.freeze({- read_paths: Object.freeze([...block.read_paths]) as ReadonlyArray<string>,- }) as ResolvedBrainNotesConfig;-}--/**- * Default `sessions:` block (Memory Integrity Suite). Empty lists- * mean every session and message is captured - the pre-boundary- * behaviour, bit-identical.- */-export const BRAIN_SESSIONS_DEFAULTS: ResolvedBrainSessionsConfig = Object.freeze({- ignore_patterns: Object.freeze([]) as ReadonlyArray<string>,- stateless_patterns: Object.freeze([]) as ReadonlyArray<string>,- ignore_message_patterns: Object.freeze([]) as ReadonlyArray<string>,-}) as ResolvedBrainSessionsConfig;--/** Merge a parsed `sessions` block (or `undefined`) with the defaults. */-export function resolveSessions(cfg: BrainConfig): ResolvedBrainSessionsConfig {- const block = cfg.sessions;- if (block === undefined) return BRAIN_SESSIONS_DEFAULTS;- return Object.freeze({- ignore_patterns: Object.freeze([...(block.ignore_patterns ?? [])]) as ReadonlyArray<string>,- stateless_patterns: Object.freeze([- ...(block.stateless_patterns ?? []),- ]) as ReadonlyArray<string>,- ignore_message_patterns: Object.freeze([- ...(block.ignore_message_patterns ?? []),- ]) as ReadonlyArray<string>,- }) as ResolvedBrainSessionsConfig;-}--/**- * Factory for the "load + resolve a block, fall back to its defaults on- * ANY failure" pattern repeated at every `load*ConfigSafe` below (missing- * `_brain.yaml`, malformed YAML, or a validation error all collapse to- * the same fallback - these are read surfaces for vaults that may not- * have run `brain init` yet, not strict config consumers).- */-function makeSafeLoader<T>(- resolveFn: (config: BrainConfig) => T,- fallback: T,-): (vault: string) => T {- return (vault: string): T => {- try {- return resolveFn(loadBrainConfig(vault));- } catch {- return fallback;- }- };-}--/**- * Load + resolve the `notes:` block, falling back to- * `BRAIN_NOTES_DEFAULTS` when the config file is missing, malformed,- * or otherwise unreadable. Same pattern as `loadTemporalConfigSafe`.- * Used by `scan-inline` and any future scanner so a freshly-cloned- * vault that has not been `brain init`-ed still produces a clean- * "no user folders to read" result.- */-export const loadNotesConfigSafe = makeSafeLoader(resolveNotes, BRAIN_NOTES_DEFAULTS);--/**- * Load + resolve the `temporal:` block, falling back to- * `BRAIN_TEMPORAL_DEFAULTS` when the config file is missing,- * malformed, or otherwise unreadable. Used by every temporal- * consumer (MCP wrappers, CLI verbs) so a freshly-initialised vault- * still produces a useful report.- */-export const loadTemporalConfigSafe = makeSafeLoader(resolveTemporal, BRAIN_TEMPORAL_DEFAULTS);--/**- * Load + resolve the `guardrails:` block, falling back to- * `BRAIN_GUARDRAIL_DEFAULTS` when the config file is missing, malformed,- * or otherwise unreadable. Used by agent-facing surfaces (e.g. the- * context pack) that must work on a vault without a full `brain init`;- * the opt-in toggles therefore default off rather than throwing.- */-export const loadGuardrailsConfigSafe = makeSafeLoader(resolveGuardrails, BRAIN_GUARDRAIL_DEFAULTS);--/**- * Gate modes used when `_brain.yaml` EXISTS but cannot be read.- *- * Not the defaults: the defaults encode "this operator has said nothing",- * and an unreadable file is the opposite - the operator said something- * and we cannot tell what. Collapsing that to the defaults turns- * `owner_scope_delivery: fail` into `off`, which disables an isolation- * boundary because of a typo somewhere else in the file, with no signal- * on any surface. Erring to the strictest mode makes the same typo loud- * and reversible instead of quiet and permanent.- *- * `pack_validity_seconds` is not a gate and has no strict direction, so- * it keeps the default window.- */-export const BRAIN_INTEGRITY_STRICT_FALLBACK: ResolvedBrainIntegrityConfig = Object.freeze({- owner_scope_delivery: GATE_MODE.fail,- embedding_abi: GATE_MODE.fail,- pack_validity_seconds: PACK_VALIDITY_SECONDS_DEFAULT,-}) as ResolvedBrainIntegrityConfig;--/**- * Why `_brain.yaml` could not be read, or `null` when it reads fine or- * does not exist.- *- * Exists so the unreadable-config condition is NAMEABLE on a surface- * rather than only inferable from a gate that suddenly refuses. The- * runtime-notice channel reports it; `loadIntegrityConfigSafe` uses the- * same distinction to choose its fallback.- */-export function brainConfigReadFailure(vault: string): string | null {- if (!existsSync(brainConfigPath(vault))) return null;- try {- loadBrainConfig(vault);- return null;- } catch (err) {- return err instanceof Error ? err.message : String(err);- }-}--/**- * Load + resolve the `integrity:` block.- *- * Two failure modes, deliberately NOT collapsed into one:- *- * - CONFIG ABSENT - a vault that has never run `o2b brain init`. The- * search layer reads its gate on a store open and must keep working- * there, so the gates land on `BRAIN_INTEGRITY_DEFAULTS`. This is the- * case the safe-loader pattern legitimately defends.- * - CONFIG PRESENT BUT UNREADABLE - a bad gate token, or any unrelated- * syntax error anywhere else in the file. Falling back to the- * defaults here would silently turn an operator's- * `owner_scope_delivery: fail` into `off`. It resolves to- * {@link BRAIN_INTEGRITY_STRICT_FALLBACK} instead, and- * {@link brainConfigReadFailure} names the cause.- */-export function loadIntegrityConfigSafe(vault: string): ResolvedBrainIntegrityConfig {- try {- return resolveIntegrity(loadBrainConfig(vault));- } catch {- return existsSync(brainConfigPath(vault))- ? BRAIN_INTEGRITY_STRICT_FALLBACK- : BRAIN_INTEGRITY_DEFAULTS;- }-}--/**- * Load the configured `feedback.default_scope`, or `undefined` when the- * config file is missing, malformed, or carries no feedback block. Used- * by the feedback write surfaces so a vault without a full `brain init`- * stays scope-less (byte-identical to pre-feature behaviour) instead of- * throwing when the signal is recorded.- */-export const loadFeedbackDefaultScopeSafe = makeSafeLoader(- (config: BrainConfig) => config.feedback?.default_scope,- undefined as string | undefined,-);--/**- * Default `_brain.yaml` content. Mirrors Β§10 of the design doc. Used by- * `brain init` and as the fallback inside `loadBrainConfig` when callers- * opt into permissive mode (the current API is strict β absent file- * throws).- */-export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({- schema_version: 1,- primary_agent: null,- dream: Object.freeze({- candidate_threshold: 3,- unconfirmed_window_days: 14,- contradiction_window_days: 14,- heal_enrich_enabled: false,- }),- retire: Object.freeze({- stale_evidence_days: 90,- }),- confidence: Object.freeze({- low_max_applied: 2,- medium_min: 0.4,- high_min: 0.75,- }),- snapshots: Object.freeze({- retention_count: 10,- }),- vault: Object.freeze({- ignore_paths: DEFAULT_VAULT_IGNORE_PATHS,- }),-}) as BrainConfig;--/**- * Load the configured snapshot `retention_count`, falling back to the- * default when the config file is missing, malformed, or otherwise- * unreadable. The destructive-snapshot gate uses this so a vault that- * has not run `brain init` still prunes to a sane bound rather than- * throwing mid-cleanup. This is the SAME `snapshots.retention_count`- * the dream pass reads via `loadBrainConfig`; the safe variant just- * tolerates an uninitialised vault the way every other read surface- * does.- */-export const loadSnapshotRetentionSafe = makeSafeLoader(- (config: BrainConfig) => config.snapshots.retention_count,- DEFAULT_BRAIN_CONFIG.snapshots.retention_count,-);--// The serialised default `_brain.yaml` (`DEFAULT_BRAIN_CONFIG_YAML`) is-// GENERATED from the default tables above and lives in-// `config-template.ts`. It cannot live here: the generator reads these-// tables, so importing it back would make `policy.ts` and-// `config-template.ts` mutually dependent at module-evaluation time.--const YAML_STRING_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;--/**- * Format a `primary_agent` value for the small `_brain.yaml` subset.- *- * We quote non-null values so spaces / `#` / `:` round-trip as data- * instead of being interpreted as comments or YAML structure. Since the- * parser intentionally does not implement escape sequences, reject bytes- * that would require escaping rather than writing a value that cannot- * be read back exactly.- */-export function formatPrimaryAgentYamlValue(- value: string | null,- source: string | null = null,-): string {- if (value === null) return "null";- const trimmed = value.trim();- if (trimmed.length === 0) {- throw new BrainConfigError(- "must be either null or a non-empty string",- "primary_agent",- source,- );- }- for (const bad of YAML_STRING_REJECTED_CHARS) {- if (trimmed.includes(bad)) {- throw new BrainConfigError(- `contains a disallowed character ${JSON.stringify(bad)}; ` +- "use a simple one-line agent id",- "primary_agent",- source,- );- }- }- return `"${trimmed}"`;-}--/**- * Warnings collected during validation. Forward-compat tolerates unknown- * top-level keys but surfaces them so a typo doesn't go unnoticed.- */-export interface BrainConfigLoadWarning {- readonly path: string;- readonly message: string;-}--export class BrainConfigError extends Error {- /**- * Dotted field path that caused the failure (`dream.candidate_threshold`,- * `schema_version`, β¦). `null` for top-level type errors.- */- readonly field: string | null;- readonly source: string | null;-- constructor(message: string, field: string | null, source: string | null) {- super(- field- ? `${source ?? "<config>"}: ${field}: ${message}`- : `${source ?? "<config>"}: ${message}`,- );- this.name = "BrainConfigError";- this.field = field;- this.source = source;- }-}--// ----- Public API -------------------------------------------------------------export interface LoadBrainConfigResult {- readonly config: BrainConfig;- readonly warnings: ReadonlyArray<BrainConfigLoadWarning>;- readonly path: string;-}--/**- * Read and validate `<vault>/Brain/_brain.yaml`.- *- * Throws {@link BrainConfigError} on:- * - missing file- * - YAML shape errors- * - unsupported `schema_version`- * - non-integer / out-of-range thresholds- * - non-integer / non-positive `snapshots.retention_count`- *- * Unknown top-level keys are reported as warnings, not errors.- */-export function loadBrainConfig(vault: string): BrainConfig {- return loadBrainConfigDetailed(vault).config;-}--/**- * Same as {@link loadBrainConfig} but also returns parser warnings (for- * the future `o2b brain doctor` integration).- */-export function loadBrainConfigDetailed(vault: string): LoadBrainConfigResult {- const path = brainConfigPath(vault);- if (!existsSync(path)) {- throw new BrainConfigError(- "config file does not exist; run `o2b brain init` first",- null,- path,- );- }- let text: string;- try {- text = readFileSync(path, "utf8");- } catch (err) {- throw new BrainConfigError(- `failed to read: ${(err as Error).message ?? String(err)}`,- null,- path,- );- }-- let parsed: ParsedBlock;- try {- parsed = parseBrainYaml(text);- } catch (err) {- throw new BrainConfigError((err as Error).message, null, path);- }-- const { config, warnings } = validateBrainConfigDetailed(parsed, path);- return { config, warnings, path };-}--/**- * Pure validator. Accepts a parsed object (typically from- * {@link parseBrainYaml}) and returns a typed {@link BrainConfig}, or- * throws {@link BrainConfigError} naming the offending field.- *- * `source` is rendered into error messages; pass the config file path or- * a synthetic label like `"<test fixture>"` so the failure points at- * something useful.- */-export function validateBrainConfig(parsed: unknown, source: string | null = null): BrainConfig {- return validateBrainConfigDetailed(parsed, source).config;-}--export interface ValidateResult {- readonly config: BrainConfig;- readonly warnings: ReadonlyArray<BrainConfigLoadWarning>;- /**- * Every key this validation run branched on, top-level and per-block.- * Recorded by construction (see {@link KeyIndexCollector}) rather than- * from a hand-maintained list, so it can never disagree with what the- * validator actually understands. Consumed by the configuration-template- * ratchet.- */- readonly knownKeys: BrainConfigKeyIndex;-}--/**- * The set of configuration keys the validator understands, as observed- * during one validation run.- */-export interface BrainConfigKeyIndex {- readonly topLevel: ReadonlySet<string>;- /** Block key β sub-keys that block declares. Scalar keys are absent. */- readonly subKeys: ReadonlyMap<string, ReadonlySet<string>>;-}--export function validateBrainConfigDetailed(- parsed: unknown,- source: string | null = null,-): ValidateResult {- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {- throw new BrainConfigError("config root must be a map of keys", null, source);- }- const obj = parsed as Record<string, unknown>;- const warnings: BrainConfigLoadWarning[] = [];- // Populated by every `hasBlock`/`mergeBlock`/`warnUnknownKeys` call- // below; drives the forward-compat "unknown top-level field" check at- // the end of this function and the template ratchet.- // `schema_version` is seeded directly since its presence is checked by- // an inverted `if (!(... in obj))` immediately below, not through- // either helper.- const knownBlockKeys = new KeyIndexCollector();- knownBlockKeys.addTop("schema_version");-- // schema_version is mandatory and must be in the supported set.- if (!("schema_version" in obj)) {- throw new BrainConfigError(- "missing required field; expected a positive integer in the supported set " +- `(${BRAIN_CONFIG_SUPPORTED_VERSIONS.join(", ")})`,- "schema_version",- source,- );- }- const schemaVersion = obj["schema_version"];- if (- typeof schemaVersion !== "number" ||- !Number.isInteger(schemaVersion) ||- !BRAIN_CONFIG_SUPPORTED_VERSIONS.includes(schemaVersion)- ) {- throw new BrainConfigError(- `unsupported value ${JSON.stringify(schemaVersion)}; expected one of ` +- BRAIN_CONFIG_SUPPORTED_VERSIONS.join(", "),- "schema_version",- source,- );- }-- // `primary_agent` β optional scalar (null or non-empty string).- // Defaults to null when absent so existing vaults are unaffected.- // Loader enforces the same character constraints as the writer- // (`formatPrimaryAgentYamlValue`) so a hand-edited file that the- // writer would later refuse to emit fails fast at load time- // instead of round-tripping into a state we cannot persist.- let primaryAgent: string | null = DEFAULT_BRAIN_CONFIG.primary_agent;- if (hasBlock(obj, "primary_agent", knownBlockKeys)) {- const v = obj["primary_agent"];- if (v === null || v === undefined) {- primaryAgent = null;- } else if (typeof v === "string") {- const trimmed = v.trim();- if (trimmed.length === 0) {- throw new BrainConfigError(- "must be either null or a non-empty string",- "primary_agent",- source,- );- }- for (const bad of YAML_STRING_REJECTED_CHARS) {- if (trimmed.includes(bad)) {- throw new BrainConfigError(- `contains a disallowed character ${JSON.stringify(bad)}; ` +- "use a simple one-line agent id",- "primary_agent",- source,- );- }- }- primaryAgent = trimmed;- } else {- throw new BrainConfigError(- `must be either null or a non-empty string; got ${describe(v)}`,- "primary_agent",- source,- );- }- }-- // Each block is optional; missing blocks inherit the default. We- // merge field-by-field so a user can override one threshold without- // having to re-state the rest.- const dream = mergeBlock(- "dream",- obj["dream"],- DEFAULT_BRAIN_CONFIG.dream as unknown as Readonly<Record<string, number>>,- source,- knownBlockKeys,- );- requirePositiveInteger("dream.candidate_threshold", dream.candidate_threshold, source);- requirePositiveInteger("dream.unconfirmed_window_days", dream.unconfirmed_window_days, source);- requirePositiveInteger(- "dream.contradiction_window_days",- dream.contradiction_window_days,- source,- );-- const retire = mergeBlock(- "retire",- obj["retire"],- DEFAULT_BRAIN_CONFIG.retire as unknown as Readonly<Record<string, number>>,- source,- knownBlockKeys,- RETIRE_OPTIONAL_KEYS,- );- requirePositiveInteger("retire.stale_evidence_days", retire.stale_evidence_days, source);- // Optional destructive-from-confirmed gate (v0.12.0). Validated here- // and carried into the typed config below; an out-of-range value is a- // hard error rather than a silently ignored knob.- if (retire.confirmed_evidence_min_threshold !== undefined) {- requirePositiveInteger(- "retire.confirmed_evidence_min_threshold",- retire.confirmed_evidence_min_threshold,- source,- );- }-- const confidence = mergeBlock(- "confidence",- obj["confidence"],- DEFAULT_BRAIN_CONFIG.confidence as unknown as Readonly<Record<string, number>>,- source,- knownBlockKeys,- );- requireNonNegativeInteger("confidence.low_max_applied", confidence.low_max_applied, source);- requireUnitInterval("confidence.medium_min", confidence.medium_min, source);- requireUnitInterval("confidence.high_min", confidence.high_min, source);- if ((confidence.medium_min as number) >= (confidence.high_min as number)) {- throw new BrainConfigError(- `medium_min must be strictly less than high_min; got ` +- `medium_min=${confidence.medium_min}, high_min=${confidence.high_min}`,- "confidence.medium_min",- source,- );- }-- const snapshots = mergeBlock(- "snapshots",- obj["snapshots"],- DEFAULT_BRAIN_CONFIG.snapshots as unknown as Readonly<Record<string, number>>,- source,- knownBlockKeys,- );- requirePositiveInteger("snapshots.retention_count", snapshots.retention_count, source);-- // Optional `vault` block (v0.10.9). Hard-error on shape problems β- // exclusions affect every walker, silent ignore would be a footgun.- // The block is absent for vaults created before v0.10.9 and for- // operators who explicitly removed it; the resolver falls back to- // `DEFAULT_VAULT_IGNORE_PATHS` in both cases.- let vault: BrainVaultConfig | undefined;- if (hasBlock(obj, "vault", knownBlockKeys)) {- const raw = obj["vault"];- const rawMap = requireMapBlock(raw, "vault", source);- if ("ignore_paths" in rawMap) {- const list = rawMap["ignore_paths"];- if (!Array.isArray(list)) {- throw new BrainConfigError(- `must be a list of strings; got ${describe(list)}`,- "vault.ignore_paths",- source,- );- }- const validated: string[] = [];- list.forEach((entry, i) => {- if (typeof entry !== "string") {- throw new BrainConfigError(- `must be a string; got ${describe(entry)}`,- `vault.ignore_paths[${i}]`,- source,- );- }- const trimmed = entry.trim();- if (trimmed.length === 0) {- throw new BrainConfigError(- "must be a non-empty string",- `vault.ignore_paths[${i}]`,- source,- );- }- for (const bad of YAML_STRING_REJECTED_CHARS) {- if (trimmed.includes(bad)) {- throw new BrainConfigError(- `contains a disallowed character ${JSON.stringify(bad)}; ` +- "use a simple one-line path",- `vault.ignore_paths[${i}]`,- source,- );- }- }- // `classifyVaultIgnoreRule` strips leading `./` / trailing- // `/` / collapsing `//`. An entry that normalises to the- // empty string (`./`, `/`, `///`) would silently disable- // itself; reject so the operator sees the typo immediately.- const normalised = classifyVaultIgnoreRule(trimmed).raw;- if (normalised.length === 0) {- throw new BrainConfigError(- "normalises to the empty string; use a real directory name or vault-relative path",- `vault.ignore_paths[${i}]`,- source,- );- }- // Reject leading-slash entries explicitly. `matchIgnore` only- // compares vault-relative POSIX prefixes (no leading `/`), so- // `/Brain/.snapshots` would silently never match β exactly the- // fail-closed contract violation the v0.10.9 policy forbids.- if (normalised.startsWith("/")) {- throw new BrainConfigError(- "must be a bare name or vault-relative POSIX path without a leading '/'",- `vault.ignore_paths[${i}]`,- source,- );- }- validated.push(normalised);- });- vault = { ignore_paths: Object.freeze(validated) };- }- // Forward-compat: unknown sub-keys under `vault:` β warning.- warnUnknownKeys(rawMap, ["ignore_paths"], "vault", source, warnings, knownBlockKeys);- }-- // Optional `active.{most_applied_window_days, most_applied_limit}`- // block (v0.10.11). Hard-error on shape problems β operator-tunable- // knobs should never silently fall back to defaults.- //- // The YAML keys are flat at level 2 to fit the existing two-level- // parser; the in-memory shape `BrainActiveConfig.most_applied` still- // groups them so downstream consumers (`active.md`, `brain_digest`)- // can pass one struct around.- let active: BrainActiveConfig | undefined;- if (hasBlock(obj, "active", knownBlockKeys)) {- const rawActive = obj["active"];- const activeMap = requireMapBlock(rawActive, "active", source);- const hasWindow = "most_applied_window_days" in activeMap;- const hasLimit = "most_applied_limit" in activeMap;- let mostApplied: BrainMostAppliedConfig | undefined;- if (hasWindow || hasLimit) {- const windowDays = hasWindow- ? activeMap["most_applied_window_days"]- : MOST_APPLIED_WINDOW_DAYS_DEFAULT;- const limit = hasLimit ? activeMap["most_applied_limit"] : MOST_APPLIED_LIMIT_DEFAULT;- if (- typeof windowDays !== "number" ||- !Number.isInteger(windowDays) ||- windowDays < MOST_APPLIED_WINDOW_DAYS_MIN ||- windowDays > MOST_APPLIED_WINDOW_DAYS_MAX- ) {- throw new BrainConfigError(- `must be an integer between ${MOST_APPLIED_WINDOW_DAYS_MIN} and ` +- `${MOST_APPLIED_WINDOW_DAYS_MAX}; got ${describe(windowDays)}`,- "active.most_applied_window_days",- source,- );- }- if (- typeof limit !== "number" ||- !Number.isInteger(limit) ||- limit < MOST_APPLIED_LIMIT_MIN ||- limit > MOST_APPLIED_LIMIT_MAX- ) {- throw new BrainConfigError(- `must be an integer between ${MOST_APPLIED_LIMIT_MIN} and ` +- `${MOST_APPLIED_LIMIT_MAX}; got ${describe(limit)}`,- "active.most_applied_limit",- source,- );- }- mostApplied = { window_days: windowDays, limit };- }- let injectBudgetChars: number | undefined;- if ("inject_budget_chars" in activeMap) {- const raw = activeMap["inject_budget_chars"];- if (- typeof raw !== "number" ||- !Number.isInteger(raw) ||- raw < INJECT_BUDGET_CHARS_MIN ||- raw > INJECT_BUDGET_CHARS_MAX- ) {- throw new BrainConfigError(- `must be an integer between ${INJECT_BUDGET_CHARS_MIN} and ` +- `${INJECT_BUDGET_CHARS_MAX}; got ${describe(raw)}`,- "active.inject_budget_chars",- source,- );- }- injectBudgetChars = raw;- }- // Forward-compat: unknown sub-keys under `active:` β warning.- warnUnknownKeys(- activeMap,- ["most_applied_window_days", "most_applied_limit", "inject_budget_chars"],- "active",- source,- warnings,- knownBlockKeys,- );- active = {- ...(mostApplied !== undefined ? { most_applied: mostApplied } : {}),- ...(injectBudgetChars !== undefined ? { inject_budget_chars: injectBudgetChars } : {}),- };- }-- // Optional `lessons:` block (t_62363378). Tunes the signed,- // recency-scored lessons digest. Hard-error on out-of-range values β- // operator-tunable knobs must never silently fall back to defaults.- let lessons: BrainLessonsConfig | undefined;- if (hasBlock(obj, "lessons", knownBlockKeys)) {- const rawLessons = obj["lessons"];- const lessonsMap = requireMapBlock(rawLessons, "lessons", source);- const halfLife = readBoundedInt(- lessonsMap,- "half_life_days",- LESSONS_HALF_LIFE_DAYS_MIN,- LESSONS_HALF_LIFE_DAYS_MAX,- source,- );- const corroborationMin = readBoundedInt(- lessonsMap,- "corroboration_min",- LESSONS_CORROBORATION_MIN_MIN,- LESSONS_CORROBORATION_MIN_MAX,- source,- );- const lessonsLimit = readBoundedInt(- lessonsMap,- "limit",- LESSONS_LIMIT_MIN,- LESSONS_LIMIT_MAX,- source,- );- warnUnknownKeys(- lessonsMap,- ["half_life_days", "corroboration_min", "limit"],- "lessons",- source,- warnings,- knownBlockKeys,- );- lessons = {- ...(halfLife !== undefined ? { half_life_days: halfLife } : {}),- ...(corroborationMin !== undefined ? { corroboration_min: corroborationMin } : {}),- ...(lessonsLimit !== undefined ? { limit: lessonsLimit } : {}),- };- }-- // Optional `discipline_report` section. On any type mismatch, emit a- // warning and drop the section (return undefined) rather than throwing β- // the rest of the CLI surface must keep working.- let disciplineReport: DisciplineReportConfig | undefined;- if (hasBlock(obj, "discipline_report", knownBlockKeys)) {- const dr = obj["discipline_report"];- if (typeof dr !== "object" || dr === null || Array.isArray(dr)) {- warnings.push({- path: source ?? "<config>",- message: `discipline_report: must be a map of keys; got ${describe(dr)} β section ignored`,- });- } else {- const drObj = dr as Record<string, unknown>;- warnUnknownKeys(- drObj,- DISCIPLINE_REPORT_KEYS,- "discipline_report",- source,- warnings,- knownBlockKeys,- );- let ok = true;-- // enabled: boolean- if (typeof drObj["enabled"] !== "boolean") {- warnings.push({- path: source ?? "<config>",- message: `discipline_report.enabled: must be a boolean; got ${describe(drObj["enabled"])} β section ignored`,- });- ok = false;- }-- // timezone: string- if (typeof drObj["timezone"] !== "string") {- warnings.push({- path: source ?? "<config>",- message: `discipline_report.timezone: must be a string; got ${describe(drObj["timezone"])} β section ignored`,- });- ok = false;- }-- // watched_paths: array of strings- if (!Array.isArray(drObj["watched_paths"])) {- warnings.push({- path: source ?? "<config>",- message: `discipline_report.watched_paths: must be an array; got ${describe(drObj["watched_paths"])} β section ignored`,- });- ok = false;- } else {- const badIdx = (drObj["watched_paths"] as unknown[]).findIndex(- (v) => typeof v !== "string",- );- if (badIdx >= 0) {- warnings.push({- path: source ?? "<config>",- message: `discipline_report.watched_paths[${badIdx}]: must be a string; got ${describe((drObj["watched_paths"] as unknown[])[badIdx])} β section ignored`,- });- ok = false;- }- }-- // known_agents: array of strings- if (!Array.isArray(drObj["known_agents"])) {- warnings.push({- path: source ?? "<config>",- message: `discipline_report.known_agents: must be an array; got ${describe(drObj["known_agents"])} β section ignored`,- });- ok = false;- } else {- const badIdx = (drObj["known_agents"] as unknown[]).findIndex((v) => typeof v !== "string");- if (badIdx >= 0) {- warnings.push({- path: source ?? "<config>",- message: `discipline_report.known_agents[${badIdx}]: must be a string; got ${describe((drObj["known_agents"] as unknown[])[badIdx])} β section ignored`,- });- ok = false;- }- }-- if (ok) {- disciplineReport = {- enabled: drObj["enabled"] as boolean,- timezone: drObj["timezone"] as string,- watched_paths: drObj["watched_paths"] as ReadonlyArray<string>,- known_agents: drObj["known_agents"] as ReadonlyArray<string>,- };- }- }- }-- // Optional `guardrails` block (v0.10.16). Hard-error on shape- // problems - thresholds are operator-tunable and silent fallback- // would mask the operator's intent. Missing block leaves- // `cfg.guardrails` undefined; `resolveGuardrails` injects defaults- // on the read side so consumers receive a fully-populated struct.- let guardrails: BrainGuardrailConfig | undefined;- if (hasBlock(obj, "guardrails", knownBlockKeys)) {- const raw = obj["guardrails"];- const rawMap = requireMapBlock(raw, "guardrails", source);- const partial: {- promotion_min_signals?: number;- promotion_min_distinct_agents?: number;- promotion_min_age_days?: number;- instruction_file_max_lines?: number;- untrusted_source_delimiting?: boolean;- derived_fact_synthesis?: boolean;- provenance_trust_ordering?: boolean;- owner_scoped_facts?: boolean;- marker_writeback?: boolean;- } = {};-- if ("promotion_min_signals" in rawMap) {- requirePositiveInteger(- "guardrails.promotion_min_signals",- rawMap["promotion_min_signals"],- source,- );- partial.promotion_min_signals = rawMap["promotion_min_signals"] as number;- }- if ("promotion_min_distinct_agents" in rawMap) {- requirePositiveInteger(- "guardrails.promotion_min_distinct_agents",- rawMap["promotion_min_distinct_agents"],- source,- );- partial.promotion_min_distinct_agents = rawMap["promotion_min_distinct_agents"] as number;- }- if ("promotion_min_age_days" in rawMap) {- requireNonNegativeInteger(- "guardrails.promotion_min_age_days",- rawMap["promotion_min_age_days"],- source,- );- partial.promotion_min_age_days = rawMap["promotion_min_age_days"] as number;- }- if ("instruction_file_max_lines" in rawMap) {- requirePositiveInteger(- "guardrails.instruction_file_max_lines",- rawMap["instruction_file_max_lines"],- source,- );- const v = rawMap["instruction_file_max_lines"] as number;- if (v > INSTRUCTION_FILE_MAX_LINES_CEILING) {- throw new BrainConfigError(- `must be at most ${INSTRUCTION_FILE_MAX_LINES_CEILING}; got ${describe(v)}`,- "guardrails.instruction_file_max_lines",- source,- );- }- partial.instruction_file_max_lines = v;- }- if ("untrusted_source_delimiting" in rawMap) {- const flag = rawMap["untrusted_source_delimiting"];- if (typeof flag !== "boolean") {- throw new BrainConfigError(- `must be a boolean; got ${describe(flag)}`,- "guardrails.untrusted_source_delimiting",- source,- );- }- partial.untrusted_source_delimiting = flag;- }- // Knowledge Provenance opt-in boolean flags (v1.7). Same shape as- // untrusted_source_delimiting: present β must be boolean, else hard error.- for (const key of [- "derived_fact_synthesis",- "provenance_trust_ordering",- "owner_scoped_facts",- "marker_writeback",- ] as const) {- if (key in rawMap) {- const flag = rawMap[key];- if (typeof flag !== "boolean") {- throw new BrainConfigError(- `must be a boolean; got ${describe(flag)}`,- `guardrails.${key}`,- source,- );- }- partial[key] = flag;- }- }-- // Forward-compat: unknown sub-keys under `guardrails:` β warning.- warnUnknownKeys(- rawMap,- [- "promotion_min_signals",- "promotion_min_distinct_agents",- "promotion_min_age_days",- "instruction_file_max_lines",- "untrusted_source_delimiting",- "derived_fact_synthesis",- "provenance_trust_ordering",- "owner_scoped_facts",- "marker_writeback",- ],- "guardrails",- source,- warnings,- knownBlockKeys,- );-- if (Object.keys(partial).length > 0) {- guardrails = partial;- } else {- // Block present but contained only unknown fields: keep an- // empty marker so `cfg.guardrails` is non-undefined and- // distinguishable from "block absent entirely".- guardrails = {};- }- }-- // Optional `rollup` block (knowledge-intake-and-consolidation, S3).- // Overrides the fact rollup-ladder thresholds; hard-error on shape- // problems so a mistyped threshold surfaces instead of silently- // reverting to the named-constant default.- let rollup: BrainRollupConfig | undefined;- if (hasBlock(obj, "rollup", knownBlockKeys)) {- const rawMap = requireMapBlock(obj["rollup"], "rollup", source);- const partial: { fact_threshold?: number; identity_threshold?: number } = {};- if ("fact_threshold" in rawMap) {- requirePositiveInteger("rollup.fact_threshold", rawMap["fact_threshold"], source);- partial.fact_threshold = rawMap["fact_threshold"] as number;- }- if ("identity_threshold" in rawMap) {- requirePositiveInteger("rollup.identity_threshold", rawMap["identity_threshold"], source);- partial.identity_threshold = rawMap["identity_threshold"] as number;- }- warnUnknownKeys(- rawMap,- ["fact_threshold", "identity_threshold"],- "rollup",- source,- warnings,- knownBlockKeys,- );- rollup = partial;- }-- // Optional `link_graph` block (v0.10.17). Shape:- // link_graph:- // moc_min_outbound_links: 5 # positive integer- // moc_min_link_ratio: 0.3 # number in (0, 1]- // vault_instruction_file: VAULT.md # vault-relative path- // Absent block β `cfg.link_graph` undefined; resolveLinkGraph- // returns the bit-identical defaults.- let linkGraph: BrainLinkGraphConfig | undefined;- if (hasBlock(obj, "link_graph", knownBlockKeys)) {- const rawLg = obj["link_graph"];- const lgObj = requireMapBlock(rawLg, "link_graph", source);- const partialLg: Record<string, unknown> = {};- if ("moc_min_outbound_links" in lgObj) {- const v = lgObj["moc_min_outbound_links"];- if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {- throw new BrainConfigError(- "must be a positive integer",- "link_graph.moc_min_outbound_links",- source,- );- }- partialLg["moc_min_outbound_links"] = v;- }- if ("moc_min_link_ratio" in lgObj) {- const v = lgObj["moc_min_link_ratio"];- if (typeof v !== "number" || !Number.isFinite(v) || v <= 0 || v > 1) {- throw new BrainConfigError(- "must be a number in (0, 1]",- "link_graph.moc_min_link_ratio",- source,- );- }- partialLg["moc_min_link_ratio"] = v;- }- if ("vault_instruction_file" in lgObj) {- const v = lgObj["vault_instruction_file"];- if (typeof v !== "string" || v.trim().length === 0) {- throw new BrainConfigError(- "must be a non-empty string",- "link_graph.vault_instruction_file",- source,- );- }- // Trim BEFORE the path-shape check so a value like- // `" VAULT.md "` doesn't survive validation and fail at- // read time as a missing file.- const trimmed = v.trim();- // Reject absolute paths and `..` traversal at load time so- // the config surface fails loudly instead of silently- // omitting the envelope field at read time.- if (trimmed.startsWith("/") || trimmed.startsWith("\\") || trimmed.includes("..")) {- throw new BrainConfigError(- "must be a vault-relative path without '..' segments",- "link_graph.vault_instruction_file",- source,- );- }- partialLg["vault_instruction_file"] = trimmed;- }- // Forward-compat: unknown sub-keys under `link_graph:` β warning.- warnUnknownKeys(- lgObj,- ["moc_min_outbound_links", "moc_min_link_ratio", "vault_instruction_file"],- "link_graph",- source,- warnings,- knownBlockKeys,- );- linkGraph = Object.keys(partialLg).length > 0 ? (partialLg as BrainLinkGraphConfig) : {};- }-- // Optional `temporal` block (v0.10.18). Shape:- // temporal:- // stale_pref_days: 90 # positive integer- // stale_signal_days: 30 # positive integer- // stale_log_days: 180 # positive integer- // weekly_start_dow: 1 # 1..7 (ISO-8601 weekday)- // daily_window_offset_hours: 0 # -23..23- // Absent block β `cfg.temporal` undefined; resolveTemporal returns- // the bit-identical defaults.- let temporal: BrainTemporalConfig | undefined;- if (hasBlock(obj, "temporal", knownBlockKeys)) {- const rawTp = obj["temporal"];- const tpObj = requireMapBlock(rawTp, "temporal", source);- const partialTp: Record<string, unknown> = {};- const positiveIntKeys: ReadonlyArray<- "stale_pref_days" | "stale_signal_days" | "stale_log_days"- > = ["stale_pref_days", "stale_signal_days", "stale_log_days"];- for (const key of positiveIntKeys) {- if (key in tpObj) {- const v = tpObj[key];- if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {- throw new BrainConfigError("must be a positive integer", `temporal.${key}`, source);- }- partialTp[key] = v;- }- }- if ("weekly_start_dow" in tpObj) {- const v = tpObj["weekly_start_dow"];- if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 7) {- throw new BrainConfigError(- "must be an ISO-8601 weekday number (1..7)",- "temporal.weekly_start_dow",- source,- );- }- partialTp["weekly_start_dow"] = v;- }- if ("daily_window_offset_hours" in tpObj) {- const v = tpObj["daily_window_offset_hours"];- if (typeof v !== "number" || !Number.isInteger(v) || v < -23 || v > 23) {- throw new BrainConfigError(- "must be an integer in [-23, 23]",- "temporal.daily_window_offset_hours",- source,- );- }- partialTp["daily_window_offset_hours"] = v;- }- // Forward-compat: unknown sub-keys under `temporal:` β warning.- warnUnknownKeys(- tpObj,- [- "stale_pref_days",- "stale_signal_days",- "stale_log_days",- "weekly_start_dow",- "daily_window_offset_hours",- ],- "temporal",- source,- warnings,- knownBlockKeys,- );- temporal = Object.keys(partialTp).length > 0 ? (partialTp as BrainTemporalConfig) : {};- }-- // Optional `health:` block (v0.14.0). Shape:- // health:- // contradiction_jaccard: 0.5 # float in (0, 1]- // concept_gap_min_frequency: 3 # positive integer- // stale_claim_max_age_days: 180- // remediation_step_cap: 20- // silence_before: "2026-01-01" # ISO date/timestamp (watermark)- // Absent block β `cfg.health` undefined; resolveHealth returns the- // bit-identical defaults.- let health: BrainHealthConfig | undefined;- if (hasBlock(obj, "health", knownBlockKeys)) {- const rawH = obj["health"];- const hObj = requireMapBlock(rawH, "health", source);- const partialH: Record<string, unknown> = {};- if ("contradiction_jaccard" in hObj) {- const v = hObj["contradiction_jaccard"];- if (typeof v !== "number" || !Number.isFinite(v) || v <= 0 || v > 1) {- throw new BrainConfigError(- "must be a finite number in (0, 1]",- "health.contradiction_jaccard",- source,- );- }- partialH["contradiction_jaccard"] = v;- }- const positiveIntKeys: ReadonlyArray<- "concept_gap_min_frequency" | "stale_claim_max_age_days" | "remediation_step_cap"- > = ["concept_gap_min_frequency", "stale_claim_max_age_days", "remediation_step_cap"];- for (const key of positiveIntKeys) {- if (key in hObj) {- const v = hObj[key];- if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {- throw new BrainConfigError("must be a positive integer", `health.${key}`, source);- }- partialH[key] = v;- }- }- if ("silence_before" in hObj) {- const v = hObj["silence_before"];- if (typeof v !== "string" || !isValidIsoInstant(v)) {- throw new BrainConfigError(- "must be an ISO-8601 date (YYYY-MM-DD) or timestamp",- "health.silence_before",- source,- );- }- partialH["silence_before"] = v;- }- warnUnknownKeys(- hObj,- [- "contradiction_jaccard",- "concept_gap_min_frequency",- "stale_claim_max_age_days",- "remediation_step_cap",- "silence_before",- ],- "health",- source,- warnings,- knownBlockKeys,- );- health = Object.keys(partialH).length > 0 ? (partialH as BrainHealthConfig) : {};- }-- // Optional `integrity:` block (context-integrity-gates). Shape:- // integrity:- // owner_scope_delivery: off | warn | fail # default off- // embedding_abi: off | warn | fail # default warn- // pack_validity_seconds: 900 # positive integer- // Every value is a hard error when out of range. A gate that clamped- // an unrecognised mode to `off`, or a validity window that silently- // reverted to the default, would be indistinguishable from the- // operator's intent - which is the exact class of silent degradation- // this block exists to gate. Absent block β `cfg.integrity` undefined;- // `resolveIntegrity` returns the bit-identical defaults.- let integrity: BrainIntegrityConfig | undefined;- if (hasBlock(obj, "integrity", knownBlockKeys)) {- const itObj = requireMapBlock(obj["integrity"], "integrity", source);- const partialIt: Record<string, unknown> = {};- for (const key of INTEGRITY_GATE_KEYS) {- if (key in itObj) {- const v = itObj[key];- if (!isGateMode(v)) {- throw new BrainConfigError(- `must be one of ${GATE_MODES.join(", ")}; got ${describe(v)}`,- `integrity.${key}`,- source,- );- }- partialIt[key] = v;- }- }- if ("pack_validity_seconds" in itObj) {- requirePositiveInteger(- "integrity.pack_validity_seconds",- itObj["pack_validity_seconds"],- source,- );- partialIt["pack_validity_seconds"] = itObj["pack_validity_seconds"] as number;- }- warnUnknownKeys(- itObj,- [...INTEGRITY_GATE_KEYS, "pack_validity_seconds"],- "integrity",- source,- warnings,- knownBlockKeys,- );- integrity = Object.keys(partialIt).length > 0 ? (partialIt as BrainIntegrityConfig) : {};- }-- // Optional `notes:` block (v0.11.0). Shape:- // notes:- // read_paths:- // - Daily- // - Journal/Weekly- // Absent block β `cfg.notes` undefined; resolveNotes returns the- // bit-identical defaults (empty `read_paths`). The list is purely- // a READ surface; agents never write to these paths.- let notes: BrainNotesConfig | undefined;- if (hasBlock(obj, "notes", knownBlockKeys)) {- const rawNotes = obj["notes"];- const notesObj = requireMapBlock(rawNotes, "notes", source);- const partialNotes: Record<string, unknown> = {};- if ("read_paths" in notesObj) {- const v = notesObj["read_paths"];- if (!Array.isArray(v)) {- throw new BrainConfigError(- "must be an array of vault-relative folder paths",- "notes.read_paths",- source,- );- }- const cleaned: string[] = [];- v.forEach((entry, idx) => {- if (typeof entry !== "string") {- throw new BrainConfigError(- `must be a string; got ${describe(entry)}`,- `notes.read_paths[${idx}]`,- source,- );- }- const trimmed = entry.trim();- if (trimmed.length === 0) {- throw new BrainConfigError(- "must be a non-empty string",- `notes.read_paths[${idx}]`,- source,- );- }- if (trimmed.startsWith("/") || trimmed.startsWith("\\")) {- throw new BrainConfigError(- "must be a vault-relative path (no leading slash)",- `notes.read_paths[${idx}]`,- source,- );- }- const segments = trimmed.split(/[\\/]/);- if (segments.some((s) => s === "..")) {- throw new BrainConfigError(- "must not contain '..' segments",- `notes.read_paths[${idx}]`,- source,- );- }- cleaned.push(trimmed);- });- partialNotes["read_paths"] = cleaned;- }- // Forward-compat: unknown sub-keys under `notes:` β warning.- warnUnknownKeys(notesObj, ["read_paths"], "notes", source, warnings, knownBlockKeys);- notes = Object.keys(partialNotes).length > 0 ? (partialNotes as BrainNotesConfig) : {};- }-- // Optional `sessions:` block (Memory Integrity Suite). Shape:- // sessions:- // ignore_patterns: ["cron-*"]- // stateless_patterns: ["probe-*"]- // ignore_message_patterns: ["^\\[heartbeat\\]"]- // Session patterns are anchored globs; message patterns are regexes- // (validated lazily at compile time - an invalid regex degrades to a- // capture-boundary warning, never a config error, so a typo cannot- // take the whole Brain config down).- let sessions: BrainSessionsConfig | undefined;- if (hasBlock(obj, "sessions", knownBlockKeys)) {- const rawSessions = obj["sessions"];- const sessionsObj = requireMapBlock(rawSessions, "sessions", source);- const partial: Record<string, unknown> = {};- const LIST_KEYS = ["ignore_patterns", "stateless_patterns", "ignore_message_patterns"];- for (const key of LIST_KEYS) {- if (!(key in sessionsObj)) continue;- const v = sessionsObj[key];- if (!Array.isArray(v)) {- throw new BrainConfigError(- "must be an array of pattern strings",- `sessions.${key}`,- source,- );- }- const cleaned: string[] = [];- v.forEach((entry, idx) => {- if (typeof entry !== "string" || entry.trim().length === 0) {- throw new BrainConfigError(- `must be a non-empty string; got ${describe(entry)}`,- `sessions.${key}[${idx}]`,- source,- );- }- cleaned.push(entry.trim());- });- partial[key] = cleaned;- }- warnUnknownKeys(sessionsObj, LIST_KEYS, "sessions", source, warnings, knownBlockKeys);- sessions = partial as BrainSessionsConfig;- }-- // Optional `schema:` block (runtime schema-pack foundation). Shape:- // schema:- // preference_types: [research, decision]- // signal_types: [observation]- // page_types: [paper]- // log_event_kinds: [milestone]- // aliases: [decision=choice]- // prefixes: [pref=decision]- // link_types: [supports]- // extractable: [decision]- // expert_routing: [decision=schema-author]- // Absent block leaves cfg.schema undefined; consumers merge built-ins- // through resolveSchemaVocabulary.- let schema: BrainSchemaConfig | undefined;- if (hasBlock(obj, "schema", knownBlockKeys)) {- const rawSchema = obj["schema"];- const schemaObj = requireMapBlock(rawSchema, "schema", source);- const partialSchema: Partial<Record<keyof BrainSchemaConfig, ReadonlyArray<string>>> = {};- for (const category of SCHEMA_VOCAB_CATEGORIES) {- if (!(category in schemaObj)) continue;- const value = schemaObj[category];- if (!Array.isArray(value)) {- throw new BrainConfigError(- "must be an array of schema tokens",- `schema.${category}`,- source,- );- }- partialSchema[category] = value;- }- const schemaMetaKeys = [- "aliases",- "prefixes",- "link_types",- "extractable",- "expert_routing",- ] as const;- for (const key of schemaMetaKeys) {- if (!(key in schemaObj)) continue;- const value = schemaObj[key];- if (!Array.isArray(value)) {- throw new BrainConfigError(- "must be an array of schema metadata entries",- `schema.${key}`,- source,- );- }- partialSchema[key] = value.map((entry, index) => {- if (typeof entry !== "string") {- throw new BrainConfigError(- "must be a string schema metadata entry",- `schema.${key}[${index}]`,- source,- );- }- const trimmed = entry.trim();- if (trimmed.length === 0) {- throw new BrainConfigError(- "must be a non-empty schema metadata entry",- `schema.${key}[${index}]`,- source,- );- }- return trimmed;- });- }- warnUnknownKeys(- schemaObj,- [...(SCHEMA_VOCAB_CATEGORIES as ReadonlyArray<string>), ...schemaMetaKeys],- "schema",- source,- warnings,- knownBlockKeys,- );- try {- const declarations = validateSchemaDeclarations(partialSchema);- schema = {- ...declarations,- ...(partialSchema.aliases ? { aliases: partialSchema.aliases } : {}),- ...(partialSchema.prefixes ? { prefixes: partialSchema.prefixes } : {}),- ...(partialSchema.link_types ? { link_types: partialSchema.link_types } : {}),- ...(partialSchema.extractable ? { extractable: partialSchema.extractable } : {}),- ...(partialSchema.expert_routing ? { expert_routing: partialSchema.expert_routing } : {}),- } as BrainSchemaConfig;- } catch (err) {- if (err instanceof SchemaVocabularyError) {- const detail = err.message.startsWith(`${err.field}: `)- ? err.message.slice(err.field.length + 2)- : err.message;- throw new BrainConfigError(detail, err.field, source);- }- throw err;- }- }-- // Optional `hygiene:` block (continuity-hygiene-freshness suite).- let hygiene: BrainHygieneConfig | undefined;- if (hasBlock(obj, "hygiene", knownBlockKeys)) {- const raw = obj["hygiene"];- const rawMap = requireMapBlock(raw, "hygiene", source);- const partial: { resolver_cmd?: string; dedup_threshold?: number } = {};- if ("resolver_cmd" in rawMap) {- const cmd = rawMap["resolver_cmd"];- if (typeof cmd !== "string" || cmd.trim() === "") {- throw new BrainConfigError(- `must be a non-empty string; got ${describe(cmd)}`,- "hygiene.resolver_cmd",- source,- );- }- partial.resolver_cmd = cmd;- }- if ("dedup_threshold" in rawMap) {- const threshold = rawMap["dedup_threshold"];- if (typeof threshold !== "number" || !(threshold > 0) || threshold > 1) {- throw new BrainConfigError(- `must be a number in (0, 1]; got ${describe(threshold)}`,- "hygiene.dedup_threshold",- source,- );- }- partial.dedup_threshold = threshold;- }- warnUnknownKeys(rawMap, HYGIENE_KEYS, "hygiene", source, warnings, knownBlockKeys);- hygiene = Object.freeze(partial);- }-- // Optional `anticipatory:` block (continuity-hygiene-freshness suite).- let anticipatory: BrainAnticipatoryConfig | undefined;- if (hasBlock(obj, "anticipatory", knownBlockKeys)) {- const raw = obj["anticipatory"];- const rawMap = requireMapBlock(raw, "anticipatory", source);- const partial: { ttl_seconds?: number; max_tokens?: number } = {};- if ("ttl_seconds" in rawMap) {- requirePositiveInteger("anticipatory.ttl_seconds", rawMap["ttl_seconds"], source);- partial.ttl_seconds = rawMap["ttl_seconds"] as number;- }- if ("max_tokens" in rawMap) {- requirePositiveInteger("anticipatory.max_tokens", rawMap["max_tokens"], source);- partial.max_tokens = rawMap["max_tokens"] as number;- }- warnUnknownKeys(rawMap, ANTICIPATORY_KEYS, "anticipatory", source, warnings, knownBlockKeys);- anticipatory = Object.freeze(partial);- }-- // Optional `recall:` block (continuity-hygiene-freshness suite).- let recall: BrainRecallConfig | undefined;- if (hasBlock(obj, "recall", knownBlockKeys)) {- const raw = obj["recall"];- const rawMap = requireMapBlock(raw, "recall", source);- const partial: { degradation?: "hard-cut" | "staged" } = {};- if ("degradation" in rawMap) {- const mode = rawMap["degradation"];- if (mode !== "hard-cut" && mode !== "staged") {- throw new BrainConfigError(- `must be 'hard-cut' or 'staged'; got ${describe(mode)}`,- "recall.degradation",- source,- );- }- partial.degradation = mode;- }- warnUnknownKeys(rawMap, RECALL_KEYS, "recall", source, warnings, knownBlockKeys);- recall = Object.freeze(partial);- }-- // Optional `feedback:` block (default-scope-feedback suite). Validates a- // vault-default scope applied to feedback signal writes that omit an- // explicit per-call scope. Constraints mirror the signal `scope` field- // exactly (non-empty after trim, single-line, <= SCOPE_MAX_LEN) so a- // configured default can never pass validation yet fail at write time.- let feedback: BrainFeedbackConfig | undefined;- if (hasBlock(obj, "feedback", knownBlockKeys)) {- const raw = obj["feedback"];- const rawMap = requireMapBlock(raw, "feedback", source);- const partial: { default_scope?: string } = {};- if ("default_scope" in rawMap) {- const value = rawMap["default_scope"];- if (typeof value !== "string") {- throw new BrainConfigError(- `must be a string; got ${describe(value)}`,- "feedback.default_scope",- source,- );- }- const trimmed = value.trim();- if (trimmed === "") {- throw new BrainConfigError(- `must be a non-empty single-line scope slug`,- "feedback.default_scope",- source,- );- }- if (/[\n\r]/.test(value)) {- throw new BrainConfigError(- `must be single-line (no newline characters)`,- "feedback.default_scope",- source,- );- }- if (trimmed.length > SCOPE_MAX_LEN) {- throw new BrainConfigError(- `must be at most ${SCOPE_MAX_LEN} characters; got ${trimmed.length}`,- "feedback.default_scope",- source,- );- }- partial.default_scope = trimmed;- }- // Forward-compat: unknown sub-keys under `feedback:` β warning.- warnUnknownKeys(rawMap, ["default_scope"], "feedback", source, warnings, knownBlockKeys);- feedback = Object.freeze(partial);- }-- // Forward-compat: unknown top-level keys β warning, not error. Runs- // last (every block above has had a chance to register itself into- // `knownBlockKeys` via `hasBlock`/`mergeBlock`) so a block can never be- // parsed-but-not-yet-known at the point this check reads the set. Uses- // its own message format (distinct from `warnUnknownKeys`'s- // `block.key: ...` shape), pinned by an existing test.- for (const key of Object.keys(obj)) {- if (!knownBlockKeys.topLevel.has(key)) {- warnings.push({- path: source ?? "<config>",- message: `unknown top-level field '${key}' ignored (forward-compat)`,- });- }- }-- const config: BrainConfig = {- schema_version: schemaVersion,- primary_agent: primaryAgent,- dream: {- candidate_threshold: dream.candidate_threshold as number,- unconfirmed_window_days: dream.unconfirmed_window_days as number,- contradiction_window_days: dream.contradiction_window_days as number,- // Brain lifecycle suite F6: opt-in heal-phase enrichment. Absent- // or non-boolean coerces to false so the default install stays- // byte-identical (the heal phase becomes a checkpoint-only no-op).- heal_enrich_enabled: dream.heal_enrich_enabled === true,- },- retire: {- stale_evidence_days: retire.stale_evidence_days as number,- // Absent stays absent: `undefined` is the documented "gate off"- // state the dream pass branches on, so spreading the key in- // unconditionally would change `retire` from omitting it to- // carrying an explicit undefined.- ...(retire.confirmed_evidence_min_threshold !== undefined- ? { confirmed_evidence_min_threshold: retire.confirmed_evidence_min_threshold as number }- : {}),- },- confidence: {- low_max_applied: confidence.low_max_applied as number,- medium_min: confidence.medium_min as number,- high_min: confidence.high_min as number,- },- snapshots: {- retention_count: snapshots.retention_count as number,- },- ...(vault !== undefined ? { vault } : {}),- ...(active !== undefined ? { active } : {}),- ...(lessons !== undefined ? { lessons } : {}),- ...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),- ...(rollup !== undefined ? { rollup } : {}),- ...(guardrails !== undefined ? { guardrails } : {}),- ...(linkGraph !== undefined ? { link_graph: linkGraph } : {}),- ...(temporal !== undefined ? { temporal } : {}),- ...(notes !== undefined ? { notes } : {}),- ...(sessions !== undefined ? { sessions } : {}),- ...(health !== undefined ? { health } : {}),- ...(integrity !== undefined ? { integrity } : {}),- ...(schema !== undefined ? { schema } : {}),- ...(hygiene !== undefined ? { hygiene } : {}),- ...(anticipatory !== undefined ? { anticipatory } : {}),- ...(recall !== undefined ? { recall } : {}),- ...(feedback !== undefined ? { feedback } : {}),- };-- return { config, warnings, knownKeys: knownBlockKeys };-}--// ----- Helpers ----------------------------------------------------------------/**- * Merge a parsed block (or `undefined`) with its default, returning a- * plain object whose value types are validated downstream. A non-object- * block (string, number, array) is a hard error β the user probably- * miswrote the YAML.- */-/**- * Narrow a raw config value to a plain object, or throw a field-named- * `BrainConfigError`. Centralizes the "block must be a map of keys" guard- * that used to be copy-pasted at every optional-block site with two- * slightly different wordings ("must be a mapping" vs "must be a map of- * keys") - callers get one consistent message (`BrainConfigError` already- * prepends the block's `field` name, so the message itself does not repeat- * it).- */-function requireMapBlock(- raw: unknown,- blockKey: string,- source: string | null,-): Record<string, unknown> {- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {- throw new BrainConfigError(`must be a map of keys; got ${describe(raw)}`, blockKey, source);- }- return raw as Record<string, unknown>;-}--/**- * Push one forward-compat warning per key in `map` that isn't in `known`.- * Replaces the per-block loop that used to mix `Set`, chained `!==`, and- * (elsewhere) `.includes` for the same "unknown sub-key" check, each with- * its own copy of the `${blockName}.${key}: unknown field ignored- * (forward-compat)` message.- */-function warnUnknownKeys(- map: Readonly<Record<string, unknown>>,- known: ReadonlySet<string> | ReadonlyArray<string>,- blockName: string,- source: string | null,- warnings: BrainConfigLoadWarning[],- knownBlockKeys: KeyIndexCollector,-): void {- const knownSet = known instanceof Set ? known : new Set(known);- knownBlockKeys.addSub(blockName, knownSet);- for (const key of Object.keys(map)) {- if (!knownSet.has(key)) {- warnings.push({- path: source ?? "<config>",- message: `${blockName}.${key}: unknown field ignored (forward-compat)`,- });- }- }-}--function mergeBlock(- blockKey: string,- raw: unknown,- fallback: Readonly<Record<string, number>>,- source: string | null,- knownBlockKeys: KeyIndexCollector,- optionalKeys: ReadonlyArray<string> = [],-): Record<string, unknown> {- knownBlockKeys.addTop(blockKey);- knownBlockKeys.addSub(blockKey, [...Object.keys(fallback), ...optionalKeys]);- if (raw === undefined) {- return { ...fallback };- }- const rawMap = requireMapBlock(raw, blockKey, source);- const merged: Record<string, unknown> = { ...fallback };- for (const [k, v] of Object.entries(rawMap)) {- merged[k] = v;- }- return merged;-}--/**- * Record that this call site checked for `key` at the top level, then- * report whether it's present. Every top-level block/field presence- * check (`"vault" in obj`, etc.) MUST go through this - or `mergeBlock`,- * for the four blocks that merge onto numeric defaults instead of being- * fully optional - so `knownBlockKeys` can never drift from the set of- * keys this function actually understands (the bug class fixed in- * phase 0: four blocks were parsed but missing from a hand-maintained- * `known` list, so valid config produced a false "unknown field"- * warning). A key that is never checked can never be "known", by- * construction - there is no separate list to forget to update.- */-function hasBlock(- obj: Record<string, unknown>,- key: string,- knownBlockKeys: KeyIndexCollector,-): boolean {- knownBlockKeys.addTop(key);- return key in obj;-}--/**- * Mutable accumulator behind {@link BrainConfigKeyIndex}. Every helper- * that branches on a key registers it here, so the index is a- * by-construction record of what the validator understands rather than a- * second list that can drift from the first.- */-class KeyIndexCollector implements BrainConfigKeyIndex {- readonly topLevel = new Set<string>();- readonly subKeys = new Map<string, ReadonlySet<string>>();-- addTop(key: string): void {- this.topLevel.add(key);- }-- addSub(block: string, keys: Iterable<string>): void {- const merged = new Set(this.subKeys.get(block) ?? []);- for (const key of keys) merged.add(key);- this.subKeys.set(block, merged);- }-}--/**- * Probe source label used by {@link brainConfigKnownKeys}. Never reaches- * a user-visible surface: the probe discards its warnings.- */-const KEY_INDEX_PROBE_SOURCE = "<brain-config-key-index>";--/**- * Every configuration key {@link validateBrainConfigDetailed} branches- * on, enumerated by running the validator rather than by reading a list.*- * Two passes are needed because a block's sub-key vocabulary is only- * declared inside the branch that parses the block: pass one discovers- * the top-level keys against a minimal config, pass two re-runs with- * every discovered block present but empty so each block's sub-key- * registration executes. Scalar top-level keys keep their default value- * in pass two - handing `primary_agent` an empty map would (correctly)- * be rejected.- */-export function brainConfigKnownKeys(): BrainConfigKeyIndex {- const minimal: Record<string, unknown> = {- schema_version: BRAIN_CONFIG_SUPPORTED_VERSIONS[0],- };- const firstPass = validateBrainConfigDetailed(minimal, KEY_INDEX_PROBE_SOURCE).knownKeys;- const defaults = DEFAULT_BRAIN_CONFIG as unknown as Record<string, unknown>;- const probe: Record<string, unknown> = { ...minimal };- for (const key of firstPass.topLevel) {- if (key in minimal) continue;- const fallback = defaults[key];- const isScalar = key in defaults && (fallback === null || typeof fallback !== "object");- probe[key] = isScalar ? fallback : {};- }- return validateBrainConfigDetailed(probe, KEY_INDEX_PROBE_SOURCE).knownKeys;-}--function requirePositiveInteger(field: string, value: unknown, source: string | null): void {- if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {- throw new BrainConfigError(`must be a positive integer; got ${describe(value)}`, field, source);- }-}--function requireNonNegativeInteger(field: string, value: unknown, source: string | null): void {- if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {- throw new BrainConfigError(- `must be a non-negative integer; got ${describe(value)}`,- field,- source,- );- }-}--function requireUnitInterval(field: string, value: unknown, source: string | null): void {- if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {- throw new BrainConfigError(`must be a number in [0, 1]; got ${describe(value)}`, field, source);- }-}--/**- * Read an optional integer field bounded to `[min, max]` from a config- * sub-map. Returns `undefined` when the key is absent; throws a- * {@link BrainConfigError} (never clamps) when present but out of range- * or non-integer. Shared by the `lessons:` block loader.- */-function readBoundedInt(- map: Record<string, unknown>,- key: string,- min: number,- max: number,- source: string | null,- field: string = `lessons.${key}`,-): number | undefined {- if (!(key in map)) return undefined;- const raw = map[key];- if (typeof raw !== "number" || !Number.isInteger(raw) || raw < min || raw > max) {- throw new BrainConfigError(- `must be an integer between ${min} and ${max}; got ${describe(raw)}`,- field,- source,- );- }- return raw;-}--function describe(value: unknown): string {- if (value === null) return "null";- if (value === undefined) return "undefined";- if (Array.isArray(value)) return `array(${value.length})`;- if (typeof value === "object") return "object";- return `${typeof value}(${JSON.stringify(value)})`;-}+ * This module is the PUBLIC SURFACE only. The implementation lives under+ * `./policy/`, split so each part has one reason to change:+ *+ * - `policy/errors.ts` β the diagnostic vocabulary+ * - `policy/field-checks.ts` β the scalar/shape constraints+ * - `policy/key-index.ts` β the by-construction key vocabulary+ * - `policy/defaults.ts` β the `_brain.yaml` a fresh vault gets+ * - `policy/primary-agent.ts`β the agent-id grammar, read and written+ * - `policy/blocks/*.ts` β one module per configuration block,+ * each owning its defaults, its read-side+ * resolver and its parser together+ * - `policy/validate.ts` β the block sequence+ * - `policy/load.ts` β the disk read and its fallback policy+ */++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 { formatPrimaryAgentYamlValue } from "./policy/primary-agent.ts";+export {+ brainConfigKnownKeys,+ validateBrainConfig,+ validateBrainConfigDetailed,+ type ValidateResult,+} from "./policy/validate.ts";+export {+ brainConfigReadFailure,+ brainConfigUnreadableReport,+ loadActiveMostAppliedSafe,+ loadBrainConfig,+ loadBrainConfigDetailed,+ loadFeedbackDefaultScopeSafe,+ loadGuardrailsConfigSafe,+ loadIntegrityConfigSafe,+ loadNotesConfigSafe,+ loadSnapshotRetentionSafe,+ loadTemporalConfigSafe,+ type LoadBrainConfigResult,+} from "./policy/load.ts";++export {+ BRAIN_MOST_APPLIED_DEFAULTS,+ INJECT_BUDGET_CHARS_DEFAULT,+ INJECT_BUDGET_CHARS_MAX,+ INJECT_BUDGET_CHARS_MIN,+ MOST_APPLIED_LIMIT_DEFAULT,+ MOST_APPLIED_LIMIT_MAX,+ MOST_APPLIED_LIMIT_MIN,+ MOST_APPLIED_WINDOW_DAYS_DEFAULT,+ MOST_APPLIED_WINDOW_DAYS_MAX,+ MOST_APPLIED_WINDOW_DAYS_MIN,+} from "./policy/blocks/active.ts";+export {+ LESSONS_CORROBORATION_MIN_DEFAULT,+ LESSONS_CORROBORATION_MIN_MAX,+ LESSONS_CORROBORATION_MIN_MIN,+ LESSONS_HALF_LIFE_DAYS_DEFAULT,+ LESSONS_HALF_LIFE_DAYS_MAX,+ LESSONS_HALF_LIFE_DAYS_MIN,+ LESSONS_LIMIT_DEFAULT,+ LESSONS_LIMIT_MAX,+ LESSONS_LIMIT_MIN,+} from "./policy/blocks/lessons.ts";+export {+ BRAIN_GUARDRAIL_DEFAULTS,+ INSTRUCTION_FILE_MAX_LINES_CEILING,+ resolveGuardrails,+} from "./policy/blocks/guardrails.ts";+export {+ BRAIN_INTEGRITY_DEFAULTS,+ BRAIN_INTEGRITY_STRICT_FALLBACK,+ PACK_VALIDITY_SECONDS_DEFAULT,+ resolveIntegrity,+} from "./policy/blocks/integrity.ts";+export { BRAIN_HEALTH_DEFAULTS, resolveHealth } from "./policy/blocks/health.ts";+export { BRAIN_TEMPORAL_DEFAULTS, resolveTemporal } from "./policy/blocks/temporal.ts";+export { BRAIN_LINK_GRAPH_DEFAULTS, resolveLinkGraph } from "./policy/blocks/link-graph.ts";+export { BRAIN_NOTES_DEFAULTS, resolveNotes } from "./policy/blocks/notes.ts";+export { BRAIN_SESSIONS_DEFAULTS, resolveSessions } from "./policy/blocks/sessions.ts";diff --git a/src/core/brain/policy/blocks/active.ts b/src/core/brain/policy/blocks/active.tsnew file mode 100644index 00000000..03489e81--- /dev/null+++ b/src/core/brain/policy/blocks/active.ts@@ -0,0 +1,133 @@+/**+ * 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.+ * 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 { requireIntegerInRange } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "active";++/**+ * Bounds applied to `active.most_applied.{window_days, limit}` at load+ * time. Values outside these ranges are hard errors β clamping silently+ * would mask the operator's intent.+ */+export const MOST_APPLIED_WINDOW_DAYS_MIN = 1;+export const MOST_APPLIED_WINDOW_DAYS_MAX = 365;+export const MOST_APPLIED_LIMIT_MIN = 1;+export const MOST_APPLIED_LIMIT_MAX = 50;+/** Default window when `_brain.yaml` lacks `active.most_applied.window_days`. */+export const MOST_APPLIED_WINDOW_DAYS_DEFAULT = 30;+/** Default top-N limit when `_brain.yaml` lacks `active.most_applied.limit`. */+export const MOST_APPLIED_LIMIT_DEFAULT = 10;++/**+ * The window every most-applied consumer uses when `_brain.yaml` does not+ * configure one. One struct rather than two loose constants, because both+ * readers of this block (`active.md` and the digest) need the pair+ * together and a half-taken default would report a window the operator+ * never chose.+ */+export const BRAIN_MOST_APPLIED_DEFAULTS: BrainMostAppliedConfig = Object.freeze({+ window_days: MOST_APPLIED_WINDOW_DAYS_DEFAULT,+ limit: MOST_APPLIED_LIMIT_DEFAULT,+});++/**+ * Character budget for the active.md body injected at SessionStart+ * (token-diet, t_40eb1de7). ~2K tokens - enough for every confirmed+ * rule on a typical vault, small enough that a runaway preference set+ * cannot flood the session preamble. Override via+ * `active.inject_budget_chars`.+ */+export const INJECT_BUDGET_CHARS_DEFAULT = 8000;+export const INJECT_BUDGET_CHARS_MIN = 500;+export const INJECT_BUDGET_CHARS_MAX = 200_000;++const KNOWN_KEYS = [+ "most_applied_window_days",+ "most_applied_limit",+ "inject_budget_chars",+] as const;++/**+ * The YAML keys are flat at level 2 to fit the existing two-level+ * parser; the in-memory shape `BrainActiveConfig.most_applied` still+ * groups them so downstream consumers (`active.md`, `brain_digest`)+ * can pass one struct around.+ */+export function parseActiveBlock(ctx: BlockParseContext): BrainActiveConfig | undefined {+ const activeMap = openBlock(ctx, BLOCK);+ if (activeMap === undefined) return undefined;++ const 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;+ }++ warnUnknownKeys(ctx, activeMap, KNOWN_KEYS, BLOCK);+ return {+ ...(mostApplied !== undefined ? { most_applied: mostApplied } : {}),+ ...(injectBudgetChars !== undefined ? { inject_budget_chars: injectBudgetChars } : {}),+ };+}++/**+ * Read side of `active.most_applied`: the configured window, or+ * {@link BRAIN_MOST_APPLIED_DEFAULTS} when the block (or the whole+ * `active:` section) was omitted. Shared by `active.md` and the digest so+ * the two cannot report different windows for the same vault.+ */+export function resolveMostApplied(cfg: BrainConfig): BrainMostAppliedConfig {+ return cfg.active?.most_applied ?? BRAIN_MOST_APPLIED_DEFAULTS;+}++/**+ * Either key alone opts the block in; the other one falls back to its+ * default, so `most_applied` is always a complete struct or absent+ * entirely and consumers never see a half-configured window.+ */+function parseMostApplied(+ activeMap: Readonly<Record<string, unknown>>,+ source: string | null,+): BrainMostAppliedConfig | undefined {+ const hasWindow = "most_applied_window_days" in activeMap;+ const hasLimit = "most_applied_limit" in activeMap;+ if (!hasWindow && !hasLimit) return undefined;++ const windowDays = hasWindow+ ? activeMap["most_applied_window_days"]+ : MOST_APPLIED_WINDOW_DAYS_DEFAULT;+ const limit = hasLimit ? activeMap["most_applied_limit"] : MOST_APPLIED_LIMIT_DEFAULT;+ requireIntegerInRange(+ "active.most_applied_window_days",+ windowDays,+ MOST_APPLIED_WINDOW_DAYS_MIN,+ MOST_APPLIED_WINDOW_DAYS_MAX,+ source,+ );+ requireIntegerInRange(+ "active.most_applied_limit",+ limit,+ MOST_APPLIED_LIMIT_MIN,+ MOST_APPLIED_LIMIT_MAX,+ source,+ );+ return { window_days: windowDays as number, limit: limit as number };+}diff --git a/src/core/brain/policy/blocks/continuity-hygiene.ts b/src/core/brain/policy/blocks/continuity-hygiene.tsnew file mode 100644index 00000000..95a39966--- /dev/null+++ b/src/core/brain/policy/blocks/continuity-hygiene.ts@@ -0,0 +1,96 @@+/**+ * The three blocks of the continuity-hygiene-freshness suite:+ * `hygiene:`, `anticipatory:` and `recall:`.+ *+ * One reason to change: how the suite trades freshness against cost β+ * what resolves a conflict, how long an anticipatory answer stays warm,+ * and how a budget overrun is trimmed. They ship and change as one+ * feature, which is why they share a module.+ */++import type {+ BrainAnticipatoryConfig,+ BrainHygieneConfig,+ BrainRecallConfig,+} from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { describe, requirePositiveInteger } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const HYGIENE_KEYS = ["resolver_cmd", "dedup_threshold"] as const;+const ANTICIPATORY_KEYS = ["ttl_seconds", "max_tokens"] as const;+const RECALL_KEYS = ["degradation"] as const;++/** The two per-entry budget trim strategies `recall.degradation` selects. */+const RECALL_DEGRADATION_MODES = ["hard-cut", "staged"] as const;++/**+ * `resolver_cmd` is operator-configured only - it is never accepted from+ * a tool argument, so this is the single place it can enter the process.+ */+export function parseHygieneBlock(ctx: BlockParseContext): BrainHygieneConfig | undefined {+ const rawMap = openBlock(ctx, "hygiene");+ if (rawMap === undefined) return undefined;++ const partial: { resolver_cmd?: string; dedup_threshold?: number } = {};+ if ("resolver_cmd" in rawMap) {+ const cmd = rawMap["resolver_cmd"];+ if (typeof cmd !== "string" || cmd.trim() === "") {+ throw new BrainConfigError(+ `must be a non-empty string; got ${describe(cmd)}`,+ "hygiene.resolver_cmd",+ ctx.source,+ );+ }+ partial.resolver_cmd = cmd;+ }+ if ("dedup_threshold" in rawMap) {+ const threshold = rawMap["dedup_threshold"];+ if (typeof threshold !== "number" || !(threshold > 0) || threshold > 1) {+ throw new BrainConfigError(+ `must be a number in (0, 1]; got ${describe(threshold)}`,+ "hygiene.dedup_threshold",+ ctx.source,+ );+ }+ partial.dedup_threshold = threshold;+ }+ warnUnknownKeys(ctx, rawMap, HYGIENE_KEYS, "hygiene");+ return Object.freeze(partial);+}++export function parseAnticipatoryBlock(+ ctx: BlockParseContext,+): BrainAnticipatoryConfig | undefined {+ const rawMap = openBlock(ctx, "anticipatory");+ if (rawMap === undefined) return undefined;++ const partial: { ttl_seconds?: number; max_tokens?: number } = {};+ for (const key of ANTICIPATORY_KEYS) {+ if (!(key in rawMap)) continue;+ requirePositiveInteger(`anticipatory.${key}`, rawMap[key], ctx.source);+ partial[key] = rawMap[key] as number;+ }+ warnUnknownKeys(ctx, rawMap, ANTICIPATORY_KEYS, "anticipatory");+ return Object.freeze(partial);+}++export function parseRecallBlock(ctx: BlockParseContext): BrainRecallConfig | undefined {+ const rawMap = openBlock(ctx, "recall");+ if (rawMap === undefined) return undefined;++ const partial: { degradation?: (typeof RECALL_DEGRADATION_MODES)[number] } = {};+ if ("degradation" in rawMap) {+ const mode = rawMap["degradation"];+ if (mode !== "hard-cut" && mode !== "staged") {+ throw new BrainConfigError(+ `must be 'hard-cut' or 'staged'; got ${describe(mode)}`,+ "recall.degradation",+ ctx.source,+ );+ }+ partial.degradation = mode;+ }+ warnUnknownKeys(ctx, rawMap, RECALL_KEYS, "recall");+ return Object.freeze(partial);+}diff --git a/src/core/brain/policy/blocks/discipline-report.ts b/src/core/brain/policy/blocks/discipline-report.tsnew file mode 100644index 00000000..2eafa0c4--- /dev/null+++ b/src/core/brain/policy/blocks/discipline-report.ts@@ -0,0 +1,87 @@+/**+ * The `discipline_report:` section (Β§D of the agent-discipline-tail+ * design).+ *+ * One reason to change: what the daily discipline report needs to be+ * configured with. This is the only block that WARNS AND DROPS instead of+ * throwing: the report is an optional side surface, and a malformed+ * section must not take the rest of the CLI down with it. Every field is+ * mandatory once the section is present, so a partial section is dropped+ * whole rather than half-applied.+ */++import type { DisciplineReportConfig } from "../../types.ts";+import { describe } from "../field-checks.ts";+import { hasBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "discipline_report";++const KNOWN_KEYS = ["enabled", "timezone", "watched_paths", "known_agents"] as const;++const IGNORED = "section ignored";++export function parseDisciplineReportBlock(+ ctx: BlockParseContext,+): DisciplineReportConfig | undefined {+ if (!hasBlock(ctx.obj, BLOCK, ctx.keys)) return undefined;+ const dr = ctx.obj[BLOCK];+ if (typeof dr !== "object" || dr === null || Array.isArray(dr)) {+ warn(ctx, `${BLOCK}: must be a map of keys; got ${describe(dr)} β ${IGNORED}`);+ return undefined;+ }++ const drObj = dr as Record<string, unknown>;+ warnUnknownKeys(ctx, drObj, KNOWN_KEYS, BLOCK);+ let ok = true;++ if (typeof drObj["enabled"] !== "boolean") {+ warn(+ ctx,+ `${BLOCK}.enabled: must be a boolean; got ${describe(drObj["enabled"])} β ${IGNORED}`,+ );+ ok = false;+ }+ if (typeof drObj["timezone"] !== "string") {+ warn(+ ctx,+ `${BLOCK}.timezone: must be a string; got ${describe(drObj["timezone"])} β ${IGNORED}`,+ );+ ok = false;+ }+ if (!checkStringArray(ctx, drObj, "watched_paths")) ok = false;+ if (!checkStringArray(ctx, drObj, "known_agents")) ok = false;++ if (!ok) return undefined;+ return {+ enabled: drObj["enabled"] as boolean,+ timezone: drObj["timezone"] as string,+ watched_paths: drObj["watched_paths"] as ReadonlyArray<string>,+ known_agents: drObj["known_agents"] as ReadonlyArray<string>,+ };+}++/** Warn on a non-array or on the first non-string entry; never throws. */+function checkStringArray(+ ctx: BlockParseContext,+ drObj: Readonly<Record<string, unknown>>,+ key: string,+): boolean {+ const value = drObj[key];+ if (!Array.isArray(value)) {+ warn(ctx, `${BLOCK}.${key}: must be an array; got ${describe(value)} β ${IGNORED}`);+ return false;+ }+ const badIdx = (value as unknown[]).findIndex((v) => typeof v !== "string");+ if (badIdx >= 0) {+ warn(+ ctx,+ `${BLOCK}.${key}[${badIdx}]: must be a string; got ${describe((value as unknown[])[badIdx])} β ${IGNORED}`,+ );+ return false;+ }+ return true;+}++function warn(ctx: BlockParseContext, message: string): void {+ ctx.warnings.push({ path: ctx.source ?? "<config>", message });+}diff --git a/src/core/brain/policy/blocks/feedback.ts b/src/core/brain/policy/blocks/feedback.tsnew file mode 100644index 00000000..4a994e6d--- /dev/null+++ b/src/core/brain/policy/blocks/feedback.ts@@ -0,0 +1,53 @@+/**+ * The `feedback:` block (default-scope-feedback suite) β the vault-wide+ * default scope for feedback signal writes that pass none.+ *+ * One reason to change: what a vault-default scope may be. The+ * constraints mirror the signal `scope` field exactly (non-empty after+ * trim, single-line, at most {@link SCOPE_MAX_LEN}) so a configured+ * default can never pass validation here yet fail at write time.+ */++import type { BrainFeedbackConfig } from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { describe } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";+import { SCOPE_MAX_LEN } from "../../signal.ts";++const BLOCK = "feedback";+const FIELD = "feedback.default_scope";++const KNOWN_KEYS = ["default_scope"] as const;++export function parseFeedbackBlock(ctx: BlockParseContext): BrainFeedbackConfig | undefined {+ const rawMap = openBlock(ctx, BLOCK);+ if (rawMap === undefined) return undefined;++ const partial: { default_scope?: string } = {};+ if ("default_scope" in rawMap) {+ partial.default_scope = cleanScope(rawMap["default_scope"], ctx.source);+ }+ warnUnknownKeys(ctx, rawMap, KNOWN_KEYS, BLOCK);+ return Object.freeze(partial);+}++function cleanScope(value: unknown, source: string | null): string {+ if (typeof value !== "string") {+ throw new BrainConfigError(`must be a string; got ${describe(value)}`, FIELD, source);+ }+ const trimmed = value.trim();+ if (trimmed === "") {+ throw new BrainConfigError("must be a non-empty single-line scope slug", FIELD, source);+ }+ if (/[\n\r]/.test(value)) {+ throw new BrainConfigError("must be single-line (no newline characters)", FIELD, source);+ }+ if (trimmed.length > SCOPE_MAX_LEN) {+ throw new BrainConfigError(+ `must be at most ${SCOPE_MAX_LEN} characters; got ${trimmed.length}`,+ FIELD,+ source,+ );+ }+ return trimmed;+}diff --git a/src/core/brain/policy/blocks/guardrails.ts b/src/core/brain/policy/blocks/guardrails.tsnew file mode 100644index 00000000..0c13dad9--- /dev/null+++ b/src/core/brain/policy/blocks/guardrails.ts@@ -0,0 +1,190 @@+/**+ * The `guardrails:` block β the dream pass self-approval thresholds and+ * the opt-in provenance toggles.+ *+ * One reason to change: which guardrail knobs exist and what they accept.+ * Default table, read-side resolver and parser sit together because a new+ * guardrail always touches all three.+ */++import type {+ BrainConfig,+ BrainGuardrailConfig,+ ResolvedBrainGuardrailConfig,+} from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { describe, requireNonNegativeInteger, requirePositiveInteger } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "guardrails";++/**+ * Hard upper bound on `guardrails.instruction_file_max_lines`. Any+ * value above this is a misconfiguration - vault-root instruction+ * files are intended to stay small for compliance reasons, so a+ * ceiling like 100000 lines silently disables the warning.+ */+export const INSTRUCTION_FILE_MAX_LINES_CEILING = 10000;++/**+ * Knowledge Provenance opt-in boolean flags (v1.7). Present β must be+ * boolean, else hard error. Named once so the parser, the forward-compat+ * unknown-key warning and the resolver read the same list.+ */+const BOOLEAN_KEYS = [+ "untrusted_source_delimiting",+ "derived_fact_synthesis",+ "provenance_trust_ordering",+ "owner_scoped_facts",+ "marker_writeback",+] as const;++const KNOWN_KEYS = [+ "promotion_min_signals",+ "promotion_min_distinct_agents",+ "promotion_min_age_days",+ "instruction_file_max_lines",+ ...BOOLEAN_KEYS,+] as const;++/**+ * Default `guardrails` block (v0.10.16). When `_brain.yaml` omits+ * `guardrails` (or omits individual fields), `resolveGuardrails`+ * returns these values so consumers can rely on a fully-populated+ * struct.+ *+ * Defaults are chosen to be strictly looser than every existing+ * dream-pass gate so adding the guardrail cannot block a promotion+ * that previously succeeded:+ * - `promotion_min_signals: 1` is below any sane+ * `dream.candidate_threshold` (default 3). When an operator+ * tunes `candidate_threshold` below 2, the guardrail still+ * cannot block them by default - explicit opt-in is required+ * via the `_brain.yaml:guardrails:promotion_min_signals` field.+ * - `promotion_min_distinct_agents: 1` imposes no cross-agent+ * requirement.+ * - `promotion_min_age_days: 0` disables the age gate.+ * - `instruction_file_max_lines: 200` matches the documented+ * compliance ceiling.+ */+export const BRAIN_GUARDRAIL_DEFAULTS: ResolvedBrainGuardrailConfig = Object.freeze({+ promotion_min_signals: 1,+ promotion_min_distinct_agents: 1,+ promotion_min_age_days: 0,+ instruction_file_max_lines: 200,+ untrusted_source_delimiting: false,+ derived_fact_synthesis: false,+ provenance_trust_ordering: false,+ owner_scoped_facts: false,+ marker_writeback: false,+}) as ResolvedBrainGuardrailConfig;++/**+ * Merge a parsed `guardrails` block (or `undefined`) with+ * `BRAIN_GUARDRAIL_DEFAULTS`. Returns a fully-populated struct so+ * consumers do not branch on optional fields.+ */+export function resolveGuardrails(cfg: BrainConfig): ResolvedBrainGuardrailConfig {+ const g = cfg.guardrails;+ if (g === undefined) return BRAIN_GUARDRAIL_DEFAULTS;+ return {+ promotion_min_signals:+ g.promotion_min_signals ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_signals,+ promotion_min_distinct_agents:+ g.promotion_min_distinct_agents ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_distinct_agents,+ promotion_min_age_days:+ g.promotion_min_age_days ?? BRAIN_GUARDRAIL_DEFAULTS.promotion_min_age_days,+ instruction_file_max_lines:+ g.instruction_file_max_lines ?? BRAIN_GUARDRAIL_DEFAULTS.instruction_file_max_lines,+ untrusted_source_delimiting:+ g.untrusted_source_delimiting ?? BRAIN_GUARDRAIL_DEFAULTS.untrusted_source_delimiting,+ derived_fact_synthesis:+ g.derived_fact_synthesis ?? BRAIN_GUARDRAIL_DEFAULTS.derived_fact_synthesis,+ provenance_trust_ordering:+ g.provenance_trust_ordering ?? BRAIN_GUARDRAIL_DEFAULTS.provenance_trust_ordering,+ owner_scoped_facts: g.owner_scoped_facts ?? BRAIN_GUARDRAIL_DEFAULTS.owner_scoped_facts,+ marker_writeback: g.marker_writeback ?? BRAIN_GUARDRAIL_DEFAULTS.marker_writeback,+ };+}++/**+ * Hard-error on shape problems - thresholds are operator-tunable and+ * silent fallback would mask the operator's intent. Missing block leaves+ * `cfg.guardrails` undefined; `resolveGuardrails` injects defaults on the+ * read side so consumers receive a fully-populated struct.+ */+export function parseGuardrailsBlock(ctx: BlockParseContext): BrainGuardrailConfig | undefined {+ const rawMap = openBlock(ctx, BLOCK);+ if (rawMap === undefined) return undefined;++ const partial: {+ promotion_min_signals?: number;+ promotion_min_distinct_agents?: number;+ promotion_min_age_days?: number;+ instruction_file_max_lines?: number;+ untrusted_source_delimiting?: boolean;+ derived_fact_synthesis?: boolean;+ provenance_trust_ordering?: boolean;+ owner_scoped_facts?: boolean;+ marker_writeback?: boolean;+ } = {};++ if ("promotion_min_signals" in rawMap) {+ requirePositiveInteger(+ "guardrails.promotion_min_signals",+ rawMap["promotion_min_signals"],+ ctx.source,+ );+ partial.promotion_min_signals = rawMap["promotion_min_signals"] as number;+ }+ if ("promotion_min_distinct_agents" in rawMap) {+ requirePositiveInteger(+ "guardrails.promotion_min_distinct_agents",+ rawMap["promotion_min_distinct_agents"],+ ctx.source,+ );+ partial.promotion_min_distinct_agents = rawMap["promotion_min_distinct_agents"] as number;+ }+ if ("promotion_min_age_days" in rawMap) {+ requireNonNegativeInteger(+ "guardrails.promotion_min_age_days",+ rawMap["promotion_min_age_days"],+ ctx.source,+ );+ partial.promotion_min_age_days = rawMap["promotion_min_age_days"] as number;+ }+ if ("instruction_file_max_lines" in rawMap) {+ requirePositiveInteger(+ "guardrails.instruction_file_max_lines",+ rawMap["instruction_file_max_lines"],+ ctx.source,+ );+ const v = rawMap["instruction_file_max_lines"] as number;+ if (v > INSTRUCTION_FILE_MAX_LINES_CEILING) {+ throw new BrainConfigError(+ `must be at most ${INSTRUCTION_FILE_MAX_LINES_CEILING}; got ${describe(v)}`,+ "guardrails.instruction_file_max_lines",+ ctx.source,+ );+ }+ partial.instruction_file_max_lines = v;+ }+ for (const key of BOOLEAN_KEYS) {+ if (!(key in rawMap)) continue;+ const flag = rawMap[key];+ if (typeof flag !== "boolean") {+ throw new BrainConfigError(+ `must be a boolean; got ${describe(flag)}`,+ `guardrails.${key}`,+ ctx.source,+ );+ }+ partial[key] = flag;+ }++ warnUnknownKeys(ctx, rawMap, KNOWN_KEYS, BLOCK);+ // A block present but carrying only unknown fields still yields an+ // empty struct, so `cfg.guardrails` stays non-undefined and+ // distinguishable from "block absent entirely".+ return partial;+}diff --git a/src/core/brain/policy/blocks/health.ts b/src/core/brain/policy/blocks/health.tsnew file mode 100644index 00000000..4881aefe--- /dev/null+++ b/src/core/brain/policy/blocks/health.ts@@ -0,0 +1,114 @@+/**+ * The `health:` block β the semantic-health detector thresholds and the+ * remediation step cap.+ *+ * One reason to change: what the health detectors are tuned by.+ */++import type { BrainConfig, BrainHealthConfig, ResolvedBrainHealthConfig } from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";+import { isValidIsoInstant } from "../../health/iso-time.ts";++const BLOCK = "health";++/** Sub-keys whose value is a plain positive integer count of days/steps. */+const POSITIVE_INT_KEYS = [+ "concept_gap_min_frequency",+ "stale_claim_max_age_days",+ "remediation_step_cap",+] as const;++/**+ * Default `health:` block (v0.14.0). Drives the semantic-health+ * detectors and the remediation step cap. Absent block falls back here+ * via `resolveHealth`:+ *+ * - `contradiction_jaccard: 0.5` - two confirmed preferences must+ * share at least half their principle tokens (and carry opposite+ * signs) to count as a contradiction.+ * - `concept_gap_min_frequency: 3` - an entity must recur across 3+ * distinct corpus entries before an uncovered-concept gap fires.+ * - `stale_claim_max_age_days: 180` - 6 months without fresh+ * evidence before a confirmed preference is flagged stale.+ * - `remediation_step_cap: 20` - a single `doctor --remediate` run+ * applies at most 20 auto-safe repairs.+ */+export const BRAIN_HEALTH_DEFAULTS: ResolvedBrainHealthConfig = Object.freeze({+ contradiction_jaccard: 0.5,+ concept_gap_min_frequency: 3,+ stale_claim_max_age_days: 180,+ remediation_step_cap: 20,+ silence_before: null,+}) as ResolvedBrainHealthConfig;++/**+ * Merge a parsed `health` block (or `undefined`) with+ * `BRAIN_HEALTH_DEFAULTS`.+ */+export function resolveHealth(cfg: BrainConfig): ResolvedBrainHealthConfig {+ const h = cfg.health;+ if (h === undefined) return BRAIN_HEALTH_DEFAULTS;+ return {+ contradiction_jaccard: h.contradiction_jaccard ?? BRAIN_HEALTH_DEFAULTS.contradiction_jaccard,+ concept_gap_min_frequency:+ h.concept_gap_min_frequency ?? BRAIN_HEALTH_DEFAULTS.concept_gap_min_frequency,+ stale_claim_max_age_days:+ h.stale_claim_max_age_days ?? BRAIN_HEALTH_DEFAULTS.stale_claim_max_age_days,+ remediation_step_cap: h.remediation_step_cap ?? BRAIN_HEALTH_DEFAULTS.remediation_step_cap,+ silence_before: h.silence_before ?? BRAIN_HEALTH_DEFAULTS.silence_before,+ };+}++/**+ * Shape:+ * health:+ * contradiction_jaccard: 0.5 # float in (0, 1]+ * concept_gap_min_frequency: 3 # positive integer+ * stale_claim_max_age_days: 180+ * remediation_step_cap: 20+ * silence_before: "2026-01-01" # ISO date/timestamp (watermark)+ */+export function parseHealthBlock(ctx: BlockParseContext): BrainHealthConfig | undefined {+ const hObj = openBlock(ctx, BLOCK);+ if (hObj === undefined) return undefined;++ const partial: Record<string, unknown> = {};+ if ("contradiction_jaccard" in hObj) {+ const v = hObj["contradiction_jaccard"];+ if (typeof v !== "number" || !Number.isFinite(v) || v <= 0 || v > 1) {+ throw new BrainConfigError(+ "must be a finite number in (0, 1]",+ "health.contradiction_jaccard",+ ctx.source,+ );+ }+ partial["contradiction_jaccard"] = v;+ }+ for (const key of POSITIVE_INT_KEYS) {+ if (!(key in hObj)) continue;+ const v = hObj[key];+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {+ throw new BrainConfigError("must be a positive integer", `health.${key}`, ctx.source);+ }+ partial[key] = v;+ }+ if ("silence_before" in hObj) {+ const v = hObj["silence_before"];+ if (typeof v !== "string" || !isValidIsoInstant(v)) {+ throw new BrainConfigError(+ "must be an ISO-8601 date (YYYY-MM-DD) or timestamp",+ "health.silence_before",+ ctx.source,+ );+ }+ partial["silence_before"] = v;+ }+ warnUnknownKeys(+ ctx,+ hObj,+ ["contradiction_jaccard", ...POSITIVE_INT_KEYS, "silence_before"],+ BLOCK,+ );+ return partial as BrainHealthConfig;+}diff --git a/src/core/brain/policy/blocks/integrity.ts b/src/core/brain/policy/blocks/integrity.tsnew file mode 100644index 00000000..13325743--- /dev/null+++ b/src/core/brain/policy/blocks/integrity.ts@@ -0,0 +1,150 @@+/**+ * The `integrity:` block β the context-integrity gates and the pack+ * staleness window.+ *+ * One reason to change: which integrity gates exist and how a vault that+ * declares them is read. This module also owns the STRICT fallback, which+ * is deliberately not the default table: see+ * {@link BRAIN_INTEGRITY_STRICT_FALLBACK}.+ */++import type {+ BrainConfig,+ BrainIntegrityConfig,+ ResolvedBrainIntegrityConfig,+} from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { describe, requirePositiveInteger } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";+import { GATE_MODE, GATE_MODES, isGateMode } from "../../../integrity/stamp.ts";++const BLOCK = "integrity";++/**+ * Sub-keys of the `integrity:` block whose value is a gate mode. Named+ * once and reused by the validator, the unknown-key list, and the+ * resolver so the three can never disagree about what the block holds.+ */+const INTEGRITY_GATE_KEYS = ["owner_scope_delivery", "embedding_abi"] as const;++/**+ * How long a context pack stays servable after it was built, when+ * `_brain.yaml` omits `integrity.pack_validity_seconds`.+ *+ * 900 seconds (15 minutes) is the same bound `CRUTCH_LINK_WINDOW_MS`+ * already uses for "still the same working session", so the pack's outer+ * staleness bound and the session-continuity bound agree on what a+ * session is rather than inventing a second, conflicting answer.+ *+ * It is deliberately much longer than the anticipatory cache's 120 s TTL:+ * the provenance stamp is the PRIMARY invalidator (it observes the vault+ * edits that matter), and this window is the backstop for the changes a+ * stamp cannot observe. A short window here would duplicate the TTL and+ * mask which mechanism actually did the invalidating.+ *+ * The value is unbounded above on purpose - unlike the instruction-file+ * ceiling, a large window does not silently disable anything, because+ * the stamp still refuses a drifted pack.+ */+export const PACK_VALIDITY_SECONDS_DEFAULT = 900;++/**+ * Default `integrity:` block (context-integrity-gates). Absent block (or+ * absent individual keys) falls back here via `resolveIntegrity`.+ *+ * Both gate defaults are the modes that leave every existing vault+ * byte-identical:+ * - `owner_scope_delivery: off` - the delivery path documents a "null+ * scope is byte-identical" contract throughout, so defaulting a+ * scope would silently narrow vaults that never opted in. There is+ * no writer surface for `owner` yet, so nothing would be gained.+ * - `embedding_abi: warn` - `vec_version()` is not stable across+ * environments, so two peers on different sqlite-vec builds would+ * each see a mismatch. Refusing by default risks a rebuild loop on a+ * synced vault; reporting cannot.+ */+export const BRAIN_INTEGRITY_DEFAULTS: ResolvedBrainIntegrityConfig = Object.freeze({+ owner_scope_delivery: GATE_MODE.off,+ embedding_abi: GATE_MODE.warn,+ pack_validity_seconds: PACK_VALIDITY_SECONDS_DEFAULT,+}) as ResolvedBrainIntegrityConfig;++/**+ * Gate modes used when `_brain.yaml` EXISTS but cannot be read.+ *+ * Not the defaults: the defaults encode "this operator has said nothing",+ * and an unreadable file is the opposite - the operator said something+ * and we cannot tell what. Collapsing that to the defaults turns+ * `owner_scope_delivery: fail` into `off`, which disables an isolation+ * boundary because of a typo somewhere else in the file, with no signal+ * on any surface. Erring to the strictest mode makes the same typo loud+ * and reversible instead of quiet and permanent.+ *+ * `pack_validity_seconds` is not a gate and has no strict direction, so+ * it keeps the default window.+ */+export const BRAIN_INTEGRITY_STRICT_FALLBACK: ResolvedBrainIntegrityConfig = Object.freeze({+ owner_scope_delivery: GATE_MODE.fail,+ embedding_abi: GATE_MODE.fail,+ pack_validity_seconds: PACK_VALIDITY_SECONDS_DEFAULT,+}) as ResolvedBrainIntegrityConfig;++/**+ * Merge a parsed `integrity` block (or `undefined`) with+ * `BRAIN_INTEGRITY_DEFAULTS`. Resolution happens on the READ side, not+ * at parse time, so `cfg.integrity` keeps recording exactly what the+ * operator wrote and "absent" stays distinguishable from "explicitly set+ * to the default".+ */+export function resolveIntegrity(cfg: BrainConfig): ResolvedBrainIntegrityConfig {+ const it = cfg.integrity;+ if (it === undefined) return BRAIN_INTEGRITY_DEFAULTS;+ return {+ owner_scope_delivery: it.owner_scope_delivery ?? BRAIN_INTEGRITY_DEFAULTS.owner_scope_delivery,+ embedding_abi: it.embedding_abi ?? BRAIN_INTEGRITY_DEFAULTS.embedding_abi,+ pack_validity_seconds:+ it.pack_validity_seconds ?? BRAIN_INTEGRITY_DEFAULTS.pack_validity_seconds,+ };+}++/**+ * Shape:+ * integrity:+ * owner_scope_delivery: off | warn | fail # default off+ * embedding_abi: off | warn | fail # default warn+ * pack_validity_seconds: 900 # positive integer+ *+ * Every value is a hard error when out of range. A gate that clamped an+ * unrecognised mode to `off`, or a validity window that silently reverted+ * to the default, would be indistinguishable from the operator's intent -+ * which is the exact class of silent degradation this block exists to+ * gate.+ */+export function parseIntegrityBlock(ctx: BlockParseContext): BrainIntegrityConfig | undefined {+ const itObj = openBlock(ctx, BLOCK);+ if (itObj === undefined) return undefined;++ const partial: Record<string, unknown> = {};+ for (const key of INTEGRITY_GATE_KEYS) {+ if (!(key in itObj)) continue;+ const v = itObj[key];+ if (!isGateMode(v)) {+ throw new BrainConfigError(+ `must be one of ${GATE_MODES.join(", ")}; got ${describe(v)}`,+ `integrity.${key}`,+ ctx.source,+ );+ }+ partial[key] = v;+ }+ if ("pack_validity_seconds" in itObj) {+ requirePositiveInteger(+ "integrity.pack_validity_seconds",+ itObj["pack_validity_seconds"],+ ctx.source,+ );+ partial["pack_validity_seconds"] = itObj["pack_validity_seconds"] as number;+ }+ warnUnknownKeys(ctx, itObj, [...INTEGRITY_GATE_KEYS, "pack_validity_seconds"], BLOCK);+ return partial as BrainIntegrityConfig;+}diff --git a/src/core/brain/policy/blocks/lessons.ts b/src/core/brain/policy/blocks/lessons.tsnew file mode 100644index 00000000..ac1d6ec6--- /dev/null+++ b/src/core/brain/policy/blocks/lessons.ts@@ -0,0 +1,65 @@+/**+ * The `lessons:` block (t_62363378) β tuning for the signed,+ * recency-scored lessons digest (`Brain/lessons.md`).+ *+ * One reason to change: how a lesson's score decays and when it earns+ * `preferred`. Out-of-range values are hard errors β an operator-tunable+ * knob must never silently clamp. The half-life default matches the+ * working-memory continuity decay (30 days); the corroboration floor+ * (2 distinct results) keeps a one-off application from promoting+ * straight to `preferred`.+ */++import type { BrainLessonsConfig } from "../../types.ts";+import { readBoundedInt } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "lessons";++export const LESSONS_HALF_LIFE_DAYS_DEFAULT = 30;+export const LESSONS_HALF_LIFE_DAYS_MIN = 1;+export const LESSONS_HALF_LIFE_DAYS_MAX = 365;+export const LESSONS_CORROBORATION_MIN_DEFAULT = 2;+export const LESSONS_CORROBORATION_MIN_MIN = 1;+export const LESSONS_CORROBORATION_MIN_MAX = 100;+export const LESSONS_LIMIT_DEFAULT = 20;+export const LESSONS_LIMIT_MIN = 1;+export const LESSONS_LIMIT_MAX = 200;++const KNOWN_KEYS = ["half_life_days", "corroboration_min", "limit"] as const;++export function parseLessonsBlock(ctx: BlockParseContext): BrainLessonsConfig | undefined {+ const lessonsMap = openBlock(ctx, BLOCK);+ if (lessonsMap === undefined) return undefined;++ const halfLife = readBoundedInt(+ lessonsMap,+ "half_life_days",+ LESSONS_HALF_LIFE_DAYS_MIN,+ LESSONS_HALF_LIFE_DAYS_MAX,+ "lessons.half_life_days",+ ctx.source,+ );+ const corroborationMin = readBoundedInt(+ lessonsMap,+ "corroboration_min",+ LESSONS_CORROBORATION_MIN_MIN,+ LESSONS_CORROBORATION_MIN_MAX,+ "lessons.corroboration_min",+ ctx.source,+ );+ const limit = readBoundedInt(+ lessonsMap,+ "limit",+ LESSONS_LIMIT_MIN,+ LESSONS_LIMIT_MAX,+ "lessons.limit",+ ctx.source,+ );+ warnUnknownKeys(ctx, lessonsMap, KNOWN_KEYS, BLOCK);+ return {+ ...(halfLife !== undefined ? { half_life_days: halfLife } : {}),+ ...(corroborationMin !== undefined ? { corroboration_min: corroborationMin } : {}),+ ...(limit !== undefined ? { limit } : {}),+ };+}diff --git a/src/core/brain/policy/blocks/lifecycle.ts b/src/core/brain/policy/blocks/lifecycle.tsnew file mode 100644index 00000000..e489dec4--- /dev/null+++ b/src/core/brain/policy/blocks/lifecycle.ts@@ -0,0 +1,128 @@+/**+ * The four always-present blocks that drive the preference lifecycle:+ * `dream:`, `retire:`, `confidence:`, `snapshots:`.+ *+ * One reason to change: a lifecycle threshold's accepted range. These are+ * the only blocks that merge field-by-field onto {@link+ * DEFAULT_BRAIN_CONFIG}, so an operator can override one threshold+ * without re-stating the rest, and they always appear in the resolved+ * config rather than being absent-or-present like every optional block.+ */++import type {+ BrainConfidenceConfig,+ BrainDreamConfig,+ BrainRetireConfig,+ BrainSnapshotsConfig,+} from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import {+ requireNonNegativeInteger,+ requirePositiveInteger,+ requireUnitInterval,+} from "../field-checks.ts";+import { mergeBlock, type BlockParseContext } from "../key-index.ts";+import { DEFAULT_BRAIN_CONFIG } from "../defaults.ts";++/**+ * Optional `retire:` sub-key with no default. Declared here because+ * `mergeBlock` derives a block's vocabulary from its default table, and+ * a key whose default is "absent" has no entry there.+ */+const RETIRE_OPTIONAL_KEYS = ["confirmed_evidence_min_threshold"] as const;++/**+ * Merge one lifecycle block onto its slice of {@link DEFAULT_BRAIN_CONFIG}.+ * The cast is the one `mergeBlock` already documents: the merged values+ * are `unknown` until the per-field checks below narrow them, and only+ * the DEFAULTS need to be a flat numeric table.+ */+function merge(+ ctx: BlockParseContext,+ blockKey: string,+ fallback: object,+ optionalKeys?: ReadonlyArray<string>,+): Record<string, unknown> {+ return mergeBlock(+ blockKey,+ ctx.obj[blockKey],+ fallback as Readonly<Record<string, number>>,+ ctx.source,+ ctx.keys,+ optionalKeys,+ );+}++export function parseDreamBlock(ctx: BlockParseContext): BrainDreamConfig {+ const dream = merge(ctx, "dream", DEFAULT_BRAIN_CONFIG.dream);+ requirePositiveInteger("dream.candidate_threshold", dream.candidate_threshold, ctx.source);+ requirePositiveInteger(+ "dream.unconfirmed_window_days",+ dream.unconfirmed_window_days,+ ctx.source,+ );+ requirePositiveInteger(+ "dream.contradiction_window_days",+ dream.contradiction_window_days,+ ctx.source,+ );+ return {+ candidate_threshold: dream.candidate_threshold as number,+ unconfirmed_window_days: dream.unconfirmed_window_days as number,+ contradiction_window_days: dream.contradiction_window_days as number,+ // Brain lifecycle suite F6: opt-in heal-phase enrichment. Absent+ // or non-boolean coerces to false so the default install stays+ // byte-identical (the heal phase becomes a checkpoint-only no-op).+ heal_enrich_enabled: dream.heal_enrich_enabled === true,+ };+}++export function parseRetireBlock(ctx: BlockParseContext): BrainRetireConfig {+ const retire = merge(ctx, "retire", DEFAULT_BRAIN_CONFIG.retire, RETIRE_OPTIONAL_KEYS);+ requirePositiveInteger("retire.stale_evidence_days", retire.stale_evidence_days, ctx.source);+ // Optional destructive-from-confirmed gate (v0.12.0). An out-of-range+ // value is a hard error rather than a silently ignored knob.+ if (retire.confirmed_evidence_min_threshold !== undefined) {+ requirePositiveInteger(+ "retire.confirmed_evidence_min_threshold",+ retire.confirmed_evidence_min_threshold,+ ctx.source,+ );+ }+ return {+ stale_evidence_days: retire.stale_evidence_days as number,+ // Absent stays absent: `undefined` is the documented "gate off"+ // state the dream pass branches on, so spreading the key in+ // unconditionally would change `retire` from omitting it to+ // carrying an explicit undefined.+ ...(retire.confirmed_evidence_min_threshold !== undefined+ ? { confirmed_evidence_min_threshold: retire.confirmed_evidence_min_threshold as number }+ : {}),+ };+}++export function parseConfidenceBlock(ctx: BlockParseContext): BrainConfidenceConfig {+ const confidence = merge(ctx, "confidence", DEFAULT_BRAIN_CONFIG.confidence);+ requireNonNegativeInteger("confidence.low_max_applied", confidence.low_max_applied, ctx.source);+ requireUnitInterval("confidence.medium_min", confidence.medium_min, ctx.source);+ requireUnitInterval("confidence.high_min", confidence.high_min, ctx.source);+ if ((confidence.medium_min as number) >= (confidence.high_min as number)) {+ throw new BrainConfigError(+ `medium_min must be strictly less than high_min; got ` ++ `medium_min=${confidence.medium_min}, high_min=${confidence.high_min}`,+ "confidence.medium_min",+ ctx.source,+ );+ }+ return {+ low_max_applied: confidence.low_max_applied as number,+ medium_min: confidence.medium_min as number,+ high_min: confidence.high_min as number,+ };+}++export 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 };+}diff --git a/src/core/brain/policy/blocks/link-graph.ts b/src/core/brain/policy/blocks/link-graph.tsnew file mode 100644index 00000000..0140eeb4--- /dev/null+++ b/src/core/brain/policy/blocks/link-graph.ts@@ -0,0 +1,125 @@+/**+ * The `link_graph:` block β the MOC-audit thresholds and the name of the+ * user-authored vault-root instruction file.+ *+ * One reason to change: how a hub note is recognised structurally. Both+ * thresholds are counts and ratios over `[[β¦]]` links - there is no+ * vocabulary detection of "this looks like a MOC".+ */++import type {+ BrainConfig,+ BrainLinkGraphConfig,+ ResolvedBrainLinkGraphConfig,+} from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "link_graph";++/**+ * Default `link_graph` block (v0.10.17). Absent from `_brain.yaml`+ * (or with absent individual keys) falls back here via+ * `resolveLinkGraph`. Both knobs are purely structural - no+ * vocabulary detection of "this looks like a MOC".+ *+ * Defaults:+ * - `moc_min_outbound_links: 5` - the heuristic floor for "this+ * is a hub note", chosen to filter out prose notes with a few+ * inline references.+ * - `moc_min_link_ratio: 0.3` - 30 % of the body's non-whitespace+ * characters must sit inside `[[β¦]]` for the audit to accept+ * the note as a MOC. Prose notes typically score below 0.1.+ * - `vault_instruction_file: "VAULT.md"` - the user-authored+ * vault-root instruction file `brain_context` surfaces when+ * present. Configurable per vault.+ */+export const BRAIN_LINK_GRAPH_DEFAULTS: ResolvedBrainLinkGraphConfig = Object.freeze({+ moc_min_outbound_links: 5,+ moc_min_link_ratio: 0.3,+ vault_instruction_file: "VAULT.md",+}) as ResolvedBrainLinkGraphConfig;++/**+ * Merge a parsed `link_graph` block (or `undefined`) with+ * `BRAIN_LINK_GRAPH_DEFAULTS`.+ */+export function resolveLinkGraph(cfg: BrainConfig): ResolvedBrainLinkGraphConfig {+ const lg = cfg.link_graph;+ if (lg === undefined) return BRAIN_LINK_GRAPH_DEFAULTS;+ return {+ moc_min_outbound_links:+ lg.moc_min_outbound_links ?? BRAIN_LINK_GRAPH_DEFAULTS.moc_min_outbound_links,+ moc_min_link_ratio: lg.moc_min_link_ratio ?? BRAIN_LINK_GRAPH_DEFAULTS.moc_min_link_ratio,+ vault_instruction_file:+ lg.vault_instruction_file ?? BRAIN_LINK_GRAPH_DEFAULTS.vault_instruction_file,+ };+}++/**+ * Shape:+ * link_graph:+ * moc_min_outbound_links: 5 # positive integer+ * moc_min_link_ratio: 0.3 # number in (0, 1]+ * vault_instruction_file: VAULT.md # vault-relative path+ */+export function parseLinkGraphBlock(ctx: BlockParseContext): BrainLinkGraphConfig | undefined {+ const lgObj = openBlock(ctx, BLOCK);+ if (lgObj === undefined) return undefined;++ const partial: Record<string, unknown> = {};+ if ("moc_min_outbound_links" in lgObj) {+ const v = lgObj["moc_min_outbound_links"];+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {+ throw new BrainConfigError(+ "must be a positive integer",+ "link_graph.moc_min_outbound_links",+ ctx.source,+ );+ }+ partial["moc_min_outbound_links"] = v;+ }+ if ("moc_min_link_ratio" in lgObj) {+ const v = lgObj["moc_min_link_ratio"];+ if (typeof v !== "number" || !Number.isFinite(v) || v <= 0 || v > 1) {+ throw new BrainConfigError(+ "must be a number in (0, 1]",+ "link_graph.moc_min_link_ratio",+ ctx.source,+ );+ }+ partial["moc_min_link_ratio"] = v;+ }+ if ("vault_instruction_file" in lgObj) {+ const v = lgObj["vault_instruction_file"];+ if (typeof v !== "string" || v.trim().length === 0) {+ throw new BrainConfigError(+ "must be a non-empty string",+ "link_graph.vault_instruction_file",+ ctx.source,+ );+ }+ // Trim BEFORE the path-shape check so a value like+ // `" VAULT.md "` doesn't survive validation and fail at+ // read time as a missing file.+ const trimmed = v.trim();+ // Reject absolute paths and `..` traversal at load time so+ // the config surface fails loudly instead of silently+ // omitting the envelope field at read time.+ if (trimmed.startsWith("/") || trimmed.startsWith("\\") || trimmed.includes("..")) {+ throw new BrainConfigError(+ "must be a vault-relative path without '..' segments",+ "link_graph.vault_instruction_file",+ ctx.source,+ );+ }+ partial["vault_instruction_file"] = trimmed;+ }+ warnUnknownKeys(+ ctx,+ lgObj,+ ["moc_min_outbound_links", "moc_min_link_ratio", "vault_instruction_file"],+ BLOCK,+ );+ return partial as BrainLinkGraphConfig;+}diff --git a/src/core/brain/policy/blocks/notes.ts b/src/core/brain/policy/blocks/notes.tsnew file mode 100644index 00000000..7071ca92--- /dev/null+++ b/src/core/brain/policy/blocks/notes.ts@@ -0,0 +1,83 @@+/**+ * The `notes:` block β the user-authored folders the agent may READ.+ *+ * One reason to change: how the operator opts folders into the agent's+ * read scope. Agents never write to these paths, so the whole surface is+ * a list of vault-relative folders and the rules that keep that list+ * inside the vault.+ */++import type { BrainConfig, BrainNotesConfig, ResolvedBrainNotesConfig } from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { describe, requireArrayField } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "notes";++/**+ * Default `notes:` block (v0.11.0). Empty `read_paths` list means+ * the agent does not scan any user-authored notes. The operator+ * opts in by listing folders in `_brain.yaml`.+ */+export const BRAIN_NOTES_DEFAULTS: ResolvedBrainNotesConfig = Object.freeze({+ read_paths: Object.freeze([]) as ReadonlyArray<string>,+}) as ResolvedBrainNotesConfig;++/**+ * Merge a parsed `notes` block (or `undefined`) with+ * `BRAIN_NOTES_DEFAULTS`. The resulting struct (and its inner array)+ * are frozen so consumers can pass the slice around without copying.+ */+export function resolveNotes(cfg: BrainConfig): ResolvedBrainNotesConfig {+ const block = cfg.notes;+ if (block === undefined || block.read_paths === undefined) {+ return BRAIN_NOTES_DEFAULTS;+ }+ return Object.freeze({+ read_paths: Object.freeze([...block.read_paths]) as ReadonlyArray<string>,+ }) as ResolvedBrainNotesConfig;+}++/**+ * Shape:+ * notes:+ * read_paths:+ * - Daily+ * - Journal/Weekly+ */+export function parseNotesBlock(ctx: BlockParseContext): BrainNotesConfig | undefined {+ const notesObj = openBlock(ctx, BLOCK);+ if (notesObj === undefined) return undefined;++ const partial: Record<string, unknown> = {};+ if ("read_paths" in notesObj) {+ const list = requireArrayField(+ notesObj["read_paths"],+ "notes.read_paths",+ ctx.source,+ "must be an array of vault-relative folder paths",+ );+ partial["read_paths"] = list.map((entry, idx) =>+ cleanReadPath(entry, `notes.read_paths[${idx}]`, ctx.source),+ );+ }+ warnUnknownKeys(ctx, notesObj, ["read_paths"], BLOCK);+ return partial as BrainNotesConfig;+}++function cleanReadPath(entry: unknown, field: string, source: string | null): string {+ if (typeof entry !== "string") {+ throw new BrainConfigError(`must be a string; got ${describe(entry)}`, field, source);+ }+ const trimmed = entry.trim();+ if (trimmed.length === 0) {+ throw new BrainConfigError("must be a non-empty string", field, source);+ }+ if (trimmed.startsWith("/") || trimmed.startsWith("\\")) {+ throw new BrainConfigError("must be a vault-relative path (no leading slash)", field, source);+ }+ if (trimmed.split(/[\\/]/).some((s) => s === "..")) {+ throw new BrainConfigError("must not contain '..' segments", field, source);+ }+ return trimmed;+}diff --git a/src/core/brain/policy/blocks/rollup.ts b/src/core/brain/policy/blocks/rollup.tsnew file mode 100644index 00000000..dbe66355--- /dev/null+++ b/src/core/brain/policy/blocks/rollup.ts@@ -0,0 +1,31 @@+/**+ * The `rollup:` block (knowledge-intake-and-consolidation, S3) β the+ * fact rollup-ladder thresholds.+ *+ * One reason to change: when the ladder promotes facts to rollups and+ * rollups to identities. Shape problems are hard errors so a mistyped+ * threshold surfaces instead of silently reverting to the named-constant+ * default in `rollup-ladder.ts`.+ */++import type { BrainRollupConfig } from "../../types.ts";+import { requirePositiveInteger } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "rollup";++const KNOWN_KEYS = ["fact_threshold", "identity_threshold"] as const;++export function parseRollupBlock(ctx: BlockParseContext): BrainRollupConfig | undefined {+ const rawMap = openBlock(ctx, BLOCK);+ if (rawMap === undefined) return undefined;++ const partial: { fact_threshold?: number; identity_threshold?: number } = {};+ for (const key of KNOWN_KEYS) {+ if (!(key in rawMap)) continue;+ requirePositiveInteger(`rollup.${key}`, rawMap[key], ctx.source);+ partial[key] = rawMap[key] as number;+ }+ warnUnknownKeys(ctx, rawMap, KNOWN_KEYS, BLOCK);+ return partial;+}diff --git a/src/core/brain/policy/blocks/schema.ts b/src/core/brain/policy/blocks/schema.tsnew file mode 100644index 00000000..24b3d27b--- /dev/null+++ b/src/core/brain/policy/blocks/schema.ts@@ -0,0 +1,118 @@+/**+ * The `schema:` block β the runtime schema-pack vocabulary a vault adds+ * on top of the built-in taxonomy.+ *+ * One reason to change: which vocabulary categories and metadata forms a+ * vault may declare. Token-level validation itself belongs to+ * `schema-vocab.ts`; this module only shapes the YAML into the+ * declarations that validator accepts and re-labels its failures as+ * config errors.+ */++import type { BrainSchemaConfig } from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { requireArrayField } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";+import {+ SCHEMA_VOCAB_CATEGORIES,+ SchemaVocabularyError,+ validateSchemaDeclarations,+} from "../../schema-vocab.ts";++const BLOCK = "schema";++/**+ * Keys carrying `name=value`-style metadata rather than bare tokens.+ * Unlike the vocabulary categories they are not passed to+ * `validateSchemaDeclarations`, so their entries are checked here.+ */+const SCHEMA_META_KEYS = [+ "aliases",+ "prefixes",+ "link_types",+ "extractable",+ "expert_routing",+] as const;++/**+ * Shape:+ * schema:+ * preference_types: [research, decision]+ * signal_types: [observation]+ * page_types: [paper]+ * log_event_kinds: [milestone]+ * aliases: [decision=choice]+ * prefixes: [pref=decision]+ * link_types: [supports]+ * extractable: [decision]+ * expert_routing: [decision=schema-author]+ *+ * Absent block leaves `cfg.schema` undefined; consumers merge built-ins+ * through `resolveSchemaVocabulary`.+ */+export function parseSchemaBlock(ctx: BlockParseContext): BrainSchemaConfig | undefined {+ const schemaObj = openBlock(ctx, BLOCK);+ if (schemaObj === undefined) return undefined;++ const partial: Partial<Record<keyof BrainSchemaConfig, ReadonlyArray<string>>> = {};+ for (const category of SCHEMA_VOCAB_CATEGORIES) {+ if (!(category in schemaObj)) continue;+ partial[category] = requireArrayField(+ schemaObj[category],+ `schema.${category}`,+ ctx.source,+ "must be an array of schema tokens",+ ) as ReadonlyArray<string>;+ }+ for (const key of SCHEMA_META_KEYS) {+ if (!(key in schemaObj)) continue;+ const value = requireArrayField(+ schemaObj[key],+ `schema.${key}`,+ ctx.source,+ "must be an array of schema metadata entries",+ );+ partial[key] = value.map((entry, index) =>+ cleanMetaEntry(entry, `schema.${key}[${index}]`, ctx.source),+ );+ }+ warnUnknownKeys(+ ctx,+ schemaObj,+ [...(SCHEMA_VOCAB_CATEGORIES as ReadonlyArray<string>), ...SCHEMA_META_KEYS],+ BLOCK,+ );++ try {+ const declarations = validateSchemaDeclarations(partial);+ return {+ ...declarations,+ ...(partial.aliases ? { aliases: partial.aliases } : {}),+ ...(partial.prefixes ? { prefixes: partial.prefixes } : {}),+ ...(partial.link_types ? { link_types: partial.link_types } : {}),+ ...(partial.extractable ? { extractable: partial.extractable } : {}),+ ...(partial.expert_routing ? { expert_routing: partial.expert_routing } : {}),+ } as BrainSchemaConfig;+ } catch (err) {+ if (err instanceof SchemaVocabularyError) {+ // `SchemaVocabularyError` already prefixes its field; strip it so+ // `BrainConfigError` does not render the field name twice.+ const detail = err.message.startsWith(`${err.field}: `)+ ? err.message.slice(err.field.length + 2)+ : err.message;+ throw new BrainConfigError(detail, err.field, ctx.source);+ }+ throw err;+ }+}++function cleanMetaEntry(entry: unknown, field: string, source: string | null): string {+ if (typeof entry !== "string") {+ throw new BrainConfigError("must be a string schema metadata entry", field, source);+ }+ const trimmed = entry.trim();+ if (trimmed.length === 0) {+ throw new BrainConfigError("must be a non-empty schema metadata entry", field, source);+ }+ return trimmed;+}diff --git a/src/core/brain/policy/blocks/sessions.ts b/src/core/brain/policy/blocks/sessions.tsnew file mode 100644index 00000000..d3f8877c--- /dev/null+++ b/src/core/brain/policy/blocks/sessions.ts@@ -0,0 +1,80 @@+/**+ * The `sessions:` block β which sessions and messages the capture+ * boundary lets through.+ *+ * One reason to change: how an operator excludes traffic from capture.+ * Session patterns are anchored globs; message patterns are regexes+ * validated lazily at compile time - an invalid regex degrades to a+ * capture-boundary warning, never a config error, so a typo cannot take+ * the whole Brain config down.+ */++import type { BrainConfig, BrainSessionsConfig, ResolvedBrainSessionsConfig } from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { describe, requireArrayField } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "sessions";++const LIST_KEYS = ["ignore_patterns", "stateless_patterns", "ignore_message_patterns"] as const;++/**+ * Default `sessions:` block (Memory Integrity Suite). Empty lists+ * mean every session and message is captured - the pre-boundary+ * behaviour, bit-identical.+ */+export const BRAIN_SESSIONS_DEFAULTS: ResolvedBrainSessionsConfig = Object.freeze({+ ignore_patterns: Object.freeze([]) as ReadonlyArray<string>,+ stateless_patterns: Object.freeze([]) as ReadonlyArray<string>,+ ignore_message_patterns: Object.freeze([]) as ReadonlyArray<string>,+}) as ResolvedBrainSessionsConfig;++/** Merge a parsed `sessions` block (or `undefined`) with the defaults. */+export function resolveSessions(cfg: BrainConfig): ResolvedBrainSessionsConfig {+ const block = cfg.sessions;+ if (block === undefined) return BRAIN_SESSIONS_DEFAULTS;+ return Object.freeze({+ ignore_patterns: Object.freeze([...(block.ignore_patterns ?? [])]) as ReadonlyArray<string>,+ stateless_patterns: Object.freeze([+ ...(block.stateless_patterns ?? []),+ ]) as ReadonlyArray<string>,+ ignore_message_patterns: Object.freeze([+ ...(block.ignore_message_patterns ?? []),+ ]) as ReadonlyArray<string>,+ }) as ResolvedBrainSessionsConfig;+}++/**+ * Shape:+ * sessions:+ * ignore_patterns: ["cron-*"]+ * stateless_patterns: ["probe-*"]+ * ignore_message_patterns: ["^\\[heartbeat\\]"]+ */+export function parseSessionsBlock(ctx: BlockParseContext): BrainSessionsConfig | undefined {+ const sessionsObj = openBlock(ctx, BLOCK);+ if (sessionsObj === undefined) return undefined;++ const partial: Record<string, unknown> = {};+ for (const key of LIST_KEYS) {+ if (!(key in sessionsObj)) continue;+ const list = requireArrayField(+ sessionsObj[key],+ `sessions.${key}`,+ ctx.source,+ "must be an array of pattern strings",+ );+ partial[key] = list.map((entry, idx) => {+ if (typeof entry !== "string" || entry.trim().length === 0) {+ throw new BrainConfigError(+ `must be a non-empty string; got ${describe(entry)}`,+ `sessions.${key}[${idx}]`,+ ctx.source,+ );+ }+ return entry.trim();+ });+ }+ warnUnknownKeys(ctx, sessionsObj, LIST_KEYS, BLOCK);+ return partial as BrainSessionsConfig;+}diff --git a/src/core/brain/policy/blocks/temporal.ts b/src/core/brain/policy/blocks/temporal.tsnew file mode 100644index 00000000..b06723ba--- /dev/null+++ b/src/core/brain/policy/blocks/temporal.ts@@ -0,0 +1,110 @@+/**+ * The `temporal:` block β staleness windows and the calendar conventions+ * the brief/report surfaces align to.+ *+ * One reason to change: how the vault's notion of "stale" and "this week"+ * is configured. Every knob is purely structural; none of them detects+ * anything from prose.+ */++import type { BrainConfig, BrainTemporalConfig, ResolvedBrainTemporalConfig } from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "temporal";++/** Sub-keys whose value is a plain positive day count. */+const STALE_DAY_KEYS = ["stale_pref_days", "stale_signal_days", "stale_log_days"] as const;++/**+ * Default `temporal:` block (v0.10.18). Drives the temporal ++ * synthesis subsystem. Absent block falls back here via+ * `resolveTemporal`. All knobs are purely structural:+ *+ * - `stale_pref_days: 90` - 3 months without activity before a+ * preference is reported as stale.+ * - `stale_signal_days: 30` - 1 month without activity for signals.+ * - `stale_log_days: 180` - 6 months for Brain/log files.+ * - `weekly_start_dow: 1` - ISO-8601 weekday number (1 = Monday,+ * 7 = Sunday). Configurable for vaults that prefer Sunday-start+ * weeks without any language-specific detection.+ * - `daily_window_offset_hours: 0` - daily-brief windows align+ * with UTC midnight by default.+ */+export const BRAIN_TEMPORAL_DEFAULTS: ResolvedBrainTemporalConfig = Object.freeze({+ stale_pref_days: 90,+ stale_signal_days: 30,+ stale_log_days: 180,+ weekly_start_dow: 1,+ daily_window_offset_hours: 0,+}) as ResolvedBrainTemporalConfig;++/**+ * Merge a parsed `temporal` block (or `undefined`) with+ * `BRAIN_TEMPORAL_DEFAULTS`.+ */+export function resolveTemporal(cfg: BrainConfig): ResolvedBrainTemporalConfig {+ const tp = cfg.temporal;+ if (tp === undefined) return BRAIN_TEMPORAL_DEFAULTS;+ return {+ stale_pref_days: tp.stale_pref_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_pref_days,+ stale_signal_days: tp.stale_signal_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_signal_days,+ stale_log_days: tp.stale_log_days ?? BRAIN_TEMPORAL_DEFAULTS.stale_log_days,+ weekly_start_dow: tp.weekly_start_dow ?? BRAIN_TEMPORAL_DEFAULTS.weekly_start_dow,+ daily_window_offset_hours:+ tp.daily_window_offset_hours ?? BRAIN_TEMPORAL_DEFAULTS.daily_window_offset_hours,+ };+}++/**+ * Shape:+ * temporal:+ * stale_pref_days: 90 # positive integer+ * stale_signal_days: 30 # positive integer+ * stale_log_days: 180 # positive integer+ * weekly_start_dow: 1 # 1..7 (ISO-8601 weekday)+ * daily_window_offset_hours: 0 # -23..23+ */+export function parseTemporalBlock(ctx: BlockParseContext): BrainTemporalConfig | undefined {+ const tpObj = openBlock(ctx, BLOCK);+ if (tpObj === undefined) return undefined;++ const partial: Record<string, unknown> = {};+ for (const key of STALE_DAY_KEYS) {+ if (!(key in tpObj)) continue;+ const v = tpObj[key];+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1) {+ throw new BrainConfigError("must be a positive integer", `temporal.${key}`, ctx.source);+ }+ partial[key] = v;+ }+ if ("weekly_start_dow" in tpObj) {+ const v = tpObj["weekly_start_dow"];+ if (typeof v !== "number" || !Number.isInteger(v) || v < 1 || v > 7) {+ throw new BrainConfigError(+ "must be an ISO-8601 weekday number (1..7)",+ "temporal.weekly_start_dow",+ ctx.source,+ );+ }+ partial["weekly_start_dow"] = v;+ }+ if ("daily_window_offset_hours" in tpObj) {+ const v = tpObj["daily_window_offset_hours"];+ if (typeof v !== "number" || !Number.isInteger(v) || v < -23 || v > 23) {+ throw new BrainConfigError(+ "must be an integer in [-23, 23]",+ "temporal.daily_window_offset_hours",+ ctx.source,+ );+ }+ partial["daily_window_offset_hours"] = v;+ }+ warnUnknownKeys(+ ctx,+ tpObj,+ [...STALE_DAY_KEYS, "weekly_start_dow", "daily_window_offset_hours"],+ BLOCK,+ );+ return partial as BrainTemporalConfig;+}diff --git a/src/core/brain/policy/blocks/vault-ignore.ts b/src/core/brain/policy/blocks/vault-ignore.tsnew file mode 100644index 00000000..9149aed0--- /dev/null+++ b/src/core/brain/policy/blocks/vault-ignore.ts@@ -0,0 +1,77 @@+/**+ * The `vault:` block β the vault-wide exclusion list every walker obeys.+ *+ * One reason to change: what an exclusion entry may look like. Shape+ * problems are hard errors rather than dropped entries: exclusions affect+ * the search indexer, `scan-inline` and every future walker, so an entry+ * that silently disabled itself would be a fail-open footgun.+ */++import type { BrainVaultConfig } from "../../types.ts";+import { BrainConfigError } from "../errors.ts";+import { assertNoYamlUnsafeChars, describe, requireArrayField } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";+import { classifyVaultIgnoreRule } from "../../../vault-scope/defaults.ts";++const BLOCK = "vault";++/**+ * The block is absent for vaults created before v0.10.9 and for+ * operators who explicitly removed it; the resolver falls back to+ * `DEFAULT_VAULT_IGNORE_PATHS` in both cases.+ */+export function parseVaultBlock(ctx: BlockParseContext): BrainVaultConfig | undefined {+ const rawMap = openBlock(ctx, BLOCK);+ if (rawMap === undefined) return undefined;++ let vault: BrainVaultConfig | undefined;+ if ("ignore_paths" in rawMap) {+ const list = requireArrayField(+ rawMap["ignore_paths"],+ "vault.ignore_paths",+ ctx.source,+ `must be a list of strings; got ${describe(rawMap["ignore_paths"])}`,+ );+ const validated = list.map((entry, i) =>+ normaliseIgnorePath(entry, `vault.ignore_paths[${i}]`, ctx.source),+ );+ vault = { ignore_paths: Object.freeze(validated) };+ }+ warnUnknownKeys(ctx, rawMap, ["ignore_paths"], BLOCK);+ return vault;+}++function normaliseIgnorePath(entry: unknown, field: string, source: string | null): string {+ if (typeof entry !== "string") {+ throw new BrainConfigError(`must be a string; got ${describe(entry)}`, field, source);+ }+ const trimmed = entry.trim();+ if (trimmed.length === 0) {+ throw new BrainConfigError("must be a non-empty string", field, source);+ }+ assertNoYamlUnsafeChars(trimmed, field, source, "use a simple one-line path");+ // `classifyVaultIgnoreRule` strips leading `./` / trailing+ // `/` / collapsing `//`. An entry that normalises to the+ // empty string (`./`, `/`, `///`) would silently disable+ // itself; reject so the operator sees the typo immediately.+ const normalised = classifyVaultIgnoreRule(trimmed).raw;+ if (normalised.length === 0) {+ throw new BrainConfigError(+ "normalises to the empty string; use a real directory name or vault-relative path",+ field,+ source,+ );+ }+ // Reject leading-slash entries explicitly. `matchIgnore` only+ // compares vault-relative POSIX prefixes (no leading `/`), so+ // `/Brain/.snapshots` would silently never match β exactly the+ // fail-closed contract violation the v0.10.9 policy forbids.+ if (normalised.startsWith("/")) {+ throw new BrainConfigError(+ "must be a bare name or vault-relative POSIX path without a leading '/'",+ field,+ source,+ );+ }+ return normalised;+}diff --git a/src/core/brain/policy/defaults.ts b/src/core/brain/policy/defaults.tsnew file mode 100644index 00000000..0cdf9701--- /dev/null+++ b/src/core/brain/policy/defaults.ts@@ -0,0 +1,56 @@+/**+ * The `_brain.yaml` a fresh vault gets, and the schema versions this+ * build can read.+ *+ * One reason to change: a shipped default value. Per-block defaults that+ * only exist on the READ side (a block absent from the file) live next to+ * their block parser in `./blocks/`; this table is the subset that is+ * WRITTEN by `brain init` and merged onto field-by-field at load time.+ */++import type { BrainConfig } from "../types.ts";+// Imported from `defaults.ts` (not from `vault-scope/index.ts`) to+// break the module-init cycle: the resolver lives in `index.ts` and+// itself imports `loadBrainConfig` from this file. See the+// `defaults.ts` header for the rationale.+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 `_brain.yaml` content. Mirrors Β§10 of the design doc. Used by+ * `brain init` and as the fallback inside `loadBrainConfig` when callers+ * opt into permissive mode (the current API is strict β absent file+ * throws).+ */+export const DEFAULT_BRAIN_CONFIG: BrainConfig = Object.freeze({+ schema_version: 1,+ primary_agent: null,+ dream: Object.freeze({+ candidate_threshold: 3,+ unconfirmed_window_days: 14,+ contradiction_window_days: 14,+ heal_enrich_enabled: false,+ }),+ retire: Object.freeze({+ stale_evidence_days: 90,+ }),+ confidence: Object.freeze({+ low_max_applied: 2,+ medium_min: 0.4,+ high_min: 0.75,+ }),+ snapshots: Object.freeze({+ retention_count: 10,+ }),+ vault: Object.freeze({+ ignore_paths: DEFAULT_VAULT_IGNORE_PATHS,+ }),+}) as BrainConfig;++// The serialised default `_brain.yaml` (`DEFAULT_BRAIN_CONFIG_YAML`) is+// GENERATED from the default tables above and lives in+// `config-template.ts`. It cannot live here: the generator reads these+// tables, so importing it back would make the config layer and+// `config-template.ts` mutually dependent at module-evaluation time.diff --git a/src/core/brain/policy/errors.ts b/src/core/brain/policy/errors.tsnew file mode 100644index 00000000..46b134f0--- /dev/null+++ b/src/core/brain/policy/errors.ts@@ -0,0 +1,36 @@+/**+ * Failure and warning vocabulary for `Brain/_brain.yaml`.+ *+ * Kept apart from every validator so the rest of the config layer can+ * raise and collect diagnostics without importing the parsing machinery,+ * and so the rendered message format has exactly one definition.+ */++/**+ * Warnings collected during validation. Forward-compat tolerates unknown+ * top-level keys but surfaces them so a typo doesn't go unnoticed.+ */+export interface BrainConfigLoadWarning {+ readonly path: string;+ readonly message: string;+}++export class BrainConfigError extends Error {+ /**+ * Dotted field path that caused the failure (`dream.candidate_threshold`,+ * `schema_version`, β¦). `null` for top-level type errors.+ */+ readonly field: string | null;+ readonly source: string | null;++ constructor(message: string, field: string | null, source: string | null) {+ super(+ field+ ? `${source ?? "<config>"}: ${field}: ${message}`+ : `${source ?? "<config>"}: ${message}`,+ );+ this.name = "BrainConfigError";+ this.field = field;+ this.source = source;+ }+}diff --git a/src/core/brain/policy/field-checks.ts b/src/core/brain/policy/field-checks.tsnew file mode 100644index 00000000..b6c00052--- /dev/null+++ b/src/core/brain/policy/field-checks.ts@@ -0,0 +1,153 @@+/**+ * Scalar and shape constraints reused across every `_brain.yaml` block.+ *+ * One reason to change: the vocabulary of constraints a config field can+ * be held to. Every check raises {@link BrainConfigError} naming the+ * offending field β none of them clamps, defaults, or returns a neutral+ * value, because a knob that silently reverted would be indistinguishable+ * from the operator never having set it.+ */++import { BrainConfigError } from "./errors.ts";++/**+ * Bytes the small `_brain.yaml` subset cannot round-trip: the writer+ * quotes strings but implements no escape sequences, so a value carrying+ * one of these could be written and then read back as something else.+ */+const YAML_STRING_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;++export function describe(value: unknown): string {+ if (value === null) return "null";+ if (value === undefined) return "undefined";+ if (Array.isArray(value)) return `array(${value.length})`;+ if (typeof value === "object") return "object";+ return `${typeof value}(${JSON.stringify(value)})`;+}++/**+ * Reject a string that the `_brain.yaml` writer could not emit verbatim.+ * `hint` names the shape the field does accept and is appended to the+ * message, so a path field and an agent-id field each point at their own+ * remedy.+ */+export function assertNoYamlUnsafeChars(+ value: string,+ field: string,+ source: string | null,+ hint: string,+): void {+ for (const bad of YAML_STRING_REJECTED_CHARS) {+ if (value.includes(bad)) {+ throw new BrainConfigError(+ `contains a disallowed character ${JSON.stringify(bad)}; ${hint}`,+ field,+ source,+ );+ }+ }+}++/**+ * Narrow a raw config value to a plain object, or throw a field-named+ * `BrainConfigError`. Centralizes the "block must be a map of keys" guard+ * that used to be copy-pasted at every optional-block site with two+ * slightly different wordings ("must be a mapping" vs "must be a map of+ * keys") - callers get one consistent message (`BrainConfigError` already+ * prepends the block's `field` name, so the message itself does not repeat+ * it).+ */+export function requireMapBlock(+ raw: unknown,+ blockKey: string,+ source: string | null,+): Record<string, unknown> {+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {+ throw new BrainConfigError(`must be a map of keys; got ${describe(raw)}`, blockKey, source);+ }+ return raw as Record<string, unknown>;+}++/**+ * Narrow a raw config value to an array. The message is caller-supplied+ * because each list field names what its entries are for ("pattern+ * strings", "vault-relative folder paths", β¦), and those wordings are+ * pinned by tests.+ */+export function requireArrayField(+ raw: unknown,+ field: string,+ source: string | null,+ message: string,+): ReadonlyArray<unknown> {+ if (!Array.isArray(raw)) {+ throw new BrainConfigError(message, field, source);+ }+ return raw as ReadonlyArray<unknown>;+}++export function requirePositiveInteger(field: string, value: unknown, source: string | null): void {+ if (typeof value !== "number" || !Number.isInteger(value) || value <= 0) {+ throw new BrainConfigError(`must be a positive integer; got ${describe(value)}`, field, source);+ }+}++export function requireNonNegativeInteger(+ field: string,+ value: unknown,+ source: string | null,+): void {+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {+ throw new BrainConfigError(+ `must be a non-negative integer; got ${describe(value)}`,+ field,+ source,+ );+ }+}++export function requireUnitInterval(field: string, value: unknown, source: string | null): void {+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1) {+ throw new BrainConfigError(`must be a number in [0, 1]; got ${describe(value)}`, field, source);+ }+}++/**+ * Assert that a present value is an integer inside `[min, max]`. Used+ * where the enclosing block already resolved a default for an absent key,+ * so "absent" is not one of the outcomes.+ */+export function requireIntegerInRange(+ field: string,+ value: unknown,+ min: number,+ max: number,+ source: string | null,+): void {+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {+ throw new BrainConfigError(+ `must be an integer between ${min} and ${max}; got ${describe(value)}`,+ field,+ source,+ );+ }+}++/**+ * Read an optional integer field bounded to `[min, max]` from a config+ * sub-map. Returns `undefined` when the key is absent; throws a+ * {@link BrainConfigError} (never clamps) when present but out of range+ * or non-integer.+ */+export function readBoundedInt(+ map: Readonly<Record<string, unknown>>,+ key: string,+ min: number,+ max: number,+ field: string,+ source: string | null,+): number | undefined {+ if (!(key in map)) return undefined;+ requireIntegerInRange(field, map[key], min, max, source);+ return map[key] as number;+}diff --git a/src/core/brain/policy/key-index.ts b/src/core/brain/policy/key-index.tsnew file mode 100644index 00000000..2cc6bf08--- /dev/null+++ b/src/core/brain/policy/key-index.ts@@ -0,0 +1,143 @@+/**+ * The record of which `_brain.yaml` keys the validator understands, and+ * the block-entry protocol that keeps that record honest.+ *+ * One reason to change: how the validator declares and reports its key+ * vocabulary. The index is built BY CONSTRUCTION β a key becomes "known"+ * only because some branch registered it while checking for it β so it+ * can never drift from what the validator actually reads. That drift is+ * the bug class fixed in phase 0, where four blocks were parsed but+ * missing from a hand-maintained list and valid config produced a false+ * "unknown field" warning.+ */++import type { BrainConfigLoadWarning } from "./errors.ts";+import { requireMapBlock } from "./field-checks.ts";++/**+ * The set of configuration keys the validator understands, as observed+ * during one validation run.+ */+export interface BrainConfigKeyIndex {+ readonly topLevel: ReadonlySet<string>;+ /** Block key β sub-keys that block declares. Scalar keys are absent. */+ readonly subKeys: ReadonlyMap<string, ReadonlySet<string>>;+}++/**+ * Mutable accumulator behind {@link BrainConfigKeyIndex}. Every helper+ * that branches on a key registers it here, so the index is a+ * by-construction record of what the validator understands rather than a+ * second list that can drift from the first.+ */+export class KeyIndexCollector implements BrainConfigKeyIndex {+ readonly topLevel = new Set<string>();+ readonly subKeys = new Map<string, ReadonlySet<string>>();++ addTop(key: string): void {+ this.topLevel.add(key);+ }++ addSub(block: string, keys: Iterable<string>): void {+ const merged = new Set(this.subKeys.get(block) ?? []);+ for (const key of keys) merged.add(key);+ this.subKeys.set(block, merged);+ }+}++/**+ * Everything a single block parser needs: the raw root map, the label+ * rendered into error messages, the warning sink, and the key index it+ * must register itself with. Passed as one value so adding a fifth+ * concern later does not re-thread twenty signatures.+ */+export interface BlockParseContext {+ readonly obj: Record<string, unknown>;+ readonly source: string | null;+ readonly warnings: BrainConfigLoadWarning[];+ readonly keys: KeyIndexCollector;+}++/**+ * Record that this call site checked for `key` at the top level, then+ * report whether it's present. Every top-level block/field presence+ * check (`"vault" in obj`, etc.) MUST go through this - or `mergeBlock`,+ * for the four blocks that merge onto numeric defaults instead of being+ * fully optional - so the key index can never drift from the set of keys+ * the validator actually understands. A key that is never checked can+ * never be "known", by construction - there is no separate list to+ * forget to update.+ */+export function hasBlock(+ obj: Record<string, unknown>,+ key: string,+ knownBlockKeys: KeyIndexCollector,+): boolean {+ knownBlockKeys.addTop(key);+ return key in obj;+}++/**+ * Register an optional block and, when present, narrow it to a map.+ * Returns `undefined` for an absent block so the caller's whole body is+ * an early return rather than a nesting level.+ */+export function openBlock(+ ctx: BlockParseContext,+ blockKey: string,+): Record<string, unknown> | undefined {+ if (!hasBlock(ctx.obj, blockKey, ctx.keys)) return undefined;+ return requireMapBlock(ctx.obj[blockKey], blockKey, ctx.source);+}++/**+ * Push one forward-compat warning per key in `map` that isn't in `known`.+ * Replaces the per-block loop that used to mix `Set`, chained `!==`, and+ * (elsewhere) `.includes` for the same "unknown sub-key" check, each with+ * its own copy of the `${blockName}.${key}: unknown field ignored+ * (forward-compat)` message.+ */+export function warnUnknownKeys(+ ctx: BlockParseContext,+ map: Readonly<Record<string, unknown>>,+ known: ReadonlyArray<string>,+ blockName: string,+): void {+ const knownSet = new Set(known);+ ctx.keys.addSub(blockName, knownSet);+ for (const key of Object.keys(map)) {+ if (!knownSet.has(key)) {+ ctx.warnings.push({+ path: ctx.source ?? "<config>",+ message: `${blockName}.${key}: unknown field ignored (forward-compat)`,+ });+ }+ }+}++/**+ * Merge a parsed block (or `undefined`) with its default, returning a+ * plain object whose value types are validated downstream. A non-object+ * block (string, number, array) is a hard error β the user probably+ * miswrote the YAML.+ */+export function mergeBlock(+ blockKey: string,+ raw: unknown,+ fallback: Readonly<Record<string, number>>,+ source: string | null,+ knownBlockKeys: KeyIndexCollector,+ optionalKeys: ReadonlyArray<string> = [],+): Record<string, unknown> {+ knownBlockKeys.addTop(blockKey);+ knownBlockKeys.addSub(blockKey, [...Object.keys(fallback), ...optionalKeys]);+ if (raw === undefined) {+ return { ...fallback };+ }+ const rawMap = requireMapBlock(raw, blockKey, source);+ const merged: Record<string, unknown> = { ...fallback };+ for (const [k, v] of Object.entries(rawMap)) {+ merged[k] = v;+ }+ return merged;+}diff --git a/src/core/brain/policy/load.ts b/src/core/brain/policy/load.tsnew file mode 100644index 00000000..faef76c5--- /dev/null+++ b/src/core/brain/policy/load.ts@@ -0,0 +1,303 @@+/**+ * Reading `<vault>/Brain/_brain.yaml` off disk, and the fallback policy+ * for vaults where that read cannot succeed.+ *+ * One reason to change: what happens when the config file is missing,+ * unreadable, or malformed. Those are TWO conditions, not one, and every+ * entry point here splits on the same predicate:+ *+ * - ABSENT - a vault that has never run `o2b brain init`. There are no+ * operator settings to contradict, so the documented defaults are the+ * configuration. The `*Safe` entry points exist for exactly this, so+ * a freshly-cloned vault keeps working.+ * - PRESENT BUT UNREADABLE - malformed YAML, a block that does not+ * validate, a permission error, a directory in the file's place. The+ * operator's settings exist and are not in force; answering with the+ * defaults would revert them silently and leave the vault looking+ * healthy. The `*Safe` entry points do not absorb this.+ *+ * The strict entry point ({@link loadBrainConfig}) throws on both.+ */++import { existsSync, readFileSync } from "node:fs";+import type { BrainConfig, ResolvedBrainIntegrityConfig } from "../types.ts";+import { parseBrainYaml, type ParsedBlock } from "../yaml-parse.ts";+import { brainConfigPath } from "../paths.ts";+import { BrainConfigError, type BrainConfigLoadWarning } from "./errors.ts";+import { validateBrainConfigDetailed } from "./validate.ts";+import { DEFAULT_BRAIN_CONFIG } from "./defaults.ts";+import { BRAIN_MOST_APPLIED_DEFAULTS, resolveMostApplied } from "./blocks/active.ts";+import { BRAIN_NOTES_DEFAULTS, resolveNotes } from "./blocks/notes.ts";+import { BRAIN_TEMPORAL_DEFAULTS, resolveTemporal } from "./blocks/temporal.ts";+import { BRAIN_GUARDRAIL_DEFAULTS, resolveGuardrails } from "./blocks/guardrails.ts";+import {+ BRAIN_INTEGRITY_DEFAULTS,+ BRAIN_INTEGRITY_STRICT_FALLBACK,+ resolveIntegrity,+} from "./blocks/integrity.ts";++export interface LoadBrainConfigResult {+ readonly config: BrainConfig;+ readonly warnings: ReadonlyArray<BrainConfigLoadWarning>;+ readonly path: string;+}++/**+ * Read and validate `<vault>/Brain/_brain.yaml`.+ *+ * Throws {@link BrainConfigError} on:+ * - missing file+ * - YAML shape errors+ * - unsupported `schema_version`+ * - non-integer / out-of-range thresholds+ * - non-integer / non-positive `snapshots.retention_count`+ *+ * Unknown top-level keys are reported as warnings, not errors.+ */+export function loadBrainConfig(vault: string): BrainConfig {+ return loadBrainConfigDetailed(vault).config;+}++/**+ * Same as {@link loadBrainConfig} but also returns parser warnings (for+ * the future `o2b brain doctor` integration).+ */+export function loadBrainConfigDetailed(vault: string): LoadBrainConfigResult {+ const path = brainConfigPath(vault);+ if (!existsSync(path)) {+ throw new BrainConfigError(+ "config file does not exist; run `o2b brain init` first",+ null,+ path,+ );+ }+ let text: string;+ try {+ text = readFileSync(path, "utf8");+ } catch (err) {+ throw new BrainConfigError(+ `failed to read: ${(err as Error).message ?? String(err)}`,+ null,+ path,+ );+ }++ let parsed: ParsedBlock;+ try {+ parsed = parseBrainYaml(text);+ } catch (err) {+ throw new BrainConfigError((err as Error).message, null, path);+ }++ const { config, warnings } = validateBrainConfigDetailed(parsed, path);+ return { config, warnings, path };+}++/**+ * Whether `<vault>/Brain/_brain.yaml` is there at all.+ *+ * The ONE predicate every reader in this module splits on, so "absent"+ * cannot come to mean two different things on two surfaces. It is+ * deliberately existence and nothing more: a file that exists but cannot+ * be opened is present, and its contents are not the defaults.+ */+function brainConfigExists(vault: string): boolean {+ return existsSync(brainConfigPath(vault));+}++/**+ * Factory for the "resolve a block, tolerating a vault that has never+ * run `o2b brain init`" pattern repeated at every `load*ConfigSafe`+ * below.+ *+ * Exactly ONE condition is absorbed, and it is named: `_brain.yaml` is+ * ABSENT. A vault with no config has no operator settings to contradict,+ * so the block defaults ARE the configuration, and these read surfaces+ * keep working on a freshly-cloned vault.+ *+ * Every other failure propagates as a {@link BrainConfigError}: malformed+ * YAML, a block that parses but does not validate, a permission error, a+ * directory where the file should be. All four mean the operator's+ * settings exist and are NOT the ones in force, and answering with the+ * defaults would make that vault indistinguishable from a healthy one+ * while silently reverting whatever they configured. This is the same+ * split {@link loadIntegrityConfigSafe} makes; it differs only in what it+ * does with the unreadable case, and says why at its own site.+ */+function makeAbsentTolerantLoader<T>(+ resolveFn: (config: BrainConfig) => T,+ fallback: T,+): (vault: string) => T {+ return (vault: string): T => {+ if (!brainConfigExists(vault)) return fallback;+ return resolveFn(loadBrainConfig(vault));+ };+}++/**+ * Load + resolve the `notes:` block, falling back to+ * `BRAIN_NOTES_DEFAULTS` when the config file is absent. Used by+ * `scan-inline` and every other note walk so a freshly-cloned vault that+ * has not been `brain init`-ed still produces a clean "no user folders to+ * read" result. On an unreadable config it raises: an empty root list is+ * indistinguishable from a scan that found nothing, and a scanner that+ * silently walks the wrong folders is worse than one that stops.+ */+export const loadNotesConfigSafe = makeAbsentTolerantLoader(resolveNotes, BRAIN_NOTES_DEFAULTS);++/**+ * Load + resolve the `temporal:` block, falling back to+ * `BRAIN_TEMPORAL_DEFAULTS` when the config file is absent. Used by every+ * temporal consumer (MCP wrappers, CLI verbs) so a freshly-initialised+ * vault still produces a useful report; each of those callers is a verb+ * or a tool that can report the raise on an unreadable config, and the+ * operator snapshot already degrades its own way rather than reading+ * all-clear.+ */+export const loadTemporalConfigSafe = makeAbsentTolerantLoader(+ resolveTemporal,+ BRAIN_TEMPORAL_DEFAULTS,+);++/**+ * Load + resolve the `guardrails:` block, falling back to+ * `BRAIN_GUARDRAIL_DEFAULTS` when the config file is absent. Used by+ * agent-facing surfaces (e.g. the context pack) that must work on a vault+ * without a full `brain init`; the opt-in toggles therefore default off+ * there. They must NOT default off on a vault where the operator turned+ * one on and then broke the file: every flag in this block is a+ * containment or isolation switch, so a quiet revert to `false` is the+ * gate silently opening.+ */+export const loadGuardrailsConfigSafe = makeAbsentTolerantLoader(+ resolveGuardrails,+ BRAIN_GUARDRAIL_DEFAULTS,+);++/**+ * Load the configured `feedback.default_scope`, or `undefined` when the+ * config file is absent or carries no feedback block. Used by the+ * feedback write surfaces so a vault without a full `brain init` stays+ * scope-less (byte-identical to pre-feature behaviour) instead of+ * throwing when the signal is recorded. An unreadable config raises+ * before the write: a signal recorded under the wrong scope is a durable+ * record no later fix reaches.+ */+export const loadFeedbackDefaultScopeSafe = makeAbsentTolerantLoader(+ (config: BrainConfig) => config.feedback?.default_scope,+ undefined as string | undefined,+);++/**+ * Load the configured snapshot `retention_count`, falling back to the+ * default when the config file is absent, so a vault that has not run+ * `brain init` still prunes to a sane bound. This is the SAME+ * `snapshots.retention_count` the dream pass reads via+ * {@link loadBrainConfig}.+ *+ * An unreadable config raises, and the prune is the one caller that most+ * needs it to: pruning is destructive, and doing it at a GUESSED+ * retention deletes archives the operator asked to keep. The+ * destructive-snapshot gate already catches a prune failure and warns on+ * stderr with the operation's result intact, so the raise costs a+ * deferred cleanup and buys a named cause.+ */+export const loadSnapshotRetentionSafe = makeAbsentTolerantLoader(+ (config: BrainConfig) => config.snapshots.retention_count,+ DEFAULT_BRAIN_CONFIG.snapshots.retention_count,+);++/**+ * Load + resolve `active.most_applied`, falling back to+ * `BRAIN_MOST_APPLIED_DEFAULTS` when the config file is absent, so a vault+ * that has never run `brain init` still renders its most-applied section+ * over the documented window. Read by `active.md` and by the digest, which+ * report the same section and must agree on its window.+ *+ * An unreadable config raises: the section is the operator's own list of+ * the rules they lean on, and re-windowing it silently would change WHICH+ * rules appear while the digest looks entirely healthy. Both callers have+ * a channel for the raise - the CLI verb reports `digest failed: β¦`, the+ * MCP tool returns the error - so neither has to guess a window.+ */+export const loadActiveMostAppliedSafe = makeAbsentTolerantLoader(+ resolveMostApplied,+ BRAIN_MOST_APPLIED_DEFAULTS,+);++/**+ * Why `_brain.yaml` could not be read, or `null` when it reads fine or+ * does not exist.+ *+ * Exists so the unreadable-config condition is NAMEABLE on a surface+ * rather than only inferable from a gate that suddenly refuses. The+ * runtime-notice channel reports it; `loadIntegrityConfigSafe` uses the+ * same distinction to choose its fallback.+ */+export function brainConfigReadFailure(vault: string): string | null {+ if (!brainConfigExists(vault)) return null;+ try {+ loadBrainConfig(vault);+ return null;+ } catch (err) {+ return err instanceof Error ? err.message : String(err);+ }+}++/**+ * The one-line operator-facing statement of {@link brainConfigReadFailure},+ * or `null` when the config is absent or reads fine.+ *+ * One formulation, because the condition now reaches an operator on more+ * than one surface: the runtime-notice channel pushes it at SessionStart+ * and `vault_health`, and a delivery surface that DEGRADED because of it+ * carries it on its own result. Two hand-written copies of the same+ * sentence would drift, and an operator who saw one would not recognise+ * the other as the same fault.+ *+ * It names no command on purpose. The repair is an edit to the YAML the+ * parser just rejected and no `o2b` verb performs it, which is why+ * `brain_config_unreadable` is deliberately absent from+ * `DIAGNOSTIC_SIGNALS` - see the notice that raises it. The cause the+ * parser gave IS the actionable part, so it is quoted verbatim.+ */+export function brainConfigUnreadableReport(vault: string): string | null {+ const failure = brainConfigReadFailure(vault);+ if (failure === null) return null;+ return (+ `Brain/_brain.yaml could not be read, so configured settings are not in force ` ++ `and the integrity gates fall back to their strictest mode (${failure}). ` ++ `Fix the file, then re-run.`+ );+}++/**+ * Load + resolve the `integrity:` block.+ *+ * Two failure modes, deliberately NOT collapsed into one:+ *+ * - CONFIG ABSENT - a vault that has never run `o2b brain init`. The+ * search layer reads its gate on a store open and must keep working+ * there, so the gates land on `BRAIN_INTEGRITY_DEFAULTS`. This is the+ * case the safe-loader pattern legitimately defends.+ * - CONFIG PRESENT BUT UNREADABLE - a bad gate token, or any unrelated+ * syntax error anywhere else in the file. Falling back to the+ * defaults here would silently turn an operator's+ * `owner_scope_delivery: fail` into `off`. It resolves to+ * {@link BRAIN_INTEGRITY_STRICT_FALLBACK} instead, and+ * {@link brainConfigReadFailure} names the cause.+ *+ * This is the one reader that resolves rather than raises on the second+ * case, and the reason is its caller: the search layer reads its gate on+ * every store open, including inside a fail-soft path, so a throw there+ * would take out recall instead of tightening it. Resolving STRICT is+ * what makes that safe - the unreadable config cannot loosen a gate, it+ * can only close one.+ */+export function loadIntegrityConfigSafe(vault: string): ResolvedBrainIntegrityConfig {+ try {+ return resolveIntegrity(loadBrainConfig(vault));+ } catch {+ return brainConfigExists(vault) ? BRAIN_INTEGRITY_STRICT_FALLBACK : BRAIN_INTEGRITY_DEFAULTS;+ }+}diff --git a/src/core/brain/policy/primary-agent.ts b/src/core/brain/policy/primary-agent.tsnew file mode 100644index 00000000..d1c8eaea--- /dev/null+++ b/src/core/brain/policy/primary-agent.ts@@ -0,0 +1,59 @@+/**+ * The `primary_agent:` scalar β both directions.+ *+ * One reason to change: the grammar of an agent id. Reader and writer sit+ * together on purpose. The loader enforces exactly the constraints the+ * writer enforces, so a hand-edited file that the writer would later+ * refuse to emit fails fast at load time instead of round-tripping into a+ * state we cannot persist.+ */++import { BrainConfigError } from "./errors.ts";+import { assertNoYamlUnsafeChars, describe } from "./field-checks.ts";+import { hasBlock, type BlockParseContext } from "./key-index.ts";+import { DEFAULT_BRAIN_CONFIG } from "./defaults.ts";++const FIELD = "primary_agent";+const SHAPE_HINT = "use a simple one-line agent id";+const EMPTY_MESSAGE = "must be either null or a non-empty string";++/**+ * Format a `primary_agent` value for the small `_brain.yaml` subset.+ *+ * We quote non-null values so spaces / `#` / `:` round-trip as data+ * instead of being interpreted as comments or YAML structure. Since the+ * parser intentionally does not implement escape sequences, reject bytes+ * that would require escaping rather than writing a value that cannot+ * be read back exactly.+ */+export function formatPrimaryAgentYamlValue(+ value: string | null,+ source: string | null = null,+): string {+ if (value === null) return "null";+ const trimmed = value.trim();+ if (trimmed.length === 0) {+ throw new BrainConfigError(EMPTY_MESSAGE, FIELD, source);+ }+ assertNoYamlUnsafeChars(trimmed, FIELD, source, SHAPE_HINT);+ return `"${trimmed}"`;+}++/**+ * Read the optional `primary_agent` scalar. Absent (or explicitly null)+ * resolves to the default so existing vaults are unaffected.+ */+export function parsePrimaryAgent(ctx: BlockParseContext): string | null {+ if (!hasBlock(ctx.obj, FIELD, ctx.keys)) return DEFAULT_BRAIN_CONFIG.primary_agent;+ const value = ctx.obj[FIELD];+ if (value === null || value === undefined) return null;+ if (typeof value !== "string") {+ throw new BrainConfigError(`${EMPTY_MESSAGE}; got ${describe(value)}`, FIELD, ctx.source);+ }+ const trimmed = value.trim();+ if (trimmed.length === 0) {+ throw new BrainConfigError(EMPTY_MESSAGE, FIELD, ctx.source);+ }+ assertNoYamlUnsafeChars(trimmed, FIELD, ctx.source, SHAPE_HINT);+ return trimmed;+}diff --git a/src/core/brain/policy/validate.ts b/src/core/brain/policy/validate.tsnew file mode 100644index 00000000..52dd8738--- /dev/null+++ b/src/core/brain/policy/validate.ts@@ -0,0 +1,225 @@+/**+ * Turn a parsed `_brain.yaml` object into a typed {@link BrainConfig}.+ *+ * One reason to change: which blocks exist and in what order they are+ * read. Every block's own rules live in `./blocks/`; this module owns+ * only the sequence, the mandatory `schema_version` check, and the+ * forward-compat sweep that must run after every block has registered+ * itself.+ */++import type { BrainConfig } from "../types.ts";+import { BrainConfigError, type BrainConfigLoadWarning } from "./errors.ts";+import {+ KeyIndexCollector,+ type BlockParseContext,+ type BrainConfigKeyIndex,+} from "./key-index.ts";+import { BRAIN_CONFIG_SUPPORTED_VERSIONS, DEFAULT_BRAIN_CONFIG } from "./defaults.ts";+import { parsePrimaryAgent } from "./primary-agent.ts";+import {+ parseConfidenceBlock,+ parseDreamBlock,+ parseRetireBlock,+ parseSnapshotsBlock,+} from "./blocks/lifecycle.ts";+import { parseVaultBlock } from "./blocks/vault-ignore.ts";+import { parseActiveBlock } from "./blocks/active.ts";+import { parseLessonsBlock } from "./blocks/lessons.ts";+import { parseDisciplineReportBlock } from "./blocks/discipline-report.ts";+import { parseGuardrailsBlock } from "./blocks/guardrails.ts";+import { parseRollupBlock } from "./blocks/rollup.ts";+import { parseLinkGraphBlock } from "./blocks/link-graph.ts";+import { parseTemporalBlock } from "./blocks/temporal.ts";+import { parseHealthBlock } from "./blocks/health.ts";+import { parseIntegrityBlock } from "./blocks/integrity.ts";+import { parseNotesBlock } from "./blocks/notes.ts";+import { parseSessionsBlock } from "./blocks/sessions.ts";+import { parseSchemaBlock } from "./blocks/schema.ts";+import {+ parseAnticipatoryBlock,+ parseHygieneBlock,+ parseRecallBlock,+} from "./blocks/continuity-hygiene.ts";+import { parseFeedbackBlock } from "./blocks/feedback.ts";++export interface ValidateResult {+ readonly config: BrainConfig;+ readonly warnings: ReadonlyArray<BrainConfigLoadWarning>;+ /**+ * Every key this validation run branched on, top-level and per-block.+ * Recorded by construction (see `KeyIndexCollector`) rather than from a+ * hand-maintained list, so it can never disagree with what the+ * validator actually understands. Consumed by the configuration-template+ * ratchet.+ */+ readonly knownKeys: BrainConfigKeyIndex;+}++/**+ * Pure validator. Accepts a parsed object (typically from+ * `parseBrainYaml`) and returns a typed {@link BrainConfig}, or+ * throws {@link BrainConfigError} naming the offending field.+ *+ * `source` is rendered into error messages; pass the config file path or+ * a synthetic label like `"<test fixture>"` so the failure points at+ * something useful.+ */+export function validateBrainConfig(parsed: unknown, source: string | null = null): BrainConfig {+ return validateBrainConfigDetailed(parsed, source).config;+}++export function validateBrainConfigDetailed(+ parsed: unknown,+ source: string | null = null,+): ValidateResult {+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {+ throw new BrainConfigError("config root must be a map of keys", null, source);+ }+ const ctx: BlockParseContext = {+ obj: parsed as Record<string, unknown>,+ source,+ warnings: [],+ keys: new KeyIndexCollector(),+ };+ // `schema_version` is seeded directly because `readSchemaVersion`+ // checks its presence with an inverted `in` test rather than through+ // `hasBlock`, so nothing else would register it.+ ctx.keys.addTop("schema_version");+ const schemaVersion = readSchemaVersion(ctx);+ const primaryAgent = parsePrimaryAgent(ctx);++ // Each block is optional; a missing block inherits its default. The+ // lifecycle blocks merge field-by-field so a user can override one+ // threshold without having to re-state the rest.+ const dream = parseDreamBlock(ctx);+ const retire = parseRetireBlock(ctx);+ const confidence = parseConfidenceBlock(ctx);+ const snapshots = parseSnapshotsBlock(ctx);++ const vault = parseVaultBlock(ctx);+ const active = parseActiveBlock(ctx);+ const lessons = parseLessonsBlock(ctx);+ const disciplineReport = parseDisciplineReportBlock(ctx);+ const guardrails = parseGuardrailsBlock(ctx);+ const rollup = parseRollupBlock(ctx);+ const linkGraph = parseLinkGraphBlock(ctx);+ const temporal = parseTemporalBlock(ctx);+ const health = parseHealthBlock(ctx);+ const integrity = parseIntegrityBlock(ctx);+ const notes = parseNotesBlock(ctx);+ const sessions = parseSessionsBlock(ctx);+ const schema = parseSchemaBlock(ctx);+ const hygiene = parseHygieneBlock(ctx);+ const anticipatory = parseAnticipatoryBlock(ctx);+ const recall = parseRecallBlock(ctx);+ const feedback = parseFeedbackBlock(ctx);++ warnUnknownTopLevelKeys(ctx);++ const config: BrainConfig = {+ schema_version: schemaVersion,+ primary_agent: primaryAgent,+ dream,+ retire,+ confidence,+ snapshots,+ ...(vault !== undefined ? { vault } : {}),+ ...(active !== undefined ? { active } : {}),+ ...(lessons !== undefined ? { lessons } : {}),+ ...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),+ ...(rollup !== undefined ? { rollup } : {}),+ ...(guardrails !== undefined ? { guardrails } : {}),+ ...(linkGraph !== undefined ? { link_graph: linkGraph } : {}),+ ...(temporal !== undefined ? { temporal } : {}),+ ...(notes !== undefined ? { notes } : {}),+ ...(sessions !== undefined ? { sessions } : {}),+ ...(health !== undefined ? { health } : {}),+ ...(integrity !== undefined ? { integrity } : {}),+ ...(schema !== undefined ? { schema } : {}),+ ...(hygiene !== undefined ? { hygiene } : {}),+ ...(anticipatory !== undefined ? { anticipatory } : {}),+ ...(recall !== undefined ? { recall } : {}),+ ...(feedback !== undefined ? { feedback } : {}),+ };++ return { config, warnings: ctx.warnings, knownKeys: ctx.keys };+}++/** Mandatory, and must be in the supported set. */+function readSchemaVersion(ctx: BlockParseContext): number {+ if (!("schema_version" in ctx.obj)) {+ throw new BrainConfigError(+ "missing required field; expected a positive integer in the supported set " ++ `(${BRAIN_CONFIG_SUPPORTED_VERSIONS.join(", ")})`,+ "schema_version",+ ctx.source,+ );+ }+ const value = ctx.obj["schema_version"];+ if (+ typeof value !== "number" ||+ !Number.isInteger(value) ||+ !BRAIN_CONFIG_SUPPORTED_VERSIONS.includes(value)+ ) {+ throw new BrainConfigError(+ `unsupported value ${JSON.stringify(value)}; expected one of ` ++ BRAIN_CONFIG_SUPPORTED_VERSIONS.join(", "),+ "schema_version",+ ctx.source,+ );+ }+ return value;+}++/**+ * Forward-compat: unknown top-level keys β warning, not error. Runs after+ * every block has had a chance to register itself, so a block can never be+ * parsed-but-not-yet-known at the point this check reads the set. Uses its+ * own message format (distinct from `warnUnknownKeys`'s `block.key: β¦`+ * shape), pinned by an existing test.+ */+function warnUnknownTopLevelKeys(ctx: BlockParseContext): void {+ for (const key of Object.keys(ctx.obj)) {+ if (!ctx.keys.topLevel.has(key)) {+ ctx.warnings.push({+ path: ctx.source ?? "<config>",+ message: `unknown top-level field '${key}' ignored (forward-compat)`,+ });+ }+ }+}++/**+ * Probe source label used by {@link brainConfigKnownKeys}. Never reaches+ * a user-visible surface: the probe discards its warnings.+ */+const KEY_INDEX_PROBE_SOURCE = "<brain-config-key-index>";++/**+ * Every configuration key {@link validateBrainConfigDetailed} branches+ * on, enumerated by running the validator rather than by reading a list.+ *+ * Two passes are needed because a block's sub-key vocabulary is only+ * declared inside the branch that parses the block: pass one discovers+ * the top-level keys against a minimal config, pass two re-runs with+ * every discovered block present but empty so each block's sub-key+ * registration executes. Scalar top-level keys keep their default value+ * in pass two - handing `primary_agent` an empty map would (correctly)+ * be rejected.+ */+export function brainConfigKnownKeys(): BrainConfigKeyIndex {+ const minimal: Record<string, unknown> = {+ schema_version: BRAIN_CONFIG_SUPPORTED_VERSIONS[0],+ };+ const firstPass = validateBrainConfigDetailed(minimal, KEY_INDEX_PROBE_SOURCE).knownKeys;+ const defaults = DEFAULT_BRAIN_CONFIG as unknown as Record<string, unknown>;+ const probe: Record<string, unknown> = { ...minimal };+ for (const key of firstPass.topLevel) {+ if (key in minimal) continue;+ const fallback = defaults[key];+ const isScalar = key in defaults && (fallback === null || typeof fallback !== "object");+ probe[key] = isScalar ? fallback : {};+ }+ return validateBrainConfigDetailed(probe, KEY_INDEX_PROBE_SOURCE).knownKeys;+}diff --git a/src/core/brain/pre-compress-pack.ts b/src/core/brain/pre-compress-pack.tsindex f67d329b..db6bc0c0 100644--- a/src/core/brain/pre-compress-pack.ts+++ b/src/core/brain/pre-compress-pack.ts@@ -19,7 +19,12 @@ import { existsSync, readFileSync } from "node:fs";import { renderActive } from "./active.ts";import { brainActivePath, brainDirs } from "./paths.ts";-import { collectPreferences, resolveOwnerScopeDelivery } from "./preferences-collect.ts";+import { brainConfigUnreadableReport } from "./policy.ts";+import {+ collectPreferences,+ resolveOwnerScopeDelivery,+ type OwnerScopeDelivery,+} from "./preferences-collect.ts";import { applyCharBudget, type CharBudgetDegradationMode } from "./recall-budget.ts";import { emitContextReceipt, type ContextReceiptOptions } from "./context-receipts.ts";import { emitGatedTelemetry } from "./continuity/emit.ts";@@ -53,6 +58,14 @@ export interface PreCompressPack {readonly receiptId?: string;readonly telemetryId?: string;readonly totalChars: number;+ /**+ * Delivery reports that are not pack content: currently only the+ * unreadable-config degradation below. Same key and same+ * absent-when-empty rule as `ContextPackReport.warnings`, so the two+ * pack builders answer "what should the caller know about this+ * result" in one shape. A healthy vault carries no key at all.+ */+ readonly warnings?: ReadonlyArray<string>;}export interface PreCompressOptions {@@ -88,15 +101,13 @@ interface ConfirmedPref {readonly createdAt: string;}-function collectConfirmed(vault: string, agentScope: string | undefined): ConfirmedPref[] {+function collectConfirmed(vault: string, ownerScope: OwnerScopeDelivery): ConfirmedPref[] {const dir = brainDirs(vault).preferences;const out: ConfirmedPref[] = [];// Listing and parse come from the shared delivery-path walk// (context-integrity-gates, Unit A); the confirmed-status filter is// this surface's own and stays here.- for (const { pref } of collectPreferences(dir, {- ownerScope: resolveOwnerScopeDelivery(vault, agentScope),- }).entries) {+ for (const { pref } of collectPreferences(dir, { ownerScope }).entries) {if (pref.status !== BRAIN_PREFERENCE_STATUS.confirmed) continue;out.push({id: pref.id,@@ -108,6 +119,22 @@ function collectConfirmed(vault: string, agentScope: string | undefined): Confirreturn out;}+/** The active head this caller may see, and why it may be missing. */+interface ActiveHead {+ /** Head text, or `null` when there is none to deliver. */+ readonly text: string | null;+ /** Operator-facing reason the head was withheld, or `null`. */+ readonly warning: string | null;+}++/** Nothing to deliver, nothing to report. */+const NO_ACTIVE_HEAD: ActiveHead = Object.freeze({ text: null, warning: null });++/** An active head that is present, with nothing to report about it. */+function deliveredHead(text: string): ActiveHead {+ return text.length > 0 ? Object.freeze({ text, warning: null }) : NO_ACTIVE_HEAD;+}+/*** The active-digest head this caller may see.*@@ -121,19 +148,40 @@ function collectConfirmed(vault: string, agentScope: string | undefined): Confir** With no enforced scope - the shipped `off` default - the file is read* verbatim exactly as before, stamp and all.+ *+ * ## Why an unreadable config is checked here rather than caught+ *+ * The two halves of the gate compose into a failure neither designed+ * for. `loadIntegrityConfigSafe` deliberately RESOLVES on an unreadable+ * `_brain.yaml`, to its strict fallback, so the gate closes rather than+ * opens - which hands this caller an `enforcedScope`. {@link+ * renderActive} then reads the guardrail block through a loader that+ * RAISES on the same file. One bad line therefore cost a scoped agent+ * its entire pre-compaction pack while an unscoped one still got a pack.+ *+ * So the condition is a precondition of the scoped render, tested by the+ * same predicate the loader splits on, and the head is withheld with the+ * reason named. It is not a `catch`: any other failure inside+ * `renderActive` still propagates, and a `catch` here would re-absorb+ * exactly the silence the split removed.+ *+ * Withheld, never substituted. The file's bytes are not a fallback for a+ * scoped render - serving them under an enforcing gate is the leak A3+ * exists to prevent - and the strict fallback is what makes withholding+ * safe: an unreadable config can only close this gate, never open it.*/-function readActiveHead(vault: string, enforcedScope: string | null): string | null {+function readActiveHead(vault: string, enforcedScope: string | null): ActiveHead {if (enforcedScope !== null) {- const text = renderActive(vault, { agentScope: enforcedScope }).document.trim();- return text.length > 0 ? text : null;+ const unreadableConfig = brainConfigUnreadableReport(vault);+ if (unreadableConfig !== null) return Object.freeze({ text: null, warning: unreadableConfig });+ return deliveredHead(renderActive(vault, { agentScope: enforcedScope }).document.trim());}const path = brainActivePath(vault);- if (!existsSync(path)) return null;+ if (!existsSync(path)) return NO_ACTIVE_HEAD;try {- const text = readFileSync(path, "utf8").trim();- return text.length > 0 ? text : null;+ return deliveredHead(readFileSync(path, "utf8").trim());} catch {- return null;+ return NO_ACTIVE_HEAD;}}@@ -144,21 +192,22 @@ function readActiveHead(vault: string, enforcedScope: string | null): string | n*/export function buildPreCompressPack(vault: string, opts: PreCompressOptions): PreCompressPack {const startedAtMs = Date.now();- const ranked = collectConfirmed(vault, opts.agentScope).toSorted((a, b) => {+ // One gate verdict for the whole build. The preference walk and the+ // active head must agree on it, and resolving it twice also read+ // `_brain.yaml` twice per pack.+ const ownerScope = resolveOwnerScopeDelivery(vault, opts.agentScope);+ const ranked = collectConfirmed(vault, ownerScope).toSorted((a, b) => {if (b.confidence !== a.confidence) return b.confidence - a.confidence;if (a.createdAt !== b.createdAt) return a.createdAt < b.createdAt ? 1 : -1;return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;});const top = ranked.slice(0, Math.max(0, opts.topK));- const activeHead = readActiveHead(- vault,- resolveOwnerScopeDelivery(vault, opts.agentScope).enforcedScope,- );+ const activeHead = readActiveHead(vault, ownerScope.enforcedScope);const safetyById = new Map<string, ContextSafetyReport>();const entries: Array<{ item: string; text: string }> = [];- if (activeHead !== null) {- const guarded = guardBrainContextSnippet(activeHead, {+ if (activeHead.text !== null) {+ const guarded = guardBrainContextSnippet(activeHead.text, {source: { id: ACTIVE_ID, path: brainActivePath(vault) },});const safety = contextSafetyReport(guarded);@@ -275,5 +324,6 @@ export function buildPreCompressPack(vault: string, opts: PreCompressOptions): P...(receipt ? { receiptId: receipt.id } : {}),...(telemetry ? { telemetryId: telemetry.id } : {}),totalChars: budgeted.totalChars,+ ...(activeHead.warning !== null ? { warnings: Object.freeze([activeHead.warning]) } : {}),});}diff --git a/src/core/brain/runtime-notices.ts b/src/core/brain/runtime-notices.tsindex 25a06214..eedd4b86 100644--- a/src/core/brain/runtime-notices.ts+++ b/src/core/brain/runtime-notices.ts@@ -34,7 +34,7 @@ import { resolveSearchConfig } from "../search/index.ts";import { checkVaultWriteable } from "../doctor.ts";import { NEXT_COMMAND_KEY, nextCommandField, type NextCommandField } from "./next-step.ts";import { BRAIN_ROOT_REL } from "./paths.ts";-import { brainConfigReadFailure } from "./policy.ts";+import { brainConfigUnreadableReport } from "./policy.ts";import { vaultMarkerAbsentNotice } from "./vault-identity.ts";export type RuntimeNoticeSeverity = "info" | "warning";@@ -137,20 +137,18 @@ export function collectRuntimeNotices(// not the ones in force, so the condition has to be visible instead of// inferable from a gate that suddenly refuses.//+ // The sentence is `brainConfigUnreadableReport`'s, not this channel's:+ // a delivery surface that degraded because of the same condition+ // carries the same words, so an operator meets one fault and not two.+ //// No registered command: the repair is an edit to the YAML the parser- // just rejected, and no `o2b` verb performs it. The failure detail below- // is what the operator acts on; `o2b brain doctor` would only re-report- // the same line, which is a round-trip, not an exit.+ // just rejected, and no `o2b` verb performs it. The failure detail the+ // report quotes is what the operator acts on; `o2b brain doctor` would+ // only re-report the same line, which is a round-trip, not an exit.try {- const failure = brainConfigReadFailure(vault);- if (failure !== null) {- notices.push(- notice(- "brain_config_unreadable",- "warning",- `Brain/_brain.yaml could not be read, so configured settings are not in force and the integrity gates fall back to their strictest mode (${failure}). Fix the file, then re-run.`,- ),- );+ const report = brainConfigUnreadableReport(vault);+ if (report !== null) {+ notices.push(notice("brain_config_unreadable", "warning", report));}} catch {// best-effortdiff --git a/src/core/brain/truth/store.ts b/src/core/brain/truth/store.tsindex 676bd0c2..cd6e3ff1 100644--- a/src/core/brain/truth/store.ts+++ b/src/core/brain/truth/store.ts@@ -60,7 +60,18 @@ export function truthStatePath(vault: string): string {return join(truthDir(vault), "state.json");}-/** The shard this device appends to. */+/**+ * The shard this device appends to.+ *+ * @throws {@link ConfigReadError} when the device-local config naming this+ * device cannot be read. Propagated rather than falling back to the+ * legacy un-sharded `claims.jsonl`: `resolveDeviceId` would otherwise+ * mint and persist a fresh id over a config it could not read (see its+ * docblock), and a silent shard switch would scatter one device's claims+ * across two files with nothing recording why. The error names the file+ * and the way out; the CLI verb wrapping this call prints it, and+ * `O2B_DEVICE_ID` resolves the append without the file.+ */export function claimShardPath(vault: string, configPath?: string): string {const deviceId = resolveDeviceId(configPath);const name = deviceId === "" ? "claims.jsonl" : `claims.${deviceId}.jsonl`;diff --git a/src/core/brain/vault-identity.ts b/src/core/brain/vault-identity.tsindex 55727f4c..1040baba 100644--- a/src/core/brain/vault-identity.ts+++ b/src/core/brain/vault-identity.ts@@ -88,7 +88,7 @@ import {type DegradationNotice,} from "../integrity/degradation.ts";import { compareStamps, formatStampMismatch, type StampMismatch } from "../integrity/stamp.ts";-import { BRAIN_ROOT_REL } from "./paths.ts";+import { BRAIN_ROOT_REL } from "./path-constants.ts";/** Marker schema version. Bumped only on an incompatible field change. */export const VAULT_IDENTITY_SCHEMA_VERSION = 1;diff --git a/src/core/brain/wikilink.ts b/src/core/brain/wikilink.tsindex c7604218..eab36fd5 100644--- a/src/core/brain/wikilink.ts+++ b/src/core/brain/wikilink.ts@@ -118,6 +118,27 @@ function stripBasenameDecoration(body: string): string {return s;}+/**+ * The id prefixes this Brain owns: preferences, retired records, and+ * signals. Anything else a wikilink resolves to is user prose or a+ * cross-layer note, and is nobody here's to flag or to prune.+ */+const BRAIN_ID_RE = /^(pref|ret|sig)-/;++/**+ * Whether `target` β a bare id, normally straight out of+ * {@link normaliseWikilinkTarget} β names an artifact this Brain+ * manages.+ *+ * A predicate rather than an exported pattern: the two callers that+ * asked this question each carried their own copy of the regex, which is+ * one grammar in two places waiting to disagree about a fourth prefix.+ * Exposing the answer instead of the pattern is what keeps it single.+ */+export function isBrainArtifactId(target: string): boolean {+ return BRAIN_ID_RE.test(target);+}+/*** Return the bare target id if `value` is exactly a wikilink form* (`^\[\[β¦\]\]$` modulo surrounding whitespace), otherwise `null`.diff --git a/src/core/config.ts b/src/core/config.tsindex 7fa3c434..08dea91b 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -7,7 +7,7 @@* via parallel suites in tests/core/config.test.ts.*/-import { mkdirSync, readFileSync } from "node:fs";+import { mkdirSync, readFileSync, statSync, type Stats } from "node:fs";import { createHmac, randomBytes } from "node:crypto";import { homedir } from "node:os";import { dirname, isAbsolute, join, resolve } from "node:path";@@ -15,7 +15,6 @@ import { dirname, isAbsolute, join, resolve } from "node:path";import lockfile from "proper-lockfile";import { atomicWriteFileSync } from "./fs-atomic.ts";-import { isFile } from "./fs-utils.ts";import { resolveActiveProfileVault } from "./brain/portability/profiles.ts";import { resolvePointerVault } from "./brain/portability/pointer.ts";import {@@ -61,6 +60,43 @@ export class UnsupportedPlatformError extends Error {}}+/**+ * Raised when the plugin config file is PRESENT but its contents cannot be+ * obtained: a directory (or any non-regular file) where the file should be,+ * a path that cannot be stat'ed at all (an untraversable parent, a symlink+ * loop), a file that cannot be opened, or bytes that are not UTF-8.+ *+ * Named and specific for the same reason {@link UnsupportedPlatformError}+ * is: the alternative - reporting the file as absent - is a+ * plausible-looking answer to a question this module cannot answer. Absent+ * means "no operator settings, defaults apply"; every gate resolved from+ * this file is default-OFF, so absorbing an unreadable file turns the+ * operator's flags off and leaves the install indistinguishable from one+ * that never set them.+ */+export class ConfigReadError extends Error {+ /** The config file that could not be read. */+ readonly path: string;++ constructor(path: string, reason: string) {+ // The remedy rides in the message rather than in each reporting+ // surface. This error escapes through four channels with nothing in+ // common - the CLI dispatch, an MCP error envelope, a hook's stderr,+ // and a subcommand that wraps it in its own prose - and a remedy+ // rendered per surface would drift between them or be dropped by the+ // wrappers. Long and instructive matches+ // {@link UnsupportedPlatformError}, for the same reason: the whole+ // value of a refusal is telling the operator what to do next.+ super(+ `failed to read plugin config ${path}: ${reason}. The file is present, so its ` ++ "settings are NOT in force and are not read as absent; make it readable " ++ `(chmod u+r "${path}") or set OPEN_SECOND_BRAIN_CONFIG to a readable config file.`,+ );+ this.name = "ConfigReadError";+ this.path = path;+ }+}+/** Injected view of the environment {@link resolveDefaultConfigPath} reads. */export interface ConfigPathEnv {/** `process.platform` value. */@@ -139,17 +175,97 @@ export function parseSimpleYaml(text: string): Record<string, string> {return data;}-/** Read and parse the config file, or report it as missing. */+/**+ * Read and parse the config file, or report it as missing.+ *+ * TWO conditions, not one, and they are kept apart on purpose - the same+ * split `Brain/_brain.yaml` makes in `brain/policy/load.ts`:+ *+ * - ABSENT - nothing at this path. There are no operator settings to+ * contradict, so `exists: false` with no data is the correct answer and+ * every resolver above falls back to its documented default. This is+ * the common case on any install that has not run `o2b init`.+ * - PRESENT BUT UNREADABLE - a non-regular file (a directory in the+ * file's place), a path that cannot be stat'ed, a file that cannot be+ * opened, or bytes that are not UTF-8. The operator's settings exist+ * and are NOT the ones in force. Reporting that as absent turned every+ * default-OFF gate resolved from this file back to `false` and left the+ * install looking exactly like one that never set a flag;+ * {@link ConfigReadError} names the file instead.+ *+ * The parse itself has no third condition: {@link parseSimpleYaml} skips+ * whatever it cannot represent (comments, blank lines, nested blocks), and+ * that tolerance is deliberate parity with the legacy Python reader. That+ * tolerance is about SHAPE, not encoding - see {@link readConfigText}.+ */export function discoverConfig(path?: string): ConfigDiscovery {const resolved = path ?? defaultConfigPath();- if (!isFile(resolved)) {+ const stat = statConfigPath(resolved);+ if (stat === undefined) {return { path: resolved, exists: false, data: {} };}+ // Ahead of the read rather than letting `readFileSync` raise `EISDIR`,+ // because it also covers the paths a read cannot survive: a FIFO at the+ // config path would block the process forever.+ if (!stat.isFile()) {+ throw new ConfigReadError(resolved, "path exists but is not a regular file");+ }+ return { path: resolved, exists: true, data: parseSimpleYaml(readConfigText(resolved)) };+}++/**+ * Stat of the config path: `undefined` for a genuine absence, {@link Stats}+ * otherwise, {@link ConfigReadError} when the answer is unknowable.+ *+ * This replaces an `existsSync` check, which is not the absent/broken split+ * it looks like: it answers `false` for EVERY stat failure, so a perfectly+ * readable config behind a directory lacking the execute bit (or under a+ * symlink loop, or past a name-too-long component) reported as absent and+ * silently reverted the operator's `vault` and every gate in the file to+ * its default. Only ENOENT on this path is an absence; every other errno is+ * a failure to read it.+ *+ * `throwIfNoEntry: false` is what makes that split free rather than a+ * downgrade: it suppresses ENOENT alone and still raises every other errno,+ * so the common absent case pays one syscall and constructs no error - the+ * same cost `existsSync` had, since it is the same `stat`.+ */+function statConfigPath(resolved: string): Stats | undefined {try {- const text = readFileSync(resolved, "utf8");- return { path: resolved, exists: true, data: parseSimpleYaml(text) };- } catch {- return { path: resolved, exists: false, data: {} };+ return statSync(resolved, { throwIfNoEntry: false });+ } catch (err) {+ throw new ConfigReadError(resolved, (err as Error).message ?? String(err));+ }+}++/**+ * Decoded contents of a config file that is known to be a regular file, or+ * a {@link ConfigReadError}.+ *+ * The decode is FATAL, so bytes that are not UTF-8 are the present-but-+ * unreadable condition rather than a lossy parse. `parseSimpleYaml` is+ * tolerant about the SHAPE of a line - that is deliberate parity with the+ * legacy Python reader - but nothing about it licenses accepting bytes we+ * cannot represent: a lossy decode drops whichever keys the undecodable+ * run straddles, which is the same silent revert-to-default as reading the+ * file as absent. It is also destructive, because {@link setConfigValue}+ * merges onto what this returns and would persist the operator's file with+ * every undecodable byte replaced.+ */+function readConfigText(resolved: string): string {+ let bytes: Buffer;+ try {+ bytes = readFileSync(resolved);+ } catch (err) {+ throw new ConfigReadError(resolved, (err as Error).message ?? String(err));+ }+ try {+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);+ } catch (err) {+ throw new ConfigReadError(+ resolved,+ `not valid UTF-8: ${(err as Error).message ?? String(err)}`,+ );}}@@ -271,6 +387,26 @@ export function resolveAgentName(configPath?: string): string {* hand-edited value self-heals to a fresh generated id; the* `sync-conflict` prefix is reserved so a renamed Syncthing conflict* copy can never masquerade as a shard.+ *+ * ## A config that cannot be READ is a refusal, deliberately+ *+ * {@link resolveDeviceId} and {@link resolveInstallationSecret} tolerate a+ * config directory they cannot LOCK - the lock only orders a race, and+ * losing it costs at most a duplicate generation. They do NOT tolerate a+ * config they cannot READ, and {@link ConfigReadError} propagates out of+ * both. The self-heal is the reason: a miss means generate-and-persist,+ * an unreadable file is not a miss, and treating it as one is destructive+ * twice over. {@link setConfigValue} merges onto what it read, so writing+ * a generated id through it would flatten the operator's whole config to+ * that single line; and the value itself is load-bearing - a fresh device+ * id silently re-shards this device's log, a fresh installation secret+ * silently changes every `vault://` reference agents correlate by. There+ * is no neutral answer to fall back to, so the file is named instead.+ *+ * The env overrides are the escape hatch that makes the refusal+ * survivable: `O2B_DEVICE_ID` (and, for tests,+ * {@link INSTALLATION_SECRET_ENV_KEY}) are honoured before the file is+ * opened at all.*/export const DEVICE_ID_RE = /^[a-z0-9][a-z0-9-]{0,31}$/;@@ -295,12 +431,15 @@ export function resolveDeviceId(configPath?: string): string {const existing = read();if (existing !== null) return existing;- // First-use generation. Two processes racing here could each persist- // a different id and split one device's logs across two shards, so- // the read-generate-write sequence holds a directory lock (same- // bounded-retry shape as the log writer's `acquireLogLock`). A- // lock failure (read-only config home, exotic fs) falls through to- // the unlocked path - identity resolution must never fail.+ // First-use generation, reached only because the config was READ and+ // holds no usable id (see the identity docblock above for why an+ // unreadable one never gets here). Two processes racing could each persist a different+ // id and split one device's logs across two shards, so the+ // read-generate-write sequence holds a directory lock (same+ // bounded-retry shape as the log writer's `acquireLogLock`). A lock+ // failure (read-only config home, exotic fs) falls through to the+ // unlocked path - losing the lock costs at most a duplicate generation,+ // which is not worth failing over.const dir = dirname(resolved);mkdirSync(dir, { recursive: true });let release: (() => void) | undefined;@@ -381,9 +520,9 @@ export function resolveInstallationSecret(configPath?: string): string {const existing = read();if (existing !== null) return existing;- // First-use generation under a directory lock, mirroring resolveDeviceId:- // a lock failure falls through to the unlocked path so secret resolution- // never fails outright.+ // First-use generation under a directory lock, mirroring resolveDeviceId+ // in both halves: a lock failure falls through to the unlocked path,+ // while a config that could not be READ never reaches here at all.const dir = dirname(resolved);mkdirSync(dir, { recursive: true });let release: (() => void) | undefined;@@ -421,6 +560,13 @@ const VAULT_STORE_REF_HEX_LEN = 32;* negligible. It is stable across calls on the same install (agents correlate* by it) and never leaks the raw path. Returned by MCP tools in place of the* absolute path unless {@link resolveExposeHostPaths} is on.+ *+ * @throws {@link ConfigReadError} when the device-local config holding the+ * key cannot be read. Propagated, not absorbed: the only fallbacks would+ * be a fresh key (breaking the stability every consumer correlates by) or+ * the raw host path (the leak this function exists to prevent). Callers+ * that render a payload report the condition in the field - see+ * `vaultPathField` in `src/mcp/tools.ts`.*/export function vaultStoreReference(vaultPath: string, configPath?: string): string {const key = resolveInstallationSecret(configPath);diff --git a/src/core/doctor.ts b/src/core/doctor.tsindex c53b5879..a9f5e292 100644--- a/src/core/doctor.ts+++ b/src/core/doctor.ts@@ -14,10 +14,11 @@ import {rmSync,writeSync,closeSync,+ type Stats,} from "node:fs";import { dirname, join } from "node:path";-import { isFile } from "./fs-utils.ts";+import { statOrAbsent } from "./fs-utils.ts";import { checkCodegraph } from "./partner/codegraph.ts";import type { CheckResult } from "./types.ts";@@ -73,15 +74,50 @@ export function checkConfigWriteable(config: string): CheckResult {return { name: "config_writeable", ok: true, message: `config writable: ${config}` };}+interface ManifestFileProblem {+ /** True when the path was examined and holds no usable file. */+ readonly absent: boolean;+ readonly message: string;+ readonly fix: string;+}++/**+ * Why `path` does not hold a readable manifest file, or null when it does.+ *+ * Doctor's whole output is the difference between a file that is not there+ * and a file that is there and wrong, so it is the one caller that must+ * not ask `isFile`: that probe answers `false` for an absent file AND for+ * one this process cannot stat at all - a parent directory without the+ * execute bit, a symlink loop - so a manifest sitting behind a permission+ * problem was reported as one that had never been generated, under a+ * `o2b update` remedy that regenerates it and changes nothing. The two+ * conditions carry different messages and different fixes.+ */+function manifestFileProblem(path: string): ManifestFileProblem | null {+ let stat: Stats | undefined;+ try {+ stat = statOrAbsent(path);+ } catch (exc) {+ return {+ absent: false,+ message: `unreadable: ${path} (${(exc as Error).message ?? exc})`,+ fix: `chmod u+r "${path}"`,+ };+ }+ if (stat?.isFile() === true) return null;+ return { absent: true, message: `missing: ${path}`, fix: MANIFEST_FIX };+}+interface JsonLoadResult {readonly result: CheckResult;readonly data: Record<string, unknown> | null;}function loadJsonManifest(path: string, name: string): JsonLoadResult {- if (!isFile(path)) {+ const problem = manifestFileProblem(path);+ if (problem !== null) {return {- result: { name, ok: false, message: `missing: ${path}`, fix: MANIFEST_FIX },+ result: { name, ok: false, message: problem.message, fix: problem.fix },data: null,};}@@ -230,8 +266,9 @@ export function checkClaudeManifest(path: string): CheckResult {}export function checkHermesManifest(path: string): CheckResult {- if (!isFile(path)) {- return { name: "hermes_manifest", ok: false, message: `missing: ${path}`, fix: MANIFEST_FIX };+ const problem = manifestFileProblem(path);+ if (problem !== null) {+ return { name: "hermes_manifest", ok: false, message: problem.message, fix: problem.fix };}let text: string;try {@@ -321,7 +358,8 @@ export function checkOpenclawInstallability(repoRoot: string): CheckResult[] {continue;}const entryPath = join(repoRoot, entry);- if (isFile(entryPath)) {+ const problem = manifestFileProblem(entryPath);+ if (problem === null) {results.push({name: `openclaw_entry_${entry}`,ok: true,@@ -331,8 +369,10 @@ export function checkOpenclawInstallability(repoRoot: string): CheckResult[] {results.push({name: `openclaw_entry_${entry}`,ok: false,- message: `missing extension entry: ${entry}`,- fix: MANIFEST_FIX,+ message: problem.absent+ ? `missing extension entry: ${entry}`+ : `extension entry ${entry} ${problem.message}`,+ fix: problem.fix,});}}diff --git a/src/core/fs-utils.ts b/src/core/fs-utils.tsindex c5a86b90..c18767a8 100644--- a/src/core/fs-utils.ts+++ b/src/core/fs-utils.ts@@ -6,23 +6,56 @@* copy-pasted across 4+ files.*/-import { existsSync, statSync } from "node:fs";+import { statSync, type Stats } from "node:fs";-/** True when `p` exists and is a regular file. Never throws. */+/**+ * Stat `p`, keeping a genuine absence apart from a failure to look.+ *+ * `undefined` means ENOENT on this path: nothing is there. Every OTHER+ * errno - an unreadable parent directory, a symlink loop, a name too long+ * - is a failure to ANSWER the question, and propagates. This is the split+ * `discoverConfig` makes for the plugin config, for the same reason:+ * answering "not there" for a path that is there but unreachable sends the+ * operator a remedy that tells them to create what already exists, and+ * hides the permission problem that is the real fault.+ *+ * `throwIfNoEntry: false` is what makes the split free rather than a cost:+ * it suppresses ENOENT alone and raises every other errno, so the common+ * absent case pays one syscall and constructs no error.+ */+export function statOrAbsent(p: string): Stats | undefined {+ return statSync(p, { throwIfNoEntry: false });+}++/**+ * True when `p` exists and is a regular file. False when it is absent,+ * when it is something other than a regular file, AND when it cannot be+ * stat'ed at all.+ *+ * That third case is a deliberate leniency, which is why this stays a+ * separate verb from {@link statOrAbsent} rather than wrapping it+ * silently: callers asking only "is this a candidate worth opening" act+ * identically on "absent" and "unreachable", and a probe that raises would+ * make them all grow a catch. Any caller whose OUTPUT distinguishes the+ * two - a diagnostic that prints "missing" and a remedy - must use+ * {@link statOrAbsent} and report the reason.+ */export function isFile(p: string): boolean {- if (!existsSync(p)) return false;try {- return statSync(p).isFile();+ return statOrAbsent(p)?.isFile() ?? false;} catch {return false;}}-/** True when `p` exists and is a directory. Never throws. */+/**+ * True when `p` exists and is a directory; false when absent, when it is+ * not a directory, and when it cannot be stat'ed. See {@link isFile} for+ * when that leniency is the wrong verb.+ */export function isDir(p: string): boolean {- if (!existsSync(p)) return false;try {- return statSync(p).isDirectory();+ return statOrAbsent(p)?.isDirectory() ?? false;} catch {return false;}diff --git a/src/core/partner/codegraph.ts b/src/core/partner/codegraph.tsindex 8fb030c2..15e19f0a 100644--- a/src/core/partner/codegraph.ts+++ b/src/core/partner/codegraph.ts@@ -16,7 +16,7 @@ import { existsSync, readdirSync, realpathSync } from "node:fs";import { dirname, join, resolve } from "node:path";import type { CheckResult } from "../types.ts";-import { isDir } from "../fs-utils.ts";+import { isDir, statOrAbsent } from "../fs-utils.ts";import { assessGraphHealth, summarizeGraphHealth } from "./codegraph-health.ts";const CODE_MANIFESTS: ReadonlyArray<string> = [@@ -287,7 +287,23 @@ export function checkCodegraph(*/function evaluateProjectStatus(project: string, deps?: CodegraphCheckDeps): CheckResult {const indexDir = join(project, ".codegraph");- if (!isDir(indexDir)) {+ // Stat'ed rather than probed with `isDir`, which answers `false` both for+ // an index that was never built and for one this process cannot look at.+ // Only the first is "not indexed", and it is the only one `codegraph+ // init` clears - telling an operator to re-init an index that is already+ // there sends them past the permission fault that is the actual cause.+ let indexed: boolean;+ try {+ indexed = statOrAbsent(indexDir)?.isDirectory() === true;+ } catch (exc) {+ return {+ name: "code_graph",+ ok: false,+ message: `code project at ${project}: index directory unreadable: ${(exc as Error).message ?? exc}`,+ fix: `chmod u+rx "${indexDir}"`,+ };+ }+ if (!indexed) {return {name: "code_graph",ok: false,diff --git a/src/core/search/pipeline/assemble.ts b/src/core/search/pipeline/assemble.tsnew file mode 100644index 00000000..59be1008--- /dev/null+++ b/src/core/search/pipeline/assemble.ts@@ -0,0 +1,255 @@+/**+ * Rank and assemble: rank the fused candidate pool, then run the phases+ * that can still drop or re-order a ranked row - traversal expansion, the+ * relevance floor, diversity/relevance rerank, and the frontmatter-backed+ * filters (status, property, degree, visibility, agent, scope).+ *+ * Owns the pool width, because every one of those phases is a reason to+ * rank more rows than the caller asked for.+ */++import { statSync } from "node:fs";+import { join } from "node:path";++import { rerankByRelevance } from "../enrich.ts";+import { applyTraversal } from "../graph-phases.ts";+import { mmrRerank } from "../mmr.ts";+import { rankResults } from "../ranker.ts";+import { applyExactStateBarrier, type FrontmatterCache } from "../result-filters.ts";+import { semanticPoolSize } from "../semantic-phase.ts";+import { applyTemporalBridge } from "../temporal-bridge.ts";+import { applyPoolFilters, resolvePoolFilters, type FilterContext } from "./pool-filters.ts";+import type { CandidateSignals } from "./candidate-signals.ts";+import type { HydratedChunk, KeywordHit, SemanticHit, Store } from "../store.ts";+import type { ResolvedTimeRange } from "../time-range.ts";+import type { TemporalIntent } from "../temporal-intent.ts";+import type {+ BrainSearchResult,+ ResolvedSearchConfig,+ SearchOptions,+ SearchSessionFocus,+ StructuredRecallQueryDocument,+ WeightProfile,+} from "../types.ts";++/** Widening factors for the phases that need a pool wider than `limit`. */+const POOL_LIMIT_MULTIPLIER = 3;+const POOL_MIN_WIDTH = 30;++/** Traversal is off at zero hops; MMR is off at a lambda of 1. */+const NO_TRAVERSAL_HOPS = 0;+const MMR_OFF_LAMBDA = 1;++export interface AssemblyInput {+ readonly store: Store;+ readonly config: ResolvedSearchConfig;+ readonly opts: SearchOptions;+ readonly keywordHits: ReadonlyArray<KeywordHit>;+ readonly semanticHits: ReadonlyArray<SemanticHit>;+ readonly hydrated: ReadonlyMap<number, HydratedChunk>;+ readonly signals: CandidateSignals;+ readonly relationalRankedChunkIds: ReadonlyArray<number>;+ readonly weightProfile: WeightProfile | undefined;+ readonly sessionFocus: SearchSessionFocus | null;+ readonly semanticEnabled: boolean;+ readonly structured: StructuredRecallQueryDocument | undefined;+ readonly frontmatterCache: FrontmatterCache;+ readonly timeRange: ResolvedTimeRange | null;+ readonly temporalIntent: TemporalIntent | null;+ readonly declaredEventTimeMs: (path: string) => number | null;+ readonly limit: number;+}++interface Assembly {+ readonly preVisibility: number;+ readonly visible: ReadonlyArray<BrainSearchResult>;+ /** Whether the cap truncated the pool, as opposed to the pool running out. */+ readonly capHit: boolean;+}++export function assembleRankedResults(input: AssemblyInput): ReadonlyArray<BrainSearchResult> {+ const { config, opts, limit } = input;++ const filters = resolvePoolFilters(opts);+ const filterContext: FilterContext = {+ vault: config.vault,+ store: input.store,+ frontmatterCache: input.frontmatterCache,+ };++ // MMR and traversal both need a candidate pool wider than `limit`:+ // MMR diversifies from it, and traversal seeds expansion from it (a+ // narrow pool lets a high-parent expansion crowd a genuine but+ // lower-ranked hit out of the final window). When both are disabled+ // the pool collapses back to the historical rankLimit.+ // The structured exclusion lane drops rows after this stage, so it+ // widens the pool for the same reason a frontmatter filter does.+ const hasStructuredExclusions = (input.structured?.lex.exclude.length ?? 0) > 0;+ const mmrLambda = opts.mmrLambda ?? config.recall.mmrLambda;+ const mmrActive = mmrLambda < MMR_OFF_LAMBDA;+ // Relevance floor + rerank (Search & Recall Quality Suite). The floor+ // drops sub-threshold candidates before the diversity rerank so a+ // query with no sufficiently relevant memory returns no match; the+ // rerank re-orders the qualified set by core textual relevance. Both+ // off by default keep results byte-identical.+ const scoreFloor = opts.threshold ?? 0;+ const rerankActive = opts.rerank === true;+ // Cross-encoder rerank (retrieval-precision-quality-loop, card A): the+ // learned final reader step re-scores the top-K fused candidates. When+ // it is on, the candidate pool must be at least `top_k` wide so a+ // genuinely-relevant hit the heuristic ranker placed deep can be pulled+ // into the final window. Off by default keeps the pool byte-identical.+ const crossEncoderActive = config.rerank.enabled;+ const maxHops = opts.maxHops ?? config.recall.maxHops;+ const traversalActive = maxHops > NO_TRAVERSAL_HOPS;+ const baseRankLimit =+ filters.canDropRows || hasStructuredExclusions ? semanticPoolSize(limit) : limit;+ const rankLimit =+ mmrActive || traversalActive || crossEncoderActive+ ? Math.max(+ baseRankLimit,+ limit * POOL_LIMIT_MULTIPLIER,+ POOL_MIN_WIDTH,+ crossEncoderActive ? config.rerank.topK : 0,+ )+ : baseRankLimit;++ // Rank β traverse β diversify β property filter β visibility scope,+ // for a given candidate cap. Returns the pre-visibility count, the+ // post-visibility list, and whether the cap was actually hit (so the+ // caller can tell "the pool ran out" from "the cap truncated more").+ const assemble = (rankCap: number): Assembly => {+ let ranked = rankCandidates(input, rankCap);+ const capHit = ranked.length >= rankCap;+ // Retrieval-time staleness barrier (t_b0c9d0a3): drop any exact-state+ // lane artifact a stale/older index may still hold, before any later+ // phase can surface it. No-op (same reference) when the pool has none,+ // so a vault that never used the lane is byte-identical.+ ranked = applyExactStateBarrier(ranked).slice();+ // Link-graph traversal (v0.13.0): walk outbound links from the top+ // hits and surface related documents not already matched, scored by+ // decay. No-op when maxHops == 0. Runs before MMR so expansions are+ // subject to the same diversity pass.+ if (traversalActive && ranked.length > 0) {+ ranked = applyTraversal(input.store, ranked, {+ maxHops,+ hopDecay: config.recall.hopDecay,+ maxExpansionPerHit: config.recall.maxExpansionPerHit,+ });+ // Temporal bridge (t_c3871f0c): with an active time range,+ // traversal expansions must stay within a padded event-time+ // neighbourhood of the window - linked causes/consequences+ // bridge in with proximity-decayed scores, arbitrary old+ // neighbours do not. Event time = validity start, else mtime.+ if (input.timeRange !== null) {+ ranked = applyTemporalBridge(ranked, {+ range: input.timeRange,+ eventTimeMs: (path) => eventTimeOrMtimeMs(config.vault, path, input.declaredEventTimeMs),+ });+ }+ }+ // Relevance floor (Search & Recall Quality Suite): drop+ // sub-threshold candidates BEFORE diversity so the rerank works over+ // the qualified set only. No-op when the floor is 0.+ if (scoreFloor > 0) {+ ranked = ranked.filter((r) => r.score >= scoreFloor);+ }+ // Diversity rerank (v0.13.0). No-op when lambda >= 1 or < 2 results.+ if (mmrActive) {+ ranked = mmrRerank(ranked, { lambda: mmrLambda });+ }+ // Relevance rerank (Search & Recall Quality Suite): re-order the+ // qualified set by core textual relevance, a deeper-relevance second+ // pass. Opt-in; replaces the diversity ordering when requested.+ if (rerankActive) {+ ranked = rerankByRelevance(ranked).slice();+ }+ return { ...applyPoolFilters(ranked, filters, filterContext), capHit };+ };++ let assembled = assemble(rankLimit);+ // Default-scope visibility (no explicit filter, so no overfetch above)+ // can drop tagged pages and leave fewer than `limit` rows while more+ // untagged matches sit deeper in the candidate pool. When that happens+ // and the narrow cap was actually hit, re-assemble once at the wider+ // cap from the same in-memory candidates - no extra DB fetch. Untagged+ // vaults never drop rows, so this never fires and their results stay+ // byte-identical.+ if (+ !filters.canDropRows &&+ assembled.visible.length < limit &&+ assembled.visible.length < assembled.preVisibility &&+ assembled.capHit+ ) {+ const wideCap = Math.max(+ semanticPoolSize(limit),+ limit * POOL_LIMIT_MULTIPLIER,+ POOL_MIN_WIDTH,+ );+ if (wideCap > rankLimit) assembled = assemble(wideCap);+ }+ return assembled.visible;+}++function rankCandidates(input: AssemblyInput, rankCap: number): BrainSearchResult[] {+ const { config, opts, signals } = input;+ return rankResults(+ {+ keyword: input.keywordHits,+ semantic: input.semanticHits,+ hydrated: input.hydrated,+ inboundLinkSources: signals.inboundLinkSources,+ tagsByDoc: signals.tagsByDoc,+ ...(signals.entityMatchByChunk !== undefined+ ? { entityMatchByChunk: signals.entityMatchByChunk }+ : {}),+ ...(signals.activationByChunk !== undefined+ ? { activationByChunk: signals.activationByChunk }+ : {}),+ ...(signals.coAccessByChunk !== undefined+ ? { coAccessByChunk: signals.coAccessByChunk }+ : {}),+ ...(signals.trendByDoc !== undefined ? { trendByDoc: signals.trendByDoc } : {}),+ ...(signals.reuseRateByChunk !== undefined+ ? { reuseRateByChunk: signals.reuseRateByChunk }+ : {}),+ ...(input.relationalRankedChunkIds.length > 0+ ? { relationalRankedChunkIds: input.relationalRankedChunkIds }+ : {}),+ ...(signals.eventTimeMsByChunk !== undefined+ ? { eventTimeMsByChunk: signals.eventTimeMsByChunk }+ : {}),+ },+ {+ keywordWeight: opts.keywordWeight ?? config.keywordWeight,+ semanticWeight: opts.semanticWeight ?? config.semanticWeight,+ limit: rankCap,+ semanticEnabled: input.semanticEnabled,+ recency: {+ shape: config.recall.recencyShape,+ scale: config.recall.recencyScale,+ amplitude: config.recall.recencyAmplitude,+ },+ ...(input.weightProfile !== undefined ? { weightProfile: input.weightProfile } : {}),+ ...(input.sessionFocus !== undefined ? { sessionFocus: input.sessionFocus } : {}),+ fusionMode: config.fusionMode,+ rrfK: config.rrfK,+ temporalIntent: input.temporalIntent,+ },+ );+}++/** Declared event time, falling back to storage mtime. */+function eventTimeOrMtimeMs(+ vault: string,+ path: string,+ declaredEventTimeMs: (path: string) => number | null,+): number {+ const declared = declaredEventTimeMs(path);+ if (declared !== null) return declared;+ try {+ return statSync(join(vault, path)).mtimeMs;+ } catch {+ return Number.NEGATIVE_INFINITY;+ }+}diff --git a/src/core/search/pipeline/attribution.ts b/src/core/search/pipeline/attribution.tsnew file mode 100644index 00000000..5a79eed7--- /dev/null+++ b/src/core/search/pipeline/attribution.ts@@ -0,0 +1,103 @@+/**+ * Result decoration for the final window: the typed relations each page+ * declares, plus the reasons that explain WHY a row surfaced - learned+ * weights, structured lanes, a canonical-entity hop, a second-pass retry,+ * or the relational arm.+ *+ * Every layer is a no-op when its feature did not fire, so the default+ * path returns the rows untouched.+ */++import { learnedWeightsReason } from "../feedback.ts";+import { addStructuredReasons } from "../structured-lanes.ts";+import type { RelationalReach } from "./relational-arm.ts";+import type { LearnedWeights } from "../feedback.ts";+import type { Store } from "../store.ts";+import type { BrainSearchResult, SearchOutcome, StructuredRecallQueryDocument } from "../types.ts";++export interface DecorationInput {+ readonly store: Store;+ readonly results: ReadonlyArray<BrainSearchResult>;+ readonly structured: StructuredRecallQueryDocument | undefined;+ /** Non-null only when learned weights actually moved this ranking. */+ readonly activeLearned: LearnedWeights | null;+ /** Chunks matched through a registry-added entity form. */+ readonly canonicalMatchByChunk: ReadonlyMap<number, number> | undefined;+ readonly canonicalSourceIds: ReadonlyArray<string>;+ readonly secondPass: SearchOutcome["secondPass"];+ readonly targetedChunkIds: ReadonlySet<number>;+ readonly relationalReach: ReadonlyMap<number, RelationalReach>;+}++export function decorateFinalResults(input: DecorationInput): ReadonlyArray<BrainSearchResult> {+ // Explainability: when learned weights affected this ranking, every+ // surfaced result says so (acceptance: "search explanations show+ // when learned weights affected a result").+ const learned = input.activeLearned;+ const filtered =+ learned !== null+ ? input.results.map((r) =>+ Object.freeze({+ ...r,+ reasons: Object.freeze([...r.reasons, learnedWeightsReason(learned)]),+ }),+ )+ : input.results;++ // Typed graph semantics (v3): surface the typed relations each+ // result page declares in its frontmatter. Computed here from the+ // links table, never stored on the result row. One batched query.+ const relByDoc = input.store.typedRelationsForDocuments(filtered.map((r) => r.documentId));+ const withRelations = filtered.map((r) => {+ const rels = relByDoc.get(r.documentId);+ return rels && rels.length > 0 ? { ...r, relations: Object.freeze(rels) } : r;+ });+ const withStructuredReasons = addStructuredReasons(withRelations, input.structured);+ // Canonical-entity attribution (Memory Integrity Suite): a hit whose+ // chunk matched a registry-added form explains the alias hop. Vaults+ // without a registry never reach this branch.+ const canonicalMatchByChunk = input.canonicalMatchByChunk;+ const withCanonicalReasons =+ canonicalMatchByChunk !== undefined+ ? withStructuredReasons.map((r) =>+ (canonicalMatchByChunk.get(r.chunkId) ?? 0) > 0+ ? Object.freeze({+ ...r,+ reasons: Object.freeze([+ ...r.reasons,+ `entity_canonical: ${input.canonicalSourceIds.join(", ")}`,+ ]),+ })+ : r,+ )+ : withStructuredReasons;+ // Two-pass attribution (t_ef92dfdc; targeted retry t_8eb5ca32): a+ // surfaced result of a retry says so - the operator can tell+ // recovered evidence from a first-pass hit. The broadened retry+ // replaced the whole pool, so every result is recovered; the+ // targeted retry only ADDED candidates, so only those (tracked in+ // `targetedChunkIds`) carry the reason - the first-pass hits they+ // merge with do not.+ const secondPass = input.secondPass;+ const withSecondPassReasons =+ secondPass === undefined+ ? withCanonicalReasons+ : withCanonicalReasons.map((r) => {+ if (secondPass.kind === "targeted" && !input.targetedChunkIds.has(r.chunkId)) return r;+ const reason =+ secondPass.kind === "targeted"+ ? "second_pass: targeted retry on uncovered rare terms"+ : "second_pass: or-broadened retry";+ return Object.freeze({ ...r, reasons: Object.freeze([...r.reasons, reason]) });+ });+ // Relational-arm attribution (t_09b7ccea): a node surfaced by the+ // typed-edge fan-out carries a reason naming the link types and hop+ // distance it was reached by. An empty reach map (arm off) is a no-op.+ if (input.relationalReach.size === 0) return withSecondPassReasons;+ return withSecondPassReasons.map((r) => {+ const reach = input.relationalReach.get(r.chunkId);+ if (reach === undefined) return r;+ const reason = `relational: via ${reach.via.join(", ")} (${reach.hops} hop${reach.hops === 1 ? "" : "s"})`;+ return Object.freeze({ ...r, reasons: Object.freeze([...r.reasons, reason]) });+ });+}diff --git a/src/core/search/pipeline/cache-slot.ts b/src/core/search/pipeline/cache-slot.tsnew file mode 100644index 00000000..9d732c52--- /dev/null+++ b/src/core/search/pipeline/cache-slot.ts@@ -0,0 +1,184 @@+/**+ * Persistent query-cache slot: which queries may be cached, what the row+ * is keyed by, and how a computed outcome is written back.+ *+ * The key composition is a compatibility surface: every previously cached+ * row was written under it, so any change to the fingerprint fields, their+ * order, or the suffix layout silently orphans the existing cache.+ */++import { canonicalSourceSetKey } from "../../scope-key.ts";+import { activationStateFingerprint } from "../activation/store.ts";+import { learnedWeightsFingerprint } from "../feedback.ts";+import { buildCacheKey, getCachedOutcome, putCachedOutcome } from "../query-cache.ts";+import { reinforceFingerprint } from "../reinforce.ts";+import type { Store } from "../store.ts";+import type { SemanticPolicy } from "../semantic-phase.ts";+import type { TemporalIntent } from "../temporal-intent.ts";+import type { ResolvedTimeRange } from "../time-range.ts";+import type {+ ResolvedSearchConfig,+ SearchOptions,+ SearchOutcome,+ SearchSessionFocus,+ TunedParameters,+} from "../types.ts";++const MILLISECONDS_PER_SECOND = 1000;++/** Fingerprint placeholder for a state source the query did not consult. */+const FINGERPRINT_OFF = "off";++/**+ * A compact fingerprint of the resolved-config fields that change search+ * results, folded into the cache key so a config change (weights,+ * semantic toggle, recall tunables) invalidates cached rows alongside the+ * corpus generation. Cache-only knobs (enable/TTL) are excluded - they do+ * not change result content.+ */+function configFingerprint(config: ResolvedSearchConfig): string {+ const r = config.recall;+ return JSON.stringify({+ kw: config.keywordWeight,+ sw: config.semanticWeight,+ sem: config.semantic.enabled,+ mmr: r.mmrLambda,+ hops: r.maxHops,+ hopDecay: r.hopDecay,+ maxExp: r.maxExpansionPerHit,+ rShape: r.recencyShape,+ rScale: r.recencyScale,+ rAmp: r.recencyAmplitude,+ intent: r.intentEnabled,+ syn: r.synonymEnabled,+ synMax: r.synonymMaxTerms,+ relPol: r.relationPolarityEnabled,+ relArm: r.relationalArmEnabled,+ trustGate: r.retrievalTrustGateEnabled,+ supFade: r.supersedeFadeEnabled,+ lw: r.learnedWeightsEnabled,+ // Cross-encoder rerank re-orders the cached outcome, so a toggle or+ // knob change must invalidate cached rows (the endpoint identity is+ // omitted - a key rotation on the same model does not change ordering+ // semantics, and secrets never belong in a cache key).+ rrk: config.rerank.enabled,+ rrkModel: config.rerank.model,+ rrkTopK: config.rerank.topK,+ rrkMin: config.rerank.minScore,+ // Trigram prefilter augments the candidate pool, so a toggle or+ // selectivity change must invalidate cached rows.+ tri: r.trigramPrefilterEnabled,+ triMin: r.trigramPrefilterMinChunks,+ triSel: r.trigramPrefilterMaxSelectivity,+ });+}++/**+ * Whether this query may be served from - and written to - the cache.+ * A time-filtered query is excluded: a relative range ("24h") resolves to+ * a different absolute window on every call, so a cached row would serve a+ * stale window within the TTL. A window the QUERY declared (`since:24h`)+ * is the same hazard from the other direction: its resolved signature is+ * in the plan hash, so every call keys differently, never hits, and writes+ * one more row that can never be served. Both forms are excluded by the+ * one condition.+ */+export function isCacheEligible(+ config: ResolvedSearchConfig,+ timeRange: ResolvedTimeRange | null,+ temporalIntent: TemporalIntent | null,+): boolean {+ return config.recall.cacheEnabled && timeRange === null && temporalIntent === null;+}++export interface CacheSlot {+ readonly key: string;+ readonly generation: string;+ readonly ttlMs: number;+}++export interface CacheProbe {+ /** Null when the cache could not be reached; nothing is written back. */+ readonly slot: CacheSlot | null;+ readonly hit: SearchOutcome | null;+}++export interface CacheProbeInput {+ readonly store: Store;+ readonly config: ResolvedSearchConfig;+ readonly opts: SearchOptions;+ readonly limit: number;+ readonly policy: SemanticPolicy;+ readonly sessionFocus: SearchSessionFocus | null;+ readonly tuned: TunedParameters | null;+ readonly planHash: string;+}++/**+ * Look the query up in the persistent cache (v0.20.0). Keyed by the+ * request + base plan hash + a config fingerprint, gated by the corpus+ * generation and a TTL. Expansion terms are not in the key: they are+ * determined by (query, index content) and any content change bumps the+ * generation.+ *+ * The whole lookup is best-effort: any failure (e.g. a SQLITE_BUSY past+ * the busy_timeout under a concurrent reindex) yields an empty probe and+ * a fresh compute rather than breaking the search.+ */+export function probeQueryCache(input: CacheProbeInput): CacheProbe {+ const { store, config, opts, limit, policy, sessionFocus, tuned, planHash } = input;+ const ttlMs = config.recall.cacheTtlSeconds * MILLISECONDS_PER_SECOND;+ try {+ const generation = store.corpusGeneration();+ // Key on the EFFECTIVE request (clamped limit, resolved semantic+ // decision) so equivalent calls share a cache entry.+ const keyOpts = {+ ...opts,+ limit,+ semantic: policy.wantSemantic,+ keywordOnly: false,+ sessionFocus,+ };+ // The learned-weights state changes results outside the static+ // config, so its fingerprint joins the key (recall-trust-suite).+ const lwFp = config.recall.learnedWeightsEnabled+ ? learnedWeightsFingerprint(config.vault)+ : FINGERPRINT_OFF;+ // The activation state evolves with recorded accesses the same+ // way, so its fingerprint joins too (Time-Aware Recall Suite).+ const actFp = config.recall.activationEnabled+ ? activationStateFingerprint(config.vault)+ : FINGERPRINT_OFF;+ const tuneFp = tuned !== null ? JSON.stringify(tuned) : FINGERPRINT_OFF;+ // The reinforce ledger changes results only when the caller opted+ // in (Search & Recall Quality Suite); its fingerprint joins the+ // key just for those calls so an unrelated ledger write never+ // invalidates ordinary searches.+ const reinfFp =+ opts.reinforce !== undefined ? reinforceFingerprint(config.vault) : FINGERPRINT_OFF;+ // Federation hardening (t_09b7ccea): the query cache scopes by the+ // canonical source-set key, so a cache row is never served for a+ // different set of origins. Single-vault search draws from one+ // origin (this vault).+ const srcSet = canonicalSourceSetKey([config.vault]);+ const key = buildCacheKey(+ keyOpts,+ planHash,+ `${configFingerprint(config)}|lw:${lwFp}|act:${actFp}|tune:${tuneFp}|reinf:${reinfFp}|src:${srcSet}`,+ );+ const hit = getCachedOutcome(store, key, generation, ttlMs, Date.now());+ return { slot: { key, generation, ttlMs }, hit };+ } catch {+ return { slot: null, hit: null };+ }+}++/** Write the computed outcome back. Best-effort: never fails a search. */+export function persistCachedOutcome(store: Store, slot: CacheSlot, outcome: SearchOutcome): void {+ try {+ store.queryCacheSweep(slot.generation, Date.now() - slot.ttlMs);+ putCachedOutcome(store, slot.key, slot.generation, outcome, Date.now());+ } catch {+ // Cache persistence is best-effort; never fail a search on it.+ }+}diff --git a/src/core/search/pipeline/candidate-signals.ts b/src/core/search/pipeline/candidate-signals.tsnew file mode 100644index 00000000..97c6bb48--- /dev/null+++ b/src/core/search/pipeline/candidate-signals.ts@@ -0,0 +1,274 @@+/**+ * Per-candidate ranking signals: everything the ranker needs about the+ * candidate set beyond the two lanes' own scores - link sources, tags,+ * entity overlap, access-reinforced activation and its co-access+ * companions, freshness trend, observed reuse, and declared event time.+ *+ * Every map here is OMITTED when it would be empty, so a vault that+ * carries none of these signals ranks bit-identically.+ */++import { parseFreshnessTrend } from "../../brain/temporal/freshness-trend.ts";+import { observedReuseRates } from "../../brain/observed-use.ts";+import { effectiveActivation, halfLifeDays, resolveActivationKind } from "../activation/decay.ts";+import { CO_ACCESS_MIN_COUNT, readActivationState } from "../activation/store.ts";+import type { ActivationPathState, CoAccessPair } from "../activation/types.ts";+import { extractEntities } from "../entities.ts";+import { expandQueryEntities } from "../entity-alias.ts";+import { readCachedFrontmatter, type FrontmatterCache } from "../result-filters.ts";+import type { HydratedChunk, Store } from "../store.ts";+import type { ResolvedSearchConfig } from "../types.ts";++const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000;++/** The freshness-trend stamp is a preference-lifecycle field, not a generic page property. */+const FRESHNESS_TREND_PATH_PREFIX = "Brain/preferences/";++export interface CandidateSignalsInput {+ readonly store: Store;+ readonly config: ResolvedSearchConfig;+ readonly ids: ReadonlyArray<number>;+ readonly hydrated: ReadonlyMap<number, HydratedChunk>;+ /** Residual query text, for entity extraction. */+ readonly query: string;+ readonly frontmatterCache: FrontmatterCache;+ /** Present only when the query declares a temporal window. */+ readonly temporalIntentActive: boolean;+ readonly declaredEventTimeMs: (path: string) => number | null;+}++export interface CandidateSignals {+ readonly inboundLinkSources: ReadonlyMap<number, ReadonlySet<number>>;+ readonly tagsByDoc: ReadonlyMap<number, ReadonlySet<string>>;+ readonly entityMatchByChunk: ReadonlyMap<number, number> | undefined;+ /** Chunks matching a registry-ADDED form, for canonical-hop attribution. */+ readonly canonicalMatchByChunk: ReadonlyMap<number, number> | undefined;+ /** Canonical entity ids the expansion hopped through. */+ readonly canonicalSourceIds: ReadonlyArray<string>;+ readonly activationByChunk: ReadonlyMap<number, number> | undefined;+ readonly coAccessByChunk: ReadonlyMap<number, ReadonlyMap<number, number>> | undefined;+ readonly trendByDoc: ReadonlyMap<number, string> | undefined;+ readonly reuseRateByChunk: ReadonlyMap<number, number> | undefined;+ readonly eventTimeMsByChunk: ReadonlyMap<number, number> | undefined;+}++export function collectCandidateSignals(input: CandidateSignalsInput): CandidateSignals {+ const { store, config, ids } = input;+ const inboundLinkSources = store.inboundLinkSources(ids);+ const tagsByDoc = store.tagsByChunkDocument(ids);++ // Entity-boosted retrieval (v0.13.0): extract entities from the+ // query and count overlaps with each candidate chunk. Empty when the+ // query names no entities or the index predates the entity store.+ // The canonical entity registry (Memory Integrity Suite) expands the+ // set so a query naming an alias also matches chunks naming the+ // canonical entity; identity expansion (no registry) keeps ranking+ // bit-identical to pre-registry behaviour.+ const queryEntities = extractEntities(input.query);+ const entityExpansion = expandQueryEntities(config.vault, queryEntities);+ const entityMatchByChunk =+ entityExpansion.expanded.length > 0+ ? store.chunkEntityMatches(ids, entityExpansion.expanded)+ : undefined;+ const canonicalMatchByChunk =+ entityExpansion.added.length > 0+ ? store.chunkEntityMatches(ids, entityExpansion.added)+ : undefined;++ const activation = config.recall.activationEnabled+ ? collectActivationSignals(input)+ : { activationByChunk: undefined, coAccessByChunk: undefined };++ return {+ inboundLinkSources,+ tagsByDoc,+ entityMatchByChunk,+ canonicalMatchByChunk,+ canonicalSourceIds: entityExpansion.sourceIds,+ activationByChunk: activation.activationByChunk,+ coAccessByChunk: activation.coAccessByChunk,+ trendByDoc: collectFreshnessTrend(input),+ reuseRateByChunk: collectReuseRates(input),+ eventTimeMsByChunk: input.temporalIntentActive ? collectDeclaredEventTimes(input) : undefined,+ };+}++/**+ * The two signals derived from one read of the activation state: the+ * decayed per-chunk strength and the co-access companions.+ */+function collectActivationSignals(input: CandidateSignalsInput): {+ activationByChunk: ReadonlyMap<number, number> | undefined;+ coAccessByChunk: ReadonlyMap<number, ReadonlyMap<number, number>> | undefined;+} {+ const activationState = readActivationState(input.config.vault);+ if (activationState === null) {+ return { activationByChunk: undefined, coAccessByChunk: undefined };+ }+ return {+ activationByChunk:+ Object.keys(activationState.paths).length > 0+ ? decayedActivationByChunk(input, activationState.paths)+ : undefined,+ coAccessByChunk:+ activationState.coAccess.length > 0+ ? coAccessCompanions(input, activationState.coAccess)+ : undefined,+ };+}++/**+ * Access-reinforced activation (Time-Aware Recall & Activation Suite):+ * map the derived activation state onto the candidate set.+ * O(candidates): one state read per query, one frontmatter read per+ * candidate path that actually carries activation. The type half-life+ * decays the stored strength at read time, so a vault without recorded+ * events contributes nothing and ranks bit-identically.+ */+function decayedActivationByChunk(+ input: CandidateSignalsInput,+ paths: Readonly<Record<string, ActivationPathState>>,+): ReadonlyMap<number, number> | undefined {+ const { config, ids, hydrated, frontmatterCache } = input;+ const nowActivationMs = Date.now();+ const kindCache = new Map<string, string>();+ const kindFor = (path: string): string => {+ const cached = kindCache.get(path);+ if (cached !== undefined) return cached;+ let fmKind: string | null = null;+ try {+ const meta = readCachedFrontmatter(frontmatterCache, config.vault, path);+ const raw = (meta as Record<string, unknown>)["kind"];+ fmKind = typeof raw === "string" ? raw : null;+ } catch {+ fmKind = null;+ }+ const kind = resolveActivationKind(fmKind, path);+ kindCache.set(path, kind);+ return kind;+ };+ const byChunk = new Map<number, number>();+ for (const chunkId of ids) {+ const h = hydrated.get(chunkId);+ if (h === undefined) continue;+ const row = paths[h.path];+ if (row === undefined) continue;+ const days = (nowActivationMs - row.lastAccessAt) / MILLISECONDS_PER_DAY;+ const act = effectiveActivation(row.strength, days, halfLifeDays(kindFor(h.path)));+ if (act > 0) byChunk.set(chunkId, act);+ }+ return byChunk.size > 0 ? byChunk : undefined;+}++/**+ * Co-access companions (t_c5ef25a3): restrict the recorded pairs to+ * documents present in this candidate set, then hand each chunk its+ * companion documentIds with pair counts. Pairs seen fewer than+ * CO_ACCESS_MIN_COUNT times are noise and skipped.+ */+function coAccessCompanions(+ input: CandidateSignalsInput,+ pairs: ReadonlyArray<CoAccessPair>,+): ReadonlyMap<number, ReadonlyMap<number, number>> | undefined {+ const { ids, hydrated } = input;+ const docIdByPath = new Map<string, number>();+ const chunksByDocId = new Map<number, number[]>();+ for (const chunkId of ids) {+ const h = hydrated.get(chunkId);+ if (h === undefined) continue;+ docIdByPath.set(h.path, h.documentId);+ const list = chunksByDocId.get(h.documentId) ?? [];+ list.push(chunkId);+ chunksByDocId.set(h.documentId, list);+ }+ const companionsByChunk = new Map<number, Map<number, number>>();+ const addCompanion = (ownDoc: number, otherDoc: number, count: number): void => {+ for (const chunkId of chunksByDocId.get(ownDoc) ?? []) {+ const m = companionsByChunk.get(chunkId) ?? new Map<number, number>();+ m.set(otherDoc, Math.max(m.get(otherDoc) ?? 0, count));+ companionsByChunk.set(chunkId, m);+ }+ };+ for (const pair of pairs) {+ if (pair.count < CO_ACCESS_MIN_COUNT) continue;+ const docA = docIdByPath.get(pair.a);+ const docB = docIdByPath.get(pair.b);+ if (docA === undefined || docB === undefined) continue;+ addCompanion(docA, docB, pair.count);+ addCompanion(docB, docA, pair.count);+ }+ return companionsByChunk.size > 0 ? companionsByChunk : undefined;+}++/**+ * Freshness-trend bias (t_ee09a6ce): preference pages stamped with a+ * `freshness_trend` by the dream refresh get a bounded relevance+ * multiplier. O(candidate preference pages) frontmatter reads.+ *+ * Cache note: like the tier signal, the stamp is read from frontmatter at+ * query time and is NOT part of the query-cache key; a dream re-stamp+ * reaches cached queries on the next reindex (the content change bumps the+ * corpus generation).+ */+function collectFreshnessTrend(+ input: CandidateSignalsInput,+): ReadonlyMap<number, string> | undefined {+ const { config, ids, hydrated, frontmatterCache } = input;+ const byDoc = new Map<number, string>();+ const seenDocs = new Set<number>();+ for (const chunkId of ids) {+ const h = hydrated.get(chunkId);+ if (h === undefined || seenDocs.has(h.documentId)) continue;+ seenDocs.add(h.documentId);+ if (!h.path.startsWith(FRESHNESS_TREND_PATH_PREFIX)) continue;+ try {+ const meta = readCachedFrontmatter(frontmatterCache, config.vault, h.path);+ const trend = parseFreshnessTrend((meta as Record<string, unknown>)["freshness_trend"]);+ if (trend !== null) byDoc.set(h.documentId, trend);+ } catch {+ // Unreadable frontmatter stays neutral.+ }+ }+ return byDoc.size > 0 ? byDoc : undefined;+}++/**+ * Observed-reuse boost (t_65588d8b): fold the session-end USED/IGNORED/+ * CONTRADICTED verdicts into a per-document reuse score and map it onto+ * each candidate chunk. Keyed by path (else id) to match how verdicts+ * are recorded. Empty (byte-identical) when no verdicts exist.+ */+function collectReuseRates(input: CandidateSignalsInput): ReadonlyMap<number, number> | undefined {+ const { config, ids, hydrated } = input;+ const reuse = observedReuseRates(config.vault);+ if (reuse.size === 0) return undefined;+ const byChunk = new Map<number, number>();+ for (const chunkId of ids) {+ const h = hydrated.get(chunkId);+ if (h === undefined) continue;+ const entry = reuse.get(h.path) ?? reuse.get(`${h.documentId}:${chunkId}`);+ if (entry !== undefined && entry.score > 0) byChunk.set(chunkId, entry.score);+ }+ return byChunk.size > 0 ? byChunk : undefined;+}++/**+ * Query-side temporal intent (t_58fc4720): hand the ranker the DECLARED+ * event time of every candidate that states one, so the temporal layer+ * judges a note by when it is about rather than by when it was last+ * written. Candidates with no declaration are omitted and the ranker falls+ * back to their mtime.+ */+function collectDeclaredEventTimes(+ input: CandidateSignalsInput,+): ReadonlyMap<number, number> | undefined {+ const { ids, hydrated, declaredEventTimeMs } = input;+ const byChunk = new Map<number, number>();+ for (const chunkId of ids) {+ const h = hydrated.get(chunkId);+ if (h === undefined) continue;+ const declared = declaredEventTimeMs(h.path);+ if (declared !== null) byChunk.set(chunkId, declared);+ }+ return byChunk.size > 0 ? byChunk : undefined;+}diff --git a/src/core/search/pipeline/event-time.ts b/src/core/search/pipeline/event-time.tsnew file mode 100644index 00000000..e4b45bec--- /dev/null+++ b/src/core/search/pipeline/event-time.ts@@ -0,0 +1,91 @@+/**+ * Event-time discipline for one query (t_b7191486): the single definition+ * of "event time, storage time only as fallback" shared by the hard time+ * filter, the targeted-retry coverage gate, the temporal bridge and the+ * query-side temporal layer - plus the hard filter itself.+ *+ * A document declaring `valid_from` / `valid_until` is judged by+ * validity-window OVERLAP; storage mtime is the fallback, never the+ * authority, when explicit event time exists.+ */++import { readCachedFrontmatter, type FrontmatterCache } from "../result-filters.ts";+import { eventTimeInRange, parseValidityWindow, type ValidityWindow } from "../validity.ts";+import type { HydratedChunk, KeywordHit, SemanticHit } from "../store.ts";+import type { ResolvedTimeRange } from "../time-range.ts";++export interface EventTimeResolver {+ /** The declared validity window of a path, cached per path. */+ readonly validityWindowFor: (path: string) => ValidityWindow | null;+ /**+ * Declared EVENT time for a path (unix ms), or null when the page+ * declares none: validity start, else validity end.+ */+ readonly declaredEventTimeMs: (path: string) => number | null;+}++export function createEventTimeResolver(+ vault: string,+ frontmatterCache: FrontmatterCache,+): EventTimeResolver {+ const windowCache = new Map<string, ValidityWindow | null>();+ const validityWindowFor = (path: string): ValidityWindow | null => {+ if (windowCache.has(path)) return windowCache.get(path) ?? null;+ let window: ValidityWindow | null = null;+ try {+ const meta = readCachedFrontmatter(frontmatterCache, vault, path);+ window = parseValidityWindow(meta as Record<string, unknown>);+ } catch {+ window = null;+ }+ windowCache.set(path, window);+ return window;+ };+ const declaredEventTimeMs = (path: string): number | null => {+ const window = validityWindowFor(path);+ if (window === null || window.invalid) return null;+ return window.validFromMs ?? window.validUntilMs;+ };+ return { validityWindowFor, declaredEventTimeMs };+}++export interface RangeFilterInput {+ readonly hydrated: ReadonlyMap<number, HydratedChunk>;+ readonly keywordHits: KeywordHit[];+ readonly semanticHits: SemanticHit[];+ readonly timeRange: ResolvedTimeRange;+ readonly validityWindowFor: (path: string) => ValidityWindow | null;+}++export interface RangeFilterOutcome {+ readonly keywordHits: KeywordHit[];+ readonly semanticHits: SemanticHit[];+ readonly warnings: string[];+}++/**+ * Time-aware recall (recall-trust-suite): drop out-of-range candidates+ * BEFORE ranking so every later phase (traversal seeds, MMR, relation+ * polarity) sees only in-range candidates. An unparseable declared value+ * warns once per path and falls back to mtime.+ */+export function filterCandidatesInRange(input: RangeFilterInput): RangeFilterOutcome {+ const { hydrated, timeRange, validityWindowFor } = input;+ const warnings: string[] = [];+ const warnedInvalid = new Set<string>();+ const inRange = (chunkId: number): boolean => {+ const h = hydrated.get(chunkId);+ if (h === undefined) return false;+ const window = validityWindowFor(h.path);+ if (window?.invalid === true && !warnedInvalid.has(h.path)) {+ warnedInvalid.add(h.path);+ warnings.push(`validity: unparseable valid_from/valid_until in ${h.path}; using mtime`);+ }+ return eventTimeInRange(window, h.mtime, timeRange);+ };+ return {+ keywordHits: input.keywordHits.filter((h) => inRange(h.chunkId)),+ semanticHits: input.semanticHits.filter((h) => inRange(h.chunkId)),+ warnings,+ };+}diff --git a/src/core/search/pipeline/keyword-lane.ts b/src/core/search/pipeline/keyword-lane.tsnew file mode 100644index 00000000..4208aa60--- /dev/null+++ b/src/core/search/pipeline/keyword-lane.ts@@ -0,0 +1,151 @@+/**+ * Keyword candidate lane: the FTS pass, the opt-in synonym re-run that+ * broadens it, and the opt-in trigram prefilter that merges substring+ * matches the word tokenizer missed. Owns the query plan, because the+ * synonym step is what folds derived terms into it.+ */++import { runFtsQueryDetailed } from "../fts.ts";+import { buildQueryPlan } from "../query-plan.ts";+import { DEFAULT_EXPANSION, deriveExpansionTerms, tokenizeForExpansion } from "../synonyms.ts";+import { isLowSelectivity, planTrigramPrefilter } from "../trigram-prefilter.ts";+import type { KeywordHit, Store } from "../store.ts";+import type { TemporalIntent } from "../temporal-intent.ts";+import type { QueryIntent, QueryPlan } from "../types.ts";++/** Top candidates whose own content seeds the synonym derivation. */+const SYNONYM_SEED_HITS = 10;++export interface KeywordLaneInput {+ readonly store: Store;+ readonly recall: {+ readonly poolMultiplier: number;+ readonly synonymEnabled: boolean;+ readonly synonymMaxTerms: number;+ readonly trigramPrefilterEnabled: boolean;+ readonly trigramPrefilterMinChunks: number;+ readonly trigramPrefilterMaxSelectivity: number;+ };+ /** Residual query text, for the term derivations that read prose. */+ readonly query: string;+ /** The lane's FTS query (structured lex lane, else the residual text). */+ readonly keywordQuery: string;+ readonly structuredIntent: QueryIntent | null | undefined;+ readonly surfaceVocabulary: ReadonlySet<string>;+ readonly nowMs: number;+ readonly temporalIntent: TemporalIntent | null;+ readonly basePlan: QueryPlan;+ readonly limit: number;+ readonly pathPrefix: string | undefined;+}++export interface KeywordLaneOutcome {+ /** Mutable: later stages merge retry candidates into this pool. */+ readonly hits: KeywordHit[];+ /** The base plan, or a re-plan carrying the derived expansion terms. */+ readonly plan: QueryPlan;+ readonly warnings: string[];+}++export function runKeywordLane(input: KeywordLaneInput): KeywordLaneOutcome {+ const { store, recall, keywordQuery, limit, pathPrefix } = input;+ const warnings: string[] = [];++ const kwOutcome = runFtsQueryDetailed(store, keywordQuery, {+ limit: limit * recall.poolMultiplier,+ pathPrefix,+ });+ let hits = kwOutcome.hits;+ for (const w of kwOutcome.warnings) warnings.push(w);++ // Synonym / query expansion (v0.20.0): opt-in and never for an+ // exact-intent (quoted/wildcard) query. Derive related terms from+ // the top candidates' own content (local co-occurrence) and re-run+ // FTS with them OR'd onto the original query to broaden recall. A+ // no-op - byte-identical hits - when disabled or no term qualifies.+ let plan = input.basePlan;+ if (recall.synonymEnabled && input.basePlan.intent !== "exact" && hits.length > 0) {+ const expanded = expandWithSynonyms(input, hits);+ if (expanded !== null) {+ plan = expanded.plan;+ hits = expanded.hits;+ for (const w of expanded.warnings) warnings.push(w);+ }+ }++ // Trigram candidate source (t_4a672b84): opt-in. On large vaults, merge+ // substring / partial-token matches the word tokenizer missed into the+ // keyword candidate pool. A strict superset of substring matches, so it+ // only ADDS candidates (deduped by chunkId; existing keyword hits keep+ // their bm25). Skipped for short/CJK/low-selectivity queries and when+ // disabled - leaving hits byte-identical.+ if (recall.trigramPrefilterEnabled && store.chunkCount() >= recall.trigramPrefilterMinChunks) {+ mergeTrigramCandidates(input, hits, warnings);+ }++ return { hits, plan, warnings };+}++/**+ * Re-plan and re-run the lane with terms derived from the top candidates'+ * own content. Null when no term qualified, leaving the first pass intact.+ */+function expandWithSynonyms(+ input: KeywordLaneInput,+ hits: KeywordHit[],+): { plan: QueryPlan; hits: KeywordHit[]; warnings: ReadonlyArray<string> } | null {+ const { store, recall, query, keywordQuery, limit, pathPrefix } = input;+ const topIds = hits.slice(0, SYNONYM_SEED_HITS).map((h) => h.chunkId);+ const ctx = store.hydrateChunks(topIds);+ const texts = topIds.map((id) => ctx.get(id)?.content ?? "").filter((t) => t.length > 0);+ const expandedTerms = deriveExpansionTerms(tokenizeForExpansion(query), texts, {+ ...DEFAULT_EXPANSION,+ maxTerms: recall.synonymMaxTerms,+ });+ if (expandedTerms.length === 0) return null;+ const plan = buildQueryPlan(+ keywordQuery,+ expandedTerms,+ input.structuredIntent,+ input.surfaceVocabulary,+ input.nowMs,+ input.temporalIntent,+ );+ const kwOutcome = runFtsQueryDetailed(store, keywordQuery, {+ limit: limit * recall.poolMultiplier,+ pathPrefix,+ expandedTerms,+ });+ return { plan, hits: kwOutcome.hits, warnings: kwOutcome.warnings };+}++/**+ * Append the trigram candidates the keyword pool does not already hold.+ * The lane only broadens the pool, so a fault in it degrades this step+ * (no candidates, one warning) rather than failing the search.+ */+function mergeTrigramCandidates(+ input: KeywordLaneInput,+ hits: KeywordHit[],+ warnings: string[],+): void {+ const { store, recall, query, limit, pathPrefix } = input;+ const trigramPlan = planTrigramPrefilter(query);+ if (trigramPlan.mode !== "match") return;+ const corpus = store.chunkCount();+ const outcome = store.trigramCandidates(trigramPlan.ftsQuery, {+ limit: limit * recall.poolMultiplier,+ pathPrefix,+ });+ for (const w of outcome.warnings) warnings.push(w);+ const cand = outcome.hits;+ if (cand.length === 0) return;+ if (isLowSelectivity(cand.length, corpus, recall.trigramPrefilterMaxSelectivity)) return;+ const seen = new Set(hits.map((h) => h.chunkId));+ for (const h of cand) {+ if (!seen.has(h.chunkId)) {+ hits.push(h);+ seen.add(h.chunkId);+ }+ }+}diff --git a/src/core/search/pipeline/outcome.ts b/src/core/search/pipeline/outcome.tsnew file mode 100644index 00000000..141aa35a--- /dev/null+++ b/src/core/search/pipeline/outcome.ts@@ -0,0 +1,160 @@+/**+ * Outcome assembly: the evidence pack and its terminal-state downrank,+ * the opt-in access recording, the opt-in trust metadata, and the two+ * surfaced shapes (full rows or progressive-disclosure cards).+ *+ * The only place a `SearchOutcome` is constructed, so the optional fields+ * are omitted from exactly one set of rules.+ */++import { ACCESS_EVENT_PATHS_CAP, recordAccessEvent } from "../activation/store.ts";+import { toSearchCard } from "../cards.ts";+import { buildEvidencePack, downrankTerminalEvidenceResults } from "../evidence-pack.ts";+import { buildEvidenceVerification } from "../evidence-verification.ts";+import { fnv1aHex } from "../feedback.ts";+import {+ attachTrustMetadata,+ buildTerminalPaths,+ type FrontmatterCache,+} from "../result-filters.ts";+import type { TrustReceipts } from "./post-rank.ts";+import type { Store } from "../store.ts";+import type {+ BrainSearchResult,+ QuerySurface,+ ResolvedSearchConfig,+ SearchOptions,+ SearchOutcome,+} from "../types.ts";++const NO_RESULTS: ReadonlyArray<BrainSearchResult> = Object.freeze([]);++export interface EmptyOutcomeInput {+ readonly store: Store;+ readonly opts: SearchOptions;+ /** Residual query text. */+ readonly query: string;+ readonly pathPrefix: string | undefined;+ readonly warnings: ReadonlyArray<string>;+ readonly routedSurface: QuerySurface;+}++/** The zero-candidate outcome: no pool to rank, filter or attribute. */+export function emptyOutcome(input: EmptyOutcomeInput): SearchOutcome {+ const evidencePack =+ input.opts.evidencePack === true+ ? buildEvidencePack(+ input.query,+ [],+ buildEvidenceVerification(input.store, input.query, [], input.pathPrefix),+ )+ : undefined;+ return Object.freeze({+ results: NO_RESULTS,+ warnings: Object.freeze(input.warnings),+ total: 0,+ ...(evidencePack !== undefined ? { evidencePack } : {}),+ ...(input.routedSurface === "summary" ? { surface: input.routedSurface } : {}),+ });+}++export interface OutcomeInput {+ readonly store: Store;+ readonly config: ResolvedSearchConfig;+ readonly opts: SearchOptions;+ /** Residual query text. */+ readonly query: string;+ readonly pathPrefix: string | undefined;+ readonly results: ReadonlyArray<BrainSearchResult>;+ /** Mutable: access recording appends its own failure warning. */+ readonly warnings: string[];+ readonly secondPass: SearchOutcome["secondPass"];+ readonly routedSurface: QuerySurface;+ readonly trustReceipts: TrustReceipts | null;+ readonly frontmatterCache: FrontmatterCache;+}++export function buildSearchOutcome(input: OutcomeInput): SearchOutcome {+ const { config, opts, query, warnings } = input;+ // Terminal-state downrank (recall-trust-suite) is structural and+ // language-agnostic: a result is terminal when its frontmatter+ // `status:` field declares a terminal value (controlled vocabulary),+ // never because the note's prose happens to contain an English word+ // like "done". One cached frontmatter read per candidate path, only+ // in evidence-pack mode.+ const wantsEvidencePack = opts.evidencePack === true;+ const terminalPaths = wantsEvidencePack+ ? buildTerminalPaths(config.vault, input.results, input.frontmatterCache)+ : new Set<string>();+ const finalResults = wantsEvidencePack+ ? downrankTerminalEvidenceResults(input.results, terminalPaths)+ : input.results;+ const evidencePack = wantsEvidencePack+ ? buildEvidencePack(+ query,+ finalResults,+ buildEvidenceVerification(input.store, query, finalResults, input.pathPrefix),+ terminalPaths,+ )+ : undefined;++ // Access recording (Time-Aware Recall & Activation Suite): the+ // orchestrator edge opted in, so persist which documents this query+ // surfaced - AFTER ranking, so the current query is never affected+ // by its own recording. Cache hits return earlier and never reach+ // this point. Best-effort: a failed write never breaks the search.+ if (opts.recordAccess === true && config.recall.activationEnabled && finalResults.length > 0) {+ const surfacedPaths = Array.from(new Set(finalResults.map((r) => r.path))).slice(+ 0,+ ACCESS_EVENT_PATHS_CAP,+ );+ const normalized = query.trim().replace(/\s+/gu, " ").toLowerCase();+ try {+ recordAccessEvent(config.vault, {+ ts: Date.now(),+ queryHash: fnv1aHex(normalized),+ paths: surfacedPaths,+ });+ } catch {+ warnings.push("activation: failed to record access event");+ }+ }++ // Inline trust metadata (Search & Recall Quality Suite): opt-in,+ // computed at read time from the document mtime and the surfaced+ // typed relations, never stored. Off by default keeps the result+ // shape byte-identical.+ const resultsOut =+ opts.trust === true ? attachTrustMetadata(config.vault, finalResults) : finalResults;++ const tail = {+ ...(evidencePack !== undefined ? { evidencePack } : {}),+ ...(input.secondPass !== undefined ? { secondPass: input.secondPass } : {}),+ ...(input.routedSurface === "summary" ? { surface: input.routedSurface } : {}),+ ...input.trustReceipts,+ };++ // Progressive disclosure (D3): layer 1. When the caller opts into+ // `cards`, project the SAME ranked rows into token-cheap cards and+ // return them on `cards` with an empty `results`. The ranking,+ // filtering, and evidence pack are computed identically to full mode -+ // only the surfaced depth differs - so the contract stays+ // deterministic and the default `full` path is byte-identical.+ if ((opts.disclosure ?? "full") === "cards") {+ const cards = resultsOut.map(toSearchCard);+ return Object.freeze({+ results: NO_RESULTS,+ cards: Object.freeze(cards),+ warnings: Object.freeze(warnings),+ total: cards.length,+ ...tail,+ });+ }++ return Object.freeze({+ results: Object.freeze(resultsOut),+ warnings: Object.freeze(warnings),+ total: resultsOut.length,+ ...tail,+ });+}diff --git a/src/core/search/pipeline/pool-filters.ts b/src/core/search/pipeline/pool-filters.tsnew file mode 100644index 00000000..433c8382--- /dev/null+++ b/src/core/search/pipeline/pool-filters.ts@@ -0,0 +1,144 @@+/**+ * The post-rank filters that can drop a ranked row: belief status,+ * frontmatter properties, graph degree, visibility scope, agent ownership+ * and the composite session/project scope.+ *+ * Resolving them is separate from applying them, because the pool width+ * has to know up front whether ANY of them can shrink the window.+ */++import { normalizeAgentScope } from "../../graph/agent-scope.ts";+import { normalizeVisibilityScope } from "../../graph/visibility.ts";+import { normalizeScopeFilter } from "../../scope-key.ts";+import {+ applyAgentScope,+ applyDegreeFilter,+ applyPropertyFilter,+ applyScopeFilter,+ applyStatusFilter,+ applyVisibilityScope,+ type FrontmatterCache,+} from "../result-filters.ts";+import type { Store } from "../store.ts";+import type { DegreePredicate } from "../property-filter.ts";+import type { BrainSearchResult, SearchOptions } from "../types.ts";++export interface PoolFilters {+ readonly properties: ReadonlyMap<string, ReadonlyArray<string>> | null;+ readonly degreeFilters: ReadonlyArray<DegreePredicate>;+ readonly visibilityScope: ReturnType<typeof normalizeVisibilityScope>;+ readonly agentScope: ReturnType<typeof normalizeAgentScope>;+ readonly scopeFilter: ReturnType<typeof normalizeScopeFilter> | null;+ /**+ * True when at least one requested filter can drop a ranked row, which+ * is what makes the candidate pool overfetch up front.+ */+ readonly canDropRows: boolean;+}++export function resolvePoolFilters(opts: SearchOptions): PoolFilters {+ // When a property filter is active, overfetch the ranked+ // candidates so the post-filter result set still has a chance+ // of producing `limit` matching rows. Without this, the+ // top-`limit` ranked hits can lose all their property-matching+ // candidates to the filter and surface zero results even when+ // matches exist deeper in the rank.+ const properties =+ opts.properties !== undefined && opts.properties.size > 0 ? opts.properties : null;+ // Graph-degree cardinality predicates (t_9bee8f0b): a post-rank filter+ // that can drop ranked rows, so it shares the frontmatter-filter+ // overfetch. Absent / empty leaves the pool and results byte-identical.+ const degreeFilters = opts.degreeFilters ?? [];+ // An explicit visibility scope can also drop ranked rows, so it+ // shares the property filter's overfetch. The default (no scope)+ // path does NOT overfetch up front - all-untagged vaults stay+ // byte-identical to prior behaviour - and instead relies on the+ // one-shot backfill in the assembly when tagged pages actually shrink+ // the window.+ const visibilityScope = normalizeVisibilityScope(opts.visibility ?? []);+ const hasVisibilityRequest = (opts.visibility?.length ?? 0) > 0;+ // Agent-ownership scope (Unit 5): null means "no scope requested" -+ // no ownership filtering, so untagged vaults stay byte-identical.+ const agentScope = normalizeAgentScope(opts.agentScope);+ // Composite scope filter (t_37c05a34): session/project axes on top of+ // owner. Null when no axis is requested, so an omitted filter never+ // narrows the pool (byte-identical default).+ const normalizedScope = opts.scope !== undefined ? normalizeScopeFilter(opts.scope) : null;+ const scopeFilter =+ normalizedScope !== null &&+ (normalizedScope.session !== null || normalizedScope.project !== null)+ ? normalizedScope+ : null;+ return {+ properties,+ degreeFilters,+ visibilityScope,+ agentScope,+ scopeFilter,+ canDropRows:+ properties !== null ||+ hasVisibilityRequest ||+ agentScope !== null ||+ scopeFilter !== null ||+ degreeFilters.length > 0,+ };+}++export interface FilterContext {+ readonly vault: string;+ readonly store: Store;+ readonly frontmatterCache: FrontmatterCache;+}++export interface FilteredPool {+ /** Row count before visibility scoping, for the backfill decision. */+ readonly preVisibility: number;+ readonly visible: ReadonlyArray<BrainSearchResult>;+}++export function applyPoolFilters(+ ranked: ReadonlyArray<BrainSearchResult>,+ filters: PoolFilters,+ ctx: FilterContext,+): FilteredPool {+ // Optional post-rank property filter (v0.10.17). Reads each+ // result's source frontmatter and drops rows whose scalars do not+ // match the requested key/value pairs, then visibility scoping (v3)+ // drops pages outside the requested visibility scope. Caching by+ // document path bounds the read cost to the result set.+ // Belief lifecycle suite (t_7d5a3589): drop tombstoned (incl.+ // superseded-non-tip) memories before any other post-rank stage.+ // A vault with no tombstoned entries passes through unchanged.+ const statusFiltered = applyStatusFilter(ranked, ctx.vault, ctx.frontmatterCache);+ const propFiltered =+ filters.properties !== null+ ? applyPropertyFilter(statusFiltered, filters.properties, ctx.vault, ctx.frontmatterCache)+ : statusFiltered;+ // Graph-degree cardinality predicates (t_9bee8f0b): drop rows whose+ // backlink/outlink counts fail the predicates, backed by the+ // link-graph degree index. No-op when no predicate was requested.+ const degreeFiltered =+ filters.degreeFilters.length > 0+ ? applyDegreeFilter(propFiltered, filters.degreeFilters, ctx.store)+ : propFiltered;+ const visible = applyVisibilityScope(+ degreeFiltered,+ filters.visibilityScope,+ ctx.vault,+ ctx.frontmatterCache,+ );+ // Agent-ownership isolation (Unit 5): only when a scope is requested;+ // a null scope skips the filter entirely (byte-identical default).+ const scoped =+ filters.agentScope !== null+ ? applyAgentScope(visible, filters.agentScope, ctx.vault, ctx.frontmatterCache)+ : visible;+ // Composite session/project scope filter (t_37c05a34): applied only+ // when an axis is requested; a null filter skips it entirely so the+ // default path is byte-identical.+ const compositeScoped =+ filters.scopeFilter !== null+ ? applyScopeFilter(scoped, filters.scopeFilter, ctx.vault, ctx.frontmatterCache)+ : scoped;+ return { preVisibility: degreeFiltered.length, visible: compositeScoped };+}diff --git a/src/core/search/pipeline/post-rank.ts b/src/core/search/pipeline/post-rank.tsnew file mode 100644index 00000000..bb4a3833--- /dev/null+++ b/src/core/search/pipeline/post-rank.ts@@ -0,0 +1,131 @@+/**+ * Post-rank pool phases: everything that still adds, removes or re-orders+ * a candidate AFTER ranking and BEFORE the final `limit` slice - so a+ * demoted row can fall out of the window and a promoted one can enter it.+ *+ * Order is the contract here: structured exclusions, relation polarity,+ * reinforce, the cross-encoder reader, then the deterministic+ * rank-adjustment sink that emits the trust receipts.+ */++import { emitGatedTelemetry } from "../../brain/continuity/emit.ts";+import {+ buildMemoryTrustAssessment,+ buildRetrievalDecisionTrace,+} from "../../brain/trust/retrieval-receipts.ts";+import { trustGateAdjuster } from "../../brain/trust/retrieval-gate.ts";+import { applyRelationPolarityPhase } from "../graph-phases.ts";+import { applyRankAdjusters, type RankAdjuster } from "../rank-adjust.ts";+import { applyReinforceBoost, loadReinforceStrengths } from "../reinforce.ts";+import { applyCrossEncoderRerank } from "../rerank/index.ts";+import {+ readCachedFrontmatter,+ supersedeFadeAdjuster,+ type FrontmatterCache,+} from "../result-filters.ts";+import { applyStructuredExclusions } from "../structured-lanes.ts";+import type { Store } from "../store.ts";+import type {+ BrainSearchResult,+ ResolvedSearchConfig,+ SearchOptions,+ StructuredRecallQueryDocument,+} from "../types.ts";++export interface PostRankInput {+ readonly store: Store;+ readonly config: ResolvedSearchConfig;+ readonly opts: SearchOptions;+ /** Residual query text, the cross-encoder's reader input. */+ readonly query: string;+ readonly pool: ReadonlyArray<BrainSearchResult>;+ readonly structured: StructuredRecallQueryDocument | undefined;+ readonly frontmatterCache: FrontmatterCache;+}++export interface TrustReceipts {+ readonly retrievalDecisionTrace: ReturnType<typeof buildRetrievalDecisionTrace>;+ readonly memoryTrustAssessment: ReturnType<typeof buildMemoryTrustAssessment>;+}++export interface PostRankOutcome {+ readonly results: ReadonlyArray<BrainSearchResult>;+ /** Null on the default path, where the outcome shape stays unchanged. */+ readonly trustReceipts: TrustReceipts | null;+ readonly warnings: string[];+}++export async function applyPostRankPhases(input: PostRankInput): Promise<PostRankOutcome> {+ const { store, config, opts, frontmatterCache } = input;+ const warnings: string[] = [];++ const excluded = applyStructuredExclusions(input.pool, input.structured);+ // Relation polarity (recall-trust-suite): typed relation edges adjust+ // the pool BEFORE the final slice so a demoted predecessor can fall+ // out of the window and a pulled-in successor can enter it. A pool+ // whose documents declare no typed edges passes through untouched.+ const polarized = config.recall.relationPolarityEnabled+ ? applyRelationPolarityPhase(store, excluded, opts.includeSuperseded === true)+ : excluded;+ // Self-tuning reinforce (Search & Recall Quality Suite): opt-in. When+ // the caller passes a reinforce set, the persisted ledger lifts+ // proven-useful memories by a bounded boost BEFORE the top_k cut, so+ // a reinforced hit can enter the window. Absent leaves the pool+ // untouched; an empty ledger is a no-op either way.+ const reinforced =+ opts.reinforce !== undefined+ ? applyReinforceBoost(polarized, loadReinforceStrengths(config.vault))+ : polarized;+ // Cross-encoder rerank (retrieval-precision-quality-loop, card A): the+ // final reader step, appended AFTER every heuristic rerank. Disabled+ // (default) returns the pool unchanged (byte-identical); enabled but+ // unconfigured throws a typed config error; enabled + a request-time+ // endpoint error degrades to the heuristic ordering and records one+ // fail-open telemetry warning. Runs over the widened pool so a deep+ // candidate can be promoted into the final `limit` window below.+ const reranked = await applyCrossEncoderRerank(reinforced, input.query, config.rerank, {+ onTelemetry: (event) =>+ emitGatedTelemetry(event.status === "error", () => {+ warnings.push(`rerank_degraded: ${event.reason ?? "endpoint error"}`);+ }),+ });+ // Kernel 1 (t_5f61130a): the deterministic rank-adjustment sink between+ // ranking and result emission, mounted on BOTH the semantic and the+ // pure-lexical paths (both flow through this single pre-slice pool).+ // Registered adjusters return a per-candidate verdict; with none+ // registered the pool is returned unchanged, so the default path is+ // byte-identical. Runs BEFORE the slice so a gate exclusion lets a+ // deeper survivor backfill the window rather than shrinking it.+ const rankAdjusters: RankAdjuster[] = [];+ if (config.recall.retrievalTrustGateEnabled) {+ rankAdjusters.push(+ trustGateAdjuster((path) => readCachedFrontmatter(frontmatterCache, config.vault, path)),+ );+ }+ if (config.recall.supersedeFadeEnabled) {+ // Relation-only supersede fade (t_c4a9cef8): fetch the pool's typed+ // relations once and fade any candidate a `superseded_by` edge marks+ // superseded, the same source of truth `attachTrustMetadata` uses.+ const poolDocIds = Array.from(new Set(reranked.map((r) => r.documentId)));+ const relByPoolDoc = store.typedRelationsForDocuments(poolDocIds);+ rankAdjusters.push(supersedeFadeAdjuster((documentId) => relByPoolDoc.get(documentId) ?? []));+ }+ const adjusted = applyRankAdjusters(reranked, rankAdjusters);+ // Per-pack retrieval trust receipts (t_5f61130a): compact references+ // consistent with the context-receipt model. Built only when the gate+ // ran, so the outcome shape stays byte-identical on the default path.+ const trustReceipts = config.recall.retrievalTrustGateEnabled+ ? {+ retrievalDecisionTrace: buildRetrievalDecisionTrace({+ surfaced: adjusted.results.length,+ excluded: adjusted.excluded,+ }),+ memoryTrustAssessment: buildMemoryTrustAssessment({+ surfaced: adjusted.results.length,+ excluded: adjusted.excluded,+ }),+ }+ : null;++ return { results: adjusted.results, trustReceipts, warnings };+}diff --git a/src/core/search/pipeline/query-shape.ts b/src/core/search/pipeline/query-shape.tsnew file mode 100644index 00000000..b45f2973--- /dev/null+++ b/src/core/search/pipeline/query-shape.ts@@ -0,0 +1,128 @@+/**+ * Query shape: how the caller's text becomes the two lane queries and the+ * structural plan they are ranked under. Resolves the structured recall+ * document (explicit or expanded), splits it into the keyword and semantic+ * lane queries, and builds the base query plan whose hash keys the cache.+ *+ * Both vocabularies consulted here are config-derived token sets - never a+ * natural-language word list.+ */++import { loadSchemaPack } from "../../brain/schema-pack.ts";+import { buildQueryPlan } from "../query-plan.ts";+import { expandQuery } from "../query-expansion.ts";+import { structuredKeywordQuery, structuredSemanticQuery } from "../structured-lanes.ts";+import { tokenizeForExpansion } from "../synonyms.ts";+import type { Store } from "../store.ts";+import type { TemporalIntent } from "../temporal-intent.ts";+import type { QueryPlan, StructuredRecallQueryDocument } from "../types.ts";++/** A token in at least this share of the corpus is treated as common. */+const COMMON_TOKEN_CORPUS_SHARE = 0.5;+/**+ * Floor on document frequency before a token can be "common". Below this+ * a corpus is too small to tell a stopword-like word from a rare one, so+ * nothing is flagged (a 2-document vault must not call a word that appears+ * once "ubiquitous").+ */+const MIN_COMMON_DOCUMENT_FREQUENCY = 2;++/**+ * Corpus-common query tokens, derived from document frequency. A token+ * present in at least {@link COMMON_TOKEN_CORPUS_SHARE} of the indexed+ * documents (and in at least {@link MIN_COMMON_DOCUMENT_FREQUENCY} of+ * them) carries little discriminating signal - in ANY language - so the+ * lex expansion lane drops it rather than letting one ubiquitous word+ * kill an implicit-AND match. Language-agnostic: no stopword list.+ *+ * Note: document frequency is measured through the FTS index, whose+ * tokenization can differ slightly from `tokenizeForExpansion`. A miss+ * only fails to flag a token as common (it stays in the lex lane), so the+ * fallback is always the safe, non-lossy direction.+ */+function highFrequencyTokens(store: Store, query: string): ReadonlySet<string> {+ const tokens = [...new Set(tokenizeForExpansion(query))];+ if (tokens.length === 0) return new Set();+ const documentCount = store.counts().documents;+ if (documentCount === 0) return new Set();+ const threshold = COMMON_TOKEN_CORPUS_SHARE * documentCount;+ const df = store.documentFrequencies(tokens);+ const common = new Set<string>();+ for (const token of tokens) {+ const freq = df.get(token) ?? 0;+ if (freq >= MIN_COMMON_DOCUMENT_FREQUENCY && freq >= threshold) common.add(token);+ }+ return common;+}++/**+ * The artifact-kind vocabulary for the summary-search router (t_7b96f242):+ * the schema pack's declared page types, already normalized. This is the+ * ONLY place artifact-kind vocabulary enters the surface router - a+ * config-derived token set, never a natural-language word list. An+ * unreadable pack yields an empty set, so the router falls back to the+ * vocabulary-independent source signal only.+ */+function summarySurfaceVocabulary(vault: string): ReadonlySet<string> {+ try {+ return new Set(loadSchemaPack(vault).vocabulary.page_types.map((t) => t.toLowerCase()));+ } catch {+ return new Set<string>();+ }+}++export interface QueryShapeInput {+ readonly store: Store;+ readonly vault: string;+ /** Residual query text (time directives already stripped). */+ readonly query: string;+ /** An explicit structured document from the caller, if any. */+ readonly structuredQuery: StructuredRecallQueryDocument | undefined;+ /** Whether opt-in local expansion runs. */+ readonly expandActive: boolean;+ readonly nowMs: number;+ readonly temporalIntent: TemporalIntent | null;+}++export interface QueryShape {+ readonly structured: StructuredRecallQueryDocument | undefined;+ readonly keywordQuery: string;+ readonly semanticLaneQuery: string | null;+ readonly surfaceVocabulary: ReadonlySet<string>;+ readonly basePlan: QueryPlan;+}++export function resolveQueryShape(input: QueryShapeInput): QueryShape {+ const { store, vault, query, structuredQuery, expandActive, nowMs, temporalIntent } = input;+ // Opt-in local expansion (t_2fa95db1): an explicit structured+ // document always wins; expansion only fills the gap. The lex lane's+ // corpus-common tokens are derived from document frequency here+ // (language-agnostic, no stopword list) so an implicit-AND query is+ // not killed by a word that is ubiquitous in this vault.+ // Expansion reads the RESIDUAL text (see the strip in request+ // resolution): a window directive is an instruction, so it must never+ // become an expansion token, and the residual is byte-identical when no+ // window was declared.+ const commonTokens =+ structuredQuery === undefined && expandActive === true+ ? highFrequencyTokens(store, query)+ : new Set<string>();+ const structured =+ structuredQuery ??+ (expandActive === true ? expandQuery(vault, query, { commonTokens }) : undefined);+ const keywordQuery = structuredKeywordQuery(query, structured);+ const semanticLaneQuery = structuredSemanticQuery(structured);+ // Query plan (v0.20.0): one structural pass yields the intent weight+ // profile and the cache key. Expanded terms (if any) are folded in+ // once they have been derived from the store by the keyword lane.+ const surfaceVocabulary = summarySurfaceVocabulary(vault);+ const basePlan = buildQueryPlan(+ keywordQuery,+ [],+ structured?.intent,+ surfaceVocabulary,+ nowMs,+ temporalIntent,+ );+ return { structured, keywordQuery, semanticLaneQuery, surfaceVocabulary, basePlan };+}diff --git a/src/core/search/pipeline/relational-arm.ts b/src/core/search/pipeline/relational-arm.tsnew file mode 100644index 00000000..d06093c4--- /dev/null+++ b/src/core/search/pipeline/relational-arm.ts@@ -0,0 +1,116 @@+/**+ * Typed-edge relational arm (t_09b7ccea): the fourth RRF arm. Resolves the+ * query's wikilink seeds, fans out over typed edges, and contributes one+ * representative chunk per reached node - with the link types and hop+ * distance it was reached by, for attribution.+ */++import { DEFAULT_RELATION_TYPES, normalizeRelation } from "../../graph/relation-vocab.ts";+import { loadSchemaPack } from "../../brain/schema-pack.ts";+import { rrfKey } from "../../scope-key.ts";+import { relationalFanout } from "../relational-fanout.ts";+import { parseRelationalQuery } from "../relational-query.ts";+import type { Store } from "../store.ts";+import type { ResolvedSearchConfig, SearchOptions } from "../types.ts";++/** Bounded typed-edge fan-out depth for the relational arm (t_09b7ccea). */+const RELATIONAL_MAX_DEPTH = 2;++export interface RelationalReach {+ readonly via: ReadonlyArray<string>;+ readonly hops: number;+}++export interface RelationalArmOutcome {+ readonly rankedChunkIds: number[];+ readonly reachByChunk: Map<number, RelationalReach>;+}++/**+ * The arm engages ONLY in rrf fusion and when enabled (per-call override+ * ahead of the config default). Off / linear fusion leaves the pool and+ * ranking byte-identical.+ */+export function isRelationalArmActive(config: ResolvedSearchConfig, opts: SearchOptions): boolean {+ return config.fusionMode === "rrf" && (opts.relationalArm ?? config.recall.relationalArmEnabled);+}++export function noRelationalArm(): RelationalArmOutcome {+ return { rankedChunkIds: [], reachByChunk: new Map() };+}++/**+ * A bounded depth-2 typed-edge fan-out from the resolved seeds. A+ * non-relational query (no wikilink seed plus schema-vocabulary edge-type+ * token) contributes nothing. Source identity from the shared key module+ * dedups the lane (federation hardening).+ */+export function runRelationalArm(store: Store, vault: string, query: string): RelationalArmOutcome {+ const outcome = noRelationalArm();+ const relQuery = parseRelationalQuery(query, relationalEdgeVocabulary(vault));+ if (relQuery === null) return outcome;+ const seedDocIds = resolveSeedDocumentIds(store, relQuery.seeds);+ if (seedDocIds.length === 0) return outcome;+ const nodes = relationalFanout(store, seedDocIds, {+ maxDepth: RELATIONAL_MAX_DEPTH,+ edgeTypes: relQuery.edgeTypes,+ });+ const reps = store.representativeChunks(nodes.map((n) => n.documentId));+ const seenKeys = new Set<string>();+ for (const node of nodes) {+ const rep = reps.get(node.documentId);+ if (rep === undefined) continue;+ const key = rrfKey({ origin: null, path: rep.path, chunkId: rep.chunkId });+ if (seenKeys.has(key)) continue;+ seenKeys.add(key);+ outcome.rankedChunkIds.push(rep.chunkId);+ outcome.reachByChunk.set(rep.chunkId, { via: node.viaLinkTypes, hops: node.hops });+ }+ return outcome;+}++/**+ * The recognised edge-type vocabulary for the relational parser: the schema+ * pack's declared link types unioned with the default relation vocabulary,+ * all normalized. An unreadable pack falls back to the defaults. This is the+ * only place edge-type vocabulary enters the search path - never a+ * natural-language word list.+ */+function relationalEdgeVocabulary(vault: string): string[] {+ const vocab = new Set<string>(DEFAULT_RELATION_TYPES.map((t) => normalizeRelation(t)));+ try {+ for (const t of loadSchemaPack(vault).link_types) vocab.add(normalizeRelation(t));+ } catch {+ // An unreadable schema pack falls back to the default relation vocabulary.+ }+ return [...vocab];+}++/**+ * Resolve relational-query wikilink seeds to document ids. Tries the exact+ * `<seed>.md` path, then the bare seed, then an UNAMBIGUOUS basename match+ * anywhere in the tree (an ambiguous basename stays unresolved -+ * deterministic inertness beats guessing the wrong page). Deduped.+ */+function resolveSeedDocumentIds(store: Store, seeds: ReadonlyArray<string>): number[] {+ const out: number[] = [];+ const seen = new Set<number>();+ let titles: Map<number, { readonly path: string; readonly title: string | null }> | null = null;+ for (const seed of seeds) {+ let docId = store.getDocumentIdByPath(`${seed}.md`) ?? store.getDocumentIdByPath(seed);+ if (docId === null) {+ titles ??= store.documentTitles();+ const matches: number[] = [];+ for (const [id, meta] of titles) {+ const base = meta.path.split("/").pop() ?? meta.path;+ if (base === `${seed}.md`) matches.push(id);+ }+ if (matches.length === 1) docId = matches[0]!;+ }+ if (docId !== null && !seen.has(docId)) {+ seen.add(docId);+ out.push(docId);+ }+ }+ return out;+}diff --git a/src/core/search/pipeline/request.ts b/src/core/search/pipeline/request.tsnew file mode 100644index 00000000..a7ef88ed--- /dev/null+++ b/src/core/search/pipeline/request.ts@@ -0,0 +1,149 @@+/**+ * Request resolution: everything the caller's options decide BEFORE any+ * store I/O - the effective knob tuple (recall profile / self-tuning), the+ * clamped limit, input validation, the semantic policy, the session focus,+ * and the two time layers (the `since`/`until` parameters and the window+ * the query text itself declares). Resolving it here means invalid input+ * fails fast, before the index is opened.+ */++import { resolveRecallProfile } from "../profiles.ts";+import { resolveSemanticPolicy, type SemanticPolicy } from "../semantic-phase.ts";+import { readActiveSessionFocus } from "../session-focus.ts";+import {+ detectTemporalIntent,+ stripTemporalDirectives,+ type TemporalIntent,+} from "../temporal-intent.ts";+import { resolveTimeRange, type ResolvedTimeRange } from "../time-range.ts";+import { applyTunedParameters, loadTunedParameters } from "../tuning-store.ts";+import { SearchError } from "../types.ts";+import type {+ ResolvedSearchConfig,+ SearchOptions,+ SearchSessionFocus,+ TunedParameters,+} from "../types.ts";++/**+ * Bounds for the public `limit` option. CLI validates against the same+ * ceiling before calling in; MCP applies its own, lower `MCP_LIMIT_MAX`+ * (token-budget conscious) - the two ceilings are deliberately different,+ * this just gives the shared one a name instead of a bare `100` literal.+ */+export const SEARCH_LIMIT_MIN = 1;+export const SEARCH_LIMIT_MAX = 100;++const DEFAULT_LIMIT = 10;++export interface ResolvedSearchRequest {+ /** The config with the resolved profile / tuning knobs already applied. */+ readonly config: ResolvedSearchConfig;+ /** RESIDUAL query text: the caller's query minus any time directive. */+ readonly query: string;+ readonly limit: number;+ readonly pathPrefix: string | undefined;+ readonly policy: SemanticPolicy;+ readonly sessionFocus: SearchSessionFocus | null;+ /** One clock for every time-resolving decision in this call. */+ readonly nowMs: number;+ readonly timeRange: ResolvedTimeRange | null;+ readonly temporalIntent: TemporalIntent | null;+ /** Whether local query expansion runs for this call. */+ readonly expandActive: boolean;+ /** The applied knob tuple, or null when neither profile nor tuning fired. */+ readonly tuned: TunedParameters | null;+}++function assertSafePathPrefix(prefix: string | undefined): string | undefined {+ if (!prefix) return undefined;+ if (prefix.includes("..") || prefix.startsWith("/")) {+ throw new SearchError("INVALID_INPUT", "path_prefix escapes vault");+ }+ return prefix;+}++export function resolveSearchRequest(+ config: ResolvedSearchConfig,+ opts: SearchOptions,+): ResolvedSearchRequest {+ const rawQuery = (opts.query ?? "").trim();+ if (!rawQuery) {+ throw new SearchError("INVALID_INPUT", "missing required argument: query");+ }+ // Recall profile (Recall & Working-Memory Quality Suite, t_98c39dd6) and+ // opt-in self-tuning (t_ae973491) resolve to the SAME knob tuple, applied+ // through applyTunedParameters (which disarms selfTuningEnabled so the+ // applied config can never recurse). An explicitly selected profile is an+ // operator choice and takes precedence over the persisted grid point; with+ // no profile, behaviour is unchanged - self-tuning applies iff enabled. An+ // explicit opts.expand always wins over the resolved expansion default.+ const profileParams = opts.profile !== undefined ? resolveRecallProfile(opts.profile) : null;+ const tuned =+ profileParams ?? (config.recall.selfTuningEnabled ? loadTunedParameters(config.vault) : null);+ const resolvedConfig = tuned !== null ? applyTunedParameters(config, tuned) : config;+ const expandActive = opts.expand ?? (tuned !== null && tuned.expansion);+ const limit = Math.max(SEARCH_LIMIT_MIN, Math.min(SEARCH_LIMIT_MAX, opts.limit ?? DEFAULT_LIMIT));+ if (opts.threshold !== undefined && (!Number.isFinite(opts.threshold) || opts.threshold < 0)) {+ throw new SearchError("INVALID_INPUT", "threshold must be a finite number >= 0");+ }+ const pathPrefix = assertSafePathPrefix(opts.pathPrefix);+ const policy = resolveSemanticPolicy(resolvedConfig, opts);+ const sessionFocus =+ opts.sessionFocus === undefined+ ? readActiveSessionFocus(resolvedConfig, opts.focusSession, Date.now())+ : opts.sessionFocus;+ // One clock for every time-resolving decision in this call, so the hard+ // filter and the query-declared window below cannot disagree by a few+ // milliseconds of wall-clock drift.+ const nowMs = Date.now();+ // Time-aware recall (recall-trust-suite): resolve since/until up front+ // so invalid input fails fast, before any store I/O.+ const timeRange =+ opts.since !== undefined || opts.until !== undefined+ ? resolveTimeRange({ since: opts.since, until: opts.until }, nowMs)+ : null;+ // Query-side temporal intent (t_58fc4720). Resolved HERE, from the raw+ // query as the caller typed it, and before any store I/O:+ //+ // - detection must read the ORIGINAL text. Expansion rewrites the+ // keyword lane into bare lexical terms, and the `field:value`+ // grammar does not survive that rewrite - planning from the+ // rewritten text saw no directive while the strip below still+ // removed one, so a declared window was voided and its directive+ // reached the implicit-AND keyword lane as a term nothing matches;+ // - a malformed directive then fails as fast as `since` / `until`+ // does, rather than after the index is opened.+ //+ // From here on the query text is the RESIDUAL text: a directive states+ // the window and is not a term, so it must not reach the keyword lane,+ // the semantic lane, the coverage gate or the evidence pack. Stripping+ // is byte-identical for a query that carries no directive.+ const temporalIntent = detectTemporalIntent(rawQuery, nowMs);+ const query = stripTemporalDirectives(rawQuery);+ if (query === "") {+ // A window with nothing to search for. Both lanes would be handed the+ // empty string - FTS short-circuits on an empty match and the semantic+ // lane embeds "" - so the honest answer is the same one the parameter+ // form gives: a window FILTERS a query, it is not a query.+ throw new SearchError(+ "INVALID_INPUT",+ "the query declares a time window and no search terms: " ++ "add the terms to look for, or pass the window as the since / until parameters",+ );+ }++ return {+ config: resolvedConfig,+ query,+ limit,+ pathPrefix,+ policy,+ sessionFocus,+ nowMs,+ timeRange,+ temporalIntent,+ expandActive,+ tuned,+ };+}diff --git a/src/core/search/pipeline/second-pass.ts b/src/core/search/pipeline/second-pass.tsnew file mode 100644index 00000000..d3003a50--- /dev/null+++ b/src/core/search/pipeline/second-pass.ts@@ -0,0 +1,163 @@+/**+ * Self-correcting second-pass recall: the two mutually exclusive retries+ * that rescue a first pass which was too strict. At most ONE fires per+ * query - a zero-candidate pool gets a broadened OR retry (t_ef92dfdc),+ * a partially-covered pool gets a targeted retry on the specifically+ * uncovered rare terms (t_8eb5ca32). Both are deterministic and LLM-free.+ */++import {+ COMPLETENESS_COMPLETE_THRESHOLD,+ planTargetedRetry,+ significantTerms,+} from "../coverage.ts";+import { coverageOverChunks } from "../evidence-verification.ts";+import { runFtsQueryDetailed } from "../fts.ts";+import { semanticPoolSize } from "../semantic-phase.ts";+import { eventTimeInRange, type ValidityWindow } from "../validity.ts";+import type { KeywordHit, Store } from "../store.ts";+import type { ResolvedTimeRange } from "../time-range.ts";+import type { SearchOutcome } from "../types.ts";++/** A broadened retry needs a base term plus at least one alternative. */+const MIN_BROADENING_TERMS = 2;++export interface SecondPassInput {+ readonly store: Store;+ /** Residual query text. */+ readonly query: string;+ readonly limit: number;+ readonly pathPrefix: string | undefined;+ readonly timeRange: ResolvedTimeRange | null;+ readonly validityWindowFor: (path: string) => ValidityWindow | null;+ readonly keywordHits: KeywordHit[];+ /** The candidate id set; a firing retry adds to it in place. */+ readonly chunkIds: Set<number>;+ readonly ids: number[];+}++export interface SecondPassOutcome {+ readonly secondPass: SearchOutcome["secondPass"];+ readonly keywordHits: KeywordHit[];+ readonly ids: number[];+ /**+ * Chunk ids the TARGETED retry recovered, so only those results (not+ * the first-pass hits they merge with) get the attribution reason.+ */+ readonly targetedChunkIds: ReadonlySet<number>;+ readonly warnings: string[];+}++export function noSecondPass(input: {+ readonly keywordHits: KeywordHit[];+ readonly ids: number[];+}): SecondPassOutcome {+ return {+ secondPass: undefined,+ keywordHits: input.keywordHits,+ ids: input.ids,+ targetedChunkIds: new Set(),+ warnings: [],+ };+}++export function runSecondPassRecall(input: SecondPassInput): SecondPassOutcome {+ if (input.ids.length === 0) return runBroadenedRetry(input);+ return runTargetedRetry(input);+}++/**+ * A zero-candidate first pass in evidence-pack mode means the implicit-AND+ * keyword match was too strict - the classic abstention dead end. Instead+ * of returning empty, run EXACTLY ONE broadened retry that keeps the first+ * significant term as the base group and ORs the rest in as alternatives,+ * then let the merged pool flow through the normal ranking, filters, and a+ * recomputed evidence pack.+ */+function runBroadenedRetry(input: SecondPassInput): SecondPassOutcome {+ const { store, query, limit, pathPrefix, chunkIds } = input;+ const terms = significantTerms(query);+ if (terms.length < MIN_BROADENING_TERMS) return noSecondPass(input);+ const broadened = runFtsQueryDetailed(store, terms[0]!, {+ expandedTerms: terms.slice(1),+ limit: semanticPoolSize(limit),+ pathPrefix: pathPrefix ?? null,+ });+ const warnings = [...broadened.warnings];+ if (broadened.hits.length === 0) {+ return { ...noSecondPass(input), warnings };+ }+ const keywordHits = broadened.hits;+ for (const h of keywordHits) chunkIds.add(h.chunkId);+ return {+ secondPass: Object.freeze({+ triggered: true,+ kind: "broadened",+ reason: "zero-candidate first pass; broadened OR retry",+ added: keywordHits.length,+ }),+ keywordHits,+ ids: Array.from(chunkIds),+ targetedChunkIds: new Set(),+ warnings,+ };+}++/**+ * Coverage-driven targeted follow-up: the first pass DID return+ * candidates, but their IDF-weighted coverage of the query is below the+ * completeness threshold with rare query terms still uncovered - a PARTIAL+ * miss, distinct from the zero-candidate dead end. Issue exactly ONE+ * targeted retry built from the specifically-uncovered rare terms (not a+ * generic broadening of the whole query) and merge the recovered+ * candidates into the pool. The recomputed pack still abstains on any term+ * left uncovered after the retry.+ */+function runTargetedRetry(input: SecondPassInput): SecondPassOutcome {+ const { store, query, limit, pathPrefix, timeRange, chunkIds, ids } = input;+ // Judge coverage over the pool that will actually survive ranking:+ // for a time-scoped query, exclude out-of-range candidates first, so+ // a rare term is not marked "covered" only because an out-of-range+ // chunk matched it (which would wrongly suppress the retry while the+ // final in-range result set still misses that term).+ let coverageIds = ids;+ if (timeRange !== null) {+ const hydratedForCoverage = store.hydrateChunks(ids);+ coverageIds = ids.filter((chunkId) => {+ const chunk = hydratedForCoverage.get(chunkId);+ if (chunk === undefined) return false;+ return eventTimeInRange(input.validityWindowFor(chunk.path), chunk.mtime, timeRange);+ });+ }+ const poolCoverage = coverageOverChunks(store, query, coverageIds);+ const retryPlan = planTargetedRetry(poolCoverage);+ if (!retryPlan.fire) return noSecondPass(input);+ const targeted = runFtsQueryDetailed(store, retryPlan.terms[0]!, {+ expandedTerms: retryPlan.terms.slice(1),+ limit: semanticPoolSize(limit),+ pathPrefix: pathPrefix ?? null,+ });+ const warnings = [...targeted.warnings];+ const newHits = targeted.hits.filter((h) => !chunkIds.has(h.chunkId));+ if (newHits.length === 0) {+ return { ...noSecondPass(input), warnings };+ }+ const targetedChunkIds = new Set<number>();+ for (const h of newHits) {+ chunkIds.add(h.chunkId);+ targetedChunkIds.add(h.chunkId);+ }+ return {+ secondPass: Object.freeze({+ triggered: true,+ kind: "targeted",+ reason: `partial coverage ${poolCoverage.idfWeightedCoverage.toFixed(2)} < ${COMPLETENESS_COMPLETE_THRESHOLD}; targeted retry on uncovered rare terms: ${retryPlan.terms.join(", ")}`,+ added: newHits.length,+ targetedTerms: retryPlan.terms,+ }),+ keywordHits: input.keywordHits.concat(newHits),+ ids: Array.from(chunkIds),+ targetedChunkIds,+ warnings,+ };+}diff --git a/src/core/search/pipeline/semantic-lane.ts b/src/core/search/pipeline/semantic-lane.tsnew file mode 100644index 00000000..176e6605--- /dev/null+++ b/src/core/search/pipeline/semantic-lane.ts@@ -0,0 +1,84 @@+/**+ * Semantic candidate lane as the pipeline sees it: the guarded vector+ * phase plus the two caller-visible signals that only make sense once the+ * lane has run or been skipped - embedding-ABI drift and hybrid degrade.+ */++import { detectHybridDegrade } from "../enrich.ts";+import { runSemanticPhase, semanticPoolSize } from "../semantic-phase.ts";+import { contradictedAbiFields, formatEmbeddingAbiDrift } from "../store.ts";+import type { SemanticPolicy } from "../semantic-phase.ts";+import type { Store } from "../store.ts";+import type { ResolvedSearchConfig } from "../types.ts";++export interface SemanticLaneInput {+ readonly store: Store;+ readonly config: ResolvedSearchConfig;+ readonly policy: SemanticPolicy;+ /** Residual query text, used when no structured vec lane was given. */+ readonly query: string;+ readonly semanticLaneQuery: string | null;+ readonly limit: number;+ readonly pathPrefix: string | undefined;+ /** Keyword pool size, the other half of the hybrid-degrade signal. */+ readonly keywordHitCount: number;+}++export interface SemanticLaneOutcome {+ readonly hits: ReturnType<Store["semanticTopK"]>;+ readonly attempted: boolean;+ readonly warnings: string[];+}++export async function runSemanticLane(input: SemanticLaneInput): Promise<SemanticLaneOutcome> {+ const { store, config, policy, query, semanticLaneQuery, limit, pathPrefix } = input;+ const warnings: string[] = [];+ let hits: ReturnType<Store["semanticTopK"]> = [];+ let attempted = false;++ if (semanticLaneQuery !== null && !policy.wantSemantic) {+ warnings.push("semantic structured lanes skipped: semantic search is disabled");+ }+ if (policy.wantSemantic) {+ const semOutcome = await runSemanticPhase(store, config, semanticLaneQuery ?? query, {+ limit: semanticPoolSize(limit),+ pathPrefix,+ explicit: policy.explicit,+ });+ attempted = semOutcome.attempted;+ hits = semOutcome.hits;+ for (const w of semOutcome.warnings) warnings.push(w);+ // Embedding-ABI drift on the QUERY path (context-integrity-gates,+ // Unit E). The read open already ran the gated comparison; until+ // now nothing on this path looked at the result, so under the+ // shipped `warn` default a caller was served neighbours out of a+ // vector table written by another build with nothing to observe.+ //+ // Attached to the queries it actually describes: only when the+ // semantic lane RAN, so a keyword-only query stays byte-identical,+ // and only for fields the index CONTRADICTS. An unrecorded token+ // is a store predating the stamp - true of every index built+ // before this release - and repeating it on every query would+ // make the warning worthless; it stays on `search status`,+ // `second_brain_status` and `search check`, which is where an+ // operator goes looking.+ if (attempted) {+ const contradicted = contradictedAbiFields(store.embeddingAbiMismatches());+ if (contradicted.length > 0) warnings.push(formatEmbeddingAbiDrift(contradicted));+ }+ }++ // Hybrid-degrade signal (Search & Recall Quality Suite): one+ // structural warning when the caller wanted the semantic lane but it+ // did not run, so the query was served keyword-only. The granular+ // runSemanticPhase warnings above explain WHY; this is the single+ // greppable flag a caller can test for.+ const degrade = detectHybridDegrade({+ wantSemantic: policy.wantSemantic,+ semanticAttempted: attempted,+ keywordHitCount: input.keywordHitCount,+ });+ if (degrade !== null) warnings.push(degrade);++ return { hits, attempted, warnings };+}diff --git a/src/core/search/pipeline/store-open.ts b/src/core/search/pipeline/store-open.tsnew file mode 100644index 00000000..812bdca9--- /dev/null+++ b/src/core/search/pipeline/store-open.ts@@ -0,0 +1,38 @@+/**+ * Read-open policy for the query hot path: how a stale, absent, or+ * unreadable index heals itself instead of failing the search.+ */++import { Store } from "../store.ts";+import { SearchError } from "../types.ts";+import type { ResolvedSearchConfig } from "../types.ts";++/**+ * Open the index for reading, self-healing a stale, absent, or unreadable+ * index. After a plugin upgrade the on-disk index can be a different schema+ * version (`SCHEMA_MISMATCH`), not yet built (`INDEX_MISSING`), or corrupt+ * / truncated / non-OSB at the index path (`INDEX_UNREADABLE`); rather than+ * forcing the user to run `o2b search reindex` / `o2b search index`, rebuild+ * once and retry. `reindexVault` is imported lazily so the hot path never+ * pulls in the indexer and there is no module cycle.+ */+export async function openReadOrSelfHeal(config: ResolvedSearchConfig): Promise<Store> {+ try {+ return await Store.open(config, { mode: "read" });+ } catch (e) {+ if (+ e instanceof SearchError &&+ (e.code === "INDEX_MISSING" || e.code === "SCHEMA_MISMATCH" || e.code === "INDEX_UNREADABLE")+ ) {+ try {+ const { reindexVault } = await import("../indexer.ts");+ await reindexVault(config);+ } catch {+ // A concurrent writer may already be rebuilding (INDEX_LOCKED), or the+ // rebuild failed - fall through and let the retry surface real state.+ }+ return await Store.open(config, { mode: "read" });+ }+ throw e;+ }+}diff --git a/src/core/search/pipeline/weights.ts b/src/core/search/pipeline/weights.tsnew file mode 100644index 00000000..5a063811--- /dev/null+++ b/src/core/search/pipeline/weights.ts@@ -0,0 +1,39 @@+/**+ * Effective ranking weights for one query: the plan's intent profile+ * composed with the opt-in weights learned from explicit feedback.+ */++import {+ composeWeightProfiles,+ isNeutralLearnedWeights,+ readLearnedWeights,+ type LearnedWeights,+} from "../feedback.ts";+import type { QueryPlan, ResolvedSearchConfig, WeightProfile } from "../types.ts";++export interface EffectiveWeights {+ /** Undefined leaves the ranker on its unweighted default. */+ readonly weightProfile: WeightProfile | undefined;+ /**+ * The learned weights that actually moved this ranking, or null when+ * the feature is off or the fold is neutral. Non-null is exactly the+ * condition under which a result explains the learned-weight effect.+ */+ readonly activeLearned: LearnedWeights | null;+}++export function resolveEffectiveWeights(+ config: ResolvedSearchConfig,+ plan: QueryPlan,+): EffectiveWeights {+ const intentProfile = config.recall.intentEnabled ? plan.weightProfile : undefined;+ // Learned recall weights (recall-trust-suite): opt-in multipliers+ // derived from explicit feedback compose with the intent profile.+ // Both factors are bounded, so the product is too; neutral learned+ // weights leave ranking bit-identical.+ const learned = config.recall.learnedWeightsEnabled ? readLearnedWeights(config.vault) : null;+ const activeLearned = learned !== null && !isNeutralLearnedWeights(learned) ? learned : null;+ const weightProfile =+ activeLearned !== null ? composeWeightProfiles(intentProfile, activeLearned) : intentProfile;+ return { weightProfile, activeLearned };+}diff --git a/src/core/search/property-filter.ts b/src/core/search/property-filter.tsindex de57ec47..e8b419e7 100644--- a/src/core/search/property-filter.ts+++ b/src/core/search/property-filter.ts@@ -17,7 +17,7 @@* reader, tests can pass an in-memory map.*/-import { SearchError } from "./types.ts";+import { SearchError } from "./search-error.ts";export type PropertyFilterMap = ReadonlyMap<string, ReadonlyArray<string>>;export type PropertyFrontmatterReader = (path: string) => Record<string, unknown> | null;diff --git a/src/core/search/rank-adjust.ts b/src/core/search/rank-adjust.tsindex 970fd3f9..fa863012 100644--- a/src/core/search/rank-adjust.ts+++ b/src/core/search/rank-adjust.ts@@ -26,7 +26,7 @@*/import { clamp01 } from "../math.ts";-import type { BrainSearchResult } from "./types.ts";+import type { BrainSearchResult } from "./search-result.ts";/** A per-candidate verdict returned by a {@link RankAdjuster}. */export type RankAdjustVerdict =diff --git a/src/core/search/search-error.ts b/src/core/search/search-error.tsnew file mode 100644index 00000000..808a3e7b--- /dev/null+++ b/src/core/search/search-error.ts@@ -0,0 +1,74 @@+/**+ * The typed failure vocabulary of `src/core/search/*`: the error-code+ * union, the {@link SearchError} carrier, and the embedding-provider+ * error taxonomy.+ *+ * A LEAF by construction β it imports nothing from the search layer. The+ * parsers that raise (`time-range.ts`, `temporal-intent.ts`,+ * `property-filter.ts`) are themselves leaves that `types.ts` aggregates+ * from, so an error carrier living in the aggregate would make every+ * raising parser point back at it.+ */++export const SEARCH_ERROR_CODES = [+ "INDEX_MISSING",+ "INDEX_UNREADABLE",+ "SCHEMA_MISMATCH",+ "VEC_EXTENSION_UNAVAILABLE",+ "EMBEDDING_DISABLED",+ "EMBEDDING_KEY_MISSING",+ "EMBEDDING_PROVIDER_HTTP",+ "EMBEDDING_PROVIDER_TIMEOUT",+ "EMBEDDING_DIMENSION_MISMATCH",+ "EMBEDDING_INVALID_VECTOR",+ "EMBEDDING_COST_GATE",+ "EMBEDDING_QUOTA_EXHAUSTED",+ "RERANK_PROVIDER_HTTP",+ "INDEX_LOCKED",+ "INVALID_INPUT",+] as const;+export type SearchErrorCode = (typeof SEARCH_ERROR_CODES)[number];++/**+ * Actionable operator-facing message for an exhausted embedding quota /+ * billing limit (Task C1/C2). Shared by the provider (thrown message), the+ * semantic-phase degrade warning, and the MCP error mapping so the single+ * remediation instruction stays consistent across every surface.+ */+export const EMBEDDING_QUOTA_MESSAGE =+ "embedding quota/billing exhausted: semantic search is degraded to keyword-only. " ++ "Check your embedding provider billing and quota, raise the limit or top up, then reindex.";++/**+ * Coarse outcome category for an embedding-provider error (Task C1). Drives+ * both the retry policy (`retriable`) and the degrade-warning wording.+ * `quota` and `auth` fail fast; `rate_limit` and `transient` retry.+ */+export type EmbeddingErrorCategory = "quota" | "rate_limit" | "auth" | "transient" | "fatal";++/**+ * Additive structured context for a {@link SearchError} originating from a+ * provider HTTP response. Both fields are optional so every existing+ * two-argument call site stays valid.+ */+export interface SearchErrorOptions {+ /** Upstream HTTP status code. */+ readonly status?: number;+ /** Parsed `Retry-After` delay in milliseconds. */+ readonly retryAfterMs?: number;+}++export class SearchError extends Error {+ readonly code: SearchErrorCode;+ /** Upstream HTTP status when this error originated from a provider response. */+ readonly status?: number;+ /** Parsed `Retry-After` delay in milliseconds when the provider supplied one. */+ readonly retryAfterMs?: number;+ constructor(code: SearchErrorCode, message: string, opts?: SearchErrorOptions) {+ super(message);+ this.name = "SearchError";+ this.code = code;+ if (opts?.status !== undefined) this.status = opts.status;+ if (opts?.retryAfterMs !== undefined) this.retryAfterMs = opts.retryAfterMs;+ }+}diff --git a/src/core/search/search-result.ts b/src/core/search/search-result.tsnew file mode 100644index 00000000..f1b3ec32--- /dev/null+++ b/src/core/search/search-result.ts@@ -0,0 +1,132 @@+/**+ * The shape of ONE ranked search hit: the result row plus the per-hit+ * score and trust metadata computed alongside it. Plain data β no+ * behaviour, no I/O.+ *+ * A LEAF by construction β it imports nothing from the search layer, so+ * the stages that consume a ranked hit (`rank-adjust.ts` and, through+ * its exclusion record, `../brain/trust/retrieval-receipts.ts`) can name+ * the row without pointing back at the `types.ts` aggregate that+ * re-exports it.+ */++/**+ * Structured per-layer score components (Search & Recall Quality Suite).+ * The numeric sibling of `reasons[]`: where `reasons` formats only the+ * layers that fired as strings, `breakdown` carries every component of+ * the final score as a number, zero for a layer that did not fire and 1+ * for a neutral multiplier. Additive layers (keyword, semantic, rrf,+ * entity, activation, coAccess, link, recency, sessionFocus) are the raw+ * contributions; `tier` and `trend` are the relevance-portion multipliers+ * (1.0 = neutral). The ranker emits it for every primary result; the MCP+ * `explain` projection and `feedback.ts` read it directly instead of+ * re-parsing reason strings.+ */+export interface ScoreBreakdown {+ readonly keyword: number;+ readonly semantic: number;+ readonly rrf: number;+ readonly entity: number;+ readonly activation: number;+ readonly coAccess: number;+ /** Observed-reuse boost (t_65588d8b); 0 when no verdicts apply. */+ readonly reuse: number;+ readonly link: number;+ readonly recency: number;+ readonly tier: number;+ readonly trend: number;+ readonly sessionFocus: number;+ /**+ * Query-side temporal-intent boost (t_58fc4720). Present ONLY when the+ * query declared a time window; absent - not zero - for every query+ * that declared none, so a breakdown without temporal intent stays+ * byte-identical to pre-suite behaviour.+ */+ readonly temporal?: number;+}++/**+ * Inline per-hit trust metadata (Search & Recall Quality Suite). Computed+ * at read time, never stored. `age_days` is the whole-day distance from+ * the document mtime; `superseded` / `conflict` are derived from the+ * typed relation edges the recall pipeline surfaces (`superseded_by` /+ * `contradicts`). Present on a result only when the caller set `trust`.+ */+export interface TrustMetadata {+ readonly age_days: number;+ readonly superseded: boolean;+ readonly conflict: boolean;+ /**+ * Belief lifecycle suite (A4, t_d9365884): when the hit is superseded,+ * the `superseded_by` successor target so recall carries a pointer to+ * the replacement. `null` when the hit is not superseded or declares no+ * successor target.+ */+ readonly replacement: string | null;+}++export interface BrainSearchResult {+ readonly documentId: number;+ readonly chunkId: number;+ readonly path: string;+ readonly title: string | null;+ readonly content: string;+ readonly startLine: number;+ readonly endLine: number;+ readonly score: number;+ readonly keywordScore: number;+ readonly semanticScore: number;+ readonly linkBoost: number;+ readonly recencyBoost: number;+ /**+ * Transcript turn instant (unix seconds) this result was authored at+ * (conversation chronology, S1 / t_347e8224). Present only for a note+ * carrying an `authored_at` frontmatter instant; absent for every note+ * with no turn instant, so the result shape stays byte-identical for a+ * vault without transcript-authored notes. Exact hybrid-score ties are+ * ordered newer-first by this value.+ */+ readonly authoredAt?: number;+ readonly searchType: "keyword" | "semantic" | "hybrid" | "link";+ /**+ * Explainable recall: one entry per scoring layer that contributed+ * to `score`, formatted `"<layer>: <fixed-precision value>"`. Layers+ * that did not fire (zero contribution) are omitted. Always present;+ * never empty for a result that surfaced.+ */+ readonly reasons: ReadonlyArray<string>;+ /**+ * Typed semantic relations this result's page declares in its+ * frontmatter (v3 / typed graph semantics): `related` / `extends` /+ * `contradicts` / `superseded_by` and any other vocabulary relation.+ * Computed at query time from the links table, never stored on the+ * result row. Absent when the page declares no typed relations.+ */+ readonly relations?: ReadonlyArray<{+ readonly relation: string;+ readonly target: string;+ }>;+ /**+ * Structured per-layer score components (Search & Recall Quality+ * Suite). Always present on a primary ranked result; absent on+ * synthetic results (link-traversal expansions, relation-polarity+ * successor pull-ins) whose score is not a per-layer sum - the+ * `explain` projection derives a faithful breakdown from the+ * first-class lane/boost fields for those. Never serialized to the MCP+ * output unless the caller sets `explain`.+ */+ readonly breakdown?: ScoreBreakdown;+ /**+ * Inline trust metadata (Search & Recall Quality Suite). Present only+ * when the caller set `trust`; computed at read time from the document+ * mtime and the surfaced typed relations, never stored.+ */+ readonly trust?: TrustMetadata;+ /**+ * Kind-namespaced origin label (Workspace Insight Suite, cross-vault+ * search): "local", "profile/<name>", or "source/<alias>". Only set+ * by `searchAcrossVaults`; plain single-vault search leaves it+ * absent, keeping the legacy result shape byte-identical.+ */+ readonly origin?: string;+}diff --git a/src/core/search/search.ts b/src/core/search/search.tsindex 0afd65c8..8327decb 100644--- a/src/core/search/search.ts+++ b/src/core/search/search.ts@@ -4,1444 +4,275 @@** Anchored in docs/plans/2026-05-16-brain-search-design.md Β§7, Β§9.*- * The function is async because semantic search requires an HTTP call- * (the provider embeds the query). Keyword-only paths stay sync inside- * the store but the public surface stays uniform.+ * This module is the pipeline itself: every stage lives in `./pipeline/`+ * with its own input and output type, and each stage's opt-in gate is+ * visible here, at the call site. The function is async because semantic+ * search requires an HTTP call (the provider embeds the query).+ * Keyword-only paths stay sync inside the store but the public surface+ * stays uniform.*/-import { statSync } from "node:fs";-import { join } from "node:path";--import { normalizeVisibilityScope } from "../graph/visibility.ts";-import { normalizeAgentScope } from "../graph/agent-scope.ts";-import { canonicalSourceSetKey, normalizeScopeFilter, rrfKey } from "../scope-key.ts";-import { DEFAULT_RELATION_TYPES, normalizeRelation } from "../graph/relation-vocab.ts";-import { loadSchemaPack } from "../brain/schema-pack.ts";-import { parseRelationalQuery } from "./relational-query.ts";-import { relationalFanout } from "./relational-fanout.ts";-import { isLowSelectivity, planTrigramPrefilter } from "./trigram-prefilter.ts";-import {- composeWeightProfiles,- fnv1aHex,- isNeutralLearnedWeights,- learnedWeightsFingerprint,- learnedWeightsReason,- readLearnedWeights,-} from "./feedback.ts";-import { parseFreshnessTrend } from "../brain/temporal/freshness-trend.ts";-import { observedReuseRates } from "../brain/observed-use.ts";-import { effectiveActivation, halfLifeDays, resolveActivationKind } from "./activation/decay.ts";-import {- ACCESS_EVENT_PATHS_CAP,- CO_ACCESS_MIN_COUNT,- activationStateFingerprint,- readActivationState,- recordAccessEvent,-} from "./activation/store.ts";-import { extractEntities } from "./entities.ts";-import { expandQueryEntities } from "./entity-alias.ts";-import {- COMPLETENESS_COMPLETE_THRESHOLD,- planTargetedRetry,- significantTerms,-} from "./coverage.ts";-import { buildEvidencePack, downrankTerminalEvidenceResults } from "./evidence-pack.ts";-import { runFtsQueryDetailed } from "./fts.ts";-import { mmrRerank } from "./mmr.ts";-import { buildQueryPlan } from "./query-plan.ts";-import { buildCacheKey, getCachedOutcome, putCachedOutcome } from "./query-cache.ts";-import { deriveExpansionTerms, tokenizeForExpansion, DEFAULT_EXPANSION } from "./synonyms.ts";-import { rankResults } from "./ranker.ts";-import { applyRankAdjusters, type RankAdjuster } from "./rank-adjust.ts";-import { trustGateAdjuster } from "../brain/trust/retrieval-gate.ts";+import { assembleRankedResults } from "./pipeline/assemble.ts";+import { decorateFinalResults } from "./pipeline/attribution.ts";+import { isCacheEligible, persistCachedOutcome, probeQueryCache } from "./pipeline/cache-slot.ts";+import { collectCandidateSignals } from "./pipeline/candidate-signals.ts";+import { createEventTimeResolver, filterCandidatesInRange } from "./pipeline/event-time.ts";+import { runKeywordLane } from "./pipeline/keyword-lane.ts";+import { buildSearchOutcome, emptyOutcome } from "./pipeline/outcome.ts";+import { applyPostRankPhases } from "./pipeline/post-rank.ts";+import { resolveQueryShape } from "./pipeline/query-shape.ts";import {- buildMemoryTrustAssessment,- buildRetrievalDecisionTrace,-} from "../brain/trust/retrieval-receipts.ts";-import { detectHybridDegrade, rerankByRelevance } from "./enrich.ts";-import { applyReinforceBoost, loadReinforceStrengths, reinforceFingerprint } from "./reinforce.ts";-import { readActiveSessionFocus } from "./session-focus.ts";-import { applyTemporalBridge } from "./temporal-bridge.ts";-import { detectTemporalIntent, stripTemporalDirectives } from "./temporal-intent.ts";-import { resolveTimeRange } from "./time-range.ts";-import { eventTimeInRange, parseValidityWindow, type ValidityWindow } from "./validity.ts";-import { contradictedAbiFields, formatEmbeddingAbiDrift, Store } from "./store.ts";-import { SearchError } from "./types.ts";-import type {- BrainSearchResult,- ResolvedSearchConfig,- SearchOptions,- SearchOutcome,-} from "./types.ts";-import { expandQuery } from "./query-expansion.ts";-import { applyTunedParameters, loadTunedParameters } from "./tuning-store.ts";-import { resolveRecallProfile } from "./profiles.ts";-import { applyCrossEncoderRerank } from "./rerank/index.ts";-import { emitGatedTelemetry } from "../brain/continuity/emit.ts";-import {- addStructuredReasons,- applyStructuredExclusions,- structuredKeywordQuery,- structuredSemanticQuery,-} from "./structured-lanes.ts";-import { resolveSemanticPolicy, runSemanticPhase, semanticPoolSize } from "./semantic-phase.ts";-import { toSearchCard } from "./cards.ts";-import {- applyAgentScope,- applyDegreeFilter,- applyExactStateBarrier,- applyPropertyFilter,- applyScopeFilter,- applyStatusFilter,- applyVisibilityScope,- attachTrustMetadata,- buildTerminalPaths,- readCachedFrontmatter,- supersedeFadeAdjuster,- type FrontmatterCache,-} from "./result-filters.ts";-import { applyRelationPolarityPhase, applyTraversal } from "./graph-phases.ts";-import { buildEvidenceVerification, coverageOverChunks } from "./evidence-verification.ts";--/**- * A compact fingerprint of the resolved-config fields that change search- * results, folded into the cache key so a config change (weights,- * semantic toggle, recall tunables) invalidates cached rows alongside the- * corpus generation. Cache-only knobs (enable/TTL) are excluded - they do- * not change result content.- */-function configFingerprint(config: ResolvedSearchConfig): string {- const r = config.recall;- return JSON.stringify({- kw: config.keywordWeight,- sw: config.semanticWeight,- sem: config.semantic.enabled,- mmr: r.mmrLambda,- hops: r.maxHops,- hopDecay: r.hopDecay,- maxExp: r.maxExpansionPerHit,- rShape: r.recencyShape,- rScale: r.recencyScale,- rAmp: r.recencyAmplitude,- intent: r.intentEnabled,- syn: r.synonymEnabled,- synMax: r.synonymMaxTerms,- relPol: r.relationPolarityEnabled,- relArm: r.relationalArmEnabled,- trustGate: r.retrievalTrustGateEnabled,- supFade: r.supersedeFadeEnabled,- lw: r.learnedWeightsEnabled,- // Cross-encoder rerank re-orders the cached outcome, so a toggle or- // knob change must invalidate cached rows (the endpoint identity is- // omitted - a key rotation on the same model does not change ordering- // semantics, and secrets never belong in a cache key).- rrk: config.rerank.enabled,- rrkModel: config.rerank.model,- rrkTopK: config.rerank.topK,- rrkMin: config.rerank.minScore,- // Trigram prefilter augments the candidate pool, so a toggle or- // selectivity change must invalidate cached rows.- tri: r.trigramPrefilterEnabled,- triMin: r.trigramPrefilterMinChunks,- triSel: r.trigramPrefilterMaxSelectivity,- });-}--function assertSafePathPrefix(prefix: string | undefined): string | undefined {- if (!prefix) return undefined;- if (prefix.includes("..") || prefix.startsWith("/")) {- throw new SearchError("INVALID_INPUT", "path_prefix escapes vault");- }- return prefix;-}--/**- * Open the index for reading, self-healing a stale, absent, or unreadable- * index. After a plugin upgrade the on-disk index can be a different schema- * version (`SCHEMA_MISMATCH`), not yet built (`INDEX_MISSING`), or corrupt- * / truncated / non-OSB at the index path (`INDEX_UNREADABLE`); rather than- * forcing the user to run `o2b search reindex` / `o2b search index`, rebuild- * once and retry. `reindexVault` is imported lazily so the hot path never- * pulls in the indexer and there is no module cycle.- */-async function openReadOrSelfHeal(config: ResolvedSearchConfig): Promise<Store> {- try {- return await Store.open(config, { mode: "read" });- } catch (e) {- if (- e instanceof SearchError &&- (e.code === "INDEX_MISSING" || e.code === "SCHEMA_MISMATCH" || e.code === "INDEX_UNREADABLE")- ) {- try {- const { reindexVault } = await import("./indexer.ts");- await reindexVault(config);- } catch {- // A concurrent writer may already be rebuilding (INDEX_LOCKED), or the- // rebuild failed - fall through and let the retry surface real state.- }- return await Store.open(config, { mode: "read" });- }- throw e;- }-}--/**- * Bounds for the public `limit` option. CLI validates against the same- * ceiling before calling in; MCP applies its own, lower `MCP_LIMIT_MAX`- * (token-budget conscious) - the two ceilings are deliberately different,- * this just gives the shared one a name instead of a bare `100` literal.- */-export const SEARCH_LIMIT_MIN = 1;-export const SEARCH_LIMIT_MAX = 100;+ isRelationalArmActive,+ noRelationalArm,+ runRelationalArm,+} from "./pipeline/relational-arm.ts";+import { resolveSearchRequest } from "./pipeline/request.ts";+import { noSecondPass, runSecondPassRecall } from "./pipeline/second-pass.ts";+import { runSemanticLane } from "./pipeline/semantic-lane.ts";+import { openReadOrSelfHeal } from "./pipeline/store-open.ts";+import { resolveEffectiveWeights } from "./pipeline/weights.ts";+import type { CacheProbe } from "./pipeline/cache-slot.ts";+import type { FrontmatterCache } from "./result-filters.ts";+import { Store } from "./store.ts";+import type { ResolvedSearchConfig, SearchOptions, SearchOutcome } from "./types.ts";++export { SEARCH_LIMIT_MAX, SEARCH_LIMIT_MIN } from "./pipeline/request.ts";++const CACHE_BYPASSED: CacheProbe = { slot: null, hit: null };export async function search(config: ResolvedSearchConfig,opts: SearchOptions,): Promise<SearchOutcome> {- const rawQuery = (opts.query ?? "").trim();- if (!rawQuery) {- throw new SearchError("INVALID_INPUT", "missing required argument: query");- }- // Recall profile (Recall & Working-Memory Quality Suite, t_98c39dd6) and- // opt-in self-tuning (t_ae973491) resolve to the SAME knob tuple, applied- // through applyTunedParameters (which disarms selfTuningEnabled so the- // applied config can never recurse). An explicitly selected profile is an- // operator choice and takes precedence over the persisted grid point; with- // no profile, behaviour is unchanged - self-tuning applies iff enabled. An- // explicit opts.expand always wins over the resolved expansion default.- const profileParams = opts.profile !== undefined ? resolveRecallProfile(opts.profile) : null;- const tuned =- profileParams ?? (config.recall.selfTuningEnabled ? loadTunedParameters(config.vault) : null);- if (tuned !== null) config = applyTunedParameters(config, tuned);- const expandActive = opts.expand ?? (tuned !== null && tuned.expansion);- const limit = Math.max(SEARCH_LIMIT_MIN, Math.min(SEARCH_LIMIT_MAX, opts.limit ?? 10));- if (opts.threshold !== undefined && (!Number.isFinite(opts.threshold) || opts.threshold < 0)) {- throw new SearchError("INVALID_INPUT", "threshold must be a finite number >= 0");- }- const pathPrefix = assertSafePathPrefix(opts.pathPrefix);- const policy = resolveSemanticPolicy(config, opts);- const warnings: string[] = [];- const sessionFocus =- opts.sessionFocus === undefined- ? readActiveSessionFocus(config, opts.focusSession, Date.now())- : opts.sessionFocus;- // One clock for every time-resolving decision in this call, so the hard- // filter and the query-declared window below cannot disagree by a few- // milliseconds of wall-clock drift.- const nowMs = Date.now();- // Time-aware recall (recall-trust-suite): resolve since/until up front- // so invalid input fails fast, before any store I/O.- const timeRange =- opts.since !== undefined || opts.until !== undefined- ? resolveTimeRange({ since: opts.since, until: opts.until }, nowMs)- : null;- // Query-side temporal intent (t_58fc4720). Resolved HERE, from the raw- // query as the caller typed it, and before any store I/O:- //- // - detection must read the ORIGINAL text. Expansion rewrites the- // keyword lane into bare lexical terms, and the `field:value`- // grammar does not survive that rewrite - planning from the- // rewritten text saw no directive while the strip below still- // removed one, so a declared window was voided and its directive- // reached the implicit-AND keyword lane as a term nothing matches;- // - a malformed directive then fails as fast as `since` / `until`- // does, rather than after the index is opened.- //- // From here on the query text is the RESIDUAL text: a directive states- // the window and is not a term, so it must not reach the keyword lane,- // the semantic lane, the coverage gate or the evidence pack. Stripping- // is byte-identical for a query that carries no directive.- const temporalIntent = detectTemporalIntent(rawQuery, nowMs);- const query = stripTemporalDirectives(rawQuery);- if (query === "") {- // A window with nothing to search for. Both lanes would be handed the- // empty string - FTS short-circuits on an empty match and the semantic- // lane embeds "" - so the honest answer is the same one the parameter- // form gives: a window FILTERS a query, it is not a query.- throw new SearchError(- "INVALID_INPUT",- "the query declares a time window and no search terms: " +- "add the terms to look for, or pass the window as the since / until parameters",- );- }+ const request = resolveSearchRequest(config, opts);+ // The resolved knob tuple (recall profile / self-tuning) replaces the+ // caller's config for the rest of the pipeline; `query` is the RESIDUAL+ // text, with any time directive already stripped into `temporalIntent`.+ const {+ config: effectiveConfig,+ query,+ limit,+ pathPrefix,+ policy,+ sessionFocus,+ nowMs,+ timeRange,+ temporalIntent,+ } = request;// Read-only origins (cross-vault search) disable self-healing: a// rebuild would write an index INTO the external vault. Default// (selfHeal absent) keeps the legacy heal-and-retry behaviour.const store =opts.selfHeal === false- ? await Store.open(config, { mode: "read" })- : await openReadOrSelfHeal(config);+ ? await Store.open(effectiveConfig, { mode: "read" })+ : await openReadOrSelfHeal(effectiveConfig);try {- // Shared across every frontmatter-reading filter stage below (Plan 1,- // 1.3) so a candidate path already read by one stage is not re-read+ const warnings: string[] = [];+ // Shared across every frontmatter-reading stage below (Plan 1, 1.3)+ // so a candidate path already read by one stage is not re-read// and re-parsed by the next.const frontmatterCache: FrontmatterCache = new Map();- // Opt-in local expansion (t_2fa95db1): an explicit structured- // document always wins; expansion only fills the gap. The lex lane's- // corpus-common tokens are derived from document frequency here- // (language-agnostic, no stopword list) so an implicit-AND query is- // not killed by a word that is ubiquitous in this vault.- // Expansion reads the RESIDUAL text (see the strip above): a window- // directive is an instruction, so it must never become an expansion- // token, and the residual is byte-identical when no window was- // declared.- const commonTokens =- opts.structuredQuery === undefined && expandActive === true- ? highFrequencyTokens(store, query)- : new Set<string>();- const structured =- opts.structuredQuery ??- (expandActive === true ? expandQuery(config.vault, query, { commonTokens }) : undefined);- const keywordQuery = structuredKeywordQuery(query, structured);- const semanticLaneQuery = structuredSemanticQuery(structured);- // Query plan (v0.20.0): one structural pass yields the intent weight- // profile and the cache key. Expanded terms (if any) are folded in- // once they have been derived from the store below.- const surfaceVocabulary = summarySurfaceVocabulary(config.vault);- const basePlan = buildQueryPlan(- keywordQuery,- [],- structured?.intent,- surfaceVocabulary,+ const shape = resolveQueryShape({+ store,+ vault: effectiveConfig.vault,+ query,+ structuredQuery: opts.structuredQuery,+ expandActive: request.expandActive,nowMs,temporalIntent,- );+ });// Summary-search router (t_7b96f242): a per-query structural decision,// independent of results, so it is resolved once here and echoed on// every outcome below. `default` is omitted from the outcome, keeping// the generic-surface response byte-identical to today.- const routedSurface = basePlan.surface;-- // Persistent query cache (v0.20.0): opt-in. Keyed by the request +- // base plan hash + a config fingerprint, gated by the corpus- // generation and a TTL. A hit returns the previously computed- // outcome; generation changes (embedding change or content reindex)- // and TTL expiry invalidate it. Expansion terms are not in the key:- // they are determined by (query, index content) and any content- // change bumps the generation. The cache write is best-effort.- // A time-filtered query bypasses the cache: a relative range- // ("24h") resolves to a different absolute window on every call, so- // a cached row would serve a stale window within the TTL. A window- // the QUERY declared (`since:24h`) is the same hazard from the other- // direction: its resolved signature is in the plan hash, so every- // call keys differently, never hits, and writes one more row that can- // never be served. Both forms are excluded by the one condition.- const cacheEnabled =- config.recall.cacheEnabled && timeRange === null && temporalIntent === null;- const ttlMs = config.recall.cacheTtlSeconds * 1000;- let cacheKey: string | null = null;- let generation = "";- if (cacheEnabled) {- // The whole cache lookup is best-effort: any failure (e.g. a- // SQLITE_BUSY past the busy_timeout under a concurrent reindex)- // falls through to a normal fresh compute rather than breaking the- // search. Key on the EFFECTIVE request (clamped limit, resolved- // semantic decision) so equivalent calls share a cache entry.- try {- generation = store.corpusGeneration();- const keyOpts = {- ...opts,+ const routedSurface = shape.basePlan.surface;++ // Persistent query cache (v0.20.0): opt-in. A hit returns the+ // previously computed outcome; generation changes (embedding change or+ // content reindex) and TTL expiry invalidate it. The write-back is+ // best-effort.+ const cache = isCacheEligible(effectiveConfig, timeRange, temporalIntent)+ ? probeQueryCache({+ store,+ config: effectiveConfig,+ opts,limit,- semantic: policy.wantSemantic,- keywordOnly: false,+ policy,sessionFocus,- };- // The learned-weights state changes results outside the static- // config, so its fingerprint joins the key (recall-trust-suite).- const lwFp = config.recall.learnedWeightsEnabled- ? learnedWeightsFingerprint(config.vault)- : "off";- // The activation state evolves with recorded accesses the same- // way, so its fingerprint joins too (Time-Aware Recall Suite).- const actFp = config.recall.activationEnabled- ? activationStateFingerprint(config.vault)- : "off";- const tuneFp = tuned !== null ? JSON.stringify(tuned) : "off";- // The reinforce ledger changes results only when the caller opted- // in (Search & Recall Quality Suite); its fingerprint joins the- // key just for those calls so an unrelated ledger write never- // invalidates ordinary searches.- const reinfFp = opts.reinforce !== undefined ? reinforceFingerprint(config.vault) : "off";- // Federation hardening (t_09b7ccea): the query cache scopes by the- // canonical source-set key, so a cache row is never served for a- // different set of origins. Single-vault search draws from one- // origin (this vault).- const srcSet = canonicalSourceSetKey([config.vault]);- cacheKey = buildCacheKey(- keyOpts,- basePlan.planHash,- `${configFingerprint(config)}|lw:${lwFp}|act:${actFp}|tune:${tuneFp}|reinf:${reinfFp}|src:${srcSet}`,- );- const hit = getCachedOutcome(store, cacheKey, generation, ttlMs, Date.now());- if (hit) return hit;- } catch {- cacheKey = null;- }- }+ tuned: request.tuned,+ planHash: shape.basePlan.planHash,+ })+ : CACHE_BYPASSED;+ if (cache.hit !== null) return cache.hit;const finalize = (outcome: SearchOutcome): SearchOutcome => {- if (cacheEnabled && cacheKey) {- try {- store.queryCacheSweep(generation, Date.now() - ttlMs);- putCachedOutcome(store, cacheKey, generation, outcome, Date.now());- } catch {- // Cache persistence is best-effort; never fail a search on it.- }- }+ if (cache.slot !== null) persistCachedOutcome(store, cache.slot, outcome);return outcome;};- // Keyword candidates.- let kwOutcome = runFtsQueryDetailed(store, keywordQuery, {- limit: limit * config.recall.poolMultiplier,+ // Keyword candidates, with the plan the synonym step may have re-built.+ const keywordLane = runKeywordLane({+ store,+ recall: effectiveConfig.recall,+ query,+ keywordQuery: shape.keywordQuery,+ structuredIntent: shape.structured?.intent,+ surfaceVocabulary: shape.surfaceVocabulary,+ nowMs,+ temporalIntent,+ basePlan: shape.basePlan,+ limit,pathPrefix,});- let kwHits = kwOutcome.hits;- for (const w of kwOutcome.warnings) warnings.push(w);+ let keywordHits = keywordLane.hits;+ for (const w of keywordLane.warnings) warnings.push(w);- // Synonym / query expansion (v0.20.0): opt-in and never for an- // exact-intent (quoted/wildcard) query. Derive related terms from- // the top candidates' own content (local co-occurrence) and re-run- // FTS with them OR'd onto the original query to broaden recall. A- // no-op - byte-identical kwHits - when disabled or no term qualifies.- let plan = basePlan;- if (config.recall.synonymEnabled && basePlan.intent !== "exact" && kwHits.length > 0) {- const topIds = kwHits.slice(0, 10).map((h) => h.chunkId);- const ctx = store.hydrateChunks(topIds);- const texts = topIds.map((id) => ctx.get(id)?.content ?? "").filter((t) => t.length > 0);- const expandedTerms = deriveExpansionTerms(tokenizeForExpansion(query), texts, {- ...DEFAULT_EXPANSION,- maxTerms: config.recall.synonymMaxTerms,- });- if (expandedTerms.length > 0) {- plan = buildQueryPlan(- keywordQuery,- expandedTerms,- structured?.intent,- surfaceVocabulary,- nowMs,- temporalIntent,- );- kwOutcome = runFtsQueryDetailed(store, keywordQuery, {- limit: limit * config.recall.poolMultiplier,- pathPrefix,- expandedTerms,- });- kwHits = kwOutcome.hits;- for (const w of kwOutcome.warnings) warnings.push(w);- }- }- // Trigram candidate source (t_4a672b84): opt-in. On large vaults, merge- // substring / partial-token matches the word tokenizer missed into the- // keyword candidate pool. A strict superset of substring matches, so it- // only ADDS candidates (deduped by chunkId; existing keyword hits keep- // their bm25). Skipped for short/CJK/low-selectivity queries and when- // disabled - leaving kwHits byte-identical.- if (- config.recall.trigramPrefilterEnabled &&- store.chunkCount() >= config.recall.trigramPrefilterMinChunks- ) {- const trigramPlan = planTrigramPrefilter(query);- if (trigramPlan.mode === "match") {- const corpus = store.chunkCount();- const cand = store.trigramCandidates(trigramPlan.ftsQuery, {- limit: limit * config.recall.poolMultiplier,- pathPrefix,- });- if (- cand.length > 0 &&- !isLowSelectivity(cand.length, corpus, config.recall.trigramPrefilterMaxSelectivity)- ) {- const seen = new Set(kwHits.map((h) => h.chunkId));- for (const h of cand) {- if (!seen.has(h.chunkId)) {- kwHits.push(h);- seen.add(h.chunkId);- }- }- }- }- }-- const intentProfile = config.recall.intentEnabled ? plan.weightProfile : undefined;- // Learned recall weights (recall-trust-suite): opt-in multipliers- // derived from explicit feedback compose with the intent profile.- // Both factors are bounded, so the product is too; neutral learned- // weights leave ranking bit-identical.- const learned = config.recall.learnedWeightsEnabled ? readLearnedWeights(config.vault) : null;- const learnedActive = learned !== null && !isNeutralLearnedWeights(learned);- const weightProfile = learnedActive- ? composeWeightProfiles(intentProfile, learned)- : intentProfile;+ const { weightProfile, activeLearned } = resolveEffectiveWeights(+ effectiveConfig,+ keywordLane.plan,+ );// Semantic candidates (may be skipped).- let semHits: ReturnType<Store["semanticTopK"]> = [];- let semanticAttempted = false;- if (semanticLaneQuery !== null && !policy.wantSemantic) {- warnings.push("semantic structured lanes skipped: semantic search is disabled");- }- if (policy.wantSemantic) {- const semOutcome = await runSemanticPhase(store, config, semanticLaneQuery ?? query, {- limit: semanticPoolSize(limit),- pathPrefix,- explicit: policy.explicit,- });- semanticAttempted = semOutcome.attempted;- semHits = semOutcome.hits;- for (const w of semOutcome.warnings) warnings.push(w);- // Embedding-ABI drift on the QUERY path (context-integrity-gates,- // Unit E). The read open already ran the gated comparison; until- // now nothing on this path looked at the result, so under the- // shipped `warn` default a caller was served neighbours out of a- // vector table written by another build with nothing to observe.- //- // Attached to the queries it actually describes: only when the- // semantic lane RAN, so a keyword-only query stays byte-identical,- // and only for fields the index CONTRADICTS. An unrecorded token- // is a store predating the stamp - true of every index built- // before this release - and repeating it on every query would- // make the warning worthless; it stays on `search status`,- // `second_brain_status` and `search check`, which is where an- // operator goes looking.- if (semanticAttempted) {- const contradicted = contradictedAbiFields(store.embeddingAbiMismatches());- if (contradicted.length > 0) warnings.push(formatEmbeddingAbiDrift(contradicted));- }- }-- // Hybrid-degrade signal (Search & Recall Quality Suite): one- // structural warning when the caller wanted the semantic lane but it- // did not run, so the query was served keyword-only. The granular- // runSemanticPhase warnings above explain WHY; this is the single- // greppable flag a caller can test for.- {- const degrade = detectHybridDegrade({- wantSemantic: policy.wantSemantic,- semanticAttempted,- keywordHitCount: kwHits.length,- });- if (degrade !== null) warnings.push(degrade);- }+ const semanticLane = await runSemanticLane({+ store,+ config: effectiveConfig,+ policy,+ query,+ semanticLaneQuery: shape.semanticLaneQuery,+ limit,+ pathPrefix,+ keywordHitCount: keywordHits.length,+ });+ let semanticHits = semanticLane.hits;+ for (const w of semanticLane.warnings) warnings.push(w);- // Typed-edge relational arm (t_09b7ccea): a fourth RRF arm. Engages- // ONLY in rrf fusion, when enabled, for a relationship-shaped query (a- // wikilink seed plus a schema-vocabulary edge-type token). A bounded- // depth-2 typed-edge fan-out from the resolved seeds contributes ranked- // related nodes. Off / linear fusion / a non-relational query leaves the- // pool and ranking byte-identical. Source identity from the shared key- // module dedups the lane (federation hardening).- const relationalRankedChunkIds: number[] = [];- const relationalMeta = new Map<number, { via: ReadonlyArray<string>; hops: number }>();- const relationalArmActive =- config.fusionMode === "rrf" && (opts.relationalArm ?? config.recall.relationalArmEnabled);- if (relationalArmActive) {- const relQuery = parseRelationalQuery(query, relationalEdgeVocabulary(config.vault));- if (relQuery !== null) {- const seedDocIds = resolveSeedDocumentIds(store, relQuery.seeds);- if (seedDocIds.length > 0) {- const nodes = relationalFanout(store, seedDocIds, {- maxDepth: RELATIONAL_MAX_DEPTH,- edgeTypes: relQuery.edgeTypes,- });- const reps = store.representativeChunks(nodes.map((n) => n.documentId));- const seenKeys = new Set<string>();- for (const node of nodes) {- const rep = reps.get(node.documentId);- if (rep === undefined) continue;- const key = rrfKey({ origin: null, path: rep.path, chunkId: rep.chunkId });- if (seenKeys.has(key)) continue;- seenKeys.add(key);- relationalRankedChunkIds.push(rep.chunkId);- relationalMeta.set(rep.chunkId, { via: node.viaLinkTypes, hops: node.hops });- }- }- }- }+ // Typed-edge relational arm (t_09b7ccea): a fourth RRF arm, engaged+ // only for a relationship-shaped query under rrf fusion.+ const relational = isRelationalArmActive(effectiveConfig, opts)+ ? runRelationalArm(store, effectiveConfig.vault, query)+ : noRelationalArm();// Hydrate.const allChunkIds = new Set<number>();- for (const h of kwHits) allChunkIds.add(h.chunkId);- for (const h of semHits) allChunkIds.add(h.chunkId);- for (const id of relationalRankedChunkIds) allChunkIds.add(id);- let idsList = Array.from(allChunkIds);-- // Validity-window resolver (hoisted): used both by the time-range- // filter below and by the targeted-retry coverage gate, which must- // judge coverage over the IN-RANGE pool (see below). One cached- // frontmatter read per candidate path.- const validityWindowCache = new Map<string, ValidityWindow | null>();- const validityWindowFor = (path: string): ValidityWindow | null => {- if (validityWindowCache.has(path)) return validityWindowCache.get(path) ?? null;- let window: ValidityWindow | null = null;- try {- const meta = readCachedFrontmatter(frontmatterCache, config.vault, path);- window = parseValidityWindow(meta as Record<string, unknown>);- } catch {- window = null;- }- validityWindowCache.set(path, window);- return window;- };- // Declared EVENT time for a path (unix ms), or null when the page- // declares none: validity start, else validity end. The single- // definition of "event time, storage time only as fallback" shared by- // the temporal bridge and the query-side temporal layer.- const declaredEventTimeMs = (path: string): number | null => {- const window = validityWindowFor(path);- if (window === null || window.invalid) return null;- return window.validFromMs ?? window.validUntilMs;- };-- // Self-correcting two-pass recall (t_ef92dfdc): a zero-candidate- // first pass in evidence-pack mode means the implicit-AND keyword- // match was too strict - the classic abstention dead end. Instead- // of returning empty, run EXACTLY ONE broadened retry that keeps- // the first significant term as the base group and ORs the rest in- // as alternatives, then let the merged pool flow through the normal- // ranking, filters, and a recomputed evidence pack.- let secondPass: SearchOutcome["secondPass"];- // Chunk ids the targeted retry below recovered, so only those- // results (not the first-pass hits they merge with) get the- // second-pass attribution reason.- const targetedChunkIds = new Set<number>();- if (idsList.length === 0 && opts.evidencePack === true && config.recall.twoPassEnabled) {- const terms = significantTerms(query);- if (terms.length >= 2) {- const broadened = runFtsQueryDetailed(store, terms[0]!, {- expandedTerms: terms.slice(1),- limit: semanticPoolSize(limit),- pathPrefix: pathPrefix ?? null,- });- for (const w of broadened.warnings) warnings.push(w);- if (broadened.hits.length > 0) {- kwHits = broadened.hits;- for (const h of kwHits) allChunkIds.add(h.chunkId);- idsList = Array.from(allChunkIds);- secondPass = Object.freeze({- triggered: true,- kind: "broadened",- reason: "zero-candidate first pass; broadened OR retry",- added: kwHits.length,- });- }- }- }-- // Coverage-driven targeted follow-up (t_8eb5ca32): the first pass- // DID return candidates, but their IDF-weighted coverage of the- // query is below the completeness threshold with rare query terms- // still uncovered - a PARTIAL miss, distinct from the zero-candidate- // dead end above. Issue exactly ONE targeted retry built from the- // specifically-uncovered rare terms (not a generic broadening of the- // whole query), merge the recovered candidates into the pool, and- // let them flow through the normal ranking and a recomputed evidence- // pack. Mutually exclusive with the broadened retry above (that needs- // an empty pool, this a non-empty one), so at most one retry fires -- // the same single-retry discipline. The trigger is deterministic and- // LLM-free; the recomputed pack still abstains on any term left- // uncovered after the retry.- if (- secondPass === undefined &&- idsList.length > 0 &&- opts.evidencePack === true &&- config.recall.twoPassEnabled- ) {- // Judge coverage over the pool that will actually survive ranking:- // for a time-scoped query, exclude out-of-range candidates first, so- // a rare term is not marked "covered" only because an out-of-range- // chunk matched it (which would wrongly suppress the retry while the- // final in-range result set still misses that term).- let coverageIds = idsList;- if (timeRange !== null) {- const hydratedForCoverage = store.hydrateChunks(idsList);- coverageIds = idsList.filter((chunkId) => {- const chunk = hydratedForCoverage.get(chunkId);- if (chunk === undefined) return false;- return eventTimeInRange(validityWindowFor(chunk.path), chunk.mtime, timeRange);- });- }- const poolCoverage = coverageOverChunks(store, query, coverageIds);- const retryPlan = planTargetedRetry(poolCoverage);- if (retryPlan.fire) {- const targeted = runFtsQueryDetailed(store, retryPlan.terms[0]!, {- expandedTerms: retryPlan.terms.slice(1),- limit: semanticPoolSize(limit),- pathPrefix: pathPrefix ?? null,- });- for (const w of targeted.warnings) warnings.push(w);- const newHits = targeted.hits.filter((h) => !allChunkIds.has(h.chunkId));- if (newHits.length > 0) {- kwHits = kwHits.concat(newHits);- for (const h of newHits) {- allChunkIds.add(h.chunkId);- targetedChunkIds.add(h.chunkId);- }- idsList = Array.from(allChunkIds);- secondPass = Object.freeze({- triggered: true,- kind: "targeted",- reason: `partial coverage ${poolCoverage.idfWeightedCoverage.toFixed(2)} < ${COMPLETENESS_COMPLETE_THRESHOLD}; targeted retry on uncovered rare terms: ${retryPlan.terms.join(", ")}`,- added: newHits.length,- targetedTerms: retryPlan.terms,- });- }- }- }+ for (const h of keywordHits) allChunkIds.add(h.chunkId);+ for (const h of semanticHits) allChunkIds.add(h.chunkId);+ for (const id of relational.rankedChunkIds) allChunkIds.add(id);++ // One event-time resolver for the whole call: the targeted-retry+ // coverage gate, the hard time filter, the temporal bridge and the+ // ranker's declared-event-time map all judge a page the same way.+ const eventTime = createEventTimeResolver(effectiveConfig.vault, frontmatterCache);++ // Second-pass recall (t_ef92dfdc, t_8eb5ca32): evidence-pack mode only,+ // at most one retry, merged into the pool before ranking.+ const twoPassActive = opts.evidencePack === true && effectiveConfig.recall.twoPassEnabled;+ const retry = twoPassActive+ ? runSecondPassRecall({+ store,+ query,+ limit,+ pathPrefix,+ timeRange,+ validityWindowFor: eventTime.validityWindowFor,+ keywordHits,+ chunkIds: allChunkIds,+ ids: Array.from(allChunkIds),+ })+ : noSecondPass({ keywordHits, ids: Array.from(allChunkIds) });+ keywordHits = retry.keywordHits;+ for (const w of retry.warnings) warnings.push(w);+ const idsList = retry.ids;if (idsList.length === 0) {- const evidencePack =- opts.evidencePack === true- ? buildEvidencePack(query, [], buildEvidenceVerification(store, query, [], pathPrefix))- : undefined;- return finalize(- Object.freeze({- results: Object.freeze([] as ReadonlyArray<BrainSearchResult>),- warnings: Object.freeze(warnings),- total: 0,- ...(evidencePack !== undefined ? { evidencePack } : {}),- ...(routedSurface === "summary" ? { surface: routedSurface } : {}),- }),- );+ return finalize(emptyOutcome({ store, opts, query, pathPrefix, warnings, routedSurface }));}const hydrated = store.hydrateChunks(idsList);- // Time-aware recall (recall-trust-suite): drop out-of-range- // candidates BEFORE ranking so every later phase (traversal seeds,- // MMR, relation polarity) sees only in-range candidates.- // Event-time discipline (t_b7191486): a document declaring- // `valid_from` / `valid_until` is tested by validity-window- // OVERLAP - storage mtime is the fallback, never the authority,- // when explicit event time exists. The `validityWindowFor` resolver- // is hoisted above (shared with the targeted-retry coverage gate); an- // unparseable declared value warns once and falls back to mtime.if (timeRange !== null) {- const warnedInvalid = new Set<string>();- const windowFor = validityWindowFor;- const inRange = (chunkId: number): boolean => {- const h = hydrated.get(chunkId);- if (h === undefined) return false;- const window = windowFor(h.path);- if (window?.invalid === true && !warnedInvalid.has(h.path)) {- warnedInvalid.add(h.path);- warnings.push(`validity: unparseable valid_from/valid_until in ${h.path}; using mtime`);- }- return eventTimeInRange(window, h.mtime, timeRange);- };- kwHits = kwHits.filter((h) => inRange(h.chunkId));- semHits = semHits.filter((h) => inRange(h.chunkId));- }-- const inboundLinkSources = store.inboundLinkSources(idsList);- const tagsByDoc = store.tagsByChunkDocument(idsList);-- // Entity-boosted retrieval (v0.13.0): extract entities from the- // query and count overlaps with each candidate chunk. Empty when the- // query names no entities or the index predates the entity store.- // The canonical entity registry (Memory Integrity Suite) expands the- // set so a query naming an alias also matches chunks naming the- // canonical entity; identity expansion (no registry) keeps ranking- // bit-identical to pre-registry behaviour.- const queryEntities = extractEntities(query);- const entityExpansion = expandQueryEntities(config.vault, queryEntities);- const entityMatchByChunk =- entityExpansion.expanded.length > 0- ? store.chunkEntityMatches(idsList, entityExpansion.expanded)- : undefined;- // Canonical-hop attribution: chunks matching a registry-ADDED form- // carry an explicit reason naming the canonical entity ids below.- const canonicalMatchByChunk =- entityExpansion.added.length > 0- ? store.chunkEntityMatches(idsList, entityExpansion.added)- : undefined;-- // Access-reinforced activation (Time-Aware Recall & Activation- // Suite): map the derived activation state onto the candidate set.- // O(candidates): one state read per query, one frontmatter read per- // candidate path that actually carries activation. The type- // half-life decays the stored strength at read time, so a vault- // without recorded events contributes nothing and ranks- // bit-identically.- let activationByChunk: ReadonlyMap<number, number> | undefined;- let coAccessByChunk: ReadonlyMap<number, ReadonlyMap<number, number>> | undefined;- if (config.recall.activationEnabled) {- const activationState = readActivationState(config.vault);- if (activationState !== null && Object.keys(activationState.paths).length > 0) {- const nowActivationMs = Date.now();- const kindCache = new Map<string, string>();- const kindFor = (path: string): string => {- const cached = kindCache.get(path);- if (cached !== undefined) return cached;- let fmKind: string | null = null;- try {- const meta = readCachedFrontmatter(frontmatterCache, config.vault, path);- const raw = (meta as Record<string, unknown>)["kind"];- fmKind = typeof raw === "string" ? raw : null;- } catch {- fmKind = null;- }- const kind = resolveActivationKind(fmKind, path);- kindCache.set(path, kind);- return kind;- };- const byChunk = new Map<number, number>();- for (const chunkId of idsList) {- const h = hydrated.get(chunkId);- if (h === undefined) continue;- const row = activationState.paths[h.path];- if (row === undefined) continue;- const days = (nowActivationMs - row.lastAccessAt) / (24 * 60 * 60 * 1000);- const act = effectiveActivation(row.strength, days, halfLifeDays(kindFor(h.path)));- if (act > 0) byChunk.set(chunkId, act);- }- if (byChunk.size > 0) activationByChunk = byChunk;- }- // Co-access companions (t_c5ef25a3): restrict the recorded pairs- // to documents present in this candidate set, then hand each- // chunk its companion documentIds with pair counts. Pairs seen- // fewer than CO_ACCESS_MIN_COUNT times are noise and skipped.- if (activationState !== null && activationState.coAccess.length > 0) {- const docIdByPath = new Map<string, number>();- const chunksByDocId = new Map<number, number[]>();- for (const chunkId of idsList) {- const h = hydrated.get(chunkId);- if (h === undefined) continue;- docIdByPath.set(h.path, h.documentId);- const list = chunksByDocId.get(h.documentId) ?? [];- list.push(chunkId);- chunksByDocId.set(h.documentId, list);- }- const companionsByChunk = new Map<number, Map<number, number>>();- const addCompanion = (ownDoc: number, otherDoc: number, count: number): void => {- for (const chunkId of chunksByDocId.get(ownDoc) ?? []) {- const m = companionsByChunk.get(chunkId) ?? new Map<number, number>();- m.set(otherDoc, Math.max(m.get(otherDoc) ?? 0, count));- companionsByChunk.set(chunkId, m);- }- };- for (const pair of activationState.coAccess) {- if (pair.count < CO_ACCESS_MIN_COUNT) continue;- const docA = docIdByPath.get(pair.a);- const docB = docIdByPath.get(pair.b);- if (docA === undefined || docB === undefined) continue;- addCompanion(docA, docB, pair.count);- addCompanion(docB, docA, pair.count);- }- if (companionsByChunk.size > 0) coAccessByChunk = companionsByChunk;- }- }-- // Freshness-trend bias (t_ee09a6ce): preference pages stamped with- // a `freshness_trend` by the dream refresh get a bounded relevance- // multiplier. Restricted to Brain/preferences/ paths - the stamp is- // a preference-lifecycle field, not a generic page property - and- // O(candidate preference pages) frontmatter reads.- // Cache note: like the tier signal, the stamp is read from- // frontmatter at query time and is NOT part of the query-cache key;- // a dream re-stamp reaches cached queries on the next reindex (the- // content change bumps the corpus generation).- let trendByDoc: ReadonlyMap<number, string> | undefined;- {- const byDoc = new Map<number, string>();- const seenDocs = new Set<number>();- for (const chunkId of idsList) {- const h = hydrated.get(chunkId);- if (h === undefined || seenDocs.has(h.documentId)) continue;- seenDocs.add(h.documentId);- if (!h.path.startsWith("Brain/preferences/")) continue;- try {- const meta = readCachedFrontmatter(frontmatterCache, config.vault, h.path);- const trend = parseFreshnessTrend((meta as Record<string, unknown>)["freshness_trend"]);- if (trend !== null) byDoc.set(h.documentId, trend);- } catch {- // Unreadable frontmatter stays neutral.- }- }- if (byDoc.size > 0) trendByDoc = byDoc;- }-- // Observed-reuse boost (t_65588d8b): fold the session-end USED/IGNORED/- // CONTRADICTED verdicts into a per-document reuse score and map it onto- // each candidate chunk. Keyed by path (else id) to match how verdicts- // are recorded. Empty (byte-identical) when no verdicts exist.- let reuseRateByChunk: ReadonlyMap<number, number> | undefined;- {- const reuse = observedReuseRates(config.vault);- if (reuse.size > 0) {- const byChunk = new Map<number, number>();- for (const chunkId of idsList) {- const h = hydrated.get(chunkId);- if (h === undefined) continue;- const entry = reuse.get(h.path) ?? reuse.get(`${h.documentId}:${chunkId}`);- if (entry !== undefined && entry.score > 0) byChunk.set(chunkId, entry.score);- }- if (byChunk.size > 0) reuseRateByChunk = byChunk;- }- }-- // Query-side temporal intent (t_58fc4720): hand the ranker the- // DECLARED event time of every candidate that states one, so the- // temporal layer judges a note by when it is about rather than by- // when it was last written. Candidates with no declaration are- // omitted and the ranker falls back to their mtime; with no window- // declared the map is never built at all.- let eventTimeMsByChunk: ReadonlyMap<number, number> | undefined;- if (temporalIntent !== null) {- const byChunk = new Map<number, number>();- for (const chunkId of idsList) {- const h = hydrated.get(chunkId);- if (h === undefined) continue;- const declared = declaredEventTimeMs(h.path);- if (declared !== null) byChunk.set(chunkId, declared);- }- if (byChunk.size > 0) eventTimeMsByChunk = byChunk;+ const inRange = filterCandidatesInRange({+ hydrated,+ keywordHits,+ semanticHits,+ timeRange,+ validityWindowFor: eventTime.validityWindowFor,+ });+ keywordHits = inRange.keywordHits;+ semanticHits = inRange.semanticHits;+ for (const w of inRange.warnings) warnings.push(w);}- // When a property filter is active, overfetch the ranked- // candidates so the post-filter result set still has a chance- // of producing `limit` matching rows. Without this, the- // top-`limit` ranked hits can lose all their property-matching- // candidates to the filter and surface zero results even when- // matches exist deeper in the rank.- const hasPropertyFilter = opts.properties !== undefined && opts.properties.size > 0;- // Graph-degree cardinality predicates (t_9bee8f0b): a post-rank filter- // that can drop ranked rows, so it shares the frontmatter-filter- // overfetch. Absent / empty leaves the pool and results byte-identical.- const degreeFilters = opts.degreeFilters ?? [];- const hasDegreeFilter = degreeFilters.length > 0;- // An explicit visibility scope can also drop ranked rows, so it- // shares the property filter's overfetch. The default (no scope)- // path does NOT overfetch up front - all-untagged vaults stay- // byte-identical to prior behaviour - and instead relies on the- // one-shot backfill below when tagged pages actually shrink the- // window.- const visibilityScope = normalizeVisibilityScope(opts.visibility ?? []);- const hasVisibilityRequest = (opts.visibility?.length ?? 0) > 0;- // Agent-ownership scope (Unit 5): null means "no scope requested" -- // no ownership filtering, so untagged vaults stay byte-identical.- const agentScope = normalizeAgentScope(opts.agentScope);- const hasAgentScopeRequest = agentScope !== null;- // Composite scope filter (t_37c05a34): session/project axes on top of- // owner. Null when no axis is requested, so an omitted filter never- // narrows the pool (byte-identical default).- const scopeFilter = opts.scope !== undefined ? normalizeScopeFilter(opts.scope) : null;- const hasScopeRequest =- scopeFilter !== null && (scopeFilter.session !== null || scopeFilter.project !== null);- const hasFrontmatterFilter =- hasPropertyFilter ||- hasVisibilityRequest ||- hasAgentScopeRequest ||- hasScopeRequest ||- hasDegreeFilter;-- // MMR and traversal both need a candidate pool wider than `limit`:- // MMR diversifies from it, and traversal seeds expansion from it (a- // narrow pool lets a high-parent expansion crowd a genuine but- // lower-ranked hit out of the final window). When both are disabled- // the pool collapses back to the historical rankLimit.- const hasStructuredExclusions = (structured?.lex.exclude.length ?? 0) > 0;- const mmrLambda = opts.mmrLambda ?? config.recall.mmrLambda;- const mmrActive = mmrLambda < 1;- // Relevance floor + rerank (Search & Recall Quality Suite). The floor- // drops sub-threshold candidates before the diversity rerank so a- // query with no sufficiently relevant memory returns no match; the- // rerank re-orders the qualified set by core textual relevance. Both- // off by default keep results byte-identical.- const scoreFloor = opts.threshold ?? 0;- const rerankActive = opts.rerank === true;- // Cross-encoder rerank (retrieval-precision-quality-loop, card A): the- // learned final reader step re-scores the top-K fused candidates. When- // it is on, the candidate pool must be at least `top_k` wide so a- // genuinely-relevant hit the heuristic ranker placed deep can be pulled- // into the final window. Off by default keeps the pool byte-identical.- const crossEncoderActive = config.rerank.enabled;- const maxHops = opts.maxHops ?? config.recall.maxHops;- const traversalActive = maxHops > 0;- const baseRankLimit =- hasFrontmatterFilter || hasStructuredExclusions ? semanticPoolSize(limit) : limit;- const rankLimit =- mmrActive || traversalActive || crossEncoderActive- ? Math.max(baseRankLimit, limit * 3, 30, crossEncoderActive ? config.rerank.topK : 0)- : baseRankLimit;-- // Rank β traverse β diversify β property filter β visibility scope,- // for a given candidate cap. Returns the pre-visibility count, the- // post-visibility list, and whether the cap was actually hit (so the- // caller can tell "the pool ran out" from "the cap truncated more").- const assemble = (- rankCap: number,- ): {- preVisibility: number;- visible: ReadonlyArray<BrainSearchResult>;- capHit: boolean;- } => {- let ranked = rankResults(- {- keyword: kwHits,- semantic: semHits,- hydrated,- inboundLinkSources,- tagsByDoc,- ...(entityMatchByChunk !== undefined ? { entityMatchByChunk } : {}),- ...(activationByChunk !== undefined ? { activationByChunk } : {}),- ...(coAccessByChunk !== undefined ? { coAccessByChunk } : {}),- ...(trendByDoc !== undefined ? { trendByDoc } : {}),- ...(reuseRateByChunk !== undefined ? { reuseRateByChunk } : {}),- ...(relationalRankedChunkIds.length > 0 ? { relationalRankedChunkIds } : {}),- ...(eventTimeMsByChunk !== undefined ? { eventTimeMsByChunk } : {}),- },- {- keywordWeight: opts.keywordWeight ?? config.keywordWeight,- semanticWeight: opts.semanticWeight ?? config.semanticWeight,- limit: rankCap,- semanticEnabled: policy.wantSemantic && semanticAttempted,- recency: {- shape: config.recall.recencyShape,- scale: config.recall.recencyScale,- amplitude: config.recall.recencyAmplitude,- },- ...(weightProfile !== undefined ? { weightProfile } : {}),- ...(sessionFocus !== undefined ? { sessionFocus } : {}),- fusionMode: config.fusionMode,- rrfK: config.rrfK,- temporalIntent,- },- );- const capHit = ranked.length >= rankCap;- // Retrieval-time staleness barrier (t_b0c9d0a3): drop any exact-state- // lane artifact a stale/older index may still hold, before any later- // phase can surface it. No-op (same reference) when the pool has none,- // so a vault that never used the lane is byte-identical.- ranked = applyExactStateBarrier(ranked).slice();- // Link-graph traversal (v0.13.0): walk outbound links from the top- // hits and surface related documents not already matched, scored by- // decay. No-op when maxHops == 0. Runs before MMR so expansions are- // subject to the same diversity pass.- if (traversalActive && ranked.length > 0) {- ranked = applyTraversal(store, ranked, {- maxHops,- hopDecay: config.recall.hopDecay,- maxExpansionPerHit: config.recall.maxExpansionPerHit,- });- // Temporal bridge (t_c3871f0c): with an active time range,- // traversal expansions must stay within a padded event-time- // neighbourhood of the window - linked causes/consequences- // bridge in with proximity-decayed scores, arbitrary old- // neighbours do not. Event time = validity start, else mtime.- if (timeRange !== null) {- ranked = applyTemporalBridge(ranked, {- range: timeRange,- eventTimeMs: (path) => {- const declared = declaredEventTimeMs(path);- if (declared !== null) return declared;- try {- return statSync(join(config.vault, path)).mtimeMs;- } catch {- return Number.NEGATIVE_INFINITY;- }- },- });- }- }- // Relevance floor (Search & Recall Quality Suite): drop- // sub-threshold candidates BEFORE diversity so the rerank works over- // the qualified set only. No-op when the floor is 0.- if (scoreFloor > 0) {- ranked = ranked.filter((r) => r.score >= scoreFloor);- }- // Diversity rerank (v0.13.0). No-op when lambda >= 1 or < 2 results.- if (mmrActive) {- ranked = mmrRerank(ranked, { lambda: mmrLambda });- }- // Relevance rerank (Search & Recall Quality Suite): re-order the- // qualified set by core textual relevance, a deeper-relevance second- // pass. Opt-in; replaces the diversity ordering when requested.- if (rerankActive) {- ranked = rerankByRelevance(ranked).slice();- }- // Optional post-rank property filter (v0.10.17). Reads each- // result's source frontmatter and drops rows whose scalars do not- // match the requested key/value pairs, then visibility scoping (v3)- // drops pages outside the requested visibility scope. Caching by- // document path bounds the read cost to the result set.- // Belief lifecycle suite (t_7d5a3589): drop tombstoned (incl.- // superseded-non-tip) memories before any other post-rank stage.- // A vault with no tombstoned entries passes through unchanged.- const statusFiltered = applyStatusFilter(ranked, config.vault, frontmatterCache);- const propFiltered = hasPropertyFilter- ? applyPropertyFilter(statusFiltered, opts.properties!, config.vault, frontmatterCache)- : statusFiltered;- // Graph-degree cardinality predicates (t_9bee8f0b): drop rows whose- // backlink/outlink counts fail the predicates, backed by the- // link-graph degree index. No-op when no predicate was requested.- const degreeFiltered = hasDegreeFilter- ? applyDegreeFilter(propFiltered, degreeFilters, store)- : propFiltered;- const visible = applyVisibilityScope(- degreeFiltered,- visibilityScope,- config.vault,- frontmatterCache,- );- // Agent-ownership isolation (Unit 5): only when a scope is requested;- // a null scope skips the filter entirely (byte-identical default).- const scoped =- agentScope !== null- ? applyAgentScope(visible, agentScope, config.vault, frontmatterCache)- : visible;- // Composite session/project scope filter (t_37c05a34): applied only- // when an axis is requested; a null filter skips it entirely so the- // default path is byte-identical.- const compositeScoped = hasScopeRequest- ? applyScopeFilter(scoped, scopeFilter!, config.vault, frontmatterCache)- : scoped;- return { preVisibility: degreeFiltered.length, visible: compositeScoped, capHit };- };-- let assembled = assemble(rankLimit);- // Default-scope visibility (no explicit filter, so no overfetch above)- // can drop tagged pages and leave fewer than `limit` rows while more- // untagged matches sit deeper in the candidate pool. When that happens- // and the narrow cap was actually hit, re-assemble once at the wider- // cap from the same in-memory candidates - no extra DB fetch. Untagged- // vaults never drop rows, so this never fires and their results stay- // byte-identical.- if (- !hasFrontmatterFilter &&- assembled.visible.length < limit &&- assembled.visible.length < assembled.preVisibility &&- assembled.capHit- ) {- const wideCap = Math.max(semanticPoolSize(limit), limit * 3, 30);- if (wideCap > rankLimit) assembled = assemble(wideCap);- }- const excluded = applyStructuredExclusions(assembled.visible, structured);- // Relation polarity (recall-trust-suite): typed relation edges adjust- // the pool BEFORE the final slice so a demoted predecessor can fall- // out of the window and a pulled-in successor can enter it. A pool- // whose documents declare no typed edges passes through untouched.- const polarized = config.recall.relationPolarityEnabled- ? applyRelationPolarityPhase(store, excluded, opts.includeSuperseded === true)- : excluded;- // Self-tuning reinforce (Search & Recall Quality Suite): opt-in. When- // the caller passes a reinforce set, the persisted ledger lifts- // proven-useful memories by a bounded boost BEFORE the top_k cut, so- // a reinforced hit can enter the window. Absent leaves the pool- // untouched; an empty ledger is a no-op either way.- const reinforced =- opts.reinforce !== undefined- ? applyReinforceBoost(polarized, loadReinforceStrengths(config.vault))- : polarized;- // Cross-encoder rerank (retrieval-precision-quality-loop, card A): the- // final reader step, appended AFTER every heuristic rerank. Disabled- // (default) returns the pool unchanged (byte-identical); enabled but- // unconfigured throws a typed config error; enabled + a request-time- // endpoint error degrades to the heuristic ordering and records one- // fail-open telemetry warning. Runs over the widened pool so a deep- // candidate can be promoted into the final `limit` window below.- const reranked = await applyCrossEncoderRerank(reinforced, query, config.rerank, {- onTelemetry: (event) =>- emitGatedTelemetry(event.status === "error", () => {- warnings.push(`rerank_degraded: ${event.reason ?? "endpoint error"}`);- }),+ const signals = collectCandidateSignals({+ store,+ config: effectiveConfig,+ ids: idsList,+ hydrated,+ query,+ frontmatterCache,+ temporalIntentActive: temporalIntent !== null,+ declaredEventTimeMs: eventTime.declaredEventTimeMs,});- // Kernel 1 (t_5f61130a): the deterministic rank-adjustment sink between- // ranking and result emission, mounted on BOTH the semantic and the- // pure-lexical paths (both flow through this single pre-slice pool).- // Registered adjusters return a per-candidate verdict; with none- // registered the pool is returned unchanged, so the default path is- // byte-identical. Runs BEFORE the slice so a gate exclusion lets a- // deeper survivor backfill the window rather than shrinking it.- const rankAdjusters: RankAdjuster[] = [];- if (config.recall.retrievalTrustGateEnabled) {- rankAdjusters.push(- trustGateAdjuster((path) => readCachedFrontmatter(frontmatterCache, config.vault, path)),- );- }- if (config.recall.supersedeFadeEnabled) {- // Relation-only supersede fade (t_c4a9cef8): fetch the pool's typed- // relations once and fade any candidate a `superseded_by` edge marks- // superseded, the same source of truth `attachTrustMetadata` uses.- const poolDocIds = Array.from(new Set(reranked.map((r) => r.documentId)));- const relByPoolDoc = store.typedRelationsForDocuments(poolDocIds);- rankAdjusters.push(supersedeFadeAdjuster((documentId) => relByPoolDoc.get(documentId) ?? []));- }- const adjusted = applyRankAdjusters(reranked, rankAdjusters);- // Per-pack retrieval trust receipts (t_5f61130a): compact references- // consistent with the context-receipt model. Built only when the gate- // ran, so the outcome shape stays byte-identical on the default path.- const trustReceipts = config.recall.retrievalTrustGateEnabled- ? {- retrievalDecisionTrace: buildRetrievalDecisionTrace({- surfaced: adjusted.results.length,- excluded: adjusted.excluded,- }),- memoryTrustAssessment: buildMemoryTrustAssessment({- surfaced: adjusted.results.length,- excluded: adjusted.excluded,- }),- }- : null;- const sliced = adjusted.results.slice(0, limit);- // Explainability: when learned weights affected this ranking, every- // surfaced result says so (acceptance: "search explanations show- // when learned weights affected a result").- const filtered = learnedActive- ? sliced.map((r) =>- Object.freeze({- ...r,- reasons: Object.freeze([...r.reasons, learnedWeightsReason(learned)]),- }),- )- : sliced;- // Typed graph semantics (v3): surface the typed relations each- // result page declares in its frontmatter. Computed here from the- // links table, never stored on the result row. One batched query.- const relByDoc = store.typedRelationsForDocuments(filtered.map((r) => r.documentId));- const withRelations = filtered.map((r) => {- const rels = relByDoc.get(r.documentId);- return rels && rels.length > 0 ? { ...r, relations: Object.freeze(rels) } : r;+ const pool = assembleRankedResults({+ store,+ config: effectiveConfig,+ opts,+ keywordHits,+ semanticHits,+ hydrated,+ signals,+ relationalRankedChunkIds: relational.rankedChunkIds,+ weightProfile,+ sessionFocus,+ semanticEnabled: policy.wantSemantic && semanticLane.attempted,+ structured: shape.structured,+ frontmatterCache,+ timeRange,+ temporalIntent,+ declaredEventTimeMs: eventTime.declaredEventTimeMs,+ limit,});- const withStructuredReasons = addStructuredReasons(withRelations, structured);- // Canonical-entity attribution (Memory Integrity Suite): a hit whose- // chunk matched a registry-added form explains the alias hop. Vaults- // without a registry never reach this branch.- const withCanonicalReasons =- canonicalMatchByChunk !== undefined- ? withStructuredReasons.map((r) =>- (canonicalMatchByChunk.get(r.chunkId) ?? 0) > 0- ? Object.freeze({- ...r,- reasons: Object.freeze([- ...r.reasons,- `entity_canonical: ${entityExpansion.sourceIds.join(", ")}`,- ]),- })- : r,- )- : withStructuredReasons;- // Two-pass attribution (t_ef92dfdc; targeted retry t_8eb5ca32): a- // surfaced result of a retry says so - the operator can tell- // recovered evidence from a first-pass hit. The broadened retry- // replaced the whole pool, so every result is recovered; the- // targeted retry only ADDED candidates, so only those (tracked in- // `targetedChunkIds`) carry the reason - the first-pass hits they- // merge with do not.- const withSecondPassReasons =- secondPass === undefined- ? withCanonicalReasons- : withCanonicalReasons.map((r) => {- if (secondPass.kind === "targeted" && !targetedChunkIds.has(r.chunkId)) return r;- const reason =- secondPass.kind === "targeted"- ? "second_pass: targeted retry on uncovered rare terms"- : "second_pass: or-broadened retry";- return Object.freeze({ ...r, reasons: Object.freeze([...r.reasons, reason]) });- });- // Relational-arm attribution (t_09b7ccea): a node surfaced by the- // typed-edge fan-out carries a reason naming the link types and hop- // distance it was reached by. Empty relationalMeta (arm off) is a no-op.- const withRelationalReasons =- relationalMeta.size === 0- ? withSecondPassReasons- : withSecondPassReasons.map((r) => {- const meta = relationalMeta.get(r.chunkId);- if (meta === undefined) return r;- const reason = `relational: via ${meta.via.join(", ")} (${meta.hops} hop${meta.hops === 1 ? "" : "s"})`;- return Object.freeze({ ...r, reasons: Object.freeze([...r.reasons, reason]) });- });- // Terminal-state downrank (recall-trust-suite) is now structural and- // language-agnostic: a result is terminal when its frontmatter- // `status:` field declares a terminal value (controlled vocabulary),- // never because the note's prose happens to contain an English word- // like "done". One cached frontmatter read per candidate path, only- // in evidence-pack mode.- const terminalPaths =- opts.evidencePack === true- ? buildTerminalPaths(config.vault, withRelationalReasons, frontmatterCache)- : new Set<string>();- const finalResults =- opts.evidencePack === true- ? downrankTerminalEvidenceResults(withRelationalReasons, terminalPaths)- : withRelationalReasons;- const evidencePack =- opts.evidencePack === true- ? buildEvidencePack(- query,- finalResults,- buildEvidenceVerification(store, query, finalResults, pathPrefix),- terminalPaths,- )- : undefined;-- // Access recording (Time-Aware Recall & Activation Suite): the- // orchestrator edge opted in, so persist which documents this query- // surfaced - AFTER ranking, so the current query is never affected- // by its own recording. Cache hits return earlier and never reach- // this point. Best-effort: a failed write never breaks the search.- if (opts.recordAccess === true && config.recall.activationEnabled && finalResults.length > 0) {- const surfacedPaths = Array.from(new Set(finalResults.map((r) => r.path))).slice(- 0,- ACCESS_EVENT_PATHS_CAP,- );- const normalized = query.trim().replace(/\s+/gu, " ").toLowerCase();- try {- recordAccessEvent(config.vault, {- ts: Date.now(),- queryHash: fnv1aHex(normalized),- paths: surfacedPaths,- });- } catch {- warnings.push("activation: failed to record access event");- }- }-- // Inline trust metadata (Search & Recall Quality Suite): opt-in,- // computed at read time from the document mtime and the surfaced- // typed relations, never stored. Off by default keeps the result- // shape byte-identical.- const resultsOut =- opts.trust === true ? attachTrustMetadata(config.vault, finalResults) : finalResults;- // Progressive disclosure (D3): layer 1. When the caller opts into- // `cards`, project the SAME ranked rows into token-cheap cards and- // return them on `cards` with an empty `results`. The ranking,- // filtering, and evidence pack are computed identically to full mode -- // only the surfaced depth differs - so the contract stays- // deterministic and the default `full` path is byte-identical.- if ((opts.disclosure ?? "full") === "cards") {- const cards = resultsOut.map(toSearchCard);- return finalize(- Object.freeze({- results: Object.freeze([] as ReadonlyArray<BrainSearchResult>),- cards: Object.freeze(cards),- warnings: Object.freeze(warnings),- total: cards.length,- ...(evidencePack !== undefined ? { evidencePack } : {}),- ...(secondPass !== undefined ? { secondPass } : {}),- ...(routedSurface === "summary" ? { surface: routedSurface } : {}),- ...trustReceipts,- }),- );- }+ const postRank = await applyPostRankPhases({+ store,+ config: effectiveConfig,+ opts,+ query,+ pool,+ structured: shape.structured,+ frontmatterCache,+ });+ for (const w of postRank.warnings) warnings.push(w);++ const results = decorateFinalResults({+ store,+ results: postRank.results.slice(0, limit),+ structured: shape.structured,+ activeLearned,+ canonicalMatchByChunk: signals.canonicalMatchByChunk,+ canonicalSourceIds: signals.canonicalSourceIds,+ secondPass: retry.secondPass,+ targetedChunkIds: retry.targetedChunkIds,+ relationalReach: relational.reachByChunk,+ });return finalize(- Object.freeze({- results: Object.freeze(resultsOut),- warnings: Object.freeze(warnings),- total: resultsOut.length,- ...(evidencePack !== undefined ? { evidencePack } : {}),- ...(secondPass !== undefined ? { secondPass } : {}),- ...(routedSurface === "summary" ? { surface: routedSurface } : {}),- ...trustReceipts,+ buildSearchOutcome({+ store,+ config: effectiveConfig,+ opts,+ query,+ pathPrefix,+ results,+ warnings,+ secondPass: retry.secondPass,+ routedSurface,+ trustReceipts: postRank.trustReceipts,+ frontmatterCache,}),);} finally {await store.close();}}--/** A token in at least this share of the corpus is treated as common. */-const COMMON_TOKEN_CORPUS_SHARE = 0.5;-/**- * Floor on document frequency before a token can be "common". Below this- * a corpus is too small to tell a stopword-like word from a rare one, so- * nothing is flagged (a 2-document vault must not call a word that appears- * once "ubiquitous").- */-const MIN_COMMON_DOCUMENT_FREQUENCY = 2;--/**- * Corpus-common query tokens, derived from document frequency. A token- * present in at least {@link COMMON_TOKEN_CORPUS_SHARE} of the indexed- * documents (and in at least {@link MIN_COMMON_DOCUMENT_FREQUENCY} of- * them) carries little discriminating signal - in ANY language - so the- * lex expansion lane drops it rather than letting one ubiquitous word- * kill an implicit-AND match. Language-agnostic: no stopword list.- *- * Note: document frequency is measured through the FTS index, whose- * tokenization can differ slightly from `tokenizeForExpansion`. A miss- * only fails to flag a token as common (it stays in the lex lane), so the- * fallback is always the safe, non-lossy direction.- */-/** Bounded typed-edge fan-out depth for the relational arm (t_09b7ccea). */-const RELATIONAL_MAX_DEPTH = 2;--/**- * The recognised edge-type vocabulary for the relational parser: the schema- * pack's declared link types unioned with the default relation vocabulary,- * all normalized. An unreadable pack falls back to the defaults. This is the- * only place edge-type vocabulary enters the search path - never a- * natural-language word list.- */-function relationalEdgeVocabulary(vault: string): string[] {- const vocab = new Set<string>(DEFAULT_RELATION_TYPES.map((t) => normalizeRelation(t)));- try {- for (const t of loadSchemaPack(vault).link_types) vocab.add(normalizeRelation(t));- } catch {- // An unreadable schema pack falls back to the default relation vocabulary.- }- return [...vocab];-}--/**- * The artifact-kind vocabulary for the summary-search router (t_7b96f242):- * the schema pack's declared page types, already normalized. This is the- * ONLY place artifact-kind vocabulary enters the surface router - a- * config-derived token set, never a natural-language word list. An- * unreadable pack yields an empty set, so the router falls back to the- * vocabulary-independent source signal only.- */-function summarySurfaceVocabulary(vault: string): ReadonlySet<string> {- try {- return new Set(loadSchemaPack(vault).vocabulary.page_types.map((t) => t.toLowerCase()));- } catch {- return new Set<string>();- }-}--/**- * Resolve relational-query wikilink seeds to document ids. Tries the exact- * `<seed>.md` path, then the bare seed, then an UNAMBIGUOUS basename match- * anywhere in the tree (an ambiguous basename stays unresolved -- * deterministic inertness beats guessing the wrong page). Deduped.- */-function resolveSeedDocumentIds(store: Store, seeds: ReadonlyArray<string>): number[] {- const out: number[] = [];- const seen = new Set<number>();- let titles: Map<number, { readonly path: string; readonly title: string | null }> | null = null;- for (const seed of seeds) {- let docId = store.getDocumentIdByPath(`${seed}.md`) ?? store.getDocumentIdByPath(seed);- if (docId === null) {- titles ??= store.documentTitles();- const matches: number[] = [];- for (const [id, meta] of titles) {- const base = meta.path.split("/").pop() ?? meta.path;- if (base === `${seed}.md`) matches.push(id);- }- if (matches.length === 1) docId = matches[0]!;- }- if (docId !== null && !seen.has(docId)) {- seen.add(docId);- out.push(docId);- }- }- return out;-}--function highFrequencyTokens(store: Store, query: string): ReadonlySet<string> {- const tokens = [...new Set(tokenizeForExpansion(query))];- if (tokens.length === 0) return new Set();- const documentCount = store.counts().documents;- if (documentCount === 0) return new Set();- const threshold = COMMON_TOKEN_CORPUS_SHARE * documentCount;- const df = store.documentFrequencies(tokens);- const common = new Set<string>();- for (const token of tokens) {- const freq = df.get(token) ?? 0;- if (freq >= MIN_COMMON_DOCUMENT_FREQUENCY && freq >= threshold) common.add(token);- }- return common;-}diff --git a/src/core/search/store.ts b/src/core/search/store.tsindex 8c278113..bdecbe0f 100644--- a/src/core/search/store.ts+++ b/src/core/search/store.ts@@ -10,13 +10,14 @@* - the embedding-model fingerprint check runs in one place at open* time.*+ * The statements themselves live one module per table or lane under+ * `store/`; this file is the connection's lifetime, the vec/lock state+ * those statements need, and the typed surface callers hold.+ ** Anchored in docs/plans/2026-05-16-brain-search-design.md Β§5, Β§15.*/import { Database } from "bun:sqlite";-import { existsSync, mkdirSync, renameSync } from "node:fs";-import { dirname } from "node:path";-import lockfile from "proper-lockfile";import { registerWriterDb, unregisterWriterDb } from "./store-exit.ts";@@ -24,120 +25,70 @@ import { loadIntegrityConfigSafe } from "../brain/policy.ts";import {checkStamp,compareStamps,- formatStampMismatch,STAMP_VERDICT,type StampMismatch,- type StampTokens,} from "../integrity/stamp.ts";-import { computeCorpusGeneration } from "./corpus-generation.ts";import { SearchError } from "./types.ts";import type { ResolvedSearchConfig } from "./types.ts";-import { assertValidVector } from "./vector-guard.ts";-import {- applyMigrations,- documentBasename,- dropVecTable,- ensureVecTable,- LATEST_SCHEMA_VERSION,- readSchemaVersion,-} from "./schema.ts";+import { readSchemaVersion } from "./schema.ts";++import * as aliases from "./store/aliases.ts";+import * as chunkEntities from "./store/chunk-entities.ts";+import * as chunks from "./store/chunks.ts";+import * as census from "./store/counts.ts";+import * as documents from "./store/documents.ts";+import * as abi from "./store/embedding-abi.ts";+import * as keyword from "./store/keyword.ts";+import * as lifecycle from "./store/lifecycle.ts";+import * as links from "./store/links.ts";+import * as queryCache from "./store/query-cache-table.ts";+import * as relations from "./store/relations.ts";+import * as state from "./store/state.ts";+import * as tiers from "./store/tiers.ts";+import * as trigram from "./store/trigram.ts";+import * as vectors from "./store/vectors.ts";// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-// Types+// Public surface re-exported from the per-concern modules// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-/**- * `index_state` keys for the active embedding instruction prefixes- * (memory-write-path-integrity B2). Recorded per index run so a later- * stored-vs-configured mismatch can surface the reindex-required warning:- * vectors embedded under one prefix pair are not comparable to queries- * embedded under another.- */-export const EMBEDDING_PREFIX_QUERY_STATE_KEY = "embedding_prefix_query";-export const EMBEDDING_PREFIX_PASSAGE_STATE_KEY = "embedding_prefix_passage";--/**- * `index_state` keys behind the corpus-generation fingerprint. Named so- * the class accessors and {@link readCorpusGenerationSync} cannot drift- * into two spellings of the same key.- */-export const EMBEDDING_MODEL_STATE_KEY = "embedding_model";-export const EMBEDDING_DIMENSION_STATE_KEY = "embedding_dimension";-export const INDEX_REVISION_STATE_KEY = "index_revision";--/**- * sqlite-vec version the stored vectors were written against- * (context-integrity-gates, Unit E). `SELECT vec_version()` was already- * executed on every extension load and the row discarded every time;- * this key is where it now lands, so the ABI the vectors were produced- * under can be compared later instead of assumed.- */-export const EMBEDDING_VEC_VERSION_STATE_KEY = "embedding_vec_version";--/**- * The single remediation for embedding-ABI drift, named once so the- * store's refusal, the status warning and the `search check`- * recommendation cannot grow three spellings of the same instruction.- */-export const EMBEDDING_ABI_FIX_COMMAND = "o2b search reindex --embeddings";--/**- * `index_state` keys stamped by every index run (`last_indexed_at`) and- * by a FORCED one only (`last_full_index_at`). Both carry the same ISO- * instant when the run was forced, which is what makes their equality a- * usable "the last run resolved the whole vault" predicate - the- * precondition the broken-link ratchet verifies before it trusts a- * dangling count (context-integrity-gates, unit G).- */-export const LAST_INDEXED_AT_STATE_KEY = "last_indexed_at";-export const LAST_FULL_INDEX_AT_STATE_KEY = "last_full_index_at";--/** Vault-wide link-resolution census (see {@link Store.linkResolutionCounts}). */-export interface LinkResolutionCounts {- /**- * Link rows carrying a target path. Tag rows have `target_path IS- * NULL` and are excluded - a tag has nothing to resolve to.- */- readonly total: number;- /**- * Rows the read-time resolution ladder cannot resolve to any- * document - broken links as a reader experiences them.- */- readonly unresolved: number;-}--/**- * The READ-TIME link-resolution ladder, as one SQL expression over a- * `links` row aliased `l`, yielding the resolved document id or NULL.- *- * Three rungs, in order: the materialized `target_document_id` that- * `resolveLinkTargets` / `resolveAliasTargets` wrote, then a- * `<target>.md` exact path match, then an UNAMBIGUOUS nested-basename- * match (`basename = target` with exactly one such nested document -- * a top-level `target.md` has no leading slash and belongs to the exact- * rung above).- *- * Defined once and shared by {@link Store.resolvedDocLinkPairs} (which- * follows it) and {@link Store.linkResolutionCounts} (which counts what- * it leaves over), so "resolvable" and "broken" can never drift apart- * into two different opinions of the same vault.- */-const RESOLVED_LINK_TARGET_SQL =- "COALESCE(" +- " l.target_document_id, " +- " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +- " (SELECT d.id FROM documents d " +- " WHERE d.basename = l.target_path AND instr(d.path, '/') > 0 " +- " AND 1 = (SELECT COUNT(*) FROM documents d2 " +- " WHERE d2.basename = l.target_path AND instr(d2.path, '/') > 0))" +- ")";--/** The query/passage instruction prefixes active for an index run. */-export interface EmbeddingPrefixPair {- readonly query: string;- readonly passage: string;-}+export {+ EMBEDDING_DIMENSION_STATE_KEY,+ EMBEDDING_MODEL_STATE_KEY,+ EMBEDDING_PREFIX_PASSAGE_STATE_KEY,+ EMBEDDING_PREFIX_QUERY_STATE_KEY,+ EMBEDDING_VEC_VERSION_STATE_KEY,+ INDEX_REVISION_STATE_KEY,+ LAST_FULL_INDEX_AT_STATE_KEY,+ LAST_INDEXED_AT_STATE_KEY,+ peekCorpusGenerationSync,+ readCorpusGenerationSync,+} from "./store/state.ts";+export type { IndexPeek } from "./store/state.ts";++export {+ contradictedAbiFields,+ EMBEDDING_ABI_FIX_COMMAND,+ formatEmbeddingAbiDrift,+ readEmbeddingAbiSync,+ runtimeEmbeddingAbi,+} from "./store/embedding-abi.ts";++export {+ acquireWriterLock,+ WRITER_LOCK_HEARTBEAT_MS,+ WRITER_LOCK_STALE_MS,+} from "./store/writer-lock.ts";++export { normalizeAlias } from "./store/aliases.ts";++export type { DocumentInput, DocumentSummary } from "./store/documents.ts";+export type { ChunkInput, ChunkRow, HydratedChunk } from "./store/chunks.ts";+export type { KeywordHit } from "./store/keyword.ts";+export type { LinkInput, LinkResolutionCounts } from "./store/links.ts";+export type { EmbeddingPrefixPair, ModelChangeOutcome, SemanticHit } from "./store/vectors.ts";+export type { StoreCounts } from "./store/counts.ts";export interface StoreOpenOptions {/** "read" never locks; "write" acquires an exclusive proper-lockfile. */@@ -146,506 +97,6 @@ export interface StoreOpenOptions {readonly loadVec?: boolean;}-export interface DocumentInput {- readonly path: string; // vault-relative POSIX- readonly title: string | null;- readonly contentHash: string;- readonly mtime: number; // unix seconds- readonly size: number;- /**- * The page's declared frontmatter `type` (normalized token), or null- * when undeclared. Persisted so link-constraint enforcement can join- * endpoint types without re-reading files (v6).- */- readonly pageType?: string | null;- /**- * Transcript turn instant this note was authored at, in unix seconds- * (conversation chronology, S1 / t_347e8224). Derived from the- * `authored_at` frontmatter field. Absent / null for a note with no- * turn instant, which then ranks byte-identically to pre-feature.- */- readonly authoredAt?: number | null;-}--export interface DocumentSummary {- readonly id: number;- readonly contentHash: string;- readonly mtime: number;- readonly size: number;-}--export interface ChunkInput {- readonly chunkIndex: number;- readonly content: string;- readonly ftsContent?: string;- readonly contentHash: string;- readonly startLine: number;- readonly endLine: number;- readonly tokenCount: number;- /**- * Heading breadcrumb in effect at the chunk (v0.13.0). Indexed in the- * dedicated FTS column; defaults to "" so callers that do not supply- * it (and pre-v0.13.0 fixtures) index an empty heading column.- */- readonly headingPath?: string;-}--export interface ChunkRow {- readonly id: number;- readonly documentId: number;- readonly chunkIndex: number;- readonly content: string;- readonly contentHash: string;- readonly startLine: number;- readonly endLine: number;- readonly tokenCount: number;-}--export interface LinkInput {- readonly sourceChunkId: number | null;- readonly targetPath: string | null;- readonly linkText: string | null;- readonly linkType: "wikilink" | "markdown_link" | "tag";- /**- * Semantic relation type for this edge (v3 / typed graph semantics),- * orthogonal to `linkType`. `null`/absent for plain syntactic links;- * set for frontmatter-relation and MCP-config edges. Validated- * against the open vocabulary in src/core/graph/relation-vocab.ts.- */- readonly relation?: string | null;-}--export interface KeywordHit {- readonly chunkId: number;- readonly documentId: number;- /** Lower is better (FTS5 returns negative bm25). */- readonly bm25: number;-}--export interface SemanticHit {- readonly chunkId: number;- readonly documentId: number;- /** L2 distance on unit-normalised vectors. */- readonly distance: number;-}--export interface HydratedChunk {- readonly chunkId: number;- readonly documentId: number;- readonly path: string;- readonly title: string | null;- readonly content: string;- readonly startLine: number;- readonly endLine: number;- readonly mtime: number;- /**- * Transcript turn instant (unix seconds) or null (conversation- * chronology, S1). Feeds the exact-tie recency tie-break in the ranker- * and is surfaced on the search result. Null for notes with no turn- * instant, keeping their ordering byte-identical.- */- readonly authoredAt?: number | null;-}--export interface StoreCounts {- readonly documents: number;- readonly chunks: number;- readonly embeddings: number;- /** Embeddings whose `model`/`dimension` no longer match the current config. */- readonly staleEmbeddings: number;-}--export interface ModelChangeOutcome {- readonly wasChanged: boolean;- readonly previousModel: string | null;- readonly previousDimension: number | null;- readonly currentModel: string | null;- readonly currentDimension: number | null;-}--// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-// Helpers-// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--function applyPragmas(db: Database): void {- db.exec("PRAGMA journal_mode = WAL");- db.exec("PRAGMA foreign_keys = ON");- db.exec("PRAGMA synchronous = NORMAL");- // Wait briefly for a concurrent writer (e.g. an indexer holding the WAL- // write lock) instead of failing immediately with SQLITE_BUSY. Matters- // for the opportunistic query-cache writes a read-mode connection makes- // during search (v0.20.0); search itself also degrades gracefully.- db.exec("PRAGMA busy_timeout = 5000");-}--function ensureFts5(db: Database): void {- // Probe FTS5 by attempting a benign expression. bun:sqlite ships with- // FTS5 enabled in the embedded amalgamation; failing here means a- // custom build without FTS5 and the index is unusable.- try {- db.query("SELECT fts5_source('chunk_fts')").get();- } catch (e) {- const msg = e instanceof Error ? e.message : String(e);- // Older SQLite returns "no such function" or "no such table" depending- // on whether FTS5 is even compiled in. We treat any failure here as- // FTS5-unavailable rather than guessing the build flag.- if (!/fts5|chunk_fts/i.test(msg)) {- throw new SearchError("INDEX_UNREADABLE", `FTS5 probe failed: ${msg}`);- }- }-}--/**- * Load sqlite-vec and return the version it reports, or `null` when the- * extension is unavailable.- *- * The `vec_version()` probe was always executed and its row always- * discarded; returning it costs nothing and is what lets the ABI the- * vectors were written against be stamped rather than assumed- * (context-integrity-gates, Unit E). `null` doubles as the- * "not loaded" signal, so there is exactly one source of truth for both- * facts.- */-function tryLoadVecExtension(db: Database): string | null {- try {- // sqlite-vec is an optional dependency. Wrap the import + load so- // a missing platform package degrades to "extension unavailable"- // instead of crashing the process.- // eslint-disable-next-line @typescript-eslint/no-require-imports- const vec = require("sqlite-vec") as { getLoadablePath(): string };- db.loadExtension(vec.getLoadablePath());- // Confirm by calling vec_version() β guards against partial loads.- const row = db.query<{ v: string }, []>("SELECT vec_version() AS v").get();- return typeof row?.v === "string" ? row.v : null;- } catch {- return null;- }-}--/**- * Corpus-generation fingerprint read WITHOUT opening a {@link Store}.- *- * `Store.open` is async (the write path acquires a lock) and a read open- * refuses a schema mismatch, so neither form is usable from a- * synchronous caller that only wants to observe the index's identity and- * must keep working when there is no index at all. The context pack's- * provenance stamp (context-integrity-gates, Unit B) is exactly that- * caller. It lives here rather than beside the caller because this- * module is the single SQL boundary for the index.- *- * Returns `null` - "unrecorded", per `integrity/stamp.ts` - when the- * index file is absent or cannot be read. That is DISTINCT from a- * recorded generation string: a vault that gains or loses its index- * drifts from `null` to a value (or back) and the stamp comparison names- * it, rather than treating "nothing to compare" as agreement.- *- * The schema version comes from the file itself, not from- * {@link LATEST_SCHEMA_VERSION}: an index still at an older schema is a- * different corpus state, and folding it onto the current constant would- * hide precisely that.- */-export function readCorpusGenerationSync(dbPath: string): string | null {- const peek = peekCorpusGenerationSync(dbPath);- return peek.kind === "read" ? peek.value : null;-}--/**- * {@link readCorpusGenerationSync} with the three outcomes kept apart, so- * a caller that must not treat a corrupt index as "no index" can tell.- */-export function peekCorpusGenerationSync(dbPath: string): IndexPeek<string | null> {- return peekReadonlyIndex(dbPath, (read, db) => {- const dimRaw = read(EMBEDDING_DIMENSION_STATE_KEY);- const dim = dimRaw === null ? null : Number(dimRaw);- const revRaw = read(INDEX_REVISION_STATE_KEY);- const rev = revRaw === null ? 0 : Number(revRaw);- return computeCorpusGeneration({- embeddingModel: read(EMBEDDING_MODEL_STATE_KEY),- embeddingDimension: dim !== null && Number.isFinite(dim) ? dim : null,- schemaVersion: readSchemaVersion(db),- indexRevision: Number.isFinite(rev) && rev >= 0 ? Math.floor(rev) : 0,- });- });-}--/**- * Embedding-ABI tokens recorded in an index, without opening a- * {@link Store}.- *- * `indexCheck` needs these and cannot get them from its own probe: it- * deliberately runs against an IN-MEMORY database and never touches the- * real index, so a stored-versus-runtime comparison there has no stored- * side unless one is read explicitly.- *- * `null` means the index is absent or unreadable - not that its ABI- * matches.- */-export function readEmbeddingAbiSync(dbPath: string): StampTokens | null {- return withReadonlyIndex(dbPath, (read) => recordedEmbeddingAbi(read));-}--/**- * Outcome of a synchronous peek at the index.- *- * ABSENT and UNREADABLE used to collapse to one `null`, which is wrong- * for a stamp: "no index here" and "an index that exists and is corrupt"- * are different states of the world, and a caller that records both as- * unrecorded makes two such sides compare EQUAL - "two unrecorded sides- * are not a finding" - so a corrupt index silently agrees with a missing- * one. They are now separate arms and the caller chooses.- */-export type IndexPeek<T> =- | { readonly kind: "read"; readonly value: T }- | { readonly kind: "absent" }- | { readonly kind: "unreadable"; readonly detail: string };--/**- * Run `read` against a read-only handle on the index, naming which of- * the three outcomes occurred. Shared by the synchronous peeks so the- * classification lives in one place rather than once per caller.- */-function peekReadonlyIndex<T>(- dbPath: string,- read: (state: (key: string) => string | null, db: Database) => T,-): IndexPeek<T> {- if (!existsSync(dbPath)) return { kind: "absent" };- let db: Database;- try {- db = new Database(dbPath, { readonly: true });- } catch (e) {- return { kind: "unreadable", detail: e instanceof Error ? e.message : String(e) };- }- try {- return {- kind: "read",- value: read(- (key: string): string | null =>- db- .query<{ value: string }, [string]>("SELECT value FROM index_state WHERE key = ?")- .get(key)?.value ?? null,- db,- ),- };- } catch (e) {- return { kind: "unreadable", detail: e instanceof Error ? e.message : String(e) };- } finally {- try {- db.close();- } catch {- /* a close failure cannot change what was already read */- }- }-}--/**- * {@link peekReadonlyIndex} collapsed to `T | null` for the callers that- * genuinely cannot act on the distinction.- */-function withReadonlyIndex<T>(- dbPath: string,- read: (state: (key: string) => string | null, db: Database) => T,-): T | null {- const peek = peekReadonlyIndex(dbPath, read);- return peek.kind === "read" ? peek.value : null;-}--/** The ABI tokens an index recorded, read through any state accessor. */-function recordedEmbeddingAbi(state: (key: string) => string | null): StampTokens {- return {- [EMBEDDING_MODEL_STATE_KEY]: state(EMBEDDING_MODEL_STATE_KEY),- [EMBEDDING_DIMENSION_STATE_KEY]: state(EMBEDDING_DIMENSION_STATE_KEY),- [EMBEDDING_VEC_VERSION_STATE_KEY]: state(EMBEDDING_VEC_VERSION_STATE_KEY),- };-}--/**- * The ABI tokens the CURRENT build and configuration would produce. The- * counterpart of {@link recordedEmbeddingAbi}, kept beside it so the two- * sides of the comparison can never cover different fields.- */-export function runtimeEmbeddingAbi(- config: ResolvedSearchConfig,- vecVersion: string | null,-): StampTokens {- return {- [EMBEDDING_MODEL_STATE_KEY]: config.semantic.model,- [EMBEDDING_DIMENSION_STATE_KEY]:- config.semantic.dimension === null ? null : String(config.semantic.dimension),- [EMBEDDING_VEC_VERSION_STATE_KEY]: vecVersion,- };-}--/**- * The subset of an ABI comparison the index actually CONTRADICTS: it- * recorded a token and that token disagrees with this build.- *- * A mismatch whose recorded side is `null` is an UNRECORDED field - a- * store written before that token was stamped. An absent marker cannot- * tell an old store from a wrong one, so it is reported on the- * diagnostic surfaces and never drives a refusal or a per-read warning.- * Both consumers of that distinction (the `fail` verdict's refusal and- * the query path's warning) route through here rather than restating- * the predicate, so they cannot drift on what counts as contradicted.- */-export function contradictedAbiFields(- mismatches: ReadonlyArray<StampMismatch>,-): ReadonlyArray<StampMismatch> {- return mismatches.filter((m) => m.expected !== null);-}--/**- * One operator-facing line for embedding-ABI drift. Shared by the read- * open's refusal, the status warning and the `search check`- * recommendation, so the three cannot describe the same condition- * differently or name different fixes.- */-export function formatEmbeddingAbiDrift(mismatches: ReadonlyArray<StampMismatch>): string {- return (- `embedding ABI drift between the stored index and this build ` +- `(${mismatches.map(formatStampMismatch).join("; ")}); stored vectors are not ` +- `comparable to queries embedded now. Run: ${EMBEDDING_ABI_FIX_COMMAND}`- );-}--/** Parse a JSON-encoded drift value; a corrupt cell surfaces as-is. */-function parseJsonValue(raw: string): unknown {- try {- return JSON.parse(raw);- } catch {- return raw;- }-}--function nowIso(): string {- return new Date().toISOString();-}--/** `?,?,...` placeholder list for a SQL `IN (...)` clause of `items.length` params. */-function sqlPlaceholders(items: ReadonlyArray<unknown>): string {- return items.map(() => "?").join(",");-}--/**- * Stale window for the writer lock (ms). A lock whose mtime is older- * than this is treated as abandoned (crashed holder) and taken over by- * the next writer, so a SIGKILL never wedges the index for longer than- * this window.- */-export const WRITER_LOCK_STALE_MS = 60_000;--/**- * Heartbeat interval (ms): the async writer lock refreshes its mtime- * this often so a legitimate long-running index is never mistaken for- * a stale lock. Must stay below {@link WRITER_LOCK_STALE_MS}. NOTE: the- * per-file document walk is synchronous, so this timer only fires- * across the await points (embed batches); a multi-minute fully- * synchronous walk still relies on the stale window, which 60s amply- * covers for real vaults.- */-export const WRITER_LOCK_HEARTBEAT_MS = 30_000;--function acquireWriterLockSync(path: string): () => void {- const maxAttempts = 10;- const sleepMs = 50;- let lastError: unknown;- for (let attempt = 0; attempt < maxAttempts; attempt++) {- try {- return lockfile.lockSync(path, { stale: WRITER_LOCK_STALE_MS, realpath: false });- } catch (err) {- const code = (err as NodeJS.ErrnoException).code;- if (code !== "ELOCKED") throw err;- lastError = err;- if (attempt < maxAttempts - 1) Bun.sleepSync(sleepMs);- }- }- const msg = lastError instanceof Error ? lastError.message : String(lastError);- throw new SearchError("INDEX_LOCKED", `another writer holds the search index lock: ${msg}`);-}--/**- * Acquire the exclusive writer lock on the LIVE index path. Shared by- * `Store.open({ mode: "write" })` and `reindexVault`'s rebuild+swap so both- * serialise on the SAME lock (keyed on `dbPath`, not on the `.new` staging- * path). Fast-fails to `INDEX_LOCKED` after a few retries rather than- * blocking indefinitely, matching the module's fail-fast contention- * contract. `realpath: false` lets the lock be taken before `dbPath` exists- * (a fresh reindex has no live index yet); only the parent directory must- * already exist.- */-export async function acquireWriterLock(dbPath: string): Promise<() => Promise<void>> {- try {- return await lockfile.lock(dbPath, {- retries: { retries: 3, factor: 1, minTimeout: 1000, maxTimeout: 1000 },- stale: WRITER_LOCK_STALE_MS,- // Explicit heartbeat: refresh the lock mtime mid-run so a long index- // is never mistaken for a stale lock and taken over.- update: WRITER_LOCK_HEARTBEAT_MS,- realpath: false,- });- } catch (e) {- const msg = e instanceof Error ? e.message : String(e);- throw new SearchError("INDEX_LOCKED", `another writer holds the search index lock: ${msg}`);- }-}--/**- * Crash-recovery preamble shared by every {@link Store.open}: if the live- * index file is absent but a `.bak` from a `reindex` rename swap is present,- * restore it. Guarded by the SAME writer lock `reindexVault` holds across- * its swap, so a read that opens during the swap's brief db-absent window- * cannot mistake it for a crashed reindex and clobber the freshly built- * index with the stale `.bak` (the silent-data-loss race, A.2).- *- * Lock semantics distinguish the two cases without a heuristic:- * - a live reindex mid-swap holds a heartbeated (non-stale) lock, so we- * block briefly, then find `dbPath` present and skip the restore;- * - a genuine crash leaves a stale lock (no heartbeat) that is taken over- * within the stale window, after which we restore.- * If the lock cannot be taken at all we skip the restore rather than risk a- * clobber; the caller's open path then re-evaluates existence and reports- * honestly (INDEX_MISSING). The `.bak` restore of a genuine crash is- * unaffected: with no live holder the lock is acquired immediately.- */-function restoreFromBakIfMissing(dbPath: string): void {- const bak = dbPath + ".bak";- if (existsSync(dbPath) || !existsSync(bak)) return;- let release: (() => void) | null = null;- try {- release = acquireWriterLockSync(dbPath);- } catch {- // A live writer holds the lock (mid-swap). Do not restore β the swap- // will place the fresh index; the open path re-checks existence.- return;- }- try {- // Re-check under the lock: the swap may have completed while we waited,- // or another opener may have already restored.- if (existsSync(dbPath) || !existsSync(bak)) return;- renameSync(bak, dbPath);- // eslint-disable-next-line no-console- console.error(`restored search index from ${bak} (previous reindex crash)`);- } catch {- /* fall through β open path below will report INDEX_MISSING */- } finally {- release();- }-}--/**- * Canonical alias/lookup-key normalisation for `doc_aliases` (v7):- * trim, NFC-normalise, lower-case - the exact rule- * `link-graph/alias-index.ts` applies on the Brain-artifact side, so- * the two alias surfaces never disagree on a key.- */-export function normalizeAlias(value: string): string {- return value.trim().normalize("NFC").toLowerCase();-}--function vecToBuffer(values: ReadonlyArray<number> | Float32Array): Buffer {- const arr = values instanceof Float32Array ? values : Float32Array.from(values);- return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);-}-// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// Store// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -654,7 +105,7 @@ export class Store {private db: Database;private readonly config: ResolvedSearchConfig;private readonly loadedVecVersion: string | null;- private readonly _vecLoaded: boolean;+ private readonly vecExtensionLoaded: boolean;private readonly release: (() => Promise<void>) | null;private closed = false;/** Empty unless a gated read-mode open found ABI drift; see {@link embeddingAbiMismatches}. */@@ -671,7 +122,7 @@ export class Store {this.loadedVecVersion = vecVersion;// One source of truth: the version is present exactly when the// extension loaded, so "loaded" is derived rather than tracked twice.- this._vecLoaded = vecVersion !== null;+ this.vecExtensionLoaded = vecVersion !== null;this.release = release;}@@ -683,48 +134,12 @@ export class Store {// read opening during a live reindex's swap window cannot clobber the// freshly built index with the stale `.bak`. Stderr notice (not a thrown// error) so existing tooling keeps working.- restoreFromBakIfMissing(config.dbPath);+ lifecycle.restoreFromBakIfMissing(config.dbPath);if (opts.mode === "read") {- if (!existsSync(config.dbPath)) {- throw new SearchError(- "INDEX_MISSING",- `search index not initialised at ${config.dbPath}. Run: o2b search index`,- );- }- let db: Database;- try {- db = new Database(config.dbPath);- } catch (e) {- const msg = e instanceof Error ? e.message : String(e);- throw new SearchError("INDEX_UNREADABLE", `cannot open ${config.dbPath}: ${msg}`);- }+ const opened = lifecycle.openReadDatabase(config, loadVec);try {- applyPragmas(db);- ensureFts5(db);- let version: number;- try {- version = readSchemaVersion(db);- } catch (e) {- // A corrupt or non-OSB sqlite file at the index path can make- // readSchemaVersion throw raw SQLITE errors (e.g. "no such- // table: index_state"). Surface those as a typed- // INDEX_UNREADABLE so callers see a code, not a stray Error.- if (e instanceof SearchError) throw e;- const msg = e instanceof Error ? e.message : String(e);- throw new SearchError(- "INDEX_UNREADABLE",- `cannot read schema_version from ${config.dbPath}: ${msg}`,- );- }- if (version !== LATEST_SCHEMA_VERSION) {- throw new SearchError(- "SCHEMA_MISMATCH",- `index schema version ${version} != ${LATEST_SCHEMA_VERSION}. Run: o2b search reindex`,- );- }- const vecVersion = loadVec ? tryLoadVecExtension(db) : null;- const store = new Store(db, config, vecVersion, null);+ const store = new Store(opened.db, config, opened.vecVersion, null);// The read path is where the silent-garbage window actually is:// `ensureEmbeddingModel` runs only on a write open, so every MCP// query reached `semanticTopK` - and a `chunk_vec` of unknown@@ -732,56 +147,30 @@ export class Store {store.resolveEmbeddingAbi();return store;} catch (e) {- db.close();+ opened.db.close();throw e;}}- // mode === "write"- mkdirSync(dirname(config.dbPath), { recursive: true });- if (!existsSync(config.dbPath)) {- const seed = new Database(config.dbPath);- seed.close();- }-- const release = await acquireWriterLock(config.dbPath);-- let db: Database;+ const opened = await lifecycle.openWriteDatabase(config, loadVec);try {- db = new Database(config.dbPath);- } catch (e) {- await release();- const msg = e instanceof Error ? e.message : String(e);- throw new SearchError("INDEX_UNREADABLE", `cannot open ${config.dbPath}: ${msg}`);- }-- try {- applyPragmas(db);- applyMigrations(db, { ftsTokenize: config.ftsTokenize });- ensureFts5(db);- const vecVersion = loadVec ? tryLoadVecExtension(db) : null;- const store = new Store(db, config, vecVersion, release);+ const store = new Store(opened.db, config, opened.vecVersion, opened.release);store.ensureEmbeddingModel(config.semantic.model, config.semantic.dimension, {query: config.semantic.queryPrefix ?? "",passage: config.semantic.passagePrefix ?? "",});// Belt-and-suspenders: consolidate this writer's WAL on a// bypassed close (process.exit / signal-driven exit).- registerWriterDb(db);+ registerWriterDb(opened.db);return store;} catch (e) {- try {- db.close();- } catch {- /* ignore close errors */- }- await release();+ await lifecycle.abandonWriteDatabase(opened.db, opened.release);throw e;}}vecLoaded(): boolean {- return this._vecLoaded;+ return this.vecExtensionLoaded;}/** sqlite-vec version this connection loaded, or null when unavailable. */@@ -829,16 +218,16 @@ export class Store {*/private resolveEmbeddingAbi(): void {if (!this.config.semantic.enabled) return;- const recorded = recordedEmbeddingAbi((key) => this.getState(key));- const runtime = runtimeEmbeddingAbi(this.config, this.loadedVecVersion);+ const recorded = abi.recordedEmbeddingAbi((key) => this.getState(key));+ const runtime = abi.runtimeEmbeddingAbi(this.config, this.loadedVecVersion);if (compareStamps(recorded, runtime).length === 0) return;const mode = loadIntegrityConfigSafe(this.config.vault).embedding_abi;const check = checkStamp(recorded, runtime, mode);this.abiDrift = check.mismatches;if (check.verdict !== STAMP_VERDICT.fail) return;- const drifted = contradictedAbiFields(check.mismatches);+ const drifted = abi.contradictedAbiFields(check.mismatches);if (drifted.length === 0) return;- throw new SearchError("EMBEDDING_DIMENSION_MISMATCH", formatEmbeddingAbiDrift(drifted));+ throw new SearchError("EMBEDDING_DIMENSION_MISMATCH", abi.formatEmbeddingAbiDrift(drifted));}schemaVersion(): number {@@ -851,24 +240,7 @@ export class Store {// Orderly close owns consolidation below; drop the exit-hook entry.unregisterWriterDb(this.db);try {- // Writer mode: consolidate WAL into the main file and switch back to- // DELETE journal mode so the `-wal`/`-shm` siblings are removed. This- // matters for `reindexVault`: after the temp-file rename swap, any- // orphan `*-wal` next to the new main would trigger- // SQLITE_IOERR_SHORT_READ on the next open.- if (this.release) {- try {- this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");- this.db.exec("PRAGMA journal_mode = DELETE");- } catch (e) {- // Don't fail the close, but make the failure visible β an- // unconsolidated WAL is the exact thing that triggers- // SQLITE_IOERR_SHORT_READ after a `reindexVault` rename swap.- const msg = e instanceof Error ? e.message : String(e);- // eslint-disable-next-line no-console- console.error(`search store: WAL consolidation failed on close: ${msg}`);- }- }+ if (this.release) lifecycle.consolidateWal(this.db);this.db.close();} finally {if (this.release) await this.release();@@ -878,36 +250,27 @@ export class Store {// ββ index_state KV βββββββββββββββββββββββββββββββββββββββββββββββββββββββββgetState(key: string): string | null {- const row = this.db- .query<{ value: string }, [string]>("SELECT value FROM index_state WHERE key = ?")- .get(key);- return row?.value ?? null;+ return state.getState(this.db, key);}setState(key: string, value: string): void {- this.db.run(- "INSERT INTO index_state(key, value, updated_at) VALUES (?, ?, ?) " +- "ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",- [key, value, nowIso()],- );+ state.setState(this.db, key, value);}deleteState(key: string): void {- this.db.run("DELETE FROM index_state WHERE key = ?", [key]);+ state.deleteState(this.db, key);}// ββ index revision + corpus generation (v0.20.0) βββββββββββββββββββββββββββββ/** Monotonic counter bumped on every index mutation; 0 if never set. */indexRevision(): number {- const raw = this.getState(INDEX_REVISION_STATE_KEY);- const n = raw === null ? 0 : Number(raw);- return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;+ return state.indexRevision(this.db);}/** Increment the index revision. Called after a mutating index run. */bumpIndexRevision(): void {- this.setState(INDEX_REVISION_STATE_KEY, String(this.indexRevision() + 1));+ state.bumpIndexRevision(this.db);}/**@@ -916,134 +279,36 @@ export class Store {* embedding change or content reindex invalidates cached results.*/corpusGeneration(): string {- const dimRaw = this.getState(EMBEDDING_DIMENSION_STATE_KEY);- const dim = dimRaw === null ? null : Number(dimRaw);- return computeCorpusGeneration({- embeddingModel: this.getState(EMBEDDING_MODEL_STATE_KEY),- embeddingDimension: dim !== null && Number.isFinite(dim) ? dim : null,- schemaVersion: LATEST_SCHEMA_VERSION,- indexRevision: this.indexRevision(),- });+ return state.corpusGeneration(this.db);}// ββ query cache (v0.20.0) ββββββββββββββββββββββββββββββββββββββββββββββββββββqueryCacheGet(key: string): { generation: string; payload: string; createdAt: number } | null {- const row = this.db- .query<{ generation: string; payload: string; created_at: number }, [string]>(- "SELECT generation, payload, created_at FROM query_cache WHERE cache_key = ?",- )- .get(key);- if (!row) return null;- return {- generation: row.generation,- payload: row.payload,- createdAt: row.created_at,- };+ return queryCache.queryCacheGet(this.db, key);}queryCachePut(key: string, generation: string, payload: string, createdAtMs: number): void {- this.db.run(- "INSERT INTO query_cache(cache_key, generation, payload, created_at) VALUES (?, ?, ?, ?) " +- "ON CONFLICT(cache_key) DO UPDATE SET generation = excluded.generation, " +- "payload = excluded.payload, created_at = excluded.created_at",- [key, generation, payload, createdAtMs],- );+ queryCache.queryCachePut(this.db, key, generation, payload, createdAtMs);}/** Delete rows from a stale generation or created before the cutoff. */queryCacheSweep(currentGeneration: string, expiredBeforeMs: number): void {- this.db.run("DELETE FROM query_cache WHERE generation <> ? OR created_at < ?", [- currentGeneration,- expiredBeforeMs,- ]);+ queryCache.queryCacheSweep(this.db, currentGeneration, expiredBeforeMs);}// ββ documents ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- listDocuments(): Map<string, DocumentSummary> {- const rows = this.db- .query<- {- id: number;- path: string;- content_hash: string;- mtime: number;- size: number;- },- []- >("SELECT id, path, content_hash, mtime, size FROM documents")- .all();- const map = new Map<string, DocumentSummary>();- for (const r of rows) {- map.set(r.path, {- id: r.id,- contentHash: r.content_hash,- mtime: r.mtime,- size: r.size,- });- }- return map;+ listDocuments(): Map<string, documents.DocumentSummary> {+ return documents.listDocuments(this.db);}getDocumentIdByPath(path: string): number | null {- const row = this.db- .query<{ id: number }, [string]>("SELECT id FROM documents WHERE path = ?")- .get(path);- return row?.id ?? null;- }-- upsertDocument(doc: DocumentInput): number {- const now = nowIso();- // SQLite RETURNING on INSERT...ON CONFLICT works in 3.35+; bun:sqlite ships modern SQLite.- const row = this.db- .query<- { id: number },- [- string,- string,- string | null,- string,- number,- number,- string | null,- number | null,- string,- string,- string,- ]- >(- "INSERT INTO documents(path, basename, title, content_hash, mtime, size, page_type, authored_at, created_at, updated_at, indexed_at) " +- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " +- "ON CONFLICT(path) DO UPDATE SET " +- " basename = excluded.basename, " +- " title = excluded.title, " +- " content_hash = excluded.content_hash, " +- " mtime = excluded.mtime, " +- " size = excluded.size, " +- " page_type = excluded.page_type, " +- " authored_at = excluded.authored_at, " +- " updated_at = excluded.updated_at, " +- " indexed_at = excluded.indexed_at " +- "RETURNING id",- )- .get(- doc.path,- documentBasename(doc.path),- doc.title,- doc.contentHash,- doc.mtime,- doc.size,- doc.pageType ?? null,- doc.authoredAt ?? null,- now,- now,- now,- );- if (!row) {- throw new SearchError("INDEX_UNREADABLE", `upsertDocument returned no id for '${doc.path}'`);- }- return row.id;+ return documents.getDocumentIdByPath(this.db, path);+ }++ upsertDocument(doc: documents.DocumentInput): number {+ return documents.upsertDocument(this.db, doc);}/**@@ -1052,10 +317,7 @@ export class Store {* `chunk_vec` virtual table.*/deleteDocument(path: string): void {- const id = this.getDocumentIdByPath(path);- if (id === null) return;- this.purgeVecRowsForDocument(id);- this.db.run("DELETE FROM documents WHERE id = ?", [id]);+ documents.deleteDocument(this.db, this.vecExtensionLoaded, path);}/**@@ -1065,44 +327,23 @@ export class Store {* same-content touch.*/touchDocument(path: string, mtime: number, size: number): void {- const now = nowIso();- this.db.run(- "UPDATE documents SET mtime = ?, size = ?, updated_at = ?, indexed_at = ? WHERE path = ?",- [mtime, size, now, now, path],- );+ documents.touchDocument(this.db, path, mtime, size);+ }++ /**+ * Document id -> { path, title } for every indexed document, reading+ * ONLY the `documents` table (never chunk bodies). The graph query+ * pre-pass uses this for its index-only short-circuit so it can rank and+ * answer from index metadata with zero note bodies hydrated.+ */+ documentTitles(): Map<number, { readonly path: string; readonly title: string | null }> {+ return documents.documentTitles(this.db);}// ββ chunks βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- getChunksByDocument(documentId: number): ChunkRow[] {- const rows = this.db- .query<- {- id: number;- document_id: number;- chunk_index: number;- content: string;- content_hash: string;- start_line: number;- end_line: number;- token_count: number;- },- [number]- >(- "SELECT id, document_id, chunk_index, content, content_hash, start_line, end_line, token_count " +- "FROM chunks WHERE document_id = ? ORDER BY chunk_index",- )- .all(documentId);- return rows.map((r) => ({- id: r.id,- documentId: r.document_id,- chunkIndex: r.chunk_index,- content: r.content,- contentHash: r.content_hash,- startLine: r.start_line,- endLine: r.end_line,- tokenCount: r.token_count,- }));+ getChunksByDocument(documentId: number): chunks.ChunkRow[] {+ return chunks.getChunksByDocument(this.db, documentId);}/**@@ -1110,89 +351,47 @@ export class Store {* removed first; FTS5 stays in sync via the chunks_ai/ad/au triggers.* Returns the new chunk ids in `chunkIndex` order.*/- replaceChunks(documentId: number, chunks: ReadonlyArray<ChunkInput>): number[] {- const ids: number[] = [];- this.db.exec("BEGIN");- try {- this.purgeVecRowsForDocument(documentId);- this.db.run("DELETE FROM chunks WHERE document_id = ?", [documentId]);- const insert = this.db.prepare<- { id: number },- [number, number, string, string, string, number, number, number, string, string, string]- >(- "INSERT INTO chunks(document_id, chunk_index, content, fts_content, content_hash, start_line, end_line, token_count, heading_path, created_at, updated_at) " +- "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",- );- const now = nowIso();- for (const c of chunks) {- const row = insert.get(- documentId,- c.chunkIndex,- c.content,- c.ftsContent ?? c.content,- c.contentHash,- c.startLine,- c.endLine,- c.tokenCount,- c.headingPath ?? "",- now,- now,- );- if (!row) throw new SearchError("INDEX_UNREADABLE", "chunk insert returned no id");- ids.push(row.id);- }- this.db.exec("COMMIT");- } catch (e) {- this.db.exec("ROLLBACK");- throw e;- }- return ids;+ replaceChunks(documentId: number, input: ReadonlyArray<chunks.ChunkInput>): number[] {+ return chunks.replaceChunks(this.db, this.vecExtensionLoaded, documentId, input);}/*** Delete a set of chunks by id. Vec rows removed first.*/deleteChunks(chunkIds: ReadonlyArray<number>): void {- if (chunkIds.length === 0) return;- this.db.exec("BEGIN");- try {- this.purgeVecRowsByChunkIds(chunkIds);- const placeholders = sqlPlaceholders(chunkIds);- this.db.run(`DELETE FROM chunks WHERE id IN (${placeholders})`, chunkIds as number[]);- this.db.exec("COMMIT");- } catch (e) {- this.db.exec("ROLLBACK");- throw e;- }+ chunks.deleteChunks(this.db, this.vecExtensionLoaded, chunkIds);+ }++ /** Ordered chunk ids for one document (surprisal, t_fddfe64a). */+ chunksForDocument(documentId: number): ReadonlyArray<{ id: number; chunkIndex: number }> {+ return chunks.chunksForDocument(this.db, documentId);}- private purgeVecRowsForDocument(documentId: number): void {- if (!this._vecLoaded) return;- const vecRows = this.db- .query<{ vec_rowid: number }, [number]>(- "SELECT vec_rowid FROM chunk_vec_map WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ?)",- )- .all(documentId);- if (vecRows.length === 0) return;- this.purgeVecRowidsRaw(vecRows.map((r) => r.vec_rowid));+ /** Total indexed chunk count - used to judge trigram-prefilter selectivity. */+ chunkCount(): number {+ return chunks.countChunks(this.db);}- private purgeVecRowsByChunkIds(chunkIds: ReadonlyArray<number>): void {- if (!this._vecLoaded || chunkIds.length === 0) return;- const placeholders = sqlPlaceholders(chunkIds);- const vecRows = this.db- .query<{ vec_rowid: number }, number[]>(- `SELECT vec_rowid FROM chunk_vec_map WHERE chunk_id IN (${placeholders})`,- )- .all(...(chunkIds as number[]));- if (vecRows.length === 0) return;- this.purgeVecRowidsRaw(vecRows.map((r) => r.vec_rowid));+ hydrateChunks(chunkIds: ReadonlyArray<number>): Map<number, chunks.HydratedChunk> {+ return chunks.hydrateChunks(this.db, chunkIds);}- private purgeVecRowidsRaw(vecRowids: number[]): void {- if (!this._vecLoaded || vecRowids.length === 0) return;- const placeholders = sqlPlaceholders(vecRowids);- this.db.run(`DELETE FROM chunk_vec WHERE rowid IN (${placeholders})`, vecRowids);+ /**+ * One representative chunk per document - the lowest `chunk_index`,+ * which for markdown is the document head (title / opening section).+ * The traversal layer surfaces this when a linked document is not+ * already a relevance hit.+ */+ representativeChunks(documentIds: ReadonlyArray<number>): Map<number, chunks.HydratedChunk> {+ return chunks.representativeChunks(this.db, documentIds);+ }++ /**+ * Chunks that have no row in `embeddings`. Used by the indexer to+ * populate vectors after a fresh index or after the model-change drop.+ */+ findChunksWithoutEmbeddings(): Array<{ chunkId: number; content: string }> {+ return chunks.findChunksWithoutEmbeddings(this.db);}// ββ embeddings βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -1213,69 +412,15 @@ export class Store {dimension: number,embeddingHash: string,): void {- if (!this._vecLoaded) {- throw new SearchError(- "VEC_EXTENSION_UNAVAILABLE",- "sqlite-vec extension not loaded; cannot store embeddings",- );- }- const len = vector instanceof Float32Array ? vector.length : vector.length;- if (len !== dimension) {- throw new SearchError(- "EMBEDDING_DIMENSION_MISMATCH",- `vector dimension ${len} != configured dimension ${dimension}`,- );- }- assertValidVector(vector, "vecUpsert");- this.db.exec("BEGIN");- try {- const existing = this.db- .query<{ vec_rowid: number }, [number]>(- "SELECT vec_rowid FROM chunk_vec_map WHERE chunk_id = ?",- )- .get(chunkId);- const buf = vecToBuffer(vector);- let vecRowid: number;- if (existing) {- this.db.run("UPDATE chunk_vec SET embedding = ? WHERE rowid = ?", [- buf,- existing.vec_rowid,- ]);- vecRowid = existing.vec_rowid;- } else {- this.db.run("INSERT INTO chunk_vec(embedding) VALUES (?)", [buf]);- const row = this.db.query<{ id: number }, []>("SELECT last_insert_rowid() AS id").get();- if (!row) throw new SearchError("INDEX_UNREADABLE", "chunk_vec insert returned no rowid");- vecRowid = row.id;- this.db.run("INSERT INTO chunk_vec_map(chunk_id, vec_rowid) VALUES (?, ?)", [- chunkId,- vecRowid,- ]);- }- const now = nowIso();- this.db.run(- "INSERT INTO embeddings(chunk_id, model, dimension, embedding_hash, created_at, updated_at) " +- "VALUES (?, ?, ?, ?, ?, ?) " +- "ON CONFLICT(chunk_id) DO UPDATE SET " +- " model = excluded.model, dimension = excluded.dimension, " +- " embedding_hash = excluded.embedding_hash, updated_at = excluded.updated_at",- [chunkId, model, dimension, embeddingHash, now, now],- );- this.db.exec("COMMIT");- } catch (e) {- this.db.exec("ROLLBACK");- throw e;- }- }-- /** Ordered chunk ids for one document (surprisal, t_fddfe64a). */- chunksForDocument(documentId: number): ReadonlyArray<{ id: number; chunkIndex: number }> {- return this.db- .query<{ id: number; chunk_index: number }, [number]>(- "SELECT id, chunk_index FROM chunks WHERE document_id = ? ORDER BY chunk_index ASC",- )- .all(documentId)- .map((r) => ({ id: r.id, chunkIndex: r.chunk_index }));+ vectors.vecUpsert(+ this.db,+ this.vecExtensionLoaded,+ chunkId,+ vector,+ model,+ dimension,+ embeddingHash,+ );}/**@@ -1284,29 +429,16 @@ export class Store {* t_fddfe64a).*/embeddingForChunk(chunkId: number): Float32Array | null {- if (!this.vecLoaded()) return null;- const row = this.db- .query<{ embedding: Uint8Array }, [number]>(- "SELECT v.embedding AS embedding FROM chunk_vec v " +- "JOIN chunk_vec_map m ON m.vec_rowid = v.rowid WHERE m.chunk_id = ?",- )- .get(chunkId);- if (!row) return null;- const bytes = row.embedding;- // Copy instead of viewing: a pooled buffer with a non-4-byte-aligned- // byteOffset would make the Float32Array constructor throw.- return new Float32Array(- bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),- );+ return vectors.embeddingForChunk(this.db, this.vecExtensionLoaded, chunkId);}getEmbeddingHash(chunkId: number): string | null {- const row = this.db- .query<{ embedding_hash: string }, [number]>(- "SELECT embedding_hash FROM embeddings WHERE chunk_id = ?",- )- .get(chunkId);- return row?.embedding_hash ?? null;+ return vectors.getEmbeddingHash(this.db, chunkId);+ }++ /** Number of chunks with a stored embedding row. */+ countEmbeddings(): number {+ return vectors.countEmbeddings(this.db);}/**@@ -1314,16 +446,7 @@ export class Store {* or dimension changes. `chunks` and `chunk_fts` are preserved.*/clearEmbeddings(): void {- this.db.exec("BEGIN");- try {- this.db.run("DELETE FROM embeddings");- this.db.run("DELETE FROM chunk_vec_map");- if (this._vecLoaded) dropVecTable(this.db);- this.db.exec("COMMIT");- } catch (e) {- this.db.exec("ROLLBACK");- throw e;- }+ vectors.clearEmbeddings(this.db, this.vecExtensionLoaded);}/**@@ -1335,155 +458,78 @@ export class Store {ensureEmbeddingModel(model: string | null,dimension: number | null,- prefixes?: EmbeddingPrefixPair,- ): ModelChangeOutcome {- const prevModel = this.getState(EMBEDDING_MODEL_STATE_KEY);- const prevDimRaw = this.getState(EMBEDDING_DIMENSION_STATE_KEY);- const prevDim = prevDimRaw === null ? null : Number(prevDimRaw);-- const modelChanged = prevModel !== null && model !== null && prevModel !== model;- const dimChanged =- prevDim !== null && dimension !== null && Number.isFinite(prevDim) && prevDim !== dimension;-- // A prefix change invalidates stored vectors exactly as a model/dimension- // change does: vectors embedded under the old prefix are not comparable to- // queries embedded under the new one. Reuse the same clear-and-log path.- const prevQueryPrefix = this.getState(EMBEDDING_PREFIX_QUERY_STATE_KEY);- const prevPassagePrefix = this.getState(EMBEDDING_PREFIX_PASSAGE_STATE_KEY);- // Legacy stores predate prefix metadata: absent state (null) means the- // existing vectors were embedded with EMPTY prefixes. Treat missing state- // as the empty pair so a switch to non-empty prefixes (e.g. E5's- // `query:`/`passage:`) is detected as a change and the now-incompatible- // unprefixed vectors are cleared, rather than silently marked compatible.- const effectivePrevQueryPrefix = prevQueryPrefix ?? "";- const effectivePrevPassagePrefix = prevPassagePrefix ?? "";- const prefixChanged =- prefixes !== undefined &&- this.countEmbeddings() > 0 &&- (effectivePrevQueryPrefix !== prefixes.query ||- effectivePrevPassagePrefix !== prefixes.passage);-- if (modelChanged || dimChanged) {- this.clearEmbeddings();- // eslint-disable-next-line no-console- console.error(- `embedding model changed from ${prevModel}/${prevDim} to ${model}/${dimension}, embeddings cleared`,- );- this.deleteState(EMBEDDING_MODEL_STATE_KEY);- this.deleteState(EMBEDDING_DIMENSION_STATE_KEY);- // The recorded sqlite-vec version described the vectors that were- // just cleared, so it must not outlive them: leaving it would- // claim an ABI for storage that no longer holds any.- this.deleteState(EMBEDDING_VEC_VERSION_STATE_KEY);- } else if (prefixChanged) {- // Model/dimension unchanged: the prefix change alone triggers the clear.- this.clearEmbeddings();- // eslint-disable-next-line no-console- console.error(- `embedding prefixes changed from [${effectivePrevQueryPrefix}|${effectivePrevPassagePrefix}] ` +- `to [${prefixes.query}|${prefixes.passage}], embeddings cleared`,- );- }-- if (model !== null) this.setState(EMBEDDING_MODEL_STATE_KEY, model);- if (dimension !== null) this.setState(EMBEDDING_DIMENSION_STATE_KEY, String(dimension));- // Same shape as the model and dimension above: recorded only when- // this build actually has a value. With the extension unavailable- // there is nothing to record, and writing a placeholder would be a- // claim about storage this process never touched.- if (this.loadedVecVersion !== null) {- this.setState(EMBEDDING_VEC_VERSION_STATE_KEY, this.loadedVecVersion);- }- if (prefixes !== undefined) {- this.setState(EMBEDDING_PREFIX_QUERY_STATE_KEY, prefixes.query);- this.setState(EMBEDDING_PREFIX_PASSAGE_STATE_KEY, prefixes.passage);- }-- // (Re)create vec table when we know the dimension and vec is loaded.- if (this._vecLoaded && dimension !== null) {- ensureVecTable(this.db, dimension);- }+ prefixes?: vectors.EmbeddingPrefixPair,+ ): vectors.ModelChangeOutcome {+ return vectors.ensureEmbeddingModel(+ this.db,+ { loaded: this.vecExtensionLoaded, version: this.loadedVecVersion },+ model,+ dimension,+ prefixes,+ );+ }- return Object.freeze({- wasChanged: modelChanged || dimChanged,- previousModel: prevModel,- previousDimension: prevDim,- currentModel: model,- currentDimension: dimension,- });+ semanticTopK(+ queryVector: ReadonlyArray<number> | Float32Array,+ opts: { readonly limit: number; readonly pathPrefix?: string | null },+ ): vectors.SemanticHit[] {+ return vectors.semanticTopK(this.db, this.vecExtensionLoaded, queryVector, opts);}// ββ links ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- replaceLinks(sourceDocumentId: number, links: ReadonlyArray<LinkInput>): void {- this.db.exec("BEGIN");- try {- this.db.run("DELETE FROM links WHERE source_document_id = ?", [sourceDocumentId]);- if (links.length > 0) {- const insert = this.db.prepare<- undefined,- [number, number | null, string | null, string | null, string, string | null, string]- >(- "INSERT INTO links(source_document_id, source_chunk_id, target_path, link_text, link_type, relation, created_at) " +- "VALUES (?, ?, ?, ?, ?, ?, ?)",- );- const now = nowIso();- for (const l of links) {- insert.run(- sourceDocumentId,- l.sourceChunkId,- l.targetPath,- l.linkText,- l.linkType,- l.relation ?? null,- now,- );- }- }- this.db.exec("COMMIT");- } catch (e) {- this.db.exec("ROLLBACK");- throw e;- }+ replaceLinks(sourceDocumentId: number, input: ReadonlyArray<links.LinkInput>): void {+ links.replaceLinks(this.db, sourceDocumentId, input);}resolveLinkTargets(): void {- this.db.run(- "UPDATE links SET target_document_id = (SELECT id FROM documents WHERE documents.path = links.target_path) " +- "WHERE target_path IS NOT NULL",- );+ links.resolveLinkTargets(this.db);}/*** Vault-wide link-resolution census (context-integrity-gates, unit G).- ** `unresolved` counts the link rows that carry a target path and that- * {@link RESOLVED_LINK_TARGET_SQL} - the SAME ladder- * {@link resolvedDocLinkPairs} follows - cannot resolve to any- * document. That is what "broken" means to a reader: a materialized- * id, a `<target>.md` exact match, and an unambiguous basename all- * count as resolved, and only what survives all three rungs is- * reported.- *- * The narrower `target_document_id IS NULL` predicate is NOT used- * here. It also fires on every basename-style `[[note]]`, which the- * ladder resolves perfectly well and which an Obsidian-shaped vault- * is written in - a count that rises on a healthy edit is a gate that- * gets bumped rather than obeyed.- *- * Index-backed on every rung: `idx_links_target_path` bounds the- * scan, `documents.path` is UNIQUE, and the basename rungs- * equality-join `idx_documents_basename`.+ * the read-time resolution ladder cannot resolve to any document -+ * broken links as a reader experiences them.+ */+ linkResolutionCounts(): links.LinkResolutionCounts {+ return links.linkResolutionCounts(this.db);+ }++ /**+ * Every link edge resolved to a (source, target) document-id pair,+ * deduplicated. Unresolvable edges are absent. Read-only; feeds bridge+ * discovery and community detection (link-recall-intelligence).*/- linkResolutionCounts(): LinkResolutionCounts {- const row = this.db- .query<{ total: number; unresolved: number | null }, []>(- "SELECT count(*) AS total, " +- `sum(CASE WHEN ${RESOLVED_LINK_TARGET_SQL} IS NULL THEN 1 ELSE 0 END) AS unresolved ` +- "FROM links l WHERE l.target_path IS NOT NULL",- )- .get();- return Object.freeze({ total: row?.total ?? 0, unresolved: row?.unresolved ?? 0 });+ resolvedDocLinkPairs(): Array<{ readonly source: number; readonly target: number }> {+ return links.resolvedDocLinkPairs(this.db);+ }++ /**+ * For each chunk id, return the document ids that link TO that+ * chunk's document via wikilink or markdown_link. Pure data; the+ * ranker decides how to convert this into a boost.+ */+ inboundLinkSources(candidateChunkIds: ReadonlyArray<number>): Map<number, Set<number>> {+ return links.inboundLinkSources(this.db, candidateChunkIds);+ }++ /**+ * For each source document id, the list of resolved outbound link+ * target document ids (wikilink / markdown_link only; tags and+ * unresolved targets excluded; self-links dropped). Used by the+ * recall traversal layer to walk one or more hops out from a hit.+ */+ outboundLinkTargets(sourceDocumentIds: ReadonlyArray<number>): Map<number, number[]> {+ return links.outboundLinkTargets(this.db, sourceDocumentIds);+ }++ /**+ * For each chunk id, the set of tag link_text values associated with+ * its document. Two chunks "share a tag" iff their tag sets intersect.+ */+ tagsByChunkDocument(candidateChunkIds: ReadonlyArray<number>): Map<number, Set<string>> {+ return links.tagsByChunkDocument(this.db, candidateChunkIds);}// ββ doc aliases (v7, link-recall-intelligence) βββββββββββββββββββββββββββββ@@ -1492,32 +538,13 @@ export class Store {* Replace one document's frontmatter aliases. Values are normalised* via {@link normalizeAlias}; empties and duplicates are dropped.*/- replaceDocAliases(documentId: number, aliases: ReadonlyArray<string>): void {- const normalised = [...new Set(aliases.map(normalizeAlias).filter((a) => a.length > 0))];- this.db.exec("BEGIN");- try {- this.db.run("DELETE FROM doc_aliases WHERE document_id = ?", [documentId]);- if (normalised.length > 0) {- const insert = this.db.prepare<undefined, [number, string]>(- "INSERT OR IGNORE INTO doc_aliases(document_id, alias) VALUES (?, ?)",- );- for (const alias of normalised) insert.run(documentId, alias);- }- this.db.exec("COMMIT");- } catch (e) {- this.db.exec("ROLLBACK");- throw e;- }+ replaceDocAliases(documentId: number, values: ReadonlyArray<string>): void {+ aliases.replaceDocAliases(this.db, documentId, values);}/** Normalised aliases of one document, sorted. */aliasesForDocument(documentId: number): ReadonlyArray<string> {- return this.db- .query<{ alias: string }, [number]>(- "SELECT alias FROM doc_aliases WHERE document_id = ? ORDER BY alias ASC",- )- .all(documentId)- .map((r) => r.alias);+ return aliases.aliasesForDocument(this.db, documentId);}/**@@ -1525,94 +552,13 @@ export class Store {* targets that match a declared alias. Runs AFTER* {@link resolveLinkTargets} so exact path matches always win.*- * Shadowing rule (mirrors `alias-index.ts`): a target that equals a- * real document basename is never alias-resolved - the read-time- * basename fallback owns it. Collisions (two documents claim one- * alias) resolve first-wins by sorted document path. Normalisation- * happens in JS because SQLite `lower()` is ASCII-only.- ** Returns the number of link rows resolved.*/resolveAliasTargets(): number {- const unresolved = this.db- .query<{ target_path: string }, []>(- "SELECT DISTINCT target_path FROM links " +- "WHERE target_document_id IS NULL AND target_path IS NOT NULL " +- "AND link_type = 'wikilink' AND instr(target_path, '/') = 0",- )- .all();- if (unresolved.length === 0) return 0;-- const aliasOwner = this.db.prepare<{ document_id: number }, [string]>(- "SELECT a.document_id AS document_id FROM doc_aliases a " +- "JOIN documents d ON d.id = a.document_id " +- "WHERE a.alias = ? ORDER BY d.path ASC LIMIT 1",- );- // A real document basename owns the target (top-level `target.md` or- // any nested `.../target.md`): both collapse to `basename = target`,- // an index lookup instead of the old `path = target.md OR SUBSTR(...)`- // full scan.- const basenameExists = this.db.prepare<{ id: number }, [string]>(- "SELECT id FROM documents WHERE basename = ? LIMIT 1",- );- const update = this.db.prepare<undefined, [number, string]>(- "UPDATE links SET target_document_id = ? " +- "WHERE target_document_id IS NULL AND target_path = ? AND link_type = 'wikilink'",- );-- let resolved = 0;- this.db.exec("BEGIN");- try {- for (const row of unresolved) {- const key = normalizeAlias(row.target_path);- if (key.length === 0) continue;- // Skip targets a real document basename owns.- if (basenameExists.get(row.target_path)) {- continue;- }- const owner = aliasOwner.get(key);- if (!owner) continue;- update.run(owner.document_id, row.target_path);- resolved += this.db.query<{ n: number }, []>("SELECT changes() AS n").get()?.n ?? 0;- }- this.db.exec("COMMIT");- } catch (e) {- this.db.exec("ROLLBACK");- throw e;- }- return resolved;+ return aliases.resolveAliasTargets(this.db);}- /**- * Every link edge resolved to a (source, target) document-id pair,- * deduplicated, using the same conservative resolution ladder as- * {@link typedRelationEdgesForDocuments}: materialized id first,- * then `<target>.md` exact, then an UNAMBIGUOUS basename suffix.- * Unresolvable edges are absent. Read-only; feeds bridge discovery- * and community detection (link-recall-intelligence).- */- resolvedDocLinkPairs(): Array<{ readonly source: number; readonly target: number }> {- const rows = this.db- .query<{ source: number; target: number | null }, []>(- // The ladder itself lives in RESOLVED_LINK_TARGET_SQL, shared- // with `linkResolutionCounts` so the edges this yields and the- // rows that gate counts as broken are two views of one rule.- "SELECT DISTINCT l.source_document_id AS source, " +- ` ${RESOLVED_LINK_TARGET_SQL} AS target ` +- "FROM links l WHERE l.target_path IS NOT NULL",- )- .all();- const out: Array<{ source: number; target: number }> = [];- for (const r of rows) {- if (r.target !== null) out.push({ source: r.source, target: r.target });- }- return out;- }-- /** Number of chunks with a stored embedding row. */- countEmbeddings(): number {- return this.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM embeddings").get()?.n ?? 0;- }+ // ββ typed relations ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ/*** For each document id, the typed relation edges it declares@@ -1623,44 +569,13 @@ export class Store {typedRelationsForDocuments(documentIds: ReadonlyArray<number>,): Map<number, Array<{ relation: string; target: string }>> {- const out = new Map<number, Array<{ relation: string; target: string }>>();- if (documentIds.length === 0) return out;- const placeholders = sqlPlaceholders(documentIds);- const rows = this.db- .query<- {- source_document_id: number;- relation: string;- target_path: string | null;- },- number[]- >(- "SELECT source_document_id, relation, target_path FROM links " +- `WHERE source_document_id IN (${placeholders}) AND relation IS NOT NULL ` +- "AND relation_blocked = 0 " +- "ORDER BY id",- )- .all(...(documentIds as number[]));- for (const r of rows) {- const target = r.target_path ?? "";- if (target === "") continue;- const arr = out.get(r.source_document_id);- const edge = { relation: r.relation, target };- if (arr) arr.push(edge);- else out.set(r.source_document_id, [edge]);- }- return out;+ return relations.typedRelationsForDocuments(this.db, documentIds);}/*** Typed relation edges declared by the given documents, with the* target resolved to a document id when possible (recall-trust-suite,- * relation polarity). Wikilink-style relation targets are usually bare- * ids (`[[note]]` β `note`) that the generic `resolveLinkTargets`- * exact-path pass cannot match against `note.md`, so this query also- * tries `<target>.md` and β when unambiguous β a basename match.- * Ambiguous basenames stay unresolved (deterministic inertness beats- * guessing the wrong page).+ * relation polarity).*/typedRelationEdgesForDocuments(documentIds: ReadonlyArray<number>): Array<{readonly sourceDocumentId: number;@@ -1668,50 +583,7 @@ export class Store {readonly target: string;readonly targetDocumentId: number | null;}> {- if (documentIds.length === 0) return [];- const placeholders = sqlPlaceholders(documentIds);- const rows = this.db- .query<- {- source_document_id: number;- relation: string;- target_path: string | null;- resolved_target_id: number | null;- },- number[]- >(- "SELECT l.source_document_id, l.relation, l.target_path, " +- " COALESCE(" +- " l.target_document_id, " +- " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +- " (SELECT d.id FROM documents d " +- " WHERE SUBSTR(d.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md' " +- " AND 1 = (SELECT COUNT(*) FROM documents d2 " +- " WHERE SUBSTR(d2.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md'))" +- " ) AS resolved_target_id " +- "FROM links l " +- `WHERE l.source_document_id IN (${placeholders}) AND l.relation IS NOT NULL ` +- "AND l.relation_blocked = 0 " +- "ORDER BY l.id",- )- .all(...(documentIds as number[]));- const out: Array<{- sourceDocumentId: number;- relation: string;- target: string;- targetDocumentId: number | null;- }> = [];- for (const r of rows) {- const target = r.target_path ?? "";- if (target === "") continue;- out.push({- sourceDocumentId: r.source_document_id,- relation: r.relation,- target,- targetDocumentId: r.resolved_target_id,- });- }- return out;+ return relations.typedRelationEdgesForDocuments(this.db, documentIds);}/**@@ -1719,10 +591,8 @@ export class Store {* current schema-pack constraints (write-time-integrity-governance).* Runs after `resolveLinkTargets` on every index pass, so removing a* constraint restores blocked edges on the next run without touching- * files. Endpoint resolution mirrors `typedRelationEdgesForDocuments`- * (exact id, `<target>.md`, unambiguous basename). Returns the rows- * that ended up blocked. With an empty constraint map the pass only- * resets stale flags.+ * files. Returns the rows that ended up blocked. With an empty+ * constraint map the pass only resets stale flags.*/recomputeRelationConstraintFlags(constraints: Readonly<Record<string, ReadonlyArray<string>>>,@@ -1734,68 +604,7 @@ export class Store {readonly targetType: string;readonly declared: ReadonlyArray<string>;}> {- const rows = this.db- .query<- {- id: number;- relation: string;- blocked: number;- source_path: string;- source_type: string | null;- target_path: string | null;- target_type: string | null;- },- []- >(- "SELECT l.id, l.relation, l.relation_blocked AS blocked, " +- " sd.path AS source_path, sd.page_type AS source_type, " +- " l.target_path, td.page_type AS target_type " +- "FROM links l " +- "JOIN documents sd ON sd.id = l.source_document_id " +- "LEFT JOIN documents td ON td.id = COALESCE(" +- " l.target_document_id, " +- " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +- " (SELECT d.id FROM documents d " +- " WHERE SUBSTR(d.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md' " +- " AND 1 = (SELECT COUNT(*) FROM documents d2 " +- " WHERE SUBSTR(d2.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md'))" +- " ) " +- "WHERE l.relation IS NOT NULL",- )- .all();- const block = this.db.query("UPDATE links SET relation_blocked = 1 WHERE id = ?");- const unblock = this.db.query("UPDATE links SET relation_blocked = 0 WHERE id = ?");- const violations: Array<{- relation: string;- sourcePath: string;- targetPath: string;- sourceType: string;- targetType: string;- declared: ReadonlyArray<string>;- }> = [];- for (const row of rows) {- const declared = constraints[row.relation];- const allowed =- declared === undefined ||- declared.length === 0 ||- row.source_type === null ||- row.target_type === null ||- declared.includes(`${row.source_type}->${row.target_type}`);- if (allowed) {- if (row.blocked !== 0) unblock.run(row.id);- continue;- }- if (row.blocked === 0) block.run(row.id);- violations.push({- relation: row.relation,- sourcePath: row.source_path,- targetPath: row.target_path ?? "",- sourceType: row.source_type!,- targetType: row.target_type!,- declared: declared!,- });- }- return violations;+ return relations.recomputeRelationConstraintFlags(this.db, constraints);}/**@@ -1809,69 +618,21 @@ export class Store {readonly sourceType: string | null;readonly targetType: string | null;}> {- return this.db- .query<- {- relation: string;- source_path: string;- target_path: string | null;- source_type: string | null;- target_type: string | null;- },- []- >(- "SELECT l.relation, sd.path AS source_path, l.target_path, " +- " sd.page_type AS source_type, td.page_type AS target_type " +- "FROM links l " +- "JOIN documents sd ON sd.id = l.source_document_id " +- "LEFT JOIN documents td ON td.id = COALESCE(" +- " l.target_document_id, " +- " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " +- " (SELECT d.id FROM documents d " +- " WHERE SUBSTR(d.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md' " +- " AND 1 = (SELECT COUNT(*) FROM documents d2 " +- " WHERE SUBSTR(d2.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md'))" +- " ) " +- "WHERE l.relation IS NOT NULL AND l.relation_blocked = 1 " +- "ORDER BY sd.path, l.id",- )- .all()- .map((r) => ({- relation: r.relation,- sourcePath: r.source_path,- targetPath: r.target_path ?? "",- sourceType: r.source_type,- targetType: r.target_type,- }));+ return relations.blockedRelationRows(this.db);}+ // ββ tiered frontmatter (write-time-integrity-governance) βββββββββββββββββββ+/*** The tiered-frontmatter snapshot the last index pass recorded for a- * document, or null when none exists (write-time-integrity-governance).+ * document, or null when none exists.*/getTierSnapshot(documentId: number): Record<string, unknown> | null {- const row = this.db- .query<{ tier_snapshot: string | null }, [number]>(- "SELECT tier_snapshot FROM documents WHERE id = ?",- )- .get(documentId);- if (!row || row.tier_snapshot === null) return null;- try {- const parsed: unknown = JSON.parse(row.tier_snapshot);- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {- return parsed as Record<string, unknown>;- }- return null;- } catch {- return null;- }+ return tiers.getTierSnapshot(this.db, documentId);}setTierSnapshot(documentId: number, snapshot: Readonly<Record<string, unknown>>): void {- this.db.run("UPDATE documents SET tier_snapshot = ? WHERE id = ?", [- JSON.stringify(snapshot),- documentId,- ]);+ tiers.setTierSnapshot(this.db, documentId, snapshot);}/** Stage one identity-field hand-edit; (document, field) upserts. */@@ -1882,29 +643,11 @@ export class Store {readonly actual: unknown;readonly detectedAt: string;}): void {- this.db.run(- "INSERT INTO tier_drift(document_id, field, expected, actual, detected_at) " +- "VALUES (?, ?, ?, ?, ?) " +- "ON CONFLICT(document_id, field) DO UPDATE SET actual = excluded.actual",- [- input.documentId,- input.field,- JSON.stringify(input.expected),- JSON.stringify(input.actual),- input.detectedAt,- ],- );+ tiers.upsertTierDrift(this.db, input);}clearTierDrift(documentId: number, field?: string): void {- if (field === undefined) {- this.db.run("DELETE FROM tier_drift WHERE document_id = ?", [documentId]);- } else {- this.db.run("DELETE FROM tier_drift WHERE document_id = ? AND field = ?", [- documentId,- field,- ]);- }+ tiers.clearTierDrift(this.db, documentId, field);}/** Open identity-drift findings, oldest first, with document paths. */@@ -1916,83 +659,29 @@ export class Store {readonly actual: unknown;readonly detectedAt: string;}> {- return this.db- .query<- {- document_id: number;- path: string;- field: string;- expected: string;- actual: string;- detected_at: string;- },- []- >(- "SELECT t.document_id, d.path, t.field, t.expected, t.actual, t.detected_at " +- "FROM tier_drift t JOIN documents d ON d.id = t.document_id " +- "ORDER BY t.detected_at, t.id",- )- .all()- .map((r) => ({- documentId: r.document_id,- path: r.path,- field: r.field,- expected: parseJsonValue(r.expected),- actual: parseJsonValue(r.actual),- detectedAt: r.detected_at,- }));+ return tiers.listTierDrift(this.db);}+ // ββ search βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ+/*** Corpus document frequency per term (recall-trust-suite, coverage- * engine): how many distinct documents match each term in FTS. Each- * term is quoted so FTS5 metacharacters stay literal. A term that- * fails to query (e.g. tokenizer edge case) counts as 0 rather than- * failing the search.+ * engine): how many distinct documents match each term in FTS.*/documentFrequencies(terms: ReadonlyArray<string>): Map<string, number> {- const out = new Map<string, number>();- if (terms.length === 0) return out;- const q = this.db.query<{ n: number }, [string]>(- "SELECT COUNT(DISTINCT c.document_id) AS n " +- "FROM chunk_fts JOIN chunks c ON c.id = chunk_fts.rowid " +- "WHERE chunk_fts MATCH ?",- );- for (const term of terms) {- try {- out.set(term, q.get(`"${term.replace(/"/g, '""')}"`)?.n ?? 0);- } catch {- out.set(term, 0);- }- }- return out;+ return keyword.documentFrequencies(this.db, terms);}- // ββ search βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ-ftsIntegrityCounts(): { readonly chunks: number; readonly ftsRows: number } {- const chunks =- this.db.query<{ c: number }, []>("SELECT count(*) AS c FROM chunks").get()?.c ?? 0;- const ftsRows =- this.db.query<{ c: number }, []>("SELECT count(*) AS c FROM chunk_fts_docsize").get()?.c ?? 0;- return Object.freeze({ chunks, ftsRows });+ return keyword.ftsIntegrityCounts(this.db);}rebuildFtsIndex(): void {- this.db.run("INSERT INTO chunk_fts(chunk_fts) VALUES('rebuild')");+ keyword.rebuildFtsIndex(this.db);}rebuildFtsIndexWithWriterLock(): void {- if (this.release) {- this.rebuildFtsIndex();- return;- }- const release = acquireWriterLockSync(this.config.dbPath);- try {- this.rebuildFtsIndex();- } finally {- release();- }+ keyword.rebuildFtsIndexWithWriterLock(this.db, this.config.dbPath, this.release !== null);}/**@@ -2002,318 +691,22 @@ export class Store {keywordTopK(fts5Query: string,opts: { readonly limit: number; readonly pathPrefix?: string | null },- ): KeywordHit[] {- const limit = Math.max(1, opts.limit | 0);- const prefix = opts.pathPrefix && opts.pathPrefix.length > 0 ? opts.pathPrefix : null;-- if (prefix) {- const rows = this.db- .query<- { chunk_id: number; document_id: number; bm25: number },- [string, string, string, number]- >(- "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_fts, 1.0, 0.3) AS bm25 " +- "FROM chunk_fts " +- "JOIN chunks c ON c.id = chunk_fts.rowid " +- "JOIN documents d ON d.id = c.document_id " +- "WHERE chunk_fts MATCH ? AND substr(d.path, 1, length(?)) = ? " +- "ORDER BY bm25 ASC LIMIT ?",- )- .all(fts5Query, prefix, prefix, limit);- return rows.map((r) => ({- chunkId: r.chunk_id,- documentId: r.document_id,- bm25: r.bm25,- }));- }-- const rows = this.db- .query<{ chunk_id: number; document_id: number; bm25: number }, [string, number]>(- "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_fts, 1.0, 0.3) AS bm25 " +- "FROM chunk_fts JOIN chunks c ON c.id = chunk_fts.rowid " +- "WHERE chunk_fts MATCH ? ORDER BY bm25 ASC LIMIT ?",- )- .all(fts5Query, limit);- return rows.map((r) => ({- chunkId: r.chunk_id,- documentId: r.document_id,- bm25: r.bm25,- }));+ ): keyword.KeywordHit[] {+ return keyword.keywordTopK(this.db, fts5Query, opts);}/*** Trigram candidate lookup over the `chunk_trigram` FTS5 shadow (v9).- * Returns bm25-ordered keyword hits whose content matches the trigram- * query - a strict superset of exact substring matches for the query's- * terms, used as an opt-in candidate source that broadens large-vault- * keyword recall (substring / partial-token matches the word tokenizer- * misses). Fails soft to an empty list if the trigram table is absent- * (a migrated-but-not-reindexed index always has it via the v9 rebuild).+ * An opt-in candidate source that broadens large-vault keyword recall+ * with the substring / partial-token matches the word tokenizer misses.+ * Degrades to no candidates - silently when the optional table is+ * absent, with a warning for every other fault.*/trigramCandidates(trigramQuery: string,opts: { readonly limit: number; readonly pathPrefix?: string | null },- ): KeywordHit[] {- const limit = Math.max(1, opts.limit | 0);- const prefix = opts.pathPrefix && opts.pathPrefix.length > 0 ? opts.pathPrefix : null;- try {- if (prefix) {- const rows = this.db- .query<- { chunk_id: number; document_id: number; bm25: number },- [string, string, string, number]- >(- "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_trigram) AS bm25 " +- "FROM chunk_trigram " +- "JOIN chunks c ON c.id = chunk_trigram.rowid " +- "JOIN documents d ON d.id = c.document_id " +- "WHERE chunk_trigram MATCH ? AND substr(d.path, 1, length(?)) = ? " +- "ORDER BY bm25 ASC LIMIT ?",- )- .all(trigramQuery, prefix, prefix, limit);- return rows.map((r) => ({ chunkId: r.chunk_id, documentId: r.document_id, bm25: r.bm25 }));- }- const rows = this.db- .query<{ chunk_id: number; document_id: number; bm25: number }, [string, number]>(- "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_trigram) AS bm25 " +- "FROM chunk_trigram JOIN chunks c ON c.id = chunk_trigram.rowid " +- "WHERE chunk_trigram MATCH ? ORDER BY bm25 ASC LIMIT ?",- )- .all(trigramQuery, limit);- return rows.map((r) => ({ chunkId: r.chunk_id, documentId: r.document_id, bm25: r.bm25 }));- } catch {- return [];- }- }-- /** Total indexed chunk count - used to judge trigram-prefilter selectivity. */- chunkCount(): number {- const row = this.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM chunks").get();- return row?.n ?? 0;- }-- semanticTopK(- queryVector: ReadonlyArray<number> | Float32Array,- opts: { readonly limit: number; readonly pathPrefix?: string | null },- ): SemanticHit[] {- if (!this._vecLoaded) {- throw new SearchError(- "VEC_EXTENSION_UNAVAILABLE",- "sqlite-vec extension not loaded; semantic search unavailable",- );- }- const limit = Math.max(1, opts.limit | 0);- const prefix = opts.pathPrefix && opts.pathPrefix.length > 0 ? opts.pathPrefix : null;-- assertValidVector(queryVector, "semanticTopK");- const buf = vecToBuffer(queryVector);- if (prefix) {- const rows = this.db- .query<- { chunk_id: number; document_id: number; distance: number },- [Buffer, number, string, string]- >(- "SELECT m.chunk_id AS chunk_id, c.document_id AS document_id, v.distance AS distance " +- "FROM chunk_vec v " +- "JOIN chunk_vec_map m ON m.vec_rowid = v.rowid " +- "JOIN chunks c ON c.id = m.chunk_id " +- "JOIN documents d ON d.id = c.document_id " +- "WHERE v.embedding MATCH ? AND k = ? AND substr(d.path, 1, length(?)) = ? " +- "ORDER BY v.distance ASC",- )- .all(buf, limit * 4, prefix, prefix);- return rows.slice(0, limit).map((r) => ({- chunkId: r.chunk_id,- documentId: r.document_id,- distance: r.distance,- }));- }-- const rows = this.db- .query<{ chunk_id: number; document_id: number; distance: number }, [Buffer, number]>(- "SELECT m.chunk_id AS chunk_id, c.document_id AS document_id, v.distance AS distance " +- "FROM chunk_vec v " +- "JOIN chunk_vec_map m ON m.vec_rowid = v.rowid " +- "JOIN chunks c ON c.id = m.chunk_id " +- "WHERE v.embedding MATCH ? AND k = ? " +- "ORDER BY v.distance ASC",- )- .all(buf, limit);- return rows.map((r) => ({- chunkId: r.chunk_id,- documentId: r.document_id,- distance: r.distance,- }));- }-- hydrateChunks(chunkIds: ReadonlyArray<number>): Map<number, HydratedChunk> {- const out = new Map<number, HydratedChunk>();- if (chunkIds.length === 0) return out;- const placeholders = sqlPlaceholders(chunkIds);- const rows = this.db- .query<- {- chunk_id: number;- document_id: number;- path: string;- title: string | null;- content: string;- start_line: number;- end_line: number;- mtime: number;- authored_at: number | null;- },- number[]- >(- "SELECT c.id AS chunk_id, c.document_id, d.path AS path, d.title AS title, " +- " c.content AS content, c.start_line AS start_line, c.end_line AS end_line, d.mtime AS mtime, " +- " d.authored_at AS authored_at " +- "FROM chunks c JOIN documents d ON d.id = c.document_id " +- `WHERE c.id IN (${placeholders})`,- )- .all(...(chunkIds as number[]));- for (const r of rows) {- out.set(r.chunk_id, {- chunkId: r.chunk_id,- documentId: r.document_id,- path: r.path,- title: r.title,- content: r.content,- startLine: r.start_line,- endLine: r.end_line,- mtime: r.mtime,- authoredAt: r.authored_at,- });- }- return out;- }-- /**- * For each chunk id, return the document ids that link TO that- * chunk's document via wikilink or markdown_link. Pure data; the- * ranker decides how to convert this into a boost.- */- inboundLinkSources(candidateChunkIds: ReadonlyArray<number>): Map<number, Set<number>> {- const out = new Map<number, Set<number>>();- if (candidateChunkIds.length === 0) return out;- const placeholders = sqlPlaceholders(candidateChunkIds);- const rows = this.db- .query<{ chunk_id: number; source_document_id: number }, number[]>(- "SELECT c.id AS chunk_id, l.source_document_id " +- `FROM chunks c JOIN links l ON l.target_document_id = c.document_id ` +- `WHERE c.id IN (${placeholders}) AND l.link_type IN ('wikilink','markdown_link') ` +- ` AND l.source_document_id != c.document_id`,- )- .all(...(candidateChunkIds as number[]));- for (const r of rows) {- let set = out.get(r.chunk_id);- if (!set) {- set = new Set();- out.set(r.chunk_id, set);- }- set.add(r.source_document_id);- }- return out;- }-- /**- * For each source document id, the list of resolved outbound link- * target document ids (wikilink / markdown_link only; tags and- * unresolved targets excluded; self-links dropped). Used by the- * recall traversal layer to walk one or more hops out from a hit.- */- outboundLinkTargets(sourceDocumentIds: ReadonlyArray<number>): Map<number, number[]> {- const out = new Map<number, number[]>();- if (sourceDocumentIds.length === 0) return out;- const placeholders = sqlPlaceholders(sourceDocumentIds);- const rows = this.db- .query<{ source_document_id: number; target_document_id: number }, number[]>(- "SELECT DISTINCT l.source_document_id, l.target_document_id " +- `FROM links l ` +- `WHERE l.source_document_id IN (${placeholders}) ` +- ` AND l.target_document_id IS NOT NULL ` +- ` AND l.target_document_id != l.source_document_id ` +- ` AND l.link_type IN ('wikilink','markdown_link') ` +- `ORDER BY l.source_document_id, l.target_document_id`,- )- .all(...(sourceDocumentIds as number[]));- for (const r of rows) {- let list = out.get(r.source_document_id);- if (!list) {- list = [];- out.set(r.source_document_id, list);- }- list.push(r.target_document_id);- }- return out;- }-- /**- * One representative chunk per document - the lowest `chunk_index`,- * which for markdown is the document head (title / opening section).- * The traversal layer surfaces this when a linked document is not- * already a relevance hit.- */- /**- * Document id -> { path, title } for every indexed document, reading- * ONLY the `documents` table (never chunk bodies). The graph query- * pre-pass uses this for its index-only short-circuit so it can rank and- * answer from index metadata with zero note bodies hydrated.- */- documentTitles(): Map<number, { readonly path: string; readonly title: string | null }> {- const out = new Map<number, { path: string; title: string | null }>();- const rows = this.db- .query<{ id: number; path: string; title: string | null }, []>(- "SELECT id, path, title FROM documents",- )- .all();- for (const r of rows) out.set(r.id, { path: r.path, title: r.title });- return out;- }-- representativeChunks(documentIds: ReadonlyArray<number>): Map<number, HydratedChunk> {- const out = new Map<number, HydratedChunk>();- if (documentIds.length === 0) return out;- const placeholders = sqlPlaceholders(documentIds);- const rows = this.db- .query<- {- chunk_id: number;- document_id: number;- path: string;- title: string | null;- content: string;- start_line: number;- end_line: number;- mtime: number;- },- number[]- >(- "SELECT c.id AS chunk_id, c.document_id AS document_id, d.path AS path, " +- "d.title AS title, c.content AS content, c.start_line AS start_line, " +- "c.end_line AS end_line, d.mtime AS mtime " +- "FROM chunks c JOIN documents d ON d.id = c.document_id " +- `WHERE c.document_id IN (${placeholders}) ` +- "ORDER BY c.document_id, c.chunk_index ASC",- )- .all(...(documentIds as number[]));- for (const r of rows) {- if (out.has(r.document_id)) continue; // first row per doc = lowest chunk_index- out.set(- r.document_id,- Object.freeze({- chunkId: r.chunk_id,- documentId: r.document_id,- path: r.path,- title: r.title,- content: r.content,- startLine: r.start_line,- endLine: r.end_line,- mtime: r.mtime,- }),- );- }- return out;+ ): trigram.TrigramCandidateOutcome {+ return trigram.trigramCandidates(this.db, trigramQuery, opts);}// ββ entities βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@@ -2324,20 +717,7 @@ export class Store {* pre-normalised (lowercased) by the extractor.*/replaceEntities(chunkId: number, entities: ReadonlyArray<string>): void {- this.db.exec("BEGIN");- try {- this.db.run("DELETE FROM chunk_entities WHERE chunk_id = ?", [chunkId]);- if (entities.length > 0) {- const insert = this.db.prepare<undefined, [number, string]>(- "INSERT OR IGNORE INTO chunk_entities(chunk_id, entity) VALUES (?, ?)",- );- for (const e of entities) insert.run(chunkId, e);- }- this.db.exec("COMMIT");- } catch (e) {- this.db.exec("ROLLBACK");- throw e;- }+ chunkEntities.replaceEntities(this.db, chunkId, entities);}/**@@ -2345,13 +725,7 @@ export class Store {* (link-recall-intelligence: shared-entity digest in cluster notes).*/entitiesForDocument(documentId: number): ReadonlyArray<string> {- return this.db- .query<{ entity: string }, [number]>(- "SELECT DISTINCT e.entity AS entity FROM chunk_entities e " +- "JOIN chunks c ON c.id = e.chunk_id WHERE c.document_id = ? ORDER BY e.entity ASC",- )- .all(documentId)- .map((r) => r.entity);+ return chunkEntities.entitiesForDocument(this.db, documentId);}/**@@ -2363,94 +737,17 @@ export class Store {candidateChunkIds: ReadonlyArray<number>,queryEntities: ReadonlyArray<string>,): Map<number, number> {- const out = new Map<number, number>();- if (candidateChunkIds.length === 0 || queryEntities.length === 0) return out;- const chunkPlaceholders = sqlPlaceholders(candidateChunkIds);- const entityPlaceholders = sqlPlaceholders(queryEntities);- const rows = this.db- .query<{ chunk_id: number; c: number }, (number | string)[]>(- "SELECT chunk_id, COUNT(DISTINCT entity) AS c FROM chunk_entities " +- `WHERE chunk_id IN (${chunkPlaceholders}) AND entity IN (${entityPlaceholders}) ` +- "GROUP BY chunk_id",- )- .all(...(candidateChunkIds as number[]), ...(queryEntities as string[]));- for (const r of rows) out.set(r.chunk_id, r.c);- return out;- }-- /**- * For each chunk id, the set of tag link_text values associated with- * its document. Two chunks "share a tag" iff their tag sets intersect.- */- tagsByChunkDocument(candidateChunkIds: ReadonlyArray<number>): Map<number, Set<string>> {- const out = new Map<number, Set<string>>();- if (candidateChunkIds.length === 0) return out;- const placeholders = sqlPlaceholders(candidateChunkIds);- const rows = this.db- .query<{ chunk_id: number; tag: string }, number[]>(- "SELECT c.id AS chunk_id, l.link_text AS tag " +- `FROM chunks c JOIN links l ON l.source_document_id = c.document_id ` +- `WHERE c.id IN (${placeholders}) AND l.link_type = 'tag' AND l.link_text IS NOT NULL`,- )- .all(...(candidateChunkIds as number[]));- for (const r of rows) {- let set = out.get(r.chunk_id);- if (!set) {- set = new Set();- out.set(r.chunk_id, set);- }- set.add(r.tag);- }- return out;+ return chunkEntities.chunkEntityMatches(this.db, candidateChunkIds, queryEntities);}// ββ counts βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- counts(): StoreCounts {- const docs = this.db.query<{ c: number }, []>("SELECT count(*) AS c FROM documents").get();- const chunks = this.db.query<{ c: number }, []>("SELECT count(*) AS c FROM chunks").get();- const emb = this.db.query<{ c: number }, []>("SELECT count(*) AS c FROM embeddings").get();- const stale = this.staleEmbeddings();- return Object.freeze({- documents: docs?.c ?? 0,- chunks: chunks?.c ?? 0,- embeddings: emb?.c ?? 0,- staleEmbeddings: stale,- });- }-- private staleEmbeddings(): number {- const model = this.config.semantic.model;- const dimension = this.config.semantic.dimension;- if (!model || !dimension) {- // No baseline to compare against: 0 stale by convention.- return 0;- }- const row = this.db- .query<{ c: number }, [string, number]>(- "SELECT count(*) AS c FROM embeddings WHERE model != ? OR dimension != ?",- )- .get(model, dimension);- return row?.c ?? 0;+ counts(): census.StoreCounts {+ return census.counts(this.db, this.config.semantic.model, this.config.semantic.dimension);}// ββ direct accessors used by indexer/CLI/status ββββββββββββββββββββββββββββ- /**- * Chunks that have no row in `embeddings`. Used by the indexer to- * populate vectors after a fresh index or after the model-change drop.- */- findChunksWithoutEmbeddings(): Array<{ chunkId: number; content: string }> {- const rows = this.db- .query<{ id: number; content: string }, []>(- "SELECT c.id AS id, c.content AS content FROM chunks c " +- "LEFT JOIN embeddings e ON e.chunk_id = c.id " +- "WHERE e.chunk_id IS NULL ORDER BY c.id",- )- .all();- return rows.map((r) => ({ chunkId: r.id, content: r.content }));- }-/** Escape hatch for status queries that don't fit the typed API. */rawQuery<T>(sql: string, params: ReadonlyArray<string | number | null> = []): T[] {return this.dbdiff --git a/src/core/search/store/aliases.ts b/src/core/search/store/aliases.tsnew file mode 100644index 00000000..8d92ad31--- /dev/null+++ b/src/core/search/store/aliases.ts@@ -0,0 +1,116 @@+/**+ * The `doc_aliases` table (v7, link-recall-intelligence): the alternate+ * names a document declares in frontmatter, and the pass that resolves+ * link targets through them.+ */++import { Database } from "bun:sqlite";++/**+ * Canonical alias/lookup-key normalisation for `doc_aliases` (v7):+ * trim, NFC-normalise, lower-case - the exact rule+ * `link-graph/alias-index.ts` applies on the Brain-artifact side, so+ * the two alias surfaces never disagree on a key.+ */+export function normalizeAlias(value: string): string {+ return value.trim().normalize("NFC").toLowerCase();+}++/**+ * Replace one document's frontmatter aliases. Values are normalised+ * via {@link normalizeAlias}; empties and duplicates are dropped.+ */+export function replaceDocAliases(+ db: Database,+ documentId: number,+ aliases: ReadonlyArray<string>,+): void {+ const normalised = [...new Set(aliases.map(normalizeAlias).filter((a) => a.length > 0))];+ db.exec("BEGIN");+ try {+ db.run("DELETE FROM doc_aliases WHERE document_id = ?", [documentId]);+ if (normalised.length > 0) {+ const insert = db.prepare<undefined, [number, string]>(+ "INSERT OR IGNORE INTO doc_aliases(document_id, alias) VALUES (?, ?)",+ );+ for (const alias of normalised) insert.run(documentId, alias);+ }+ db.exec("COMMIT");+ } catch (e) {+ db.exec("ROLLBACK");+ throw e;+ }+}++/** Normalised aliases of one document, sorted. */+export function aliasesForDocument(db: Database, documentId: number): ReadonlyArray<string> {+ return db+ .query<{ alias: string }, [number]>(+ "SELECT alias FROM doc_aliases WHERE document_id = ? ORDER BY alias ASC",+ )+ .all(documentId)+ .map((r) => r.alias);+}++/**+ * Materialize `target_document_id` for unresolved, slash-free link+ * targets that match a declared alias. Runs AFTER+ * `resolveLinkTargets` so exact path matches always win.+ *+ * Shadowing rule (mirrors `alias-index.ts`): a target that equals a+ * real document basename is never alias-resolved - the read-time+ * basename fallback owns it. Collisions (two documents claim one+ * alias) resolve first-wins by sorted document path. Normalisation+ * happens in JS because SQLite `lower()` is ASCII-only.+ *+ * Returns the number of link rows resolved.+ */+export function resolveAliasTargets(db: Database): number {+ const unresolved = db+ .query<{ target_path: string }, []>(+ "SELECT DISTINCT target_path FROM links " ++ "WHERE target_document_id IS NULL AND target_path IS NOT NULL " ++ "AND link_type = 'wikilink' AND instr(target_path, '/') = 0",+ )+ .all();+ if (unresolved.length === 0) return 0;++ const aliasOwner = db.prepare<{ document_id: number }, [string]>(+ "SELECT a.document_id AS document_id FROM doc_aliases a " ++ "JOIN documents d ON d.id = a.document_id " ++ "WHERE a.alias = ? ORDER BY d.path ASC LIMIT 1",+ );+ // A real document basename owns the target (top-level `target.md` or+ // any nested `.../target.md`): both collapse to `basename = target`,+ // an index lookup instead of the old `path = target.md OR SUBSTR(...)`+ // full scan.+ const basenameExists = db.prepare<{ id: number }, [string]>(+ "SELECT id FROM documents WHERE basename = ? LIMIT 1",+ );+ const update = db.prepare<undefined, [number, string]>(+ "UPDATE links SET target_document_id = ? " ++ "WHERE target_document_id IS NULL AND target_path = ? AND link_type = 'wikilink'",+ );++ let resolved = 0;+ db.exec("BEGIN");+ try {+ for (const row of unresolved) {+ const key = normalizeAlias(row.target_path);+ if (key.length === 0) continue;+ // Skip targets a real document basename owns.+ if (basenameExists.get(row.target_path)) {+ continue;+ }+ const owner = aliasOwner.get(key);+ if (!owner) continue;+ update.run(owner.document_id, row.target_path);+ resolved += db.query<{ n: number }, []>("SELECT changes() AS n").get()?.n ?? 0;+ }+ db.exec("COMMIT");+ } catch (e) {+ db.exec("ROLLBACK");+ throw e;+ }+ return resolved;+}diff --git a/src/core/search/store/chunk-entities.ts b/src/core/search/store/chunk-entities.tsnew file mode 100644index 00000000..9afb5a56--- /dev/null+++ b/src/core/search/store/chunk-entities.ts@@ -0,0 +1,74 @@+/**+ * The `chunk_entities` table (v0.13.0): the normalised entity set the+ * extractor found in each chunk, and the co-occurrence reads the ranker+ * and the cluster digest build on it.+ */++import { Database } from "bun:sqlite";++import { sqlPlaceholders } from "./sql.ts";++/**+ * Replace a chunk's entity set (v0.13.0). Deletes any prior entries+ * for the chunk, then inserts the deduped list. Entities are expected+ * pre-normalised (lowercased) by the extractor.+ */+export function replaceEntities(+ db: Database,+ chunkId: number,+ entities: ReadonlyArray<string>,+): void {+ db.exec("BEGIN");+ try {+ db.run("DELETE FROM chunk_entities WHERE chunk_id = ?", [chunkId]);+ if (entities.length > 0) {+ const insert = db.prepare<undefined, [number, string]>(+ "INSERT OR IGNORE INTO chunk_entities(chunk_id, entity) VALUES (?, ?)",+ );+ for (const e of entities) insert.run(chunkId, e);+ }+ db.exec("COMMIT");+ } catch (e) {+ db.exec("ROLLBACK");+ throw e;+ }+}++/**+ * Distinct entities across one document's chunks, sorted+ * (link-recall-intelligence: shared-entity digest in cluster notes).+ */+export function entitiesForDocument(db: Database, documentId: number): ReadonlyArray<string> {+ return db+ .query<{ entity: string }, [number]>(+ "SELECT DISTINCT e.entity AS entity FROM chunk_entities e " ++ "JOIN chunks c ON c.id = e.chunk_id WHERE c.document_id = ? ORDER BY e.entity ASC",+ )+ .all(documentId)+ .map((r) => r.entity);+}++/**+ * For each candidate chunk, the count of distinct query entities it+ * also carries. Empty `queryEntities` yields an empty map (no work).+ * Pure read; used by the ranker to add a capped entity boost.+ */+export function chunkEntityMatches(+ db: Database,+ candidateChunkIds: ReadonlyArray<number>,+ queryEntities: ReadonlyArray<string>,+): Map<number, number> {+ const out = new Map<number, number>();+ if (candidateChunkIds.length === 0 || queryEntities.length === 0) return out;+ const chunkPlaceholders = sqlPlaceholders(candidateChunkIds);+ const entityPlaceholders = sqlPlaceholders(queryEntities);+ const rows = db+ .query<{ chunk_id: number; c: number }, (number | string)[]>(+ "SELECT chunk_id, COUNT(DISTINCT entity) AS c FROM chunk_entities " ++ `WHERE chunk_id IN (${chunkPlaceholders}) AND entity IN (${entityPlaceholders}) ` ++ "GROUP BY chunk_id",+ )+ .all(...(candidateChunkIds as number[]), ...(queryEntities as string[]));+ for (const r of rows) out.set(r.chunk_id, r.c);+ return out;+}diff --git a/src/core/search/store/chunks.ts b/src/core/search/store/chunks.tsnew file mode 100644index 00000000..b7c02f84--- /dev/null+++ b/src/core/search/store/chunks.ts@@ -0,0 +1,292 @@+/**+ * The `chunks` table: the units search actually ranks. Owns their+ * atomic replacement per document (the FTS5 shadow follows via the+ * chunks_ai/ad/au triggers) and the hydration reads that turn ids back+ * into rendered text.+ */++import { Database } from "bun:sqlite";++import { SearchError } from "../types.ts";+import { nowIso, sqlPlaceholders } from "./sql.ts";+import { purgeVecRowsByChunkIds, purgeVecRowsForDocument } from "./vectors.ts";++export interface ChunkInput {+ readonly chunkIndex: number;+ readonly content: string;+ readonly ftsContent?: string;+ readonly contentHash: string;+ readonly startLine: number;+ readonly endLine: number;+ readonly tokenCount: number;+ /**+ * Heading breadcrumb in effect at the chunk (v0.13.0). Indexed in the+ * dedicated FTS column; defaults to "" so callers that do not supply+ * it (and pre-v0.13.0 fixtures) index an empty heading column.+ */+ readonly headingPath?: string;+}++export interface ChunkRow {+ readonly id: number;+ readonly documentId: number;+ readonly chunkIndex: number;+ readonly content: string;+ readonly contentHash: string;+ readonly startLine: number;+ readonly endLine: number;+ readonly tokenCount: number;+}++export interface HydratedChunk {+ readonly chunkId: number;+ readonly documentId: number;+ readonly path: string;+ readonly title: string | null;+ readonly content: string;+ readonly startLine: number;+ readonly endLine: number;+ readonly mtime: number;+ /**+ * Transcript turn instant (unix seconds) or null (conversation+ * chronology, S1). Feeds the exact-tie recency tie-break in the ranker+ * and is surfaced on the search result. Null for notes with no turn+ * instant, keeping their ordering byte-identical.+ */+ readonly authoredAt?: number | null;+}++export function getChunksByDocument(db: Database, documentId: number): ChunkRow[] {+ const rows = db+ .query<+ {+ id: number;+ document_id: number;+ chunk_index: number;+ content: string;+ content_hash: string;+ start_line: number;+ end_line: number;+ token_count: number;+ },+ [number]+ >(+ "SELECT id, document_id, chunk_index, content, content_hash, start_line, end_line, token_count " ++ "FROM chunks WHERE document_id = ? ORDER BY chunk_index",+ )+ .all(documentId);+ return rows.map((r) => ({+ id: r.id,+ documentId: r.document_id,+ chunkIndex: r.chunk_index,+ content: r.content,+ contentHash: r.content_hash,+ startLine: r.start_line,+ endLine: r.end_line,+ tokenCount: r.token_count,+ }));+}++/**+ * Atomically replace every chunk for a document. Old vec rows are+ * removed first; FTS5 stays in sync via the chunks_ai/ad/au triggers.+ * Returns the new chunk ids in `chunkIndex` order.+ */+export function replaceChunks(+ db: Database,+ vecLoaded: boolean,+ documentId: number,+ chunks: ReadonlyArray<ChunkInput>,+): number[] {+ const ids: number[] = [];+ db.exec("BEGIN");+ try {+ purgeVecRowsForDocument(db, vecLoaded, documentId);+ db.run("DELETE FROM chunks WHERE document_id = ?", [documentId]);+ const insert = db.prepare<+ { id: number },+ [number, number, string, string, string, number, number, number, string, string, string]+ >(+ "INSERT INTO chunks(document_id, chunk_index, content, fts_content, content_hash, start_line, end_line, token_count, heading_path, created_at, updated_at) " ++ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",+ );+ const now = nowIso();+ for (const c of chunks) {+ const row = insert.get(+ documentId,+ c.chunkIndex,+ c.content,+ c.ftsContent ?? c.content,+ c.contentHash,+ c.startLine,+ c.endLine,+ c.tokenCount,+ c.headingPath ?? "",+ now,+ now,+ );+ if (!row) throw new SearchError("INDEX_UNREADABLE", "chunk insert returned no id");+ ids.push(row.id);+ }+ db.exec("COMMIT");+ } catch (e) {+ db.exec("ROLLBACK");+ throw e;+ }+ return ids;+}++/**+ * Delete a set of chunks by id. Vec rows removed first.+ */+export function deleteChunks(+ db: Database,+ vecLoaded: boolean,+ chunkIds: ReadonlyArray<number>,+): void {+ if (chunkIds.length === 0) return;+ db.exec("BEGIN");+ try {+ purgeVecRowsByChunkIds(db, vecLoaded, chunkIds);+ const placeholders = sqlPlaceholders(chunkIds);+ db.run(`DELETE FROM chunks WHERE id IN (${placeholders})`, chunkIds as number[]);+ db.exec("COMMIT");+ } catch (e) {+ db.exec("ROLLBACK");+ throw e;+ }+}++/** Ordered chunk ids for one document (surprisal, t_fddfe64a). */+export function chunksForDocument(+ db: Database,+ documentId: number,+): ReadonlyArray<{ id: number; chunkIndex: number }> {+ return db+ .query<{ id: number; chunk_index: number }, [number]>(+ "SELECT id, chunk_index FROM chunks WHERE document_id = ? ORDER BY chunk_index ASC",+ )+ .all(documentId)+ .map((r) => ({ id: r.id, chunkIndex: r.chunk_index }));+}++/** Total indexed chunk count - used to judge trigram-prefilter selectivity. */+export function countChunks(db: Database): number {+ return db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM chunks").get()?.n ?? 0;+}++/**+ * Chunks that have no row in `embeddings`. Used by the indexer to+ * populate vectors after a fresh index or after the model-change drop.+ */+export function findChunksWithoutEmbeddings(+ db: Database,+): Array<{ chunkId: number; content: string }> {+ const rows = db+ .query<{ id: number; content: string }, []>(+ "SELECT c.id AS id, c.content AS content FROM chunks c " ++ "LEFT JOIN embeddings e ON e.chunk_id = c.id " ++ "WHERE e.chunk_id IS NULL ORDER BY c.id",+ )+ .all();+ return rows.map((r) => ({ chunkId: r.id, content: r.content }));+}++export function hydrateChunks(+ db: Database,+ chunkIds: ReadonlyArray<number>,+): Map<number, HydratedChunk> {+ const out = new Map<number, HydratedChunk>();+ if (chunkIds.length === 0) return out;+ const placeholders = sqlPlaceholders(chunkIds);+ const rows = db+ .query<+ {+ chunk_id: number;+ document_id: number;+ path: string;+ title: string | null;+ content: string;+ start_line: number;+ end_line: number;+ mtime: number;+ authored_at: number | null;+ },+ number[]+ >(+ "SELECT c.id AS chunk_id, c.document_id, d.path AS path, d.title AS title, " ++ " c.content AS content, c.start_line AS start_line, c.end_line AS end_line, d.mtime AS mtime, " ++ " d.authored_at AS authored_at " ++ "FROM chunks c JOIN documents d ON d.id = c.document_id " ++ `WHERE c.id IN (${placeholders})`,+ )+ .all(...(chunkIds as number[]));+ for (const r of rows) {+ out.set(r.chunk_id, {+ chunkId: r.chunk_id,+ documentId: r.document_id,+ path: r.path,+ title: r.title,+ content: r.content,+ startLine: r.start_line,+ endLine: r.end_line,+ mtime: r.mtime,+ authoredAt: r.authored_at,+ });+ }+ return out;+}++/**+ * One representative chunk per document - the lowest `chunk_index`,+ * which for markdown is the document head (title / opening section).+ * The traversal layer surfaces this when a linked document is not+ * already a relevance hit.+ */+export function representativeChunks(+ db: Database,+ documentIds: ReadonlyArray<number>,+): Map<number, HydratedChunk> {+ const out = new Map<number, HydratedChunk>();+ if (documentIds.length === 0) return out;+ const placeholders = sqlPlaceholders(documentIds);+ const rows = db+ .query<+ {+ chunk_id: number;+ document_id: number;+ path: string;+ title: string | null;+ content: string;+ start_line: number;+ end_line: number;+ mtime: number;+ },+ number[]+ >(+ "SELECT c.id AS chunk_id, c.document_id AS document_id, d.path AS path, " ++ "d.title AS title, c.content AS content, c.start_line AS start_line, " ++ "c.end_line AS end_line, d.mtime AS mtime " ++ "FROM chunks c JOIN documents d ON d.id = c.document_id " ++ `WHERE c.document_id IN (${placeholders}) ` ++ "ORDER BY c.document_id, c.chunk_index ASC",+ )+ .all(...(documentIds as number[]));+ for (const r of rows) {+ if (out.has(r.document_id)) continue; // first row per doc = lowest chunk_index+ out.set(+ r.document_id,+ Object.freeze({+ chunkId: r.chunk_id,+ documentId: r.document_id,+ path: r.path,+ title: r.title,+ content: r.content,+ startLine: r.start_line,+ endLine: r.end_line,+ mtime: r.mtime,+ }),+ );+ }+ return out;+}diff --git a/src/core/search/store/counts.ts b/src/core/search/store/counts.tsnew file mode 100644index 00000000..9e6bf4b7--- /dev/null+++ b/src/core/search/store/counts.ts@@ -0,0 +1,32 @@+/**+ * The index census: one row-count per table the operator surfaces care+ * about, taken together so `o2b search status` reports a single+ * consistent picture rather than four independent probes.+ */++import { Database } from "bun:sqlite";++import { countChunks } from "./chunks.ts";+import { countDocuments } from "./documents.ts";+import { countEmbeddings, staleEmbeddings } from "./vectors.ts";++export interface StoreCounts {+ readonly documents: number;+ readonly chunks: number;+ readonly embeddings: number;+ /** Embeddings whose `model`/`dimension` no longer match the current config. */+ readonly staleEmbeddings: number;+}++export function counts(+ db: Database,+ configuredModel: string | null,+ configuredDimension: number | null,+): StoreCounts {+ return Object.freeze({+ documents: countDocuments(db),+ chunks: countChunks(db),+ embeddings: countEmbeddings(db),+ staleEmbeddings: staleEmbeddings(db, configuredModel, configuredDimension),+ });+}diff --git a/src/core/search/store/documents.ts b/src/core/search/store/documents.tsnew file mode 100644index 00000000..b6bd962c--- /dev/null+++ b/src/core/search/store/documents.ts@@ -0,0 +1,174 @@+/**+ * The `documents` table: one row per indexed vault file, its identity+ * (path, basename, title), its stat fingerprint, and the frontmatter+ * facets later phases join on without re-reading the file.+ */++import { Database } from "bun:sqlite";++import { documentBasename } from "../schema.ts";+import { SearchError } from "../types.ts";+import { nowIso } from "./sql.ts";+import { purgeVecRowsForDocument } from "./vectors.ts";++export interface DocumentInput {+ readonly path: string; // vault-relative POSIX+ readonly title: string | null;+ readonly contentHash: string;+ readonly mtime: number; // unix seconds+ readonly size: number;+ /**+ * The page's declared frontmatter `type` (normalized token), or null+ * when undeclared. Persisted so link-constraint enforcement can join+ * endpoint types without re-reading files (v6).+ */+ readonly pageType?: string | null;+ /**+ * Transcript turn instant this note was authored at, in unix seconds+ * (conversation chronology, S1 / t_347e8224). Derived from the+ * `authored_at` frontmatter field. Absent / null for a note with no+ * turn instant, which then ranks byte-identically to pre-feature.+ */+ readonly authoredAt?: number | null;+}++export interface DocumentSummary {+ readonly id: number;+ readonly contentHash: string;+ readonly mtime: number;+ readonly size: number;+}++export function listDocuments(db: Database): Map<string, DocumentSummary> {+ const rows = db+ .query<+ {+ id: number;+ path: string;+ content_hash: string;+ mtime: number;+ size: number;+ },+ []+ >("SELECT id, path, content_hash, mtime, size FROM documents")+ .all();+ const map = new Map<string, DocumentSummary>();+ for (const r of rows) {+ map.set(r.path, {+ id: r.id,+ contentHash: r.content_hash,+ mtime: r.mtime,+ size: r.size,+ });+ }+ return map;+}++export function getDocumentIdByPath(db: Database, path: string): number | null {+ const row = db+ .query<{ id: number }, [string]>("SELECT id FROM documents WHERE path = ?")+ .get(path);+ return row?.id ?? null;+}++export function upsertDocument(db: Database, doc: DocumentInput): number {+ const now = nowIso();+ // SQLite RETURNING on INSERT...ON CONFLICT works in 3.35+; bun:sqlite ships modern SQLite.+ const row = db+ .query<+ { id: number },+ [+ string,+ string,+ string | null,+ string,+ number,+ number,+ string | null,+ number | null,+ string,+ string,+ string,+ ]+ >(+ "INSERT INTO documents(path, basename, title, content_hash, mtime, size, page_type, authored_at, created_at, updated_at, indexed_at) " ++ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " ++ "ON CONFLICT(path) DO UPDATE SET " ++ " basename = excluded.basename, " ++ " title = excluded.title, " ++ " content_hash = excluded.content_hash, " ++ " mtime = excluded.mtime, " ++ " size = excluded.size, " ++ " page_type = excluded.page_type, " ++ " authored_at = excluded.authored_at, " ++ " updated_at = excluded.updated_at, " ++ " indexed_at = excluded.indexed_at " ++ "RETURNING id",+ )+ .get(+ doc.path,+ documentBasename(doc.path),+ doc.title,+ doc.contentHash,+ doc.mtime,+ doc.size,+ doc.pageType ?? null,+ doc.authoredAt ?? null,+ now,+ now,+ now,+ );+ if (!row) {+ throw new SearchError("INDEX_UNREADABLE", `upsertDocument returned no id for '${doc.path}'`);+ }+ return row.id;+}++/**+ * Delete a document and everything that hangs off it. The vec rows+ * are removed first because the FK cascade does not reach the+ * `chunk_vec` virtual table.+ */+export function deleteDocument(db: Database, vecLoaded: boolean, path: string): void {+ const id = getDocumentIdByPath(db, path);+ if (id === null) return;+ purgeVecRowsForDocument(db, vecLoaded, id);+ db.run("DELETE FROM documents WHERE id = ?", [id]);+}++/**+ * Touch a document's mtime and size without changing its title,+ * hash, or triggering chunk replacement. Used by the indexer's+ * mtime-fastpath fallback to re-arm the stat cache after a+ * same-content touch.+ */+export function touchDocument(db: Database, path: string, mtime: number, size: number): void {+ const now = nowIso();+ db.run(+ "UPDATE documents SET mtime = ?, size = ?, updated_at = ?, indexed_at = ? WHERE path = ?",+ [mtime, size, now, now, path],+ );+}++/**+ * Document id -> { path, title } for every indexed document, reading+ * ONLY the `documents` table (never chunk bodies). The graph query+ * pre-pass uses this for its index-only short-circuit so it can rank and+ * answer from index metadata with zero note bodies hydrated.+ */+export function documentTitles(+ db: Database,+): Map<number, { readonly path: string; readonly title: string | null }> {+ const out = new Map<number, { path: string; title: string | null }>();+ const rows = db+ .query<{ id: number; path: string; title: string | null }, []>(+ "SELECT id, path, title FROM documents",+ )+ .all();+ for (const r of rows) out.set(r.id, { path: r.path, title: r.title });+ return out;+}++export function countDocuments(db: Database): number {+ return db.query<{ c: number }, []>("SELECT count(*) AS c FROM documents").get()?.c ?? 0;+}diff --git a/src/core/search/store/embedding-abi.ts b/src/core/search/store/embedding-abi.tsnew file mode 100644index 00000000..27106b02--- /dev/null+++ b/src/core/search/store/embedding-abi.ts@@ -0,0 +1,99 @@+/**+ * The embedding ABI an index was written under versus the one this build+ * would produce (context-integrity-gates, Unit E): reading the recorded+ * tokens, deriving the runtime ones, and naming the drift between them.+ *+ * Both sides of the comparison are built here so they can never cover+ * different fields.+ */++import type { StampMismatch, StampTokens } from "../../integrity/stamp.ts";+import { formatStampMismatch } from "../../integrity/stamp.ts";++import type { ResolvedSearchConfig } from "../types.ts";+import {+ EMBEDDING_DIMENSION_STATE_KEY,+ EMBEDDING_MODEL_STATE_KEY,+ EMBEDDING_VEC_VERSION_STATE_KEY,+ withReadonlyIndex,+} from "./state.ts";++/**+ * The single remediation for embedding-ABI drift, named once so the+ * store's refusal, the status warning and the `search check`+ * recommendation cannot grow three spellings of the same instruction.+ */+export const EMBEDDING_ABI_FIX_COMMAND = "o2b search reindex --embeddings";++/** The ABI tokens an index recorded, read through any state accessor. */+export function recordedEmbeddingAbi(state: (key: string) => string | null): StampTokens {+ return {+ [EMBEDDING_MODEL_STATE_KEY]: state(EMBEDDING_MODEL_STATE_KEY),+ [EMBEDDING_DIMENSION_STATE_KEY]: state(EMBEDDING_DIMENSION_STATE_KEY),+ [EMBEDDING_VEC_VERSION_STATE_KEY]: state(EMBEDDING_VEC_VERSION_STATE_KEY),+ };+}++/**+ * The ABI tokens the CURRENT build and configuration would produce. The+ * counterpart of {@link recordedEmbeddingAbi}, kept beside it so the two+ * sides of the comparison can never cover different fields.+ */+export function runtimeEmbeddingAbi(+ config: ResolvedSearchConfig,+ vecVersion: string | null,+): StampTokens {+ return {+ [EMBEDDING_MODEL_STATE_KEY]: config.semantic.model,+ [EMBEDDING_DIMENSION_STATE_KEY]:+ config.semantic.dimension === null ? null : String(config.semantic.dimension),+ [EMBEDDING_VEC_VERSION_STATE_KEY]: vecVersion,+ };+}++/**+ * Embedding-ABI tokens recorded in an index, without opening a `Store`.+ *+ * `indexCheck` needs these and cannot get them from its own probe: it+ * deliberately runs against an IN-MEMORY database and never touches the+ * real index, so a stored-versus-runtime comparison there has no stored+ * side unless one is read explicitly.+ *+ * `null` means the index is absent or unreadable - not that its ABI+ * matches.+ */+export function readEmbeddingAbiSync(dbPath: string): StampTokens | null {+ return withReadonlyIndex(dbPath, (read) => recordedEmbeddingAbi(read));+}++/**+ * The subset of an ABI comparison the index actually CONTRADICTS: it+ * recorded a token and that token disagrees with this build.+ *+ * A mismatch whose recorded side is `null` is an UNRECORDED field - a+ * store written before that token was stamped. An absent marker cannot+ * tell an old store from a wrong one, so it is reported on the+ * diagnostic surfaces and never drives a refusal or a per-read warning.+ * Both consumers of that distinction (the `fail` verdict's refusal and+ * the query path's warning) route through here rather than restating+ * the predicate, so they cannot drift on what counts as contradicted.+ */+export function contradictedAbiFields(+ mismatches: ReadonlyArray<StampMismatch>,+): ReadonlyArray<StampMismatch> {+ return mismatches.filter((m) => m.expected !== null);+}++/**+ * One operator-facing line for embedding-ABI drift. Shared by the read+ * open's refusal, the status warning and the `search check`+ * recommendation, so the three cannot describe the same condition+ * differently or name different fixes.+ */+export function formatEmbeddingAbiDrift(mismatches: ReadonlyArray<StampMismatch>): string {+ return (+ `embedding ABI drift between the stored index and this build ` ++ `(${mismatches.map(formatStampMismatch).join("; ")}); stored vectors are not ` ++ `comparable to queries embedded now. Run: ${EMBEDDING_ABI_FIX_COMMAND}`+ );+}diff --git a/src/core/search/store/keyword.ts b/src/core/search/store/keyword.tsnew file mode 100644index 00000000..05642578--- /dev/null+++ b/src/core/search/store/keyword.ts@@ -0,0 +1,155 @@+/**+ * The keyword lane: the `chunk_fts` FTS5 index - its availability probe,+ * its BM25 top-K query, its corpus document frequencies, and the+ * integrity counts and rebuild that repair it.+ */++import { Database } from "bun:sqlite";++import { SearchError } from "../types.ts";+import { acquireWriterLockSync } from "./writer-lock.ts";++export interface KeywordHit {+ readonly chunkId: number;+ readonly documentId: number;+ /** Lower is better (FTS5 returns negative bm25). */+ readonly bm25: number;+}++/**+ * BM25 column weights for `chunk_fts`: body first, heading breadcrumb+ * discounted. Named once so the prefixed and unprefixed queries below+ * cannot rank the same row two ways.+ */+const CHUNK_FTS_BM25 = "bm25(chunk_fts, 1.0, 0.3)";++export function ensureFts5(db: Database): void {+ // Probe FTS5 by attempting a benign expression. bun:sqlite ships with+ // FTS5 enabled in the embedded amalgamation; failing here means a+ // custom build without FTS5 and the index is unusable.+ try {+ db.query("SELECT fts5_source('chunk_fts')").get();+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ // Older SQLite returns "no such function" or "no such table" depending+ // on whether FTS5 is even compiled in. We treat any failure here as+ // FTS5-unavailable rather than guessing the build flag.+ if (!/fts5|chunk_fts/i.test(msg)) {+ throw new SearchError("INDEX_UNREADABLE", `FTS5 probe failed: ${msg}`);+ }+ }+}++export function ftsIntegrityCounts(db: Database): {+ readonly chunks: number;+ readonly ftsRows: number;+} {+ const chunks = db.query<{ c: number }, []>("SELECT count(*) AS c FROM chunks").get()?.c ?? 0;+ const ftsRows =+ db.query<{ c: number }, []>("SELECT count(*) AS c FROM chunk_fts_docsize").get()?.c ?? 0;+ return Object.freeze({ chunks, ftsRows });+}++export function rebuildFtsIndex(db: Database): void {+ db.run("INSERT INTO chunk_fts(chunk_fts) VALUES('rebuild')");+}++/**+ * Rebuild under the writer lock when the caller does not already hold it+ * (a read-mode store repairing the index in place). `heldWriterLock` is+ * the caller's own ownership of the lock on `dbPath`: a write-mode store+ * holds it for its whole session and would contend with itself here,+ * since the lock is a file lock and re-entry from the holder is+ * INDEX_LOCKED like any other contender.+ */+export function rebuildFtsIndexWithWriterLock(+ db: Database,+ dbPath: string,+ heldWriterLock: boolean,+): void {+ if (heldWriterLock) {+ rebuildFtsIndex(db);+ return;+ }+ const release = acquireWriterLockSync(dbPath);+ try {+ rebuildFtsIndex(db);+ } finally {+ release();+ }+}++/**+ * Top-K BM25 keyword hits. `fts5Query` is an already-escaped FTS5+ * MATCH expression; building it is fts.ts's job.+ */+export function keywordTopK(+ db: Database,+ fts5Query: string,+ opts: { readonly limit: number; readonly pathPrefix?: string | null },+): KeywordHit[] {+ const limit = Math.max(1, opts.limit | 0);+ const prefix = opts.pathPrefix && opts.pathPrefix.length > 0 ? opts.pathPrefix : null;++ if (prefix) {+ const rows = db+ .query<+ { chunk_id: number; document_id: number; bm25: number },+ [string, string, string, number]+ >(+ `SELECT c.id AS chunk_id, c.document_id AS document_id, ${CHUNK_FTS_BM25} AS bm25 ` ++ "FROM chunk_fts " ++ "JOIN chunks c ON c.id = chunk_fts.rowid " ++ "JOIN documents d ON d.id = c.document_id " ++ "WHERE chunk_fts MATCH ? AND substr(d.path, 1, length(?)) = ? " ++ "ORDER BY bm25 ASC LIMIT ?",+ )+ .all(fts5Query, prefix, prefix, limit);+ return rows.map((r) => ({+ chunkId: r.chunk_id,+ documentId: r.document_id,+ bm25: r.bm25,+ }));+ }++ const rows = db+ .query<{ chunk_id: number; document_id: number; bm25: number }, [string, number]>(+ `SELECT c.id AS chunk_id, c.document_id AS document_id, ${CHUNK_FTS_BM25} AS bm25 ` ++ "FROM chunk_fts JOIN chunks c ON c.id = chunk_fts.rowid " ++ "WHERE chunk_fts MATCH ? ORDER BY bm25 ASC LIMIT ?",+ )+ .all(fts5Query, limit);+ return rows.map((r) => ({+ chunkId: r.chunk_id,+ documentId: r.document_id,+ bm25: r.bm25,+ }));+}++/**+ * Corpus document frequency per term (recall-trust-suite, coverage+ * engine): how many distinct documents match each term in FTS. Each+ * term is quoted so FTS5 metacharacters stay literal. A term that+ * fails to query (e.g. tokenizer edge case) counts as 0 rather than+ * failing the search.+ */+export function documentFrequencies(+ db: Database,+ terms: ReadonlyArray<string>,+): Map<string, number> {+ const out = new Map<string, number>();+ if (terms.length === 0) return out;+ const q = db.query<{ n: number }, [string]>(+ "SELECT COUNT(DISTINCT c.document_id) AS n " ++ "FROM chunk_fts JOIN chunks c ON c.id = chunk_fts.rowid " ++ "WHERE chunk_fts MATCH ?",+ );+ for (const term of terms) {+ try {+ out.set(term, q.get(`"${term.replace(/"/g, '""')}"`)?.n ?? 0);+ } catch {+ out.set(term, 0);+ }+ }+ return out;+}diff --git a/src/core/search/store/lifecycle.ts b/src/core/search/store/lifecycle.tsnew file mode 100644index 00000000..cce7e044--- /dev/null+++ b/src/core/search/store/lifecycle.ts@@ -0,0 +1,209 @@+/**+ * Opening, healing and closing the index file: crash recovery from a+ * reindex `.bak`, the connection pragmas, the schema gate a read open+ * refuses on, and the WAL consolidation an orderly close owes the next+ * opener.+ *+ * Everything here is about the FILE, not about any one table.+ */++import { Database } from "bun:sqlite";+import { existsSync, mkdirSync, renameSync } from "node:fs";+import { dirname } from "node:path";++import { applyMigrations, LATEST_SCHEMA_VERSION, readSchemaVersion } from "../schema.ts";+import { SearchError } from "../types.ts";+import type { ResolvedSearchConfig } from "../types.ts";+import { ensureFts5 } from "./keyword.ts";+import { loadVecExtension } from "./vectors.ts";+import { acquireWriterLock, acquireWriterLockSync } from "./writer-lock.ts";++/** A connection on the index, plus the vec ABI it opened under. */+export interface OpenedDatabase {+ readonly db: Database;+ /** sqlite-vec version this connection loaded, or null when unavailable. */+ readonly vecVersion: string | null;+}++/** {@link OpenedDatabase} plus the writer lock the caller now owns. */+export interface OpenedWriteDatabase extends OpenedDatabase {+ readonly release: () => Promise<void>;+}++function applyPragmas(db: Database): void {+ db.exec("PRAGMA journal_mode = WAL");+ db.exec("PRAGMA foreign_keys = ON");+ db.exec("PRAGMA synchronous = NORMAL");+ // Wait briefly for a concurrent writer (e.g. an indexer holding the WAL+ // write lock) instead of failing immediately with SQLITE_BUSY. Matters+ // for the opportunistic query-cache writes a read-mode connection makes+ // during search (v0.20.0); search itself also degrades gracefully.+ db.exec("PRAGMA busy_timeout = 5000");+}++/**+ * Crash-recovery preamble shared by every `Store.open`: if the live+ * index file is absent but a `.bak` from a `reindex` rename swap is present,+ * restore it. Guarded by the SAME writer lock `reindexVault` holds across+ * its swap, so a read that opens during the swap's brief db-absent window+ * cannot mistake it for a crashed reindex and clobber the freshly built+ * index with the stale `.bak` (the silent-data-loss race, A.2).+ *+ * Lock semantics distinguish the two cases without a heuristic:+ * - a live reindex mid-swap holds a heartbeated (non-stale) lock, so we+ * block briefly, then find `dbPath` present and skip the restore;+ * - a genuine crash leaves a stale lock (no heartbeat) that is taken over+ * within the stale window, after which we restore.+ * If the lock cannot be taken at all we skip the restore rather than risk a+ * clobber; the caller's open path then re-evaluates existence and reports+ * honestly (INDEX_MISSING). The `.bak` restore of a genuine crash is+ * unaffected: with no live holder the lock is acquired immediately.+ */+export function restoreFromBakIfMissing(dbPath: string): void {+ const bak = dbPath + ".bak";+ if (existsSync(dbPath) || !existsSync(bak)) return;+ let release: (() => void) | null = null;+ try {+ release = acquireWriterLockSync(dbPath);+ } catch {+ // A live writer holds the lock (mid-swap). Do not restore β the swap+ // will place the fresh index; the open path re-checks existence.+ return;+ }+ try {+ // Re-check under the lock: the swap may have completed while we waited,+ // or another opener may have already restored.+ if (existsSync(dbPath) || !existsSync(bak)) return;+ renameSync(bak, dbPath);+ // eslint-disable-next-line no-console+ console.error(`restored search index from ${bak} (previous reindex crash)`);+ } catch {+ /* fall through β open path below will report INDEX_MISSING */+ } finally {+ release();+ }+}++/**+ * The read open's schema gate. A corrupt or non-OSB sqlite file at the+ * index path can make readSchemaVersion throw raw SQLITE errors (e.g.+ * "no such table: index_state"). Surface those as a typed+ * INDEX_UNREADABLE so callers see a code, not a stray Error.+ */+function assertSchemaIsCurrent(db: Database, dbPath: string): void {+ let version: number;+ try {+ version = readSchemaVersion(db);+ } catch (e) {+ if (e instanceof SearchError) throw e;+ const msg = e instanceof Error ? e.message : String(e);+ throw new SearchError("INDEX_UNREADABLE", `cannot read schema_version from ${dbPath}: ${msg}`);+ }+ if (version !== LATEST_SCHEMA_VERSION) {+ throw new SearchError(+ "SCHEMA_MISMATCH",+ `index schema version ${version} != ${LATEST_SCHEMA_VERSION}. Run: o2b search reindex`,+ );+ }+}++/**+ * Open the index for reading: no lock, no migration. An index at an+ * older schema is refused rather than upgraded, because a reader holds+ * no writer lock and must not migrate under a concurrent writer.+ */+export function openReadDatabase(config: ResolvedSearchConfig, loadVec: boolean): OpenedDatabase {+ if (!existsSync(config.dbPath)) {+ throw new SearchError(+ "INDEX_MISSING",+ `search index not initialised at ${config.dbPath}. Run: o2b search index`,+ );+ }+ let db: Database;+ try {+ db = new Database(config.dbPath);+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ throw new SearchError("INDEX_UNREADABLE", `cannot open ${config.dbPath}: ${msg}`);+ }+ try {+ applyPragmas(db);+ ensureFts5(db);+ assertSchemaIsCurrent(db, config.dbPath);+ return { db, vecVersion: loadVec ? loadVecExtension(db) : null };+ } catch (e) {+ db.close();+ throw e;+ }+}++/**+ * Open the index for writing: create the file if absent, take the+ * exclusive writer lock, then migrate to the current schema. The+ * returned `release` is the caller's to hold until close.+ */+export async function openWriteDatabase(+ config: ResolvedSearchConfig,+ loadVec: boolean,+): Promise<OpenedWriteDatabase> {+ mkdirSync(dirname(config.dbPath), { recursive: true });+ if (!existsSync(config.dbPath)) {+ const seed = new Database(config.dbPath);+ seed.close();+ }++ const release = await acquireWriterLock(config.dbPath);++ let db: Database;+ try {+ db = new Database(config.dbPath);+ } catch (e) {+ await release();+ const msg = e instanceof Error ? e.message : String(e);+ throw new SearchError("INDEX_UNREADABLE", `cannot open ${config.dbPath}: ${msg}`);+ }++ try {+ applyPragmas(db);+ applyMigrations(db, { ftsTokenize: config.ftsTokenize });+ ensureFts5(db);+ return { db, vecVersion: loadVec ? loadVecExtension(db) : null, release };+ } catch (e) {+ await abandonWriteDatabase(db, release);+ throw e;+ }+}++/** Unwind a write open that failed after the lock was taken. */+export async function abandonWriteDatabase(+ db: Database,+ release: () => Promise<void>,+): Promise<void> {+ try {+ db.close();+ } catch {+ /* ignore close errors */+ }+ await release();+}++/**+ * Writer mode: consolidate WAL into the main file and switch back to+ * DELETE journal mode so the `-wal`/`-shm` siblings are removed. This+ * matters for `reindexVault`: after the temp-file rename swap, any+ * orphan `*-wal` next to the new main would trigger+ * SQLITE_IOERR_SHORT_READ on the next open.+ */+export function consolidateWal(db: Database): void {+ try {+ db.exec("PRAGMA wal_checkpoint(TRUNCATE)");+ db.exec("PRAGMA journal_mode = DELETE");+ } catch (e) {+ // Don't fail the close, but make the failure visible β an+ // unconsolidated WAL is the exact thing that triggers+ // SQLITE_IOERR_SHORT_READ after a `reindexVault` rename swap.+ const msg = e instanceof Error ? e.message : String(e);+ // eslint-disable-next-line no-console+ console.error(`search store: WAL consolidation failed on close: ${msg}`);+ }+}diff --git a/src/core/search/store/links.ts b/src/core/search/store/links.tsnew file mode 100644index 00000000..21b358a6--- /dev/null+++ b/src/core/search/store/links.ts@@ -0,0 +1,268 @@+/**+ * The `links` table: every wikilink, markdown link and tag a document+ * emits, the passes that materialize their targets, and the graph reads+ * (inbound, outbound, tags, census) built on top of them.+ */++import { Database } from "bun:sqlite";++import { nowIso, sqlPlaceholders } from "./sql.ts";++export interface LinkInput {+ readonly sourceChunkId: number | null;+ readonly targetPath: string | null;+ readonly linkText: string | null;+ readonly linkType: "wikilink" | "markdown_link" | "tag";+ /**+ * Semantic relation type for this edge (v3 / typed graph semantics),+ * orthogonal to `linkType`. `null`/absent for plain syntactic links;+ * set for frontmatter-relation and MCP-config edges. Validated+ * against the open vocabulary in src/core/graph/relation-vocab.ts.+ */+ readonly relation?: string | null;+}++/** Vault-wide link-resolution census (see {@link linkResolutionCounts}). */+export interface LinkResolutionCounts {+ /**+ * Link rows carrying a target path. Tag rows have `target_path IS+ * NULL` and are excluded - a tag has nothing to resolve to.+ */+ readonly total: number;+ /**+ * Rows the read-time resolution ladder cannot resolve to any+ * document - broken links as a reader experiences them.+ */+ readonly unresolved: number;+}++/**+ * The link kinds that carry a navigable target. Tag rows are excluded+ * everywhere this appears, and the two spellings of that exclusion are+ * this one constant.+ */+const NAVIGABLE_LINK_TYPES_SQL = "('wikilink','markdown_link')";++/**+ * The READ-TIME link-resolution ladder, as one SQL expression over a+ * `links` row aliased `l`, yielding the resolved document id or NULL.+ *+ * Three rungs, in order: the materialized `target_document_id` that+ * `resolveLinkTargets` / `resolveAliasTargets` wrote, then a+ * `<target>.md` exact path match, then an UNAMBIGUOUS nested-basename+ * match (`basename = target` with exactly one such nested document -+ * a top-level `target.md` has no leading slash and belongs to the exact+ * rung above).+ *+ * Defined once and shared by {@link resolvedDocLinkPairs} (which+ * follows it) and {@link linkResolutionCounts} (which counts what+ * it leaves over), so "resolvable" and "broken" can never drift apart+ * into two different opinions of the same vault.+ */+const RESOLVED_LINK_TARGET_SQL =+ "COALESCE(" ++ " l.target_document_id, " ++ " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " ++ " (SELECT d.id FROM documents d " ++ " WHERE d.basename = l.target_path AND instr(d.path, '/') > 0 " ++ " AND 1 = (SELECT COUNT(*) FROM documents d2 " ++ " WHERE d2.basename = l.target_path AND instr(d2.path, '/') > 0))" ++ ")";++export function replaceLinks(+ db: Database,+ sourceDocumentId: number,+ links: ReadonlyArray<LinkInput>,+): void {+ db.exec("BEGIN");+ try {+ db.run("DELETE FROM links WHERE source_document_id = ?", [sourceDocumentId]);+ if (links.length > 0) {+ const insert = db.prepare<+ undefined,+ [number, number | null, string | null, string | null, string, string | null, string]+ >(+ "INSERT INTO links(source_document_id, source_chunk_id, target_path, link_text, link_type, relation, created_at) " ++ "VALUES (?, ?, ?, ?, ?, ?, ?)",+ );+ const now = nowIso();+ for (const l of links) {+ insert.run(+ sourceDocumentId,+ l.sourceChunkId,+ l.targetPath,+ l.linkText,+ l.linkType,+ l.relation ?? null,+ now,+ );+ }+ }+ db.exec("COMMIT");+ } catch (e) {+ db.exec("ROLLBACK");+ throw e;+ }+}++export function resolveLinkTargets(db: Database): void {+ db.run(+ "UPDATE links SET target_document_id = (SELECT id FROM documents WHERE documents.path = links.target_path) " ++ "WHERE target_path IS NOT NULL",+ );+}++/**+ * Vault-wide link-resolution census (context-integrity-gates, unit G).+ *+ * `unresolved` counts the link rows that carry a target path and that+ * {@link RESOLVED_LINK_TARGET_SQL} - the SAME ladder+ * {@link resolvedDocLinkPairs} follows - cannot resolve to any+ * document. That is what "broken" means to a reader: a materialized+ * id, a `<target>.md` exact match, and an unambiguous basename all+ * count as resolved, and only what survives all three rungs is+ * reported.+ *+ * The narrower `target_document_id IS NULL` predicate is NOT used+ * here. It also fires on every basename-style `[[note]]`, which the+ * ladder resolves perfectly well and which an Obsidian-shaped vault+ * is written in - a count that rises on a healthy edit is a gate that+ * gets bumped rather than obeyed.+ *+ * Index-backed on every rung: `idx_links_target_path` bounds the+ * scan, `documents.path` is UNIQUE, and the basename rungs+ * equality-join `idx_documents_basename`.+ */+export function linkResolutionCounts(db: Database): LinkResolutionCounts {+ const row = db+ .query<{ total: number; unresolved: number | null }, []>(+ "SELECT count(*) AS total, " ++ `sum(CASE WHEN ${RESOLVED_LINK_TARGET_SQL} IS NULL THEN 1 ELSE 0 END) AS unresolved ` ++ "FROM links l WHERE l.target_path IS NOT NULL",+ )+ .get();+ return Object.freeze({ total: row?.total ?? 0, unresolved: row?.unresolved ?? 0 });+}++/**+ * Every link edge resolved to a (source, target) document-id pair,+ * deduplicated, using the same conservative resolution ladder as+ * `typedRelationEdgesForDocuments`: materialized id first,+ * then `<target>.md` exact, then an UNAMBIGUOUS basename suffix.+ * Unresolvable edges are absent. Read-only; feeds bridge discovery+ * and community detection (link-recall-intelligence).+ */+export function resolvedDocLinkPairs(+ db: Database,+): Array<{ readonly source: number; readonly target: number }> {+ const rows = db+ .query<{ source: number; target: number | null }, []>(+ // The ladder itself lives in RESOLVED_LINK_TARGET_SQL, shared+ // with `linkResolutionCounts` so the edges this yields and the+ // rows that gate counts as broken are two views of one rule.+ "SELECT DISTINCT l.source_document_id AS source, " ++ ` ${RESOLVED_LINK_TARGET_SQL} AS target ` ++ "FROM links l WHERE l.target_path IS NOT NULL",+ )+ .all();+ const out: Array<{ source: number; target: number }> = [];+ for (const r of rows) {+ if (r.target !== null) out.push({ source: r.source, target: r.target });+ }+ return out;+}++/**+ * For each chunk id, return the document ids that link TO that+ * chunk's document via wikilink or markdown_link. Pure data; the+ * ranker decides how to convert this into a boost.+ */+export function inboundLinkSources(+ db: Database,+ candidateChunkIds: ReadonlyArray<number>,+): Map<number, Set<number>> {+ const out = new Map<number, Set<number>>();+ if (candidateChunkIds.length === 0) return out;+ const placeholders = sqlPlaceholders(candidateChunkIds);+ const rows = db+ .query<{ chunk_id: number; source_document_id: number }, number[]>(+ "SELECT c.id AS chunk_id, l.source_document_id " ++ `FROM chunks c JOIN links l ON l.target_document_id = c.document_id ` ++ `WHERE c.id IN (${placeholders}) AND l.link_type IN ${NAVIGABLE_LINK_TYPES_SQL} ` ++ ` AND l.source_document_id != c.document_id`,+ )+ .all(...(candidateChunkIds as number[]));+ for (const r of rows) {+ let set = out.get(r.chunk_id);+ if (!set) {+ set = new Set();+ out.set(r.chunk_id, set);+ }+ set.add(r.source_document_id);+ }+ return out;+}++/**+ * For each source document id, the list of resolved outbound link+ * target document ids (wikilink / markdown_link only; tags and+ * unresolved targets excluded; self-links dropped). Used by the+ * recall traversal layer to walk one or more hops out from a hit.+ */+export function outboundLinkTargets(+ db: Database,+ sourceDocumentIds: ReadonlyArray<number>,+): Map<number, number[]> {+ const out = new Map<number, number[]>();+ if (sourceDocumentIds.length === 0) return out;+ const placeholders = sqlPlaceholders(sourceDocumentIds);+ const rows = db+ .query<{ source_document_id: number; target_document_id: number }, number[]>(+ "SELECT DISTINCT l.source_document_id, l.target_document_id " ++ `FROM links l ` ++ `WHERE l.source_document_id IN (${placeholders}) ` ++ ` AND l.target_document_id IS NOT NULL ` ++ ` AND l.target_document_id != l.source_document_id ` ++ ` AND l.link_type IN ${NAVIGABLE_LINK_TYPES_SQL} ` ++ `ORDER BY l.source_document_id, l.target_document_id`,+ )+ .all(...(sourceDocumentIds as number[]));+ for (const r of rows) {+ let list = out.get(r.source_document_id);+ if (!list) {+ list = [];+ out.set(r.source_document_id, list);+ }+ list.push(r.target_document_id);+ }+ return out;+}++/**+ * For each chunk id, the set of tag link_text values associated with+ * its document. Two chunks "share a tag" iff their tag sets intersect.+ */+export function tagsByChunkDocument(+ db: Database,+ candidateChunkIds: ReadonlyArray<number>,+): Map<number, Set<string>> {+ const out = new Map<number, Set<string>>();+ if (candidateChunkIds.length === 0) return out;+ const placeholders = sqlPlaceholders(candidateChunkIds);+ const rows = db+ .query<{ chunk_id: number; tag: string }, number[]>(+ "SELECT c.id AS chunk_id, l.link_text AS tag " ++ `FROM chunks c JOIN links l ON l.source_document_id = c.document_id ` ++ `WHERE c.id IN (${placeholders}) AND l.link_type = 'tag' AND l.link_text IS NOT NULL`,+ )+ .all(...(candidateChunkIds as number[]));+ for (const r of rows) {+ let set = out.get(r.chunk_id);+ if (!set) {+ set = new Set();+ out.set(r.chunk_id, set);+ }+ set.add(r.tag);+ }+ return out;+}diff --git a/src/core/search/store/query-cache-table.ts b/src/core/search/store/query-cache-table.tsnew file mode 100644index 00000000..db6c0bc7--- /dev/null+++ b/src/core/search/store/query-cache-table.ts@@ -0,0 +1,55 @@+/**+ * The `query_cache` table (v0.20.0): serialized search payloads keyed by+ * cache key and stamped with the corpus generation that produced them.+ * Storage only - what is cacheable and for how long is `query-cache.ts`'s+ * decision.+ */++import { Database } from "bun:sqlite";++export interface QueryCacheRow {+ readonly generation: string;+ readonly payload: string;+ readonly createdAt: number;+}++export function queryCacheGet(db: Database, key: string): QueryCacheRow | null {+ const row = db+ .query<{ generation: string; payload: string; created_at: number }, [string]>(+ "SELECT generation, payload, created_at FROM query_cache WHERE cache_key = ?",+ )+ .get(key);+ if (!row) return null;+ return {+ generation: row.generation,+ payload: row.payload,+ createdAt: row.created_at,+ };+}++export function queryCachePut(+ db: Database,+ key: string,+ generation: string,+ payload: string,+ createdAtMs: number,+): void {+ db.run(+ "INSERT INTO query_cache(cache_key, generation, payload, created_at) VALUES (?, ?, ?, ?) " ++ "ON CONFLICT(cache_key) DO UPDATE SET generation = excluded.generation, " ++ "payload = excluded.payload, created_at = excluded.created_at",+ [key, generation, payload, createdAtMs],+ );+}++/** Delete rows from a stale generation or created before the cutoff. */+export function queryCacheSweep(+ db: Database,+ currentGeneration: string,+ expiredBeforeMs: number,+): void {+ db.run("DELETE FROM query_cache WHERE generation <> ? OR created_at < ?", [+ currentGeneration,+ expiredBeforeMs,+ ]);+}diff --git a/src/core/search/store/relations.ts b/src/core/search/store/relations.tsnew file mode 100644index 00000000..73dd0385--- /dev/null+++ b/src/core/search/store/relations.ts@@ -0,0 +1,251 @@+/**+ * Typed relation edges (v3 / typed graph semantics): the `links` rows+ * whose `relation` is set, the schema-pack constraints that block them,+ * and the endpoint resolution those reads share.+ *+ * Separate from `links.ts` because the reason to change is different:+ * this module follows the relation vocabulary and its constraints, not+ * the syntactic link rows themselves.+ */++import { Database } from "bun:sqlite";++import { sqlPlaceholders } from "./sql.ts";++/**+ * Endpoint resolution for a typed edge, as one SQL expression over a+ * `links` row aliased `l`. Wikilink-style relation targets are usually+ * bare ids (`[[note]]` -> `note`) that the generic `resolveLinkTargets`+ * exact-path pass cannot match against `note.md`, so the ladder also+ * tries `<target>.md` and - when unambiguous - a path-suffix match.+ * Ambiguous suffixes stay unresolved.+ *+ * Shared by all three typed-edge reads below so an edge cannot count as+ * resolved in one and dangling in another.+ */+const TYPED_RELATION_TARGET_SQL =+ "COALESCE(" ++ " l.target_document_id, " ++ " (SELECT d.id FROM documents d WHERE d.path = l.target_path || '.md'), " ++ " (SELECT d.id FROM documents d " ++ " WHERE SUBSTR(d.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md' " ++ " AND 1 = (SELECT COUNT(*) FROM documents d2 " ++ " WHERE SUBSTR(d2.path, -(LENGTH(l.target_path) + 4)) = '/' || l.target_path || '.md'))" ++ " )";++/**+ * The join that hangs both endpoints' `page_type` off a typed edge: the+ * source document is required, the target is whatever+ * {@link TYPED_RELATION_TARGET_SQL} resolves to.+ */+const TYPED_RELATION_ENDPOINTS_SQL =+ "FROM links l " ++ "JOIN documents sd ON sd.id = l.source_document_id " ++ "LEFT JOIN documents td ON td.id = " ++ TYPED_RELATION_TARGET_SQL ++ " ";++/**+ * For each document id, the typed relation edges it declares+ * (v3 / typed graph semantics): rows whose `relation` is set, in+ * insertion order. The target is the edge's `target_path` as written.+ * Documents with no typed edges are absent from the returned map.+ */+export function typedRelationsForDocuments(+ db: Database,+ documentIds: ReadonlyArray<number>,+): Map<number, Array<{ relation: string; target: string }>> {+ const out = new Map<number, Array<{ relation: string; target: string }>>();+ if (documentIds.length === 0) return out;+ const placeholders = sqlPlaceholders(documentIds);+ const rows = db+ .query<+ {+ source_document_id: number;+ relation: string;+ target_path: string | null;+ },+ number[]+ >(+ "SELECT source_document_id, relation, target_path FROM links " ++ `WHERE source_document_id IN (${placeholders}) AND relation IS NOT NULL ` ++ "AND relation_blocked = 0 " ++ "ORDER BY id",+ )+ .all(...(documentIds as number[]));+ for (const r of rows) {+ const target = r.target_path ?? "";+ if (target === "") continue;+ const arr = out.get(r.source_document_id);+ const edge = { relation: r.relation, target };+ if (arr) arr.push(edge);+ else out.set(r.source_document_id, [edge]);+ }+ return out;+}++/**+ * Typed relation edges declared by the given documents, with the+ * target resolved to a document id when possible (recall-trust-suite,+ * relation polarity). Ambiguous basenames stay unresolved+ * (deterministic inertness beats guessing the wrong page).+ */+export function typedRelationEdgesForDocuments(+ db: Database,+ documentIds: ReadonlyArray<number>,+): Array<{+ readonly sourceDocumentId: number;+ readonly relation: string;+ readonly target: string;+ readonly targetDocumentId: number | null;+}> {+ if (documentIds.length === 0) return [];+ const placeholders = sqlPlaceholders(documentIds);+ const rows = db+ .query<+ {+ source_document_id: number;+ relation: string;+ target_path: string | null;+ resolved_target_id: number | null;+ },+ number[]+ >(+ "SELECT l.source_document_id, l.relation, l.target_path, " ++ ` ${TYPED_RELATION_TARGET_SQL} AS resolved_target_id ` ++ "FROM links l " ++ `WHERE l.source_document_id IN (${placeholders}) AND l.relation IS NOT NULL ` ++ "AND l.relation_blocked = 0 " ++ "ORDER BY l.id",+ )+ .all(...(documentIds as number[]));+ const out: Array<{+ sourceDocumentId: number;+ relation: string;+ target: string;+ targetDocumentId: number | null;+ }> = [];+ for (const r of rows) {+ const target = r.target_path ?? "";+ if (target === "") continue;+ out.push({+ sourceDocumentId: r.source_document_id,+ relation: r.relation,+ target,+ targetDocumentId: r.resolved_target_id,+ });+ }+ return out;+}++/**+ * Recompute every typed edge's `relation_blocked` flag from the+ * current schema-pack constraints (write-time-integrity-governance).+ * Runs after `resolveLinkTargets` on every index pass, so removing a+ * constraint restores blocked edges on the next run without touching+ * files. Returns the rows that ended up blocked. With an empty+ * constraint map the pass only resets stale flags.+ */+export function recomputeRelationConstraintFlags(+ db: Database,+ constraints: Readonly<Record<string, ReadonlyArray<string>>>,+): Array<{+ readonly relation: string;+ readonly sourcePath: string;+ readonly targetPath: string;+ readonly sourceType: string;+ readonly targetType: string;+ readonly declared: ReadonlyArray<string>;+}> {+ const rows = db+ .query<+ {+ id: number;+ relation: string;+ blocked: number;+ source_path: string;+ source_type: string | null;+ target_path: string | null;+ target_type: string | null;+ },+ []+ >(+ "SELECT l.id, l.relation, l.relation_blocked AS blocked, " ++ " sd.path AS source_path, sd.page_type AS source_type, " ++ " l.target_path, td.page_type AS target_type " ++ TYPED_RELATION_ENDPOINTS_SQL ++ "WHERE l.relation IS NOT NULL",+ )+ .all();+ const block = db.query("UPDATE links SET relation_blocked = 1 WHERE id = ?");+ const unblock = db.query("UPDATE links SET relation_blocked = 0 WHERE id = ?");+ const violations: Array<{+ relation: string;+ sourcePath: string;+ targetPath: string;+ sourceType: string;+ targetType: string;+ declared: ReadonlyArray<string>;+ }> = [];+ for (const row of rows) {+ const declared = constraints[row.relation];+ const allowed =+ declared === undefined ||+ declared.length === 0 ||+ row.source_type === null ||+ row.target_type === null ||+ declared.includes(`${row.source_type}->${row.target_type}`);+ if (allowed) {+ if (row.blocked !== 0) unblock.run(row.id);+ continue;+ }+ if (row.blocked === 0) block.run(row.id);+ violations.push({+ relation: row.relation,+ sourcePath: row.source_path,+ targetPath: row.target_path ?? "",+ sourceType: row.source_type!,+ targetType: row.target_type!,+ declared: declared!,+ });+ }+ return violations;+}++/**+ * The typed edges currently blocked by link constraints, for lint+ * surfacing. Read-only over the flags the last index pass computed.+ */+export function blockedRelationRows(db: Database): Array<{+ readonly relation: string;+ readonly sourcePath: string;+ readonly targetPath: string;+ readonly sourceType: string | null;+ readonly targetType: string | null;+}> {+ return db+ .query<+ {+ relation: string;+ source_path: string;+ target_path: string | null;+ source_type: string | null;+ target_type: string | null;+ },+ []+ >(+ "SELECT l.relation, sd.path AS source_path, l.target_path, " ++ " sd.page_type AS source_type, td.page_type AS target_type " ++ TYPED_RELATION_ENDPOINTS_SQL ++ "WHERE l.relation IS NOT NULL AND l.relation_blocked = 1 " ++ "ORDER BY sd.path, l.id",+ )+ .all()+ .map((r) => ({+ relation: r.relation,+ sourcePath: r.source_path,+ targetPath: r.target_path ?? "",+ sourceType: r.source_type,+ targetType: r.target_type,+ }));+}diff --git a/src/core/search/store/sql.ts b/src/core/search/store/sql.tsnew file mode 100644index 00000000..7c82405c--- /dev/null+++ b/src/core/search/store/sql.ts@@ -0,0 +1,15 @@+/**+ * SQL text helpers shared by the per-table modules behind `Store`. One+ * spelling of a placeholder list and one of the instant every table+ * stamps, so the tables cannot drift into two.+ */++/** `?,?,...` placeholder list for a SQL `IN (...)` clause of `items.length` params. */+export function sqlPlaceholders(items: ReadonlyArray<unknown>): string {+ return items.map(() => "?").join(",");+}++/** The instant recorded in every `created_at` / `updated_at` / `indexed_at` column. */+export function nowIso(): string {+ return new Date().toISOString();+}diff --git a/src/core/search/store/state.ts b/src/core/search/store/state.tsnew file mode 100644index 00000000..7c9a5cd7--- /dev/null+++ b/src/core/search/store/state.ts@@ -0,0 +1,216 @@+/**+ * The `index_state` key/value table: every fact the index records about+ * itself (embedding identity, revision counter, index-run timestamps),+ * plus the synchronous read-only peeks that observe those facts without+ * opening a `Store`.+ *+ * The key namespace lives here in full so no two readers of the same+ * cell can spell its key differently.+ */++import { Database } from "bun:sqlite";+import { existsSync } from "node:fs";++import { computeCorpusGeneration } from "../corpus-generation.ts";+import { LATEST_SCHEMA_VERSION, readSchemaVersion } from "../schema.ts";+import { nowIso } from "./sql.ts";++/**+ * `index_state` keys for the active embedding instruction prefixes+ * (memory-write-path-integrity B2). Recorded per index run so a later+ * stored-vs-configured mismatch can surface the reindex-required warning:+ * vectors embedded under one prefix pair are not comparable to queries+ * embedded under another.+ */+export const EMBEDDING_PREFIX_QUERY_STATE_KEY = "embedding_prefix_query";+export const EMBEDDING_PREFIX_PASSAGE_STATE_KEY = "embedding_prefix_passage";++/**+ * `index_state` keys behind the corpus-generation fingerprint. Named so+ * the class accessors and {@link readCorpusGenerationSync} cannot drift+ * into two spellings of the same key.+ */+export const EMBEDDING_MODEL_STATE_KEY = "embedding_model";+export const EMBEDDING_DIMENSION_STATE_KEY = "embedding_dimension";+export const INDEX_REVISION_STATE_KEY = "index_revision";++/**+ * sqlite-vec version the stored vectors were written against+ * (context-integrity-gates, Unit E). `SELECT vec_version()` was already+ * executed on every extension load and the row discarded every time;+ * this key is where it now lands, so the ABI the vectors were produced+ * under can be compared later instead of assumed.+ */+export const EMBEDDING_VEC_VERSION_STATE_KEY = "embedding_vec_version";++/**+ * `index_state` keys stamped by every index run (`last_indexed_at`) and+ * by a FORCED one only (`last_full_index_at`). Both carry the same ISO+ * instant when the run was forced, which is what makes their equality a+ * usable "the last run resolved the whole vault" predicate - the+ * precondition the broken-link ratchet verifies before it trusts a+ * dangling count (context-integrity-gates, unit G).+ */+export const LAST_INDEXED_AT_STATE_KEY = "last_indexed_at";+export const LAST_FULL_INDEX_AT_STATE_KEY = "last_full_index_at";++const SELECT_STATE_SQL = "SELECT value FROM index_state WHERE key = ?";++export function getState(db: Database, key: string): string | null {+ const row = db.query<{ value: string }, [string]>(SELECT_STATE_SQL).get(key);+ return row?.value ?? null;+}++export function setState(db: Database, key: string, value: string): void {+ db.run(+ "INSERT INTO index_state(key, value, updated_at) VALUES (?, ?, ?) " ++ "ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",+ [key, value, nowIso()],+ );+}++export function deleteState(db: Database, key: string): void {+ db.run("DELETE FROM index_state WHERE key = ?", [key]);+}++/**+ * A stored revision counter as a non-negative integer; anything absent,+ * unparseable or negative reads as 0. Shared by the store accessor and+ * the synchronous peek so a malformed cell cannot mean two different+ * generations depending on who read it.+ */+function parseIndexRevision(raw: string | null): number {+ const n = raw === null ? 0 : Number(raw);+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;+}++/** A stored embedding dimension, or null when absent or unparseable. */+function parseEmbeddingDimension(raw: string | null): number | null {+ const dim = raw === null ? null : Number(raw);+ return dim !== null && Number.isFinite(dim) ? dim : null;+}++/** Monotonic counter bumped on every index mutation; 0 if never set. */+export function indexRevision(db: Database): number {+ return parseIndexRevision(getState(db, INDEX_REVISION_STATE_KEY));+}++/** Increment the index revision. Called after a mutating index run. */+export function bumpIndexRevision(db: Database): void {+ setState(db, INDEX_REVISION_STATE_KEY, String(indexRevision(db) + 1));+}++/**+ * Current corpus-generation fingerprint: embedding model + dimension ++ * schema version + index revision. The query cache gates on this so any+ * embedding change or content reindex invalidates cached results.+ */+export function corpusGeneration(db: Database): string {+ return computeCorpusGeneration({+ embeddingModel: getState(db, EMBEDDING_MODEL_STATE_KEY),+ embeddingDimension: parseEmbeddingDimension(getState(db, EMBEDDING_DIMENSION_STATE_KEY)),+ schemaVersion: LATEST_SCHEMA_VERSION,+ indexRevision: indexRevision(db),+ });+}++/**+ * Outcome of a synchronous peek at the index.+ *+ * ABSENT and UNREADABLE used to collapse to one `null`, which is wrong+ * for a stamp: "no index here" and "an index that exists and is corrupt"+ * are different states of the world, and a caller that records both as+ * unrecorded makes two such sides compare EQUAL - "two unrecorded sides+ * are not a finding" - so a corrupt index silently agrees with a missing+ * one. They are now separate arms and the caller chooses.+ */+export type IndexPeek<T> =+ | { readonly kind: "read"; readonly value: T }+ | { readonly kind: "absent" }+ | { readonly kind: "unreadable"; readonly detail: string };++/**+ * Run `read` against a read-only handle on the index, naming which of+ * the three outcomes occurred. Shared by the synchronous peeks so the+ * classification lives in one place rather than once per caller.+ */+export function peekReadonlyIndex<T>(+ dbPath: string,+ read: (state: (key: string) => string | null, db: Database) => T,+): IndexPeek<T> {+ if (!existsSync(dbPath)) return { kind: "absent" };+ let db: Database;+ try {+ db = new Database(dbPath, { readonly: true });+ } catch (e) {+ return { kind: "unreadable", detail: e instanceof Error ? e.message : String(e) };+ }+ try {+ return {+ kind: "read",+ value: read((key: string): string | null => getState(db, key), db),+ };+ } catch (e) {+ return { kind: "unreadable", detail: e instanceof Error ? e.message : String(e) };+ } finally {+ try {+ db.close();+ } catch {+ /* a close failure cannot change what was already read */+ }+ }+}++/**+ * {@link peekReadonlyIndex} collapsed to `T | null` for the callers that+ * genuinely cannot act on the distinction.+ */+export function withReadonlyIndex<T>(+ dbPath: string,+ read: (state: (key: string) => string | null, db: Database) => T,+): T | null {+ const peek = peekReadonlyIndex(dbPath, read);+ return peek.kind === "read" ? peek.value : null;+}++/**+ * Corpus-generation fingerprint read WITHOUT opening a `Store`.+ *+ * `Store.open` is async (the write path acquires a lock) and a read open+ * refuses a schema mismatch, so neither form is usable from a+ * synchronous caller that only wants to observe the index's identity and+ * must keep working when there is no index at all. The context pack's+ * provenance stamp (context-integrity-gates, Unit B) is exactly that+ * caller. It lives here rather than beside the caller because this+ * module is the single SQL boundary for the index.+ *+ * Returns `null` - "unrecorded", per `integrity/stamp.ts` - when the+ * index file is absent or cannot be read. That is DISTINCT from a+ * recorded generation string: a vault that gains or loses its index+ * drifts from `null` to a value (or back) and the stamp comparison names+ * it, rather than treating "nothing to compare" as agreement.+ *+ * The schema version comes from the file itself, not from+ * {@link LATEST_SCHEMA_VERSION}: an index still at an older schema is a+ * different corpus state, and folding it onto the current constant would+ * hide precisely that.+ */+export function readCorpusGenerationSync(dbPath: string): string | null {+ const peek = peekCorpusGenerationSync(dbPath);+ return peek.kind === "read" ? peek.value : null;+}++/**+ * {@link readCorpusGenerationSync} with the three outcomes kept apart, so+ * a caller that must not treat a corrupt index as "no index" can tell.+ */+export function peekCorpusGenerationSync(dbPath: string): IndexPeek<string | null> {+ return peekReadonlyIndex(dbPath, (read, db) =>+ computeCorpusGeneration({+ embeddingModel: read(EMBEDDING_MODEL_STATE_KEY),+ embeddingDimension: parseEmbeddingDimension(read(EMBEDDING_DIMENSION_STATE_KEY)),+ schemaVersion: readSchemaVersion(db),+ indexRevision: parseIndexRevision(read(INDEX_REVISION_STATE_KEY)),+ }),+ );+}diff --git a/src/core/search/store/tiers.ts b/src/core/search/store/tiers.tsnew file mode 100644index 00000000..b8a369cd--- /dev/null+++ b/src/core/search/store/tiers.ts@@ -0,0 +1,118 @@+/**+ * Tiered-frontmatter identity (write-time-integrity-governance): the+ * per-document snapshot the last index pass recorded, and the+ * `tier_drift` rows that stage hand-edits of an identity field.+ */++import { Database } from "bun:sqlite";++/** Parse a JSON-encoded drift value; a corrupt cell surfaces as-is. */+function parseJsonValue(raw: string): unknown {+ try {+ return JSON.parse(raw);+ } catch {+ return raw;+ }+}++/**+ * The tiered-frontmatter snapshot the last index pass recorded for a+ * document, or null when none exists.+ */+export function getTierSnapshot(db: Database, documentId: number): Record<string, unknown> | null {+ const row = db+ .query<{ tier_snapshot: string | null }, [number]>(+ "SELECT tier_snapshot FROM documents WHERE id = ?",+ )+ .get(documentId);+ if (!row || row.tier_snapshot === null) return null;+ try {+ const parsed: unknown = JSON.parse(row.tier_snapshot);+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {+ return parsed as Record<string, unknown>;+ }+ return null;+ } catch {+ return null;+ }+}++export function setTierSnapshot(+ db: Database,+ documentId: number,+ snapshot: Readonly<Record<string, unknown>>,+): void {+ db.run("UPDATE documents SET tier_snapshot = ? WHERE id = ?", [+ JSON.stringify(snapshot),+ documentId,+ ]);+}++/** Stage one identity-field hand-edit; (document, field) upserts. */+export function upsertTierDrift(+ db: Database,+ input: {+ readonly documentId: number;+ readonly field: string;+ readonly expected: unknown;+ readonly actual: unknown;+ readonly detectedAt: string;+ },+): void {+ db.run(+ "INSERT INTO tier_drift(document_id, field, expected, actual, detected_at) " ++ "VALUES (?, ?, ?, ?, ?) " ++ "ON CONFLICT(document_id, field) DO UPDATE SET actual = excluded.actual",+ [+ input.documentId,+ input.field,+ JSON.stringify(input.expected),+ JSON.stringify(input.actual),+ input.detectedAt,+ ],+ );+}++export function clearTierDrift(db: Database, documentId: number, field?: string): void {+ if (field === undefined) {+ db.run("DELETE FROM tier_drift WHERE document_id = ?", [documentId]);+ } else {+ db.run("DELETE FROM tier_drift WHERE document_id = ? AND field = ?", [documentId, field]);+ }+}++/** Open identity-drift findings, oldest first, with document paths. */+export function listTierDrift(db: Database): Array<{+ readonly documentId: number;+ readonly path: string;+ readonly field: string;+ readonly expected: unknown;+ readonly actual: unknown;+ readonly detectedAt: string;+}> {+ return db+ .query<+ {+ document_id: number;+ path: string;+ field: string;+ expected: string;+ actual: string;+ detected_at: string;+ },+ []+ >(+ "SELECT t.document_id, d.path, t.field, t.expected, t.actual, t.detected_at " ++ "FROM tier_drift t JOIN documents d ON d.id = t.document_id " ++ "ORDER BY t.detected_at, t.id",+ )+ .all()+ .map((r) => ({+ documentId: r.document_id,+ path: r.path,+ field: r.field,+ expected: parseJsonValue(r.expected),+ actual: parseJsonValue(r.actual),+ detectedAt: r.detected_at,+ }));+}diff --git a/src/core/search/store/trigram.ts b/src/core/search/store/trigram.tsnew file mode 100644index 00000000..d746b379--- /dev/null+++ b/src/core/search/store/trigram.ts@@ -0,0 +1,123 @@+/**+ * The `chunk_trigram` FTS5 shadow (v9): an opt-in candidate source that+ * broadens large-vault keyword recall with the substring / partial-token+ * matches the word tokenizer misses.+ */++import { Database } from "bun:sqlite";++import type { KeywordHit } from "./keyword.ts";++/**+ * What the lane returns: the candidates it gathered plus the warnings its+ * caller owes the query. Same shape as the keyword lane's own outcome,+ * because the two fill the same candidate pool.+ */+export interface TrigramCandidateOutcome {+ readonly hits: KeywordHit[];+ readonly warnings: ReadonlyArray<string>;+}++const NO_WARNINGS: ReadonlyArray<string> = Object.freeze([]);++/**+ * The one condition this lane stays SILENT for: `chunk_trigram` itself is+ * absent, which is a store migrated to v9 but never rebuilt - the table+ * is documented as optional. Anchored on the right, because a message+ * naming `chunk_trigram_data` / `_idx` / `_content` / `_docsize` names an+ * FTS5 shadow the index has LOST: the index HAS the trigram table and+ * cannot read it, which is corruption and must be reported, not silently+ * answered with an empty candidate list.+ */+export function isMissingTrigramTable(message: string): boolean {+ return /no such table:?\s*(?:main\.)?chunk_trigram(?![A-Za-z0-9_])/i.test(message);+}++/**+ * Why the lane could not answer, as a closed vocabulary. The SQLite+ * message itself never reaches the warning: FTS5 reports a rejected MATCH+ * by echoing the expression, and that expression is built from the+ * caller's query, while other messages can name the index file - a+ * warning travels into logs and MCP payloads, so it carries a cause and+ * never content.+ */+type TrigramFault =+ | "locked"+ | "tokenizer_unavailable"+ | "corrupt"+ | "shadow_incomplete"+ | "unknown";++function classifyTrigramFault(message: string): TrigramFault {+ if (/\bis locked\b|SQLITE_BUSY/i.test(message)) return "locked";+ if (/no such tokenizer/i.test(message)) return "tokenizer_unavailable";+ if (/malformed|corrupt/i.test(message)) return "corrupt";+ if (/no such (?:table|column|module)/i.test(message)) return "shadow_incomplete";+ return "unknown";+}++/**+ * The lane only ever ADDS to a pool the keyword lane already filled, so a+ * fault degrades the lane instead of failing the query - but visibly:+ * `trigram_degraded` is the greppable flag, alongside `hybrid_degraded`+ * for the semantic lane. A silent empty list here would narrow recall+ * while reading as a vault with nothing to match.+ */+function degradeWarning(fault: TrigramFault): string {+ return `trigram_degraded [${fault}]: trigram candidate lane skipped; keyword candidates unaffected`;+}++/**+ * Trigram candidate lookup over the `chunk_trigram` FTS5 shadow (v9).+ * Returns bm25-ordered keyword hits whose content matches the trigram+ * query - a strict superset of exact substring matches for the query's+ * terms, used as an opt-in candidate source that broadens large-vault+ * keyword recall (substring / partial-token matches the word tokenizer+ * misses). Yields no candidates and no warning when the trigram table is+ * absent; any other fault yields no candidates and one warning naming+ * the cause.+ */+export function trigramCandidates(+ db: Database,+ trigramQuery: string,+ opts: { readonly limit: number; readonly pathPrefix?: string | null },+): TrigramCandidateOutcome {+ const limit = Math.max(1, opts.limit | 0);+ const prefix = opts.pathPrefix && opts.pathPrefix.length > 0 ? opts.pathPrefix : null;+ try {+ if (prefix) {+ const rows = db+ .query<+ { chunk_id: number; document_id: number; bm25: number },+ [string, string, string, number]+ >(+ "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_trigram) AS bm25 " ++ "FROM chunk_trigram " ++ "JOIN chunks c ON c.id = chunk_trigram.rowid " ++ "JOIN documents d ON d.id = c.document_id " ++ "WHERE chunk_trigram MATCH ? AND substr(d.path, 1, length(?)) = ? " ++ "ORDER BY bm25 ASC LIMIT ?",+ )+ .all(trigramQuery, prefix, prefix, limit);+ return {+ hits: rows.map((r) => ({ chunkId: r.chunk_id, documentId: r.document_id, bm25: r.bm25 })),+ warnings: NO_WARNINGS,+ };+ }+ const rows = db+ .query<{ chunk_id: number; document_id: number; bm25: number }, [string, number]>(+ "SELECT c.id AS chunk_id, c.document_id AS document_id, bm25(chunk_trigram) AS bm25 " ++ "FROM chunk_trigram JOIN chunks c ON c.id = chunk_trigram.rowid " ++ "WHERE chunk_trigram MATCH ? ORDER BY bm25 ASC LIMIT ?",+ )+ .all(trigramQuery, limit);+ return {+ hits: rows.map((r) => ({ chunkId: r.chunk_id, documentId: r.document_id, bm25: r.bm25 })),+ warnings: NO_WARNINGS,+ };+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ if (isMissingTrigramTable(msg)) return { hits: [], warnings: NO_WARNINGS };+ return { hits: [], warnings: Object.freeze([degradeWarning(classifyTrigramFault(msg))]) };+ }+}diff --git a/src/core/search/store/vectors.ts b/src/core/search/store/vectors.tsnew file mode 100644index 00000000..3fccabb0--- /dev/null+++ b/src/core/search/store/vectors.ts@@ -0,0 +1,417 @@+/**+ * The semantic lane: the sqlite-vec extension, the `chunk_vec` virtual+ * table and its `chunk_vec_map` rowid bridge, the `embeddings` metadata+ * rows, and the k-nearest-neighbour query over them.+ *+ * The two-step deletion of `chunk_vec` rows that the SQLite FK cascade+ * does NOT reach (design Β§5) is centralised here, which is why the+ * document and chunk modules delete through this one.+ */++import { Database } from "bun:sqlite";++import { dropVecTable, ensureVecTable } from "../schema.ts";+import { SearchError } from "../types.ts";+import { assertValidVector } from "../vector-guard.ts";+import {+ deleteState,+ EMBEDDING_DIMENSION_STATE_KEY,+ EMBEDDING_MODEL_STATE_KEY,+ EMBEDDING_PREFIX_PASSAGE_STATE_KEY,+ EMBEDDING_PREFIX_QUERY_STATE_KEY,+ EMBEDDING_VEC_VERSION_STATE_KEY,+ getState,+ setState,+} from "./state.ts";+import { nowIso, sqlPlaceholders } from "./sql.ts";++/** The query/passage instruction prefixes active for an index run. */+export interface EmbeddingPrefixPair {+ readonly query: string;+ readonly passage: string;+}++export interface SemanticHit {+ readonly chunkId: number;+ readonly documentId: number;+ /** L2 distance on unit-normalised vectors. */+ readonly distance: number;+}++export interface ModelChangeOutcome {+ readonly wasChanged: boolean;+ readonly previousModel: string | null;+ readonly previousDimension: number | null;+ readonly currentModel: string | null;+ readonly currentDimension: number | null;+}++/** What an open connection knows about sqlite-vec. */+export interface VecRuntime {+ readonly loaded: boolean;+ /** The version the extension reported, or null when it never loaded. */+ readonly version: string | null;+}++/**+ * Load sqlite-vec and return the version it reports, or `null` when the+ * extension is unavailable.+ *+ * The `vec_version()` probe was always executed and its row always+ * discarded; returning it costs nothing and is what lets the ABI the+ * vectors were written against be stamped rather than assumed+ * (context-integrity-gates, Unit E). `null` doubles as the+ * "not loaded" signal, so there is exactly one source of truth for both+ * facts.+ */+export function loadVecExtension(db: Database): string | null {+ try {+ // sqlite-vec is an optional dependency. Wrap the import + load so+ // a missing platform package degrades to "extension unavailable"+ // instead of crashing the process.+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ const vec = require("sqlite-vec") as { getLoadablePath(): string };+ db.loadExtension(vec.getLoadablePath());+ // Confirm by calling vec_version() β guards against partial loads.+ const row = db.query<{ v: string }, []>("SELECT vec_version() AS v").get();+ return typeof row?.v === "string" ? row.v : null;+ } catch {+ return null;+ }+}++function vecToBuffer(values: ReadonlyArray<number> | Float32Array): Buffer {+ const arr = values instanceof Float32Array ? values : Float32Array.from(values);+ return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);+}++export function purgeVecRowsForDocument(+ db: Database,+ vecLoaded: boolean,+ documentId: number,+): void {+ if (!vecLoaded) return;+ const vecRows = db+ .query<{ vec_rowid: number }, [number]>(+ "SELECT vec_rowid FROM chunk_vec_map WHERE chunk_id IN (SELECT id FROM chunks WHERE document_id = ?)",+ )+ .all(documentId);+ if (vecRows.length === 0) return;+ purgeVecRowidsRaw(+ db,+ vecLoaded,+ vecRows.map((r) => r.vec_rowid),+ );+}++export function purgeVecRowsByChunkIds(+ db: Database,+ vecLoaded: boolean,+ chunkIds: ReadonlyArray<number>,+): void {+ if (!vecLoaded || chunkIds.length === 0) return;+ const placeholders = sqlPlaceholders(chunkIds);+ const vecRows = db+ .query<{ vec_rowid: number }, number[]>(+ `SELECT vec_rowid FROM chunk_vec_map WHERE chunk_id IN (${placeholders})`,+ )+ .all(...(chunkIds as number[]));+ if (vecRows.length === 0) return;+ purgeVecRowidsRaw(+ db,+ vecLoaded,+ vecRows.map((r) => r.vec_rowid),+ );+}++function purgeVecRowidsRaw(db: Database, vecLoaded: boolean, vecRowids: number[]): void {+ if (!vecLoaded || vecRowids.length === 0) return;+ const placeholders = sqlPlaceholders(vecRowids);+ db.run(`DELETE FROM chunk_vec WHERE rowid IN (${placeholders})`, vecRowids);+}++/**+ * Insert or replace a single embedding. The vec table receives the+ * raw float32 bytes; the metadata row in `embeddings` tracks model /+ * dimension / hash for stale detection.+ *+ * Throws VEC_EXTENSION_UNAVAILABLE if sqlite-vec didn't load. The+ * caller decides whether to surface this (explicit semantic) or warn+ * and skip (implicit semantic).+ */+export function vecUpsert(+ db: Database,+ vecLoaded: boolean,+ chunkId: number,+ vector: ReadonlyArray<number> | Float32Array,+ model: string,+ dimension: number,+ embeddingHash: string,+): void {+ if (!vecLoaded) {+ throw new SearchError(+ "VEC_EXTENSION_UNAVAILABLE",+ "sqlite-vec extension not loaded; cannot store embeddings",+ );+ }+ if (vector.length !== dimension) {+ throw new SearchError(+ "EMBEDDING_DIMENSION_MISMATCH",+ `vector dimension ${vector.length} != configured dimension ${dimension}`,+ );+ }+ assertValidVector(vector, "vecUpsert");+ db.exec("BEGIN");+ try {+ const existing = db+ .query<{ vec_rowid: number }, [number]>(+ "SELECT vec_rowid FROM chunk_vec_map WHERE chunk_id = ?",+ )+ .get(chunkId);+ const buf = vecToBuffer(vector);+ let vecRowid: number;+ if (existing) {+ db.run("UPDATE chunk_vec SET embedding = ? WHERE rowid = ?", [buf, existing.vec_rowid]);+ vecRowid = existing.vec_rowid;+ } else {+ db.run("INSERT INTO chunk_vec(embedding) VALUES (?)", [buf]);+ const row = db.query<{ id: number }, []>("SELECT last_insert_rowid() AS id").get();+ if (!row) throw new SearchError("INDEX_UNREADABLE", "chunk_vec insert returned no rowid");+ vecRowid = row.id;+ db.run("INSERT INTO chunk_vec_map(chunk_id, vec_rowid) VALUES (?, ?)", [chunkId, vecRowid]);+ }+ const now = nowIso();+ db.run(+ "INSERT INTO embeddings(chunk_id, model, dimension, embedding_hash, created_at, updated_at) " ++ "VALUES (?, ?, ?, ?, ?, ?) " ++ "ON CONFLICT(chunk_id) DO UPDATE SET " ++ " model = excluded.model, dimension = excluded.dimension, " ++ " embedding_hash = excluded.embedding_hash, updated_at = excluded.updated_at",+ [chunkId, model, dimension, embeddingHash, now, now],+ );+ db.exec("COMMIT");+ } catch (e) {+ db.exec("ROLLBACK");+ throw e;+ }+}++/**+ * The stored embedding for one chunk, or null when the vec layer is+ * unavailable or the chunk was never embedded (surprisal,+ * t_fddfe64a).+ */+export function embeddingForChunk(+ db: Database,+ vecLoaded: boolean,+ chunkId: number,+): Float32Array | null {+ if (!vecLoaded) return null;+ const row = db+ .query<{ embedding: Uint8Array }, [number]>(+ "SELECT v.embedding AS embedding FROM chunk_vec v " ++ "JOIN chunk_vec_map m ON m.vec_rowid = v.rowid WHERE m.chunk_id = ?",+ )+ .get(chunkId);+ if (!row) return null;+ const bytes = row.embedding;+ // Copy instead of viewing: a pooled buffer with a non-4-byte-aligned+ // byteOffset would make the Float32Array constructor throw.+ return new Float32Array(+ bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),+ );+}++export function getEmbeddingHash(db: Database, chunkId: number): string | null {+ const row = db+ .query<{ embedding_hash: string }, [number]>(+ "SELECT embedding_hash FROM embeddings WHERE chunk_id = ?",+ )+ .get(chunkId);+ return row?.embedding_hash ?? null;+}++/** Number of chunks with a stored embedding row. */+export function countEmbeddings(db: Database): number {+ return db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM embeddings").get()?.n ?? 0;+}++/** Embeddings whose `model`/`dimension` no longer match the current config. */+export function staleEmbeddings(+ db: Database,+ model: string | null,+ dimension: number | null,+): number {+ if (!model || !dimension) {+ // No baseline to compare against: 0 stale by convention.+ return 0;+ }+ const row = db+ .query<{ c: number }, [string, number]>(+ "SELECT count(*) AS c FROM embeddings WHERE model != ? OR dimension != ?",+ )+ .get(model, dimension);+ return row?.c ?? 0;+}++/**+ * Drop all embeddings + vec storage. Used when the configured model+ * or dimension changes. `chunks` and `chunk_fts` are preserved.+ */+export function clearEmbeddings(db: Database, vecLoaded: boolean): void {+ db.exec("BEGIN");+ try {+ db.run("DELETE FROM embeddings");+ db.run("DELETE FROM chunk_vec_map");+ if (vecLoaded) dropVecTable(db);+ db.exec("COMMIT");+ } catch (e) {+ db.exec("ROLLBACK");+ throw e;+ }+}++/**+ * Compare the configured embedding model/dimension with what was+ * recorded in `index_state` on the last index run. If they differ+ * and both old + new are non-null, drop embeddings + vec table and+ * log one line per design Β§13. First-time set just records state.+ */+export function ensureEmbeddingModel(+ db: Database,+ vec: VecRuntime,+ model: string | null,+ dimension: number | null,+ prefixes?: EmbeddingPrefixPair,+): ModelChangeOutcome {+ const prevModel = getState(db, EMBEDDING_MODEL_STATE_KEY);+ const prevDimRaw = getState(db, EMBEDDING_DIMENSION_STATE_KEY);+ const prevDim = prevDimRaw === null ? null : Number(prevDimRaw);++ const modelChanged = prevModel !== null && model !== null && prevModel !== model;+ const dimChanged =+ prevDim !== null && dimension !== null && Number.isFinite(prevDim) && prevDim !== dimension;++ // A prefix change invalidates stored vectors exactly as a model/dimension+ // change does: vectors embedded under the old prefix are not comparable to+ // queries embedded under the new one. Reuse the same clear-and-log path.+ const prevQueryPrefix = getState(db, EMBEDDING_PREFIX_QUERY_STATE_KEY);+ const prevPassagePrefix = getState(db, EMBEDDING_PREFIX_PASSAGE_STATE_KEY);+ // Legacy stores predate prefix metadata: absent state (null) means the+ // existing vectors were embedded with EMPTY prefixes. Treat missing state+ // as the empty pair so a switch to non-empty prefixes (e.g. E5's+ // `query:`/`passage:`) is detected as a change and the now-incompatible+ // unprefixed vectors are cleared, rather than silently marked compatible.+ const effectivePrevQueryPrefix = prevQueryPrefix ?? "";+ const effectivePrevPassagePrefix = prevPassagePrefix ?? "";+ const prefixChanged =+ prefixes !== undefined &&+ countEmbeddings(db) > 0 &&+ (effectivePrevQueryPrefix !== prefixes.query ||+ effectivePrevPassagePrefix !== prefixes.passage);++ if (modelChanged || dimChanged) {+ clearEmbeddings(db, vec.loaded);+ // eslint-disable-next-line no-console+ console.error(+ `embedding model changed from ${prevModel}/${prevDim} to ${model}/${dimension}, embeddings cleared`,+ );+ deleteState(db, EMBEDDING_MODEL_STATE_KEY);+ deleteState(db, EMBEDDING_DIMENSION_STATE_KEY);+ // The recorded sqlite-vec version described the vectors that were+ // just cleared, so it must not outlive them: leaving it would+ // claim an ABI for storage that no longer holds any.+ deleteState(db, EMBEDDING_VEC_VERSION_STATE_KEY);+ } else if (prefixChanged) {+ // Model/dimension unchanged: the prefix change alone triggers the clear.+ clearEmbeddings(db, vec.loaded);+ // eslint-disable-next-line no-console+ console.error(+ `embedding prefixes changed from [${effectivePrevQueryPrefix}|${effectivePrevPassagePrefix}] ` ++ `to [${prefixes.query}|${prefixes.passage}], embeddings cleared`,+ );+ }++ if (model !== null) setState(db, EMBEDDING_MODEL_STATE_KEY, model);+ if (dimension !== null) setState(db, EMBEDDING_DIMENSION_STATE_KEY, String(dimension));+ // Same shape as the model and dimension above: recorded only when+ // this build actually has a value. With the extension unavailable+ // there is nothing to record, and writing a placeholder would be a+ // claim about storage this process never touched.+ if (vec.version !== null) {+ setState(db, EMBEDDING_VEC_VERSION_STATE_KEY, vec.version);+ }+ if (prefixes !== undefined) {+ setState(db, EMBEDDING_PREFIX_QUERY_STATE_KEY, prefixes.query);+ setState(db, EMBEDDING_PREFIX_PASSAGE_STATE_KEY, prefixes.passage);+ }++ // (Re)create vec table when we know the dimension and vec is loaded.+ if (vec.loaded && dimension !== null) {+ ensureVecTable(db, dimension);+ }++ return Object.freeze({+ wasChanged: modelChanged || dimChanged,+ previousModel: prevModel,+ previousDimension: prevDim,+ currentModel: model,+ currentDimension: dimension,+ });+}++export function semanticTopK(+ db: Database,+ vecLoaded: boolean,+ queryVector: ReadonlyArray<number> | Float32Array,+ opts: { readonly limit: number; readonly pathPrefix?: string | null },+): SemanticHit[] {+ if (!vecLoaded) {+ throw new SearchError(+ "VEC_EXTENSION_UNAVAILABLE",+ "sqlite-vec extension not loaded; semantic search unavailable",+ );+ }+ const limit = Math.max(1, opts.limit | 0);+ const prefix = opts.pathPrefix && opts.pathPrefix.length > 0 ? opts.pathPrefix : null;++ assertValidVector(queryVector, "semanticTopK");+ const buf = vecToBuffer(queryVector);+ if (prefix) {+ const rows = db+ .query<+ { chunk_id: number; document_id: number; distance: number },+ [Buffer, number, string, string]+ >(+ "SELECT m.chunk_id AS chunk_id, c.document_id AS document_id, v.distance AS distance " ++ "FROM chunk_vec v " ++ "JOIN chunk_vec_map m ON m.vec_rowid = v.rowid " ++ "JOIN chunks c ON c.id = m.chunk_id " ++ "JOIN documents d ON d.id = c.document_id " ++ "WHERE v.embedding MATCH ? AND k = ? AND substr(d.path, 1, length(?)) = ? " ++ "ORDER BY v.distance ASC",+ )+ .all(buf, limit * 4, prefix, prefix);+ return rows.slice(0, limit).map((r) => ({+ chunkId: r.chunk_id,+ documentId: r.document_id,+ distance: r.distance,+ }));+ }++ const rows = db+ .query<{ chunk_id: number; document_id: number; distance: number }, [Buffer, number]>(+ "SELECT m.chunk_id AS chunk_id, c.document_id AS document_id, v.distance AS distance " ++ "FROM chunk_vec v " ++ "JOIN chunk_vec_map m ON m.vec_rowid = v.rowid " ++ "JOIN chunks c ON c.id = m.chunk_id " ++ "WHERE v.embedding MATCH ? AND k = ? " ++ "ORDER BY v.distance ASC",+ )+ .all(buf, limit);+ return rows.map((r) => ({+ chunkId: r.chunk_id,+ documentId: r.document_id,+ distance: r.distance,+ }));+}diff --git a/src/core/search/store/writer-lock.ts b/src/core/search/store/writer-lock.tsnew file mode 100644index 00000000..e7dcad87--- /dev/null+++ b/src/core/search/store/writer-lock.ts@@ -0,0 +1,77 @@+/**+ * The exclusive writer lock on the index path. Every writer - a write+ * open, the reindex rebuild+swap, the crash-recovery restore, an+ * out-of-band FTS rebuild - serialises here, on the LIVE `dbPath`, so+ * there is exactly one lock and one stale window in the system.+ */++import lockfile from "proper-lockfile";++import { SearchError } from "../types.ts";++/**+ * Stale window for the writer lock (ms). A lock whose mtime is older+ * than this is treated as abandoned (crashed holder) and taken over by+ * the next writer, so a SIGKILL never wedges the index for longer than+ * this window.+ */+export const WRITER_LOCK_STALE_MS = 60_000;++/**+ * Heartbeat interval (ms): the async writer lock refreshes its mtime+ * this often so a legitimate long-running index is never mistaken for+ * a stale lock. Must stay below {@link WRITER_LOCK_STALE_MS}. NOTE: the+ * per-file document walk is synchronous, so this timer only fires+ * across the await points (embed batches); a multi-minute fully+ * synchronous walk still relies on the stale window, which 60s amply+ * covers for real vaults.+ */+export const WRITER_LOCK_HEARTBEAT_MS = 30_000;++/** The one message both lock paths report contention with. */+function contentionError(cause: unknown): SearchError {+ const msg = cause instanceof Error ? cause.message : String(cause);+ return new SearchError("INDEX_LOCKED", `another writer holds the search index lock: ${msg}`);+}++export function acquireWriterLockSync(path: string): () => void {+ const maxAttempts = 10;+ const sleepMs = 50;+ let lastError: unknown;+ for (let attempt = 0; attempt < maxAttempts; attempt++) {+ try {+ return lockfile.lockSync(path, { stale: WRITER_LOCK_STALE_MS, realpath: false });+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code !== "ELOCKED") throw err;+ lastError = err;+ if (attempt < maxAttempts - 1) Bun.sleepSync(sleepMs);+ }+ }+ throw contentionError(lastError);+}++/**+ * Acquire the exclusive writer lock on the LIVE index path. Shared by+ * `Store.open({ mode: "write" })` and `reindexVault`'s rebuild+swap so both+ * serialise on the SAME lock (keyed on `dbPath`, not on the `.new` staging+ * path). Fast-fails to `INDEX_LOCKED` after a few retries rather than+ * blocking indefinitely, matching the module's fail-fast contention+ * contract. `realpath: false` lets the lock be taken before `dbPath` exists+ * (a fresh reindex has no live index yet); only the parent directory must+ * already exist.+ */+export async function acquireWriterLock(dbPath: string): Promise<() => Promise<void>> {+ try {+ return await lockfile.lock(dbPath, {+ retries: { retries: 3, factor: 1, minTimeout: 1000, maxTimeout: 1000 },+ stale: WRITER_LOCK_STALE_MS,+ // Explicit heartbeat: refresh the lock mtime mid-run so a long index+ // is never mistaken for a stale lock and taken over.+ update: WRITER_LOCK_HEARTBEAT_MS,+ realpath: false,+ });+ } catch (e) {+ throw contentionError(e);+ }+}diff --git a/src/core/search/temporal-intent.ts b/src/core/search/temporal-intent.tsindex 474e25d6..afba999f 100644--- a/src/core/search/temporal-intent.ts+++ b/src/core/search/temporal-intent.ts@@ -59,7 +59,7 @@ import {isLanguageNeutralTimePoint,type ResolvedTimeRange,} from "./time-range.ts";-import { SearchError } from "./types.ts";+import { SearchError } from "./search-error.ts";const DAY_MS = 24 * 60 * 60 * 1000;diff --git a/src/core/search/time-range.ts b/src/core/search/time-range.tsindex af9f8d7f..1a82dcf0 100644--- a/src/core/search/time-range.ts+++ b/src/core/search/time-range.ts@@ -15,7 +15,7 @@* throws `SearchError("INVALID_INPUT")` β explicit, never silent.*/-import { SearchError } from "./types.ts";+import { SearchError } from "./search-error.ts";const HOUR_MS = 60 * 60 * 1000;const DAY_MS = 24 * HOUR_MS;diff --git a/src/core/search/types.ts b/src/core/search/types.tsindex 862b9c69..f6f03b6a 100644--- a/src/core/search/types.ts+++ b/src/core/search/types.ts@@ -2,6 +2,15 @@* Public types for `src/core/search/*`. Plain data β no behaviour, no I/O.** Anchored in docs/plans/2026-05-16-brain-search-design.md Β§12, Β§14.+ *+ * This module AGGREGATES: it names the leaf types its own dependents own+ * (`DegreePredicate`, `TemporalIntent`, the trust receipts) inside the+ * option / outcome shapes. The two things those dependents need back -+ * the {@link SearchError} carrier and the ranked-hit row - therefore live+ * in leaf modules of their own (`search-error.ts`, `search-result.ts`)+ * and are re-exported here, so no dependent has to point at the+ * aggregate. Import surface unchanged: every symbol this module exported+ * before is still exported from this path.*/import type { DegradationNotice } from "../integrity/degradation.ts";@@ -9,196 +18,22 @@ import type { StampMismatch } from "../integrity/stamp.ts";import type { VaultIgnoreRule } from "../vault-scope/defaults.ts";import type { DegreePredicate } from "./property-filter.ts";import type { TemporalIntent } from "./temporal-intent.ts";+import type { BrainSearchResult, ScoreBreakdown, TrustMetadata } from "./search-result.ts";import type {MemoryTrustAssessment,RetrievalDecisionTrace,} from "../brain/trust/retrieval-receipts.ts";export type { VaultIgnoreRule };--export const SEARCH_ERROR_CODES = [- "INDEX_MISSING",- "INDEX_UNREADABLE",- "SCHEMA_MISMATCH",- "VEC_EXTENSION_UNAVAILABLE",- "EMBEDDING_DISABLED",- "EMBEDDING_KEY_MISSING",- "EMBEDDING_PROVIDER_HTTP",- "EMBEDDING_PROVIDER_TIMEOUT",- "EMBEDDING_DIMENSION_MISMATCH",- "EMBEDDING_INVALID_VECTOR",- "EMBEDDING_COST_GATE",- "EMBEDDING_QUOTA_EXHAUSTED",- "RERANK_PROVIDER_HTTP",- "INDEX_LOCKED",- "INVALID_INPUT",-] as const;-export type SearchErrorCode = (typeof SEARCH_ERROR_CODES)[number];--/**- * Actionable operator-facing message for an exhausted embedding quota /- * billing limit (Task C1/C2). Shared by the provider (thrown message), the- * semantic-phase degrade warning, and the MCP error mapping so the single- * remediation instruction stays consistent across every surface.- */-export const EMBEDDING_QUOTA_MESSAGE =- "embedding quota/billing exhausted: semantic search is degraded to keyword-only. " +- "Check your embedding provider billing and quota, raise the limit or top up, then reindex.";--/**- * Coarse outcome category for an embedding-provider error (Task C1). Drives- * both the retry policy (`retriable`) and the degrade-warning wording.- * `quota` and `auth` fail fast; `rate_limit` and `transient` retry.- */-export type EmbeddingErrorCategory = "quota" | "rate_limit" | "auth" | "transient" | "fatal";--/**- * Additive structured context for a {@link SearchError} originating from a- * provider HTTP response. Both fields are optional so every existing- * two-argument call site stays valid.- */-export interface SearchErrorOptions {- /** Upstream HTTP status code. */- readonly status?: number;- /** Parsed `Retry-After` delay in milliseconds. */- readonly retryAfterMs?: number;-}--export class SearchError extends Error {- readonly code: SearchErrorCode;- /** Upstream HTTP status when this error originated from a provider response. */- readonly status?: number;- /** Parsed `Retry-After` delay in milliseconds when the provider supplied one. */- readonly retryAfterMs?: number;- constructor(code: SearchErrorCode, message: string, opts?: SearchErrorOptions) {- super(message);- this.name = "SearchError";- this.code = code;- if (opts?.status !== undefined) this.status = opts.status;- if (opts?.retryAfterMs !== undefined) this.retryAfterMs = opts.retryAfterMs;- }-}--/**- * Structured per-layer score components (Search & Recall Quality Suite).- * The numeric sibling of `reasons[]`: where `reasons` formats only the- * layers that fired as strings, `breakdown` carries every component of- * the final score as a number, zero for a layer that did not fire and 1- * for a neutral multiplier. Additive layers (keyword, semantic, rrf,- * entity, activation, coAccess, link, recency, sessionFocus) are the raw- * contributions; `tier` and `trend` are the relevance-portion multipliers- * (1.0 = neutral). The ranker emits it for every primary result; the MCP- * `explain` projection and `feedback.ts` read it directly instead of- * re-parsing reason strings.- */-export interface ScoreBreakdown {- readonly keyword: number;- readonly semantic: number;- readonly rrf: number;- readonly entity: number;- readonly activation: number;- readonly coAccess: number;- /** Observed-reuse boost (t_65588d8b); 0 when no verdicts apply. */- readonly reuse: number;- readonly link: number;- readonly recency: number;- readonly tier: number;- readonly trend: number;- readonly sessionFocus: number;- /**- * Query-side temporal-intent boost (t_58fc4720). Present ONLY when the- * query declared a time window; absent - not zero - for every query- * that declared none, so a breakdown without temporal intent stays- * byte-identical to pre-suite behaviour.- */- readonly temporal?: number;-}--/**- * Inline per-hit trust metadata (Search & Recall Quality Suite). Computed- * at read time, never stored. `age_days` is the whole-day distance from- * the document mtime; `superseded` / `conflict` are derived from the- * typed relation edges the recall pipeline surfaces (`superseded_by` /- * `contradicts`). Present on a result only when the caller set `trust`.- */-export interface TrustMetadata {- readonly age_days: number;- readonly superseded: boolean;- readonly conflict: boolean;- /**- * Belief lifecycle suite (A4, t_d9365884): when the hit is superseded,- * the `superseded_by` successor target so recall carries a pointer to- * the replacement. `null` when the hit is not superseded or declares no- * successor target.- */- readonly replacement: string | null;-}--export interface BrainSearchResult {- readonly documentId: number;- readonly chunkId: number;- readonly path: string;- readonly title: string | null;- readonly content: string;- readonly startLine: number;- readonly endLine: number;- readonly score: number;- readonly keywordScore: number;- readonly semanticScore: number;- readonly linkBoost: number;- readonly recencyBoost: number;- /**- * Transcript turn instant (unix seconds) this result was authored at- * (conversation chronology, S1 / t_347e8224). Present only for a note- * carrying an `authored_at` frontmatter instant; absent for every note- * with no turn instant, so the result shape stays byte-identical for a- * vault without transcript-authored notes. Exact hybrid-score ties are- * ordered newer-first by this value.- */- readonly authoredAt?: number;- readonly searchType: "keyword" | "semantic" | "hybrid" | "link";- /**- * Explainable recall: one entry per scoring layer that contributed- * to `score`, formatted `"<layer>: <fixed-precision value>"`. Layers- * that did not fire (zero contribution) are omitted. Always present;- * never empty for a result that surfaced.- */- readonly reasons: ReadonlyArray<string>;- /**- * Typed semantic relations this result's page declares in its- * frontmatter (v3 / typed graph semantics): `related` / `extends` /- * `contradicts` / `superseded_by` and any other vocabulary relation.- * Computed at query time from the links table, never stored on the- * result row. Absent when the page declares no typed relations.- */- readonly relations?: ReadonlyArray<{- readonly relation: string;- readonly target: string;- }>;- /**- * Structured per-layer score components (Search & Recall Quality- * Suite). Always present on a primary ranked result; absent on- * synthetic results (link-traversal expansions, relation-polarity- * successor pull-ins) whose score is not a per-layer sum - the- * `explain` projection derives a faithful breakdown from the- * first-class lane/boost fields for those. Never serialized to the MCP- * output unless the caller sets `explain`.- */- readonly breakdown?: ScoreBreakdown;- /**- * Inline trust metadata (Search & Recall Quality Suite). Present only- * when the caller set `trust`; computed at read time from the document- * mtime and the surfaced typed relations, never stored.- */- readonly trust?: TrustMetadata;- /**- * Kind-namespaced origin label (Workspace Insight Suite, cross-vault- * search): "local", "profile/<name>", or "source/<alias>". Only set- * by `searchAcrossVaults`; plain single-vault search leaves it- * absent, keeping the legacy result shape byte-identical.- */- readonly origin?: string;-}+export type { BrainSearchResult, ScoreBreakdown, TrustMetadata };+export {+ EMBEDDING_QUOTA_MESSAGE,+ SEARCH_ERROR_CODES,+ SearchError,+ type EmbeddingErrorCategory,+ type SearchErrorCode,+ type SearchErrorOptions,+} from "./search-error.ts";/*** Structural query intent (v0.20.0). Derived purely from query shape -diff --git a/src/core/vault-presence.ts b/src/core/vault-presence.tsnew file mode 100644index 00000000..f8aad745--- /dev/null+++ b/src/core/vault-presence.ts@@ -0,0 +1,57 @@+/**+ * Whether a vault directory is there, with "not there" kept apart from+ * "cannot look".+ *+ * The ordinary probes (`isDir`, `existsSync`) answer `false` for both,+ * which is right for a caller asking only "is this worth opening". It is+ * wrong for a status payload, where that difference IS the product:+ * `vault_exists: false` reads as "this install was never set up", and+ * whatever the field gates then reads as a set of confident negatives -+ * for what is usually one missing execute bit on a parent directory,+ * under a remedy telling the operator to create a vault they already have.+ *+ * This lives in core rather than beside either caller because two+ * independent runtimes publish a `second_brain_status` payload with this+ * field, and one formulation of the condition has to reach the operator+ * from both.+ */++import { statOrAbsent } from "./fs-utils.ts";++/** A declared field whose value could not be resolved, with the reason. */+export type UnresolvedField = { readonly error: string };++export interface VaultPresence {+ /** True only when the path was examined and is a directory. */+ readonly present: boolean;+ /** Non-null when the answer is UNKNOWN rather than known-false. */+ readonly unexaminable: UnresolvedField | null;+}++/**+ * The reason a vault directory could not be examined, as a degraded field.+ *+ * The remedy rides in the message rather than in each reporting surface,+ * the same call the config read failure makes and for the same reason:+ * this condition reaches the operator through a payload field, several+ * degraded blocks and a tool-level refusal, and a remedy rendered per+ * surface would drift between them or be dropped.+ */+export function vaultUnexaminable(vault: string, err: unknown): UnresolvedField {+ const reason = (err as Error)?.message ?? String(err);+ return {+ error:+ `cannot determine whether the vault directory ${vault} exists: ${reason}. ` ++ "It is NOT reported as absent - a path that cannot be examined is not a " ++ "path that is not there; make it and every parent directory traversable " ++ "(chmod u+rx), or set VAULT_DIR to a vault this process can read.",+ };+}++export function probeVaultDirectory(vault: string): VaultPresence {+ try {+ return { present: statOrAbsent(vault)?.isDirectory() === true, unexaminable: null };+ } catch (err) {+ return { present: false, unexaminable: vaultUnexaminable(vault, err) };+ }+}diff --git a/src/core/vault.ts b/src/core/vault.tsindex 3dcb4951..697c2d65 100644--- a/src/core/vault.ts+++ b/src/core/vault.ts@@ -531,6 +531,11 @@ interface WalkNoticeSink {* Used where callers only need existence-by-basename (Obsidian* wikilink resolution semantics) and the YAML parse cost of* {@link listVaultPages} is unwarranted.+ *+ * Honours `opts.notices` exactly as {@link listVaultPages} does. The+ * option has always been on this signature β it is the same options type+ * β and until now it was accepted and dropped, so a caller that asked+ * where the walk went blind was answered with silence.*/export function listVaultBasenames(vaultDir: string,@@ -539,28 +544,46 @@ export function listVaultBasenames(const skipDirs = new Set(opts.skipDirs ?? DEFAULT_SKIP_DIRS);const skipFiles = new Set((opts.skipFiles ?? DEFAULT_SKIP_FILES).map((f) => f.toLowerCase()));const out = new Set<string>();- walkBasenames(vaultDir, vaultDir, skipDirs, skipFiles, out);+ walkBasenames(vaultDir, vaultDir, skipDirs, skipFiles, out, {+ sink: opts.notices,+ site: opts.site ?? LIST_VAULT_BASENAMES_SITE,+ });return out;}+const LIST_VAULT_BASENAMES_SITE = "vault.listVaultBasenames";+function walkBasenames(root: string,dir: string,skipDirs: Set<string>,skipFiles: Set<string>,out: Set<string>,+ notices: WalkNoticeSink,): void {let entries;try {entries = readdirSync(dir, { withFileTypes: true });- } catch {+ } catch (err) {+ // Same branch, and the same fail-soft return, as {@link walk}: an+ // unreadable directory removes a whole subtree from the basename+ // universe, and a caller resolving links against that universe+ // cannot tell the missing pages from pages that never existed.+ if (notices.sink !== undefined) {+ emitDegradationNotice(notices.sink, {+ code: DEGRADATION_CODE.vaultWalkEntrySkipped,+ site: notices.site,+ path: dir,+ detail: `directory listing failed: ${err instanceof Error ? err.message : String(err)}`,+ });+ }return;}for (const entry of entries) {const full = join(dir, entry.name);if (entry.isDirectory()) {if (skipDirs.has(entry.name)) continue;- walkBasenames(root, full, skipDirs, skipFiles, out);+ walkBasenames(root, full, skipDirs, skipFiles, out, notices);continue;}if (!entry.isFile()) continue;diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.tsindex 907486dd..25102adc 100644--- a/src/mcp/brain/pack-tools.ts+++ b/src/mcp/brain/pack-tools.ts@@ -582,6 +582,10 @@ async function toolBrainPreCompressPack(active_head_included: pack.activeHeadIncluded,...(pack.activeHeadSafety ? { active_head_safety: pack.activeHeadSafety } : {}),total_chars: pack.totalChars,+ // The pack's one degradation channel. This is the only surface the+ // builder has, so a warning dropped here is a broken `_brain.yaml`+ // nothing tells the caller about.+ ...(pack.warnings ? { warnings: pack.warnings } : {}),...(pack.receiptId ? { receipt_id: pack.receiptId } : {}),...(pack.telemetryId ? { telemetry_id: pack.telemetryId } : {}),items: pack.items.map((i) => ({diff --git a/src/mcp/instructions.ts b/src/mcp/instructions.tsindex 02940767..507af2ee 100644--- a/src/mcp/instructions.ts+++ b/src/mcp/instructions.ts@@ -11,8 +11,18 @@import type { ToolScope } from "./tool-contract.ts";export interface BuildInstructionsOpts {- /** Resolved agent identity (e.g. "hermes-vps-agent"). */- readonly agent: string;+ /**+ * Resolved agent identity (e.g. "hermes-vps-agent"), or the error+ * explaining why it could not be resolved.+ *+ * The error form exists because the identity comes from the plugin+ * config, and a config that is present but unreadable has no identity in+ * it to state. Substituting one would be the worst available answer: the+ * instructions tell the agent to always log under the name they carry,+ * so a guessed name is a standing instruction to write under it. The+ * refusal is rendered in its place instead, naming the file.+ */+ readonly agent: string | Error;/** Vault path β reserved for future per-vault customisation. */readonly vault?: string;/** When "writer", return the trimmed writer-surface text. */@@ -66,6 +76,32 @@ registration step exists or is needed.Do not invent substitute workflows for a capability you cannot see:hydrate the catalog first; the tool is almost certainly already here.`;+/**+ * The opening identity sentence of the full-surface instructions.+ *+ * Both branches are an instruction, not a report: the resolved branch says+ * which name to log under, and the unresolved branch says that there is+ * none and that the writers will refuse until the named file is fixed - so+ * an agent reading it does not go looking for a name to supply by hand.+ * The error carries its own remedy (`ConfigReadError` renders the chmod),+ * so nothing is assembled here.+ */+function identityLine(agent: string | Error): string {+ if (typeof agent === "string") {+ return (+ `You are @${agent} on this Open Second Brain vault. ` ++ "Always log under this identity; do not invent or change the name."+ );+ }+ return (+ "Your identity on this Open Second Brain vault is UNRESOLVED: " ++ `${agent.message} Until it is readable, every tool that writes under an ` ++ "identity refuses and names that file; do not substitute a name of your " ++ "own. The read-only diagnostics (vault_health, second_brain_status) " ++ "still answer and report the same condition."+ );+}+export function buildInstructions(opts: BuildInstructionsOpts | string): string {// Legacy call-site compat: plain string β full-surface branch.const agent = typeof opts === "string" ? opts : opts.agent;@@ -78,8 +114,8 @@ export function buildInstructions(opts: BuildInstructionsOpts | string): string// descriptions and docs/mcp.md; this text carries only the contract// that cannot be read off the schemas.return (- `You are @${agent} on this Open Second Brain vault. ` +- "Always log under this identity; do not invent or change the name.\n\n" ++ identityLine(agent) ++ "\n\n" +"Memory contract: call brain_feedback once per taste signal the " +"user expresses; brain_apply_evidence right after producing a " +"durable artifact a preference in `Brain/preferences/` scopes to " +diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex a19a2a5f..2ffd90bc 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -4,7 +4,11 @@* class, including handshake instructions and error semantics.*/-import { resolveAgentName, resolveMcpRouteMetricsEnabled } from "../core/config.ts";+import {+ ConfigReadError,+ resolveAgentName,+ resolveMcpRouteMetricsEnabled,+} from "../core/config.ts";import { emitMcpRouteLatency, type McpRouteStatus } from "../core/brain/mcp-route-metrics.ts";import { buildInstructions } from "./instructions.ts";import {@@ -77,9 +81,9 @@ export class MCPServer {private readonly capabilityReport: ToolCapabilityReport;/*** Route-level latency metrics gate (config `mcp_route_metrics_enabled`),- * resolved once at construction. Off by default; when on, every tool- * call is timed and a payload-safe `mcp_route_latency` continuity- * record is emitted (fail-open).+ * resolved once at construction by {@link routeMetricsGate}. Off by+ * default; when on, every tool call is timed and a payload-safe+ * `mcp_route_latency` continuity record is emitted (fail-open).*/private readonly routeMetricsEnabled: boolean;@@ -96,7 +100,7 @@ export class MCPServer {});this.tools = evaluated.tools;this.capabilityReport = evaluated.report;- this.routeMetricsEnabled = resolveMcpRouteMetricsEnabled(this.configPath ?? undefined);+ this.routeMetricsEnabled = routeMetricsGate(this.configPath ?? undefined);const runId = runtimeOpts.artifactRunId ?? `run-${process.pid}-${Date.now().toString(36)}`;this.artifactStore = new ArtifactStore({ vault: this.vault, runId });// Best-effort housekeeping: clear prior processes' stale artifacts.@@ -109,6 +113,7 @@ export class MCPServer {}get context(): ServerContext {+ const configPath = this.configPath ?? undefined;return {vault: this.vault,configPath: this.configPath,@@ -119,7 +124,21 @@ export class MCPServer {// only source of identity for `brain_context`, which takes no// arguments. Resolved per access, like `resolveAgentName`'s other// callers, so a config edit takes effect without a restart.- agentName: resolveAgentName(this.configPath ?? undefined),+ //+ // A GETTER, not a value, and that is the whole separation this+ // context makes. `resolveAgentName` raises on a config that is+ // present but unreadable, and it is right to: the alternative is a+ // guessed identity, and every write path that takes one records+ // under it. Resolved eagerly here, that refusal ran before EVERY+ // handler, including the two read-only diagnostics whose entire job+ // is to name the file that is broken - so the payload naming it was+ // computed and then discarded by the condition it described.+ // Deferred to the point of use, the refusal reaches exactly the+ // handlers that need an identity (as a tool-level error carrying the+ // file name), and the handlers that never ask answer normally.+ get agentName(): string {+ return resolveAgentName(configPath);+ },};}@@ -235,7 +254,14 @@ export class MCPServer {private handleInitialize(params: Record<string, unknown>): Record<string, unknown> {const clientVersion = params["protocolVersion"];const negotiated = typeof clientVersion === "string" ? clientVersion : PROTOCOL_VERSION;- const defaultAgent = resolveAgentName(this.configPath ?? undefined);+ // The handshake is the third site that read the config before any+ // handler could run, and the one that mattered most: a client whose+ // `initialize` fails never issues a `tools/call` at all, so a refusal+ // here withholds the diagnostics along with everything else. It does+ // not become a guess either - `buildInstructions` renders the reason+ // in place of the identity line, so the agent is told there is no+ // identity to log under rather than handed one.+ const identity = resolveIdentityOrReason(this.configPath ?? undefined);return {protocolVersion: negotiated,capabilities: {@@ -244,7 +270,7 @@ export class MCPServer {},serverInfo: { name: this.serverName, version: SERVER_VERSION },instructions: buildInstructions({- agent: defaultAgent,+ agent: identity,scope: this.scope,}),};@@ -307,6 +333,59 @@ export class MCPServer {}}+/**+ * The route-metrics gate for this process, with a config that is present+ * but UNREADABLE folded to the gate's own default rather than raised.+ *+ * This is the only config read on the construction path, so raising here+ * cost the entire process - no `tools/list`, no `tools/call`, and in+ * particular no `vault_health`, the surface whose whole job is to name+ * the file that is broken. It is the same trade `appendLogEvent` makes+ * with `resolveDeviceId` (see `AppendLogEventOptions.deviceId`): a read+ * that sits in front of everything turns one bad file mode into a dead+ * runtime, and the fallback is not a neutral value invented to make a+ * broken install look healthy - it is this gate's documented default-OFF+ * state, it loses only telemetry, and nothing else absorbs the condition.+ * `second_brain_status` and `vault_health` still report the file by name,+ * and every identity-bearing write still refuses on it.+ *+ * Deliberately NOT the same answer as the identity resolvers, because it+ * is not the same class of problem: an unresolvable identity has no+ * neutral value - every candidate is a guess that gets written into the+ * vault under someone's name - while an unresolvable observability toggle+ * has exactly one, and choosing it writes nothing at all.+ *+ * Narrow on purpose: only {@link ConfigReadError} is absorbed, so an+ * unsupported platform or any other failure to locate the config at all+ * is still fatal at construction. `OPEN_SECOND_BRAIN_MCP_ROUTE_METRICS_ENABLED`+ * remains the escape hatch - it is read before the file is opened, so an+ * operator who wants the metrics on can have them on a broken config.+ */+function routeMetricsGate(configPath: string | undefined): boolean {+ try {+ return resolveMcpRouteMetricsEnabled(configPath);+ } catch (err) {+ if (err instanceof ConfigReadError) return false;+ throw err;+ }+}++/**+ * The agent identity for the handshake instructions, or the error saying+ * why there is none. Never a substitute name: see+ * {@link MCPServer.context} for why `resolveAgentName`'s refusal is kept+ * rather than defaulted, and `buildInstructions` for what the caller is+ * told in its place.+ */+function resolveIdentityOrReason(configPath: string | undefined): string | ConfigReadError {+ try {+ return resolveAgentName(configPath);+ } catch (err) {+ if (err instanceof ConfigReadError) return err;+ throw err;+ }+}+function toolResult(tool: ToolDefinition, structured: unknown): Record<string, unknown> {assertOutputContract(tool.name, tool.outputSchema, structured);const text = JSON.stringify(structured, sortedReplacer, 2);diff --git a/src/mcp/tools.ts b/src/mcp/tools.tsindex 69de5b71..8873ca8d 100644--- a/src/mcp/tools.ts+++ b/src/mcp/tools.ts@@ -22,17 +22,19 @@*/import {+ ConfigReadError,discoverConfig,redactMapping,resolveExposeHostPaths,vaultStoreReference,} from "../core/config.ts";+import type { ConfigDiscovery } from "../core/types.ts";import { REMOVED_TOOLS } from "../core/removed-surfaces.ts";import { computeBrainStatus } from "../core/brain/status.ts";import { doctor } from "../core/doctor.ts";import { nextCommandField } from "../core/brain/next-step.ts";import { collectRuntimeNotices } from "../core/brain/runtime-notices.ts";-import { isDir } from "../core/fs-utils.ts";+import { probeVaultDirectory, type UnresolvedField } from "../core/vault-presence.ts";import { resolveVaultScope, walkVaultScope } from "../core/vault-scope/index.ts";import { BRAIN_TOOLS } from "./brain-tools.ts";import { SEARCH_TOOLS, buildSearchStatusBlock } from "./search-tools.ts";@@ -77,31 +79,98 @@ function vaultRelpath(target: string, vault: string): string {}}+/**+ * A field whose value could not be resolved, carrying the reason. Same+ * shape `toolStatus` already degrades the `vault` block to when the vault+ * scope cannot be resolved, and `buildSearchStatusBlock` its own: the+ * failure is a value the consumer reads, never a key it has to notice is+ * missing.+ */++function unresolved(err: Error): UnresolvedField {+ return { error: err.message };+}+/*** The `vault_path` field for an MCP response. By default this is the* opaque, stable store reference (`vault://<hex>`) rather than the* absolute host path, since MCP responses land in model context. The* `expose_host_paths` config escape hatch restores the raw path for* operators whose tooling depends on it (D2).+ *+ * Both branches read the device-local config - the escape hatch is a+ * config flag and the reference is keyed by a config-held secret - so an+ * unreadable config leaves this field, and ONLY this field, unresolvable.+ * It reports the reason rather than raising, because raising here took+ * down whole diagnostic payloads on their very last field. Degrading to+ * the raw host path instead would breach the redaction contract this+ * function exists to enforce, so there is no value to fall back to.*/-function vaultPathField(ctx: ServerContext): string {+function vaultPathField(ctx: ServerContext): string | UnresolvedField {const configPath = ctx.configPath ?? undefined;- return resolveExposeHostPaths(configPath)- ? ctx.vault- : vaultStoreReference(ctx.vault, configPath);+ try {+ return resolveExposeHostPaths(configPath)+ ? ctx.vault+ : vaultStoreReference(ctx.vault, configPath);+ } catch (err) {+ if (err instanceof ConfigReadError) return unresolved(err);+ throw err;+ }}// ββ Tool implementations ββββββββββββββββββββββββββββββββββββββββββββββββββββ+/**+ * `discoverConfig`, or the reason it could not answer.+ *+ * `second_brain_status` exists to report what this install sees in its+ * config, so a config it cannot read is the tool's SUBJECT, not a reason to+ * fail: raising here cost the caller `config_path`, `config_exists`,+ * `config_keys` and `config` - every field that answers the question - and+ * returned an error naming nothing the operator could act on beyond what+ * the payload would have said anyway.+ */+function discoverConfigOrReason(configPath: string | undefined): ConfigDiscovery | ConfigReadError {+ try {+ return discoverConfig(configPath);+ } catch (err) {+ if (err instanceof ConfigReadError) return err;+ throw err;+ }+}+async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>> {- const discovery = discoverConfig(ctx.configPath ?? undefined);- const vaultExists = isDir(ctx.vault);- const configKeys = Object.keys(discovery.data).toSorted();+ const discovered = discoverConfigOrReason(ctx.configPath ?? undefined);+ const broken = discovered instanceof ConfigReadError ? discovered : null;+ // `exists: true` on the broken branch is the whole point of the read+ // split: the file IS there, and `false` would say this install was never+ // configured. `config_keys` and `config` cannot be known, so they carry+ // the reason rather than an empty list an agent would read as "no keys".+ const discovery: ConfigDiscovery =+ broken === null+ ? (discovered as ConfigDiscovery)+ : { path: broken.path, exists: true, data: {} };+ // Three blocks below are gated on this answer, and on the UNEXAMINABLE+ // branch each is built carrying the reason rather than skipped: an+ // omitted block reads as the same confident negative the bare `false`+ // did, which is precisely what the probe could not determine. The absent+ // branch keeps omitting them, because there the omission IS the answer.+ const { present: vaultExists, unexaminable } = probeVaultDirectory(ctx.vault);+ const configKeys = broken === null ? Object.keys(discovery.data).toSorted() : unresolved(broken);// Safe to call on a vault that has no Brain layer yet β returns// `present: false` with zero counts.- const brain = vaultExists ? computeBrainStatus(ctx.vault) : null;+ const brain = vaultExists ? computeBrainStatus(ctx.vault) : unexaminable;+ // On the broken branch this gate is unresolvable, so the block is built+ // rather than skipped: `buildSearchStatusBlock` resolves its own config+ // and degrades to `{ exists: false, error }` naming the same file. A skip+ // would have been the silent omission - a missing block reads as "search+ // is off", which is exactly the answer the gate could not give.const searchDisabled = discovery.data["search_enabled"] === "false";- const search = vaultExists && !searchDisabled ? await buildSearchStatusBlock(ctx) : null;+ const search = searchDisabled+ ? null+ : vaultExists+ ? await buildSearchStatusBlock(ctx)+ : unexaminable;// v0.10.9 β `vault` block exposes the shared exclusion policy plus// aggregate include/exclude counts. Per-path detail lives in the CLI// (`o2b vault status`); MCP payloads stay small.@@ -113,7 +182,7 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>// config blocks visible even when the vault scope cannot be// resolved. Catch and degrade to `{ error: "..." }` instead of// taking the whole `second_brain_status` payload down with it.- let vault: Record<string, unknown> | null = null;+ let vault: Record<string, unknown> | UnresolvedField | null = unexaminable;if (vaultExists) {try {const scope = resolveVaultScope(ctx.vault);@@ -135,9 +204,13 @@ async function toolStatus(ctx: ServerContext): Promise<Record<string, unknown>>config_path: String(discovery.path),config_exists: discovery.exists,config_keys: configKeys,- config: redactMapping(discovery.data),+ config: broken === null ? redactMapping(discovery.data) : unresolved(broken),vault_path: vaultPathField(ctx),- vault_exists: vaultExists,+ // `boolean | { error }`. Both answerable cases keep their exact literal+ // - `true` when the directory is there, `false` when it is genuinely+ // not - and the third value exists only for the case that previously+ // impersonated the second.+ vault_exists: unexaminable ?? vaultExists,...(vault ? { vault } : {}),...(brain ? { brain } : {}),...(search ? { search } : {}),@@ -148,7 +221,14 @@ async function toolQuery(ctx: ServerContext,args: Record<string, unknown>,): Promise<Record<string, unknown>> {- if (!isDir(ctx.vault)) {+ // Refusing either way, but not with the same reason: an operator told+ // their vault is missing goes and creates one, which is the wrong move+ // when the directory is there behind a parent it cannot traverse.+ const presence = probeVaultDirectory(ctx.vault);+ if (presence.unexaminable !== null) {+ throw new MCPError(INVALID_PARAMS, presence.unexaminable.error);+ }+ if (!presence.present) {throw new MCPError(INVALID_PARAMS, `vault directory missing: ${ctx.vault}`);}const pattern = coerceStr(args, "pattern", false);diff --git a/src/openclaw/index.ts b/src/openclaw/index.tsindex 5bd6825c..12846138 100644--- a/src/openclaw/index.ts+++ b/src/openclaw/index.ts@@ -10,9 +10,9 @@*/import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";-import { existsSync } from "node:fs";import { discoverConfig, redactMapping, resolveAgentName } from "../core/config.ts";+import { probeVaultDirectory } from "../core/vault-presence.ts";import { doctor } from "../core/doctor.ts";import { buildReminder } from "../core/identity-reminder.ts";import { listVaultPages } from "../core/vault.ts";@@ -68,13 +68,17 @@ export default definePluginEntry({async execute(): Promise<unknown> {const vault = resolveVaultPath(api);const discovery = discoverConfig();+ // Shared with the primary runtime's status tool: a vault that+ // cannot be examined is not a vault that is not there, and this+ // payload is the one place that difference is the product.+ const presence = probeVaultDirectory(vault);const result = {config_path: discovery.path,config_exists: discovery.exists,config_keys: Object.keys(discovery.data).toSorted(),config: redactMapping(discovery.data),vault_path: vault,- vault_exists: existsSync(vault),+ vault_exists: presence.unexaminable ?? presence.present,};return {content: [{ type: "text", text: JSON.stringify(result, null, 2) }],@@ -103,7 +107,12 @@ export default definePluginEntry({},async execute(_id, params): Promise<unknown> {const vault = resolveVaultPath(api);- if (!existsSync(vault)) throw new Error(`vault directory missing: ${vault}`);+ // Refuses either way, but the REASON has to be right: telling an+ // operator their vault is missing sends them to create one they+ // already have.+ const presence = probeVaultDirectory(vault);+ if (presence.unexaminable) throw new Error(presence.unexaminable.error);+ if (!presence.present) throw new Error(`vault directory missing: ${vault}`);const pattern = (params["pattern"] as string | undefined) ?? null;const limit = typeof params["limit"] === "number" ? (params["limit"] as number) : 50;if (limit < 1 || limit > 500) throw new Error("argument 'limit' must be between 1 and 500");diff --git a/tests/cli/advisory-claim-truth.test.ts b/tests/cli/advisory-claim-truth.test.tsindex 74e6524d..af3b3277 100644--- a/tests/cli/advisory-claim-truth.test.ts+++ b/tests/cli/advisory-claim-truth.test.ts@@ -219,7 +219,7 @@ describe("the audit of every other registered emission", () => {["src/cli/brain/verbs/tiers.ts", "tier-drift-restore", "findings.length > 0"],["src/cli/brain/verbs/tune.ts", "recall-tuning-absent", "tuned === null"],["src/cli/main.ts", "cli-config-absent", "!result.exists"],- ["src/cli/search.ts", "search-index-missing", "!status.exists"],+ ["src/cli/search/verbs/status.ts", "search-index-missing", "!status.exists"],];test("every other emission sits under a guard naming its condition", () => {diff --git a/tests/cli/config-read-failure-surfaces.test.ts b/tests/cli/config-read-failure-surfaces.test.tsnew file mode 100644index 00000000..fca1d63b--- /dev/null+++ b/tests/cli/config-read-failure-surfaces.test.ts@@ -0,0 +1,268 @@+/**+ * What an OPERATOR sees when the plugin config is present but unreadable.+ *+ * `ConfigReadError` is raised deep in the config reader, which is the right+ * place to detect the condition and the wrong place to report it. These+ * tests own the reporting end: every assertion here is about what escapes+ * the command line, so they spawn `o2b` rather than calling `main()`. The+ * in-process runner maps an uncaught throw to "code 1 with the stack on+ * stderr", which is indistinguishable from a handled refusal - exactly the+ * confusion that let the raw crash ship.+ *+ * Three properties, together, are what the operator needs:+ *+ * - a FORMATTED refusal (one `error:` line naming the file and the way+ * out), not a source excerpt and a stack;+ * - a STABLE exit code - 1, the environment-error code this command line+ * already uses for `no vault configured`, distinct from 2 for a usage+ * error;+ * - on a `--json` surface, PARSEABLE JSON on stdout, because a machine+ * consumer cannot read the stderr prose and empty stdout is not a+ * result.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");+const CLI_ENTRY = join(REPO_ROOT, "src", "cli", "main.ts");++/** A config an operator could plausibly have written. */+const VALID_CONFIG = `vault: "/srv/example-vault"\nagent_name: "someone"\n`;++/** Bun prints an unhandled throw as a numbered source excerpt plus frames. */+const SOURCE_EXCERPT_RE = /^\s*\d+ \|/m;+const STACK_FRAME_RE = /^\s+at .+ \(.*:\d+:\d+\)$/m;++interface RunResult {+ readonly stdout: string;+ readonly stderr: string;+ readonly exit: number;+}++let tmp: string;+let configPath: string;+let vault: string;++/**+ * Spawn `o2b` with an env built from scratch. Nothing is inherited beyond+ * `PATH`, so the developer's `O2B_DEVICE_ID` / `VAULT_DIR` / real config+ * cannot decide the outcome, and `HOME` points inside the sandbox.+ */+async function runO2b(args: string[], env: Record<string, string> = {}): Promise<RunResult> {+ const proc = Bun.spawn(["bun", "run", CLI_ENTRY, ...args], {+ cwd: REPO_ROOT,+ stdin: "ignore",+ stdout: "pipe",+ stderr: "pipe",+ env: {+ PATH: process.env["PATH"] ?? "",+ HOME: tmp,+ OPEN_SECOND_BRAIN_CONFIG: configPath,+ ...env,+ },+ });+ const [stdout, stderr] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ const exit = await proc.exited;+ return { stdout, stderr, exit } satisfies RunResult;+}++/** Run `args` with the config file unreadable, restoring the mode after. */+async function withUnreadableConfig(+ args: string[],+ env: Record<string, string> = {},+): Promise<RunResult> {+ chmodSync(configPath, 0o000);+ try {+ return await runO2b(args, env);+ } finally {+ chmodSync(configPath, 0o600);+ }+}++/** Every refusal below must be a formatted one, never a raw crash. */+function expectFormattedRefusal(result: RunResult): void {+ expect(result.stderr).toMatch(/^error: /);+ expect(result.stderr).toContain(configPath);+ expect(result.stderr).not.toMatch(SOURCE_EXCERPT_RE);+ expect(result.stderr).not.toMatch(STACK_FRAME_RE);+ expect(result.stderr).not.toContain("ConfigReadError:");+ expect(result.exit).toBe(1);+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-config-read-cli-"));+ configPath = join(tmp, "config.yaml");+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeFileSync(configPath, VALID_CONFIG, "utf8");+});++afterEach(() => {+ chmodSync(configPath, 0o600);+ rmSync(tmp, { recursive: true, force: true });+});++describe("an unreadable plugin config is a named refusal, not a crash", () => {+ /**+ * `doctor` is the worst case and the reason this matters: its whole job+ * is diagnosing this condition, and it can - see the companion test+ * below. Only the unhandled raise on the way in destroyed the report.+ */+ test("doctor refuses by name instead of printing a stack", async () => {+ const result = await withUnreadableConfig(["doctor"]);+ expectFormattedRefusal(result);+ });++ test("status refuses by name instead of printing a stack", async () => {+ const result = await withUnreadableConfig(["status"]);+ expectFormattedRefusal(result);+ });++ test("secrets list refuses by name instead of printing a stack", async () => {+ const result = await withUnreadableConfig(["secrets", "list"]);+ expectFormattedRefusal(result);+ });++ test("export-config refuses by name instead of printing a stack", async () => {+ const result = await withUnreadableConfig([+ "export-config",+ "--output",+ join(tmp, "exported.json"),+ ]);+ expectFormattedRefusal(result);+ });++ /**+ * The refusal is not merely formatted, it is actionable: it says the file+ * is present (so its settings are NOT in force and were not read as+ * absent) and names both ways out.+ */+ test("the refusal names the remedy, not only the failure", async () => {+ const result = await withUnreadableConfig(["doctor"]);+ expect(result.stderr).toContain("OPEN_SECOND_BRAIN_CONFIG");+ expect(result.stderr).toContain("chmod");+ });++ /**+ * The exit code is the environment-error code, matching `no vault+ * configured` - a broken config file is a fact about the machine, not a+ * mistake in the argv. 2 stays reserved for usage errors.+ */+ test("the exit code is the environment-error code, not the usage one", async () => {+ const broken = await withUnreadableConfig(["doctor"]);+ const noVault = await runO2b(["doctor"], {+ OPEN_SECOND_BRAIN_CONFIG: join(tmp, "absent.yaml"),+ });+ const usage = await runO2b(["completions", "not-a-shell"]);+ expect(broken.exit).toBe(noVault.exit);+ expect(usage.exit).toBe(2);+ });++ /**+ * The diagnosis the crash destroyed. With the vault supplied explicitly+ * nothing resolves through the broken file on the way in, and `doctor`+ * reports the condition as a check with a fix line - which is what the+ * refusal above now points the operator at.+ */+ test("doctor --vault still diagnoses the same file as a failed check", async () => {+ const result = await withUnreadableConfig(["doctor", "--vault", vault]);+ expect(result.stdout).toContain("[FAIL] config_writeable");+ expect(result.stdout).toContain(configPath);+ expect(result.stdout).toContain("fix:");+ });+});++describe("machine consumers get JSON, never empty stdout", () => {+ /**+ * `status --json` renders its own payload, so it is never wrapped in the+ * `withJsonFallback` envelope: without a handler of its own a consumer+ * got empty stdout plus a stack trace.+ */+ test("status --json emits parseable JSON naming the unreadable file", async () => {+ const result = await withUnreadableConfig(["status", "--json"]);+ expect(result.exit).toBe(1);+ const payload = JSON.parse(result.stdout) as Record<string, unknown>;+ expect(payload["config_path"]).toBe(configPath);+ expect(String(payload["error"])).toContain(configPath);+ });++ /**+ * A command whose JSON IS the envelope: the fallback has no catch of its+ * own, so a throw escaped it and printed no envelope at all. Handling the+ * error inside the dispatch restores it.+ */+ test("the --json envelope survives for a command that does not own its JSON", async () => {+ const result = await withUnreadableConfig([+ "export-config",+ "--output",+ join(tmp, "exported.json"),+ "--json",+ ]);+ const payload = JSON.parse(result.stdout) as Record<string, unknown>;+ expect(payload["ok"]).toBe(false);+ expect(String(payload["stderr"])).toContain(configPath);+ });+});++/**+ * Identity resolution (Finding 3). With `VAULT_DIR` set, nothing upstream+ * has opened the config, so the first read is the device-id lookup inside+ * the claim shard path. It raises - deliberately, because the alternative+ * is minting a fresh device id and persisting it over a config we could+ * not read - and the operator has to be able to see why.+ */+describe("identity resolution surfaces the same file, actionably", () => {+ test("brain truth ingest names the unreadable config and exits non-zero", async () => {+ const result = await withUnreadableConfig(+ [+ "brain",+ "truth",+ "ingest",+ "--entity",+ "a",+ "--aspect",+ "b",+ "--value",+ "c",+ "--source",+ "s",+ ],+ { VAULT_DIR: vault },+ );+ expect(result.exit).not.toBe(0);+ expect(result.stderr).toContain(configPath);+ expect(result.stderr).toContain("OPEN_SECOND_BRAIN_CONFIG");+ expect(result.stderr).not.toMatch(SOURCE_EXCERPT_RE);+ expect(result.stderr).not.toMatch(STACK_FRAME_RE);+ });++ /** And it wrote nothing: no claim shard, no rewritten config. */+ test("nothing is written when identity cannot be resolved", async () => {+ await withUnreadableConfig(+ [+ "brain",+ "truth",+ "ingest",+ "--entity",+ "a",+ "--aspect",+ "b",+ "--value",+ "c",+ "--source",+ "s",+ ],+ { VAULT_DIR: vault },+ );+ const result = await runO2b(["status"], {});+ expect(result.stdout).toContain("config_exists: true");+ expect(Bun.file(join(vault, "Brain", "truth", "claims.jsonl")).size).toBe(0);+ });+});diff --git a/tests/cli/config-unreadable-verbs.test.ts b/tests/cli/config-unreadable-verbs.test.tsnew file mode 100644index 00000000..1bafd728--- /dev/null+++ b/tests/cli/config-unreadable-verbs.test.ts@@ -0,0 +1,130 @@+/**+ * A broken `Brain/_brain.yaml` must reach an operator as a named verb+ * failure, never as an unhandled throw.+ *+ * Commit 96b14d72 made `loadGuardrailsConfigSafe` raise on a config that+ * is present and unreadable, which is right: the operator's settings are+ * not in force and serving the defaults would hide that. Two verbs on the+ * `packContext` path had no boundary for it, so `o2b brain context-pack`+ * and `o2b brain anticipate` printed a stack trace - which names the+ * repo's file layout rather than the operator's file. Every sibling verb+ * on this path (`scan-inline`, `scan-citations`, `apply-markers`) already+ * had that boundary and reported `<verb> failed: <cause>`.+ *+ * The absent-config case is asserted beside each one: a vault that has+ * never run `o2b brain init` must keep succeeding, which is the whole+ * reason the `*Safe` readers exist.+ */++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 { brainConfigPath } from "../../src/core/brain/paths.ts";+import { runCli } from "../helpers/run-cli.ts";++/** Parses as YAML, fails validation, in a block neither verb reads. */+const BROKEN_CONFIG = `schema_version: 1\ndream:\n candidate_threshold: 0\n`;++let vault: string;+let configHome: string;+/**+ * A machine config is required, not incidental: `anticipate` resolves the+ * search-index path through it, so without one the absent-`_brain.yaml`+ * case would fail for an unrelated reason and prove nothing.+ */+let env: Record<string, string>;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-cli-broken-config-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ configHome = mkdtempSync(join(tmpdir(), "o2b-cli-broken-config-cfg-"));+ const configPath = join(configHome, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`, "utf8");+ env = { OPEN_SECOND_BRAIN_CONFIG: configPath };+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++function breakConfig(): void {+ writeFileSync(brainConfigPath(vault), BROKEN_CONFIG, "utf8");+}++describe("o2b brain context-pack", () => {+ test("an uninitialised vault still packs", async () => {+ const res = await runCli(["brain", "context-pack", "--max-tokens", "500", "--vault", vault], {+ env,+ });+ expect(res.returncode).toBe(0);+ });++ test("an unreadable config fails by name, with the file the operator must fix", async () => {+ breakConfig();+ const res = await runCli(["brain", "context-pack", "--max-tokens", "500", "--vault", vault], {+ env,+ });+ expect(res.returncode).toBe(1);+ expect(res.stderr).toContain("context-pack failed");+ expect(res.stderr).toContain(brainConfigPath(vault));+ });++ test("the failure does not carry a stack trace into stderr", async () => {+ breakConfig();+ const res = await runCli(["brain", "context-pack", "--max-tokens", "500", "--vault", vault], {+ env,+ });+ expect(res.stderr).not.toContain("src/core/brain/policy/load.ts");+ });+});++describe("o2b brain anticipate", () => {+ test("an uninitialised vault still reports a cache state", async () => {+ const res = await runCli(["brain", "anticipate", "--session", "s1", "--vault", vault], { env });+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("cache:");+ });++ test("an unreadable config fails by name, with the file the operator must fix", async () => {+ breakConfig();+ const res = await runCli(["brain", "anticipate", "--session", "s1", "--vault", vault], { env });+ expect(res.returncode).toBe(1);+ expect(res.stderr).toContain("anticipate failed");+ expect(res.stderr).toContain(brainConfigPath(vault));+ });+});++/**+ * `resolveNoteRoots` reads `notes.read_paths` through the same split, and+ * an empty root list is indistinguishable from a scan that found nothing+ * - so it raises. Every verb that walks note space already owned a+ * boundary for it; these two are the representatives, one per shape (a+ * scanner and a writeback), and they need no change. They are pinned so+ * a later refactor cannot quietly remove the boundary and leave the raise+ * escaping the way `context-pack`'s did.+ */+describe("note-space verbs already name the raise", () => {+ test("scan-inline: absent config scans nothing and succeeds", async () => {+ const res = await runCli(["brain", "scan-inline", "--dry-run", "--vault", vault], { env });+ expect(res.returncode).toBe(0);+ });++ test("scan-inline: an unreadable config fails by name", async () => {+ breakConfig();+ const res = await runCli(["brain", "scan-inline", "--dry-run", "--vault", vault], { env });+ expect(res.returncode).toBe(1);+ expect(res.stderr).toContain("scan-inline failed");+ expect(res.stderr).toContain(brainConfigPath(vault));+ });++ test("apply-markers: an unreadable config fails by name", async () => {+ breakConfig();+ const res = await runCli(["brain", "apply-markers", "--vault", vault], { env });+ expect(res.returncode).toBe(1);+ expect(res.stderr).toContain("apply-markers");+ expect(res.stderr).toContain(brainConfigPath(vault));+ });+});diff --git a/tests/cli/terminal-state-census.test.ts b/tests/cli/terminal-state-census.test.tsindex c08bf5c8..73929c67 100644--- a/tests/cli/terminal-state-census.test.ts+++ b/tests/cli/terminal-state-census.test.ts@@ -15,27 +15,47 @@* why that is right.** The direction matters. A verb cannot vouch for itself, so the census- * reads each handler's transitive call graph WITHIN its own module and- * classifies from what is actually reachable. Adding a verb that can- * only exit zero in silence fails here, by name, until someone either- * gives it an exit or writes down why it has none.+ * reads each handler's transitive call graph and classifies from what is+ * actually reachable. Adding a verb that can only exit zero in silence+ * fails here, by name, until someone either gives it an exit or writes+ * down why it has none.+ *+ * That walk used to stop at the handler's own module, which was the right+ * boundary while a CLI verb WAS one file. It is not any more: a verb now+ * lives in `<command>/verbs/<name>.ts` and states its shared refusal - "no+ * vault configured" - through `<command>/helpers.ts` beside it. Stopping+ * at the file would have credited a verb with no refusal purely because+ * the refusal it makes was extracted, and the only repair available then+ * is a hand entry, which is an exclusion. So the walk follows a call into+ * the sibling modules of the handler's OWN command that it actually+ * imports, {@link MAX_MODULE_HOPS} hop deep.+ *+ * That widening is itself an escape hatch - it is the mechanism by which+ * a verb that refuses nothing could be credited with a refusal - so every+ * state that reaches its class only through the hop is named in+ * {@link CLASSIFIED_BY_MODULE_WALK} with a written reason, under the same+ * gates and the same cap as a hand-classified entry.** Modelled on `tests/core/brain/vault-guard-census.test.ts`: detect the* property syntactically, keep one explicit inventory of exceptions, one* entry one reason, and pin the measurement so a regex that stopped* matching cannot report a clean sweep over an empty set.*- * Two limits, stated rather than discovered. Sub-verbs (`brain git+ * Three limits, stated rather than discovered. Sub-verbs (`brain git* ingest`, `search focus clear`) are parsed by each handler from its own* positionals and are covered through their parent's call graph, not- * individually. And a delegating case (`o2b brain`, `o2b search`) takes- * the classification of everything it can reach, which is the right- * answer to "can this invocation leave me with nothing".+ * individually. A delegating case (`o2b brain`, `o2b search`) takes the+ * classification of everything it can reach, which is the right answer to+ * "can this invocation leave me with nothing". And the walk stops at the+ * handler's own command: neither `src/core` nor the CLI-wide plumbing+ * every command shares is followed, because a refusal raised there is a+ * fact about the domain or about argument parsing in general, not one this+ * verb states.*/import { describe, expect, test } from "bun:test";import { readdirSync, readFileSync } from "node:fs";-import { join, relative } from "node:path";+import { dirname, join, relative, resolve, sep } from "node:path";import { runCli } from "../helpers/run-cli.ts";@@ -62,7 +82,12 @@ const STATE_CLASS = Object.freeze({type StateClass = (typeof STATE_CLASS)[keyof typeof STATE_CLASS];-interface HandClassification {+/**+ * A class this file states by name rather than leaving to the detector,+ * with the argument for it. Both inventories below hold these, and both+ * are held to the same gates.+ */+interface StateNote {readonly cls: StateClass;readonly reason: string;}@@ -74,8 +99,21 @@ interface HandClassification {* covering the state was inconvenient - the two states this census* found and COVERED (`o2b status`, `o2b brain inbox-drain`) are absent* from this table for exactly that reason.+ *+ * `deliberately-silent` currently has no members, and that is a result,+ * not an oversight. `brain semantics-backfill`, `brain mcp-landscape` and+ * `brain stale` sat here until the walk reached the helpers module beside+ * them and found the refusal each one makes on an unresolvable vault. What+ * their entries actually argued was that an EMPTY RESULT from them names+ * no forward exit and should not - a property about one path through a+ * verb, which is not the property these three classes measure. Re-adding+ * them here would be an exclusion covering a question this census does not+ * ask, so each argument travels instead with the state it describes, in+ * that verb's {@link CLASSIFIED_BY_MODULE_WALK} entry. Its best home is+ * the code that renders the empty case; a test cannot put it there, and+ * deleting it was not the alternative.*/-const CLASSIFIED_BY_HAND: Readonly<Record<string, HandClassification>> = Object.freeze({+const CLASSIFIED_BY_HAND: Readonly<Record<string, StateNote>> = Object.freeze({"o2b onboarding": {cls: STATE_CLASS.exit,reason:@@ -100,30 +138,82 @@ const CLASSIFIED_BY_HAND: Readonly<Record<string, HandClassification>> = Object."through the shared `fail()` helper this census matches on, which is more specific, " +"not less.",},- "o2b brain semantics-backfill": {- cls: STATE_CLASS.silent,+});++/**+ * States whose class the detector can only see because the walk left the+ * verb's own file for a sibling module of its command - the escape hatch+ * the widened walk opened.+ *+ * Every one of them is a refusal the split moved out of the verb and into+ * `<command>/helpers.ts`. The verb still makes it, so crediting it is the+ * right answer; but "the walk reached a shared module" is also exactly+ * how a verb that refuses nothing would come to look classified, which is+ * why an entry here owes a written reason, passes the gates a+ * hand-classified entry passes, and counts against the same cap.+ *+ * Three of these five carry a second argument, about the EMPTY RESULT+ * each verb can return. That is a different question from the one the+ * three classes ask - it is a property of one path through a verb, not of+ * the verb's terminal states - and it is recorded here because the state+ * it is about is named here.+ */+const CLASSIFIED_BY_MODULE_WALK: Readonly<Record<string, StateNote>> = Object.freeze({+ "o2b brain mcp-landscape": {+ cls: STATE_CLASS.refusal,reason:- "dry-run only by design - this verb has no apply path, so there is no command to " +- "name. An empty proposal list means the inverse-edge invariant it previews already " +- "holds, which is an answer, not a degraded state.",+ "refuses through `brainVerbContext` in `brain/helpers.ts`, which throws " ++ "`CliError(NO_VAULT_ERROR)` when no vault resolves. Its EMPTY result is the other " ++ "question, and names no exit by design: it lists the MCP servers declared in runtime " ++ "configuration files this tool never writes, so an empty landscape changes by editing " ++ "another runtime's config and no `o2b` command is its exit.",},- "o2b brain mcp-landscape": {- cls: STATE_CLASS.silent,+ "o2b brain semantics-backfill": {+ cls: STATE_CLASS.refusal,reason:- "lists the MCP servers declared in runtime configuration files this tool never " +- "writes. An empty landscape changes by editing another runtime's config, so no " +- "`o2b` command is its exit and naming one would be an invention.",+ "refuses through `brainVerbContext` in `brain/helpers.ts` on an unresolvable vault. " ++ "Its EMPTY result names no exit by design: the verb is dry-run only and has no apply " ++ "path, so there is no command to name, and an empty proposal list means the " ++ "inverse-edge invariant it previews already holds - an answer, not a degraded state.",},"o2b brain stale": {- cls: STATE_CLASS.silent,+ cls: STATE_CLASS.refusal,+ reason:+ "refuses through `brainVerbContext` in `brain/helpers.ts` on an unresolvable vault. " ++ "Its EMPTY result names no exit by design: this verb is itself the exit other " ++ "surfaces name - the `stale-notes` registry entry resolves to `o2b brain stale` - and " ++ "what to do with a stale entry (pin it, retire it, refresh its evidence) is a " ++ "judgement over content that naming any one of would be a guess dressed as an " ++ "instruction.",+ },+ "o2b search check": {+ cls: STATE_CLASS.refusal,reason:- "is itself the exit other surfaces name: the `stale-notes` registry entry resolves " +- "to `o2b brain stale`. What to do with a stale entry - pin it, retire it, refresh " +- "its evidence - is a judgement over content, and naming any one of the three would " +- "be a guess dressed as an instruction.",+ "refuses through `resolveConfig` in `search/helpers.ts`, which throws a `CliError` " ++ "naming `--vault` and `o2b init` when no vault resolves. Splitting `search.ts` by " ++ "verb moved that refusal out of this verb's own file and changed nothing about which " ++ "verb makes it.",+ },+ "o2b search weights": {+ cls: STATE_CLASS.refusal,+ reason:+ "refuses through the same `resolveConfig` in `search/helpers.ts` as `search check`, " ++ "called by `cmdSearchWeights` in `search/verbs/learned-weights.ts` before it reads " ++ "any weights. The refusal is one module away for the same reason: the verb split, " ++ "not a verb that stopped refusing.",},});+/**+ * Every state this census classifies by name instead of by detection.+ * One inventory for the gates and the cap, so neither escape hatch can be+ * widened without the other noticing.+ */+const DECLARED_STATES: ReadonlyArray<readonly [string, StateNote]> = Object.freeze([+ ...Object.entries(CLASSIFIED_BY_HAND),+ ...Object.entries(CLASSIFIED_BY_MODULE_WALK),+]);+/** A reason has to say something; a placeholder cannot reach this. */const MIN_REASON_LENGTH = 60;@@ -159,31 +249,125 @@ const MODULE_BODIES: ReadonlyArray<readonly [string, ReadonlyMap<string, string>(path) => [path, topLevelBodies(readSource(path))] as const,);+const BODIES_BY_MODULE: ReadonlyMap<string, ReadonlyMap<string, string>> = new Map(MODULE_BODIES);++/**+ * How many local-import hops a refusal may sit behind and still count as+ * one the verb makes. One is the shape the CLI has - a verb in+ * `<command>/verbs/<name>.ts` reaching `<command>/helpers.ts` - and it is+ * also the whole of what more would buy: detection over the dispatched+ * states is 166 at zero hops and 171 at one, and stays 171 at two, three+ * and five. No verb states its refusal two modules from its own file, and+ * the test below pins that so the number stops being a matter of belief.+ *+ * A larger bound could not reach the shared CLI-root modules either way:+ * `commandSubtree` returns null for `argparse.ts` and `output.ts`, so+ * {@link localImports} drops them at every hop count, which is what keeps+ * the walk from drifting into "some function somewhere in the CLI can+ * throw".+ */+const MAX_MODULE_HOPS = 1;++/**+ * The command a module belongs to: `src/cli/<command>` for anything under+ * one, null for the shared modules sitting at the `src/cli` root+ * (`argparse.ts`, `helpers.ts`, `output.ts`, `main.ts`).+ */+function commandSubtree(path: string): string | null {+ const head = relative(CLI_ROOT, path).split(sep)[0];+ if (head === undefined || head === "" || head.endsWith(".ts")) return null;+ return join(CLI_ROOT, head);+}++/**+ * The names `text` imports from sibling modules of its OWN command, each+ * mapped to the absolute path of the module it came from.+ *+ * Two filters, and the second is the load-bearing one. Only relative+ * specifiers are resolved, and only when they land on a file the census+ * already parsed - so a package or a `../../core/...` path resolves to+ * nothing. And the target must sit in the same `src/cli/<command>` subtree+ * as the importer, which is the code that was extracted OUT OF this verb's+ * own file: `search/verbs/check.ts` reaches `search/helpers.ts`, and+ * nothing reaches the CLI-wide plumbing every command shares.+ *+ * That second filter is what stops the walk from becoming vacuous.+ * Following into `argparse.ts` would credit EVERY verb with a refusal,+ * because every verb parses flags and `parseFlags` throws - 174 of 174+ * states detected at a single hop, measured. A refusal that belongs to+ * the shared entry-plumbing is not a refusal the verb makes.+ */+function localImports(path: string, text: string): ReadonlyMap<string, string> {+ const imports = new Map<string, string>();+ const command = commandSubtree(path);+ if (command === null) return imports;+ for (const match of text.matchAll(/import\s+(?:type\s+)?\{([^}]*)\}\s+from\s+"(\.[^"]*)"/g)) {+ const target = resolve(dirname(path), match[2]!);+ if (!BODIES_BY_MODULE.has(target)) continue;+ if (commandSubtree(target) !== command) continue;+ for (const specifier of match[1]!.split(",")) {+ // `x`, `type x`, and `x as y` all bind the LAST identifier locally.+ const local = specifier+ .trim()+ .split(/\s+as\s+/)+ .pop()+ ?.trim()+ .replace(/^type\s+/, "");+ if (local !== undefined && local !== "") imports.set(local, target);+ }+ }+ return imports;+}++const IMPORTS_BY_MODULE: ReadonlyMap<string, ReadonlyMap<string, string>> = new Map(+ MODULE_BODIES.map(([path]) => [path, localImports(path, readSource(path))] as const),+);+/** The module that declares `fn`, or null when nothing does. */function moduleDeclaring(fn: string): readonly [string, ReadonlyMap<string, string>] | null {return MODULE_BODIES.find(([, bodies]) => bodies.has(fn)) ?? null;}/**- * The source a call to `fn` can actually reach without leaving its own- * module: its body plus the bodies of every same-module function it- * calls, transitively. Handlers that fan out to private sub-verbs- * (`cmdBrainGit` -> `cmdStatus`) are classified by what those sub-verbs- * do, which is the only reading that matches what a caller experiences.+ * The source a call to `fn` in `module` can actually reach: its body, the+ * bodies of every same-module function it calls, and - up to `maxHops`+ * local-import hops away - the bodies of the sibling CLI modules it calls+ * into. Handlers that fan out to private sub-verbs (`cmdBrainGit` ->+ * `cmdStatus`) are classified by what those sub-verbs do, and a verb+ * whose only refusal is stated in the helpers module beside it is still+ * credited with making it - which is the only reading that matches what a+ * caller experiences.+ *+ * A name that resolves to neither a same-module function nor an imported+ * CLI module contributes nothing and ends that branch, so the `default:`+ * arm of a dispatcher - `process.stderr.write` and a literal - terminates+ * here the same way it always did.*/-function reachableSource(bodies: ReadonlyMap<string, string>, fn: string): string {+function reachableSource(module: string, fn: string, maxHops: number = MAX_MODULE_HOPS): string {const seen = new Set<string>();- const pending = [fn];+ const pending: Array<{ readonly module: string; readonly name: string; readonly hops: number }> =+ [{ module, name: fn, hops: 0 }];let source = "";while (pending.length > 0) {- const name = pending.pop()!;- if (seen.has(name)) continue;- seen.add(name);+ const { module: current, name, hops } = pending.pop()!;+ const key = `${current}::${name}`;+ if (seen.has(key)) continue;+ seen.add(key);+ const bodies = BODIES_BY_MODULE.get(current);+ if (bodies === undefined) continue;const body = bodies.get(name);if (body === undefined) continue;source += body;+ const imports = IMPORTS_BY_MODULE.get(current);for (const call of body.matchAll(/\b([A-Za-z0-9_]+)\s*\(/g)) {- if (bodies.has(call[1]!) && !seen.has(call[1]!)) pending.push(call[1]!);+ const callee = call[1]!;+ if (bodies.has(callee)) {+ pending.push({ module: current, name: callee, hops });+ continue;+ }+ if (hops >= maxHops) continue;+ const target = imports?.get(callee);+ if (target !== undefined) pending.push({ module: target, name: callee, hops: hops + 1 });}}return source;@@ -218,7 +402,7 @@ const DISPATCHERS: ReadonlyArray<readonly [string, string, string]> = [["o2b search", "search.ts", "export async function handleSearchSubcommand"],];-function census(): ReadonlyArray<CensusRow> {+function census(maxHops: number = MAX_MODULE_HOPS): ReadonlyArray<CensusRow> {const rows: CensusRow[] = [];for (const [level, file, marker] of DISPATCHERS) {for (const [verb, handler] of dispatcherCases(file, marker)) {@@ -228,8 +412,8 @@ function census(): ReadonlyArray<CensusRow> {expect(`${level} ${verb} handler ${handler} resolves: ${declaring !== null}`).toBe(`${level} ${verb} handler ${handler} resolves: true`,);- const [modulePath, bodies] = declaring!;- const source = reachableSource(bodies, handler);+ const [modulePath] = declaring!;+ const source = reachableSource(modulePath, handler, maxHops);rows.push({state: `${level} ${verb}`,handler,@@ -255,6 +439,10 @@ describe("terminal-state census", () => {});test("every state holds exactly one class", () => {+ // Only the hand inventory can add a class. A+ // `CLASSIFIED_BY_MODULE_WALK` entry restates the class the detector+ // found - it explains a detection, it does not stand in for one - and+ // the walk test below is where that agreement is checked.const rows = census();const byState = new Map(rows.map((row) => [row.state, row]));for (const row of rows) {@@ -266,16 +454,18 @@ describe("terminal-state census", () => {expect(byState.size).toBe(rows.length);});- test("no hand classification outlives the state it explains", () => {+ test("no declared classification outlives the state it explains", () => {const states = new Set(census().map((row) => row.state));- for (const state of Object.keys(CLASSIFIED_BY_HAND)) {+ for (const [state] of DECLARED_STATES) {expect(`${state} is dispatched: ${states.has(state)}`).toBe(`${state} is dispatched: true`);}+ // One state, one entry: nothing is declared by both inventories.+ expect(new Set(DECLARED_STATES.map(([state]) => state)).size).toBe(DECLARED_STATES.length);});- test("every hand-written reason is specific, and every class is a real class", () => {+ test("every declared reason is specific, and every class is a real class", () => {const known = new Set<string>(Object.values(STATE_CLASS));- for (const [state, entry] of Object.entries(CLASSIFIED_BY_HAND)) {+ for (const [state, entry] of DECLARED_STATES) {expect(`${state} class is known: ${known.has(entry.cls)}`).toBe(`${state} class is known: true`,);@@ -296,20 +486,59 @@ describe("terminal-state census", () => {expect(rows.length).toBeGreaterThan(160);expect(rows.filter((row) => row.detected === STATE_CLASS.exit).length).toBeGreaterThan(8);expect(rows.filter((row) => row.detected === STATE_CLASS.refusal).length).toBeGreaterThan(120);- // And the exception table must stay an exception.- expect(Object.keys(CLASSIFIED_BY_HAND).length).toBeLessThan(rows.length / 10);+ // And the states named by hand - by either inventory - must stay the+ // exception rather than becoming the way states get classified.+ expect(DECLARED_STATES.length).toBeLessThan(rows.length / 10);});- test("the deliberately-silent class is the smallest of the three", () => {- // If silence ever became the common answer, this release's thesis- // would have been abandoned rather than enforced.- const silent = Object.values(CLASSIFIED_BY_HAND).filter(- (entry) => entry.cls === STATE_CLASS.silent,+ test("the module walk is what classifies the verbs whose refusal was extracted", () => {+ // The measurement that keeps the widened walk honest. Each of these+ // states makes its only refusal in the helpers module beside it, so a+ // walk confined to the handler's own file cannot see it - and the only+ // repair available then is a hand entry, which is an exclusion. If the+ // import walk ever silently stops following, this names the states+ // that would have been excused rather than classified.+ const moduleLocal = new Map(census(0).map((row) => [row.state, row.detected]));+ const rescued = census()+ .filter((row) => row.detected !== null && moduleLocal.get(row.state) === null)+ .map((row) => `${row.state}: ${row.detected}`)+ .toSorted();+ // Named, not counted: the failure message is the work to be done.+ // The inventory is the expectation, so a state cannot be rescued by+ // the walk without an entry stating why - and an entry cannot claim a+ // class the detector did not actually find.+ expect(rescued.join("\n")).toBe(+ Object.entries(CLASSIFIED_BY_MODULE_WALK)+ .map(([state, entry]) => `${state}: ${entry.cls}`)+ .toSorted()+ .join("\n"),);- const rows = census();- expect(silent.length).toBeLessThan(- rows.filter((row) => row.detected === STATE_CLASS.exit).length,+ });++ test("one hop is the whole of what the module walk reaches", () => {+ // The measurement `MAX_MODULE_HOPS` is justified by. A second+ // hop detects nothing a first does not; if that ever changes, the+ // constant is wrong and its docblock is a story.+ const detected = (hops: number): number =>+ census(hops).filter((row) => row.detected !== null).length;+ const reached = detected(MAX_MODULE_HOPS);+ expect(`detected at ${MAX_MODULE_HOPS + 1} hops: ${detected(MAX_MODULE_HOPS + 1)}`).toBe(+ `detected at ${MAX_MODULE_HOPS + 1} hops: ${reached}`,+ );+ // And the hop the constant does buy has to be buying something.+ expect(reached).toBeGreaterThan(detected(0));+ });++ test("no state is classified deliberately-silent", () => {+ // The class stays in the vocabulary; nothing holds it. While it is+ // empty, "silence is the smallest of the three classes" compares zero+ // against a positive number and cannot fail, so the membership list+ // is the assertion instead. A state that genuinely earns silence+ // fails here and is added with its reason, deliberately.+ const silent = DECLARED_STATES.filter(([, entry]) => entry.cls === STATE_CLASS.silent).map(+ ([state]) => state,);+ expect(silent.toSorted().join("\n")).toBe("");});});diff --git a/tests/core/architecture/import-cycles.test.ts b/tests/core/architecture/import-cycles.test.tsnew file mode 100644index 00000000..851d275d--- /dev/null+++ b/tests/core/architecture/import-cycles.test.ts@@ -0,0 +1,258 @@+/**+ * Acyclic Dependencies Principle ratchet over `src/`.+ *+ * A cycle in the module graph is not a style problem: it makes the+ * initialisation order of the members undefined, so a class or constant+ * that one member evaluates at module scope can be observed as+ * `undefined` depending only on which file the bundler happened to enter+ * first. Both cycles this repository carried were of exactly that shape -+ * an aggregate module that DEFINED an error class and a result row while+ * also naming leaf types from its own dependents, and a path-builder+ * module that imported the write guard which imported the builder's+ * constants.+ *+ * The fix in both cases was a leaf module that imports nothing from the+ * layer above it. That property is invisible in review - re-adding one+ * import to a leaf silently closes the loop again - so it is asserted+ * here instead.+ *+ * Static `import` / `export β¦ from` declarations only, which is the+ * edge set the file-level graph is built from. Two deliberate readings+ * of that boundary, both asserted below so neither can rot into a+ * comment that outlives the code:+ *+ * `import type β¦ from "β¦"` IS an edge, even though the emitted module+ * has none. The stricter line is the useful one here: the `type` keyword+ * is one word, dropping it is invisible in review, and the moment it goes+ * the erased edge becomes a real initialisation-order edge. A ratchet+ * that only fails after that word is removed fails one commit too late.+ *+ * A deferred `await import("β¦")` is NOT an edge. It is evaluated at call+ * time, when both modules have finished initialising, so it cannot+ * produce the `undefined`-at-module-scope failure this test exists to+ * prevent - and it is the sanctioned cure for a cycle, used exactly that+ * way in this tree. Counting it would report the cure as the disease.+ * An `import("β¦")` in a type position pulls in no module either.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { dirname, relative, resolve } from "node:path";++const ROOT = resolve(import.meta.dir, "..", "..", "..");+const SRC = resolve(ROOT, "src");++/**+ * `import β¦` / `export β¦ from "<relative>"`, anchored at the start of a+ * line so a specifier quoted inside a docblock or a string literal is+ * not mistaken for a declaration. The body may span lines (formatted+ * multi-name imports) but never a `;`, which terminates the statement.+ */+const FROM_RE = /^[ \t]*(?:import|export)\b[^;]*?\bfrom\s*"(\.[^"]+)"/gm;+/** Side-effect import: `import "./x.ts";`. */+const BARE_RE = /^[ \t]*import\s*"(\.[^"]+)"/gm;+/** The same declarations minus the `type` ones, for the assertion below. */+const VALUE_FROM_RE = /^[ \t]*(?:import|export)\b(?!\s+type\b)[^;]*?\bfrom\s*"(\.[^"]+)"/gm;+/** The `export β¦ from` half of {@link FROM_RE}, floored on its own below. */+const REEXPORT_RE = /^[ \t]*export\b[^;]*?\bfrom\s*"(\.[^"]+)"/gm;+/**+ * A deferred `await import("β¦")`, anywhere in the file. Not part of the+ * graph - the assertion below is what keeps that a decision.+ */+const DEFERRED_RE = /\bawait\s+import\s*\(\s*"(\.[^"]+)"\s*\)/g;++/** The declaration kinds the initialisation-order graph is built from. */+const STATIC_PATTERNS: ReadonlyArray<RegExp> = [FROM_RE, BARE_RE];++interface ModuleGraph {+ readonly files: ReadonlyArray<string>;+ readonly edges: ReadonlyMap<string, ReadonlyArray<string>>;+}++function moduleFiles(): ReadonlyArray<string> {+ return [...new Bun.Glob("**/*.ts").scanSync({ cwd: SRC, absolute: true })].toSorted();+}++function importedFiles(+ file: string,+ known: ReadonlySet<string>,+ patterns: ReadonlyArray<RegExp>,+): ReadonlyArray<string> {+ const text = readFileSync(file, "utf8");+ const out = new Set<string>();+ for (const re of patterns) {+ for (const match of text.matchAll(new RegExp(re))) {+ const target = resolve(dirname(file), match[1]!);+ // Non-module relative imports (`../../package.json`) are data, not+ // graph edges, and are dropped by the known-file check.+ if (known.has(target)) out.add(target);+ }+ }+ return [...out];+}++function moduleGraph(patterns: ReadonlyArray<RegExp> = STATIC_PATTERNS): ModuleGraph {+ const files = moduleFiles();+ const known = new Set(files);+ const edges = new Map<string, ReadonlyArray<string>>();+ for (const file of files) edges.set(file, importedFiles(file, known, patterns));+ return { files, edges };+}++const edgeCount = (graph: ModuleGraph): number =>+ [...graph.edges.values()].reduce((total, targets) => total + targets.length, 0);++/** Edges `subset` has and `graph` does not, as readable `a -> b` pairs. */+function missingEdges(graph: ModuleGraph, subset: ModuleGraph): ReadonlyArray<string> {+ const out: string[] = [];+ for (const [file, targets] of subset.edges) {+ const present = new Set(graph.edges.get(file) ?? []);+ for (const target of targets) {+ if (!present.has(target)) out.push(`${relative(ROOT, file)} -> ${relative(ROOT, target)}`);+ }+ }+ return out.toSorted();+}++/**+ * Every strongly connected component with more than one member, as+ * repo-relative paths. Tarjan's algorithm, iterative so a deep import+ * chain cannot overflow the stack.+ */+function importCycles(graph: ModuleGraph = moduleGraph()): ReadonlyArray<ReadonlyArray<string>> {+ const { files, edges } = graph;++ const index = new Map<string, number>();+ const lowlink = new Map<string, number>();+ const onStack = new Set<string>();+ const stack: string[] = [];+ const components: string[][] = [];+ let counter = 0;++ for (const root of files) {+ if (index.has(root)) continue;+ // (node, next edge to visit) frames; a frame is revisited after each+ // child returns so the child's lowlink can be folded in.+ const frames: Array<{ node: string; edge: number }> = [{ node: root, edge: 0 }];+ index.set(root, counter);+ lowlink.set(root, counter);+ counter++;+ stack.push(root);+ onStack.add(root);++ while (frames.length > 0) {+ const frame = frames[frames.length - 1]!;+ const targets = edges.get(frame.node)!;+ if (frame.edge < targets.length) {+ const target = targets[frame.edge]!;+ frame.edge++;+ if (!index.has(target)) {+ index.set(target, counter);+ lowlink.set(target, counter);+ counter++;+ stack.push(target);+ onStack.add(target);+ frames.push({ node: target, edge: 0 });+ } else if (onStack.has(target)) {+ lowlink.set(frame.node, Math.min(lowlink.get(frame.node)!, index.get(target)!));+ }+ continue;+ }++ frames.pop();+ if (lowlink.get(frame.node) === index.get(frame.node)) {+ const component: string[] = [];+ for (;;) {+ const member = stack.pop()!;+ onStack.delete(member);+ component.push(relative(ROOT, member));+ if (member === frame.node) break;+ }+ if (component.length > 1) components.push(component.toSorted());+ }+ const parent = frames[frames.length - 1];+ if (parent !== undefined) {+ lowlink.set(parent.node, Math.min(lowlink.get(parent.node)!, lowlink.get(frame.node)!));+ }+ }+ }+ return components;+}++/**+ * Floors under the measurement, so "no cycle" cannot be reported over a+ * graph that was never built. `src/` carried 889 modules and 3808 edges+ * when these were set; each floor below is placed where a specific way of+ * losing the input crosses it, not at a round number.+ *+ * 850 modules is under today's count by less than the smallest layer+ * under `src/` holds (`src/mcp`, 54 modules), so a moved source root+ * (zero) or a glob that stopped seeing a whole layer trips it.+ *+ * 3400 edges is under that count by more than the two narrow halves of+ * the declaration pattern contribute together, and by less than any layer+ * carries (`src/mcp` alone accounts for 516), so it catches the quote+ * style changing under every pattern at once - which takes the graph to+ * zero edges over a full module list - and the layer loss above.+ *+ * The total is dominated by `import β¦ from`: the other two declaration+ * kinds are 224 and 37 edges, small enough that either could stop being+ * matched without the total crossing 3400. So each is measured on its own+ * pattern, floored at 180 and 25, and required to be PRESENT in the graph+ * the search ran over - which is what fails if the shared pattern loses+ * one of its halves. The side-effect kind earns that assertion beyond+ * symmetry: a module imported only for its registration side effect is+ * imported by nothing else, which is exactly where an+ * initialisation-order cycle hides.+ *+ * The last floor is under the erased edges themselves: 489 edges come+ * from a declaration carrying the `type` keyword, and 400 is the line+ * under which "type-only imports are edges too" would have stopped+ * describing a graph anyone can see.+ */+const MIN_MODULES = 850;+const MIN_EDGES = 3400;+const MIN_REEXPORT_EDGES = 180;+const MIN_SIDE_EFFECT_EDGES = 25;+const MIN_ERASED_EDGES = 400;++describe("module graph", () => {+ test("src/ carries no import cycle", () => {+ expect(importCycles()).toEqual([]);+ });++ test("the search is not vacuous - it ran over the real graph", () => {+ const graph = moduleGraph();+ expect(graph.files.length).toBeGreaterThan(MIN_MODULES);+ expect(edgeCount(graph)).toBeGreaterThan(MIN_EDGES);+ for (const [pattern, floor] of [+ [REEXPORT_RE, MIN_REEXPORT_EDGES],+ [BARE_RE, MIN_SIDE_EFFECT_EDGES],+ ] as const) {+ const half = moduleGraph([pattern]);+ expect(edgeCount(half)).toBeGreaterThan(floor);+ // Named, not counted: a declaration kind the graph stopped seeing+ // fails here listing the edges it lost.+ expect(missingEdges(graph, half).join("\n")).toBe("");+ }+ });++ test("a type-only import is an edge, so dropping the keyword cannot close a loop", () => {+ // The stricter reading the docblock claims, measured: the erased+ // declarations are a large minority of the graph, so a `type` keyword+ // is never what stands between the tree and a cycle.+ const strict = edgeCount(moduleGraph());+ const valuesOnly = edgeCount(moduleGraph([VALUE_FROM_RE, BARE_RE]));+ expect(valuesOnly).toBeLessThan(strict);+ expect(strict - valuesOnly).toBeGreaterThan(MIN_ERASED_EDGES);+ });++ test("a deferred import is left out because it is the cure, not the disease", () => {+ // Deferred imports exist in this tree precisely to break the loops+ // this test forbids. Counting them would report those cures as+ // findings, so the exclusion is asserted rather than assumed.+ const deferred = moduleGraph([...STATIC_PATTERNS, DEFERRED_RE]);+ expect(edgeCount(deferred)).toBeGreaterThan(edgeCount(moduleGraph()));+ expect(importCycles(deferred)).not.toEqual([]);+ });+});diff --git a/tests/core/brain/config-unreadable-call-sites.test.ts b/tests/core/brain/config-unreadable-call-sites.test.tsnew file mode 100644index 00000000..06ba1648--- /dev/null+++ b/tests/core/brain/config-unreadable-call-sites.test.ts@@ -0,0 +1,171 @@+/**+ * What a delivery surface does when `Brain/_brain.yaml` is present and+ * cannot be read.+ *+ * `policy-safe-loaders.test.ts` pins the READERS: absent is the defaults,+ * present-but-unreadable raises. This file pins the COMPOSITIONS those+ * readers sit inside, because a raise is only correct where something+ * downstream turns it into a named result. Two of them did not:+ *+ * - the pre-compress pack, where the strict integrity fallback and the+ * raising guardrail loader compose. An unreadable config resolves+ * `owner_scope_delivery` to `fail`, which gives a scoped caller an+ * enforced scope, which sends the active head through `renderActive`,+ * which raises. The scoped caller lost its whole pre-compaction+ * memory pack where the unscoped one still got a pack.+ * - `packContext`, whose raise reached the MCP surface as a named tool+ * error but escaped two CLI verbs as an unhandled throw.+ *+ * The absent-config case is asserted alongside every unreadable one: it+ * is the case the `*Safe` readers exist for, and it must not move.+ */++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 { readAnticipatoryContext } from "../../../src/core/brain/anticipatory-cache.ts";+import { packContext } from "../../../src/core/brain/context-pack.ts";+import { brainActivePath, brainConfigPath } from "../../../src/core/brain/paths.ts";+import { buildPreCompressPack } from "../../../src/core/brain/pre-compress-pack.ts";+import { BrainConfigError, brainConfigUnreadableReport } from "../../../src/core/brain/policy.ts";+import { writePreference } from "../../../src/core/brain/preference.ts";+import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../../src/core/brain/types.ts";++/**+ * Parses as YAML and fails validation. The exact shape the reviewer+ * reproduced against: one bad line in a block the pack never reads.+ */+const BROKEN_CONFIG = `schema_version: 1\ndream:\n candidate_threshold: 0\n`;++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-config-unreadable-"));+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });+ writeFileSync(brainActivePath(vault), "# Active\n\nshared head\n", "utf8");+ writePreference(vault, {+ slug: "keep-going",+ topic: "keep-going",+ principle: "Keep the highest-confidence rule.",+ created_at: "2026-05-01T00:00:00Z",+ unconfirmed_until: "2026-05-08T00:00:00Z",+ status: BRAIN_PREFERENCE_STATUS.confirmed,+ evidenced_by: ["[[sig-2026-05-01-keep-going]]"],+ confirmed_at: "2026-05-02T00:00:00Z",+ applied_count: 1,+ violated_count: 0,+ last_evidence_at: "2026-05-02T00:00:00Z",+ confidence: BRAIN_CONFIDENCE.high,+ confidence_value: 0.9,+ });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++function breakConfig(): void {+ writeFileSync(brainConfigPath(vault), BROKEN_CONFIG, "utf8");+}++describe("brainConfigUnreadableReport", () => {+ test("an absent config has nothing to report", () => {+ expect(brainConfigUnreadableReport(vault)).toBeNull();+ });++ test("a readable config has nothing to report", () => {+ writeFileSync(brainConfigPath(vault), "schema_version: 1\n", "utf8");+ expect(brainConfigUnreadableReport(vault)).toBeNull();+ });++ test("an unreadable config reports the cause the parser gave", () => {+ breakConfig();+ const report = brainConfigUnreadableReport(vault);+ expect(report).not.toBeNull();+ expect(report!).toContain(brainConfigPath(vault));+ expect(report!).toContain("dream.candidate_threshold");+ });+});++describe("buildPreCompressPack: an unreadable config degrades, it does not refuse", () => {+ test("absent config: a scoped and an unscoped call both deliver, with no warning", () => {+ const scoped = buildPreCompressPack(vault, { topK: 5, agentScope: "agent-a" });+ const unscoped = buildPreCompressPack(vault, { topK: 5 });+ expect(scoped.text).toContain("Keep the highest-confidence rule.");+ expect(unscoped.text).toContain("shared head");+ expect(scoped.warnings).toBeUndefined();+ expect(unscoped.warnings).toBeUndefined();+ });++ /** The reviewer's reproduction, verbatim. */+ test("a scoped call still returns a pack instead of throwing", () => {+ breakConfig();+ const pack = buildPreCompressPack(vault, { agentScope: "agent-a", topK: 5 });+ expect(pack.text).toContain("Keep the highest-confidence rule.");+ });++ test("an unscoped call keeps returning a pack", () => {+ breakConfig();+ const pack = buildPreCompressPack(vault, { topK: 5 });+ expect(pack.text).toContain("shared head");+ });++ /**+ * The scope-narrowed head comes from `renderActive`, and only from+ * there: falling back to the shared file's bytes under an enforcing+ * gate would hand one agent every other agent's memories.+ */+ test("the scoped active head is withheld rather than served from the shared file", () => {+ breakConfig();+ const pack = buildPreCompressPack(vault, { agentScope: "agent-a", topK: 5 });+ expect(pack.activeHeadIncluded).toBe(false);+ expect(pack.text).not.toContain("shared head");+ });++ test("the pack names the broken config so the operator can act on it", () => {+ breakConfig();+ const pack = buildPreCompressPack(vault, { agentScope: "agent-a", topK: 5 });+ expect(pack.warnings).toEqual([brainConfigUnreadableReport(vault)!]);+ });++ test("a readable config leaves the scoped pack unwarned", () => {+ writeFileSync(brainConfigPath(vault), "schema_version: 1\n", "utf8");+ const pack = buildPreCompressPack(vault, { agentScope: "agent-a", topK: 5 });+ expect(pack.warnings).toBeUndefined();+ expect(pack.activeHeadIncluded).toBe(true);+ });+});++describe("packContext: the raise is the contract, and every caller must name it", () => {+ test("absent config: the pack is built on the documented guardrail defaults", () => {+ expect(() => packContext(vault, { maxTokens: 500 })).not.toThrow();+ });++ test("an unreadable config raises, naming the file", () => {+ breakConfig();+ let caught: unknown;+ try {+ packContext(vault, { maxTokens: 500 });+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(BrainConfigError);+ expect((caught as BrainConfigError).message).toContain(brainConfigPath(vault));+ });++ /**+ * `readAnticipatoryContext` documented itself as never throwing, and+ * that stopped being true the moment `packContext` grew a raise. The+ * contract is now the raise; this pins that the two agree, so the+ * docblock cannot drift back into a promise the code does not keep.+ */+ test("readAnticipatoryContext propagates the raise rather than swallowing it", () => {+ breakConfig();+ expect(() =>+ readAnticipatoryContext(vault, { sessionId: "s1", now: new Date("2026-05-02T00:00:00Z") }),+ ).toThrow(BrainConfigError);+ });+});diff --git a/tests/core/brain/digest-most-applied.test.ts b/tests/core/brain/digest-most-applied.test.tsindex c4914584..49e9cee8 100644--- a/tests/core/brain/digest-most-applied.test.ts+++ b/tests/core/brain/digest-most-applied.test.ts@@ -12,6 +12,7 @@ import { join } from "node:path";import { renderDigest } from "../../../src/core/brain/digest.ts";import { appendLogEvent } from "../../../src/core/brain/log.ts";+import { BrainConfigError } from "../../../src/core/brain/policy.ts";import { BRAIN_APPLY_RESULT, BRAIN_LOG_EVENT_KIND } from "../../../src/core/brain/types.ts";let vault: string;@@ -154,15 +155,23 @@ describe("digest most_applied block β custom config", () => {expect(result.content).toContain("## Most-applied (14d)");});- test("malformed _brain.yaml does not break the digest (falls back to defaults)", () => {+ /**+ * Corrected assertion. This used to expect the default window on a+ * malformed `_brain.yaml`, which is the collapse the read split removed:+ * the operator's window is not in force, and re-windowing silently makes+ * the digest name a different set of rules while reporting healthy. The+ * fallback exists for a vault with NO config, and that case keeps its own+ * coverage in the `defaults` block above.+ */+ test("malformed _brain.yaml raises rather than re-windowing the digest", () => {writeBrainYaml("this is not yaml\nschema_version: nope\n");- const result = renderDigest(vault, {- format: "json",- now: new Date("2026-05-20T12:00:00Z"),- since: new Date("2026-05-19T12:00:00Z"),- until: new Date("2026-05-20T12:00:00Z"),- });- const parsed = JSON.parse(result.content);- expect(parsed.most_applied.window_days).toBe(30);+ expect(() =>+ renderDigest(vault, {+ format: "json",+ now: new Date("2026-05-20T12:00:00Z"),+ since: new Date("2026-05-19T12:00:00Z"),+ until: new Date("2026-05-20T12:00:00Z"),+ }),+ ).toThrow(BrainConfigError);});});diff --git a/tests/core/brain/doctor-exit-census.test.ts b/tests/core/brain/doctor-exit-census.test.tsindex 4957b859..1c1ea2c3 100644--- a/tests/core/brain/doctor-exit-census.test.ts+++ b/tests/core/brain/doctor-exit-census.test.ts@@ -13,8 +13,15 @@* ## Enumerated from the detector, never from the tables** `DoctorIssue.code` is a free string, so the population is read out of- * `doctor.ts` itself and the tables are asked to account for it. Two- * shapes carry a code in that module and the census reads both:+ * the doctor's own source and the tables are asked to account for it.+ * That source is `doctor.ts` - the registry - plus every check module+ * under `doctor/`, and the directory is ENUMERATED RECURSIVELY rather+ * than listed: a check module added tomorrow is swept by this census the+ * moment it exists, wherever under that directory it is put, which is+ * the property a hand-maintained list could not have. The enumeration+ * was flat before, so a check family moved into a subdirectory would+ * have dropped out of the population without failing anything.+ * Two shapes carry a code in those modules and the census reads both:** - `code: "<literal>"` at a push site;* - `const <NAME>_CODE = "<literal>"` hoisted to a module constant.@@ -27,11 +34,21 @@** ## The boundary, stated rather than discovered*- * The population is what `doctor.ts` SPELLS. Three sites forward- * `notice.code` from the closed `DEGRADATION_CODE` vocabulary owned by- * other modules; those codes are classified in `applier-capability.ts`,- * which is the table that owns that vocabulary's repair question, and- * re-declaring them here would give one code two homes.+ * The population is what the doctor SPELLS. Five sites forward+ * `notice.code` from the closed `DEGRADATION_CODE` vocabulary, whose+ * members are enumerated in `src/core/integrity/degradation.ts` and+ * minted nowhere else. Two of them are classified in+ * `applier-capability.ts` - a table that answers the REPAIR question,+ * not this one - and the rest reach the `uncertain` stream with no exit+ * of either kind. That gap is stated in {@link NON_LITERAL_CODE_SITES}+ * rather than hidden: closing it needs one entry per code in+ * `doctor-exits.ts`, which is a decision per condition rather than a+ * mechanical sweep.+ *+ * A code this module CONSTRUCTS is not in that boundary, however closed+ * the vocabulary it comes from: `doctor/unreadable-path.ts` raises+ * `vault-walk-entry-skipped` itself, so it is spelled there, read by the+ * scan below, and classified like every other doctor code.** Modelled on `tests/core/brain/vault-guard-census.test.ts` and the* terminal-state census: detect the property syntactically, keep one@@ -41,7 +58,7 @@*/import { describe, expect, test } from "bun:test";-import { readFileSync } from "node:fs";+import { readdirSync, readFileSync } from "node:fs";import { join } from "node:path";import { DIAGNOSTIC_SIGNALS } from "../../../src/core/brain/diagnostics.ts";@@ -51,10 +68,29 @@ import {noExitReasons,} from "../../../src/core/brain/doctor-exits.ts";-const DOCTOR_SOURCE = readFileSync(- join(import.meta.dir, "..", "..", "..", "src", "core", "brain", "doctor.ts"),- "utf8",-);+const BRAIN_DIR = join(import.meta.dir, "..", "..", "..", "src", "core", "brain");+const CHECKS_DIR = join(BRAIN_DIR, "doctor");++/** Every `.ts` file under `dir`, at any depth, in a stable order. */+function checkModules(dir: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>+ a.name.localeCompare(b.name),+ )) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...checkModules(path));+ else if (entry.name.endsWith(".ts")) out.push(path);+ }+ return out;+}++/** The registry plus every check module it runs, enumerated from disk. */+const DOCTOR_SOURCE_PATHS: ReadonlyArray<string> = [+ join(BRAIN_DIR, "doctor.ts"),+ ...checkModules(CHECKS_DIR),+];++const DOCTOR_SOURCE = DOCTOR_SOURCE_PATHS.map((path) => readFileSync(path, "utf8")).join("\n");/** `code: "<literal>"` - the shape most of the doctor's codes take. */const LITERAL_CODE_RE = /\bcode: "([^"]+)"/g;@@ -78,9 +114,14 @@ const CODE_IDENTIFIER_RE = /^[A-Z0-9_]*CODE[A-Z0-9_]*$/;const NON_LITERAL_CODE_SITES: Readonly<Record<string, string>> = Object.freeze({"notice.code":"forwards a code from the closed DEGRADATION_CODE vocabulary owned by vault.ts, " +- "vault-identity.ts and the lineage verifier into the uncertain stream. Those codes are " +- "classified in applier-capability.ts, the table that owns that vocabulary; declaring them " +- "here too would give one code two homes that can disagree.",+ "vault-identity.ts and the lineage verifier. Its members are enumerated in " ++ "src/core/integrity/degradation.ts and minted nowhere else, so the values this expression can " ++ "hold are readable there. Their EXITS are not all accounted for: vault-marker-absent and " ++ "frontmatter-line-dropped sit in applier-capability.ts (a table answering the repair " ++ "question), vault-walk-entry-skipped is registered in DIAGNOSTIC_SIGNALS because this pass " ++ "constructs it, and the lineage and frontmatter-unreadable members reach the uncertain stream " ++ "with neither a command nor a written reason. Closing that needs an entry per code in " ++ "doctor-exits.ts and a judgement per condition, which this census names rather than performs.","parseErrorCode(kindPrefix, msg)":"returns one of the four parse-error constants declared beside it, every one of which the " +"*_CODE scan above already reads. The function exists so the choice between them is made in " +@@ -88,6 +129,41 @@ const NON_LITERAL_CODE_SITES: Readonly<Record<string, string>> = Object.freeze({"those four codes unreadable from this module's source at all.",});+/**+ * Every doctor code whose exit is a REGISTERED command, pinned.+ *+ * The exclusion table is already guarded in both directions - a code+ * with no reason fails, and a reason outliving its code fails. The+ * registry could not be: it holds far more than the doctor's codes+ * (terminal states, runtime notices, the O3 snapshot classes), so+ * nothing derivable from it says which entries the doctor still spells.+ * Deleting a whole check module therefore satisfied every floor below+ * while the doctor silently stopped checking backlinks.+ *+ * Adding a doctor code with a command, or retiring one, edits this list+ * in the same commit - which is the review this census exists to force.+ */+const DOCTOR_REGISTERED_CODES: ReadonlyArray<string> = [+ "brain-root-absent",+ "broken-backlinks",+ "broken-wikilink",+ "config-invalid",+ "config-missing",+ "content-hash-drift",+ "contradictory-preferences",+ "dangling-workrun",+ "duplicate-preferences",+ "entity-label-malformed",+ "low-evidence-confirmed",+ "orphan-evidence",+ "principle-corrupted",+ "schema-version-unknown",+ "stale-claim",+ "sync-conflict-log",+ "tier-drift",+ "vault-walk-entry-skipped",+];+/** A reason has to say something; a placeholder cannot reach this. */const MIN_REASON_LENGTH = 80;@@ -136,6 +212,16 @@ describe("every doctor code is classified", () => {expect(both.join("\n")).toBe("");});+ test("no registration outlives the check module that spelled its code", () => {+ // Named, not counted, in both directions: a code that vanished from+ // the doctor and a code that appeared in it are different work.+ expect(+ doctorCodes()+ .filter((code) => DIAGNOSTIC_SIGNALS.has(code))+ .join("\n"),+ ).toBe([...DOCTOR_REGISTERED_CODES].toSorted().join("\n"));+ });+test("no exclusion outlives the code it explains", () => {const codes = new Set(doctorCodes());const orphans = [...DOCTOR_EXIT_EXCLUSIONS.keys()].filter((code) => !codes.has(code));@@ -159,6 +245,10 @@ describe("every doctor code is classified", () => {test("the census is not vacuous", () => {const codes = doctorCodes();+ // A sweep that lost the check modules - a renamed directory, a check+ // family moved out of it - would shrink the population without+ // failing any assertion below.+ expect(DOCTOR_SOURCE_PATHS.length).toBeGreaterThan(10);// A regex that stopped matching would sweep an empty set clean.expect(codes.length).toBeGreaterThan(35);expect(constantCodes().size).toBeGreaterThan(3);diff --git a/tests/core/brain/doctor-unreadable-paths.test.ts b/tests/core/brain/doctor-unreadable-paths.test.tsnew file mode 100644index 00000000..f143cfa1--- /dev/null+++ b/tests/core/brain/doctor-unreadable-paths.test.ts@@ -0,0 +1,405 @@+/**+ * A path the doctor could not read is uncertainty, never silence.+ *+ * The three sweeps that walk the store by hand - the symlink-escape+ * walk under `Brain/`, the removed-tool scan over Markdown, and the+ * basename sweep the orphan-evidence lint resolves references against -+ * each swallowed a failed read in a bare `catch` and returned. No+ * finding came out, and no finding is what every surface renders as a+ * clean bill of health: the operator was told the vault was fine+ * precisely where the doctor had been unable to look.+ *+ * The distinction these tests pin is the one that makes the fix safe. An+ * ABSENT directory was never a subtree to sweep - the common case, and+ * it must stay as quiet as it always was. A directory that exists and+ * cannot be listed, or a file standing where a directory was expected,+ * is a subtree that was skipped, and the doctor says so rather than+ * dying on it: every case below still returns a complete report.+ *+ * Three properties the first shipping of that fix did not have, and this+ * file now pins:+ *+ * - the code an operator reads on the `[UNSURE]` line RESOLVES to an+ * exit, so the line is not itself a dead end;+ * - one unread path produces ONE entry however many sweeps walked it,+ * and the stream is bounded;+ * - the absent/failed split is asked on every path the doctor reads,+ * including the ones an `existsSync` gate used to answer for it - a+ * gate that returns false for a permission denial as readily as for+ * an absence, and so reported a populated vault as an empty one.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ chmodSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runDoctor } from "../../../src/core/brain/doctor.ts";+import type { DoctorUncertainEntry } from "../../../src/core/brain/doctor/report.ts";+import {+ readSweptDir,+ SWEEP_ORIGIN,+ type SweptPath,+} from "../../../src/core/brain/doctor/unreadable-path.ts";+import { UNCERTAIN_MAX_PER_CODE } from "../../../src/core/brain/doctor/uncertain-stream.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { resolveNextStep } from "../../../src/core/brain/next-step.ts";+import { brainDirs } from "../../../src/core/brain/paths.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import { DEGRADATION_CODE } from "../../../src/core/integrity/degradation.ts";++const SKIPPED = DEGRADATION_CODE.vaultWalkEntrySkipped;++let tmp: string;+let vault: string;+let outside: string;+/** Paths chmod-ed unreadable by a test, restored before the tree is removed. */+let locked: string[];++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-doctor-unreadable-"));+ vault = join(tmp, "vault");+ outside = join(tmp, "outside");+ mkdirSync(vault, { recursive: true });+ mkdirSync(outside, { recursive: true });+ const configPath = join(tmp, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+ locked = [];+});++afterEach(() => {+ for (const path of locked) chmodSync(path, 0o700);+ rmSync(tmp, { recursive: true, force: true });+});++/**+ * Make `path` unreadable and register it for restoration. Fails loudly+ * rather than skipping when the mode does not actually deny the read -+ * a test that passes because the runner can read anything proves+ * nothing about the code under test.+ */+function makeUnreadable(path: string): string {+ chmodSync(path, 0o000);+ locked.push(path);+ return path;+}++function uncertain(): ReadonlyArray<DoctorUncertainEntry> {+ return runDoctor(vault).uncertain ?? [];+}++function skipsFor(path: string): ReadonlyArray<DoctorUncertainEntry> {+ return uncertain().filter((u) => u.code === SKIPPED && u.path === path);+}++describe("the environment can actually deny a read", () => {+ test("a 0o000 directory is unreadable to this runner", () => {+ const dir = join(tmp, "probe");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);+ // A runner that can read anything regardless of mode (root, or a+ // filesystem ignoring the bits) would make every assertion below+ // pass vacuously. Fail here instead, loudly.+ expect(() => readdirSync(dir)).toThrow();+ });+});++describe("the symlink-escape walk", () => {+ test("an unreadable directory under Brain/ is named, with the reason", () => {+ const dir = join(brainDirs(vault).inbox, "vaulted");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);++ const entry = skipsFor(dir).find((u) => u.message.includes("symlink"));+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("EACCES");+ });++ test("it still reports the escaping symlinks it COULD see", () => {+ const dir = join(brainDirs(vault).inbox, "vaulted");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);+ symlinkSync(outside, join(brainDirs(vault).preferences, "escape"));++ const result = runDoctor(vault);+ expect(result.errors.map((e) => e.code)).toContain("symlink-escape");+ });++ test("a directory that is merely ABSENT stays quiet", () => {+ // The freshly bootstrapped vault has no unreadable path anywhere,+ // and several of the directories the checks look for do not exist.+ expect(uncertain().filter((u) => u.code === SKIPPED)).toEqual([]);+ });+});++describe("the removed-tool scan", () => {+ test("a file standing where the skills directory was expected is named", () => {+ const skills = join(vault, ".claude", "skills");+ mkdirSync(join(vault, ".claude"), { recursive: true });+ writeFileSync(skills, "not a directory\n", "utf8");++ const entry = skipsFor(skills).find((u) => u.message.includes("removed"));+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("ENOTDIR");+ });++ test("an unreadable skills subdirectory is named", () => {+ const dir = join(vault, ".claude", "skills", "private");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);++ const entry = skipsFor(dir).find((u) => u.message.includes("removed"));+ expect(entry).toBeDefined();+ });++ test("a Markdown file it cannot open is named rather than skipped", () => {+ const file = join(brainDirs(vault).brain, "notes.md");+ writeFileSync(file, "brain_digest\n", "utf8");+ makeUnreadable(file);++ const entry = uncertain().find((u) => u.path === file && u.message.includes("removed"));+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("EACCES");+ });+});++describe("the orphan-evidence basename sweep", () => {+ test("an unreadable directory makes the basename universe incomplete, and says so", () => {+ const dir = join(vault, "notes");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);++ const entry = skipsFor(dir).find((u) => u.message.includes("basename"));+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("EACCES");+ });++ test("the lint still runs over what it could read", () => {+ const dir = join(vault, "notes");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);+ writeFileSync(+ join(brainDirs(vault).log, "2026-05-14.md"),+ `---+kind: brain-log+date: 2026-05-14+tags: [brain, brain/log]+---++# Brain Log β 2026-05-14++## 10:00:00Z β apply-evidence++- preference: [[pref-foo]]+- artifact: [[missing-vault-page]]+- agent: claude+- result: applied+`,+ "utf8",+ );++ const result = runDoctor(vault);+ expect(result.warnings.map((w) => w.code)).toContain("orphan-evidence");+ });+});++describe("the code an [UNSURE] line carries is not itself a dead end", () => {+ test("the skipped-entry code resolves to a next command", () => {+ // The CLI folds `uncertain` into the codes it resolves exits for. A+ // code in neither table prints the finding and nothing after it -+ // which is the dead end the exit census exists to make impossible.+ const step = resolveNextStep(SKIPPED);+ expect(step).not.toBeNull();+ expect(step!.nextCommand.startsWith("o2b ")).toBe(true);+ });++ test("the doctor emits exactly that code on an unreadable subtree", () => {+ const dir = join(brainDirs(vault).inbox, "vaulted");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);++ expect(uncertain().map((u) => u.code)).toContain(SKIPPED);+ });+});++describe("one unread path is one entry", () => {+ test("four sweeps over the same directory report it once", () => {+ const dir = join(brainDirs(vault).inbox, "vaulted");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);++ // The symlink walk, the removed-tool scan, the basename sweep and+ // the frontmatter probe all descend through Brain/inbox.+ expect(skipsFor(dir).length).toBe(1);+ });++ test("the surviving entry keeps the most informative consequence", () => {+ const dir = join(brainDirs(vault).inbox, "vaulted");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);++ // Of the four clauses written for this path, the basename sweep's is+ // the one that states most about what went unanswered; first-wins+ // would have kept whichever check the registry happens to run first.+ expect(skipsFor(dir)[0]!.message).toContain("basename universe");+ expect(skipsFor(dir)[0]!.message).toContain("EACCES");+ });++ test("the stream is capped, so a synced tree cannot flood the payload", () => {+ const parent = brainDirs(vault).inbox;+ for (let i = 0; i < UNCERTAIN_MAX_PER_CODE + 10; i += 1) {+ const dir = join(parent, `locked-${i}`);+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);+ }++ expect(uncertain().filter((u) => u.code === SKIPPED).length).toBe(UNCERTAIN_MAX_PER_CODE);+ });+});++describe("a failure on a parent path component", () => {+ test("an unreadable .claude/ does not read as an absent skills directory", () => {+ const claude = join(vault, ".claude");+ const skills = join(claude, "skills");+ mkdirSync(skills, { recursive: true });+ writeFileSync(join(skills, "old.md"), "brain_digest\n", "utf8");+ makeUnreadable(claude);++ // Before: `existsSync(skills)` was false because the PARENT denied+ // the stat, so the scan returned as if the vault had no skills at+ // all - and the migration this scan exists to surface vanished.+ const entry = skipsFor(skills)[0];+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("EACCES");+ });++ test("a self-referential skills symlink is named rather than silently skipped", () => {+ const skills = join(vault, ".claude", "skills");+ mkdirSync(join(vault, ".claude"), { recursive: true });+ symlinkSync(skills, skills);++ const entry = skipsFor(skills)[0];+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("ELOOP");+ });++ test("an unreadable vault root is not reported as an un-initialized one", () => {+ makeUnreadable(vault);++ const result = runDoctor(vault);+ // `brain-root-absent` resolves to `o2b brain init`, which would+ // write a Brain layer into a store this pass never managed to look+ // at. Absence and denial are different answers.+ expect(result.warnings.map((w) => w.code)).not.toContain("brain-root-absent");+ expect((result.uncertain ?? []).map((u) => u.code)).not.toContain("brain-root-absent");+ const entry = (result.uncertain ?? []).find((u) => u.code === SKIPPED);+ expect(entry).toBeDefined();+ expect(entry!.path).toBe(brainDirs(vault).brain);+ });++ test("a root that is genuinely absent still reports absent, unchanged", () => {+ const empty = join(tmp, "no-vault-here");+ mkdirSync(empty, { recursive: true });++ const result = runDoctor(empty);+ expect(result.warnings.map((w) => w.code)).toEqual(["brain-root-absent"]);+ expect((result.uncertain ?? []).map((u) => u.code)).toEqual(["brain-root-absent"]);+ });+});++describe("ENOENT means absent only where absence was possible", () => {+ test("a sweep's own root that is missing stays quiet", () => {+ const entries: DoctorUncertainEntry[] = [];+ const swept: SweptPath = { site: "test", consequence: "nothing was swept", uncertain: entries };++ expect(readSweptDir(join(tmp, "never-created"), swept, SWEEP_ORIGIN.root)).toBeNull();+ expect(entries).toEqual([]);+ });++ test("a path the walk itself listed is a race, not an absence", () => {+ const entries: DoctorUncertainEntry[] = [];+ const swept: SweptPath = {+ site: "test",+ consequence: "the subtree was skipped",+ uncertain: entries,+ };++ // The parent listed this name a moment ago, so it existed. ENOENT+ // here means it vanished under the walk - a subtree that was skipped+ // like any other, not an optional directory nobody created.+ expect(readSweptDir(join(tmp, "never-created"), swept, SWEEP_ORIGIN.discovered)).toBeNull();+ expect(entries.map((e) => e.code)).toEqual([SKIPPED]);+ expect(entries[0]!.message).toContain("ENOENT");+ });+});++describe("an entry that is neither a file nor a directory", () => {+ test("a symlinked Markdown file under Brain/ is named, not dropped", () => {+ // `Dirent.isFile()` and `isDirectory()` are both false for a+ // symlink, so this file was skipped with no error, no warning and no+ // uncertainty - and its target is outside Brain/, so no other pass+ // reads it either.+ const target = join(vault, "notes", "tool-note.md");+ mkdirSync(join(vault, "notes"), { recursive: true });+ writeFileSync(target, "brain_digest\n", "utf8");+ const alias = join(brainDirs(vault).inbox, "alias.md");+ symlinkSync(target, alias);++ const entry = skipsFor(alias)[0];+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("symbolic link");+ });+});++describe("the doctor never dies on an odd path", () => {+ test("every unreadable shape above still yields a complete report", () => {+ const dir = join(brainDirs(vault).inbox, "vaulted");+ mkdirSync(dir, { recursive: true });+ makeUnreadable(dir);+ const skills = join(vault, ".claude", "skills");+ mkdirSync(join(vault, ".claude"), { recursive: true });+ writeFileSync(skills, "not a directory\n", "utf8");++ expect(() => runDoctor(vault)).not.toThrow();+ expect(runDoctor(vault).trust_verdict).toBeDefined();+ });++ test("an unreadable Brain/ still produces findings rather than a throw", () => {+ makeUnreadable(brainDirs(vault).brain);++ expect(() => runDoctor(vault)).not.toThrow();+ const result = runDoctor(vault);+ expect(+ result.errors.length + result.warnings.length + (result.uncertain ?? []).length,+ ).toBeGreaterThan(0);+ expect((result.uncertain ?? []).some((u) => u.code === SKIPPED)).toBe(true);+ });++ test("an unreadable Brain/preferences still produces findings rather than a throw", () => {+ const prefs = brainDirs(vault).preferences;+ makeUnreadable(prefs);++ expect(() => runDoctor(vault)).not.toThrow();+ expect(skipsFor(prefs).length).toBe(1);+ });++ test("a regular file standing where Brain/log belongs is reported, not fatal", () => {+ const log = brainDirs(vault).log;+ rmSync(log, { recursive: true, force: true });+ writeFileSync(log, "not a directory\n", "utf8");++ expect(() => runDoctor(vault)).not.toThrow();+ const entry = skipsFor(log)[0];+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("ENOTDIR");+ });+});diff --git a/tests/core/brain/policy-safe-loaders.test.ts b/tests/core/brain/policy-safe-loaders.test.tsnew file mode 100644index 00000000..73e36019--- /dev/null+++ b/tests/core/brain/policy-safe-loaders.test.ts@@ -0,0 +1,438 @@+/**+ * The `load*ConfigSafe` readers and the ONE failure they are allowed to+ * absorb.+ *+ * `_brain.yaml` ABSENT is not an error: a vault that has never run+ * `o2b brain init` has no config, and the documented block defaults are+ * the correct answer. `_brain.yaml` PRESENT but unreadable is an error:+ * the operator wrote settings, those settings are not in force, and+ * serving the defaults instead makes a broken vault indistinguishable+ * from a healthy one - the exact degradation `loadIntegrityConfigSafe`+ * was already carved out to prevent, generalised here to the other five+ * readers.+ *+ * "Unreadable" is deliberately wider than "malformed YAML": a+ * structurally invalid block, a permission error and a directory where+ * the file should be are all a present config whose contents are not the+ * ones in force.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { regenerateActiveQuiet, renderActive } from "../../../src/core/brain/active.ts";+import { renderDigest } from "../../../src/core/brain/digest.ts";+import { resolveNoteRoots } from "../../../src/core/brain/notes/note-walk.ts";+import { brainConfigPath } from "../../../src/core/brain/paths.ts";+import {+ BRAIN_GUARDRAIL_DEFAULTS,+ BRAIN_MOST_APPLIED_DEFAULTS,+ BRAIN_NOTES_DEFAULTS,+ BRAIN_TEMPORAL_DEFAULTS,+ BrainConfigError,+ DEFAULT_BRAIN_CONFIG,+ loadActiveMostAppliedSafe,+ loadFeedbackDefaultScopeSafe,+ loadGuardrailsConfigSafe,+ loadIntegrityConfigSafe,+ loadNotesConfigSafe,+ loadSnapshotRetentionSafe,+ loadTemporalConfigSafe,+} from "../../../src/core/brain/policy.ts";++/**+ * Every reader that tolerates an uninitialised vault, paired with the+ * value that vault must keep producing. Driving them from one table is+ * what stops the next reader being added with a blanket catch - but only+ * together with the reverse census below, which enumerates the readers+ * from the module and fails when this list does not account for them.+ * The list alone could only ever prove things about readers somebody+ * remembered to add to it.+ */+const SAFE_LOADERS = [+ {+ name: "loadNotesConfigSafe",+ load: loadNotesConfigSafe as (vault: string) => unknown,+ absentValue: BRAIN_NOTES_DEFAULTS as unknown,+ },+ {+ name: "loadTemporalConfigSafe",+ load: loadTemporalConfigSafe as (vault: string) => unknown,+ absentValue: BRAIN_TEMPORAL_DEFAULTS as unknown,+ },+ {+ name: "loadGuardrailsConfigSafe",+ load: loadGuardrailsConfigSafe as (vault: string) => unknown,+ absentValue: BRAIN_GUARDRAIL_DEFAULTS as unknown,+ },+ {+ name: "loadFeedbackDefaultScopeSafe",+ load: loadFeedbackDefaultScopeSafe as (vault: string) => unknown,+ absentValue: undefined as unknown,+ },+ {+ name: "loadSnapshotRetentionSafe",+ load: loadSnapshotRetentionSafe as (vault: string) => unknown,+ absentValue: DEFAULT_BRAIN_CONFIG.snapshots.retention_count as unknown,+ },+ {+ name: "loadActiveMostAppliedSafe",+ load: loadActiveMostAppliedSafe as (vault: string) => unknown,+ absentValue: BRAIN_MOST_APPLIED_DEFAULTS as unknown,+ },+] as const;++// ----- Reverse census: the table must account for every reader ---------------++/**+ * A reader the table deliberately does not drive, with the reason. An+ * entry may only sit here because the module documents a DIFFERENT answer+ * to the same question - never because updating the table was awkward.+ */+const SAFE_LOADER_EXCLUSIONS: ReadonlyMap<string, string> = new Map([+ [+ "loadIntegrityConfigSafe",+ "resolves to BRAIN_INTEGRITY_STRICT_FALLBACK instead of raising, because the " ++ "search layer reads its gate on every store open inside a fail-soft path; " ++ "its own test below pins that asymmetry",+ ],+]);++const LOAD_SOURCE_PATH = join(+ import.meta.dir,+ "..",+ "..",+ "..",+ "src",+ "core",+ "brain",+ "policy",+ "load.ts",+);++/**+ * Every exported reader in `policy/load.ts`, read out of the SOURCE.+ *+ * The table above is hand-listed, so on its own it can only prove things+ * about readers somebody remembered to add to it - which is the one+ * property a ratchet must not have. Enumerating from the module and+ * asking the table to account for the result is what makes "a seventh+ * reader cannot join with a blanket catch" a checked claim. The doctor's+ * exit census reads its population off disk for the same reason.+ *+ * Two shapes declare a reader, and both are matched: the factory-built+ * `export const <name> = makeAbsentTolerantLoader(`, and a hand-written+ * `export function <name>(` for a reader that answers the split its own+ * way. The `*Safe` suffix is the module's naming convention for "reads+ * the config, tolerates a vault that has never run `brain init`" - a+ * reader that dropped the suffix would fall out of this census, which is+ * why the measured count is pinned below.+ */+const EXPORTED_SAFE_READER_RE = /^export (?:const|function) (load[A-Za-z0-9]*Safe)\b/gm;++function exportedSafeReaders(source: string): ReadonlyArray<string> {+ return [...source.matchAll(new RegExp(EXPORTED_SAFE_READER_RE))].map((m) => m[1]!).toSorted();+}++describe("the safe-loader table accounts for every reader in the module", () => {+ const declared = exportedSafeReaders(readFileSync(LOAD_SOURCE_PATH, "utf8"));++ test("the scan finds readers at all, so a clean sweep cannot be an empty set", () => {+ expect(declared.length).toBe(SAFE_LOADERS.length + SAFE_LOADER_EXCLUSIONS.size);+ });++ test("every declared reader is either driven by the table or excluded with a reason", () => {+ const driven: ReadonlySet<string> = new Set<string>(SAFE_LOADERS.map((l) => l.name));+ const unaccounted = declared.filter(+ (name) => !driven.has(name) && !SAFE_LOADER_EXCLUSIONS.has(name),+ );+ expect(unaccounted).toEqual([]);+ });++ test("nothing is both driven and excluded", () => {+ const driven: ReadonlySet<string> = new Set<string>(SAFE_LOADERS.map((l) => l.name));+ expect([...SAFE_LOADER_EXCLUSIONS.keys()].filter((name) => driven.has(name))).toEqual([]);+ });++ test("the table and the exclusions name only readers the module still declares", () => {+ const present = new Set(declared);+ const stale = [+ ...SAFE_LOADERS.map((l): string => l.name),+ ...SAFE_LOADER_EXCLUSIONS.keys(),+ ].filter((name) => !present.has(name));+ expect(stale).toEqual([]);+ });++ test("every exclusion carries a reason", () => {+ for (const [name, reason] of SAFE_LOADER_EXCLUSIONS) {+ expect(reason.trim().length, `${name} must say why it is excluded`).toBeGreaterThan(0);+ }+ });++ /**+ * The check is worth nothing if it cannot fail. Pointed at a source+ * carrying a reader neither the table nor the exclusions names, it must+ * report exactly that reader.+ */+ test("a reader the table does not list is reported", () => {+ const withEighthReader =+ readFileSync(LOAD_SOURCE_PATH, "utf8") ++ "\nexport const loadUnlistedThingSafe = makeAbsentTolerantLoader(resolveNotes, null);\n";+ const driven: ReadonlySet<string> = new Set<string>(SAFE_LOADERS.map((l) => l.name));+ const unaccounted = exportedSafeReaders(withEighthReader).filter(+ (name) => !driven.has(name) && !SAFE_LOADER_EXCLUSIONS.has(name),+ );+ expect(unaccounted).toEqual(["loadUnlistedThingSafe"]);+ });+});++/** Parses as YAML but fails validation: `read_paths` must be a list. */+const STRUCTURALLY_WRONG = `schema_version: 1\nnotes:\n read_paths: 5\n`;++/** Does not parse at all: an indented first line has no parent key. */+const MALFORMED_YAML = ` schema_version: 1\n`;++/** A config an operator could plausibly have written, for the happy path. */+const VALID_CONFIG =+ `schema_version: 1\n` ++ `notes:\n read_paths: [Journal]\n` ++ `guardrails:\n provenance_trust_ordering: true\n` ++ `feedback:\n default_scope: writing\n` ++ `snapshots:\n retention_count: 3\n`;++describe("load*ConfigSafe: absent config", () => {+ let vault: string;++ beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-safe-loader-absent-"));+ });++ afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ });++ for (const loader of SAFE_LOADERS) {+ test(`${loader.name}: a vault with no Brain tree gets the documented default`, () => {+ expect(loader.load(vault)).toEqual(loader.absentValue);+ });++ test(`${loader.name}: a Brain tree with no _brain.yaml gets the documented default`, () => {+ mkdirSync(join(vault, "Brain"), { recursive: true });+ expect(loader.load(vault)).toEqual(loader.absentValue);+ });+ }+});++describe("load*ConfigSafe: present but unreadable config", () => {+ let vault: string;+ let configPath: string;++ beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-safe-loader-broken-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+ configPath = brainConfigPath(vault);+ });++ afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ });++ for (const loader of SAFE_LOADERS) {+ test(`${loader.name}: malformed YAML raises instead of serving defaults`, () => {+ writeFileSync(configPath, MALFORMED_YAML, "utf8");+ expect(() => loader.load(vault)).toThrow(BrainConfigError);+ });++ test(`${loader.name}: a structurally wrong config raises instead of serving defaults`, () => {+ writeFileSync(configPath, STRUCTURALLY_WRONG, "utf8");+ let caught: unknown;+ try {+ loader.load(vault);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(BrainConfigError);+ expect((caught as BrainConfigError).source).toBe(configPath);+ });++ test(`${loader.name}: a directory where the file should be raises`, () => {+ mkdirSync(configPath, { recursive: true });+ let caught: unknown;+ try {+ loader.load(vault);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(BrainConfigError);+ expect((caught as BrainConfigError).message).toContain("failed to read");+ });++ test(`${loader.name}: an unreadable file raises rather than reading as absent`, () => {+ writeFileSync(configPath, VALID_CONFIG, "utf8");+ chmodSync(configPath, 0o000);+ try {+ let caught: unknown;+ try {+ loader.load(vault);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(BrainConfigError);+ expect((caught as BrainConfigError).message).toContain("failed to read");+ } finally {+ chmodSync(configPath, 0o600);+ }+ });+ }++ test("the raised message names the file the operator has to fix", () => {+ writeFileSync(configPath, MALFORMED_YAML, "utf8");+ let caught: unknown;+ try {+ loadNotesConfigSafe(vault);+ } catch (err) {+ caught = err;+ }+ expect((caught as BrainConfigError).message).toContain(configPath);+ });++ /**+ * The integrity gates keep their own answer to the same question: they+ * must stay ENFORCING on a vault whose config broke, because the+ * search layer reads them on a store open and cannot take a throw.+ * Pinned here so the two shapes are not accidentally unified later.+ */+ test("loadIntegrityConfigSafe still resolves to its strict fallback, not a throw", () => {+ writeFileSync(configPath, MALFORMED_YAML, "utf8");+ expect(() => loadIntegrityConfigSafe(vault)).not.toThrow();+ });+});++/**+ * The readers raise; what matters to an operator is that the raise lands+ * on a surface. Three representative call sites, one per shape:+ * a plain read that propagates to its verb, a digest render whose+ * fire-and-warn wrapper names the cause on stderr, and the destructive+ * prune that must not run on a guessed retention.+ */+describe("call sites: an unreadable config is surfaced, never absorbed", () => {+ let vault: string;++ beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-safe-loader-callsite-"));+ });++ afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ });++ function breakConfig(): void {+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeFileSync(brainConfigPath(vault), MALFORMED_YAML, "utf8");+ }++ test("resolveNoteRoots: absent config still means `no folders to walk`", () => {+ expect(resolveNoteRoots(vault)).toEqual([]);+ });++ test("resolveNoteRoots: an unreadable config raises rather than walking nothing", () => {+ breakConfig();+ expect(() => resolveNoteRoots(vault)).toThrow(BrainConfigError);+ });++ test("renderActive: an uninitialised vault still renders its digest", () => {+ expect(renderActive(vault).counts.confirmed).toBe(0);+ });++ test("renderActive: an unreadable config raises, naming the file", () => {+ breakConfig();+ let caught: unknown;+ try {+ renderActive(vault);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(BrainConfigError);+ expect((caught as BrainConfigError).message).toContain(brainConfigPath(vault));+ });++ /**+ * `regenerateActiveQuiet` is the fire-and-warn wrapper `dream`, `pin`+ * and `merge` use. The raise must reach its stderr warning - that is+ * the visible channel on the paths that cannot fail the run - rather+ * than a digest silently rebuilt under default guardrails.+ */+ test("regenerateActiveQuiet: the raise is warned on stderr, not swallowed", () => {+ breakConfig();+ const written: string[] = [];+ const original = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string | Uint8Array): boolean => {+ written.push(String(chunk));+ return true;+ }) as typeof process.stderr.write;+ try {+ regenerateActiveQuiet(vault);+ } finally {+ process.stderr.write = original;+ }+ const combined = written.join("");+ expect(combined).toContain("regenerate active.md failed");+ expect(combined).toContain(brainConfigPath(vault));+ });++ /**+ * The digest reads the same `active.most_applied` window as `active.md`,+ * but nothing on its path raises first (the owner-scope gate it consults+ * en route is the integrity reader, which resolves rather than throws).+ * So it needs the split itself: an uninitialised vault renders on the+ * documented window, a broken config does not quietly re-window the+ * section an operator reads as their most-applied rules.+ */+ test("renderDigest: an uninitialised vault renders on the documented window", () => {+ const rendered = renderDigest(vault, { format: "json" });+ const payload = JSON.parse(rendered.content) as {+ most_applied: { window_days: number; limit: number };+ };+ expect(payload.most_applied.window_days).toBe(BRAIN_MOST_APPLIED_DEFAULTS.window_days);+ expect(payload.most_applied.limit).toBe(BRAIN_MOST_APPLIED_DEFAULTS.limit);+ });++ test("renderDigest: an unreadable config raises, naming the file", () => {+ breakConfig();+ let caught: unknown;+ try {+ renderDigest(vault, { format: "json" });+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(BrainConfigError);+ expect((caught as BrainConfigError).message).toContain(brainConfigPath(vault));+ });+});++describe("load*ConfigSafe: readable config", () => {+ let vault: string;++ beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-safe-loader-valid-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeFileSync(brainConfigPath(vault), VALID_CONFIG, "utf8");+ });++ afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ });++ test("each reader returns exactly what the operator wrote", () => {+ expect(loadNotesConfigSafe(vault).read_paths).toEqual(["Journal"]);+ expect(loadGuardrailsConfigSafe(vault).provenance_trust_ordering).toBe(true);+ expect(loadFeedbackDefaultScopeSafe(vault)).toBe("writing");+ expect(loadSnapshotRetentionSafe(vault)).toBe(3);+ });++ test("a block the operator omitted still resolves to its defaults", () => {+ expect(loadTemporalConfigSafe(vault)).toEqual(BRAIN_TEMPORAL_DEFAULTS);+ });+});diff --git a/tests/core/config-read-failure.test.ts b/tests/core/config-read-failure.test.tsnew file mode 100644index 00000000..e3a2ede9--- /dev/null+++ b/tests/core/config-read-failure.test.ts@@ -0,0 +1,449 @@+/**+ * `discoverConfig` and the ONE failure it is allowed to absorb.+ *+ * The plugin config (`config.yaml`) is the twin of `Brain/_brain.yaml`, and+ * the same two conditions have to stay apart here:+ *+ * - ABSENT - no config file at all. Every flag is off by documented+ * default and every resolver answers with its default. This is the+ * common case on a fresh install and must stay byte-identical.+ * - PRESENT BUT UNREADABLE - a directory where the file should be, or a+ * file that cannot be opened. The operator's settings exist and are+ * NOT in force; answering with the defaults reverts every gate to+ * `false` while the install looks exactly like one that never set a+ * flag.+ *+ * There is no third "parses but is invalid" condition to test on this file:+ * `parseSimpleYaml` skips every line that is not `key: value` by design+ * (parity with the legacy Python parser), so it has no failure mode. A+ * malformed plugin config is only ever one of the two I/O conditions above,+ * and the lossy-parse test below pins that the fix did not quietly turn the+ * tolerant parser into a strict one.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import {+ ConfigReadError,+ discoverConfig,+ resolveDeviceId,+ resolveInstallationSecret,+ resolveSkillAutoAttach,+ resolveVault,+ setConfigValue,+} from "../../src/core/config.ts";+import { receiptShardPath } from "../../src/core/brain/decisions/receipts.ts";+import { claimShardPath } from "../../src/core/brain/truth/store.ts";++const HOOKS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "hooks");++/** Env keys these tests must own outright, whatever the outer shell set. */+const OWNED_ENV = [+ "OPEN_SECOND_BRAIN_SKILL_AUTO_ATTACH",+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ "XDG_CONFIG_HOME",+ // The suite preload pins the device id to "" for deterministic log+ // shards; the identity tests below need the config path to be the+ // resolution source, so they own both identity overrides outright.+ "O2B_DEVICE_ID",+ "O2B_INSTALLATION_SECRET",+] as const;++let tmp: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-config-read-failure-"));+ for (const key of OWNED_ENV) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ for (const [key, value] of Object.entries(savedEnv)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+});++/** A config an operator could plausibly have written. */+const VALID_CONFIG = `vault: "/srv/example-vault"\nskill_auto_attach: "true"\n`;++describe("discoverConfig: absent config", () => {+ test("a missing file in an existing directory reports absent, with no data", () => {+ const path = join(tmp, "config.yaml");+ const result = discoverConfig(path);+ expect(result.exists).toBe(false);+ expect(result.path).toBe(path);+ expect(result.data).toEqual({});+ });++ test("a missing parent directory reports absent too", () => {+ const path = join(tmp, "never", "created", "config.yaml");+ const result = discoverConfig(path);+ expect(result.exists).toBe(false);+ expect(result.path).toBe(path);+ expect(result.data).toEqual({});+ });+});++describe("discoverConfig: present but unreadable config", () => {+ test("a directory where the file should be raises, naming the path", () => {+ const path = join(tmp, "config.yaml");+ mkdirSync(path, { recursive: true });+ let caught: unknown;+ try {+ discoverConfig(path);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(ConfigReadError);+ expect((caught as ConfigReadError).path).toBe(path);+ expect((caught as ConfigReadError).message).toContain(path);+ });++ test("a file that cannot be opened raises rather than reading as absent", () => {+ const path = join(tmp, "config.yaml");+ writeFileSync(path, VALID_CONFIG, "utf8");+ chmodSync(path, 0o000);+ try {+ let caught: unknown;+ try {+ discoverConfig(path);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(ConfigReadError);+ expect((caught as ConfigReadError).path).toBe(path);+ expect((caught as ConfigReadError).message).toContain(path);+ } finally {+ chmodSync(path, 0o600);+ }+ });++ /**+ * The condition an existence check cannot express. `existsSync` answers+ * `false` for EVERY stat failure, not only ENOENT, so a perfectly+ * readable config behind a directory that cannot be traversed reported as+ * absent - the operator's `vault:` and every gate in the file reverting+ * to its default while the install looked like one that never ran+ * `o2b init`. Only ENOENT on the path itself is an absence.+ */+ test("a config behind an untraversable directory raises, it is not absent", () => {+ const dir = join(tmp, "locked");+ mkdirSync(dir, { recursive: true });+ const path = join(dir, "config.yaml");+ writeFileSync(path, VALID_CONFIG, "utf8");+ chmodSync(dir, 0o000);+ try {+ let caught: unknown;+ try {+ discoverConfig(path);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(ConfigReadError);+ expect((caught as ConfigReadError).path).toBe(path);+ expect((caught as ConfigReadError).message).toContain(path);+ } finally {+ chmodSync(dir, 0o755);+ }+ });++ /**+ * Same reasoning at the gate: an untraversable parent must never resolve+ * a default-OFF flag to `false`, which is indistinguishable from the+ * operator never having set it.+ */+ test("a flag gate behind an untraversable directory raises rather than answering `off`", () => {+ const dir = join(tmp, "locked");+ mkdirSync(dir, { recursive: true });+ const path = join(dir, "config.yaml");+ writeFileSync(path, VALID_CONFIG, "utf8");+ chmodSync(dir, 0o000);+ try {+ expect(() => resolveSkillAutoAttach(path)).toThrow(ConfigReadError);+ } finally {+ chmodSync(dir, 0o755);+ }+ });++ /**+ * A directory whose contents cannot be listed is still a directory in the+ * config file's place - the not-a-regular-file refusal, reached through+ * the stat rather than through a failed read.+ */+ test("an unreadable directory in the config file's place raises too", () => {+ const path = join(tmp, "config.yaml");+ mkdirSync(path, { recursive: true });+ chmodSync(path, 0o000);+ try {+ expect(() => discoverConfig(path)).toThrow(ConfigReadError);+ } finally {+ chmodSync(path, 0o755);+ }+ });++ /**+ * The opposite outcome, on the same surface: content this parser cannot+ * represent is not an unreadable config. Nested YAML and junk lines are+ * skipped exactly as before, so tightening the read did not tighten the+ * parse - an operator whose file has a comment block and an indented+ * section keeps the keys it can read.+ */+ test("content the flat parser cannot represent is still read, not raised", () => {+ const path = join(tmp, "config.yaml");+ writeFileSync(+ path,+ `# a comment\nvault: "/srv/example-vault"\nnested:\n key: value\nno-colon-here\n`,+ "utf8",+ );+ const result = discoverConfig(path);+ expect(result.exists).toBe(true);+ expect(result.data["vault"]).toBe("/srv/example-vault");+ });+});++describe("call sites: an unreadable plugin config is surfaced, never read as `off`", () => {+ test("a flag gate on an absent config is off, exactly as before", () => {+ expect(resolveSkillAutoAttach(join(tmp, "config.yaml"))).toBe(false);+ });++ test("a flag gate on an unreadable config raises instead of answering `off`", () => {+ const path = join(tmp, "config.yaml");+ writeFileSync(path, VALID_CONFIG, "utf8");+ chmodSync(path, 0o000);+ try {+ expect(() => resolveSkillAutoAttach(path)).toThrow(ConfigReadError);+ } finally {+ chmodSync(path, 0o600);+ }+ });++ /**+ * The env twin is the escape hatch that makes the raise survivable: an+ * operator whose config file broke can still drive every gate from the+ * environment, because the file is not opened when the env key is set.+ */+ test("the env twin still answers without opening an unreadable config", () => {+ const path = join(tmp, "config.yaml");+ writeFileSync(path, VALID_CONFIG, "utf8");+ chmodSync(path, 0o000);+ process.env["OPEN_SECOND_BRAIN_SKILL_AUTO_ATTACH"] = "true";+ try {+ expect(resolveSkillAutoAttach(path)).toBe(true);+ } finally {+ chmodSync(path, 0o600);+ }+ });++ test("resolveVault on an absent config is `no vault configured`", () => {+ expect(resolveVault(join(tmp, "config.yaml"), { cwd: tmp })).toBeNull();+ });++ test("resolveVault on an unreadable config raises instead of reporting no vault", () => {+ const path = join(tmp, "config.yaml");+ writeFileSync(path, VALID_CONFIG, "utf8");+ chmodSync(path, 0o000);+ try {+ expect(() => resolveVault(path, { cwd: tmp })).toThrow(ConfigReadError);+ } finally {+ chmodSync(path, 0o600);+ }+ });++ /**+ * The write path is the one that made the collapse destructive: reading+ * the existing file as absent meant the merge had nothing to merge, so+ * persisting one key rewrote the operator's whole config down to that+ * single line.+ */+ test("setConfigValue raises rather than overwriting a config it could not read", () => {+ const path = join(tmp, "config.yaml");+ writeFileSync(path, VALID_CONFIG, "utf8");+ chmodSync(path, 0o400);+ let caught: unknown;+ try {+ // Readable-but-not-writable is not the condition under test; make the+ // read itself fail, which is what the old catch absorbed.+ chmodSync(path, 0o000);+ try {+ setConfigValue("agent_name", "someone", path);+ } catch (err) {+ caught = err;+ }+ } finally {+ chmodSync(path, 0o600);+ }+ expect(caught).toBeInstanceOf(ConfigReadError);+ expect(readFileSync(path, "utf8")).toBe(VALID_CONFIG);+ });+});++/**+ * Identity resolution on a config that cannot be read.+ *+ * The decision this pins: it RAISES. `resolveDeviceId` and+ * `resolveInstallationSecret` generate-and-persist on a miss, and an+ * unreadable file is not a miss - proceeding would mint a fresh identity+ * and write it through `setConfigValue`, which merges onto what it read+ * and would therefore flatten the operator's config to a single line. A+ * fresh device id also silently re-shards this device's log; a fresh+ * installation secret silently changes every `vault://` reference agents+ * correlate by. Both are worse than a refusal that names the file.+ */+describe("identity resolution refuses rather than minting a new identity", () => {+ /** Config the resolvers would otherwise overwrite. */+ const IDENTITY_CONFIG = `device_id: "abc12345"\ninstallation_secret: "${"0".repeat(32)}"\n`;++ function brokenConfig(): string {+ const path = join(tmp, "config.yaml");+ writeFileSync(path, IDENTITY_CONFIG, "utf8");+ chmodSync(path, 0o000);+ return path;+ }++ test("resolveDeviceId raises and persists nothing", () => {+ const path = brokenConfig();+ try {+ expect(() => resolveDeviceId(path)).toThrow(ConfigReadError);+ } finally {+ chmodSync(path, 0o600);+ }+ expect(readFileSync(path, "utf8")).toBe(IDENTITY_CONFIG);+ });++ test("resolveInstallationSecret raises and persists nothing", () => {+ const path = brokenConfig();+ try {+ expect(() => resolveInstallationSecret(path)).toThrow(ConfigReadError);+ } finally {+ chmodSync(path, 0o600);+ }+ expect(readFileSync(path, "utf8")).toBe(IDENTITY_CONFIG);+ });++ test("the claim shard path raises rather than silently choosing the legacy file", () => {+ const path = brokenConfig();+ try {+ expect(() => claimShardPath(join(tmp, "vault"), path)).toThrow(ConfigReadError);+ } finally {+ chmodSync(path, 0o600);+ }+ });++ test("the receipt shard path raises rather than silently choosing the legacy file", () => {+ const path = brokenConfig();+ try {+ expect(() => receiptShardPath(join(tmp, "vault"), path)).toThrow(ConfigReadError);+ } finally {+ chmodSync(path, 0o600);+ }+ });++ /**+ * The env escape hatch survives the raise, exactly as it does for the+ * flag gates: an operator whose config broke can still name the device+ * id without the file being opened at all.+ */+ test("the device-id env override still answers without opening the file", () => {+ const path = brokenConfig();+ process.env["O2B_DEVICE_ID"] = "workstation";+ try {+ expect(resolveDeviceId(path)).toBe("workstation");+ } finally {+ chmodSync(path, 0o600);+ }+ });+});++/**+ * Hooks are the call sites with no channel of their own: every hook wraps+ * its body in a fail-open catch so a broken install can never take down a+ * session. The raise must therefore change NOTHING observable for them -+ * same exit code, same silence - which is also why the operator's channel+ * for this condition is the CLI, not the hook.+ */+describe("hooks stay fail-open on an unreadable plugin config", () => {+ interface RunResult {+ readonly stdout: string;+ readonly stderr: string;+ readonly exit: number;+ }++ async function run(argv: string[], payload: unknown, env: Record<string, string>) {+ const proc = Bun.spawn(argv, {+ stdin: "pipe",+ stdout: "pipe",+ stderr: "pipe",+ env: { PATH: process.env["PATH"] ?? "", HOME: tmp, ...env },+ });+ proc.stdin.write(JSON.stringify(payload));+ await proc.stdin.end();+ const stdout = await new Response(proc.stdout).text();+ const stderr = await new Response(proc.stderr).text();+ const exit = await proc.exited;+ return { stdout, stderr, exit } satisfies RunResult;+ }++ test("gap-agenda exits clean and emits nothing when the config cannot be read", async () => {+ const path = join(tmp, "config.yaml");+ writeFileSync(path, VALID_CONFIG, "utf8");+ chmodSync(path, 0o000);+ try {+ const result = await run(+ ["bun", "run", join(HOOKS_DIR, "gap-agenda.ts")],+ { hook_event_name: "SessionStart", session_id: "s1" },+ { OPEN_SECOND_BRAIN_CONFIG: path },+ );+ expect(result.exit).toBe(0);+ expect(result.stdout).toBe("");+ } finally {+ chmodSync(path, 0o600);+ }+ });++ /**+ * The opposite outcome for the test above, which would otherwise pass on+ * a build where nothing raises at all: the SAME resolver, on the SAME+ * broken config, outside a hook's fail-open catch. It exits non-zero and+ * names the file - so the hook's silence is the hook's contract, not an+ * absent raise.+ */+ test("the same gate outside the hook's catch exits non-zero, naming the file", async () => {+ const path = join(tmp, "config.yaml");+ writeFileSync(path, VALID_CONFIG, "utf8");+ chmodSync(path, 0o000);+ const configModule = resolve(+ dirname(fileURLToPath(import.meta.url)),+ "..",+ "..",+ "src",+ "core",+ "config.ts",+ );+ try {+ const result = await run(+ [+ "bun",+ "-e",+ `const m = await import(${JSON.stringify(configModule)});+m.resolveGapLoopEnabled(${JSON.stringify(path)});`,+ ],+ {},+ { OPEN_SECOND_BRAIN_CONFIG: path },+ );+ expect(result.exit).not.toBe(0);+ expect(result.stderr).toContain(path);+ } finally {+ chmodSync(path, 0o600);+ }+ });+});diff --git a/tests/core/config.test.ts b/tests/core/config.test.tsindex e801da61..ed444952 100644--- a/tests/core/config.test.ts+++ b/tests/core/config.test.ts@@ -4,6 +4,7 @@ import { tmpdir } from "node:os";import { dirname, isAbsolute, join, resolve } from "node:path";import {+ ConfigReadError,defaultConfigPath,discoverConfig,parseSimpleYaml,@@ -108,21 +109,55 @@ describe("discoverConfig", () => {expect(r.data["runtime"]).toBe("hermes");});- test("reports a directory as missing (not a regular file)", () => {- const r = discoverConfig(tmp);- expect(r.exists).toBe(false);- expect(r.data).toEqual({});- });-- test("reports invalid utf8 as missing", () => {+ /**+ * Corrected assertion: this used to expect `exists: false` for a+ * directory in the config file's place, which is the collapse the read+ * split removed. "Missing" is what every resolver reads as "the operator+ * set nothing, use the default"; something IS at this path, and whatever+ * the operator configured is not in force. It raises now, exactly as the+ * matching case on `_brain.yaml` does. Full coverage of the two+ * conditions - including the unreadable directory and the untraversable+ * parent - lives in `config-read-failure.test.ts`.+ */+ test("raises on a directory in the config file's place", () => {+ expect(() => discoverConfig(tmp)).toThrow(ConfigReadError);+ });++ /**+ * Corrected assertion, and a corrected name: this used to be called+ * "reports invalid utf8 as missing" while asserting only that the+ * returned path equalled the input path - true of every outcome,+ * including the crash. It never checked `exists` or `data`, and the+ * behaviour it accepted was neither of the two conditions: a lossy+ * decode produced `exists: true` with `data: {}`, which every resolver+ * reads as "the operator set nothing".+ *+ * Bytes that do not decode are the canonical PRESENT BUT UNREADABLE+ * case. The parser's tolerance is a contract about SHAPE (`key: value`+ * versus nested blocks, parity with the legacy Python reader), not about+ * encoding, and the write path makes the difference destructive:+ * `setConfigValue` merges onto what it read, so a lossy decode would+ * persist the operator's file with every undecodable byte replaced.+ */+ test("raises on bytes that are not valid utf8, rather than parsing them lossily", () => {const p = join(tmp, "config.yaml");writeFileSync(p, Buffer.from([0xff, 0xfe, 0x00]));- const r = discoverConfig(p);- // Buffer with stray bytes still decodes (TextDecoder) without throwing,- // so we don't necessarily report missing. The Python parser is more- // strict. Either accept the lossy parse OR report missing β both- // are safe. We accept the lossy parse here (matches Bun's readFileSync).- expect(r.path).toBe(p);+ let caught: unknown;+ try {+ discoverConfig(p);+ } catch (err) {+ caught = err;+ }+ expect(caught).toBeInstanceOf(ConfigReadError);+ expect((caught as ConfigReadError).path).toBe(p);+ expect((caught as ConfigReadError).message).toContain(p);+ });++ /** The opposite outcome: valid UTF-8 beyond ASCII stays readable. */+ test("non-ascii utf8 values are read, not refused", () => {+ const p = join(tmp, "config.yaml");+ writeFileSync(p, 'instance_name: "ΠΡΠΎΡΠΎΠΉ ΠΌΠΎΠ·Π³"\n', "utf8");+ expect(discoverConfig(p).data["instance_name"]).toBe("ΠΡΠΎΡΠΎΠΉ ΠΌΠΎΠ·Π³");});});diff --git a/tests/core/fs-probe-absent-versus-broken.test.ts b/tests/core/fs-probe-absent-versus-broken.test.tsnew file mode 100644index 00000000..bc2cc7d8--- /dev/null+++ b/tests/core/fs-probe-absent-versus-broken.test.ts@@ -0,0 +1,119 @@+/**+ * A path that cannot be examined is not a path that is absent.+ *+ * `isFile` / `isDir` answered `false` for both, the same conflation the+ * plugin-config read split removed in 96b14d72: `existsSync` reports+ * `false` for EVERY stat failure, so a file sitting behind a directory+ * without the execute bit read as one that had never been created. The+ * probes stay lenient on purpose - most callers only ask "is this worth+ * opening" - so the split lives in `statOrAbsent`, and the callers whose+ * OUTPUT distinguishes the two conditions use that instead.+ *+ * Doctor is the caller that must: its entire product is the difference+ * between "not there" and "there and wrong", and its remedy differs. A+ * manifest reported as missing sends the operator to `o2b update`, which+ * regenerates it and leaves the permission fault exactly where it was.+ */++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 { isDir, isFile, statOrAbsent } from "../../src/core/fs-utils.ts";+import {+ checkHermesManifest,+ checkJsonManifest,+ checkOpenclawInstallability,+} from "../../src/core/doctor.ts";++let tmp: string;+/** Directory whose execute bit is dropped, hiding everything beneath it. */+let sealed: string;+/** A real regular file inside `sealed`, unreachable while it is sealed. */+let buried: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-fs-probe-"));+ sealed = join(tmp, "sealed");+ mkdirSync(sealed, { recursive: true });+ buried = join(sealed, "plugin.json");+ writeFileSync(buried, '{"name": "test", "version": "1.0.0"}', "utf8");+});++afterEach(() => {+ chmodSync(sealed, 0o700);+ rmSync(tmp, { recursive: true, force: true });+});++function seal(): void {+ chmodSync(sealed, 0o000);+}++describe("statOrAbsent separates absence from a failure to look", () => {+ test("a genuinely absent path answers undefined", () => {+ expect(statOrAbsent(join(tmp, "never-created"))).toBeUndefined();+ });++ test("an existing file answers with its stat", () => {+ expect(statOrAbsent(buried)?.isFile()).toBe(true);+ });++ test("a file behind an untraversable parent raises rather than reporting absence", () => {+ seal();+ expect(() => statOrAbsent(buried)).toThrow(/EACCES/);+ });+});++describe("isFile and isDir stay lenient, and that is the reason they are separate", () => {+ test("both answer false for the unreachable file without raising", () => {+ seal();+ expect(isFile(buried)).toBe(false);+ expect(isDir(buried)).toBe(false);+ });+});++describe("doctor names an unreadable manifest instead of calling it missing", () => {+ test("a JSON manifest behind an untraversable parent is reported unreadable", () => {+ seal();+ const r = checkJsonManifest(buried, "Test");+ expect(r.ok).toBe(false);+ expect(r.message).toContain("unreadable");+ expect(r.message).not.toContain("missing");+ // The remedy has to be the one that actually clears the condition:+ // regenerating the manifest does not restore the traversal bit.+ expect(r.fix).toContain("chmod");+ });++ test("a genuinely absent JSON manifest still reports missing", () => {+ const r = checkJsonManifest(join(tmp, "never-created.json"), "Test");+ expect(r.ok).toBe(false);+ expect(r.message).toContain("missing");+ });++ test("the Hermes manifest check makes the same distinction", () => {+ const hermes = join(sealed, "plugin.yaml");+ writeFileSync(hermes, "name: test\nversion: 1.0.0\n", "utf8");+ seal();+ const r = checkHermesManifest(hermes);+ expect(r.ok).toBe(false);+ expect(r.message).toContain("unreadable");+ expect(r.fix).toContain("chmod");+ });++ test("an unreadable OpenClaw extension entry is not reported as missing", () => {+ writeFileSync(join(tmp, "package.json"), JSON.stringify({ name: "t" }), "utf8");+ mkdirSync(join(tmp, ".git"), { recursive: true });+ writeFileSync(+ join(tmp, "package.json"),+ JSON.stringify({ name: "t", openclaw: { extensions: ["./sealed/entry.js"] } }),+ "utf8",+ );+ writeFileSync(join(sealed, "entry.js"), "export {};\n", "utf8");+ seal();+ const failing = checkOpenclawInstallability(tmp).filter((r) => !r.ok);+ expect(failing.length).toBeGreaterThan(0);+ expect(failing.some((r) => r.message.includes("unreadable"))).toBe(true);+ expect(failing.some((r) => r.message.includes("missing extension entry"))).toBe(false);+ });+});diff --git a/tests/core/search/trigram-degrade.test.ts b/tests/core/search/trigram-degrade.test.tsnew file mode 100644index 00000000..9eaeeb78--- /dev/null+++ b/tests/core/search/trigram-degrade.test.ts@@ -0,0 +1,201 @@+/**+ * The trigram candidate lane is a BROADENER: it only ever adds to a pool+ * the keyword lane already filled. So a fault in it degrades the lane and+ * never the query - but visibly, with a `trigram_degraded` warning on the+ * outcome, next to `hybrid_degraded` for the semantic lane. The one+ * exception is a `chunk_trigram` shadow that is simply absent (a store+ * migrated to v9 but never rebuilt): the table is optional, and that case+ * stays silent.+ */++import { test, expect, afterEach } from "bun:test";+import { Database } from "bun:sqlite";++import { indexVault } from "../../../src/core/search/indexer.ts";+import { search } from "../../../src/core/search/search.ts";+import {+ isMissingTrigramTable,+ trigramCandidates,+} from "../../../src/core/search/store/trigram.ts";+import { rebuildFtsIndexWithWriterLock } from "../../../src/core/search/store/keyword.ts";+import { acquireWriterLockSync } from "../../../src/core/search/store/writer-lock.ts";+import { SearchError } from "../../../src/core/search/types.ts";+import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";++const cleanups: Array<() => void> = [];+afterEach(() => {+ for (const c of cleanups.splice(0)) c();+});++/** A real v9 index over two documents, built by the real indexer. */+async function indexedVault(): Promise<{ vault: string; dbPath: string }> {+ const v = createTempVault("trigram-degrade");+ cleanups.push(v.cleanup);+ // "Reindexing" holds the substring "index" that the word tokenizer misses,+ // and is itself a whole word the keyword lane DOES match.+ writeMd(v.vault, "a.md", "# Ops\n\nReindexing the vault can be slow on large corpora.");+ writeMd(v.vault, "b.md", "# Turtles\n\nGreen turtles migrate across oceans.");+ await indexVault(makeConfig({ vault: v.vault, dbPath: v.dbPath }), {});+ return { vault: v.vault, dbPath: v.dbPath };+}++function openRaw(dbPath: string, opts: { readonly readOnly?: boolean } = {}): Database {+ const db =+ opts.readOnly === true ? new Database(dbPath, { readonly: true }) : new Database(dbPath);+ cleanups.push(() => db.close());+ return db;+}++function trigramConfig(vault: string, dbPath: string) {+ return makeConfig({+ vault,+ dbPath,+ trigramPrefilterEnabled: true,+ trigramPrefilterMinChunks: 0,+ });+}++/** Leaves `chunk_trigram` absent - the documented optional-table case. */+function dropTrigramShadow(dbPath: string): void {+ const db = openRaw(dbPath);+ db.exec("DROP TABLE chunk_trigram");+}++/**+ * Leaves a `chunk_trigram` that is NOT an FTS5 shadow - the shape a+ * half-applied migration or a replicated-then-repaired index leaves+ * behind. SQLite rejects the MATCH against it.+ */+function breakTrigramShadow(dbPath: string): void {+ const db = openRaw(dbPath);+ db.exec("DROP TABLE chunk_trigram");+ db.exec("CREATE TABLE chunk_trigram (id INTEGER PRIMARY KEY, fts_content TEXT)");+}++// βββ the predicate βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++test("only chunk_trigram itself reads as an absent shadow", () => {+ expect(isMissingTrigramTable("no such table: chunk_trigram")).toBe(true);+ expect(isMissingTrigramTable("no such table: main.chunk_trigram")).toBe(true);+});++test("a lost FTS5 shadow table does not read as an absent shadow", () => {+ // These name a shadow the index HAS lost: corruption, not an index that+ // never had the optional table.+ for (const shadow of ["data", "idx", "content", "docsize"]) {+ expect(isMissingTrigramTable(`no such table: main.chunk_trigram_${shadow}`)).toBe(false);+ expect(isMissingTrigramTable(`no such table: chunk_trigram_${shadow}`)).toBe(false);+ }+});++// βββ the lane, against induced faults ββββββββββββββββββββββββββββββββββββββββ++test("an absent chunk_trigram shadow stays silent", async () => {+ const { dbPath } = await indexedVault();+ dropTrigramShadow(dbPath);+ const db = openRaw(dbPath);++ const outcome = trigramCandidates(db, '"index"', { limit: 10 });++ expect(outcome.hits).toEqual([]);+ expect(outcome.warnings).toEqual([]);+});++test("a chunk_trigram that is not an FTS5 shadow degrades with a warning", async () => {+ const { dbPath } = await indexedVault();+ breakTrigramShadow(dbPath);+ const db = openRaw(dbPath);++ const outcome = trigramCandidates(db, '"index"', { limit: 10 });++ expect(outcome.hits).toEqual([]);+ expect(outcome.warnings).toEqual([+ "trigram_degraded [shadow_incomplete]: trigram candidate lane skipped; keyword candidates unaffected",+ ]);+});++test("a writer holding the database lock degrades the lane", async () => {+ const { dbPath } = await indexedVault();+ // Real contention, not a stubbed error: a second connection holds an+ // EXCLUSIVE transaction while the reader - with the wait shortened to+ // zero so the test does not sit out a busy timeout - runs the lookup.+ const writer = openRaw(dbPath);+ writer.exec("PRAGMA journal_mode = DELETE");+ const reader = openRaw(dbPath, { readOnly: true });+ reader.exec("PRAGMA busy_timeout = 0");+ expect(trigramCandidates(reader, '"index"', { limit: 10 }).warnings).toEqual([]);++ writer.exec("BEGIN EXCLUSIVE");+ const outcome = trigramCandidates(reader, '"index"', { limit: 10 });+ writer.exec("ROLLBACK");++ expect(outcome.hits).toEqual([]);+ expect(outcome.warnings).toEqual([+ "trigram_degraded [locked]: trigram candidate lane skipped; keyword candidates unaffected",+ ]);+ // And the lane answers again once the writer lets go.+ expect(trigramCandidates(reader, '"index"', { limit: 10 }).warnings).toEqual([]);+});++test("the warning carries no query text", async () => {+ const { dbPath } = await indexedVault();+ const db = openRaw(dbPath);++ // An FTS5 syntax error is the one failure whose message echoes the MATCH+ // expression, which is built from the caller's own query.+ const outcome = trigramCandidates(db, '"hunterterm" AND AND', { limit: 10 });++ expect(outcome.hits).toEqual([]);+ expect(outcome.warnings.length).toBe(1);+ expect(outcome.warnings[0]).not.toContain("hunterterm");+});++// βββ end to end: the search survives βββββββββββββββββββββββββββββββββββββββββ++test("a search whose trigram lane fails still returns the keyword-lane results", async () => {+ const { vault, dbPath } = await indexedVault();+ const cfg = trigramConfig(vault, dbPath);+ const healthy = await search(cfg, { query: "reindexing", limit: 10 });+ expect(healthy.results.map((r) => r.path)).toContain("a.md");++ breakTrigramShadow(dbPath);+ const degraded = await search(cfg, { query: "reindexing", limit: 10 });++ expect(degraded.results.map((r) => r.path)).toEqual(healthy.results.map((r) => r.path));+ expect(degraded.warnings.some((w) => w.startsWith("trigram_degraded ["))).toBe(true);+});++test("a search over an absent trigram shadow is byte-identical to a healthy one", async () => {+ const { vault, dbPath } = await indexedVault();+ const cfg = trigramConfig(vault, dbPath);+ const healthy = await search(cfg, { query: "reindexing", limit: 10 });++ dropTrigramShadow(dbPath);+ const absent = await search(cfg, { query: "reindexing", limit: 10 });++ expect(absent.results.map((r) => r.path)).toEqual(healthy.results.map((r) => r.path));+ expect(absent.warnings).toEqual(healthy.warnings);+ expect(absent.warnings.some((w) => w.startsWith("trigram_degraded"))).toBe(false);+});++// βββ the writer-lock guard travels with its function βββββββββββββββββββββββββ++test("rebuildFtsIndexWithWriterLock skips the lock when the caller already holds it", async () => {+ const { dbPath } = await indexedVault();+ const db = openRaw(dbPath);+ const release = acquireWriterLockSync(dbPath);+ try {+ // A caller that holds the writer lock must not re-enter it.+ expect(() => rebuildFtsIndexWithWriterLock(db, dbPath, true)).not.toThrow();+ // Without the guard the same call contends with the held lock.+ expect(() => rebuildFtsIndexWithWriterLock(db, dbPath, false)).toThrow(SearchError);+ } finally {+ release();+ }+});++test("rebuildFtsIndexWithWriterLock takes the lock when the caller does not hold it", async () => {+ const { dbPath } = await indexedVault();+ const db = openRaw(dbPath);+ expect(() => rebuildFtsIndexWithWriterLock(db, dbPath, false)).not.toThrow();+});diff --git a/tests/hooks/active-inject.test.ts b/tests/hooks/active-inject.test.tsindex 433a3bf3..f871b621 100644--- a/tests/hooks/active-inject.test.ts+++ b/tests/hooks/active-inject.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -285,3 +285,117 @@ describe("active-inject hook", () => {expect(injected).toContain("Search index is not built");});});++/**+ * A `_brain.yaml` the operator wrote and then broke.+ *+ * The injection-budget read inside the hook resolves to the default budget+ * on a config failure and MUST keep doing so. This is a SessionStart hook,+ * and the assembly the read sits in is the fail-open loader's `assemble`+ * callback: a raise there does not surface anything, it swaps the whole+ * injection for the last-good cache - a body captured while the config+ * still read, which therefore carries no word of the breakage. So the+ * property under test is not "it throws" but "it does not throw AND the+ * condition is named on the same surface": the runtime-notice block the+ * same assembly emits before it ever reads the budget.+ *+ * Three cases, the same split `load*ConfigSafe` makes - absent (the common+ * case for every vault in the wild, and silent by design), malformed, and+ * present-but-unopenable.+ */+describe("active-inject hook: _brain.yaml absent vs. unreadable", () => {+ 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";++ /** Does not parse at all: an indented first line has no parent key. */+ const MALFORMED_CONFIG = " schema_version: 1\n";++ /** The prose the `brain_config_unreadable` notice renders. */+ const CONFIG_NOTICE = "Brain/_brain.yaml could not be read";++ function configPath(): string {+ return join(vault, "Brain", "_brain.yaml");+ }++ /** Notices are opt-out in the shared harness; this channel is the point. */+ const NOTICES_ON = { OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "true" };++ 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("absent: no config notice, and the documented default budget applies", async () => {+ writeActive(ACTIVE_DOC);+ const injected = await inject(NOTICES_ON);+ // A vault that never ran `brain init` is healthy. It has settings to+ // report only about the index, never about a file it does not have.+ expect(injected).not.toContain(CONFIG_NOTICE);+ expect(injected).toContain("pref-foo");+ });++ test("malformed: the hook still injects, and the breakage rides the same payload", async () => {+ writeActive(ACTIVE_DOC);+ writeFileSync(configPath(), MALFORMED_CONFIG, "utf8");++ const injected = await inject(NOTICES_ON);+ // Not fatal: the session gets its preferences either way.+ expect(injected).toContain("pref-foo");+ // And not silent: the operator's settings are named as not in force.+ expect(injected).toContain(CONFIG_NOTICE);+ // The notice carries THIS vault's parse failure, path and all, so the+ // assertion cannot be satisfied by a constant sentence.+ expect(injected).toContain(configPath());+ expect(injected.indexOf(CONFIG_NOTICE)).toBeLessThan(injected.indexOf("pref-foo"));+ });++ test("unopenable: a config the process cannot read is reported, not read as absent", async () => {+ writeActive(ACTIVE_DOC);+ writeFileSync(configPath(), "schema_version: 1\n", "utf8");+ chmodSync(configPath(), 0o000);+ try {+ const injected = await inject(NOTICES_ON);+ expect(injected).toContain("pref-foo");+ expect(injected).toContain(CONFIG_NOTICE);+ expect(injected).toContain(configPath());+ } finally {+ chmodSync(configPath(), 0o600);+ }+ });++ test("malformed: the budget falls back to the default rather than going unbounded", async () => {+ // The operator's `inject_budget_chars` is unreachable, so the read+ // lands on INJECT_BUDGET_CHARS_DEFAULT (8,000). Pinned because an+ // unbounded body is the failure this read exists to prevent, and it+ // would be invisible in a small fixture.+ const hugeRules = Array.from(+ { length: 400 },+ (_, i) => `- \`pref-rule-${i}\` (confidence: low (0.10)) β Rule number ${i} body text`,+ ).join("\n");+ writeActive(+ `---\nkind: brain-active\ngenerated_at: 2026-05-15T10:00:00Z\n---\n\n# Active Brain Preferences\n\n## Confirmed (400)\n\n${hugeRules}\n`,+ );+ writeFileSync(configPath(), MALFORMED_CONFIG, "utf8");++ const injected = await inject(NOTICES_ON);+ const noticeBlock = injected.slice(0, injected.indexOf("# Active Brain Preferences"));+ expect(injected.length - noticeBlock.length).toBeLessThanOrEqual(8300);+ });++ test("opting out of the notice channel is the one path that hides the breakage", async () => {+ // `OPEN_SECOND_BRAIN_RUNTIME_NOTICES=false` suppresses the whole+ // channel by the operator's own instruction. Pinned so the budget+ // read's silence is understood as delegated to that channel rather+ // than as its own decision - if this ever stops being the only quiet+ // path, the delegation has broken.+ writeActive(ACTIVE_DOC);+ writeFileSync(configPath(), MALFORMED_CONFIG, "utf8");++ const injected = await inject({ OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "false" });+ expect(injected).toContain("pref-foo");+ expect(injected).not.toContain(CONFIG_NOTICE);+ });+});diff --git a/tests/mcp/config-read-failure-server.test.ts b/tests/mcp/config-read-failure-server.test.tsnew file mode 100644index 00000000..5b998f88--- /dev/null+++ b/tests/mcp/config-read-failure-server.test.ts@@ -0,0 +1,181 @@+/**+ * The plugin config is present and unreadable, and the caller comes in+ * through the SERVER rather than the tool table.+ *+ * `tests/mcp/config-read-failure-tools.test.ts` pinned what the two+ * diagnostic handlers say about that condition, and said in a comment why+ * it could not go through `MCPServer`: the request path resolved the agent+ * identity from the same config before any handler ran, so every one of+ * those payloads was thrown away and replaced by an error envelope. A fix+ * only the tool table can observe is not a fix.+ *+ * The separation asserted here is between operations that NEED the+ * resolved identity and operations that do not:+ *+ * - the read-only diagnostics answer, with the broken file named in the+ * fields that exist to name it;+ * - a writer refuses, by name, before it writes - recording under a+ * guessed identity is worse than not recording;+ * - `initialize` completes without claiming an identity it could not+ * resolve, because a handshake that fails takes every tool above with+ * it, including the two whose job is to diagnose this.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, readdirSync, 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";++const VALID_CONFIG = `vault: "/srv/example-vault"\nagent_name: "vps-agent"\n`;++let tmp: string;+let vault: string;+let configPath: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-server-config-read-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, VALID_CONFIG, "utf8");+ for (const k of [+ "VAULT_DIR",+ "VAULT_AGENT_NAME",+ "OPEN_SECOND_BRAIN_CONFIG",+ "OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS",+ "OPEN_SECOND_BRAIN_MCP_ROUTE_METRICS_ENABLED",+ ]) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+});++afterEach(() => {+ chmodSync(configPath, 0o600);+ rmSync(tmp, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++interface CallOutcome {+ readonly payload?: Record<string, unknown>;+ readonly toolError?: string;+ readonly rpcError?: string;+}++/** Run `fn` with the config file present but unopenable. */+function withUnreadableConfig<T>(fn: () => T): T {+ chmodSync(configPath, 0o000);+ try {+ return fn();+ } finally {+ chmodSync(configPath, 0o600);+ }+}++async function callThroughServer(+ name: string,+ args: Record<string, unknown> = {},+): Promise<CallOutcome> {+ return await withUnreadableConfig(async () => {+ const server = new MCPServer({ vault, configPath });+ const response = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "tools/call",+ params: { name, arguments: args },+ })) as {+ result?: { content: ReadonlyArray<{ text: string }>; isError?: boolean };+ error?: { message: string };+ };+ if (response.error) return { rpcError: response.error.message };+ const text = response.result!.content[0]!.text;+ if (response.result!.isError) return { toolError: text };+ return { payload: JSON.parse(text) as Record<string, unknown> };+ });+}++function inboxSignalCount(): number {+ return readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.startsWith("sig-")).length;+}++describe("the server survives a config it cannot read", () => {+ test("construction does not raise on the route-metrics gate", () => {+ withUnreadableConfig(() => {+ expect(() => new MCPServer({ vault, configPath })).not.toThrow();+ });+ });++ test("initialize completes without naming an identity it could not resolve", async () => {+ const response = await withUnreadableConfig(async () => {+ const server = new MCPServer({ vault, configPath });+ return (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "config-read-failure-server-test", version: "0" },+ },+ })) as { result?: { instructions: string }; error?: { message: string } };+ });+ expect(response.error).toBeUndefined();+ const instructions = response.result!.instructions;+ expect(instructions).toContain(configPath);+ // Never the built-in default, and never the name the unreadable file+ // happens to hold: an identity that could not be read is not an+ // identity, and stating one invites the agent to log under it.+ expect(instructions).not.toContain("You are @agent");+ expect(instructions).not.toContain("@vps-agent");+ });+});++describe("the read-only diagnostics answer through the request path", () => {+ test("vault_health returns the report naming the broken file", async () => {+ const { payload, toolError, rpcError } = await callThroughServer("vault_health");+ expect(rpcError).toBeUndefined();+ expect(toolError).toBeUndefined();+ const checks = payload!["checks"] as Array<Record<string, unknown>>;+ const configCheck = checks.find((c) => c["name"] === "config_writeable");+ expect(configCheck).toBeDefined();+ expect(configCheck!["ok"]).toBe(false);+ expect(String(configCheck!["message"])).toContain(configPath);+ expect(payload!["ok"]).toBe(false);+ // The same degraded field the handler-level test pins, now actually+ // reachable: an unresolvable store reference reports the reason and+ // never falls back to the raw host path.+ expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toContain(+ configPath,+ );+ expect(JSON.stringify(payload!["vault_path"])).not.toContain(vault);+ });++ test("second_brain_status reports the condition instead of collapsing to absent", async () => {+ const { payload, toolError, rpcError } = await callThroughServer("second_brain_status");+ expect(rpcError).toBeUndefined();+ expect(toolError).toBeUndefined();+ expect(payload!["config_path"]).toBe(configPath);+ expect(payload!["config_exists"]).toBe(true);+ expect(String((payload!["config"] as Record<string, unknown>)["error"])).toContain(configPath);+ });+});++describe("a write tool refuses by name", () => {+ test("brain_feedback errors with the config named and records nothing", async () => {+ const { toolError, payload } = await callThroughServer("brain_feedback", {+ topic: "unreadable-plugin-config",+ signal: "positive",+ principle: "This must not be recorded under a guessed identity.",+ });+ expect(payload).toBeUndefined();+ expect(toolError).toBeDefined();+ expect(toolError!).toContain(configPath);+ expect(inboxSignalCount()).toBe(0);+ });+});diff --git a/tests/mcp/config-read-failure-tools.test.ts b/tests/mcp/config-read-failure-tools.test.tsnew file mode 100644index 00000000..cf21e040--- /dev/null+++ b/tests/mcp/config-read-failure-tools.test.ts@@ -0,0 +1,124 @@+/**+ * The two diagnostic tool surfaces, on a plugin config that is present but+ * unreadable.+ *+ * Both tools exist to answer "what does this install see". Raising instead+ * of answering destroys the payload that names the condition:+ *+ * - `vault_health` computes the whole report - `config_writeable` FAILs+ * with a fix line, which IS the diagnosis - and then raised on the last+ * field, `vault_path`, because the opaque store reference is keyed by a+ * secret that lives in the config;+ * - `second_brain_status` raised before producing `config_path`,+ * `config_exists`, `config_keys` and `config`, which are precisely the+ * fields whose purpose is to answer the question.+ *+ * The fix must not be a silent omission. An unresolvable field carries the+ * `{ error: "..." }` shape this payload already uses for the `vault` block+ * when the vault scope cannot be resolved, so the failure is a value a+ * consumer reads rather than a key it has to notice is missing.+ */++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 { buildToolTable, findTool } from "../../src/mcp/tools.ts";+import type { ServerContext } from "../../src/mcp/tool-contract.ts";++const VALID_CONFIG = `vault: "/srv/example-vault"\napi_key: "secret"\n`;++let tmp: string;+let vault: string;+let configPath: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-config-read-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, VALID_CONFIG, "utf8");+ for (const k of [+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ "OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS",+ ]) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+});++afterEach(() => {+ chmodSync(configPath, 0o600);+ rmSync(tmp, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++/**+ * Invoke the tool handler with the config unreadable.+ *+ * Deliberately the handler and not `MCPServer.handleRequest`, so this file+ * pins what the two payloads SAY without also depending on how the request+ * path reaches them. That path is covered next door, in+ * `config-read-failure-server.test.ts`: the server used to resolve the+ * agent name eagerly and raise on the same broken config before any+ * handler ran, which made both payloads unobservable through `tools/call`.+ */+async function callTool(name: string): Promise<Record<string, unknown>> {+ const ctx: ServerContext = { vault, configPath, repoRoot: null };+ const tool = findTool(buildToolTable(), name);+ chmodSync(configPath, 0o000);+ try {+ return (await tool.handler(ctx, {})) as Record<string, unknown>;+ } finally {+ chmodSync(configPath, 0o600);+ }+}++describe("vault_health reports the broken config instead of throwing on it", () => {+ test("the report still names the failing check and its fix", async () => {+ const payload = await callTool("vault_health");+ const checks = payload["checks"] as Array<Record<string, unknown>>;+ const configCheck = checks.find((c) => c["name"] === "config_writeable");+ expect(configCheck).toBeDefined();+ expect(configCheck!["ok"]).toBe(false);+ expect(String(configCheck!["message"])).toContain(configPath);+ expect(payload["ok"]).toBe(false);+ });++ test("vault_path carries the error rather than omitting itself", async () => {+ const payload = await callTool("vault_health");+ expect(payload).toHaveProperty("vault_path");+ const vaultPath = payload["vault_path"] as Record<string, unknown>;+ expect(String(vaultPath["error"])).toContain(configPath);+ // The redaction contract holds even in the degraded shape: an+ // unresolvable reference must not fall back to the raw host path.+ expect(JSON.stringify(payload["vault_path"])).not.toContain(vault);+ });+});++describe("second_brain_status reports the broken config instead of throwing on it", () => {+ test("the config fields answer the question they exist to answer", async () => {+ const payload = await callTool("second_brain_status");+ expect(payload["config_path"]).toBe(configPath);+ // Present, not absent: `false` here is the collapse the read split+ // removed, and it would read as "this install was never configured".+ expect(payload["config_exists"]).toBe(true);+ expect(String((payload["config"] as Record<string, unknown>)["error"])).toContain(configPath);+ expect(String((payload["config_keys"] as Record<string, unknown>)["error"])).toContain(+ configPath,+ );+ });++ test("the rest of the payload still arrives", async () => {+ const payload = await callTool("second_brain_status");+ expect(payload["vault_exists"]).toBe(true);+ expect(payload).toHaveProperty("brain");+ expect(payload).toHaveProperty("vault_path");+ });+});diff --git a/tests/mcp/config-unreadable-tools.test.ts b/tests/mcp/config-unreadable-tools.test.tsnew file mode 100644index 00000000..444adf94--- /dev/null+++ b/tests/mcp/config-unreadable-tools.test.ts@@ -0,0 +1,153 @@+/**+ * How a broken `Brain/_brain.yaml` reaches an MCP caller.+ *+ * The absent-versus-broken config split (96b14d72) made five readers+ * raise on a config that is present and unreadable. Two MCP surfaces sit+ * directly on those readers and answer the same condition differently on+ * purpose:+ *+ * - `brain_feedback` REFUSES. The raise lands before the durable write,+ * because a signal recorded under a silently wrong scope is a record+ * no later fix reaches.+ * - `brain_pre_compress_pack` DELIVERS, with the breakage named. It is+ * read-only and it runs at compaction, where a refusal costs the+ * agent every memory it was about to lose anyway.+ *+ * Both are asserted here so the asymmetry is deliberate and visible+ * rather than an accident of which call site had a guard.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { brainConfigPath } from "../../src/core/brain/paths.ts";+import { brainConfigUnreadableReport } from "../../src/core/brain/policy.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";++/** Parses as YAML, fails validation, in a block neither tool reads. */+const BROKEN_CONFIG = `schema_version: 1\ndream:\n candidate_threshold: 0\n`;++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-broken-config-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });+ mkdirSync(join(vault, "Brain", "inbox"), { recursive: true });+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-broken-config-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;+ }+});++function breakConfig(): void {+ writeFileSync(brainConfigPath(vault), BROKEN_CONFIG, "utf8");+}++function inboxSignalCount(): number {+ return readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.startsWith("sig-")).length;+}++async function callTool(+ name: string,+ args: Record<string, unknown>,+): Promise<{ result?: Record<string, unknown>; error?: string }> {+ const server = new MCPServer({ vault, configPath });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "broken-config-test", version: "0" },+ },+ });+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/call",+ params: { name, arguments: args },+ })) as {+ result?: { content: ReadonlyArray<{ type: string; text: string }>; isError?: boolean };+ error?: { message: string };+ };+ if (r.error) return { error: r.error.message };+ const text = r.result!.content[0]!.text;+ if (r.result!.isError) return { error: text };+ return { result: JSON.parse(text) as Record<string, unknown> };+}++describe("brain_feedback refuses before the write", () => {+ test("an absent config records the signal, scope-less", async () => {+ const { result, error } = await callTool("brain_feedback", {+ topic: "cold-start",+ signal: "positive",+ principle: "Record the signal on a vault with no config.",+ });+ expect(error).toBeUndefined();+ expect(result?.["id"]).toBeDefined();+ expect(inboxSignalCount()).toBe(1);+ });++ test("an unreadable config errors by name and writes no signal", async () => {+ breakConfig();+ const { error } = await callTool("brain_feedback", {+ topic: "broken-config",+ signal: "positive",+ principle: "This must not be recorded under a guessed scope.",+ });+ expect(error).toBeDefined();+ expect(error!).toContain(brainConfigPath(vault));+ expect(inboxSignalCount()).toBe(0);+ });+});++describe("brain_pre_compress_pack delivers with the breakage named", () => {+ test("an absent config yields a pack and no warnings key", async () => {+ const { result, error } = await callTool("brain_pre_compress_pack", { top_k: 5 });+ expect(error).toBeUndefined();+ expect(result).toBeDefined();+ expect(result!["warnings"]).toBeUndefined();+ });++ test("a scoped call on an unreadable config still returns a pack", async () => {+ breakConfig();+ const { result, error } = await callTool("brain_pre_compress_pack", {+ top_k: 5,+ agent_scope: "agent-a",+ });+ expect(error).toBeUndefined();+ expect(result?.["total_chars"]).toBeDefined();+ });++ test("the pack payload names the config the operator has to fix", async () => {+ breakConfig();+ const { result } = await callTool("brain_pre_compress_pack", {+ top_k: 5,+ agent_scope: "agent-a",+ });+ expect(result!["warnings"]).toEqual([brainConfigUnreadableReport(vault)!]);+ expect(result!["active_head_included"]).toBe(false);+ });+});diff --git a/tests/mcp/status-vault-unreachable.test.ts b/tests/mcp/status-vault-unreachable.test.tsnew file mode 100644index 00000000..41451696--- /dev/null+++ b/tests/mcp/status-vault-unreachable.test.ts@@ -0,0 +1,153 @@+/**+ * `second_brain_status` on a vault directory it cannot examine.+ *+ * The last instance of the conflation this wave has been closing. The+ * probe behind `vault_exists` answered `false` for a vault that is not+ * there AND for one behind a directory without the execute bit, so the+ * most misleading sentence this tool can produce - "this install has no+ * vault" - was what an operator got for a permission fault. Three blocks+ * hang off that answer (`brain`, `search`, `vault`), and each was SKIPPED+ * on the false branch, so the payload also said the Brain layer is not+ * there, search is off, and no exclusion policy applies - four unknowns+ * rendered as four confident negatives.+ *+ * The field degrades the way the config fields do: `{ error }`, never an+ * omission and never a bare `false`. The blocks follow the search-block+ * precedent - built and degraded rather than skipped, since a missing+ * block reads as the very "off" the gate could not determine.+ *+ * The two answerable cases are pinned here too, because a degradation+ * that changes them has traded one breakage for another.+ */++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 } from "../../src/mcp/index.ts";++let tmp: string;+/** Parent whose execute bit is dropped, hiding the vault beneath it. */+let sealed: string;+let sealedVault: string;+let configPath: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-status-unreachable-"));+ sealed = join(tmp, "sealed");+ sealedVault = join(sealed, "vault");+ mkdirSync(join(sealedVault, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `api_key: "secret"\n`, "utf8");+ for (const k of [+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ "OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS",+ ]) {+ savedEnv[k] = process.env[k];+ delete process.env[k];+ }+});++afterEach(() => {+ chmodSync(sealed, 0o700);+ rmSync(tmp, { recursive: true, force: true });+ for (const [k, v] of Object.entries(savedEnv)) {+ if (v === undefined) delete process.env[k];+ else process.env[k] = v;+ }+});++async function status(vault: string): Promise<Record<string, unknown>> {+ const server = new MCPServer({ vault, configPath });+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "tools/call",+ params: { name: "second_brain_status", arguments: {} },+ })) as { result?: { structuredContent: Record<string, unknown>; isError?: boolean } };+ return r.result!.structuredContent;+}++async function queryError(vault: string): Promise<string> {+ const server = new MCPServer({ vault, configPath });+ const r = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "tools/call",+ params: { name: "second_brain_query", arguments: {} },+ })) as {+ result?: { content: ReadonlyArray<{ text: string }>; isError?: boolean };+ error?: { message: string };+ };+ if (r.error) return r.error.message;+ return r.result!.content[0]!.text;+}++describe("the two answerable cases keep their exact answers", () => {+ test("a readable vault still reports the literal boolean true", async () => {+ const vault = join(tmp, "plain-vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ const payload = await status(vault);+ expect(payload["vault_exists"]).toBe(true);+ expect(typeof payload["vault_exists"]).toBe("boolean");+ // The blocks the answer gates stay exactly as they were.+ expect(payload).toHaveProperty("brain");+ expect(payload).toHaveProperty("vault");+ });++ test("a genuinely absent vault still reports the literal boolean false and omits the blocks", async () => {+ const payload = await status(join(tmp, "never-created"));+ expect(payload["vault_exists"]).toBe(false);+ expect(typeof payload["vault_exists"]).toBe("boolean");+ expect(payload["brain"]).toBeUndefined();+ expect(payload["search"]).toBeUndefined();+ expect(payload["vault"]).toBeUndefined();+ });+});++describe("a vault that cannot be examined is not a vault that is absent", () => {+ test("vault_exists carries the reason instead of collapsing to false", async () => {+ chmodSync(sealed, 0o000);+ const payload = await status(sealedVault);+ expect(payload["vault_exists"]).not.toBe(false);+ const field = payload["vault_exists"] as Record<string, unknown>;+ expect(typeof field["error"]).toBe("string");+ expect(String(field["error"])).toContain(sealedVault);+ });++ test("the three gated blocks are built and degraded, never skipped", async () => {+ chmodSync(sealed, 0o000);+ const payload = await status(sealedVault);+ for (const key of ["brain", "search", "vault"]) {+ expect(payload).toHaveProperty(key);+ const block = payload[key] as Record<string, unknown>;+ expect(typeof block["error"]).toBe("string");+ expect(String(block["error"])).toContain(sealedVault);+ }+ });++ test("the config blocks still answer, since the config is fine", async () => {+ chmodSync(sealed, 0o000);+ const payload = await status(sealedVault);+ expect(payload["config_path"]).toBe(configPath);+ expect(payload["config_exists"]).toBe(true);+ expect(payload["config_keys"]).toEqual(["api_key"]);+ });+});++describe("second_brain_query separates the same two conditions", () => {+ test("an absent vault keeps its existing refusal", async () => {+ const message = await queryError(join(tmp, "never-created"));+ expect(message).toContain("vault directory missing");+ });++ test("an unexaminable vault is refused as unexaminable, not as missing", async () => {+ chmodSync(sealed, 0o000);+ const message = await queryError(sealedVault);+ expect(message).not.toContain("vault directory missing");+ expect(message).toContain(sealedVault);+ });+});