Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat: nothing runs unwatched (v1.48.0) (#165)
Sol Aitken280469d217bb
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 98b916bc..78537db4 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.47.0",+ "version": "1.48.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 3c2b57ac..e4c539ef 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.47.0",+ "version": "1.48.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 6706ace2..79bd756f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,77 @@ 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.48.0] - 2026-08-15++Nine units picked by priority off the tracker, and reconnaissance against the real source before any of them was designed. That pass corrected six of the nine task bodies rather than following them, because they describe a different system: one with a resident daemon, a chat-model client of its own, and an ingest that locks too often. This one has none of those. What it does have is long, resource-hungry work that reports nothing while it runs, and surfaces that print claims nobody checked.++The two are the same defect from two sides. `o2b brain dream` produced its first observable character after it had already finished, so a caller could not tell a slow pass from a hung one. A cancellation contract - `signal`, `SafeguardAbortError`, abort checked in priority over the deadline - was fully written and passed by no production call site, which made that error class dead code. A herd of detached reindexes was spawned from startup with `stderr: "ignore"`, so every loser of the writer-lock race threw `INDEX_LOCKED` into a discarded stream. And the install success path was asked to state that every memory is a file in the operator's own vault - a claim with a known counterexample, a machine-local secret keying the vault identity every tool returns, and a vault-resolution chain that disagreed with the rest of the CLI about which directory it was talking about.++Then five reviewers were given the finished branch with no knowledge of how it was built, told that a comment is a claim rather than evidence and that a test which cannot fail proves nothing. Two of them were asked to break the production code in a scratch copy and report whether the test caught it; one ran thirty-seven such mutations, of which ten went green. They returned forty-four reproduced findings, and the release's own argument caught it six times.++Three of the six are worth naming, because each is the release doing precisely what it accuses the codebase of. Three of the five long operations emitted progress and then simply stopped arriving - which is the shape of a completed run, a crashed run and a hung run at once. `docs/mcp.md` stated that four long tools ran under a cooperative deadline; four of the six call paths reaching a consolidation pass had none, and a synchronous pass with no deadline holds the MCP event loop for its whole duration. And the census that the previous release's entire argument rests on - declaration plus a census is what makes a fix durable - turned out to read no source at all: it is a hand-maintained import list, and a reviewer added a vocabulary carrying three of the exact defects it audits for and got 63 pass, 0 fail.++Three findings were resolved the opposite way to the obvious one, and in each case a measurement decided it rather than an argument. Ctrl-C cannot stop a synchronous pass: 27.3 million checkpoints ran with the signal pending and the handler never fired. The obvious fix - make the pass async and await at checkpoints - does not work either, and would hide the bug: 4.8 million awaits with a signal pending, still nothing, because microtasks drain without yielding to the event loop. Only a macrotask yield works, at 184 thousand per second against 13.7 million synchronous checkpoints per second, across 137 call sites where any plain `await` silently recreates the same false claim. So the four synchronous verbs install no signal handler at all, Ctrl-C keeps killing them as it always did, and nothing claims otherwise. The retrying ingest lock was going to have its budget cut, until the wait was measured: the tail is queueing, not hold length, and a shorter budget made this branch's own designed-contention test fail intermittently. And the over-release guard a reviewer proposed for the shared semaphore cannot see the case that matters, because with a waiter queued the pool count is zero and a stray release passes the check and is handed straight to that waiter.++### Added++- **A long pass says what it is doing while it does it.** A synchronous progress sink, optional on the same options interface that already carries the operation's deadline, emitted from the checkpoints that already existed. `total` is optional and its absence means something: the index walk consumes a generator, so counting first would cost a second full traversal, while the embedding phase holds an array and knows its denominator exactly. One event shape carries both, and a renderer that sees no total shows a counter rather than inventing a percentage. `--progress` on `o2b brain dream`, `bridges discover`, `clusters run`, `maintenance run`, `architect`, `search index`, `search reindex` and `search vector-backfill`, as newline-delimited records on stderr - never stdout, which twelve top-level commands own as a payload a caller parses.+- **Progress over MCP, where the transport can carry it.** The stdio transport emits `notifications/progress` against the client's token. The HTTP transport writes one response and closes, so a token supplied there receives a typed refusal naming the transport rather than events that never arrive. A call with no token is byte-identical to before.+- **Ctrl-C reaches the passes that can observe it, and nothing pretends about the rest.** `o2b search index`, `search reindex`, `search vector-backfill` and `brain maintenance run` stop at a checkpoint and exit 130. The four fully synchronous passes install no handler, because a synchronous function never yields the event loop and a handler that cannot run is worse than none - it swallows the keystroke that used to work.+- **A fourth gate on the maintenance lane, which can say it cannot see.** Host pressure joins the window, busy and lease gates. Where the metric is degenerate - Windows, or a CPU quota in force - the gate does not evaluate and says so on its own journal line, distinct from the line a gate that evaluated and let the work through writes.+- **A consecutive-failure streak, and a narrow way past it.** A task that has failed three times running is refused rather than spending the lane's lease every pass; `--retry <task>` attempts that one task with every other gate still in force, where `--force` disables them all.+- **The install says only what it checked.** The ownership statement measures the vault, what filesystem backs it, whether the search index is inside it, and each of four outbound integrations. What it cannot measure - ten kinds of state the tool can leave outside the vault - is worded as a catalogue rather than a scan, and every row names the verb that created it and the verb that removes it.+- **A doctor check for a model with an announced decommission date**, and one for the age of the newest recovery point. The sunset survey ships sixteen sourced entries from one published deprecation page and an operator can declare a date the shipped table cannot know; a model outside the survey is reported as unsurveyed, which is a different statement from no shutdown announced.+- **A switch for the codegraph partner check** (`partner_codegraph_disabled`), which `doctor()` accepted and nothing could set.++### Changed++- **`embedding_concurrency` bounds requests in flight process-wide**, per embedding identity against one endpoint, rather than per `embed()` call. Two models on one host are two budgets, so that host sees up to `embedding_concurrency` times the number of identities at once.+- **The project scanner walks once, and stops walking what the repository ignores.** Measured on this repository: 24148 files visited became 2729, and 530.6 ms became 57.5 ms. The `.gitignore` question was settled by measurement - a dot-directory rule removes 88% of the files, and full `.gitignore` support adds 207 more, every one of them already inside a dot directory.+- **The ingest path takes the lock it never took.** Three shared read-modify-writes were unlocked; a four-process race behind a wall-clock barrier loses 74 of 100 entries without them.+- **A language tie-break in the scanner no longer depends on the host locale**, in a module whose whole contract is deterministic regeneration.+- **The prose recognizer on the write path carries no word list**, which its sibling module's rule had forbidden all along.++### Breaking++- **`o2b install` resolves the vault through the same chain as every other verb.** It previously used `--vault`, then the config `vault` key, then `VAULT_DIR`. It now uses `--vault`, then `VAULT_DIR`, then a project pointer, then the active profile, then the config key, and it expands a leading tilde where it previously passed one through literally. Where the answer changes, the new one is what `o2b status` and `o2b brain doctor` were already using - the old behaviour let the installer write one vault into an agent's config while the rest of the CLI read another, with nothing reporting the split.+- **`o2b doctor --readiness` exits 6 for a probe that did not complete**, where it exited 1. A timed-out probe was reported as a failure, so on a loaded machine the doctor declared a healthy system broken. Code 6 is the number `o2b search check` already spends on the same condition, and a test asserts the two cannot drift.+- **`o2b brain maintenance run` exits 7 when a task is refused for a failure streak.** Not 1, which would report a failure this run did not have; not 0, which would tell a nightly cron that a lane that has stopped doing heavy work is healthy.+- **Two new `_brain.yaml` blocks**, `maintenance:` and `embeddings:`, both absent by default and templated commented. A vault that declares only one of `embeddings.sunset_model` / `sunset_at` fails to load rather than ignoring the half it got.+- **Two new doctor warnings and three new uncertain codes.** Under `--strict`, a vault that previously exited 0 can now exit 2.+- **The hook self-ceiling default falls from 55 s to 8 s**, derived from the 10-second host timeout every hook entry declares. The old default could never fire, because the host killed the process first.+- **`brain_token_impact` no longer reports `method: "exact"`.** It counts nothing - it subtracts integers a caller supplied - so the vocabulary now names provenance (`tokenizer` / `heuristic`) rather than an accuracy nobody verified.+- **The bench report is schema v2**: `context_cost.est_tokens` changed meaning, not only name.+- **`o2b brain doctor` reports the codegraph check as deliberately not consulted** when it is switched off, where it previously omitted the row. Omission made a setting that had just taken effect indistinguishable from one that had done nothing.+- **`listSnapshots` returns a listing rather than an array.** A per-entry read failure was dropped with a bare `continue`, so a recovery-point history whose archives could not be stat'ed read as a history that never existed. The skipped entries are now returned beside the snapshots, `o2b brain snapshot log --json` gains `skipped`, and `pruneSnapshots`'s `retained` no longer claims "still on disk" about entries it could not see.+- **`o2b search vector-backfill` now runs under a deadline.** It declared `safeguard`, `signal` and `onProgress` and had a producer for none of them; wiring two of the three would have left the third declared and unreachable. The budget is the `reindex` key off the same ladder `o2b search index` reads, because this pass is that run's embedding phase alone.+- **`EMBEDDING_SUNSET_UNDETERMINED_REASON` loses `declaration_malformed`.** Nothing could produce it: the config parser validates the declared instant with the same predicate and refuses the vault before any check runs, so the member described a state that could not exist.++### Fixed++- **Three long operations emitted progress and never terminated the stream.** The rule is written once now, because five copies of one rule are five chances to forget it - which is what happened.+- **The first Ctrl-C was swallowed and the verb exited 0.** Registering a handler suppresses default termination, so a signal landing outside a checkpointed region was absorbed and the command reported success for a pass the operator stopped.+- **`o2b search vector-backfill` grew the entire progress spine and no way to reach it.** An options field, a counter and a terminator in core, with no `--progress` flag, no caller passing a sink, no signal and no deadline - every line of it unreachable from any surface an operator has, which is the exact defect this release is about. Found by the new execution census, which drives each entry point for real; the source census could not see it, because a declared sink is not a passed one.+- **A shared semaphore could be released by code holding nothing**, admitting four concurrent holders against a ceiling of two while its own high-water counter still reported two. `release()` is gone; `acquire()` returns a one-shot permit, and a second call on it throws.+- **A retrying lock spun forever on a `NaN` budget** and froze the event loop for the whole of a valid one.+- **The doctor could not see two of the three ingest locks**, because the stale-lock scan walked only one of the two roots locks live under.+- **A recovery-point check reported a vault whose archives could not be read as a vault that never had any.**+- **The host-pressure probe read the root cgroup rather than the one governing the process**, so a CPU quota in force yielded a confident percentage computed from the host's run queue.+- **`brain_dream`, its staged actions, `brain_brief view=operator` and `brain_review_candidates` ran without a deadline** while the documentation said otherwise.+- **The self-heal rows paired on a process id** in a file that syncs between devices and whose own docblock forbids machine-local values in a row.+- **`Bun.which` and `Bun.spawnSync` resolved against the PATH the process started with**, so a long-lived server would answer with a stale binary's result.+- **The test suite's verdict was a function of the machine it ran on, for the third release running.** `doctor()` consults the codegraph partner whenever that binary is on PATH, and the partner's cache lives under HOME - which this suite pins to a clean directory. `tests/cli/cli.test.ts` went from 96.03 s to 1.09 s with the partner switched off, same tests green. CI never saw it, because the binary is absent there.++### Notes++Two censuses were rewritten because reviewers evaded them. The progress census went from five regular expressions to a lexer and three parsers: fourteen evasions now fail it, each with a permanent positive control, including one where a brace inside a generic constraint did not merely miss an interface but silently parsed the wrong one. Four limits it still has are written into its docblock rather than left implied. The verdict-vocabulary census now reads the tree instead of a hand-kept import list. And a new execution census runs each entry point for real and asserts records arrive, which no syntactic bypass can defeat.++`README.md` recorded, one release ago, a decision this release reverses: there was to be no registry of embedding-provider shutdown dates, because a hand-maintained table over an open set of endpoints would rot in place and be believed. The objection was right, and the design that ships answers both halves of it. A surveyed negative expires and degrades to undetermined; a positive carries the date it was reviewed; a model the survey does not know is reported as unsurveyed rather than as having no announced shutdown; and an operator who has read a vendor's announcement can declare it without waiting for a release. The reversal is stated rather than quietly performed.++Some of what was asked for is not here. There is no daemon, no scheduler and no supervisor, so the startup grace period and crash-loop recovery two task bodies asked for have no subject; the portable analogue is a gate evaluated at the top of a one-shot command with its state on disk. There is no cap on model inference, because this process makes no chat-model call - it hands model work back to the caller as typed envelopes - and naming a ceiling "inference" would be a hardcoded falsehood about what the code does. There is no concurrency in the project scanner, because rendering and writing are 7.9 ms of a 396 ms run. There is no whole-ingest writer lease, because the batch-planning surface exists so a caller can dispatch each batch as a parallel subagent and the sync lock has no retry by design.++Three things are stated rather than fixed. The confidence floor the new bench leans on cannot fire through the shipped retrieval path: min-max normalisation pins the first result at the keyword weight regardless of match quality, so the abstain that actually fires is "no matches". The reindex herd's thinning is exactly zero in the scenario it was built for - four parents probing inside the 0.71-0.75 s window all spawn - and helps only a caller arriving later. And `brain_dream step` still runs without a deadline, because bounding it means threading a guard into two functions that do not accept one; the documentation now says so on its own row instead of implying otherwise.+## [1.47.0] - 2026-08-15Nine units picked by priority off the tracker, and reconnaissance against the real source before any of them was designed. That pass found they were not nine problems. In every one the capability already existed in this codebase - exported, tested, used elsewhere - and the defect was that the site needing it did not call it.@@ -7052,6 +7123,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.48.0]: https://github.com/itechmeat/open-second-brain/compare/v1.47.0...v1.48.0[1.47.0]: https://github.com/itechmeat/open-second-brain/compare/v1.46.0...v1.47.0[1.46.0]: https://github.com/itechmeat/open-second-brain/compare/v1.45.1...v1.46.0[1.45.1]: https://github.com/itechmeat/open-second-brain/compare/v1.45.0...v1.45.1diff --git a/README.md b/README.mdindex 2089066e..f93d9bf0 100644--- a/README.md+++ b/README.md@@ -8,11 +8,23 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm## What is new-Open Second Brain 1.46.0 is about claims the code could not back up. Nine units, four of them reported on the public tracker, and what they have in common is not a subsystem: in every one, the information needed to tell two cases apart either existed already and was thrown away, or cost one filesystem call nobody made. A search that returned nothing could not tell you whether the corpus was empty or the embedder was down, though fifteen degradation signals were being computed and then flattened into prose or dropped. Entity intake decided whether to trust a source from the shape of a string, never asking whether a file was behind it - and the caller supplying that string is the same agent that read the material being classified. Two concurrent writers racing for the same filename lost one of the records outright, measured at twelve dropped events out of twenty-four. The Hermes plugin and the core resolved different vaults while a docstring claimed they were identical, which is why a setup that worked showed as unconfigured for five weeks with nobody able to say why.+Open Second Brain 1.48.0 is about work you can watch, bound and stop, and about claims that were checked before they were printed. Nine units picked by priority off the tracker, and reconnaissance against the real source before any of them was designed - a pass that corrected six of the nine task bodies rather than following them, because they describe a system with a resident daemon, a chat-model client of its own, and an ingest that locks too often. This one has none of those.++What it had instead was long work that reported nothing. `o2b brain dream` produced its first observable character after it had already finished, so a caller could not tell a slow pass from a hung one. A cancellation contract was fully written and passed by no production call site, which made its error class dead code. A herd of detached reindexes was spawned at startup with their standard error discarded, so every loser of the lock race died where nobody could see it. Now the long passes emit newline-delimited progress on standard error under `--progress`, over stdio to an MCP client that asks for it, and the passes that can observe an interrupt stop at a checkpoint and exit on the shell's own signal convention. The ones that cannot observe one install no handler and say so, because a synchronous function never yields the event loop and a handler that cannot run is worse than none - it swallows the keystroke that used to work.++The other half is what the tool says about itself. A successful install now states where your brain is, what filesystem backs it, whether the search index is inside that vault, and which outbound services are configured - each measured at the moment it is printed. What cannot be measured is worded as a catalogue rather than a scan, and every row names the verb that created that state and the verb that removes it. The project scanner walks once and stops entering what the repository ignores: 24148 files visited became 2729, and 530.6 ms became 57.5 ms, measured on this repository.++Then five reviewers were given the finished branch with no knowledge of how it was built, told that a comment is a claim rather than evidence and that a test which cannot fail proves nothing. They returned forty-four reproduced findings, and one of them ran thirty-seven mutations of the production code of which ten went green. The release's own argument caught it six times - three long operations that emitted progress and then simply stopped arriving, a documented deadline four call paths did not have, and, worst, the census the previous release's entire argument rests on turning out to read no source at all. Three findings were then resolved the opposite way to the obvious one, each because a measurement decided it: making a pass async does not deliver a signal either, a shorter lock budget made this branch's own contention test fail, and the proposed semaphore guard cannot see the case that matters. The [CHANGELOG](CHANGELOG.md) has all of it, including what was found and deliberately left open.++One decision is reversed here rather than quietly performed. Release 1.46.0 recorded that there would be no registry of embedding-provider shutdown dates, because a hand-maintained table over an open set of endpoints would rot in place and be believed. The objection was right, and this design answers both halves of it: a surveyed negative expires, a positive carries the date it was reviewed, a model the survey does not know is reported as unsurveyed rather than as having no announced shutdown, and an operator who has read a vendor's announcement can declare it without waiting for a release.++Previous release, 1.47.0, wired what already existed: nine capabilities that were exported, tested and used elsewhere, each with a site that needed them and did not call them - a destructive-operation gate with two call sites against roughly twenty-five destructive operations, and a ranker that read a document's authoring instant nine lines after ranking on the file's modification time.++Previous release, 1.46.0, was about claims the code could not back up. Nine units, four of them reported on the public tracker, and what they have in common is not a subsystem: in every one, the information needed to tell two cases apart either existed already and was thrown away, or cost one filesystem call nobody made. A search that returned nothing could not tell you whether the corpus was empty or the embedder was down, though fifteen degradation signals were being computed and then flattened into prose or dropped. Entity intake decided whether to trust a source from the shape of a string, never asking whether a file was behind it - and the caller supplying that string is the same agent that read the material being classified. Two concurrent writers racing for the same filename lost one of the records outright, measured at twelve dropped events out of twenty-four. The Hermes plugin and the core resolved different vaults while a docstring claimed they were identical, which is why a setup that worked showed as unconfigured for five weeks with nobody able to say why.You can now say what you want indexed instead of listing everything you do not, with `vault.include_paths`; absent, it changes nothing, and that is measured against the previous release rather than asserted. A write tells you what is wrong with the page it just wrote, instead of deferring to a sweep that may never run. Recall telemetry carries which channel delivered, so a hook that was never installed and a hook that ran and stayed quiet stop looking identical. Every advertised tool parameter is documented and CI keeps it that way, and an unknown argument is named back to you with a suggestion rather than silently ignored.-Some of what was asked for is not here, and the absence is a decision. There is no registry of embedding-provider shutdown dates, because the only way to build one is a hand-maintained table over an open set of endpoints that would rot in place and be believed. The schema-completeness guard covers input schemas only, because the output vocabulary declares union-typed fields with no type on purpose and the rule would demand a lie there. And the fix the intake issue asked for - let the host supply the trust verdict instead of the caller - is unbuildable, because no unforgeable caller identity exists in this surface, a conclusion this project had already reached elsewhere and not applied here. What shipped instead removes the free bypass and makes the claim auditable; it does not make the claim true, and the code says so. Four reviewers were then given the finished branch with no knowledge of how it was built, and told that a comment is a claim rather than evidence. They found twelve defects, two of them regressions this work introduced and invisible to its own tests. All are fixed, and the [CHANGELOG](CHANGELOG.md) names them.+Some of what was asked for is not here, and the absence is a decision. There was no registry of embedding-provider shutdown dates, because the only way to build one is a hand-maintained table over an open set of endpoints that would rot in place and be believed - a decision 1.48.0 reverses above, having answered that objection rather than set it aside. The schema-completeness guard covers input schemas only, because the output vocabulary declares union-typed fields with no type on purpose and the rule would demand a lie there. And the fix the intake issue asked for - let the host supply the trust verdict instead of the caller - is unbuildable, because no unforgeable caller identity exists in this surface, a conclusion this project had already reached elsewhere and not applied here. What shipped instead removes the free bypass and makes the claim auditable; it does not make the claim true, and the code says so. Four reviewers were then given the finished branch with no knowledge of how it was built, and told that a comment is a claim rather than evidence. They found twelve defects, two of them regressions this work introduced and invisible to its own tests. All are fixed, and the [CHANGELOG](CHANGELOG.md) names them.Previous release, 1.45.1, fixed a Hermes flush that had been discarded at the boundary since 0.32.0 and a starter vault that went stale ninety days after it was authored. Before it, 1.45.0 was about silence not being an answer, and 1.44.0 about what the index already knew: thirteen units on the retrieval path, most of them values the system computed and discarded before anything could see them. Details for all three live in the [CHANGELOG](CHANGELOG.md).diff --git a/docs/brainstorm/nothing-runs-unwatched/cli-output/claude.md b/docs/brainstorm/nothing-runs-unwatched/cli-output/claude.mdnew file mode 100644index 00000000..16413d32--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/cli-output/claude.md@@ -0,0 +1,38 @@+### Variant 1: The observation spine+- **Approach**: One new closed-vocabulary seam — an operation-lifecycle event (started / advanced / refused / stopped / finished) carrying the existing `SafeguardOperation` id — emitted synchronously from the `checkpoint()` boundaries that already exist, delivered through an optional sink on the same `opts` object that already carries `safeguard`, and modelled on the indexer's proven `onFile?` callback rather than a new abstraction. Core only emits; every edge decides whether it can carry the event (a stderr writer for commands that are not stdout-owning or buffer-patched, a stated non-carrier for the stdio and HTTP MCP transports and for the twelve JSON-owning commands, since `progressToken` cannot be honoured without a notification channel). Durability is a census test that enumerates every `SafeguardOperation` and every long entry point and fails when one runs without either an emitter or a declared reason it cannot carry one.+- **Trade-offs**:+ - Pro: units 1, 3 and 4 are the same seam — the dead `signal?`/`SafeguardAbortError` pair becomes the `stopped` event's producer, and the detached-reindex herd becomes a `refused` event with the losing child's `INDEX_LOCKED` surfaced instead of discarded into an ignored stderr.+ - Pro: exactly matches the mechanical conventions (four-piece vocabulary, census enforcement, layering test satisfied by construction) and adds no daemon, scheduler or network.+ - Pro: the `refused` member gives units 7 and 8 a native home — "cannot classify environment", "cannot name a vendor from a transport kind", "load average is not answerable here" become the same typed refusal rather than three ad-hoc strings.+ - Con: the spine does not itself fix the honesty half of the thesis; units 5, 6, 8 and 9 still need their own edge-local work and only borrow the refusal vocabulary.+ - Con: a sink threaded through every long operation touches many call sites at once, and the "declared non-carrier" list is a place future work can quietly park things.+ - Con: MCP gets no progress at all in this release, which will read as a gap even though it is the honest outcome of having no SDK and a single-response transport.+- **Complexity**: large+- **Risk**: medium++### Variant 2: The claim census+- **Approach**: Take the second half of the thesis as the organising principle: no user-facing assertion may ship unless it is a registered claim with a resolver that checks it, or a registered refusal that names why it cannot be checked. The release adds a frozen id-keyed claim registry plus a census test enumerating the assertion sites across install output, doctor checks, the four install result shapes, environment reporting, provider health and the conformance metrics — and reclassifies each of the nine units as either "claim now backed" or "claim replaced by a named refusal". Progress and cancellation enter as claims too: "this pass is running", "this pass was stopped on purpose", "this reindex lost the lock".+- **Trade-offs**:+ - Pro: it is the sharpest possible answer to "prints claims it never checked" — the install data-ownership line, the environment class, the decommission warning, the exact-token count and the zero-leakage gate are all the same defect and get the same mechanism.+ - Pro: the mechanism generalises past the release; every future claim has to declare, matching the previous release's own stated argument about hand-called mechanisms.+ - Pro: forces the disagreements to the surface early — the install vault-resolution chain, the vault identity keyed by a machine-local secret, the settings that default off — because a claim with no honest resolver cannot be registered.+ - Con: blast radius across 110 MCP tools and every CLI surface is the largest of the three; the census is only as good as its enumeration and mis-scoping it either strangles ordinary output or under-covers.+ - Con: units 1 through 4 fit awkwardly — progress and cancellation are behaviour, not assertion, and framing them as claims is a stretch that will show in the code.+ - Con: high chance the release ships a registry with more refusals than resolvers, which is honest but reads thin.+- **Complexity**: large+- **Risk**: high++### Variant 3: Wire what is dead, refuse what is unanswerable, delete what was wrong+- **Approach**: Ship no new subsystem and no new vocabulary; instead pair each of the nine with the mechanism that already exists and either connect it or state by name that it cannot be connected. Concretely: pass a real signal into the declared `signal?`; share the embedding semaphore per process instead of per call; route the reindex spawn through the maintenance lane's existing pressure signal, TTL lease and typed journal verdicts rather than inventing host-load gating; replace the frozen adapter array with the registry pattern already present under another name; put the decommission check on the doctor that has the injected clock and severity ladder and point the operator at the catalog-listing verb; correct the scanner's walk (dot-directories, `.gitignore`, one traversal, locale-independent tie-break) and drop the concurrency ask that targets 2% of the run; fix the watchdog ceiling to match the declared hook timeout. Durability comes from extending the existing census tests — doctor exit codes, write sites, vocabularies, help parity — rather than adding a new enforcement layer.+- **Trade-offs**:+ - Pro: every fix lands inside an idiom the repo already enforces, which is the strictest reading of "maximally native integration, no crutches".+ - Pro: lowest risk per unit and each unit is independently revertable; the corrected reconnaissance framing is honoured exactly, including the units where the original ask was wrong.+ - Pro: naturally accommodates the honest refusals — no environment classifier, no load average, no exact token count — because refusal by name is already the established answer.+ - Con: no single durable mechanism comes out of it; nine local fixes with nine local guards, and the next long operation added still emits nothing because nothing forces it to.+ - Con: unit 1 degrades to "the indexer callback, copied" — progress for `dream` becomes a bespoke callback rather than a shared contract, which is the parallel-idiom the operator's constraint warns against.+ - Con: the through-line is the weakest of the three and repeats the previous release's thesis almost verbatim, which makes the release hard to state in one line.+- **Complexity**: medium+- **Risk**: low++### Recommended: Variant 1+**Rationale**: The spine is the only option where the largest and most entangled units — the silent `dream`, the dead `SafeguardAbortError`, and the herd of detached reindexes dying into an ignored stderr — collapse into one seam that the codebase has already carved out for it, at the checkpoint boundaries and on the same `opts` object, with a working precedent in the indexer's per-file callback. Its `refused` member gives the honesty units a native home for the answers that must be refusals rather than plausible numbers, so it carries both halves of the thesis without the blast radius of retrofitting a claim registry across 110 tools. Variant 3 is safer per unit but leaves nothing that forces the next long operation to speak, which is precisely the failure the previous release argued against.diff --git a/docs/brainstorm/nothing-runs-unwatched/cli-output/prompt.md b/docs/brainstorm/nothing-runs-unwatched/cli-output/prompt.mdnew file mode 100644index 00000000..a666f3a3--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/cli-output/prompt.md@@ -0,0 +1,68 @@+You are brainstorming architectural variants for the following work. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++Open Second Brain is a TypeScript-on-Bun agent memory system: an MCP server (110 tools, hand-rolled JSON-RPC, no SDK), an `o2b` CLI, and an Obsidian-compatible Markdown vault. One release must ship nine units picked off the tracker. Reconnaissance against the real source has already run and corrected most of the nine task bodies, so the framing below is the CORRECTED one — design against it, not against the original upstream framing.++The unifying thesis under consideration: **the system does long, resource-hungry, state-bearing work and tells nobody, and it prints claims it never checked.**++The nine units, as reconnaissance leaves them:++1. **Progress out of a long pass.** The repo already has a canonical vocabulary of long operations (`SafeguardOperation = "dream" | "reindex" | "bridges" | "clusters" | "maintenance"`) and every `opts.safeguard?.checkpoint()` call sits exactly at the iteration boundary a progress tick belongs at. One operation (the indexer) already emits a per-file event through an optional `onFile?: (event) => void` callback consumed on stderr behind `--verbose`. Nothing else emits anything: `o2b brain dream` prints nothing until it finishes. Hard constraints: the sink must be synchronous (`dream`, `discoverBridges`, `detectCommunities`, `runDoctor` are all synchronous functions); a layering test bans `process.stdout.write` in core, so core emits events and only the edge writes; twelve top-level commands own their own JSON on stdout, and every other command has BOTH stdout and stderr monkey-patched into buffers for the whole run, so a progress line there is swallowed and dumped at the end — worse than nothing. For MCP: there is no SDK, `params._meta.progressToken` is silently discarded, the stdio transport writes only what the request handler returns, and the HTTP transport `res.end`s a single SSE event and closes. Index and reindex are deliberately NOT exposed over MCP at all.++2. **A code-scanner that walks what it must not.** A deterministic project scanner renders facts into vault notes behind sentinel regions. Measured on the repo itself: the scan is 388 ms and rendering plus writing is 7.9 ms — 2% of the run. Of 24094 files visited, 21113 are under one tool directory; the skip list honours no `.gitignore` and no dot-directory rule, and the tree is walked twice. The original task asked for concurrency and per-note retry; concurrency would target the 2%. A separate latent defect: a tie-break uses locale-sensitive string comparison, so output is locale-dependent.++3. **Cancellation that exists and is never wired.** A safeguard module already declares `signal?: AbortSignal`, a `SafeguardAbortError` distinguished from timeout precisely so a shutdown coordinator can treat an intentional stop as clean, and checkpoint logic that checks abort in priority over the deadline. No production call site passes a signal, so that error class is dead code. Separately: the outbound-embedding concurrency semaphore is constructed per `embed()` call rather than shared, so the configured concurrency bounds one call and not the process; and one benchmark fan-out is unbounded and amplified 24× by a tuning grid.++4. **A thundering herd of detached reindexes.** A helper spawns a detached `o2b search reindex` from two startup points: every MCP server start and the SessionStart/PostCompact hook. The child is spawned with `stderr: "ignore"`. The collision is already acknowledged in source; the losing child waits on a writer lock, spins about three seconds and throws `INDEX_LOCKED` into a process whose stderr is discarded. N agent sessions after a schema bump produce N detached reindexes and N−1 silent deaths. The original task asked for host-pressure gating, a startup grace period and crash-loop recovery, framed around a daemon. **There is no daemon** — it is a stated architectural invariant, every entry point is one-shot, and nothing schedules the consolidation pass automatically. A maintenance lane already gates background work on a measured pressure signal (interactive query rate) behind a TTL lease and a journal with typed verdicts. Host load average is unavailable in any honest sense: it is `[0,0,0]` on Windows and reports the host run queue inside a container, and this repo's established answer to an unanswerable platform question is to refuse by name rather than return a plausible number. A related finding: a hook self-watchdog defaults to a 55-second ceiling while all fifteen hook entries declare a 10-second host timeout, so the watchdog the repo already has probably cannot fire.++5. **An ingest that takes no lock at all.** The original task asked to hold the single-writer lease for a whole ingest instead of per write. Reconnaissance found the opposite defect: the manifest update and the completion record are unlocked read-modify-writes of shared files. A whole-ingest lease would also break a batch-planning surface that exists so a caller can dispatch each batch as a parallel subagent, because the sync lock has no retry and no stale window by design. Separately, the adapter list is a frozen hardcoded array, while a registry of exactly the required shape (frozen id-keyed map, config-driven selection, loud unknown-id error) already exists elsewhere in the same codebase under a different name. Two silent-empty defects sit on the same path: transcript resolvers collapse "directory absent", "unreadable" and "genuinely idle" into a count of zero, and a dry-run import reports zero created indistinguishably from a real run that wrote nothing.++6. **An install that prints a claim it never checked.** On success the tool should state data ownership — every memory is a Markdown file in your own vault, copy it elsewhere, delete it and the brain is gone, no service to cancel — and expose it as a machine-readable handoff field. Reconnaissance found the claim is not unconditionally true: one editor plugin spools raw conversation turns outside the vault with no pruning, and a machine-local installation secret keys the vault identity that every tool returns, so copying the vault to another machine silently breaks those references. Also, install has four modes with four result types and four JSON shapes, one with no schema version; no test asserts any of them; and install resolves the vault through its own chain that disagrees with the rest of the CLI on precedence, so the path it prints as "your brain" can name a directory nothing else uses.++7. **Environment class, honestly.** The companion task asks to detect local versus cloud sandbox versus ephemeral container and branch behaviour, plus a durability job check verifying presence AND liveness. Reconnaissance: cgroup v2 has erased the classic container heuristic on this host, every container signal is one-way so a negative proves nothing, "cloud sandbox" cannot be separated from "container", and "container" is not "ephemeral". There is also no job registration anywhere to check the presence of — every scheduled-job surface in the repo is a recipe renderer that writes nothing and installs nothing.++8. **A provider with a death date.** A doctor check should warn when the configured embedding provider or model has an announced decommission date, naming the provider, the date and the migration command. Reconnaissance: the preset catalog has six entries, five of them open-weight checkpoints with no vendor who could announce anything, and the hosted models that actually get decommissioned live in a disjoint pricing table. The model field is a free string with no validation, and the onboarding text itself recommends a model that is not in the catalog and is a preview. The provider field resolves to one of four transport kinds, so it cannot name a vendor; vendor identity exists only inside a free-form base URL that nothing maps. No verb in the tool writes a config key, so "the migration command" cannot be a config edit — the established precedent for that situation points the operator at a catalog-listing verb instead. There are two candidate homes: one doctor has an injected clock and a severity ladder and a hard census requiring every registered code to be pinned in a test, but no check there resolves search config; the other surface owns the provider question and its exit codes but has no clock.++9. **A conformance suite for four memory failure modes.** Proactive know-to-ask paired with an anti-gaming false-fire rate; write-back fidelity through an extractor seam that runs the shipped code with zero model calls; a cross-source-leakage invariant gating at zero; and an average injected-token intrusion budget. Reconnaissance: the "zero model calls" seam is not something to build — the server never calls a model on any write path, by stated architectural contract, so a fixture supplying structured intake IS the shipped architecture. The relevance decision that makes know-to-ask measurable is a pure function with an injectable retriever, but it sits behind a setting that defaults off, while the always-on injection path makes no relevance decision at all and would score degenerately. The surfacing gate fails open by design, so anti-gaming pressure has to land on a confidence floor rather than the gate. There is no exact token count anywhere — five estimators disagree, and the surface that claims exactness subtracts caller-supplied integers. Owner-scope isolation is gated by a setting that also defaults off, so a zero-gate under shipped defaults is vacuous. There are two unrelated bench harnesses sharing nothing, no committed baseline anywhere, and CI runs no bench step at all.++# Project context++TypeScript on Bun. ~2050 source files, 1064 test files, 9816 tests. One runtime dependency. Recent releases, most recent first: wiring what exists; evidence at the boundary; the flush that never landed; silence is not an answer; what the index already knew; provenance at the boundary; module boundaries and the fallbacks behind them.++Conventions the codebase enforces mechanically:++- **Closed-vocabulary four-piece idiom**, mandatory and census-tested: a frozen object with camelCase keys and snake_case values, a derived union type, a members array, and a type guard whose parameter is `unknown`. A separate census test enumerates every registered vocabulary.+- **Census tests as the enforcement mechanism.** Raw filesystem write sites, destructive removal sites, doctor exit codes, MCP tool parity, vault-identity assertions, config-template keys, help-surface parity, and verdict vocabularies each have a test that enumerates the population and fails when a member appears without a declaration. The previous release's whole argument was that a mechanism which must be called by hand is a mechanism that will be missed, and that declaration plus a census is the answer.+- **A six-tier confirmation ladder** for destructive work: no gate, a `dryRun` option, dry-run by default plus `--apply`, `--yes` for non-interactive, an override flag for a proved hazard recorded in a log, and an exact confirmation phrase. Orthogonal to it, a `--expect N` / `--strict` count guard.+- **Byte-identity is measured, never asserted** — a vault-digest helper produces a tree digest so a release can state exactly how many bytes changed.+- **Two config files with different disciplines**: a nested vault config whose bounded-integer reader never clamps and never defaults, because a knob that silently reverted would be indistinguishable from the operator never having set it; and a flat machine config where bad values throw with the key name.+- **A layering test** bans process exit and stdout writes in core.++Constraints from the operator, non-negotiable:++- No fallback that silently does nothing and misleads. If there is an error, show the error explicitly.+- No stubs. No placeholder that reports success it did not achieve.+- SOLID, KISS, DRY. Anything extractable goes into a named constant or local.+- Maximally native integration, no crutches — extend the idioms that exist rather than inventing parallel ones.+- Never hardcode natural-language phrases of any specific language. Everything is English; any handling of other languages must be structural, not a word list.+- The release must not grow a daemon, a scheduler, a background process, or a network dependency it does not already have.++# Required output format++Produce exactly 3 distinct architectural variants for how to shape this release as a whole — the through-line, what carries the nine units, what mechanism makes the fixes durable, and where the boundary of the release sits. Variants must differ in kind, not in degree.++For each variant:++### Variant N: <short name>+- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/nothing-runs-unwatched/design.md b/docs/brainstorm/nothing-runs-unwatched/design.mdnew file mode 100644index 00000000..6e5b9a50--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/design.md@@ -0,0 +1,242 @@+# Nothing runs unwatched - long work that reports, and claims that were checked++**Status:** draft+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Nine units were picked off the tracker by priority. Reconnaissance against the+real source ran before any of them was designed, and it found the same two+defects underneath all nine.++The first: this system does long, resource-hungry work and reports nothing while+it runs. `o2b brain dream` prints its first character after it has finished. A+consolidation pass, a bridge discovery, a community detection and a maintenance+lane all accept a `safeguard` whose `checkpoint()` sits at exactly the iteration+boundary a progress tick belongs at, and none of them emits one. A herd of+detached reindexes is spawned from two startup points with `stderr: "ignore"`,+so every loser of the writer-lock race throws `INDEX_LOCKED` into a discarded+stream. A cancellation contract - `signal`, `SafeguardAbortError`, abort checked+in priority over the deadline - is fully written and passed by no production+call site, which makes that error class dead code.++The second: this system prints claims it has not checked. The install success+path is asked to state that every memory is a file in the operator's own vault+and that deleting it ends the brain - while one editor plugin spools raw+conversation turns outside the vault with no pruning, a machine-local secret+keys the `vault://` identity every tool returns, and install resolves the vault+through a chain that disagrees with the rest of the CLI, so the path it would+print as "your brain" can name a directory nothing else uses. A token-impact+surface reports `method: "exact"` over integers a caller supplied. Four+estimators disagree about what a token is.++The two are the same defect seen from two sides: a system that does not report+cannot be trusted, and a system that reports what it did not check cannot be+trusted either.++## Scope++Eleven implementation units carrying nine tracker tasks.++- **U1 - the progress spine.** A synchronous, optional progress sink threaded+ beside the `safeguard` option it mirrors, emitted from the checkpoints that+ already exist, rendered only at the edge. A census test over every long+ operation.+- **U2 - MCP progress: stdio carries it, HTTP refuses by name.** The+ `_meta.progressToken` is read rather than discarded; the stdio transport gains+ a notification writer; the single-response HTTP transport states a typed+ refusal instead of accepting a token it cannot honour.+- **U3 - cancellation, wired.** A real `AbortSignal` reaches the safeguard, an+ interrupt stops the pass cleanly at the next checkpoint, and a deliberate stop+ is not reported as a crash.+- **U4 - a ceiling that spans the process.** The embedding semaphore is shared+ per resolved provider rather than constructed per call, and the one unbounded+ fan-out is bounded.+- **U5 - the herd.** A reindex that can already be shown to lose the lock is not+ spawned, and the outcome of one that is spawned is written where the operator+ can read it.+- **U6 - a fourth gate, and a streak.** Host pressure joins the maintenance+ lane's existing gate set, refusing by name on platforms where the metric is+ degenerate; a consecutive-failure streak read off the lane journal is the+ portable analogue of crash-loop recovery for a system with no daemon. The hook+ watchdog ceiling is reconciled with the host timeout that pre-empts it.+- **U7 - the ingest lock that was never taken.** The unlocked read-modify-writes+ are locked, the frozen adapter array becomes a registry on the pattern already+ present in this codebase, and two silent-empty results learn to say which+ emptiness they mean.+- **U8 - the install says only what it checked.** One ownership statement+ derived from the resolved vault path, with the out-of-vault state it does not+ cover named rather than omitted; a vault-resolution disagreement fixed; an+ environment verdict that admits what it cannot determine.+- **U9 - the provider death date.** A sunset check that distinguishes "no sunset+ announced" from "unknown to the catalog", on the doctor that has a clock.+- **U10 - four failure modes, measured.** A conformance suite over proactive+ recall, write-back fidelity, cross-source isolation and injected-token cost,+ with one token estimator instead of five and a committed baseline.+- **U11 - the scanner's walk.** The traversal stops visiting what it must not,+ stops doing it twice, and stops depending on the host locale.++## Out of scope++Each of these is a decision, not an omission.++- **No daemon, no scheduler, no supervisor.** The absence is a stated+ architectural invariant (`docs/architecture.md:229`), and a rejected design+ item (`docs/plans/2026-05-18-brain-maturity-design.md:690-691`). The tasks+ asked for a startup grace period and crash-loop recovery; both are shaped for+ a resident process. The portable analogue is a gate evaluated at the top of a+ one-shot command with its state on disk, which is what U6 builds.+- **No cap on model inference.** The kernel makes no chat-model call at all -+ model work is handed back to the caller as `needs-llm-step` envelopes, and+ whatever inference a dream pass causes happens in the host agent's process+ after `dream()` has returned. Naming a ceiling "inference" would be a+ hardcoded falsehood about what this process does. U4 caps what actually+ crosses the boundary: outbound HTTP to the embedding provider.+- **No concurrency in the project scanner.** Measured on this repository:+ rendering and writing are 7.9 ms of a 396 ms run. Parallelising 2% is theatre.+ The measurement is recorded in the recon note and the refusal is stated in the+ release, not buried.+- **No whole-ingest writer lease.** The batch-planning surface exists so a caller+ can dispatch each batch as a parallel subagent, and the sync lock has no retry+ and no stale window by design, so subagents 2..N would fail immediately with+ `ELOCKED`. The task's premise - that the lease is taken too often - is+ inverted: it is taken not at all.+- **No three-way environment classifier.** cgroup v2 has erased the classic+ container heuristic, every container signal is one-way so a negative proves+ nothing, "cloud sandbox" cannot be separated from "container", and "container"+ is not "ephemeral". U8 probes what backs the resolved vault path and admits+ `undetermined` rather than guessing a class and stating the guess as fact.+- **No host load average as a portable metric.** It is `[0,0,0]` on Windows and+ reports the host run queue inside a container. This repository's established+ answer to an unanswerable platform question is to refuse by name+ (`src/core/config.ts:35,45-59`), not to return a plausible number.+- **No progress over the HTTP MCP transport.** It writes one SSE event and+ closes. A progress surface that accepts a token and discards the events would+ report liveness support that does not exist.++## Chosen approach++Variant 1 from the consultant, with one correction and one graft.++**The spine.** A closed four-piece vocabulary `PROGRESS_KIND`+(`started`/`advanced`/`refused`/`stopped`/`finished`) and a+`ProgressSink = (event: ProgressEvent) => void` - synchronous, because `dream`,+`discoverBridges`, `detectCommunities` and `runDoctor` are synchronous+functions and an async sink cannot be awaited inside them. It is an optional+readonly field on the same options interfaces that already carry+`safeguard?: Safeguard`, invoked with `?.`, exactly matching the house idiom+that `onFile`, `onTelemetry`, `onOversize` and `validate` already follow. Core+emits; only `src/cli` and `src/mcp` write, which is what the layering test+requires.++The event carries the operation identifier from the existing+`SafeguardOperation` union - the repository's own definition of "long" - a stage+identifier drawn from that operation's existing phase vocabulary, an integer+`completed`, and an **optional** `total`, because the index walk is a generator+and materialising a denominator costs a second full traversal.++**The correction to Variant 1.** The consultant treated both MCP transports as+non-carriers. That is true of HTTP and false of stdio: the frame writer is+private but reachable, and a third optional handler parameter does not force a+change at the 88 registration sites, because a handler declaring two parameters+satisfies a type declaring three. So stdio gains real progress notifications and+HTTP gains a typed refusal. One transport carries it; the other says why it+cannot. Neither pretends.++**The graft from Variant 3.** Every unit lands inside a mechanism this+repository already enforces rather than a new one: the maintenance lane's gate+set and journal for U6, the `agent-backend` registry shape for U7, the doctor+code census for U9, the write-site census's syntactic technique for U1's census,+the existing bounded-integer config readers for every new knob.++**Durability.** The mechanism that makes this last is the progress census: a+test enumerating every options interface that accepts `safeguard?: Safeguard`+and failing when one does not also accept `onProgress?: ProgressSink` or carry a+written declaration of why it cannot. This is the same declaration-plus-census+idiom the previous release established for destructive removal sites, and it is+the answer to the same failure: a mechanism that must be called by hand is a+mechanism that will be missed.++## Design decisions++- **Reuse `SafeguardOperation`, do not invent a second "long operation" list.**+ It already names `dream`, `reindex`, `bridges`, `clusters` and `maintenance`,+ and it came from an earlier task in this same family.+- **`total` is optional and its absence is meaningful.** The index driver+ consumes a generator; the embedding phase has an array. One event shape must+ carry both, and an edge renderer must show a bare counter when no denominator+ exists rather than inventing one.+- **Progress goes to stderr, never stdout.** Twelve top-level commands own their+ stdout as a caller-parsed payload. Every existing intermediate-output+ precedent in the repository is on stderr.+- **A command outside the internal-JSON set must not emit progress at all.** For+ those, both streams are monkey-patched into buffers for the whole run and+ released at the end, so a progress line there is swallowed and then dumped -+ which looks like it worked. The dependency is currently undocumented and+ load-bearing; a test asserts it.+- **No prose in a progress event.** Identifiers and integers only; the sentence+ is rendered at the edge from the identifier. This is the same rule that keeps+ caller-supplied prose off the advisory rail.+- **A deliberate stop is not a failure.** `SafeguardAbortError` exists precisely+ to be distinguished from a timeout; the exit code and the emitted event must+ preserve that distinction, or an operator's Ctrl-C reads as a crash.+- **A gate that cannot evaluate reports that it could not.** The pressure gate+ emits a distinct verdict on platforms where the metric is degenerate. An open+ gate and an unevaluated gate must not be the same journal line.+- **A new knob fails hard on a bad value.** Both disciplines exist in this+ codebase; for a ceiling or a gate, a silent fallback means the operator+ believes a bound is in force that is not.+- **An ownership statement names its exceptions.** The out-of-vault state that+ exists is enumerated by the statement rather than omitted from it, and the+ install path resolves the vault the same way the rest of the CLI does before+ it prints a path at all.+- **One token estimator.** Five disagreeing estimators are five different+ answers to one question; a metric averaged over them means nothing. The+ surface claiming `method: "exact"` over caller-supplied integers stops+ claiming it.+- **No natural-language word list anywhere.** The one prose recognizer on the+ write path hardcodes five English markers, contradicting the rule its own+ sibling module states. It becomes structural.++## File changes++New:++- `src/core/brain/progress.ts` - vocabulary, event, sink.+- `src/cli/progress-rail.ts` - edge renderer and legality decision.+- `src/core/search/embeddings/provider-semaphore.ts` - process-scoped ceiling.+- `src/core/brain/maintenance/pressure.ts` - the fourth gate.+- `src/core/brain/maintenance/streak.ts` - consecutive-failure read off the journal.+- `src/core/brain/ingest/adapter-registry.ts` - the registry shape.+- `src/core/brain/portability/vault-residence.ts` - what backs the vault path.+- `src/core/search/embeddings/sunset.ts` - sunset resolution and verdict.+- `src/core/bench/failure-modes/*` - the four-metric suite.+- `tests/core/architecture/progress-census.test.ts` - the durability mechanism.++Modified, in the layers they belong to: the indexer, dream, bridge discovery,+community detection, the maintenance lane, the MCP server and stdio transport,+the four CLI long verbs, the install renderers, the diagnostics registry, the+architect scanner, the ingest manifest and checkpoint writers, the session+adapter registry, the token estimators, and the hook ceiling.++## Risks and open questions++- **Threading one option through many call sites is the largest blast radius in+ the release.** Mitigation: the option is optional everywhere, absence is the+ existing behaviour, and the census names what is not yet wired rather than+ letting it pass silently.+- **The stdio notification writer must not interleave with a response frame.**+ Writes are line-delimited and synchronous; the design must state the ordering+ guarantee and test it.+- **The progress census may over-reach.** Some options interfaces accept a+ safeguard only to forward it. The census carries a declared-exception list+ with a written reason per entry, on the pattern the write-site census uses.+- **The conformance suite is the largest single unit and the least verified.**+ Two of its four metrics rest on surfaces that default off; the bench calls the+ functions directly, so the default does not block measurement, but the release+ must say that the shipped default is off and that the suite measures the+ capability rather than the delivered behaviour.+- **The install vault-resolution fix changes which directory an existing install+ names.** It is a correctness fix with a user-visible consequence and belongs+ in the breaking section.diff --git a/docs/brainstorm/nothing-runs-unwatched/plan.md b/docs/brainstorm/nothing-runs-unwatched/plan.mdnew file mode 100644index 00000000..3327b47c--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/plan.md@@ -0,0 +1,233 @@+# Nothing runs unwatched - implementation plan++Eleven units carrying nine tracker tasks. Each unit is one atomic commit or a+short sequence of them, test-first. Units marked **independent** may run in+parallel; the rest name what they depend on.++## Tasks++### U1: The progress spine+- **Tracker**: t_62bb944a+- **Files**: `src/core/brain/progress.ts` (new); `src/core/search/indexer.ts`;+ `src/core/brain/dream.ts`, `dream-types.ts`, `dream-stage.ts`;+ `src/core/brain/link-graph/bridge-discovery.ts`, `communities.ts`;+ `src/core/brain/maintenance/lane.ts`; `src/core/search/vector-backfill.ts`;+ `src/cli/progress-rail.ts` (new); `src/cli/brain/verbs/dream.ts`,+ `bridges.ts`, `clusters.ts`, `maintenance.ts`;+ `src/cli/search/verbs/indexing.ts`;+ `tests/core/architecture/progress-census.test.ts` (new)+- **Acceptance**:+ - `PROGRESS_KIND` passes the four-piece vocabulary census (frozen object,+ camelCase keys, snake_case values, derived union, members array, guard whose+ parameter is `unknown`).+ - A dream pass driven with a recording sink emits `started`, at least one+ `advanced` per phase in `DREAM_PHASE_ORDER`, and one `finished`.+ - An index run emits events with no `total`; an embedding phase emits events+ with a `total` equal to the pending-chunk count.+ - The progress census fails when a new options interface accepts+ `safeguard?: Safeguard` without `onProgress?: ProgressSink` and without a+ registered written reason.+ - A test asserts `search` and `brain` are in `COMMANDS_WITH_INTERNAL_JSON`,+ with the reason written in the test: progress from a wrapped command is+ buffered and released at the end, which looks like it worked.+ - Progress renders on stderr; a `--json` run's stdout stays byte-identical to+ the same run without a progress sink.+- **Depends on**: none++### U2: MCP progress - stdio carries, HTTP refuses+- **Tracker**: t_62bb944a+- **Files**: `src/mcp/server.ts`; `src/mcp/stdio.ts`; `src/mcp/http.ts`;+ `src/mcp/tool-contract.ts`; `src/mcp/brain/admin-tools.ts`,+ `feedback-tools.ts`, `knowledge-tools.ts`; `docs/mcp.md`+- **Acceptance**:+ - `params._meta.progressToken` is read at `handleToolsCall` and reaches the+ handler as an optional third parameter; a handler declaring two parameters+ still typechecks and still runs.+ - Over stdio, a `brain_dream` call carrying a token receives at least one+ `notifications/progress` frame before the response frame, and the response+ frame is unchanged from a call with no token.+ - Over HTTP, a call carrying a token receives a typed refusal naming the+ transport, and emits no progress frames.+ - A call with no token produces no frames and no refusal.+ - `brain_bridges` and `brain_clusters` pass a safeguard, which they do not+ today.+- **Depends on**: U1++### U3: Cancellation, wired+- **Tracker**: t_fe4b6be0+- **Files**: `src/core/brain/safeguard.ts`; `src/cli/brain/verbs/dream.ts`,+ `bridges.ts`, `clusters.ts`, `maintenance.ts`;+ `src/cli/search/verbs/indexing.ts`; `src/cli/exit-codes` surface+- **Acceptance**:+ - A long CLI verb interrupted once stops at the next checkpoint, emits a+ `stopped` progress event, and exits with a code distinct from both success+ and crash.+ - `SafeguardAbortError` is reachable from a production path; a test proves it+ by driving the verb's handler with a pre-aborted signal.+ - A second interrupt is not intercepted, matching the watch-runner precedent.+ - A timeout still produces `SafeguardTimeoutError` and its existing code.+- **Depends on**: U1++### U4: A ceiling that spans the process+- **Tracker**: t_fe4b6be0+- **Files**: `src/core/search/embeddings/provider-semaphore.ts` (new);+ `openai-compat.ts`; `zeroentropy.ts`; `src/core/search/benchmark.ts`+- **Acceptance**:+ - Two overlapping `embed()` calls against one resolved provider identity never+ exceed the configured concurrency in flight; a test counts concurrent+ in-flight requests against a stub transport.+ - Two different provider identities do not share a ceiling.+ - The benchmark fan-out is bounded by a named constant; a test asserts the+ in-flight ceiling under a dataset larger than it.+- **Depends on**: none (**independent**)++### U5: The herd+- **Tracker**: t_992f0c33+- **Files**: `src/core/maintenance/ensure-current.ts`; `src/cli/main.ts`;+ `hooks/active-inject.ts`+- **Acceptance**:+ - When the writer lock is already held, no child is spawned and the skip is+ recorded with a typed reason.+ - When a child is spawned, its terminal outcome is written where an operator+ can read it; a test drives a failing child and asserts the record exists and+ names the failure.+ - `stderr: "ignore"` no longer discards the only report of a failure.+- **Depends on**: none (**independent**)++### U6: A fourth gate, a streak, and a watchdog that can fire+- **Tracker**: t_992f0c33+- **Files**: `src/core/brain/maintenance/pressure.ts` (new);+ `streak.ts` (new); `lane.ts`; `src/core/brain/policy/blocks/*`;+ `templates/` brain config template; `hooks/hooks.json`;+ `hooks/lib/process-ceiling.ts`+- **Acceptance**:+ - On a POSIX host the gate reads a normalised pressure ratio and skips with a+ typed verdict above the configured threshold.+ - On a platform where the metric is degenerate the gate emits a distinct+ verdict meaning "unmeasurable here" and does not skip; the journal shows the+ two cases are different lines.+ - A task with N consecutive journaled failures is refused without `--force`,+ and the refusal names the streak.+ - The new config keys satisfy all four config-template ratchet assertions and+ appear commented, not live.+ - The hook ceiling and the declared host timeout no longer contradict each+ other, and a test asserts the relation rather than the two numbers.+- **Depends on**: none (**independent**)++### U7: The ingest lock that was never taken+- **Tracker**: t_da034197+- **Files**: `src/core/brain/ingest/content-manifest.ts`; `checkpoint.ts`;+ `src/core/brain/git/store.ts`;+ `src/core/brain/ingest/adapter-registry.ts` (new);+ `src/core/brain/sessions/registry.ts`;+ `src/core/discipline/transcripts/claude-code.ts` and siblings;+ `tests/core/architecture/verdict-vocabulary-census.test.ts`+- **Acceptance**:+ - Two concurrent manifest updates do not lose one another's record; a test+ drives the race and asserts both survive.+ - The adapter registry rejects an unknown id loudly with the id in the+ message, and adding an adapter touches only the new module and the registry+ entry.+ - `isSessionAdapterId` takes `unknown` and the vocabulary is registered in the+ census.+ - A transcript resolver distinguishes "directory absent", "unreadable" and+ "no transcripts" from one another; none of the three is a bare zero.+ - A dry-run import is distinguishable in its result from a real run that wrote+ nothing.+- **Depends on**: none (**independent**)++### U8: The install says only what it checked+- **Tracker**: t_b5fa7344, t_1037d94e+- **Files**: `src/core/brain/portability/vault-residence.ts` (new);+ `src/cli/install/install.ts`, `render.ts`, `init-interactive.ts`;+ `src/cli/install-cli.ts`; `src/cli/onboarding.ts`;+ `src/core/brain/diagnostics.ts`; `src/core/brain/doctor/*`+- **Acceptance**:+ - Install resolves the vault through the same chain as the rest of the CLI; a+ test pins the precedence and fails on divergence.+ - The success path carries an ownership statement built from the resolved+ path plus the enumerated out-of-vault state; a test asserts every known+ out-of-vault location appears in the enumeration, so a new one cannot be+ added without updating the statement.+ - Every install `--json` shape carries a schema version and is asserted by a+ test, which none is today.+ - The residence verdict has an `undetermined` member and a separate reason;+ a test proves a negative container signal does not produce a positive+ "local" verdict.+ - The durability check reports liveness only and states in its own message+ what it could not check, because no job registration exists to check the+ presence of.+- **Depends on**: none (**independent**)++### U9: The provider death date+- **Tracker**: t_e7a226ce+- **Files**: `src/core/search/embeddings/sunset.ts` (new); `presets.ts`;+ `signature.ts`; `src/core/brain/diagnostics.ts`;+ `src/core/brain/doctor/*`; `tests/core/brain/doctor-exit-census.test.ts`+- **Acceptance**:+ - A configured model with a declared sunset date in the future within the+ warning window produces a warning naming the model and the date.+ - A configured model that is not in the catalog produces a verdict meaning+ "unknown to the catalog", which is a different value from "no sunset+ announced"; a test asserts the two are distinguishable.+ - The check reads its clock from the injected doctor clock and calls no global+ time function.+ - The new code is present in `DOCTOR_REGISTERED_CODES` and the `nextCommand`+ passes the structural command assertion.+ - The message never claims to name a vendor, because the provider field+ resolves to a transport kind.+- **Depends on**: none (**independent**)++### U10: Four failure modes, measured+- **Tracker**: t_72d6eb23+- **Files**: `src/core/bench/failure-modes/` (new);+ `src/core/bench/phases.ts`, `types.ts`; `src/cli/brain/verbs/bench.ts`;+ `src/core/brain/token-impact.ts`; the shared token estimator;+ `src/core/brain/pre-compact-extract.ts`; `tests/helpers/run-cli.ts`;+ `.github/workflows/ci.yml`+- **Acceptance**:+ - Proactive recall is scored by driving the pure decision function with an+ injectable retriever over a fixture; a strategy that always injects scores+ worse than one that abstains correctly, because the false-fire term is+ weighted against it.+ - Write-back fidelity grades provenance fields on the shipped path with no+ model call.+ - Cross-source isolation asserts on delivered pack contents under the strict+ gate and gates at zero.+ - Injected tokens are counted by exactly one estimator; a test asserts no+ second estimator remains reachable from the bench.+ - `brain_token_impact` no longer reports `method: "exact"` over integers a+ caller supplied.+ - The prose recognizer on the write path carries no natural-language word+ list; a fixture in a non-Latin script scores on structure.+ - The two environment variables that changed the bench between a developer and+ CI are scrubbed by the CLI test helper.+ - A committed baseline exists and CI runs the suite.+- **Depends on**: none (**independent**)++### U11: The scanner's walk+- **Tracker**: t_4b479851+- **Files**: `src/core/brain/architect/scan.ts`, `generate.ts`;+ `src/cli/brain/verbs/architect.ts`+- **Acceptance**:+ - The traversal visits each directory once; a test counts directory reads on a+ fixture with a nested layout.+ - Dot-directories and `.gitignore` entries are not visited; a test asserts a+ file under an ignored directory does not appear in the facts.+ - The language tie-break is locale-independent; a test runs it under two+ locales and asserts identical output.+ - The scan emits progress through the U1 sink.+ - Rendered notes are byte-identical to the previous release on a fixture with+ no ignored directories, measured with the vault-digest helper.+- **Depends on**: U1++## Release-phase tasks++- Docs pass: `docs/mcp.md` (progress notifications and the HTTP refusal),+ `docs/cli-reference.md` (new flags, exit code for a deliberate stop, new+ doctor code), `docs/how-it-works.md` (the maintenance gate set),+ `docs/architecture.md` (out-of-vault state enumeration),+ `docs/metrics.md` if a new surface appears, `docs/observability.md`.+- `CHANGELOG.md` entry under a new version heading plus its compare link.+- `package.json` version bump followed by `bun run scripts/sync-version.ts`.+- OpenClaw bundle rebuild if any bundled source changed.diff --git a/docs/brainstorm/nothing-runs-unwatched/recon/architect-module.md b/docs/brainstorm/nothing-runs-unwatched/recon/architect-module.mdnew file mode 100644index 00000000..b18fb8ca--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/recon/architect-module.md@@ -0,0 +1,352 @@+# Recon — `architect` module (t_4b479851)++Subject: `feat/nothing-runs-unwatched`, based on v1.47.0 (`aa818084 feat: wiring what exists (v1.47.0) (#164)`).+Every claim below carries a `path:LINE` anchor that was read. Measurements were run on this repository as+subject; the exact commands are reproduced in section 2.++## 1. The full architect surface++The module is two files, 408 lines total.++| File | Role | Public entry points |+| --- | --- | --- |+| `src/core/brain/architect/scan.ts` (229 lines) | Stdlib-only structural scan of one project tree into frozen facts. No network, no LLM, no language parsing (`src/core/brain/architect/scan.ts:1-13`). | `scanProject(projectRoot): ProjectFacts` (`src/core/brain/architect/scan.ts:214`); types `ModuleFact` / `ManifestFact` / `ProjectFacts` (`:48`, `:58`, `:65`) |+| `src/core/brain/architect/generate.ts` (179 lines) | Renders those facts into vault notes under `Brain/projects/arch/<repo-key>/` through sentinel regions. | `generateArchDocs(vault, projectRoot): GenerateArchDocsResult` (`src/core/brain/architect/generate.ts:131`); result type at `:32` |++Nothing else lives in the directory (`ls src/core/brain/architect/` → `generate.ts`, `scan.ts`).++Internal helpers, for the cost analysis below: `walk` (`scan.ts:84`), `statsFor` (`scan.ts:115`), `listDirs`+(`scan.ts:121`), `readManifest` (`scan.ts:141`), `detectModules` (`scan.ts:161`), `detectEntryPoints`+(`scan.ts:193`); `languagesLine` (`generate.ts:42`), `overviewRegions` (`generate.ts:53`), `moduleRegions`+(`generate.ts:89`), `frontmatter` (`generate.ts:105`), `upsertNote` (`generate.ts:114`).++Dependencies out of the module: `atomicWriteFileSync` (`src/core/fs-atomic.ts:42`), `repoKey`+(`src/core/brain/git/identity.ts:25`), `buildRegionDocument` / `mergeRegions` (`src/core/brain/regions.ts:105`,+`:115`), `assertVaultIdentityForWrite` (`src/core/brain/vault-identity.ts:354`).++### Callers++**CLI only. There is no MCP tool.**++- CLI verb: `cmdBrainArchitect` (`src/cli/brain/verbs/architect.ts:12`), calling `generateArchDocs`+ at `src/cli/brain/verbs/architect.ts:23`.+- Dispatch: `case "architect"` in `src/cli/brain.ts:347-348`, re-exported at+ `src/cli/brain/verbs/index.ts:88`.+- Manifest + help: `src/cli/command-manifest.ts:292`, `src/cli/brain/help-text.ts:166` and `:1070-1073`.+- Docs: `docs/cli-reference.md:223`, `docs/how-it-works.md:1214`.+- Tests: `tests/core/brain/architect.test.ts:11-12`, `tests/cli/brain-architect.test.ts:31`,+ `tests/e2e/project-history.integration.test.ts:100`, `:122`, `:134`.++A repo-wide grep for `generateArchDocs|scanProject` outside the module returns exactly those sites; no+`src/mcp/**` file mentions `architect` or exposes an arch tool (checked by `grep -rln "architect" src/mcp/`+→ no matches).++### Argument shape++`cmdBrainArchitect` reads `positional[0]` only (`src/cli/brain/verbs/architect.ts:15`); extra positionals are+silently ignored. Flags are `--vault` and `--json` (`:14-17`). There is no `--repos`, no glob, no+concurrency flag, and no progress flag anywhere in the verb.++## 2. What is actually slow — measured++**Wall clock is the filesystem walk. Rendering and writing is 2% of a steady-state run on this repo.**++Command (run from any directory; timings are medians of 7):++```+bun -e '+import { mkdtempSync, mkdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os"; import { join } from "node:path";+import { scanProject } from "/srv/projects/open-second-brain/src/core/brain/architect/scan.ts";+import { generateArchDocs } from "/srv/projects/open-second-brain/src/core/brain/architect/generate.ts";+const repo = "/srv/projects/open-second-brain";+const med = (a) => a.toSorted((x,y)=>x-y)[Math.floor(a.length/2)];+const time = (fn,n) => { const t=[]; for (let i=0;i<n;i++){const s=Bun.nanoseconds(); fn(); t.push((Bun.nanoseconds()-s)/1e6);} return med(t); };+const tScan = time(()=>scanProject(repo),7);+const tmp = mkdtempSync(join(tmpdir(),"o2b-arch-bench-")); const vault = join(tmp,"vault");+mkdirSync(join(vault,"Brain"),{recursive:true});+let s=Bun.nanoseconds(); const first=generateArchDocs(vault,repo); const tFirst=(Bun.nanoseconds()-s)/1e6;+const tSteady = time(()=>generateArchDocs(vault,repo),7);+console.log({tScan,tFirst,tSteady,notes:1+first.modulePaths.length}); rmSync(tmp,{recursive:true,force:true});'+```++Result on this repository (`totalFiles: 24094`, 4 modules → 5 notes):++| Phase | ms |+| --- | --- |+| `scanProject` alone | **388.0** |+| `generateArchDocs` cold (5 notes created) | 451.4 → render+write ≈ **63.4** |+| `generateArchDocs` steady (5 notes unchanged) | 395.9 → render+read ≈ **7.9** |++Syscall census of one `scanProject` on this repo+(`strace -f -c -e trace=getdents64,newfstatat,lstat,openat,statx,write,rename,fsync bun -e 'import {scanProject} from "…/scan.ts"; scanProject("/srv/projects/open-second-brain")'`):++```+statx 28356 (68.7% of syscall time)+getdents64 6648 (20.8%)+openat 3350 (10.6%)+write 1+```++That is one `lstat` per directory entry (`scan.ts:99`) and ~2 `getdents64` per directory+(`readdirSync`, `scan.ts:87` and `scan.ts:123`). Writes do not appear because a scan writes nothing.++**Why the walk is that large, and where the redundancy is.** `scanProject` walks the tree at least twice+over parts of it:++1. `statsFor(root)` (`scan.ts:217`) walks the *entire* tree to compute `totalFiles`/`languages`.+2. `detectModules` (`scan.ts:161-179`) walks `src/<dir>` (or `packages/<dir>`) again, once per module+ (`scan.ts:169`) — so the `src` subtree is walked twice in total.+3. On a **flat layout** the whole tree is walked a second time in full (`scan.ts:181`), because the root+ becomes the single module.+4. `package.json` is read and JSON-parsed twice: `readManifest` (`scan.ts:145`) and again in+ `detectEntryPoints` (`scan.ts:196`).++`SKIP_DIRS` (`scan.ts:18-32`) skips `.git`, `node_modules`, `dist`, `build`, `out`, `coverage`, `vendor`,+`target`, `.venv`, `venv`, `__pycache__`, `.next`, `.cache` — and *nothing else*. No `.gitignore`, no+ignore-file support, no dot-directory rule. On this checkout that means the dominant cost is a directory+nobody wants in architecture notes: of the 24094 counted files, **21113 are under `.claude/`**+(`find .claude -type f | wc -l` → 21121; `scanProject("…/.claude").totalFiles` → 21113), 940 under `src/`,+1120 under `tests/`, 522 under `docs/`.++Per-subtree timings (same harness, medians of 5): `src` 940 files → 59.4 ms; `docs` 522 files → 45.1 ms;+`.claude` 21113 files → 1059.4 ms (flat layout, hence the double walk of point 3).++**The render half, isolated.** A synthetic project with 100 modules × 5 files (501 files) built in+`mkdtemp`, scanned and generated:++| Phase | ms |+| --- | --- |+| `scanProject` (501 files) | 15.9 |+| `generateArchDocs` cold, 101 notes written | 282.7 → render+write ≈ **266.9** (≈ 2.6 ms/note) |+| `generateArchDocs` steady, 101 notes unchanged | 20.5 → render+read ≈ **4.7** (≈ 0.05 ms/note) |++So the render half is fsync-bound on *first* generation only (`fsyncSync` of the temp file plus a parent+directory fsync per note — `src/core/fs-atomic.ts:291` and `:297-305`), and effectively free once the notes+exist, because an unchanged note short-circuits before any write (`generate.ts:125`).++**Conclusion, stated plainly.** Parallelising "rendering across notes" parallelises 8 ms out of 396 ms on+this repo (2%). The only case where note-level concurrency has anything to bite on is the *cold* generation+of a module-rich project (≈ 2.6 ms/note, fsync-dominated) — and `atomicWriteFileSync` is fully synchronous+(`src/core/fs-atomic.ts:42-54`, `:264-328`), so concurrency there requires either an async twin of the+shared writer or worker threads, both of which are census-relevant changes (section 4). The wall clock lives+in `walk` (`scan.ts:84-113`), which is a synchronous recursive `readdirSync`/`lstatSync` loop.++*What I did not establish:* whether the scan is CPU-bound or IO-wait-bound on cold page cache. All numbers+above are warm-cache. On a cold cache the ratio between walking and writing may shift, and I did not drop+caches (that needs root).++## 3. Determinism mechanics++Sentinels are paired HTML comments with explicit ids, not a single `@generated` marker:++```+<!-- o2b:begin <region-id> -->+…generated body…+<!-- o2b:end <region-id> -->+```++`src/core/brain/regions.ts:32-33` (the two regexes, tolerating a trailing `\r`), rendered at+`src/core/brain/regions.ts:101`. Everything outside a region is operator-owned and survives byte-for-byte+(`regions.ts:1-27`). Parsing is fail-closed: unbalanced / duplicate / nested / mismatched sentinels throw+`RegionError` *before* any write (`regions.ts:55-97`, re-validated first thing in `mergeRegions` at+`regions.ts:116`), and the CLI turns that into a repair message (`src/cli/brain/verbs/architect.ts:44-48`).++Region ids emitted today: `summary`, `modules`, `entry-points`, `dependencies` on the overview+(`generate.ts:81-86`); `facts`, `files` on each module note (`generate.ts:99-102`).++### Every place ordering can change bytes++Exhaustive list of the ordering-sensitive properties of the output, each anchored:++1. **Note set / note paths.** `overview.md` plus one `modules/<name>.md` per detected module+ (`generate.ts:148`, `:158-168`). Names come from distinct entries of one directory listing+ (`scan.ts:121-139`), so two notes can never target the same path in one run — *except* that the+ flat-layout branch always emits exactly one module named `root` (`scan.ts:182-190`).+2. **Module list inside the overview** — the `modules` region body is built by mapping `facts.modules`+ in array order (`generate.ts:63-69`). That order is `readdirSync(...).toSorted()` (`scan.ts:129`), i.e.+ fixed by the scan, not by write order. A concurrent renderer must not build this list from completion+ order.+3. **Language lists** (`generate.ts:42-51`), used by both the overview summary (`generate.ts:59`) and each+ module note (`generate.ts:93`). Sorted by count desc, ties broken by **`localeCompare`**+ (`generate.ts:44`) — see Divergence D5.+4. **Top-file lists** in module notes: `stats.paths.toSorted().slice(0, 20)` (`scan.ts:175`, `:188`, cap at+ `scan.ts:76`). Walk order is itself sorted (`scan.ts:91`), and the result is re-sorted, so the list is+ walk-order-independent.+5. **Entry points**: `Set` insertion order collapsed by `toSorted()` (`scan.ts:210`).+6. **Dependencies**: `Object.keys(...).toSorted()` (`scan.ts:148`).+7. **Region order within a note.** For a *new* file, `buildRegionDocument` emits regions in array order+ (`regions.ts:105-107`). For an existing file, region bodies are replaced in place and only ids *new to+ the update* are appended, in the update array's order (`regions.ts:144-147`). Both orders come from the+ fixed literal arrays at `generate.ts:81-86` and `:99-102`, not from scheduling.+8. **Cross-note references.** The overview links each module note by wikilink+ (`generate.ts:66`). This is computed from `facts` and `key`, *not* by reading the module notes, so there+ is no read-after-write dependency between notes in a run. Module notes contain no back-links.+9. **Frontmatter.** Written once at creation and never rewritten (`generate.ts:105-107`, `:120`, and the+ contract at `generate.ts:12-14`). Under concurrency the create/merge decision is per-note+ (`generate.ts:115-127`), so this stays per-file.+10. **Shared mutable state inside one run** — the three real hazards:+ - the `created` / `updated` / `unchanged` counters and the `tally` closure (`generate.ts:139-146`);+ - the `modulePaths` array, pushed in loop order (`generate.ts:157`, `:160`) and surfaced verbatim as+ `module_paths` in the CLI JSON (`src/cli/brain/verbs/architect.ts:30`) — completion-order pushes+ would make that array non-deterministic even though the note *bytes* stay stable;+ - `mkdirSync(join(dir, "modules"), {recursive:true})` runs once before the loop (`generate.ts:137`);+ a design that moves it per-note gains a concurrent-mkdir race that `recursive: true` tolerates but+ that no longer happens exactly once.+11. **Partial-failure surface.** A `RegionError` on note *k* leaves notes `0..k-1` already written+ (`generate.ts:149-168`); the process exits through `fail()` (`architect.ts:44`). Which prefix is on disk+ is currently a deterministic function of module order; under concurrency it becomes a function of+ scheduling.+12. **The unchanged short-circuit** (`generate.ts:125`) compares merged text against the bytes just read at+ `generate.ts:123`. Read and write are two separate syscalls with no lock between them (section 4), so+ the "unchanged" verdict is only as true as the absence of a concurrent writer to that path.++Byte-stability is pinned by tests: `tests/core/brain/architect.test.ts:117-124` ("unchanged project+regenerates byte-identically"), `:104-115` (operator prose outside regions survives), and the CLI-level+idempotency check at `tests/cli/brain-architect.test.ts:31-48`.++## 4. Write conflicts++- **Shared writer: yes.** Both writes go through `atomicWriteFileSync` (`generate.ts:120` for create,+ `generate.ts:126` for update), imported at `generate.ts:24`. That is temp-file + fsync + `rename(2)` ++ best-effort parent-dir fsync (`src/core/fs-atomic.ts:42-54`, `:264-328`). Temp names carry pid + ms ++ random suffix precisely so concurrent writers to the same target cannot collide on the temp inode+ (`src/core/fs-atomic.ts:276-280`).+- **Lock: no.** `generateArchDocs` acquires nothing. It does not import `sync-lockfile.ts`+ (`acquireLockSync` at `src/core/brain/sync-lockfile.ts:65`), which other Brain writers do use+ (`preference-txn.ts`, `idempotency-ledger.ts`, `lineage/ledger.ts`, `continuity/store.ts`, …). The+ read-modify-write in `upsertNote` (`generate.ts:123` read → `:126` write) is therefore a TOCTOU window:+ an operator edit landing between the two is silently overwritten, and two concurrent architect runs on the+ same repo are last-writer-wins. This is the *pre-existing* state; concurrency inside one run widens the+ window but does not create it.+- **Write-site census.** The census is `tests/core/architecture/write-site-census.test.ts`. Its population+ rule pulls in everything under `src/core/brain/` (`VAULT_WRITE_ROOTS`, `:77-82`). `CONTENT_WRITE_CALLS`+ (`:97-132`) deliberately excludes `mkdirSync` (`:93-96`), and `SHARED_WRITE_CALLS` (`:143-149`) names+ `atomicWriteFileSync`. `generate.ts` imports only `existsSync, mkdirSync, readFileSync` from `node:fs`+ (`generate.ts:21`), so it has **zero** direct-fs content writes: it is classified into the *shared-writer*+ class (`classify`, `:803-809`) and correctly carries **no entry** in `DIRECT_WRITE_EXCLUSIONS` (`:243-706`).+ `scan.ts` writes nothing and is out of the census entirely. **The rule architect is registered under is+ "routes through a shared writer" — i.e. it is in the clean half, not in the excused half.** Any change+ that reaches `node:fs` directly (a worker writing bytes, an async `writeFile`, a `Bun.write`) fails+ `:825-831` by name and would need a new written exclusion; note `writeFile`/`rename`/`rm` from+ `node:fs/promises` are already in the detected set (`:119-131`) and `Bun.write` is matched without any+ import (`:140`, `:796-798`).+- **Vault-identity guard.** `generateArchDocs` calls `assertVaultIdentityForWrite(vault)` as its first+ statement (`generate.ts:133`, guard at `src/core/brain/vault-identity.ts:354`). The guard census+ (`tests/core/brain/vault-guard-census.test.ts:57`) matches on the literal call, so a refactor that moves+ the assertion into a per-note worker must keep the identifier visible in the module.+- **Path construction.** The arch directory is assembled by raw `join` (`generate.ts:136`) — it is *not* in+ the `paths.ts` vocabulary and `ensureInsideVault` is never applied here (grep for `projects/` in+ `src/core/brain/paths.ts` → no match). The repo key that keys the directory is a pure function of the+ absolute path (`src/core/brain/git/identity.ts:25-29`), so two distinct repos can never share a directory,+ and the same repo scanned twice always lands in the same one.++## 5. Overlap with t_041c571f++**The claim that Open Second Brain has no architecture-notes generator is false.** `src/core/brain/architect/`+ships one, wired to `o2b brain architect` (`src/cli/brain.ts:347`), documented (`docs/cli-reference.md:223`),+and covered by unit, CLI, and e2e tests. Item by item:++| t_041c571f item | Status | Evidence |+| --- | --- | --- |+| Overview note | **Shipped** | `overview.md` with `kind: arch-overview`, summary / modules / entry-points / dependencies regions — `generate.ts:148-155`, `:53-87` |+| …with a Mermaid diagram | **Not shipped** | `grep -rln mermaid src/` → no matches anywhere in `src/` |+| …with inferred personas | **Not shipped** | No persona inference in either architect file; the only `personas` module is `src/core/brain/write-session/personas.ts:24`, an unrelated write-session review-lens list |+| One note per core module | **Shipped** | `generate.ts:158-168`, module detection at `scan.ts:161-191`; per-module regions at `generate.ts:89-103` |+| Key-decisions note | **Not shipped in architect**; an adjacent generator exists | Architect emits no decisions region. `mineCommitDecisions` (`src/core/brain/git/decisions.ts:111`) writes ADR *candidates* to `Brain/decisions/candidates/adr-<shortsha>-<slug>.md` (`decisions.ts:10-11`, `:115`) from conventional-commit signals (`decisions.ts:38`) — commit-derived, not architecture-derived, and in a different tree |+| Sentinel-marker refresh preserving hand edits | **Shipped** | `src/core/brain/regions.ts` in full; `upsertNote` (`generate.ts:114-128`); proven at `tests/core/brain/architect.test.ts:104-115` and end-to-end at `tests/e2e/project-history.integration.test.ts:108-127` |+| LLM-synthesised prose | **Not shipped, and deliberately excluded** | "no network, no LLM, no per-language parsing … the same tree always produces the same facts (the generator's idempotency rests on this)" — `scan.ts:1-13`; the docblock also puts import-graph analysis explicitly out of scope (`scan.ts:7-8`) |++Facts only; the scope call belongs to whoever owns t_041c571f. Worth flagging for that decision: the three+missing items (Mermaid, personas, LLM prose) are the three that would introduce non-determinism or a network+call into a module whose byte-identical-regeneration test (`tests/core/brain/architect.test.ts:117`) currently+depends on their absence.++## 6. Progress subject — is the unit count known up front?++- **Notes: known only *after* the expensive part.** `notes = 1 + facts.modules.length`, and `facts` comes+ from `scanProject` at `generate.ts:135` — i.e. after the whole tree has already been walked. Everything+ after that point (`generate.ts:137-168`) is the cheap 2%.+- **During the scan: not known at all.** `walk` (`scan.ts:84-113`) is a depth-first recursive discovery with+ no pre-pass and no counter; `statsFor` returns totals only when finished (`scan.ts:115-119`). There is no+ file-count total available before the walk ends, so a percentage-complete over the scan is impossible+ without adding a pre-pass (which doubles the very syscalls that dominate). A *monotone* counter —+ directories entered, files seen, current relative path — is available with no extra I/O, since both values+ are already accumulated in `WalkStats` (`scan.ts:78-82`, `:108-109`).+- **Repos: there is no multi-repo unit.** `generateArchDocs` takes one `projectRoot` (`generate.ts:131`) and+ the CLI reads one positional (`src/cli/brain/verbs/architect.ts:15`). No registry of arch repos exists; the+ only repo enumerator in the codebase is `listGitRepos` (`src/core/brain/git/store.ts:338-353`), which lists+ `Brain/projects/git/*` — the *git-history* store, not `Brain/projects/arch/`, and it is consumed only by+ `src/cli/brain/verbs/git.ts:50`, `:146`, `:218`.+- **No progress facility exists to reuse.** `grep -rn "onProgress\|progress(" --include=*.ts src/` returns+ nothing outside tests. Concurrency precedents that *do* exist: the embedding batch pipeline+ (`src/core/search/embeddings/http-util.ts:5`, `:13`, `:54-74`, with retry/backoff/jitter) and the+ `embedding_concurrency` semaphore reasoning at `src/core/search/indexer.ts:870-877`; the serialisation+ precedent is `src/core/search/store/writer-lock.ts:1-40`.++## Divergences++Where t_4b479851's framing does not survive contact with the source.++- **D1 — "concurrent rendering across notes" targets 2% of the runtime.** Measured: steady-state render+write+ is 7.9 ms of a 395.9 ms run on this repo, and 4.7 ms for 101 notes on the synthetic project (section 2).+ The wall clock is in `walk` (`scan.ts:84-113`). The one case with real cost is *cold* generation+ (≈ 2.6 ms/note, fsync-bound at `src/core/fs-atomic.ts:291`, `:297-305`), which happens once per project.+- **D2 — "multi-repo scans" do not exist in this module.** One call, one root (`generate.ts:131`;+ `src/cli/brain/verbs/architect.ts:15`). Any multi-repo pass — and therefore any repo-level progress —+ has to be *built*, not instrumented. Extra positionals are currently ignored without a word.+- **D3 — the task's own premise ("retry has little to bite on") is confirmed, but for a sharper reason than+ stated.** There is no network and no LLM anywhere in the module (`scan.ts:1-13`), and every I/O failure in+ the scan is already swallowed on purpose: `readdirSync` failures return/skip (`scan.ts:87-90`,+ `:122-126`), `lstatSync` failures `continue` (`scan.ts:99-102`, `:132-137`), a malformed `package.json`+ yields `null` (`scan.ts:156-158`). The one *unswallowed* failure class is on the write side —+ `RegionError` (fail-closed by design, `regions.ts:35-43`) and raw errno from `atomicWriteFileSync`+ (ENOSPC, EROFS, EACCES). Neither is retry-shaped: the first is a repair request, the second is+ correctly propagated (`src/core/fs-atomic.ts:240-247` propagates every non-EEXIST errno untouched).+- **D4 — the real performance lever is not concurrency at all.** It is (a) not re-walking the same subtree+ (`scan.ts:217` + `scan.ts:169`; full double-walk on flat layouts, `scan.ts:181`) and (b) the skip list+ (`scan.ts:18-32`), which honours no `.gitignore` and no dot-directory rule: 21113 of the 24094 files this+ repo's scan visits are under `.claude/`. Fixing either shrinks the dominant term by more than any+ parallelism applied to the current shape.+- **D5 — "output stays deterministic" is not unconditionally true today, independent of concurrency.**+ `languagesLine` breaks count ties with `a[0].localeCompare(b[0])` (`generate.ts:44`), which is+ ICU/locale-dependent; every other ordering in the module uses plain `toSorted()` (`scan.ts:91`, `:129`,+ `:148`, `:175`, `:210`). Two machines with different collation can therefore render different bytes for+ the same tree. Worth fixing in the same wave, since the concurrency work will lean on the byte-identity+ test at `tests/core/brain/architect.test.ts:117`.+- **D6 — "sentinel-region-stable regardless of concurrency" is currently unenforced *across processes*.**+ No lock (section 4), and `upsertNote`'s read-then-write (`generate.ts:123` → `:126`) has an open TOCTOU+ window against both a concurrent architect run and a live operator edit.+- **D7 — one ordering artefact *does* leak into an output today, just not into note bytes.**+ `module_paths` in the CLI JSON (`src/cli/brain/verbs/architect.ts:30`) is `modulePaths` in loop-push order+ (`generate.ts:157`, `:160`). Concurrent rendering scrambles it unless it is re-derived from `facts.modules`.++## What a design must not assume++- **Do not assume note-level concurrency buys anything measurable on a normal re-run.** It does not+ (D1). If concurrency is worth having, the subject is the *walk*, and the walk is synchronous+ `readdirSync`/`lstatSync` (`scan.ts:87`, `:99`) — parallelising it means either `node:fs/promises` or+ workers, both of which change the module's classification in the write-site census+ (`tests/core/architecture/write-site-census.test.ts:119-131`, `:140`) if any write moves with them.+- **Do not assume `atomicWriteFileSync` can be called concurrently "for free".** It is fully synchronous+ (`src/core/fs-atomic.ts:42-54`), so within one JS thread it serialises regardless of how the callers are+ scheduled; overlapping it needs an async twin (a new shared writer, hence a census decision) or worker+ threads (which cannot share the counters at `generate.ts:139-146`).+- **Do not assume the number of units is known before the pass starts.** Note count is known only after the+ scan (`generate.ts:135`); file count is never known before the walk finishes (`scan.ts:84-113`). A+ percentage-complete requires a pre-pass that doubles the dominant syscall cost. A monotone+ "files seen / current path" counter is free.+- **Do not assume there is a repo list to iterate.** There is none for arch (section 6);+ `listGitRepos` (`src/core/brain/git/store.ts:338`) enumerates `Brain/projects/git/`, a different store.+- **Do not assume ordering only affects note bytes.** It also affects `module_paths` in the JSON envelope+ (D7), the created/updated/unchanged tally (`generate.ts:139-146`), and *which prefix of notes exists* when+ a `RegionError` aborts mid-run (`generate.ts:149-168`).+- **Do not assume a progress channel can print freely.** `--json` emits a single JSON object via `okJson`+ (`src/cli/brain/verbs/architect.ts:25-34`); any progress line on stdout in that mode breaks the envelope.+- **Do not assume the identity guard can move.** `assertVaultIdentityForWrite` must stay textually present+ in the writing module — the guard census matches the identifier+ (`tests/core/brain/vault-guard-census.test.ts:57`) — and it must stay *before* the first byte+ (`src/core/brain/vault-identity.ts:344-352`).+- **Do not assume retry belongs anywhere here** without first naming the concrete errno it would retry.+ Scan-side I/O failures are already absorbed by design (D3); write-side failures are either fail-closed+ corruption reports or errnos that must propagate.diff --git a/docs/brainstorm/nothing-runs-unwatched/recon/concurrency-and-cancellation.md b/docs/brainstorm/nothing-runs-unwatched/recon/concurrency-and-cancellation.mdnew file mode 100644index 00000000..fd561eb6--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/recon/concurrency-and-cancellation.md@@ -0,0 +1,656 @@+# Recon: concurrency, cancellation, and host pressure (t_fe4b6be0, t_992f0c33)++Read-only reconnaissance against `feat/nothing-runs-unwatched` @ `aa818084` (v1.47.0).+Every claim is anchored to lines that were read. Findings that change the shape of+either task are marked **(shape-changing)**.++Both tasks arrive from a daemon-shaped upstream product. Open Second Brain is not+daemon-shaped, and does not call a chat model. Most of what follows is the record of+where that framing breaks.++---++## 1. Where this codebase issues LLM inference++**It does not. The server process never makes an outbound chat-model call. (shape-changing)**++The kernel's contract is to hand model work *back to the caller* as a typed envelope,+never to prompt a model itself. This is stated at the readiness probe that would have+been the natural place to hide an inference client — `src/core/doctor-readiness.ts:40-44`:++> the deterministic Brain core has no in-repo chat-LLM client (write-time model steps+> are handed back to the host as `needs-llm-step` envelopes). The only model-inference+> credential the system itself resolves is the embedding provider's API key++The `needs-llm-step` envelope is the whole mechanism, and it appears at five producers:++| Producer | Envelope construction | What the caller is asked to generate |+|---|---|---|+| `src/core/brain/rollup-ladder.ts:63-72`, built at `:193-197` | `RollupEnvelope` | the rollup summary note for a fired rung |+| `src/core/brain/diarization.ts:83`, built at `:237` | diarization envelope | subject-profile prose |+| `src/core/brain/write-session/engine.ts:98` | session step | the current section's draft |+| `src/core/brain/write-session/panel.ts:89`, `:197` | panel step | panel prose |+| `src/core/brain/write-session/types.ts:23,35` | the status vocabulary itself | — |++The determinism claim is repeated as a module invariant across the layer, not asserted+once: `src/core/brain/note-history.ts:11`, `src/core/brain/generation-reports.ts:5`+("Open Second Brain's kernel never calls an LLM - the calling agent…"),+`src/core/bench/judge.ts:5`, `src/core/reliability/command-bridge.ts:5`,+`src/core/brain/idempotency-ledger.ts:31`, `src/core/surface/lexical-score.ts:3`.++**The dream pass is one of these producers, not a consumer.** `dream()` emits rollup+envelopes (`src/core/brain/dream-types.ts:140`, plan built in+`src/core/brain/dream.ts:220-222`). Whatever inference those envelopes cause happens in+the *host agent's* process, after `dream()` has already returned. Nothing inside this+repo can cap it, count it, or cancel it.++### What outbound network calls actually exist++Six `fetch` sites in `src/`, none of them a chat completion:++| Site | Purpose | Concurrency bound today |+|---|---|---|+| `src/core/search/embeddings/openai-compat.ts:431` | `/v1/embeddings` | `Semaphore(config.concurrency)` per `embed()` call — `:279` |+| `src/core/search/embeddings/zeroentropy.ts:192` | embeddings | `Semaphore(config.concurrency)` per `embed()` call — `:107` |+| `src/core/search/rerank/cross-encoder.ts:85` | cross-encoder rerank | **none** — one request at a time by construction; per-request `AbortController` timeout at `:82,96` |+| `src/core/brain/research/external-fetch.ts:231` | Brave / Tavily web search | unbounded `Promise.all` over `pool.providers` (`src/core/brain/research/research.ts:310`), but the pool is at most 2 |+| `src/core/brain/capture/telegram-capture.ts:418` | `getUpdates` long poll | strictly sequential — each cycle uses the previous offset (`:348-354`) |+| `src/core/brain/capture/telegram-capture.ts:433` | `sendMessage` | sequential, inside the same loop |++`src/core/brain/explorer.ts:324` is a `fetch` *handler* (`Bun.serve`), i.e. inbound, not+an egress site.++Note also that the repo's egress census (`src/core/egress/registry.ts:87-160`,+enforced by `tests/core/architecture/egress-census.test.ts`) covers **export-to-file**+paths only — the seven `o2b … export` verbs. None of the six network sites above is in+it. The registry's own framing says so: "The boundary that exists is the export+surface" (`src/core/egress/registry.ts:8-9`). There is no census of outbound network+calls, so "every place this process talks to a remote host" is not currently a+maintained list.++**Consequence for t_fe4b6be0:** "a daemon-wide ceiling on concurrent LLM inference calls+shared across extraction/synthesis/dream workers" has no subject. There are no+extraction, synthesis, or dream *workers*; there is no inference to cap. The honest+restatement of the task is a ceiling on **concurrent outbound HTTP to the embedding and+rerank providers**, which is a different, smaller, and already-partly-solved problem+(§2).++---++## 2. What concurrency exists today++### 2.1 `dream()` is synchronous **(shape-changing)**++`src/core/brain/dream.ts:101`:++```ts+export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {+```++Not `async`. There is no `await` anywhere in the function. Stage 0+(`scanBrain`, `src/core/brain/dream-scan.ts:124-137`) is `readdirSync` ++`parseFrontmatter` in a plain loop; the apply stage+(`src/core/brain/dream-apply.ts`, via `withDestructiveSnapshot` at `dream.ts:213`) is+synchronous file I/O. The whole pass occupies one turn of the event loop.++That has three consequences a design must absorb:++- There is nothing *concurrent* inside a dream pass to bound. The pass is a single+ serial computation.+- A pressure gate can only run **before** the pass or **at a checkpoint**, never+ "during" it in any preemptive sense.+- Yielding mid-pass would require making `dream()` async, which changes the signature+ of a function called from five sites (`src/core/brain/review-candidates.ts:102`,+ `src/core/brain/dream-stage.ts:241,356,395`, `src/mcp/brain/feedback-tools.ts:467,484`,+ `src/cli/brain/verbs/maintenance.ts:135`).++The same is true of the write path: `applyWriteBatch`+(`src/core/brain/write-batch.ts:206`) is synchronous, and its own header names the cost+at `:51-54` — "performs synchronous file I/O … which blocks the event loop for the+duration of the whole batch; an unbounded [batch] …" — which is exactly why+`MAX_BATCH_OPERATIONS = 100` (`:56`) exists as a hardcoded constant.++### 2.2 The one in-process concurrency limiter++`Semaphore` — `src/core/search/embeddings/http-util.ts:81-100`. Counting semaphore,+FIFO waiter queue, floor of `Math.max(1, n | 0)` at `:85`.++It is **instantiated per call**, not shared: `openai-compat.ts:279` and+`zeroentropy.ts:107` each do `new Semaphore(this.config.concurrency)` inside `embed()`.+So `embedding_concurrency` bounds *one* `embed()` call, not the process. Two overlapping+`embed()` calls would get `2 × concurrency` requests in flight. In practice the indexer+serialises them — `src/core/search/indexer.ts:879-886` is a sequential `for` loop that+awaits each `provider.embed`, deliberately handed a `superBatch = batchSize × concurrency`+(`:877`) so the provider's internal semaphore stays busy. The over-subscription is+therefore latent, not live — but it is the natural seam for a process-wide ceiling.++There is no async mutex, no write queue, no promise-chain serialiser, and no `p-limit`+anywhere else in `src/`.++### 2.3 Every parallel fan-out++Ten `Promise.all` / `allSettled` / `race` sites in all of `src/`:++| Site | Bound | Kind |+|---|---|---|+| `src/core/search/embeddings/openai-compat.ts:312,315` | `embedding_concurrency` (default 4) | **config-driven** |+| `src/core/search/embeddings/zeroentropy.ts:129,132` | `embedding_concurrency` | **config-driven** |+| `src/core/search/rerank-fit-check.ts:319` | `maxQueries`, applied via `.slice` at `:300` | config-driven |+| `src/core/doctor-readiness.ts:536` | fixed `DEFAULT_PROBES` array; per-probe timeout at `:533` | constant |+| `src/core/brain/research/research.ts:310` | `pool.providers`, at most 2 | constant |+| `src/core/search/tuning.ts:95` | fixed 24-point grid (`src/core/search/tuning-store.ts:22-23`) | constant, **but see below** |+| `src/core/search/benchmark.ts:203` | **none** | **unbounded** |+| `src/core/brain/secrets/exec.ts:133` | 3-tuple of one child's streams | not a fan-out |+| `src/core/brain/recall-inject.ts:349` | `Promise.race` timeout | not a fan-out |+| `src/core/search/watch-runner.ts:101` | `Promise.race` grace window | not a fan-out |++`src/core/search/benchmark.ts:203` is the one genuinely unbounded fan-out: one concurrent+hybrid `search()` per query in an operator-supplied dataset, each a SQLite read, guarded+only by a non-emptiness check at `:194-196`. Reached through `tuneRecall` it is+amplified 24×. The comment at `:186-187` justifies the concurrency on *correctness*+grounds (the queries are read-only) and does not address resource bounding.++### 2.4 Locks++There is **no single shared lock module**. Three primitives plus one lease, plus six+copy-pasted retry loops.++| Module | Primitive | Discipline |+|---|---|---|+| `src/core/reliability/lock.ts:22-50` | `proper-lockfile`, async | stale 30 s (`:32`), 3 retries × 250 ms (`:34-39`); **fail-closed** → `FileLockError` (`:41-43`). Only 2 callers: `src/core/brain/schema-mutate.ts:197`, `src/core/brain/health-baseline.ts:58` |+| `src/core/brain/sync-lockfile.ts:65-80` | hand-rolled `openSync(…, "wx")`, **not** proper-lockfile | **no retry, no backoff, no stale timeout** — by design (`:13-15`). ~10 callers; the Brain write path |+| `src/core/search/store/writer-lock.ts:37,64` | `proper-lockfile`, sync + async | stale 60 s (`:18`); async heartbeats mtime every 30 s (`:29,71`). Sync: 10 × `Bun.sleepSync(50)` (`:37-52`). Async: 3 retries × 1000 ms (`:64-77`). **fail-closed** → `SearchError("INDEX_LOCKED")` (`:32-35`) |+| `src/core/brain/maintenance/lease.ts:59-83` | SQLite conditional upsert | TTL-based, not mtime-based; **fail-closed** (work skipped, never done unlocked) |++Per-call-site locks with hardcoded, mutually inconsistent policies:+`src/core/brain/log.ts:237-252` (stale 10 s, 10 × 50 ms, fail-closed),+`src/core/brain/triggers/store.ts:760-768` (**zero retries**),+`src/core/brain/secrets/store.ts:86-111` (20 × 25 ms),+`src/core/brain/portability/profiles.ts:147-168` (10 × 50 ms),+`src/core/brain/inline-rewrite.ts:55-59` (30 retries, factor 1.2, 30→500 ms — the most+generous in the repo; it locks the **parent directory** because a per-file lock would+race `atomicWriteFileSync`'s temp sibling, `:17-19,50-51`).++Three sites are **fail-open** and must be named because a pressure gate would sit+next to them:++- `src/core/config.ts:453-457` and `:536-543` — after exhausting attempts, `release`+ stays `undefined` and the code **proceeds unlocked**. Documented as intentional at+ `:435-440`; the cost is a duplicate device-id, absorbed downstream by+ `src/core/brain/log.ts:254-273`.+- `src/core/search/store/lifecycle.ts:81-88` — `restoreFromBakIfMissing` swallows the+ lock failure and returns **without restoring** (`:73-76`).+- `src/core/brain/lineage/ledger.ts:772-786` — drops the observation but records a typed+ gap (`lockBusy` / `lockFailed`) rather than staying silent. This is the honest pattern+ the operator's "no misleading fallback" rule points at.++Stale windows are inconsistent — 60 s / 30 s / 10 s / **∞**. `sync-lockfile.ts` has no+stale concept at all: recovery is only the `process.on("exit")` sweep (`:40-53`), so a+SIGKILL during a Brain write leaves a `.lock` that nothing ever reclaims. It is+*surfaced*, not cleared, by `scanStaleLocks` (`:120-125`) →+`src/core/brain/doctor/uncertainty-probes.ts:138`. The single exception that breaks a+stale lock is `src/core/brain/lineage/ledger.ts:929-941` (`GAP_LOCK_STALE_MS = 60_000`,+`:119`).++`src/core/brain/metrics.ts:11-14` is the *absence* of a lock, deliberately: single-line+`O_APPEND` writes (`:101`) that interleave rather than race. The task hint calls this a+concurrency control; it is the opposite — a documented decision not to have one.++Atomic writes and locks are **orthogonal and composed by the caller**.+`src/core/fs-atomic.ts` takes no lock, and says so at `:49-50`: `renameSync` "clobbers an+existing target … **No exclusivity guarantee**". Atomicity prevents torn files; it does+not prevent lost updates.++---++## 3. Cancellation++### 3.1 `AbortSignal` exists, is well-designed, and is not wired to the dream pass **(shape-changing)**++`src/core/brain/safeguard.ts` already models exactly the contract a teardown needs:++- `SafeguardAbortError` (`:51-59`) — an intentional stop, deliberately distinct from+ `SafeguardTimeoutError` so "the watch shutdown coordinator can treat an intentional+ abort as a clean stop rather than a failure" (`:46-49`).+- `CreateSafeguardOptions.signal?: AbortSignal` (`:91`).+- `checkpoint()` checks abort **in priority over** the deadline (`:117-122`).+- `throwIfAborted(signal, operation)` (`:66-68`) for hot loops holding a bare signal.++**No production call site passes `signal`.** All six construct with `operation` ++`timeoutMs` only: `src/cli/brain/verbs/dream.ts:204-207`,+`src/cli/brain/verbs/bridges.ts:155-158`, `src/cli/brain/verbs/clusters.ts:256-259`,+`src/cli/brain/verbs/maintenance.ts:120-123`, `src/cli/search/verbs/indexing.ts:59-62`,+`src/mcp/brain/admin-tools.ts:298-301`. `SafeguardAbortError` is therefore unreachable in+production.++`throwIfAborted` has exactly two callers, both in the indexer:+`src/core/search/indexer.ts:330` (between files) and `:883` (between embedding batches).+Its signal comes from `IndexVaultOptions.signal` (`:123`, `:800`).++**So: on-demand cancellation exists on exactly one path — reindex under+`o2b search watch`. The dream pass has no cancellation mechanism other than the+cooperative deadline.**++### 3.2 The one working teardown, and it is a good model++`IndexWatchRunner` — `src/core/search/watch-runner.ts:44-103`. Single-flight+(`flush()` returns the in-flight promise, `:68-86`), then `shutdown()` (`:93-102`):+stop accepting flushes, `controller.abort()`, `await Promise.race([inflight, wait(graceMs)])`+so a wedged pass cannot block exit forever. Wired at `src/cli/search/verbs/watch.ts:93-106`,+where `process.once` is deliberate — a *second* SIGINT hits the default handler and+force-kills (`:99-100`).++### 3.3 Process signal handling++Four sites, all in one-shot or operator-launched foreground commands:++| Site | Behaviour |+|---|---|+| `src/cli/search/verbs/watch.ts:105-106` | **drains, bounded** (above) |+| `src/cli/brain/verbs/explorer.ts:57-64` | closes the server; does **not** drain in-flight requests. `.catch().finally()` so a rejected `close()` cannot hang Ctrl-C (`:54-56`) |+| `src/cli/brain/verbs/telegram-capture.ts:60-61,75-76` | sets a cooperative `stop` flag checked **between** cycles (`src/core/brain/capture/telegram-capture.ts:346,374`). Does **not** abort the in-flight 30 s long poll, so SIGINT can take a full poll timeout to land |+| `src/core/brain/sync-lockfile.ts:43`, `src/core/search/store-exit.ts:34` | `process.on("exit")` cleanup sweeps, not signal handlers; explicitly not SIGKILL-safe (`store-exit.ts:17-18`) |++The MCP stdio server has **no signal handler at all** — `src/mcp/stdio.ts:37-70`, a+`for await` over stdin lines that `return 0`s on EOF. Closing the pipe is the entire+shutdown mechanism.++### 3.4 What an interrupted dream pass leaves behind++Three artifacts, and none of them is resumable state:++1. **A dangling workrun journal.** `src/core/brain/dream-workrun.ts:50-64` writes one+ JSONL line per phase to `Brain/log/dream-runs/<run-id>.jsonl`. The module header+ states the contract at `:9-13`: "Recovery is **non-resuming** - the next dream pass+ processes the inbox fresh; the dangling file serves as forensic evidence, not a+ resumable state machine." Markers are truthful — each is written where that phase's+ durable output has landed (`src/core/brain/dream.ts:225-234`). No fsync per phase+ (`dream-workrun.ts:20-22`).+2. **A pre-run snapshot that is not automatically applied.**+ `withDestructiveSnapshot` (`src/core/brain/snapshot-gate.ts:360-377`) takes the+ archive *before* `op` runs, then: "If it throws, the error propagates and the archive+ above stays exactly where it is: it is the recovery point the caller now needs"+ (`:371-373`). **There is no auto-rollback.** Restoring is an operator action.+3. **Partially applied disk state.** Each individual write is atomic+ (`src/core/fs-atomic.ts`), so no file is torn, but the *set* of writes is not+ transactional. A pass interrupted between `synthesize` and `heal` leaves the earlier+ phases committed.++**`idempotency-ledger.ts` is not a dream-resumption ledger. (shape-changing)** The task+body cites `src/core/brain/idempotency-ledger.ts:23-167` as if it were run state. Its+header (`:1-33`) is explicit: it is a **client-supplied idempotency-key** store for the+feedback/signal *write* path, deduping "a retried or double-delivered tool call". Its+concurrency boundary is stated at `:23-29`: check-and-append is atomic within one+month shard under `acquireLockSync`; two genuinely-concurrent first writers of the same+key can both observe "absent" and both proceed. `dream()` never touches it.++---++## 4. Config surface++There are **two** config files, and they are not interchangeable.++| | Plugin / device config | Vault config |+|---|---|---|+| Path | `$OPEN_SECOND_BRAIN_CONFIG` → `$XDG_CONFIG_HOME/open-second-brain/config.yaml` → `~/.config/…` — `src/core/config.ts:120-131` | `<vault>/Brain/_brain.yaml` — `BRAIN_CONFIG_FILE` at `src/core/brain/path-constants.ts:156`, joined by `brainConfigPath()` at `src/core/brain/paths.ts:196-198` |+| Shape | flat `Readonly<Record<string,string>>` — `src/core/types.ts:10-14` | nested typed `BrainConfig` |+| Reader | `discoverConfig()` — `src/core/config.ts:199-212` | `loadBrainConfig()` — `src/core/brain/policy/load.ts:57-94` |+| Parser | `parseSimpleYaml` — `src/core/config.ts:153-174` | indent-aware parser, `src/core/brain/yaml-parse.ts`; policy at `src/core/brain/policy.ts:1-33` |+| Holds | `embedding_*`, `search_*`, `safeguard_timeout_*` | `dream.*`, `guardrails.*`, `lessons.*`, … |+| Ratchet test | **none** | **yes** |++### The idiom for a bounded numeric key++**In `_brain.yaml` — the canonical one.** `readBoundedInt(map, key, min, max, field, source)`+at `src/core/brain/policy/field-checks.ts:142-153`. Absent → `undefined`;+present-and-bad → `BrainConfigError`. The policy is stated at `field-checks.ts:5-8`:++> 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.++Worked example, `src/core/brain/policy/blocks/lessons.ts`: default/min/max constants+`:19-27`, `KNOWN_KEYS` `:29`, `openBlock(ctx, BLOCK)` `:32`, three `readBoundedInt`+calls `:35-58`, then `warnUnknownKeys(ctx, map, KNOWN_KEYS, BLOCK)` `:59` — that last+call is what registers the sub-keys in the key index+(`src/core/brain/policy/key-index.ts:33-46`, `:100-116`), which is what the ratchet reads.++**In the plugin config — fail-hard variant** (`embedding_*`): `DEFAULTS` literal+`src/core/search/index.ts:150-181`; parse via+`parseInteger(envOrConfig(env, config, "<ENV>", "<key>"), DEFAULTS.x, "<key>", { min: 1 })`+— `embedding_concurrency` at `:508-513`; re-validated after programmatic overrides by+`validateIntegerRange` at `:277-298`, called at `:338-340`. Helpers in+`src/core/validate.ts:17-40` (`parseInteger` — null → default, blank/non-integer/+non-finite/out-of-range → `throw`) and `:100-111` (`envOrConfig` — env wins, empty+string counts as unset on both sides). Bad value surfaces as CLI exit 2 with the key+name on stderr, pinned by `tests/cli/search.test.ts:219-223` and+`tests/core/search/config.test.ts:303-314`.++**In the plugin config — fail-soft variant.** `resolveSafeguardTimeoutMs`+(`src/core/brain/safeguard.ts:131-148`) with `parseSeconds` (`:150-156`) returns+`undefined` on a bad value and **silently falls through to the next source**; it even+swallows `ConfigReadError` (`:136-140`). Same shape at `src/core/config.ts:1002-1009`+and `:1044-1051`. Both disciplines are live in the repo; a new key must pick one+deliberately, and for a *safety* ceiling the fail-hard form is the one that matches the+operator's rule.++### The ratchet++`tests/core/brain/config-template-ratchet.test.ts` — for `_brain.yaml` only. Keys are+enumerated **by running the validator** (`brainConfigKnownKeys()`,+`src/core/brain/policy/validate.ts:214-228`), not from a hand-kept list. Four assertions+a new key must satisfy: top-level coverage `:191-196`, sub-key coverage `:198-211`,+reverse direction (template names no unknown key) `:213-226`, every omission carries a+written reason `:228-233`. Plus `:245-247` — the live surface must stay byte-identical+to the frozen v1.38.0 `LEGACY_TEMPLATE` (`:67-111`), so **a new key must be emitted+commented, not live**, and `:249-258` asserts non-live keys appear nowhere uncommented.++**There is no equivalent ratchet for the flat plugin config**: no known-key list, no+unknown-key warning, no docs-coverage test. There is also no JSON schema for either file+(`schemas/` holds only four *report* schemas). And there is no canonical env-var list:+104 distinct `OPEN_SECOND_BRAIN_*` names appear in `src/`, 28 appear in+`docs/cli-reference.md`; only seven are hoisted into named constants. The naming+convention (`OPEN_SECOND_BRAIN_` + upper-snaked key) is unenforced and frequently+abbreviated — `embedding_batch_size` → `OPEN_SECOND_BRAIN_EMBEDDING_BATCH`,+`safeguard_timeout_seconds` → `OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`.++---++## 5. Host-pressure measurement++**Nothing in this repo measures host pressure. (shape-changing)**++`node:os` is imported at 14 sites in `src/`, and every single one is `homedir` or+`tmpdir`. There is **zero** use of `os.loadavg()`, `os.cpus()`, `os.freemem()`,+`os.totalmem()`, or `os.availableParallelism()`. There is no `/proc` read, no cgroup+read, and no `process.cpuUsage()` / `process.memoryUsage()` call in a gating position.++### What exists instead, and it is most of the feature++`src/core/brain/maintenance/lane.ts` is already a "gate background work on measured+pressure" lane. Its header (`:1-19`) names three gates:++1. **window** — a configured local-time hour window, tz-aware, midnight-wrap aware+ (`dailyWindowContains`, `:82-97`); unconfigured = always open.+2. **busy** — `evaluateGates` at `:99-113` counts recall-telemetry records in a lookback+ window: `MAINTENANCE_BUSY_MINUTES = 10`, `MAINTENANCE_BUSY_THRESHOLD = 5` (`:29-31`).+ Over threshold → `"skipped:busy"`. **This is a measured-pressure gate — the metric is+ interactive query rate, not host CPU.**+3. **lease** — `acquireLease` (`src/core/brain/maintenance/lease.ts:59-83`), never+ bypassable even with `--force`, "because two concurrent heavy passes on one vault is+ the exact failure this lane exists to prevent" (`lane.ts:11-13`).++Tasks then run **sequentially by design** — `lane.ts:149` ("the lane exists to serialize+heavy work") — stale-first, each attempt journaled with a typed verdict.++So t_992f0c33's design is not a new subsystem. It is **a fourth gate in `evaluateGates`**+plus a fourth `MaintenanceVerdict`. Everything else — the lease, the journal, the+force-bypass semantics, the sequential runner — already exists.++### Portability, stated honestly++- `os.loadavg()` on Linux and macOS returns real 1/5/15-minute run-queue averages.+- **On Windows, Node and Bun return `[0, 0, 0]`** — a constant, not a measurement. A+ gate keyed on it would read "always idle" and never fire.+- Inside a container, `os.loadavg()` reports the **host's** run queue, not the cgroup's.+ `os.cpus().length` likewise reports host CPUs, not the CPU quota. A load-average gate+ on a shared host or a CPU-limited container is measuring something other than the+ pressure the operator cares about. (This is a platform fact, not a claim about this+ repo — nothing in `src/` reads either value today.)++**On Windows specifically, this repo already refuses rather than guesses.**+`src/core/config.ts:35` declares `UNSUPPORTED_CONFIG_PLATFORMS = ["win32"]`, and the+error class at `:45-59` explains why in exactly the terms the operator's rule uses:++> the alternative - returning `C:\Users\…\.config\open-second-brain\config.yaml` - is a+> plausible-looking answer to a question this build cannot answer++That is the precedent a pressure gate must follow. `os.loadavg()` returning `[0,0,0]` on+Windows is the same class of plausible-looking wrong answer. The honest alternatives, in+order of preference:++1. **Name the metric as unavailable and leave the gate open**, reporting a verdict that+ says *why* — e.g. a `MaintenanceVerdict` value meaning "pressure unmeasurable on this+ platform", journaled like every other verdict (`lane.ts:129`). The operator sees that+ the gate did not evaluate. This is not a silent no-op.+2. **Refuse to enable the gate** when the metric is degenerate, the way+ `UnsupportedPlatformError` refuses, pointing at the config key to unset.+3. Do **not** substitute `cpus().length` or a synthetic proxy and present it as load.++Option 1 is the one that composes with the existing lane, because the lane already has a+verdict vocabulary and a journal to carry the reason. Note `src/core/brain/gates/durability.ts:156`+and `tests/core/architecture/verdict-vocabulary-census.test.ts` — verdict tokens are a+maintained namespace here, so a new one has a home and a ratchet.++Practically, on the platforms this build actually supports (POSIX only, per+`config.ts:35`), `os.loadavg()[0] / os.availableParallelism()` is a measurable,+dependency-free normalised pressure ratio. That is the only such metric available+without a native dependency.++---++## 6. Startup, crash-loop, thundering herd++### 6.1 There is no daemon **(shape-changing)**++It is a stated architectural invariant, not an accident:++- `docs/architecture.md:229` — "Filesystem-first. No database, no daemon."+- `src/core/brain/anticipatory-cache.ts:14` — "Hard constraints honored here: NO daemon+ and NO file watcher (refresh piggybacks on events that already fire)"+- `src/mcp/artifact-store.ts:24` — "no daemon, matching the 'no hidden process' convention"+- `src/cli/partner-codegraph-cron.ts:6` — "it refuses daemons and filesystem watchers for+ this purpose"+- `docs/plans/2026-05-18-brain-maturity-design.md:690-691` — a *rejected* design item:+ "`o2b search reindex --watch` long-running daemon. The OSB invariant 'no daemon' stands."++Entry points: `scripts/o2b` → `src/cli/main.ts:1004-1013` (one-shot, `process.exit(code)`);+`scripts/vault-log`, `scripts/o2b-hook`, `bin/o2b-discipline-report`, `hooks/*.ts` — all+one-shot. `cli.py:16` is a re-export shim, not a process. `src/openclaw/index.ts:36-37`+is an in-process plugin owning no loop, timer, or subprocess.++Three operator-launched foreground processes, each living and dying with the terminal or+client that started it: the MCP server (`src/mcp/stdio.ts:37-70` stdio by default per+`src/cli/main.ts:583`; HTTP opt-in at `src/mcp/http.ts:53-57`), the explorer HTTP server+(`src/core/brain/explorer.ts:320-340`, loopback-only, default port 7777), and+`o2b search watch`. Plus the Telegram long-poll bot, whose own verb doc says+"Never invoked from a hook; nothing runs implicitly"+(`src/cli/brain/verbs/telegram-capture.ts:8-9`).++The MCP server holds process-scoped state (`src/mcp/server.ts:97-113`: tool table,+route-metrics flag, an `ArtifactStore` keyed `run-${process.pid}-${Date.now()}`), but+holds **no open SQLite handle** — every writer is opened and closed per call+(`src/core/search/store-exit.ts:20-23`).++**"Startup grace period" and "crash-loop recovery" have no daemon to attach to.** The+portable analogue is per-invocation: a gate evaluated at the top of a one-shot command,+with the *cross-invocation* state kept on disk (the lease and the journal already are+exactly that).++### 6.2 No scheduler is shipped++No cron file, no `.service`, no `.timer`, no plist anywhere in `install/`, `templates/`,+`scripts/`, or `.claude-plugin/`. `templates/install/` contains one file+(`aider-context.md.tmpl`).++The dream pass has exactly three trigger paths, all caller-initiated:+MCP tool `brain_dream` (`src/mcp/brain/feedback-tools.ts:296`, registered `:760`, whose+own description at `:762` says "Typically scheduled via cron"); CLI+`o2b brain dream` (`src/cli/brain.ts:193-194` → `src/cli/brain/verbs/dream.ts`);+and `o2b brain maintenance run` (`src/cli/brain/verbs/maintenance.ts:1-14`, "Designed as+the cron entry point", calling `dream()` at `:135`). **No hook invokes it** — grep across+`hooks/`, `.githooks/`, `install/`, `templates/` finds only prose and one starter-vault+fixture.++What the repo ships instead is cron **recipes** — text on stdout that installs nothing.+`src/cli/cron-recipe.ts:6-10`: "A recipe is text on stdout and nothing else. … No verb+that renders a recipe writes a file, spawns a scheduler, or installs anything". The two+consumers are `search reindex --cron-template` and `partner codegraph resync+--cron-template`; neither is dream. The one verb that writes a real schedule,+`o2b discipline install` (`src/cli/discipline-install.ts:17,101,141-163`), mutates an+**external Hermes** job file and does not schedule dream. `README.md:53` states the+ownership boundary: "Hermes Agent owns the schedule (dream cron, daily digests…)".++### 6.3 The thundering herd is real, and it is not the dream pass **(shape-changing)**++`ensureVaultCurrent(vault, { background: true })` is called at **two** startup points:++- `src/cli/main.ts:648` — every full-scope MCP server start;+- `hooks/active-inject.ts:161` — the `SessionStart` hook.++ **Correction (implementation, U5).** This note originally said "the+ `SessionStart` **and** `PostCompact` hook". That is wrong: the call is+ guarded by `if (hookEventName === "SessionStart")` at+ `hooks/active-inject.ts:158`, so a PostCompact event spawns nothing. The+ module IS registered for both events, which is where the error came+ from - reading the registration rather than the branch. The herd is+ therefore one spawn per session start plus one per MCP server start,+ not two per session. It is still a herd, and the losers still died into+ a discarded stderr, so the unit's subject is unchanged; the multiplier+ is smaller than this note claimed.++In background mode it calls `spawnDetachedReindex`+(`src/core/maintenance/ensure-current.ts:87-99`): `Bun.spawn(["…/o2b", "search",+"reindex", …])` with `stdin/stdout/stderr: "ignore"`, then `proc.unref()`.++The source already acknowledges the collision — `src/core/search/indexer.ts:930-937`:++> a second concurrent reindex — the double-reindex a schema-bump upgrade triggers when+> CLI and the long-lived MCP server both self-heal at once — waits-or-bails on the SAME+> lock++The mitigation is `acquireWriterLock(config.dbPath)` (`indexer.ts:937`), whose async+policy is **3 retries × 1000 ms** (`src/core/search/store/writer-lock.ts:64-77`), then+`SearchError("INDEX_LOCKED")`. In a detached process with `stderr: "ignore"`, that throw+goes **nowhere the operator can see**. So today: N agent sessions starting after an+upgrade produce N detached reindexes; one runs, N−1 spin ~3 s and die silently. That is+the concrete thundering herd this task should address, and its subject is+`ensure-current.ts`, not `dream.ts`.++### 6.4 There is no crash-loop detection, and no supervisor++No PID file, no singleton-instance guard by PID, no restart logic, no repeated-failure+counter that survives a process. Two mechanisms come closest:++- **Crash recovery by lease expiry.** `src/core/brain/maintenance/lease.ts:1-8`: "a+ crashed worker's lease frees itself by expiry, never by manual cleanup". TTL+ `MAINTENANCE_LEASE_TTL_MS = 30 min` (`lane.ts:26`). `acquireLease` fails closed on a+ non-positive TTL (`lease.ts:60-64`) — "a non-positive TTL would mint an already-expired+ lease and every contender would acquire at once - silent loss of mutual exclusion."+ PIDs are written into `sync-lockfile` bodies but are **diagnostic only**+ (`src/core/brain/sync-lockfile.ts:88-91`).+- **The only exponential backoff at process level** is the Telegram transport ladder:+ `transportBackoffMs` (`src/core/brain/capture/telegram-capture.ts:81-84`, base doubling,+ capped at `TRANSPORT_BACKOFF_MAX_MS = 30_000` at `:70`), applied at `:371`, with the+ rationale at `:362-366` — "so a persistent outage … settles into a gentle retry cadence+ instead of a hot loop that hammers the API and pins the CPU, which matters because+ production runs with no maxCycles". `consecutiveFailures` is a local variable+ (`:336`); it resets to zero on every process start, so it is **not** crash-loop+ recovery.++### 6.5 A watchdog that probably cannot fire++`hooks/lib/process-ceiling.ts` is the repo's existing "nothing runs unwatched" primitive:+a spawned hook arms an `unref`ed timer on **itself** and `exit(0)`s at the deadline+(`:60-80`), disarmed in a `finally`. Default `DEFAULT_HOOK_CEILING_MS = 55_000` (`:23`),+floor 1000 ms, and a bad `OPEN_SECOND_BRAIN_HOOK_CEILING_MS` falls back to the default+"so a typo can never disable the watchdog" (`:28-40`). Seven hooks arm it+(`active-inject`, `session-capture`, `recall-inject`, `nav-inject`, `pretool-orient`,+`gap-agenda`, `gap-promote`).++But **all 15 hook entries in `hooks/hooks.json` set `"timeout": 10`** (verified: 15+occurrences, all value 10). If the host enforces that 10-second timeout by killing the+hook process, the 55-second self-ceiling can never fire under the shipped configuration.+The module doc at `:19-20` calls the host timeout "a second line of defence"; under+`hooks.json` as shipped it is the *first* and only one. This is worth resolving as part+of a "nothing runs unwatched" release, since it is the one watchdog the repo already has.++The module also states the limit any deadline design inherits (`:17-19`): "a JavaScript+timer cannot interrupt a fully-synchronous CPU hang on a single thread". Given §2.1 —+`dream()` is fully synchronous — that limit applies to the dream pass directly.++---++## Divergences++Points where the task framing does not survive contact with the source.++| # | Task claim | Source |+|---|---|---|+| 1 | t_fe4b6be0: cap "concurrent LLM inference calls" | The process makes **no** chat-model call. `src/core/doctor-readiness.ts:40-44`; the `needs-llm-step` envelope contract at `src/core/brain/rollup-ladder.ts:63-72`, `src/core/brain/diarization.ts:83`, `src/core/brain/write-session/engine.ts:98`. Inference happens in the caller's process, after `dream()` returns |+| 2 | "shared across extraction/synthesis/dream **workers**" | There are no workers. `dream()` is a **synchronous function** — `src/core/brain/dream.ts:101`. `src/core/brain/maintenance/lane.ts:149`: "Sequential by design: the lane exists to serialize heavy work" |+| 3 | `src/core/brain/dream-phases.ts:19-34` is "the multi-phase LLM pipeline" | It is a **label enum and a reporting order**. Nothing executes. `src/core/brain/dream-step.ts:7-11` is explicit: "The five `DREAM_PHASE` labels are a REPORTING layer … there is no function named `close`, `reconcile`, `synthesize`, `heal` or `log` to call" |+| 4 | Existing concurrency controls are "FILE-LEVEL locks serializing writes" (`inline-rewrite.ts:17,51`, `log.ts:310`, `metrics.ts:13`) | Two of the three are right; the third is inverted. `src/core/brain/metrics.ts:11-14` documents the deliberate **absence** of a lock (bare `appendFileSync` at `:101`, relying on `O_APPEND` atomicity). And `inline-rewrite.ts` locks the **parent directory**, not the file (`:17-19`) |+| 5 | `src/core/brain/idempotency-ledger.ts:23-167` is dream run state | It is a **client-supplied idempotency-key store for the signal write path** (`:1-33`). `dream()` never touches it. The dream pass's own journal is `src/core/brain/dream-workrun.ts`, explicitly **non-resuming** (`:9-13`) |+| 6 | t_992f0c33: "startup crash-loop recovery" and "startup grace period" | **No daemon exists.** `docs/architecture.md:229`; `src/cli/main.ts:1004-1013`. Every entry point is one-shot or client-scoped. There is no PID guard, no supervisor, and no cross-process failure counter |+| 7 | The thundering herd is about the dream pass | It is about **reindex**: `src/core/maintenance/ensure-current.ts:87-99` spawns a detached `o2b search reindex` from *both* MCP startup (`src/cli/main.ts:648`) and the `SessionStart` hook (`hooks/active-inject.ts:161`; see the correction in §6.3 - PostCompact is registered but branches away). The collision is already named in-source at `src/core/search/indexer.ts:930-937`. Dream is never triggered automatically at all |+| 8 | "a write-batch primitive that yields when pressure is high" | `brain_write_batch` already exists and is **all-or-nothing atomic** — `src/core/brain/write-batch.ts:206`, `src/mcp/brain/write-batch-tools.ts:1-16`. A batch that yields mid-way would break the contract the tool is named for. Its bound is a hardcoded `MAX_BATCH_OPERATIONS = 100` (`:56`), justified precisely as a blocking-window cap (`:51-54`) |+| 9 | (implied) a pressure gate is new ground | `evaluateGates` (`src/core/brain/maintenance/lane.ts:99-113`) is already a measured-pressure gate — the metric is interactive query rate, not host load. The lease, the journal, the verdict vocabulary and the `--force` semantics all exist |++---++## What a design must not assume++1. **Do not assume an inference call to cap.** If t_fe4b6be0 survives at all, its subject+ is outbound HTTP to the embedding and rerank providers — five `fetch` sites (§1) — not+ model inference. Naming it "inference" in code or config would be a hardcoded+ falsehood about what the process does.++2. **Do not assume anything is concurrent inside a dream pass.** `dream()` is+ synchronous end to end (`src/core/brain/dream.ts:101`). A ceiling has nothing to+ count there. Making it async to enable yielding is a signature change across five+ call sites and would forfeit the byte-reproducibility the module is built on+ (`dream.ts:253-255`).++3. **Do not assume a process to keep state in.** No daemon, no scheduler, no supervisor.+ Any counter that must survive — a failure streak, a herd token, a grace deadline —+ has to live on disk. The existing on-disk precedents are the SQLite lease+ (`src/core/brain/maintenance/lease.ts`) and the lane journal+ (`src/core/brain/maintenance/journal.ts`); a new in-memory counter would reset on+ every invocation, exactly as `consecutiveFailures` does at+ `src/core/brain/capture/telegram-capture.ts:336`.++4. **Do not assume `os.loadavg()` means what it says.** It is `[0,0,0]` on Windows and+ reports the *host* run queue inside a container. This repo's established answer to an+ unanswerable platform question is to refuse by name+ (`src/core/config.ts:35,45-59`), not to return a plausible number. A gate that+ evaluates to "idle" on a platform where the metric is degenerate is precisely the+ silent-no-op fallback the standing rules forbid — it would be indistinguishable from a+ genuinely quiet host.++5. **Do not assume a new subsystem is needed for pressure gating.** Add a fourth gate to+ `evaluateGates` and a fourth verdict token. The verdict namespace is already+ ratchet-tested (`tests/core/architecture/verdict-vocabulary-census.test.ts`), the+ journal already records every verdict (`lane.ts:129,136`), and `--force` already has+ defined semantics (soft gates bypassable, lease never — `lane.ts:15-17,126-138`).++6. **Do not assume a new config key is free.** A `_brain.yaml` key must go through a+ block parser under `src/core/brain/policy/blocks/`, register via `warnUnknownKeys`,+ be templated in `BRAIN_CONFIG_TEMPLATE` **commented, not live** (the frozen-surface+ assertion at `tests/core/brain/config-template-ratchet.test.ts:245-247`), and satisfy+ four ratchet assertions (`:191-233`). A plugin-config key has no ratchet at all —+ which means forgetting to document it fails nothing, so document it deliberately.++7. **Do not assume a bad value may fail soft.** Both disciplines exist+ (`src/core/validate.ts:17-40` throws; `src/core/brain/safeguard.ts:150-156` falls+ through silently). For a ceiling or a gate, silent fallback means the operator+ believes a bound is in force that is not. Follow `field-checks.ts:5-8`.++8. **Do not assume cancellation needs building.** `src/core/brain/safeguard.ts` already+ has `signal`, `SafeguardAbortError`, and abort-beats-deadline priority (`:91,117-122`);+ `IndexWatchRunner` (`src/core/search/watch-runner.ts:44-103`) already has+ single-flight + abort + bounded grace. The gap is **wiring**: no call site passes a+ signal, and `throwIfAborted` has only two callers, both in the indexer. Wiring the+ existing seam is a much smaller change than the task implies — and it is a real one,+ because `SafeguardAbortError` is currently dead code in production.++9. **Do not assume an interrupted pass can be resumed.** The workrun journal is forensic+ by explicit contract (`src/core/brain/dream-workrun.ts:9-13`), and+ `withDestructiveSnapshot` does not auto-rollback+ (`src/core/brain/snapshot-gate.ts:371-373`). A "coordinated teardown" therefore means+ *stopping cleanly at a checkpoint with the journal telling the truth about what+ landed* — which the current markers already do (`dream.ts:225-234`) — and not+ *resuming later*.++10. **Do not add a watchdog without checking it can fire.** `hooks/hooks.json` sets+ `"timeout": 10` on all 15 entries while `hooks/lib/process-ceiling.ts:23` defaults to+ 55 s. Before adding a second watchdog, reconcile the one that exists.diff --git a/docs/brainstorm/nothing-runs-unwatched/recon/durability-and-ownership.md b/docs/brainstorm/nothing-runs-unwatched/recon/durability-and-ownership.mdnew file mode 100644index 00000000..9827732c--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/recon/durability-and-ownership.md@@ -0,0 +1,848 @@+# Recon: durability and ownership (t_b5fa7344, t_1037d94e)++Reconnaissance only. Every claim below carries an anchor that was read on+branch `feat/nothing-runs-unwatched` (base v1.47.0). Where a question could+not be settled from source, it says so.++---++## 1. The install/verify success path, end to end++### 1.1 There is no single install "success" surface. There are four.++`o2b install` is one verb with four terminal renderings, chosen in+`cmdInstall` at `src/cli/install/install.ts:158-178`:++| mode | selector | human renderer | machine renderer |+|---|---|---|---|+| detect | no `--target`, no `--check` | `renderDetectTable` `src/cli/install/render.ts:23` | `renderDetectJson` `src/cli/install/render.ts:57` |+| plan | `--target X` | `renderPlan` `src/cli/install/render.ts:70` | inline literal `src/cli/install/install.ts:227` |+| apply | `--target X --apply` | `renderApplyResult` `src/cli/install/render.ts:87` | `renderApplyJson` `src/cli/install/render.ts:107` |+| verify | `--check` | `renderVerifyTable` `src/cli/install/render.ts:111` | `renderVerifyJson` `src/cli/install/render.ts:125` |++A fifth, unrelated verb also prints an install success: `o2b install-cli`+(symlink installer) renders through `renderInstallResult`+`src/cli/install-cli.ts:280`, dispatched at `src/cli/main.ts:751-756`. It+has **no `--json` at all** — `parseFlags` accepts only `--bindir`+(`src/cli/main.ts:752`). The task hint names `install-cli.ts:280` as the+target surface; that is the surface with no machine channel to add a field+to.++### 1.2 The `--json` payloads are not one shape++- Detect: `{ schema_version: 1, targets: [{target,status,config_path,notes}] }`+ — `src/cli/install/render.ts:58-67`.+- Verify: `{ schema_version: 1, targets: VerifyResult[] }` — `src/cli/install/render.ts:126`.+ Note this serialises `VerifyResult` **raw**, so the wire keys are+ `target`, `status`, `details`, `fix_hint` (`src/core/install/types.ts:126-131`).+- Plan: `{ schema_version: 1, plan }` — `src/cli/install/install.ts:227`,+ built inline rather than in `render.ts`.+- Apply: `JSON.stringify(result)` — `src/cli/install/render.ts:108`. **No+ `schema_version` key.** This is the only `--json` install payload without+ one, and it is the payload of the one mode that actually changed the+ machine.++### 1.3 Shared result types++No. Four unrelated result types, all in `src/core/install/types.ts`:+`DetectResult` (:64), `InstallPlan` (:77), `ApplyResult` (:113),+`VerifyResult` (:126). They share only `target: string`. A field added to+"the install result" has to be added to each of them, or carried beside+them by the CLI layer.++### 1.4 Is there a golden / snapshot / parity test on the JSON?++**No JSON parity or golden test exists.** What exists:++- `tests/cli/install-verb.test.ts:64-77` asserts only three things about+ detect `--json`: `schema_version === 1`, `targets` is an array, length > 0.+ Nothing asserts field names, and nothing at all asserts the apply, plan or+ verify payloads.+- `tests/docs/install-verify-conformance.test.ts` is a **human-output**+ conformance test: it installs each target into a temp home/vault, calls+ `verify()`, renders through the same `renderVerifyTable` the CLI uses, and+ diffs against an `<!-- expected-output: o2b install --check --target <t> -->`+ block in `install/<runtime>.md` (header docblock, lines 1-19). So the+ **human** verify surface is pinned byte-for-byte against documentation;+ the JSON twin is pinned by nothing.++Consequence for the design: adding a line to `renderVerifyTable` breaks+every `install/<runtime>.md` expected-output block and that test will name+the documents to edit. Adding the same information to `renderVerifyJson`+breaks nothing and is therefore the half that can silently be forgotten.+Whatever mechanism is chosen must make the two impossible to add+separately, because no test currently notices if only one lands.++### 1.5 Where a two-part close would have to be printed++- Verify success: `runCheck` at `src/cli/install/install.ts:258-289`. It+ already refuses an unset vault by name (`:263-268`) and returns+ `exitCodeForVerify(results)` (`:288`, defined `:305-309`). "Passing" here+ means no `drift` and no `mcp-unreachable`; `not-installed` is also exit 0+ (`:296-299` docblock states this deliberately). So "on a passing verify"+ includes the case where **nothing is installed**, which is a poor place to+ congratulate the operator on owning their brain.+- Apply success: `runTarget` at `src/cli/install/install.ts:234-241`.+- `install-cli` success: `cmdInstallCli` `src/cli/main.ts:751-756`, success+ being `result.errors.length === 0`.++### 1.6 The advisory rail constrains what may be printed forward++`tests/cli/terminal-state-census.test.ts` enumerates every CLI ending and+requires each to name an exit, name a refusal, or be listed as deliberately+silent with a reason. Its detector is `NAMES_EXIT_RE = /emitNextSteps?\(/`+(`tests/cli/terminal-state-census.test.ts:66`) with the comment "The rail is+the only sanctioned way to print a forward pointer."++The rail is `emitNextStep(code, stream)` at `src/cli/advisory-rail.ts:103`.+It resolves strictly through `DIAGNOSTIC_SIGNALS` and **never invents a+command** (`src/core/brain/next-step.ts:29-43`). It also suppresses itself+when `--json` was requested from a command that renders its own JSON+(`advisoryIsLegal`, `src/cli/advisory-rail.ts:84-88`).++`o2b install` is not in the census's hand-classified table; `o2b install-cli`+is, classified as `refusal` (`tests/cli/terminal-state-census.test.ts:133-140`)+with the reason that `renderInstallResult` names each failed outcome.++An ownership statement is **not** a forward pointer and must not be routed+through the rail; the next-action half already is one (see §1.7). Mixing them+would put a prose sentence into a channel whose whole contract is "a+structural CLI string, never prose" (`src/core/brain/diagnostics.ts:83`).++### 1.7 The next-action half already exists and is stronger++`buildOnboardingChecklist` `src/cli/onboarding.ts:77` produces an eight-step,+state-driven, ordered checklist with a per-step copy-pasteable command;+`renderOnboardingChecklist` `src/cli/onboarding.ts:175` renders it. It is+called from `o2b init` (`src/cli/main.ts:197-202`, wrapped in a try/catch so+onboarding can never fail init) and from `o2b onboarding`+(`src/cli/main.ts:206-221`), which has a `--json` mode that serialises the+whole `OnboardingChecklist` — **including `vault`** — at `src/cli/main.ts:216`.++The terminal-state census explicitly credits `o2b onboarding` as naming an+exit and explains why routing it through the rail would be wrong+(`tests/cli/terminal-state-census.test.ts:117-123`).++It is **not** called from `o2b install`, `o2b install --check`, or+`o2b install-cli`. That is the actual gap on the next-action side: the+checklist exists and the install surfaces do not reach it.++The triage verdict `present_weaker` survives contact with the source.++---++## 2. Where the vault path is resolved, and whether the success path holds it++Canonical resolver: `resolveVault(configPath?, {cwd?})` at+`src/core/config.ts:339-359`. Order (docblock `:332-338`, code `:340-358`):++1. `VAULT_DIR` env, tilde-expanded;+2. project pointer walk-up from `cwd` (`resolvePointerVault`, `:349`);+3. active named profile (`resolveActiveProfileVault`, `:354`);+4. `vault` key in the plugin config (`:356`);+5. `null`.++The install verb does **not** call `resolveVault`. It has its own chain in+`buildInstallEnv` at `src/cli/install/install.ts:113-126`:++```+args.vault ?? cfg["vault"] ?? process.env["VAULT_DIR"] ?? ""+```++Three differences from `resolveVault`, all real:++- no pointer walk-up, no profile support;+- `VAULT_DIR` is **last** here and **first** in `resolveVault`, so a machine+ with both a config `vault` and a `VAULT_DIR` gets two different answers+ from `o2b install` and from every other verb;+- the absent case is `""` rather than `null`, and no tilde expansion.++So: at render time the success path **does** have a vault string in hand+(`env.vault`), `runCheck` proves it non-empty at `src/cli/install/install.ts:263`,+and `runTarget` proves it non-empty through `loadPayload`+(`src/cli/install/install.ts:143-156`). But it is not the resolved vault path+that the rest of the CLI would print. An ownership statement naming+`env.vault` can name a different directory than `o2b status` or+`o2b brain doctor` are operating on. **This is a defect the ownership+statement would surface, not create** — but stating a path as "your brain"+that the rest of the tool does not use is exactly the misleading output the+standing rules forbid.++`o2b onboarding --json` uses the shared `requireVault` helper+(`src/cli/main.ts:213`) and therefore already reports the correct path.++---++## 3. The existing "durability gate" is about something else entirely++`src/core/brain/gates/durability.ts` (338 lines, read in full) has **nothing+to do with storage durability**. It is a *fact-triage* gate: given the text+of an extracted fact, decide whether it is worth persisting or is transient+operational noise. Docblock `:1-29`.++- Verdict shape: `{ durable: boolean; reason: DurabilitySignal | null }`+ (`:42-47`). `DurabilitySignal` is a bare string union (`:34-40`) — **not**+ the frozen-object idiom, no members array, no type guard, not in the+ verdict-vocabulary census.+- What it asserts: five pure structural detectors — `hasTempPath` (:74),+ `hasProgressCounter` (:99), `hasRunIdShape` (:120),+ `hasMeasurementDominance` (:143), `hasExitStatusShape` (:165) — plus an+ operator-supplied regex denylist (`compileDurabilityDenylist` :309,+ `resolveDurabilityDenylist` :331).+- Deliberately language-neutral: "there is deliberately zero built-in+ natural-language word list, in any language" (`:6-10`). This is the+ precedent the standing rule about hardcoded natural-language phrases+ points at.+- Liveness: **none**. Everything in the module is pure and does no I/O+ except `resolveDurabilityDenylist`, which reads config.++Callers: I did not find a call site inside `src/` from the searches run;+this recon did not establish the full consumer set of `classifyDurability`.+State that plainly rather than guess.++**Divergence:** the task hint "Nearest surfaces: … `src/core/brain/gates/durability.ts`"+is wrong. Extending this module would collide two unrelated meanings of+"durable" (a fact worth keeping vs. storage that survives) in one namespace.+The sibling `src/core/brain/gates/recoverability.ts` is the module that+actually models "can this be got back" (`RECOVERABILITY_STATE`,+`RECOVERY_COVERAGE`, `RECOVERABILITY_BLOCKER` — all three registered in the+verdict census at `tests/core/architecture/verdict-vocabulary-census.test.ts:518-551`).+That is the neighbourhood, not `durability.ts`.++The only genuine "durability job" machinery in the repo is snapshotting+(`src/core/brain/snapshot.ts`, archives at `Brain/.snapshots/<run_id>.tar.zst`,+docblock `:1-30`) and the cron-recipe renderers+(`src/cli/cron-recipe.ts:1-38`, `src/cli/search-cron-template.ts`,+`src/cli/partner-codegraph-cron.ts`). Every one of those **renders text for+the operator to install into their own scheduler and writes nothing**+(`src/cli/cron-recipe.ts:4-11`). So there is no job the product owns whose+liveness it could check from its own records — a liveness check has to infer+it from artifacts (last snapshot mtime, last index run) or from the host's+scheduler, and the latter is out of reach of a tool that never installed+anything.++---++## 4. The doctor check idiom — and there are two doctors++### 4.1 `o2b doctor` (root) — no codes, no registry, no census++`cmdDoctor` `src/cli/main.ts:284`. Checks come from `doctor(opts)`+`src/core/doctor.ts:394-412`, which **hand-pushes** `CheckResult` values into+an array. A `CheckResult` is `{ name, ok, message, fix? }` — see+`checkVaultWriteable` `src/core/doctor.ts:32-53` for the canonical example.+Human render at `src/cli/main.ts:351-355`, JSON at `src/cli/main.ts:326-348`.++There is **no code, no severity vocabulary, no `nextCommand` registry and no+census** over this family. `fix` is a free-form string (`chmod u+rwx "…"`,+`o2b update`). Adding a check here is `results.push(...)` in+`src/core/doctor.ts:394` and nothing gates it.++The opt-in readiness probes hang off the same verb: `--readiness`+(`src/cli/main.ts:290, 316-323`), `runReadinessProbes`+`src/core/doctor-readiness.ts:529`, default probe set+`src/core/doctor-readiness.ts:515-520`. Adding a probe is one row in+`DEFAULT_PROBES`. This family **does** have a closed vocabulary+(`READINESS_STATUS`, §5.4) and is censused.++### 4.2 `o2b brain doctor` — codes, registry, and a hard census++`runDoctor` `src/core/brain/doctor.ts:202`. Registration is one row in+`DOCTOR_CHECKS`, `src/core/brain/doctor.ts:132-166` — a frozen array whose+**order is part of the contract** (`:125-131`). A check implements+`DoctorCheck` `src/core/brain/doctor/check.ts:64-76`:++```+readonly failSoft: boolean;+run(ctx: DoctorCheckContext, out: DoctorFindings): void;+```++`failSoft: true` means a throw is swallowed (`src/core/brain/doctor.ts:265-277`);+`false` is reserved for the store's structural core.++A finding is a `DoctorIssue` `src/core/brain/types.ts:1977-2001`:+`severity` (`DoctorSeverity = "warning" | "error"`, `src/core/brain/types.ts:1971`+— exactly two members, no `info`), `code: string`, optional `path`,+`message`, plus optional `field`/`target`/`sources`. Anything the check+attempted but cannot claim it verified goes into the **separate** `uncertain`+stream (`DoctorFindings.uncertain`, `src/core/brain/doctor/check.ts:59-62`;+surfaced conditionally at `src/core/brain/doctor.ts:341`).++`nextCommand` does not live on the issue. It lives in `DIAGNOSTIC_SIGNALS`,+keyed by `code` — `DiagnosticSignal` is `{code, issueClass, nextCommand,+autoRepairable}` (`src/core/brain/diagnostics.ts:77-86`). Worked example, the+search-index family at `src/core/brain/diagnostics.ts:332-358`:++```+{ code: "search-index-built", issueClass: "search index up to date",+ nextCommand: "o2b search query <text>", autoRepairable: false },+{ code: SEARCH_INDEX_MISSING_CODE, issueClass: "search index not built",+ nextCommand: "o2b search index", autoRepairable: false },+{ code: SEARCH_INDEX_CORRUPT_CODE, issueClass: "search index failed a structural integrity check",+ nextCommand: "o2b search reindex", autoRepairable: false },+```++The codes are hoisted to module constants `SEARCH_INDEX_MISSING_CODE` /+`SEARCH_INDEX_CORRUPT_CODE` at `src/core/brain/diagnostics.ts:94-95`+precisely so producer and registry cannot drift into two spellings.++### 4.3 The doctor-exit census — exact obligations++`tests/core/brain/doctor-exit-census.test.ts`. It reads the population **out+of the source of `doctor.ts` plus every `.ts` under `src/core/brain/doctor/`+recursively** (`:74-124`), not out of the tables. A new check module is+swept the moment it exists. Two recognised code shapes (`:126-130`):++- `code: "<literal>"` — `LITERAL_CODE_RE`;+- `const <NAME>_CODE = "<literal>";` at module scope — `CONSTANT_CODE_RE`+ (anchored `^…$` multiline, so the declaration must be on one line, exactly+ in that form, with the identifier matching `/^[A-Z0-9_]*CODE[A-Z0-9_]*$/`).++A new check must satisfy **all** of:++1. **Classified exactly once.** Every code it spells is in `DIAGNOSTIC_SIGNALS`+ *or* in `DOCTOR_EXIT_EXCLUSIONS` (`src/core/brain/doctor-exits.ts`),+ never both, never neither — tests at `:235-248`.+2. **Registered codes pinned by hand.** If the code gets a `nextCommand`, its+ literal string must be added to `DOCTOR_REGISTERED_CODES`+ (`tests/core/brain/doctor-exit-census.test.ts:177-200`), and the test at+ `:250-258` asserts *set equality* between that list and the doctor codes+ found in `DIAGNOSTIC_SIGNALS`. Adding a registered code without editing+ this array fails. This is the assertion that catches "declared and never+ registered".+3. **Exclusions must be specific.** If it goes into `DOCTOR_EXIT_EXCLUSIONS`,+ the reason must be ≥ 80 characters (`MIN_REASON_LENGTH`, `:203`, test `:266-272`)+ and must **not** match `/\bo2b\s+[a-z]/` (`INVOCATION_RE`, `:205`, test+ `:274-279`) — a reason that names a command belongs in the registry+ instead. Only two shapes earn an exclusion, stated at+ `src/core/brain/doctor-exits.ts:19-31`: the repair is a judgement over+ content, or an edit whose target shape is not derivable from the finding.+4. **No opaque code site.** Any `code:` property whose value is neither a+ string literal nor a `*_CODE` identifier must be declared in+ `NON_LITERAL_CODE_SITES` with an explanation of where its values are+ enumerated (`:145-161`, test `:296-303`).+5. **Floors must keep rising.** The non-vacuity test `:281-292` asserts+ `DOCTOR_SOURCE_PATHS.length > 10`, `codes.length > 35`,+ `constantCodes().size > 3`, registered > 14, excluded > 20. A new check+ only ever pushes these up, so it is not an obstacle — but note that+ *deleting* a check family fails here, which is the regression the previous+ release was about.++### 4.4 Which doctor should a durability/liveness check live in?++Unresolved by source alone, and the answer is load-bearing:++- `o2b brain doctor` gives the check a `code`, a registered `nextCommand`, an+ `uncertain` stream for "could not measure", and census enforcement. Its+ `DoctorCheckContext` (`src/core/brain/doctor/check.ts:23-52`) carries+ `vault`, `now`, `config`, `dbPath`, `configPath` — enough for an artifact-+ mtime liveness probe. It does **not** carry `home`, `env` or `platform`.+- `o2b doctor` is where `checkVaultWriteable` already lives+ (`src/core/doctor.ts:32`) and where `--readiness` probes run, but it has no+ census and no next-command registry, so a check added there gets none of+ the guarantees this project's recent releases were built to provide.++---++## 5. Environment-class detection: what is honestly detectable++### 5.1 Signals, measured on this host++Probed directly (Bun 1.3.14, linux):++| signal | availability here | what it proves | what it cannot distinguish |+|---|---|---|---|+| `/.dockerenv` exists | absent | Docker (and only Docker) created the rootfs | absent on podman, containerd/CRI-O, Kubernetes without Docker shim, LXC, systemd-nspawn, gVisor, and on any image where it was deleted. **Absence proves nothing.** |+| `/run/.containerenv` | absent | podman | same one-way property |+| `/proc/1/cgroup` readable | yes → `0::/init.scope` | on cgroup **v1** hosts, a `/docker/<id>` or `/kubepods/` path is strong evidence | on cgroup **v2 unified** (what this host runs) the line is just `0::/<path>`, and a container often shows `0::/` — indistinguishable from a plain systemd scope. The v1 heuristic is dead on modern hosts. |+| `/proc/1/sched` first token | yes → `systemd (1, …)` | pid 1 is an init system → **not** a single-process container | a container *can* run systemd (`systemd-nspawn`, `docker run --init` variants). One-way at best. |+| `/proc/self/mountinfo` | yes, 32 lines | names the fs type backing any path, including `overlay` and `tmpfs` | tells you the *storage driver*, not the *lifetime*. An overlayfs root is normal for every container, ephemeral or not; a bind-mounted persistent volume inside a container is `ext4`. |+| `statfsSync(path).type` | yes — returned `61267` (`0xEF53`, ext4) for `/` | the fs magic of the path's filesystem. `0x794c7630` overlayfs, `0x01021994` tmpfs | same limit as above. Also **not portable**: `type` is a Linux magic number; on macOS/Windows the value means something else or nothing. |+| CI env vars (`CI`, `GITHUB_ACTIONS`, …) | none set here | when set by a known CI, high confidence it is CI | `CI=true` is set by hand constantly; a self-hosted persistent runner is CI **and** durable; a CI job in a VM is not a container |+| sandbox env vars (`CODESPACES`, `GITPOD_*`, `REPL_ID`, `REMOTE_CONTAINERS`) | none set here | positive identification of that specific product | one variable per vendor, unbounded set, absence proves nothing |+| agent-host vars (`CLAUDECODE`, `CLAUDE_CODE_*`) | **9 set on this host** | an agent CLI is driving the process | says nothing about durability — this host is a durable VPS |+| vault path writability | already implemented, `checkVaultWriteable` `src/core/doctor.ts:32` | the vault can be written **now** | says nothing about whether the write survives the process |++### 5.2 The honest conclusion++**No combination of these signals can prove ephemerality.** Every container+signal is one-way: a positive is decent evidence of "containerised", a+negative is evidence of nothing. And "containerised" is not "ephemeral" —+the property that matters is *whether this filesystem outlives the process*,+and nothing on the machine reports it. A bind-mounted volume in a Docker+container is more durable than a laptop's `/tmp`.++The one signal that is *close* to the real question is the filesystem type+under the **resolved vault path** specifically (not `/`): a vault on `tmpfs`+is provably lost at reboot, and a vault on `overlay` with no lower bind mount+is very likely lost at container exit. That is a claim about **one path**,+which is the claim the ownership statement actually makes. It is also+Linux-only.++A classifier that answers "local / cloud sandbox / ephemeral container" as a+single fact would be guessing on two of three members. **Recommendation: do+not build that classifier.** Build the narrower thing that can be proved:+*what backs the vault path, and can that be established at all.*++### 5.3 Recommended verdict vocabulary++Two vocabularies, not one — following the project's own stated rule that a+union of disjoint sets is a namespace rather than an abstraction+(`tests/core/architecture/verdict-vocabulary-census.test.ts:285-292`):++- **Vault durability verdict** — what backs the vault path:+ `durable` (a filesystem that survives process and reboot),+ `volatile` (proved memory-backed, e.g. tmpfs),+ `layered` (proved container-overlay-backed, survival unknown),+ `undetermined` (could not be established) — the mandatory+ "could-not-be-determined" member.+- **Undetermined reason** — why the probe reached no verdict:+ `probe_unsupported` (platform exposes no filesystem-type facility),+ `path_unreadable`, `fs_type_unknown` (a magic number this build does not+ recognise). Separate vocabulary so a guard cannot let a reason be read back+ as a verdict — the exact argument made for+ `MATERIALIZE_UNKNOWN_REASON` at+ `tests/core/architecture/verdict-vocabulary-census.test.ts:364-383`.++Deliberately **absent**: any member meaning "cloud sandbox". No signal+distinguishes it from a container, and naming it would be the guess this+document argues against.++### 5.4 The closed-vocabulary idiom, confirmed against a real example++`READINESS_STATUS` — `src/core/doctor-readiness.ts:102-127` — is the complete+trio and the one the census seeds with+(`tests/core/architecture/verdict-vocabulary-census.test.ts:250-260`):++1. `export const X = Object.freeze({ camelCaseKey: "value", … } as const);`+2. `export type XName = (typeof X)[keyof typeof X];` (derived union)+3. `export const X_MEMBERS: ReadonlyArray<XName> = Object.freeze([X.a, X.b, …]);`+4. `export function isXName(value: unknown): value is XName { return typeof value === "string" && (X_MEMBERS as ReadonlyArray<string>).includes(value); }`+ — the parameter is `unknown`, always.+5. A row in `CENSUS` at+ `tests/core/architecture/verdict-vocabulary-census.test.ts:250-617` with a+ comment saying why the vocabulary is registered.++The audit (`:213-243`) checks: object frozen, no duplicate values, no+duplicate members, every declared value is a member, the guard accepts every+declared value, no member is declared by nothing, and the guard rejects+`""`, `" "`, `"unknown-vocabulary-member"`, `null`, `undefined`, `42`, `{}`.++**Divergence from the brief:** the brief says "snake_case values". The+codebase's actual convention is *camelCase key, snake_case value for+multi-word values* — `nothingAtRisk: "nothing_at_risk"`+(`src/core/brain/gates/recoverability.ts:60`),+`outputsUnreadable: "outputs_unreadable"` (`src/core/brain/staleness.ts:146`),+`refusedScanTruncated: "refused_scan_truncated"` (`src/core/egress/guard.ts:76`).+Single-word values are the bare word (`pass`, `fail`, `skipped`, `unknown` —+`src/core/doctor-readiness.ts:104-110`). One registered outlier uses+kebab-case: `PROVIDER_PROBE` has `notConfigured: "not-configured"`,+`timedOut: "timed-out"` (`src/core/search/provider-probe.ts:58-64`). Follow+the snake_case majority.++---++## 6. Existing environment / platform detection in the repo++There is **no host-classification layer**. What exists, and what a design+should extend rather than duplicate:++**Agent-runtime detection (a different axis, but the nearest existing one).**+`detectHookRuntime(payload, env)` at `hooks/lib/detect.ts:200`, with+`export type HookRuntime = "claudecode" | "codex" | "grok" | "unknown"` at+`hooks/lib/detect.ts:174`. Payload-shape-first, env-second: `GROK_HOOK_EVENT` /+`GROK_SESSION_ID` / `GROK_WORKSPACE_ROOT` at `hooks/lib/detect.ts:208-210`,+transcript-path needles at `:176-177`. It lives **outside `src/`**, and+`src/core/` receives the classification as an injected label rather than+probing — see `src/core/brain/pretool-orient.ts:74` (`readonly runtime: string`)+and the short-circuit at `:132`. Note `HookRuntime` is a bare union, **not**+the frozen-object trio, and is not in the verdict census.++A second, unrelated runtime axis: `O2B_TARGET` read at+`src/core/identity-reminder.ts:109` against a fixed+`KNOWN_RUNTIME_TARGETS = ["hermes", "openclaw"]` (`:41`).++**Injected-environment records** (the two shapes to extend):+- `ConfigPathEnv { platform, home, env }` — `src/core/config.ts:99-105`,+ consumed by the pure `resolveDefaultConfigPath` `:120`, with the only+ `process.platform` / `homedir()` read isolated in `defaultConfigPath` `:138-144`.+- `InstallEnv { vault, home, cwd, env, now }` — `src/core/install/types.ts:56-62`.+ It carries **no `platform` field**; every adapter receives it through+ `detect`/`plan`/`apply`/`verify` (`src/core/install/types.ts:142-147`).++**Platform branching**, scattered, no shared helper:+`UNSUPPORTED_CONFIG_PLATFORMS = ["win32"]` `src/core/config.ts:35`;+`src/core/path-safety.ts:74-75`;+`src/core/brain/health/remediation.ts:188-191` (`opts.platform ?? process.platform`+— the house style for testable injection);+`src/core/brain/snapshot.ts:493-497` (PATH separator, `PATHEXT`);+`src/core/search/indexer.ts:1506` (`darwin` → brew hint).++**TTY / interactivity**: the idiom `flags["json"] || !process.stdin.isTTY` is+inlined at six sites — `src/cli/brain/verbs/lint.ts:25`,+`page-dedup.ts:24`, `rollback.ts:146`, `upgrade.ts:72`, and TTY-only variants+at `merge.ts:68`, `import-claude-memory.ts:87`. No shared helper exists.++**Filesystem probing**: no fs-type probe anywhere. Two *writability* probes+that already coexist with different techniques —+`checkVaultWriteable` create-and-unlink at `src/core/doctor.ts:32-53`, and+`accessSync(dir, W_OK)` at `src/core/search/indexer.ts:1311`.++**The existing push channel for environment degradation** is+`collectRuntimeNotices` `src/core/brain/runtime-notices.ts:74`. It already+carries a `vault_read_only` notice built from `checkVaultWriteable`+(`src/core/brain/runtime-notices.ts:92-105`), it rides SessionStart injection+and `vault_health`, and it deliberately carries **no** `next_command` for+that notice because the two exits are an OS permission change or a different+`VAULT_DIR`, "neither of them an `o2b` verb" (`:87-91`). That is the exact+precedent for a vault-durability notice, and `RuntimeNotice` is already+serialised whole by `o2b onboarding --json` (`src/core/brain/runtime-notices.ts:42-53`).++**No CI detection, no container detection, no cloud-sandbox detection exists+anywhere in `src/`, `hooks/`, `scripts/`, or `tests/`.**++---++## 7. Cross-check: is the ownership claim true as shipped?++### 7.1 What is inside the vault++Memory itself: `Brain/` and its subtrees — `Brain/preferences`, `inbox`,+`retired`, `log`, `decisions`, `theses`, `tensions`, `handoffs`, and the rest,+all named vault-relative in `src/core/brain/path-constants.ts:22-62`. Plain+Markdown files. This half of the statement is true.++Derived and operational state, also inside the vault:+- Search index: `<vault>/.open-second-brain/brain.sqlite` —+ `resolveIndexPath` `src/core/search/paths.ts:28-34`, name constants+ `src/core/brain/path-constants.ts:137-138`.+- Maintenance lease DB: `<vault>/.open-second-brain/maintenance.sqlite` —+ `src/core/brain/maintenance/lease.ts:36`.+- Install manifest: `<vault>/.open-second-brain/install.lock.json` —+ `manifestPath` `src/core/install/manifest.ts:36-38`.+- Snapshots: `Brain/.snapshots/<run_id>.tar.zst` —+ `src/core/brain/snapshot.ts:6-8`; store archives+ `src/core/brain/paths.ts:589,602`.+- **Encrypted secrets store, key included**:+ `<vault>/.open-second-brain/secrets/secrets.json` plus the AES keyfile at+ `<vault>/.open-second-brain/secrets/keyfile` —+ `secretsDir` / `storePath` / `keyPath` `src/core/brain/secrets/store.ts:69-79`,+ keyfile creation `src/core/brain/secrets/crypto.ts:36-60`. The key sits+ beside the ciphertext, so this is obfuscation at rest, not protection+ against whoever holds the vault. It reinforces the ownership claim+ (nothing is escrowed elsewhere) and is worth knowing before a design says+ "just copy it to another machine".++No `~/.cache` or `XDG_CACHE_HOME` write exists anywhere in the tree.++### 7.2 Durable state that lives OUTSIDE the vault++1. **Machine-local plugin config** —+ `$OPEN_SECOND_BRAIN_CONFIG` → `$XDG_CONFIG_HOME/open-second-brain/config.yaml`+ → `$HOME/.config/open-second-brain/config.yaml`+ (`resolveDefaultConfigPath` `src/core/config.ts:120-131`, written by+ `setConfigValue` `src/core/config.ts:277`). Holds `vault`, `agent_name`,+ `timezone`, `search_db_path`, `embedding_api_key`, `embedding_base_url`,+ `device_id`, `installation_secret`. Not memory; but the pointer *to*+ memory, and a live credential.+2. **Vault profiles registry** — `~/.config/open-second-brain/profiles.json`,+ a sibling of the config file (`profilesPath`+ `src/core/brain/portability/profiles.ts:45-47`, written by `save` `:76-79`).+ Records the name and absolute path of every registered vault plus which is+ active. Delete a vault and this file still names it.+3. **`device_id`** — minted on first use and persisted into the machine config+ (`resolveDeviceId` `src/core/config.ts:415`). Consumed by+ `src/core/brain/log.ts`, `log-jsonl.ts`, `truth/store.ts`,+ `decisions/receipts.ts`, `portability/profiles.ts`, `src/mcp/server.ts`.+ Vault records are attributed to it, so deleting the machine config mints a+ new identity and past log shards stay attributed to a device that no+ longer exists.+4. **`installation_secret`** — 16 random bytes generated under a directory+ lock and written into the machine config (`src/core/config.ts:496-546`).+ It **is** live: `vaultStoreReference` (`src/core/config.ts:569-576`) uses it+ as the HMAC-SHA256 key over the absolute vault path to produce the opaque+ `vault://<32-hex>` identifier that MCP tools return in place of a host path+ (`src/mcp/tools.ts:28, 114`). Lose the machine config and every previously+ emitted `vault://` reference stops resolving to this vault — a durable,+ out-of-vault secret with correlation value.+5. **Runtime config files the installer owns.** Nine adapters, each with its+ own out-of-vault path — `~/.cursor/mcp.json`+ (`src/core/install/adapters/cursor.ts:18-19`),+ `~/.gemini/settings.json` (`gemini-cli.ts:12-13`),+ `~/.kiro/settings.json` (`kiro.ts:16-18`),+ `${XDG_CONFIG_HOME:-~/.config}/github-copilot/mcp.json`+ (`copilot-cli.ts:107-111`),+ `${XDG_CONFIG_HOME:-~/.config}/opencode/opencode.json` plus a plugin file+ copy (`opencode.ts:38-48`), `${GROK_HOME:-~/.grok}/config.toml` plus a+ hooks file (`grok.ts:48-58`), `~/.aider.conf.yml` (`aider.ts:55-60`), a+ symlink at `${PI_HOME:-~/.pi}/skills/brain-memory` (`pi.ts:62-75`), and the+ operator-named `--out` path for `generic` (`generic.ts:119`).+ Separately, `o2b brain protect --target codex` patches a managed fence into+ `~/.codex/config.toml` (`src/core/brain/protect.ts:515-518`); its+ `claudecode` target stays in-vault (`:19`). **There is no `~/.claude.json`+ write** — the Claude Code integration ships as a plugin and+ `~/.claude/projects/**` is read-only+ (`src/core/brain/claude-memory-paths.ts:15, 27`).+ Note: `tests/core/architecture/write-site-census.test.ts:940-948`+ **explicitly excludes the install adapters** from the vault write-site+ population, so none of these paths is covered by that guard.+6. **CLI symlinks** — `~/.local/bin/{o2b,vault-log,o2b-hook}`,+ `src/cli/install-cli.ts:25, 125`. Self-healed automatically on every+ Claude Code SessionStart (`hooks/active-inject.ts:143` → `healCliSymlinks`+ `src/cli/install-cli.ts:200`).+7. **The opencode session spool — the one out-of-vault artifact that carries+ memory content.** The bundled plugin appends normalised turn text and tool+ calls as JSONL to+ `${OSB_OPENCODE_SPOOL_DIR:-${XDG_DATA_HOME:-~/.local/share}}/open-second-brain/opencode/<session>.jsonl`+ — path at `plugins/opencode/open-second-brain.ts:72-78`, atomic write at+ `:167-173`. Consumed back by `src/core/brain/sessions/opencode.ts`. This is+ raw conversation content living in `~/.local/share`, and nothing in the+ tree prunes it. **This is the sharpest counterexample to the ownership+ claim as worded**, and it applies only to operators using the opencode+ integration.+8. **Hook reminder markers** — one empty file per session id under+ `${TMPDIR}/o2b-reminder-markers/` (`hooks/post-write-reminder.ts:38-40`,+ written `:63`), pruned at 48h (`:68-79`). Metadata only.+9. **Bench run artifacts** — `resolve(".open-second-brain/bench-runs")`,+ resolved against **CWD, not the vault**+ (`src/cli/brain/verbs/bench.ts:25, 54-58`). Out-of-vault whenever CWD is+ not the vault.+10. **The search index can be relocated out of the vault** —+ `SEARCH_DB_ENV = "OPEN_SECOND_BRAIN_SEARCH_DB"` and+ `SEARCH_DB_CONFIG_KEY = "search_db_path"`+ (`src/core/search/paths.ts:23-26`, honoured in+ `resolveConfiguredIndexPath` `:53-60`). Derived and rebuildable, so no+ memory is *lost* — but on a machine with the override set, a copy of every+ indexed chunk lives somewhere else.+11. **Read-only external sources** — `~/.claude/projects/<slug>/memory`+ (`src/core/brain/claude-memory-paths.ts:13-16`), transcript collectors+ under `home` (`src/core/discipline/transcripts/{claude-code,codex}.ts:19-20`),+ and Cursor's `state.vscdb` opened `{ readonly: true }`+ (`src/core/discipline/transcripts/cursor.ts:57`). Inputs, never written.+12. **Temp scratch only** — `mkdtempSync(tmpdir(), …)` at+ `src/core/brain/snapshot.ts:853, 1324` and+ `src/core/search/link-ratchet.ts:278`. Created and removed.+13. **Config-directory lock files** — `proper-lockfile` anchored on+ `dirname(~/.config/open-second-brain/config.yaml)`+ (`src/core/config.ts:447`, `:530`).++### 7.3 "No service to cancel"++True of the product. There is no account, no sync server, no update check, no+analytics endpoint, and no phone-home. Every `fetch()` in `src/` is on a path+the operator configured:++- embeddings, OpenAI-compatible — `${embedding_base_url}/embeddings`,+ `src/core/search/embeddings/openai-compat.ts:431`. **No default base URL**:+ construction refuses without one+ (`src/core/search/embeddings/provider-resolve.ts:66-82`), and semantic+ search is default-off;+- embeddings, ZeroEntropy — `src/core/search/embeddings/zeroentropy.ts:192`;+- reranker — `src/core/search/rerank/cross-encoder.ts:74, 85`;+- research providers, hard-coded endpoints —+ `src/core/brain/research/providers/tavily.ts:17`,+ `.../brave.ts:18`, and arbitrary-URL fetch+ `src/core/brain/research/external-fetch.ts:231`;+- Telegram capture — `src/core/brain/capture/telegram-capture.ts:44, 418, 433`.++Local-only servers, not egress: the MCP HTTP transport binds `127.0.0.1` and+refuses a non-loopback bind without an API key (`src/mcp/http.ts:40-50`); the+vault explorer binds `127.0.0.1` (`src/core/brain/explorer.ts:352`).++**`tests/core/architecture/egress-census.test.ts` is not a network census.**+It measures *local file destinations* (`--out`, `--dest`) and whether each+runs the shared redactor; its registry is+`src/core/egress/registry.ts:84-160`, seven sites. Its docblock states+outright that "The vault has no git transport and deliberately never will"+(`src/core/egress/registry.ts:6-7`) — which is the source-level confirmation+of the validator's note that the upstream per-turn git-push persistence model+does not apply to this project.++The caveat: an operator who configured a cloud embedding provider **does**+have a third-party account, and vault content has been sent to it. Saying+"no service to cancel" unconditionally to that operator is false. The+statement should either be unconditional about *Open Second Brain itself*+("this tool has no account and no server") or be state-aware — and the state+is already resolvable through `resolveSemanticCapability`+(`src/core/search/capability-tier.ts`, called at+`src/core/doctor-readiness.ts:277`).++### 7.4 Verdict on the ownership statement++- "Every memory is a Markdown file in your own vault" — **true for the Brain+ layer**, with two qualifiers: the search index can be relocated out of the+ vault by config (§7.2 item 10), and the **opencode session spool writes raw+ conversation turns to `~/.local/share`** (§7.2 item 7). The second is a+ genuine counterexample and the design must either exclude opencode users+ from the unqualified sentence or name the spool.+- "Copy it to another machine" — **true**, and the in-vault secrets keyfile+ travels with it (§7.1). The machine config, `profiles.json`, `device_id`+ and `installation_secret` do not (§7.2 items 1-4), so `vault://` references+ minted on the old machine stop resolving on the new one.+- "Delete it and the brain is gone" — **true for memory**. What is left+ behind is machine-local plumbing: the config, the profiles registry, the+ device id and installation secret, nine adapter config files, the+ `~/.codex/config.toml` fence and the `~/.local/bin` symlinks (§7.2 items+ 1-6). None of it is memory, so the sentence is honest — a design that+ claims "nothing is left" would not be. `o2b uninstall` is the exit for that+ residue.+- "No service to cancel" — **true of this tool**, false as a blanket claim on+ a vault configured against a cloud embedding provider (§7.3).++**Honest restatement that survives the source:** every memory is a Markdown+file in your vault, and the search index beside it is a rebuildable SQLite+file also inside the vault. There is no account and no server. What lives+outside the vault is machine-local plumbing — a `~/.config/open-second-brain/`+config plus the managed blocks `o2b install` added to your agent's own config+files, removable with `o2b uninstall`. If you use the opencode integration,+raw session transcripts also spool to `~/.local/share/open-second-brain/opencode/`.++---++## Divergences++Points where a task body does not survive contact with the source.++1. **`src/core/brain/gates/durability.ts` is not about durability of storage.**+ It classifies extracted-fact text as durable-vs-transient noise+ (`:1-29`, verdict shape `:42-47`). It has no I/O in its classifier, no+ presence check and no liveness check. Naming it as a "nearest surface" for+ a persistence-durability feature is a namespace collision.+ `src/core/brain/gates/recoverability.ts` is the actual neighbour.+ (§3)+2. **`src/core/brain/doctor-readiness.ts` does not exist.** The module is+ `src/core/doctor-readiness.ts` — one level up, and it belongs to the root+ `o2b doctor`, not to `o2b brain doctor`. (§4.1)+3. **There is no one install "success path" and no shared result type.** Four+ modes, four result types, four `--json` shapes, one of which+ (`renderApplyJson`, `src/cli/install/render.ts:107`) has no+ `schema_version` at all. (§1.1-1.3)+4. **`src/cli/install-cli.ts:280` (`renderInstallResult`) has no `--json`+ surface.** `cmdInstallCli` parses only `--bindir`+ (`src/cli/main.ts:751-756`). A machine-readable handoff field cannot be+ added there without first giving the verb a JSON mode. (§1.1)+5. **No golden/snapshot/parity test asserts any install `--json` shape.**+ `tests/cli/install-verb.test.ts:64-77` checks three properties of one+ payload. The *human* verify output, by contrast, is pinned byte-for-byte+ against the `install/*.md` documents by+ `tests/docs/install-verify-conformance.test.ts`. Human and JSON are+ asymmetrically protected. (§1.4)+6. **`o2b install` does not use the canonical vault resolver.**+ `buildInstallEnv` (`src/cli/install/install.ts:113-126`) uses a different+ chain, in a different precedence order, from `resolveVault`+ (`src/core/config.ts:339-359`) — no pointer walk-up, no profiles, and+ `VAULT_DIR` last instead of first. Printing "your brain lives here" from+ `env.vault` can name a directory the rest of the CLI is not using. (§2)+7. **"Passing verify" includes "nothing is installed".**+ `exitCodeForVerify` returns 0 for `not-installed` by design+ (`src/cli/install/install.ts:291-308`). An ownership + next-action close+ fired on exit 0 would fire on a machine where the install did nothing. (§1.5)+8. **The verdict-vocabulary casing in the brief is slightly wrong.** Values+ are snake_case for multi-word members, bare words for single-word ones;+ one registered vocabulary uses kebab-case. (§5.4)+9. **"Cloud sandbox" is not detectable.** Every container signal is one-way,+ cgroup v2 has erased the classic `/proc/1/cgroup` heuristic (measured on+ this host: `0::/init.scope`), and no signal separates a sandbox from a+ container or a container from a durable one. (§5.1-5.2)+10. **"Durability job" has no referent in this product.** Every scheduled-job+ surface is a *recipe renderer* that writes nothing and installs nothing+ (`src/cli/cron-recipe.ts:4-11`). There is no job whose registration the+ tool could look up, so "presence" can only mean an artifact on disk. (§3)+11. **"Handoff" is already taken.** `src/core/brain/handoff.ts` means+ operator-readable session handoff notes at+ `Brain/handoffs/<date>-<scope>.md` (`:2-5, 141-146`), with a+ `session_handoff` config gate (`src/core/config.ts:715-720`) and a bench+ category (`src/core/bench/types.ts:22`). A new install-close field named+ `handoff` would collide.+12. **The ownership statement as briefed is not unconditionally true.** The+ opencode plugin spools raw conversation turns to+ `~/.local/share/open-second-brain/opencode/`+ (`plugins/opencode/open-second-brain.ts:72-78, 167-173`) with no pruning.+ "Every memory is a Markdown file in your own vault" is false for an+ operator using that integration. (§7.2 item 7)+13. **`tests/core/architecture/egress-census.test.ts` does not census network+ egress.** It censuses local file export destinations+ (`src/core/egress/registry.ts:84-160`). A design that cites it as proof+ of "no network" would be citing the wrong artifact — though the same+ file's docblock does carry the relevant statement, that the vault has no+ git transport and never will (`src/core/egress/registry.ts:6-7`).+14. **The install adapters are exempt from the write-site census.**+ `tests/core/architecture/write-site-census.test.ts:940-948` explicitly+ excludes them, so nothing enforces an inventory of the nine out-of-vault+ paths they own. Any ownership statement that enumerates residue is+ enumerating an unguarded set.+15. **Unestablished by this recon:** the call sites of `classifyDurability`+ (§3), and whether any adapter's `verify()` currently returns+ `mcp-unreachable` in practice — `src/cli/install/install.ts:300-304`+ states it is reachable only from an adapter that shells out to a runtime+ CLI, which a CLI-level test cannot stage.++---++## What a design must not assume++1. **Do not assume the vault path in `env.vault` is the vault.** Until the+ install verb goes through `resolveVault` (or the two chains are+ reconciled), any path printed as "your brain" from the install path may+ differ from the one every other verb uses. Fix the resolver or state the+ source of the path.+2. **Do not print an ownership statement without a durability verdict.**+ "These files on this machine are your brain, delete them and it is gone"+ is a claim about persistence. Printing it where persistence has not been+ established — and it usually cannot be, §5.2 — is the misleading output+ the standing rules forbid. If the verdict is `undetermined`, the sentence+ must say so, not omit the qualifier.+3. **Do not build a three-way local/sandbox/ephemeral classifier.** Two of+ its three members are unprovable. Build the narrow, provable thing: what+ filesystem backs the resolved vault path, plus an explicit "could not be+ determined".+4. **Do not treat a negative container signal as evidence of durability.**+ Absent `/.dockerenv`, absent `/run/.containerenv` and a plain cgroup v2+ line are the *normal* readings inside modern containers.+5. **Do not treat "containerised" as "ephemeral".** A bind-mounted volume in+ a container outlives a laptop's `/tmp`.+6. **Do not assume the human and JSON install surfaces will stay in sync on+ their own.** Nothing tests the JSON shapes. Either add the field through a+ single value both renderers consume, or add the golden test at the same+ time.+7. **Do not route prose through the advisory rail.** `DIAGNOSTIC_SIGNALS`+ holds "a structural CLI string, never prose"+ (`src/core/brain/diagnostics.ts:83`) and `emitNextStep` never invents one+ (`src/core/brain/next-step.ts:29-43`). The next-action half belongs there;+ the ownership half does not.+8. **Do not declare a doctor code without registering it.** The census+ asserts set equality between `DOCTOR_REGISTERED_CODES` and the doctor+ codes present in `DIAGNOSTIC_SIGNALS`+ (`tests/core/brain/doctor-exit-census.test.ts:250-258`). A code declared+ and never registered — or registered and never pinned — fails by name.+9. **Do not add a boolean where a verdict is needed.** The project has+ repeatedly converted `boolean`/`boolean | null` to a four-member+ vocabulary precisely because "could not measure" had nowhere to go+ (`src/core/doctor-readiness.ts:28-38`,+ `tests/core/architecture/verdict-vocabulary-census.test.ts:492-505`).+ A durability probe must be able to say `undetermined` with a reason.+10. **Do not hardcode natural-language phrases for classification.** The+ existing gate in this very directory states the rule and holds to it —+ zero built-in word list, in any language, structural signals only+ (`src/core/brain/gates/durability.ts:6-10`).+11. **Do not claim "nothing is left behind".** Machine config,+ `profiles.json`, `device_id`, `installation_secret`, nine adapter config+ files and the `~/.local/bin` symlinks all survive vault deletion (§7.2).+ None is memory, so the ownership claim holds — but only as worded about+ *memory*, and `o2b uninstall` is the exit for the residue.+12. **Do not claim "every memory is a Markdown file in your vault"+ unconditionally.** It is false on a machine using the opencode+ integration, which spools raw turns to `~/.local/share`+ (`plugins/opencode/open-second-brain.ts:72-78`). Either scope the+ sentence or name the spool.+13. **Do not say "no service to cancel" unconditionally** on a vault+ configured against a cloud embedding provider (§7.3).+14. **Do not assume the vault is self-contained for identity.** The opaque+ `vault://<hex>` reference every MCP tool returns is keyed by+ `installation_secret` in the machine config+ (`src/core/config.ts:569-576`, `src/mcp/tools.ts:114`). "Copy it to+ another machine" does not carry that key, and the references break.+15. **Do not fire the close on every exit-0 verify.** Exit 0 includes+ `not-installed` (`src/cli/install/install.ts:296-299`).+16. **Do not name the new field `handoff`.** The name is taken by session+ handoff notes (§Divergences 11).diff --git a/docs/brainstorm/nothing-runs-unwatched/recon/failure-mode-bench.md b/docs/brainstorm/nothing-runs-unwatched/recon/failure-mode-bench.mdnew file mode 100644index 00000000..f0c34b62--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/recon/failure-mode-bench.md@@ -0,0 +1,572 @@+# Recon: the four-failure-mode conformance suite (t_72d6eb23)++Read-only reconnaissance against `feat/nothing-runs-unwatched` @ `6caf0b83`+(v1.47.0). Every anchor below was read; paths are repo-relative.++Headline: none of `know_to_ask_failure_rate`, `false_fire_rate`,+`source_isolation_violations` or `avg_injected_tokens` appears anywhere in the+tree (grep over `*.ts`, `*.md`, `*.json` returns nothing). Two of the four are+measurable today against seams that already exist. One is measurable only+against a surface that ships default-OFF. One is, as named, unmeasurable+without first deciding which of four meanings of "source" it refers to.++## 1. The bench substrate: two parallel harnesses, not one++They share no fixture format, no scorer, no report type and no emission path.+A new suite must pick a host or become a third.++### A. `runMemoryBench` — the staged phase harness++- Entry `src/core/bench/phases.ts:65`. Phases `ingest → index → retrieve →+ evaluate → report` (`src/core/bench/types.ts:14`), each checkpointed to+ `<runsDir>/<run-id>/checkpoint.json` (`src/core/bench/run-store.ts:84`).+ Resume validates the fixture hash before skipping work and refuses a changed+ fixture (`src/core/bench/run-store.ts:72-79`).+- A **fixture** is a repo-local JSON document: `notes[]` (vault-relative path ++ body), `continuity[]` (`session_turn` records only), `questions[]`. Parsed and+ validated fail-fast at `src/core/bench/fixture.ts:27`; note paths are checked+ against traversal and absolutes at `:112`; content-hashed at `:81`.+ `materializeBenchVault` (`:86`) writes the notes and appends the continuity+ records into a **disposable vault inside the run directory** — the operator's+ configured vault is never resolved.+- Six categories (`src/core/bench/types.ts:17-25`); four are retrieval+ (`:28-33`), plus `session_handoff` and `budget`. Retrieval drives `search()`,+ handoff drives `loadNormalizedContinuityRecords()`, budget drives+ `packContext()` — all three in `retrieveQuestion`+ (`src/core/bench/phases.ts:124-165`).+- **Scoring is deterministic containment**, in `evaluateQuestion`+ (`src/core/bench/phases.ts:175`): expected paths present in the ranked list+ and no `not_expected_above` path ranked higher (`:186-207`); turn count plus+ substring for handoff (`:210-229`); expected pack-item ids present for budget+ (`:232-241`). There is no hit@k, no MRR, no rank-sensitive number at all.+- Report `BenchReport` (`src/core/bench/types.ts:88`) keeps three families+ separate on purpose: `quality`, `latency_ms`, `context_cost`+ (`src/core/bench/phases.ts:274-292`).+- Emission: `report.json` in the run dir (`src/core/bench/phases.ts:117`) and+ stdout via `o2b brain bench memory` (`src/cli/brain/verbs/bench.ts:69-86`,+ exit 1 on any failing question). **No `appendMetric` call. No MCP tool.**+ Run dirs are gitignored (`.gitignore:29`).+- LoCoMo is an adapter, not a second harness: `loadLocomoFixture`+ (`src/core/bench/locomo.ts:189`) converts a LoCoMo dataset into a+ `BenchFixture` and hands it to the unchanged runner+ (`src/cli/brain/verbs/bench.ts:53`).++### B. `runRecallBenchmark` — the hit@k / MRR harness++- Entry `src/core/search/benchmark.ts:189`. Dataset is+ `{queries:[{id, query, expected[], k?, answer?}]}` (`:125`).+- Scores hit@k, MRR, answer-containment@k, source-utilization@k, citation+ depth, source warnings (`src/core/search/benchmark.ts:249-263`) against a+ **live vault** through `search()` — no disposable vault, no materializer.+- Four consumers: the CI gate test+ (`tests/core/search/recall-benchmark.test.ts`); `o2b brain benchmark run`+ (`src/cli/brain/verbs/benchmark.ts:24`), which appends a `recall_benchmark`+ metric (`:64-80`); MCP `brain_benchmark`+ (`src/mcp/brain/recall-tools.ts:79`, definition `:967`); and the rerank+ promotion gate `runRerankEvalGate` (`src/core/search/rerank-eval-gate.ts:66`),+ which runs the benchmark twice and compares.++### Baselines and CI gating++- **No baseline is committed as a file anywhere.** Both "baselines" are+ constants inside test files:+ `tests/core/search/recall-benchmark.test.ts:45-51`+ (`MIN_HIT_AT_5 = 0.9`, `MIN_MRR = 0.85`,+ `MIN_ANSWER_CONTAINMENT_AT_5 = 0.99`, with a re-measurement protocol in the+ header comment at `:1-20`), and `tests/cli/brain-bench.test.ts:44-45`+ (`quality.total === 6 && quality.passed === 6`).+- CI (`.github/workflows/ci.yml`) has **no bench step**. Its only relevant line+ is `bun test` (`.github/workflows/ci.yml:78`). Both harnesses therefore gate+ CI, but only as ordinary test files — there is no workflow invocation of+ `o2b brain bench memory`, no artifact upload, no threshold file, no trend.++### What this means for the shape of the work++`runMemoryBench` is the only harness with a disposable-vault materializer,+checkpointing, and a report that already separates metric families — all four+new metrics need a controlled vault, so it is the natural host. But its types+are closed unions keyed on `BenchCategory`. Adding a category touches+`src/core/bench/types.ts` (category list, question fields, result fields,+report fields), `src/core/bench/fixture.ts:138` (`parseQuestion`) and `:187`+(`validateQuestionShape`), and `src/core/bench/phases.ts` in three places+(`retrieveQuestion`, `evaluateQuestion`, `buildReport`) — plus a schema bump+past `o2b.bench.v1` (`src/core/bench/types.ts:12`) if any existing field+changes meaning.++## 2. Proactive injection: it exists, and its decision core is pure++The hook manifest is `hooks/hooks.json` (Claude Code auto-discovers it;+`.claude-plugin/plugin.json` declares no hooks). Registered injection surfaces:++| Surface | Event | Default | Decision core | Pure? |+| --- | --- | --- | --- | --- |+| `active-inject` | SessionStart, PostCompact | **ON** | `assembleActiveContext` `hooks/active-inject.ts:437` | yes |+| `recall-inject` | UserPromptSubmit | OFF (`src/core/config.ts:976`) | `decideRecallInject` `src/core/brain/recall-inject.ts:155` | yes, retriever injected |+| `nav-inject` | UserPromptSubmit | OFF (`src/core/config.ts:992`) | `decideNavInject` `src/core/brain/nav-inject.ts:33` | yes |+| `gap-agenda` | SessionStart | OFF (`src/core/config.ts:1034`) | `renderGapAgenda` `src/core/brain/gaps/gap-loop.ts:368` | yes |+| `pretool-orient` | PreToolUse | OFF (`src/core/config.ts:1019`) | `decideOrient` `src/core/brain/pretool-orient.ts:125` | yes (denies, does not inject) |++`active-inject` emits `hookSpecificOutput.additionalContext`+(`hooks/active-inject.ts:197-203`): standing rules first, read outside the+fail-open boundary (`:415`), then runtime notices + `Brain/active.md` ++`Brain/lessons.md` inside it (`:437`, `:463`, `:507`). Which preferences are+live is decided by `readActivePreferences(vault, agentScope)`+(`src/core/brain/active.ts:258`) → `renderActive` (`:138`). Only+`SessionStart` and `UserPromptSubmit` may carry `additionalContext`+(`hooks/lib/context-events.ts:23`).++**The decisive point for failure mode 1.** `active.md` is injected *wholesale*,+bounded only by a character budget (`budgetActiveBody`,+`src/core/brain/active-budget.ts:161`). There is no per-turn relevance+selection on the always-on path — it fires every session with everything.+Scoring `know_to_ask_failure_rate` or `false_fire_rate` against `active-inject`+is degenerate by construction.++The surface that *can* be silent is `recall-inject`:++```+decideRecallInject(prompt, retriever, options) -> "inject" | "abstain" | "error"+```++`src/core/brain/recall-inject.ts:155`, declared I/O-free and+retriever-agnostic in its own docblock (`:12-16`). Outcomes are exactly+`inject` (`:196`), `abstain{empty_prompt|no_matches|below_floor}`+(`:162`, `:187`, `:191`) and `error{timeout|retriever_failed}` (`:174`,+`:176`). Bounds: `RECALL_INJECT_CONFIDENCE_FLOOR = 0.35` (`:43`),+`RECALL_INJECT_MAX_NOTES = 4` (`:30`), `RECALL_INJECT_MAX_CHARS = 900`+(`:33`). **This is the seam that makes failure mode 1 measurable at all** —+the retriever is a parameter, so a fixture retriever runs the shipped decision+logic offline.++A second, earlier decision exists: `evaluateSurfacingGate(input)`+(`src/core/search/surfacing-gate.ts:70`) — a pure string function of+`(prompt, previousPrompt, explicit)` behind MCP `brain_recall_gate`+(`src/mcp/search-tools.ts:1130`). It suppresses only empty prompts+(`:74`), verbatim repeats (`:77-79`), slash commands (`:80`), and single+shell commands against a hardcoded name set (`:30-42`, `:82`) — and+**otherwise fails open** (`:85`). Scored alone, it produces `retrieve: true`+for essentially every natural-language prompt.++Also proactive: the anticipatory cache. `refreshAnticipatoryCache`+(`src/core/brain/anticipatory-cache.ts:298`) and `readAnticipatoryContext`+(`:371`) are synchronous and pure, composing `packContext` and+`searchSessionRecall` (plain lowercase substring matching,+`src/core/brain/session-recall.ts:194`); it is warmed unprompted off+`UserPromptSubmit`/`PostToolUse` lifecycle events+(`src/core/brain/session-lifecycle.ts:355-363`).++The most aggressive proactive consumer is not a Claude hook — it is Hermes:+`plugins/hermes/provider.py:481` calls `brain_recall_gate` (`:489`) and, when+it says retrieve, pulls `brain_context_pack` (`:491`) before every API call,+capped by `_PREFETCH_MAX_TOKENS = 1024` (`:105`).++The **only** live-model dependency on any injection path is the embedding call+at `src/core/search/semantic-phase.ts:162`, reached through+`defaultRecallRetriever` (`src/core/brain/recall-inject.ts:361`). Because the+retriever is a parameter, an offline bench never touches it.++## 3. Token accounting: nothing in this repo counts tokens exactly++There is no BPE tokenizer and no tokenizer dependency. There are **five**+estimators, and they disagree on the same input:++| Site | Formula | Unit |+| --- | --- | --- |+| `src/core/brain/text/tokenizer.ts:34-38` | `ceil(utf8_bytes / 4)` | UTF-8 bytes |+| `src/core/search/embeddings/signature.ts:84-91` | `ceil(str.length / 4)` | UTF-16 code units |+| `src/core/search/chunker.ts:57` | whitespace-run count | words |+| `src/core/bench/phases.ts:291` | `Math.ceil(avgChars / 4)`, inline | code points |+| `src/core/brain/token-impact.ts:206` | `baseline - packed` over caller-supplied ints | whatever the caller meant |++`estimateTokens` (`src/core/brain/text/tokenizer.ts:34`) is the closest thing+to canonical, and documents itself as a non-BPE heuristic at `:1-30`. Its+callers are the whole of Brain-side token accounting:+`src/core/brain/context-pack.ts:378`, `:509`, `:552`;+`src/core/brain/context-transforms.ts:65`;+`src/core/brain/token-footprint.ts:64`, `:130`;+`src/core/brain/generation-reports.ts:102`; `hooks/active-inject.ts:320`,+`:341`. The bench's own `context_cost.est_tokens`+(`src/core/bench/phases.ts:291`) does **not** import it — it re-implements a+different formula inline.++`brain_token_impact` (handler `src/mcp/brain/recall-tools.ts:417`, core+`src/core/brain/token-impact.ts:195`) performs **zero counting**: it is a+ledger over integers the harness posts. Its `method: "exact" | "fallback"`+field (`src/core/brain/token-impact.ts:61`, defaulted to `"fallback"` at+`src/mcp/brain/recall-tools.ts:435`) is an unverified caller claim; no adapter+in this repo posts `"exact"`. Default off+(`token_impact_ledger_enabled`, `src/core/config.ts:940`).++The **only token-denominated enforcement** is `packContext`'s `maxTokens`+(admission test `src/core/brain/context-pack.ts:510`, final sum `:627`).+Everything else that actually enforces is characters or code points:+`applyCharBudget` (`src/core/brain/recall-budget.ts:127`), `budgetActiveBody`+(`src/core/brain/active-budget.ts:161`),+`INJECT_BUDGET_CHARS_DEFAULT = 8000`+(`src/core/brain/policy/blocks/active.ts:58`),+`RECALL_INJECT_MAX_CHARS = 900`, `clipPayloadToBudget`+(`src/core/brain/continuity/store.ts:210`, budget measured as+`JSON.stringify(payload).length` at `:216`), `applySectionBudget`+(`src/core/brain/text/text-budget.ts:142`).++### What "per-harness" means here++| Harness | Injection code | Budget |+| --- | --- | --- |+| Claude Code | `hooks/hooks.json:27-33` → `hooks/active-inject.ts:493`, `:514` | chars (`resolveInjectionLimits` `hooks/active-inject.ts:391-401`) |+| Codex | `.codex-plugin/plugin.json:6` → `plugins/codex/hooks/active-inject.ts` (byte-identical copy) | same |+| OpenCode | `plugins/opencode/open-second-brain.ts:193`, injected at `:265` | none — pass-through |+| OpenClaw | `src/openclaw/index.ts:48-60` (`before_prompt_build`) | none; injects only an identity reminder |+| Hermes | `plugins/hermes/provider.py:476`, `:480` | tokens, hard-coded `1024` at `:105` |+| MCP | `src/mcp/brain/recall-tools.ts` (`brain_context_pack`) | caller-supplied, no server default |+| CLI | `src/cli/brain/verbs/context-pack.ts:31-39` | `--max-tokens` required, no default |++So a per-harness `avg_injected_tokens` is computable — but only by applying+`estimateTokens` to the string each adapter emits. No adapter reports a token+count, and four of seven do not enforce a token budget at all.++## 4. Source isolation: "source" is four unrelated concepts++Before the metric can be named, the noun has to be disambiguated:++1. **Ingested source** — a document imported into the vault; record is a+ Markdown summary page under `Brain/sources/` with `kind: brain-source`.+ Type `src/core/brain/ingest/sources-registry.ts:27`; frontmatter built at+ `src/core/brain/ingest/ingest.ts:154-167` (`source_path`, `source_hash`,+ `provenance`). Note `source_hash` is an identity hash of the path string+ (`ingest.ts:142-148`), not of content.+2. **Source trace** — every page derived from one source file.+ `searchBySourceFile` `src/core/brain/source-cleanup.ts:455`, match kinds at+ `:71`. Behind `brain_search_by_source` / `brain_delete_by_source`+ (`src/mcp/brain/ingest-tools.ts:133`, `:158`).+3. **Signal `source_type`** — the closed enum `live | inline | session`+ (`src/core/brain/signal.ts:271-273`), which is what `brain_sources` reports,+ grouped by `(agent, source_type)` (`src/core/brain/portability/sources.ts:71`).+4. **Cross-vault origin** — `local`, `profile/<name>`, `source/<alias>`+ (`src/core/brain/portability/origins.ts:42-73`).++### The isolation notion that actually exists is OWNER scope++One rule: `isOwnerVisible(owner, scope)`+(`src/core/graph/agent-scope.ts:104`) — no requested scope means no filtering+(`:16-19`); an ownerless page is shared; an unparseable `owner:` fails closed+as somebody else's (`:52`). Gated by config `integrity.owner_scope_delivery`+(`off | warn | fail`), **default `off`**+(`src/core/brain/policy/blocks/integrity.ts:67`). Consumers include+`src/core/search/result-filters.ts:317`,+`src/core/brain/preferences-collect.ts:280`,+`src/core/brain/owner-scoped-facts.ts:42`.++Agent identity is *recorded* but does not *partition*: `resolveAgentName`+(`src/core/config.ts:369`) stamps `agent` on signals/log lines+(`src/core/brain/log.ts:57`) and `source_agent` on entities+(`src/core/brain/entities/types.ts:57`, stamped+`src/core/brain/entities/registry.ts:504`), but nothing copies it into+`owner`, and ingested source pages carry no `owner` at all+(`src/core/brain/ingest/ingest.ts:154-167`).++### A ready-made violation counter — with a naming trap++`packContext` already counts cross-owner items:+`collectCandidates` returns `hiddenByOwnerScope`+(`src/core/brain/context-pack.ts:311`, accumulated `:329`, returned `:387`).+Under `warn`, `formatOwnerScopeWarning`+(`src/core/brain/preferences-collect.ts:307-318`) renders it as+`"N memory item(s) owned by another agent **were delivered**"` — i.e. under+`warn` the counter is a *delivered-leak* count, exactly a+`source_isolation_violations` numerator. Under `fail` the function returns+`null` at `:311` and nothing is reported. The variable name says "hidden"; the+message says "delivered"; they are the same number in different modes.++### Cross-vault++The union happens in exactly one place: `searchAcrossVaults`+(`src/core/search/cross-vault.ts:94`, merge `:150-215`). Origin labels are+attached to every result twice — as `origin` and as an `origin:<label>` entry+in `reasons[]` (`:44-50`), mirrored onto cards at `:53-59`. Non-active origins+are read-only (`selfHeal: false`, cache off, `:157-167`). There is no+vault-level ACL: any registered profile or source vault is fully readable.++### Existing leakage invariants++- `tests/core/brain/source-cleanup.test.ts:152-155` — the only genuine+ "content derived from source A must not appear in a result scoped to source+ B" assertion, with a deliberately-planted second source (`:79-88`). Delete+ side at `:213`, `:236`.+- `tests/mcp/agent-scope-matrix.test.ts:362-379` — for five gated surfaces:+ `expect(out).not.toContain("owned-by-a")` under gate `fail`, plus own-memory+ retention. Per-surface leakage assertions at `:460-473`+ (`brain_search_expand` rejects a foreign chunk), `:475-487`+ (`second_brain_query` paths **and** `total_pages`), `:510-530`+ (`brain_search_by_source` entries **and** total), `:596-615`.+- `:391-404` asserts the converse invariant: scoping must not narrow the shared+ `Brain/active.md` (byte equality at `:403`).++### Verification of t_b18551b1++**Partly refuted.** The exactly-once partition test is real —+`tests/mcp/agent-scope-matrix.test.ts:299-311`+(`expect(new Set(classified).size).toBe(classified.length)` then a+bidirectional `toEqual(actual)`), with a count pin at `:313-315`+(`expect(TOOLS.length).toBe(110)`). But it is **not** the only assertion: the+`SCOPED_SURFACES` bucket carries the behavioural leakage assertions listed+above, plus a schema check that every argument-scoped surface declares+`agent_scope` (`:317-329`).++Where the claim **holds**: `UNSCOPED_CONTENT` (`:88-114`) and `NON_CONTENT`+(`:117-206`) are prose-justified lists with no test that a `NON_CONTENT` tool+actually returns nothing owner-taggable; and within `SCOPED_SURFACES`+(`:66-81`), `brain_query` (`:73`) and `brain_search` (`:74`) get only the+schema-declares-`agent_scope` check, while `brain_retrieval_plan` gets only a+coarse `item_count` comparison (`:447-456`). Net: classification correctness is+asserted for roughly 12 of 14 scoped tools and for **zero** of the other 96.++One further gap: `tests/core/search/cross-vault.test.ts:64-74` asserts the+*set* of origin labels and that each result carries some `origin:` reason — it+never asserts that a result labelled `local` came from the active vault. The+origin-mislabelling failure is untested.++## 5. Write-back: the extractor seam is already the only mode++**Extraction is agent-side. The server never calls a model.**+`grep -riE 'api\.anthropic|api\.openai|/v1/chat/completions|/v1/messages|generativelanguage' src/`+returns zero hits; the only `fetch` calls under `src/core/brain/` are+`research/external-fetch.ts:231`, `explorer.ts:324` and+`capture/telegram-capture.ts:418,433` — none on the write path.++The contract is stated repeatedly in the code:+`src/core/brain/fact-extract.ts:5-7` ("without an LLM call"),+`src/core/brain/session-checkpoint.ts:31`,+`src/core/brain/distill/distill-source.ts:10-12` ("the calling agent supplies+the atomic claims… this core runs NO model"),+`src/core/brain/diarization.ts:16`, and+`src/mcp/brain/context-tools.ts:579` ("The calling agent generates; the Brain+never does"). Where prose *is* required, core returns a `needs-llm-step`+envelope for the caller to fulfil+(`src/core/brain/write-session/types.ts:23-35`,+`src/core/brain/write-session/engine.ts:98`).++**Consequence for the task framing:** "an injectable-extractor seam that runs+the shipped segmentation/insertion/dedup code with ZERO LLM calls in CI" is not+a seam to build — it is the default and only mode. What a fidelity bench must+supply is the *caller's* structured intake, which is exactly the shape+`brain_feedback` and `brain_session_checkpoint` already accept.++### Entry points and their input shape++| Entry | Anchor | Input |+| --- | --- | --- |+| `brain_feedback` | `src/mcp/brain/feedback-tools.ts:700` (schema), write `:157` | structured (`topic`/`signal`/`principle`/`scope`/`source[]`/`raw`) |+| `brain_session_checkpoint` | `src/mcp/brain/synthesis-tools.ts:150`, core input `src/core/brain/session-checkpoint.ts:59-88` | structured array of signals + decisions/learnings |+| `brain_write_batch` | `src/mcp/brain/write-batch-tools.ts:190`, mapper `:64-138` | structured note ops |+| `brain_pre_compact_extract` | `src/mcp/brain/pack-tools.ts:600` (handler), `:986` (schema) | **raw bounded text** |+| `o2b brain import-session` | `src/cli/brain/verbs/import-session.ts:40` | **raw transcript JSONL** |+| aider wrapper | `src/cli/aider.ts:107-112` | raw transcript tail → `extractPreCompactRecords` |++Raw prose enters at exactly two doors: `import-session` and+`brain_pre_compact_extract`.++### Server-side recognizers (all regex, all deterministic)++1. Structural facts — url / email / quantity only:+ `src/core/brain/fact-extract.ts:90-94`, applied at `:144`. Deliberately+ language-agnostic; the docblock at `:8-13` explains that English trigger+ phrases were removed as a defect.+2. Labeled lines — `src/core/brain/pre-compact-extract.ts:60-66`+ (`decision:`, `commitment:`, `outcome:`, `rule:`, `open question:`), applied+ `:142-158`. Input truncated at `DEFAULT_MAX_CHARS = 40_000` (`:68`, `:77`),+ recorded as `truncated_input` (`:120`).+3. Inline `@osb` markers — `src/core/brain/inline.ts:850`, consumed at+ `src/core/brain/sessions/import.ts:387`.++Validation of caller-supplied structure: `validateBrainFeedbackInput`+(`src/core/brain/sessions/validate-feedback.ts:57`, shared by live MCP and+session replay), then `src/core/brain/signal.ts:257-275`.++### Segmentation, insertion, dedup++- **Segmentation** operates on already-normalized turn records, never free+ text: `DEFAULT_GROUP_SIZE = 8` (`src/core/brain/session-recall.ts:148`),+ two-level grouping at `:366-412`, and the "summary" is concatenated truncated+ lines (`summarizeGroup` `:560-572`).+- **Insertion**: `writeSignal` (`src/core/brain/signal.ts:235`, atomic name+ allocation `:311-335`, frontmatter render `:360-426`) → `Brain/inbox/sig-*.md`,+ or `Brain/pending/` under write-approval+ (`src/core/brain/fact-extract.ts:341-349`). Continuity rows via+ `appendContinuityRecord` (`src/core/brain/continuity/store.ts:100`, append+ under lock `:284-301`).+- **Dedup, four independent layers**: content hash over+ (topic, sign, principle, scope) `src/core/brain/dedup-hash.ts:86` with a+ read-side index at `:55-84`; fact hash `src/core/brain/fact-extract.ts:185`+ (chain order documented at `:353`); idempotency ledger+ `src/core/brain/signal.ts:282-298` (same key + different payload throws);+ continuity `dedupe_key` `src/core/brain/pre-compact-extract.ts:91-102`.++### Provenance fields available to grade++Authoritative list is `renderSignalDocument`+(`src/core/brain/signal.ts:360-426`): `id` `:367`, `created_at` `:368`,+`agent` `:372`, `scope` `:378`, `source[]` wikilinks `:381`, `source_type`+`:387-393`, `schema_type` `:395`, `dedup_hash` `:398`, `session_ref` `:401`,+`origin_vault` `:404`, `valid_from` `:410`, `recorded_at` `:413`,+`authored_at` `:418`, `expiration_date` `:424`. Event-time policy:+`resolveEventInstant` (`src/core/brain/sessions/import.ts:124-135`) — outside+the `epoch < ts <= now` window it falls back to wall clock and emits **no**+bi-temporal keys, which is itself a gradeable fidelity outcome.+**No confidence score is written onto a signal.**++Continuity provenance: `schema`, content-hash `id`, `kind`, canonical-UTC+`createdAt`, `sourceRefs[]`, `payload`, `private`, `redacted`+(`src/core/brain/continuity/store.ts:256-282`), with+`session_id`/`turn_start`/`turn_end`/`content_hash`/`dedupe_key` on the+pre-compact payload (`src/core/brain/pre-compact-extract.ts:108-121`).++### Existing "fixed conversation in, assert the files out" tests++Four, all pass/fail rather than scored:+`tests/core/brain.sessions.import.test.ts:113-136` (asserts `session_ref` and+the `[[basename#turn]]` wikilink, and that the absolute path is absent);+`tests/e2e/brain-capture-and-fields.test.ts:37`;+`tests/core/brain/pre-compact-extract.test.ts:20-51` (exact ordered+`extract_type` list plus source refs); and+`tests/core/brain/fact-extract.anchoring.test.ts:75-92`. Host fixtures exist+for five runtimes at `tests/fixtures/sessions/{claude,codex,grok,hermes,opencode}-minimal.jsonl`.++## 6. Determinism and CI cost++- CI is one job. The only test step is `bun test`+ (`.github/workflows/ci.yml:78`); the local wrapper is+ `scripts/test` → `exec bun test`.+- A **deterministic offline embedder ships**: `LocalProvider`+ (`src/core/search/embeddings/local-provider.ts:67-78`) — FNV-1a feature+ hashing over token unigrams and character trigrams, unit-normalised,+ dependency-free, no key, no download. The recall-benchmark CI gate already+ runs on it: `tests/core/search/recall-benchmark.test.ts:60-64`+ (`semantic: { enabled: true, provider: "local", dimension: 256 }`), and pins+ determinism explicitly at `:155-160` (two runs must be `toEqual`).+- **Measured wall clock** on this machine:+ `bun test tests/core/search/recall-benchmark.test.ts` → 1.57 s for 10 tests+ including a full `indexVault` with embeddings;+ `bun test tests/core/bench/ tests/cli/brain-bench.test.ts` → 2.03 s for 20+ tests across 5 files. A fourth-metric suite of comparable size is low+ single-digit seconds — CI cost is not a constraint.+- **Determinism is environmental, not enforced.** `runMemoryBench` calls+ `resolveSearchConfig({ vault })` with no config path+ (`src/core/bench/phases.ts:82`, `:89`), and that function still reads+ `process.env` (`src/core/search/index.ts:401`). `search_semantic_enabled`+ defaults to `false` (`src/core/search/index.ts:455-459`) — but+ `OPEN_SECOND_BRAIN_SEARCH_SEMANTIC`, `OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER`+ and the API-key variables are **not** in the test-helper scrub list+ (`tests/helpers/run-cli.ts:36-46`, which scrubs nine unrelated names). The+ "deterministic and network-free" claim at `src/core/bench/phases.ts:12-13` is+ therefore a property of the default shell, not an invariant the harness+ holds. A developer with semantic search configured runs a different bench+ than CI does.++## Divergences++Where the task framing does not survive contact with the source.++1. **"The existing bench" is two benches.** `runMemoryBench` and+ `runRecallBenchmark` share nothing. The task's own hint list names both+ without distinguishing them. Any plan must say which one it extends; the+ answer is almost certainly `runMemoryBench` (§1), and the cost is a closed+ union widened in four files plus a report-schema decision.++2. **The extractor seam is not new — it is the only mode.** The server never+ calls a model on any write path (§5). "Injectable extractor seam with zero+ LLM calls" describes the shipped architecture. The real design question is+ the inverse of the one asked: not *how to inject a fake extractor*, but+ *what structured intake a fixture supplies* to stand in for a real agent's+ distillation, and whether grading that is measuring memory or measuring the+ fixture author.++3. **`know_to_ask` is only scoreable on a default-OFF surface.** The+ always-on injection path (`active-inject`) has no know-to-ask decision — it+ injects `active.md` wholesale every session. The only code that can choose+ silence on a real prompt is `decideRecallInject`+ (`src/core/brain/recall-inject.ts:155`), behind `recall_inject_enabled`,+ default off (`src/core/config.ts:976`). A metric that gates CI would be+ gating a feature most installs do not run.++4. **`false_fire_rate` against `brain_recall_gate` is degenerate.**+ `evaluateSurfacingGate` fails open by design+ (`src/core/search/surfacing-gate.ts:66-68`, `:85`): every prompt that is not+ empty, a verbatim repeat, a slash command or a bare shell command retrieves.+ Its false-fire rate is ~1 by construction. The anti-gaming pressure the task+ wants must be applied to the confidence floor and ranking inside+ `decideRecallInject`, not to the gate.++5. **`avg_injected_tokens` has no token count to average.** Five estimators+ disagree (§3); the bench already uses a sixth formula inline+ (`src/core/bench/phases.ts:291`); `brain_token_impact` counts nothing+ (`src/core/brain/token-impact.ts:206`). Four of seven harnesses enforce no+ token budget at all. The metric is buildable, but only as+ "`estimateTokens` applied to the emitted string" — and stating that+ explicitly is the difference between an honest number and one that implies+ a precision the repo does not have.++6. **`source_isolation_violations` names four different things** (§4), and the+ isolation notion that actually exists is *owner* scope, not source scope,+ and it is **default `off`**+ (`src/core/brain/policy/blocks/integrity.ts:67`). Gating at zero under the+ shipped default is vacuous: with no requested scope there is no filtering+ (`src/core/graph/agent-scope.ts:16-19`), so nothing can be violated. The+ metric only has content if the fixture forces+ `integrity.owner_scope_delivery: fail`.++7. **The counter that exists reports in the wrong mode.**+ `hiddenByOwnerScope` is surfaced only under `warn`, where it counts items+ that **were delivered** (`src/core/brain/preferences-collect.ts:313-316`);+ under `fail` it is deliberately unreported (`:311`). A zero-gated invariant+ must therefore assert on pack *contents* — as+ `tests/mcp/agent-scope-matrix.test.ts:368-372` already does — not read a+ counter.++8. **t_b18551b1's claim is partly wrong** and should be re-scoped before it is+ acted on (§4). The matrix does assert behavioural non-leakage for its gated+ surfaces; what it does not assert is anything about the 96 tools in+ `UNSCOPED_CONTENT` and `NON_CONTENT`.++9. **The only prose recognizer in the write path is English-only.**+ `src/core/brain/pre-compact-extract.ts:60-66` hardcodes `decision`,+ `commitment`, `outcome`, `rule`, `open question`. This contradicts the rule+ the sibling extractor states in its own docblock+ (`src/core/brain/fact-extract.ts:8-13`: a per-language phrase list is a+ defect). A write-back fidelity fixture written in any other language scores+ 0 through that door for a reason that is not a memory failure.++10. **The bench emits no metric, so a new family has no dashboard path.**+ `runMemoryBench` writes only `report.json`; `docs/metrics.md:56-70` lists+ no `o2b.bench.*` surface. Anything meant to be trended must go through+ `appendMetric` (`src/core/brain/metrics.ts`).++11. **The metrics contract has already drifted.** `docs/metrics.md:62`+ documents `recall_benchmark` with six payload fields; the CLI writes eleven+ (`src/cli/brain/verbs/benchmark.ts:66-79`) and the MCP tool writes six+ (`src/mcp/brain/recall-tools.ts:107-118`) — two writers on one surface with+ different fields, neither matching the doc.++12. **Determinism is a property of the environment, not the harness** (§6).++## What a design must not assume++- That there is one bench to extend. There are two, and neither generalises to+ the other's fixture format.+- That a new extractor seam is needed. It is not; the seam that matters is the+ *retriever* parameter in `decideRecallInject`, which already exists.+- That the default-on injection path makes a relevance decision. It does not.+- That `brain_recall_gate` is the know-to-ask decision. It is a cheap+ suppressor that fails open.+- That any token number in this repo is exact, or that two token numbers from+ different modules are comparable.+- That "source" is one concept, or that source isolation is enforced by+ default. Owner scope is the only isolation primitive, and it ships `off`.+- That a violation counter can be read out of a `fail`-mode pack. It cannot.+- That the harness's network-freedom is enforced. It is inherited from an unset+ environment and not scrubbed by the CLI test helper.+- That a fixture written in one natural language exercises the same code paths+ as one written in another — `pre-compact-extract` recognises English labels+ only.+- That CI cost is a constraint. It is not: the comparable existing suites run+ in 1.6–2.0 s with the offline `LocalProvider`.diff --git a/docs/brainstorm/nothing-runs-unwatched/recon/ingest-adapters-and-lease.md b/docs/brainstorm/nothing-runs-unwatched/recon/ingest-adapters-and-lease.mdnew file mode 100644index 00000000..e1d9fb02--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/recon/ingest-adapters-and-lease.md@@ -0,0 +1,552 @@+# Recon — ingest source adapters and the writer lease (t_da034197)++Reconnaissance only. Branch `feat/nothing-runs-unwatched`, base v1.47.0+(`aa818084 feat: wiring what exists (v1.47.0) (#164)`). Every claim below carries+a `path:LINE` anchor that was read in this pass. Where something could not be+established, it says so.++---++## 1. Every ingest / import path that exists++### 1.1 Session transcript import++- Entry: `src/core/brain/sessions/import.ts:206` `importSession(vault, path, opts)`+ (single `.jsonl` file) and `src/core/brain/sessions/import.ts:582`+ `importSessionPath` (directory walk, `.jsonl` only, `src/core/brain/sessions/import.ts:619`).+- Input shape: one JSONL transcript file per runtime schema, normalised to+ `SessionTurn` (`src/core/brain/sessions/types.ts:119`) by an adapter.+- Reachability: **CLI only**. The single caller is+ `src/cli/brain/verbs/import-session.ts:91` / `:108`. A grep for+ `import_session` / `import-session` over `src/mcp/` returns nothing — there is+ no MCP tool for session import.+- Writes: signals via `writeSignal` (`src/core/brain/sessions/import.ts:276`),+ skill-invocation continuity records (`:431`), extracted facts (`:373`), the+ recall DAG (`:488`), one dedup-telemetry record per file (`:513`), and one+ `appendLogEvent` per file from the CLI (`src/cli/brain/verbs/import-session.ts:130`).++### 1.2 Source-artifact ingest++- Entry: `src/core/brain/ingest/ingest.ts:111` `ingestSource(vault, input, opts)`.+- Input shape: `IngestSourceInput` (`src/core/brain/ingest/ingest.ts:51`) — a+ source identity (vault-relative path **or** URL), agent-written summary prose,+ and an already-extracted entity/relation set. The kernel runs no model+ (`src/core/brain/ingest/ingest.ts:10-15`).+- Reachability: **MCP** (`brain_ingest_source`, `src/mcp/brain/ingest-tools.ts:32`,+ handler `:41`, call `:60`), **in-process SDK**+ (`src/core/brain/sdk.ts:118`), and **the inbox drain**+ (`src/core/brain/capture/inbox-drain.ts:158`, routing a URL-shaped capture).+ No dedicated CLI ingest verb calls it.++### 1.3 Batch planner for large-folder ingest++- Entry: `src/core/brain/ingest/batch-plan.ts` `planBatches`; MCP tool+ `brain_ingest_batch_plan` (`src/mcp/brain/ingest-tools.ts:35`).+- Read-only by design: "the kernel runs NO ingestion and spawns NO subagents+ itself" (`src/core/brain/ingest/batch-plan.ts:9-11`). It consults the content+ manifest and the checkpoint and returns batches; **the caller dispatches each+ batch as a parallel subagent** (same lines). This is load-bearing for §4.++### 1.4 Git history ingest, and `mine`++- Entry: `src/core/brain/git/ingest.ts:109` `ingestGitHistory(vault, repoPath, opts)`.+- Input shape: a worktree path plus `maxCount` (`src/core/brain/git/ingest.ts:58`).+ Read-only against the repo; all writes land in the vault (`:20-22`).+- Entry: `src/core/brain/git/decisions.ts:111` `mineCommitDecisions(vault, repoKey)` —+ the `mine` half. Input is the already-ingested commit store, output is ADR+ candidate notes.+- Reachability: **CLI only** — `src/cli/brain/verbs/git.ts:34` (`ingest`) and+ `:37` (`mine`); calls at `:110` and `:56`. No MCP surface.++### 1.5 Claude-memory / agent-memory manifest import++- Entry: `src/core/brain/import-claude-memory.ts` `importClaudeMemory({vault, memoryDir, mode, backend})`.+- Input shape: a directory of runtime memory files, parsed by a **backend**+ (§2.3). CLI resolves the backend and the directory at+ `src/cli/brain/verbs/import-claude-memory.ts:102-104`.+- Reachability: **CLI only** (`src/cli/brain/verbs/import-claude-memory.ts:9`).++### 1.6 Truth / claim ingest++- Entry: `src/core/brain/truth/ingest.ts:51` `claimsFromAssertion`.+- Input shape: one atomic assertion plus an explicit entity; only assertions+ matching a structured fact family ingest (`src/core/brain/truth/ingest.ts:4-6`,+ structurers at `:40-43`).+- Reachability: `o2b brain facts decompose --ingest` and an MCP ingest op+ (`src/core/brain/truth/ingest.ts:6-7`); help text at+ `src/cli/brain/help-text.ts:433-436`.++### 1.7 Other import-shaped verbs (named, not fully traced)++`src/cli/brain/verbs/`: `inbox-drain.ts` (dry-run default + `--apply`,+docblock `:5`), `bank-import.ts`, `graph-import.ts`, `okf-import.ts`,+`telegram-capture.ts`, `apply-markers.ts` (`:5-6`), `scan-inline.ts`.+These write into the vault from outside material but were not traced to their+lock/dry-run details in this pass.++### 1.8 The thing that is *not* an ingest path++`src/core/brain/ingest/sources-registry.ts` — confirmed as the triage said. It is+list/get/delete over the `Brain/sources` summary pages the pipeline already wrote+(`:82`, `:113`, `:132`), with a containment check that refuses ids outside+`Brain/sources` (`:69-79`). No adapter, no dispatch, no registration.++---++## 2. How adapters are selected today++### 2.1 Session adapters — a frozen array with sniffing plus an explicit override++- Dispatch structure: a **frozen array**, not a map or a switch —+ `src/core/brain/sessions/registry.ts:19-25`, five members+ (claude, codex, hermes, opencode, grok).+- Selection is **both**: explicit caller argument wins, else sniff. `chooseAdapter`+ at `src/core/brain/sessions/import.ts:191-204`: `opts.format` → `getAdapter`;+ otherwise read the first line only (`firstLineOfFile`,+ `src/core/brain/sessions/import.ts:165-172`) and probe adapters in registry+ order (`detectAdapter`, `src/core/brain/sessions/registry.ts:42-47`, first match+ wins).+- No match → **explicit failure**, not an empty result:+ `SessionImportError("DETECT_FAIL", …; pass --format to override)` at+ `src/core/brain/sessions/import.ts:198-201`. An unknown `--format` is rejected+ before any work at `src/cli/brain/verbs/import-session.ts:74-76`, and+ `getAdapter` throws on an unregistered id+ (`src/core/brain/sessions/registry.ts:56`).+- Directory walk downgrades `DETECT_FAIL` to a per-file **warning** and continues+ (`src/core/brain/sessions/import.ts:636-643`). That is reported, not silent.+- Cross-table locked by `tests/core/brain.sessions.registry.test.ts:66-80`.+- One near-silent arm, reported rather than hidden: a session the capture boundary+ classifies `ignore` returns an all-zero result+ (`src/core/brain/sessions/import.ts:324-343`), but the reason travels on+ `boundary_decision` (`:335`).++### 2.2 Discipline transcript runtimes — an array with **no** selection and a silent-empty failure++- `src/core/discipline/transcripts/index.ts:20-24` `DEFAULT_TRANSCRIPT_RUNTIMES`+ is a second hardcoded array (claudecode, codex, cursor). There is no `detect`+ in the contract (`src/core/discipline/transcripts/types.ts:59-74`) — the+ aggregator runs **every** runtime unconditionally+ (`src/core/discipline/transcripts/index.ts:37-47`).+- **Defect worth naming.** `claudeCodeTranscript.collect` returns `[]` for three+ different conditions: the base dir does not exist+ (`src/core/discipline/transcripts/claude-code.ts:21`), `readdir` failed —+ permissions, I/O (`:27`), and a project dir that cannot be read (`:34`), plus a+ per-file `stat` failure swallowed at `:44`. All surface identically as+ `fileCount: 0` (`src/core/discipline/transcripts/index.ts:41`), which is the+ same value as "the agent genuinely did nothing today". The signal feeds an alert+ decision (`src/core/discipline/transcripts/index.ts:5-9`), so an unreadable home+ reads as a clean "no activity confirmed".++### 2.3 Memory backends — a real registry, by id, from config++- `src/core/brain/agent-backend/registry.ts:18-22` — a frozen `ReadonlyMap`+ keyed by backend id (claude, mem0, generic).+- Selection is by **explicit id or config key**, never by sniffing:+ `getMemoryBackend(id)` (`:30`) throws with the registered list on an unknown id+ (`:32-37`); `resolveMemoryBackend` reads the `memory_backend` device-config key+ with `claude` as default (`:45-48`). CLI `--from` / `--backend` overrides+ (`src/cli/brain/verbs/import-claude-memory.ts:43-48`, resolution at `:102-103`).+- The protocol (`src/core/brain/agent-backend/types.ts:45-70`) states the exact+ property (a) asks for: "Adding a runtime means adding ONE module that satisfies+ this interface and registering it — no changes to the import core, CLI, or MCP+ surfaces" (`:9-11`).++### 2.4 Other registries in the tree++`src/core/brain/agent-source/registry.ts:10` (frozen provider array, all providers+always collected, `:14-23`), `src/core/install/registry.ts`,+`src/core/search/embeddings/registry.ts`, `src/core/search/rerank/registry.ts`,+`src/core/brain/entities/registry.ts`, `src/core/egress/registry.ts`.++---++## 3. The closed-vocabulary house idiom++### 3.1 Confirmed against two real examples++`src/core/brain/triggers/types.ts`:++- frozen object, camelCase key → snake/kebab value: `:20-28` (`TRIGGER_STATUS`);+- derived union type: `:30` `type TriggerStatus = (typeof TRIGGER_STATUS)[keyof typeof TRIGGER_STATUS]`;+- members array: `:37-45` `TRIGGER_STATUSES: ReadonlyArray<TriggerStatus>`, frozen,+ built from the object's own keys;+- guard whose parameter is `unknown`: `:47-49`+ `isTriggerStatus(value: unknown): value is TriggerStatus`.++`src/core/search/provider-probe.ts`: `PROVIDER_PROBE` `:58`, `ProviderProbeState`+`:66`, `PROVIDER_PROBE_STATES` `:69-75`, `isProviderProbeState(value: unknown)`+`:82`.++### 3.2 What the census enforces++`tests/core/architecture/verdict-vocabulary-census.test.ts`:++- the registered shape is `{name, values, members, guard}`+ (`:186-195`, guard typed `(value: unknown) => boolean` at `:194`);+- the audit (`:213-247`) asserts: `values` is frozen; no duplicate value; no+ duplicate member; every declared value is a member and is accepted by the guard;+ every member is declared by some value; and the guard rejects every entry of+ `NON_MEMBERS` (`:202-210` — `""`, `" "`, a near-miss string, `null`,+ `undefined`, `42`, `{}`);+- registration is one entry appended to `CENSUS` (`:250-617`), and the suite fails+ if the registry is emptied rather than fixed (`:621-626`).++### 3.3 What a new adapter-kind vocabulary must look like++Concretely, in the module that owns the vocabulary (not in the registry file):++```ts+export const INGEST_ADAPTER_KIND = Object.freeze({+ sessionTranscript: "session-transcript",+ sourceArtifact: "source-artifact",+ gitHistory: "git-history",+ agentMemory: "agent-memory",+} as const);+export type IngestAdapterKind =+ (typeof INGEST_ADAPTER_KIND)[keyof typeof INGEST_ADAPTER_KIND];+export const INGEST_ADAPTER_KINDS: ReadonlyArray<IngestAdapterKind> =+ Object.freeze([ /* every member, spelled from INGEST_ADAPTER_KIND.* */ ]);+export function isIngestAdapterKind(value: unknown): value is IngestAdapterKind {+ return typeof value === "string" &&+ (INGEST_ADAPTER_KINDS as ReadonlyArray<string>).includes(value);+}+```++Registered by adding one `{name, values, members, guard}` entry to `CENSUS` at+`tests/core/architecture/verdict-vocabulary-census.test.ts:250-617`.++A companion vocabulary for the *failure* arm is what §2.2 is missing: "base+absent" vs "base unreadable" vs "no activity" cannot be one value.++**Existing violation, in scope.** `isSessionAdapterId` takes `string`, not+`unknown` (`src/core/brain/sessions/registry.ts:27`), and `SessionAdapterId` is a+hand-written string union (`src/core/brain/sessions/types.ts:108`) with no frozen+object and no members array. `SESSION_ADAPTERS` is not in the census. So the+existing adapter identity does *not* follow the house idiom, and a new adapter+vocabulary cannot be derived from it without rewriting it first.++---++## 4. The writer lease++### 4.1 The primitives++Three, not one.++| primitive | file | mechanism | stale policy | retry | re-entrant |+|---|---|---|---|---|---|+| `withFileLock` (async) | `src/core/reliability/lock.ts:22` | `proper-lockfile` | 30 s default (`:32`) | 3 × 250 ms (`:34-39`) | no |+| `acquireLockSync` | `src/core/brain/sync-lockfile.ts:65` | `openSync(target + ".lock", "wx")` (`:72`) | **none** | **none** (`:13-15`) | no (`:75-80` → `ELOCKED`) |+| `acquireWriterLockSync` / `acquireWriterLock` | `src/core/search/store/writer-lock.ts:37` / `:64` | `proper-lockfile` on the live index path | 60 s (`:18`), 30 s heartbeat on the async form (`:29`, `:71`) | 10 × 50 ms sync / 3 × 1 s async | no |++`withFileLock` has exactly two callers: `src/core/brain/schema-mutate.ts:197` and+`src/core/brain/health-baseline.ts:58`. It is **not** on any ingest path.++### 4.2 Granularity, hold time, crash behaviour++- Granularity is **per target file**, never per vault: the preference file+ (`src/core/brain/preference-txn.ts:182`), the continuity month shard+ (`src/core/brain/continuity/store.ts:291`), the idempotency month shard+ (`src/core/brain/idempotency-ledger.ts:157`), the log **directory**+ (`src/core/brain/log.ts:243`), the search index path+ (`src/core/search/store/writer-lock.ts:43`).+- Hold time is the duration of one write. The one existing exception, and the+ precedent a whole-run lease should follow, is the skill-accept lock: taken once+ and held across the entire multi-step sequence+ (`src/core/brain/skill-proposals.ts:633`, `:741`, `:765`), with a named typed+ refusal on contention (`SkillAcceptLockedError`, `:819-828`) and a journal so an+ interrupted sequence is rolled forward or back (`:836-861`).+- Stale policy for the brain sync lock: **there is none**. Normal process exit+ unlinks held locks via an exit hook (`src/core/brain/sync-lockfile.ts:40-53`);+ a hard crash (SIGKILL/OOM) leaves the `.lock` on disk forever and the next+ acquire fails `ELOCKED` (`:17-21`). Recovery is manual: the doctor lists every+ `.lock` under `Brain/` as an *uncertainty*, explicitly refusing to break it+ because "a live writer cannot be told from a dead one"+ (`src/core/brain/doctor/uncertainty-probes.ts:133-148`,+ `src/core/brain/sync-lockfile.ts:123`).+- Contention is mapped to typed refusals, never retried into silence:+ `BrainCollisionError(sourceLock)` (`src/core/brain/preference-txn.ts:185-190`),+ `SearchError("INDEX_LOCKED")` (`src/core/search/store/writer-lock.ts:34`).++### 4.3 The concrete cost of the current discipline in an ingest++**`ingestSource` × N sources — zero locks, `2N` unlocked read-modify-writes.**++Reading the body of `src/core/brain/ingest/ingest.ts:111-216`: the summary page is+written with `writeFrontmatterAtomic` (`:186`) after a byte-compare no-op check+(`:182-187`) — no lock. Then, per source:++- `updateManifest(vault, [canonicalSource])` (`:194`) →+ `src/core/brain/ingest/content-manifest.ts:227-239`: read the whole manifest,+ merge one entry, `atomicWriteFileSync` (`:180`). **One vault-global file, no+ lock.**+- `recordCompleted(...)` (`:201`) →+ `src/core/brain/ingest/checkpoint.ts:170-194`: read the plan checkpoint, union+ one path, `atomicWriteFileSync` (`:192`). **One per-plan file, no lock.** The+ call is wrapped in a bare `try {} catch {}` (`:200-204`) — a checkpoint write+ failure is swallowed by design.++So an ingest of N sources performs **0 acquire/release cycles** and **2N unlocked+read-modify-write cycles on two shared files**. Under the parallel-subagent+dispatch the batch planner prescribes (`src/core/brain/ingest/batch-plan.ts:9-11`),+those 2N cycles race last-writer-wins across processes.++**`importSession` — locks per side effect, not per signal.**++- `writeSignal` takes **no lock**: name allocation and creation are one exclusive+ create with a candidate ladder (`src/core/brain/paths.ts:879-901`,+ `src/core/brain/sessions/import.ts:276`). Session import supplies no+ `idempotency_key`, so the ledger's shard lock is never taken either.+- One acquire/release per **skill invocation** record+ (`src/core/brain/sessions/import.ts:431` → `src/core/brain/continuity/store.ts:291`).+- One acquire/release per **new recall turn**, plus per summary node+ (`src/core/brain/session-recall.ts:351` → same `appendRecord`); the batch helper+ that would collapse these into one lock per shard+ (`src/core/brain/continuity/store.ts:168-176`) is not on this path.+- One per file for the dedup-telemetry record, only when something deduped+ (`src/core/brain/sessions/import.ts:511-517`).+- One **log-directory** lock per file, with a 10 × 50 ms retry loop+ (`src/cli/brain/verbs/import-session.ts:130` → `src/core/brain/log.ts:238-252`).++Total for a directory of F files with K skill calls and R new recall turns:+roughly `K + R + (R / groupSize summaries) + F + F` acquire/release cycles, and+**zero** for the signals themselves.++**`ingestGitHistory` — one run, no locks.** `appendGitRecords`+(`src/core/brain/git/store.ts:178-215`) reads every existing record (`:185`),+dedups in memory (`:191-210`) and appends once (`:213`) with no lock at all; the+watermark (`src/core/brain/git/ingest.ts:194`) and the digest (`:200`) are further+unlocked writes. `mineCommitDecisions` writes one note per candidate with+`atomicWriteFileSync` and no lock (`src/core/brain/git/decisions.ts:134-135`).++---++## 5. Dry-run inertness, per tier++Tier names as given in the brief; the ladder is not written down in one place in+the repo, so each placement below is anchored to the gate it actually implements.++| path | tier | anchor |+|---|---|---|+| `ingestSource` / `brain_ingest_source` | **0 — no gate** | `IngestSourceOptions` has no dry-run field (`src/core/brain/ingest/ingest.ts:60-79`); the MCP handler writes on the first call (`src/mcp/brain/ingest-tools.ts:60`); grep for `dry_run` in that file returns nothing |+| `ingestGitHistory`, `mineCommitDecisions` | **0 — no gate** | options are `maxCount` / `now` only (`src/core/brain/git/ingest.ts:58-62`); `mineCommitDecisions` takes no options (`src/core/brain/git/decisions.ts:111`) |+| `importSession` | **1 — `dryRun` option, off by default** | `ImportSessionOptions.dryRun` (`src/core/brain/sessions/import.ts:63`), CLI `--dry-run` (`src/cli/brain/verbs/import-session.ts:29`) |+| `import-claude-memory` | **2 + 3 + 4** | dry-run is the default and `--apply` opts in (`src/cli/brain/verbs/import-claude-memory.ts:13`, `:60`); `--apply` additionally requires `--yes` when stdin is not a TTY (`:87-92`); `--allow-arbitrary-memory-path` is the override flag (`:79-82`) |+| `inbox-drain`, `apply-markers` | **2 — dry-run default + `--apply`** | `src/cli/brain/verbs/inbox-drain.ts:5-6`; `src/cli/brain/verbs/apply-markers.ts:5-6` |+| link-graph repair | **5 — exact phrase** | `REPAIR_CONFIRM_PHRASE = "apply repair"` (`src/core/brain/link-graph/repair-lane.ts:67`), enforced at `:210` and again at `src/cli/brain/verbs/repair-lane.ts:187` |+| note delete | **5 — exact phrase** | `src/cli/brain/verbs/note-lifecycle.ts:15`; `src/cli/brain/help-text.ts:228` |++**Does any dry-run path touch disk?** For `importSession`, no — traced:+`emit()` returns before `writeSignal` (`src/core/brain/sessions/import.ts:260-265`);+skill-invocation continuity records are gated on `opts.dryRun !== true` (`:423`);+recall import is gated (`:478`); the dedup-telemetry record is gated (`:511`);+the CLI log append is gated (`src/cli/brain/verbs/import-session.ts:127`);+`routeExtractedFacts` skips the write (`src/core/brain/fact-extract.ts:389`) and+also skips the durability-skip log (`:364`) and the anchorable precompute+(`:320-322`). For `import-claude-memory`, the dry-run branch returns before any+write and takes no snapshot (`src/core/brain/import-claude-memory.ts:176-185`),+and the vault-identity write guard is deliberately skipped because the path is a+read (`:82-86`).++**Defect worth naming.** A dry run cannot report what it *would* write.+`signals_created` stays 0 by explicit design+(`src/core/brain/sessions/import.ts:260-264`), and `facts_extracted` is 0 for the+same reason because `routeExtractedFacts` returns `created: 0` under `dryRun`+(`src/core/brain/fact-extract.ts:389`, `:417`). So a dry run's counters are+indistinguishable from a real run that found nothing — the exact shape the+operator's "no fallbacks that silently do nothing" rule forbids. Only+`signals_deduped`, `turns_scanned` and `durabilityRejected` carry information.++---++## 6. Idempotency++### 6.1 The ledger++`src/core/brain/idempotency-ledger.ts` guarantees, per **client-supplied key**:+same key + same payload hash → `duplicate_match` no-op; same key + different hash+→ `payload_mismatch`, never a silent overwrite; unseen key → `inserted`+(`:50-54`, `:147-181`). Granularity is one key ↔ one content hash+(`computePayloadHash`, `:120`), stored in month-sharded JSONL under a per-shard+lock with a re-scan inside the lock (`:157-159`). The residual race is documented,+not hidden: two genuinely concurrent *first* writers of one key can both insert+(`:25-29`).++**It is not on the ingest path.** Session import supplies no `idempotency_key`+(the `writeSignal` call at `src/core/brain/sessions/import.ts:276-307` sets none),+and `ingestSource` never touches the ledger.++### 6.2 What actually makes each ingest idempotent++- **Session import**: a dedup-hash index built once per run from the inbox and+ processed dirs (`src/core/brain/sessions/import.ts:217`), mutated in memory as+ each write lands (`:308`), and shared across every file of a directory walk+ (`:625-629`). Granularity: one hash per (topic, signal, principle, scope)+ (`:394-399`).+- **`ingestSource`**: the summary page filename keys on a source-identity hash+ (`src/core/brain/ingest/ingest.ts:147-148`), the write is skipped when the bytes+ would not change (`:182-187`), and the content manifest records the source's+ content hash so a re-ingest classifies `unchanged` (`:189-194`).+- **Git ingest**: a watermark (`src/core/brain/git/ingest.ts:122-139`,+ `:191-197`) plus store-level sha / (tag, target) dedup+ (`src/core/brain/git/store.ts:191-210`).++### 6.3 Resume vs restart++- **`ingestSource` under a batch plan resumes at the item boundary**:+ `recordCompleted` folds each completed source into the plan checkpoint+ (`src/core/brain/ingest/ingest.ts:199-205`), `planBatches({resume: true})`+ excludes them (`src/core/brain/ingest/batch-plan.ts:96-101`), and the plan id is+ derived from the *full* discovered set so it survives a resume+ (`src/core/brain/ingest/checkpoint.ts:76-87`). Checkpointing is on unless+ `OSB_INGEST_NO_CHECKPOINT` is truthy (`:64-69`). Caveat: a checkpoint write+ failure is swallowed (`src/core/brain/ingest/ingest.ts:202-204`), so resume can+ silently re-do items — harmless because the write is idempotent, costly because+ the extraction is not free.+- **Session import does not checkpoint at all.** An interrupted directory walk+ restarts from the first file (`src/core/brain/sessions/import.ts:633-644`); the+ already-written signals are absorbed by the dedup index rebuilt from disk+ (`:217`), so it converges, but it re-reads and re-scans every file.+- **Git ingest resumes via the watermark**, and a watermark that no longer+ resolves degrades to a full re-scan with a reported warning rather than+ duplicating or failing (`src/core/brain/git/ingest.ts:126-139`).++---++## Divergences++Points where t_da034197's framing does not survive contact with the source.++1. **The triage claim is confirmed, with a correction on the second half.**+ `SESSION_ADAPTERS` is a frozen hardcoded array at+ `src/core/brain/sessions/registry.ts:19`, and+ `src/core/brain/ingest/sources-registry.ts` is CRUD over `Brain/sources` pages+ (`:82`, `:113`, `:132`). Both verified by reading. But —++2. **A registry-shaped thing already exists under another name, and it is an+ ingest registry.** `src/core/brain/agent-backend/registry.ts:18-48` is a frozen+ id-keyed map with config-driven selection, a loud unknown-id error naming the+ registered set (`:32-37`), and a protocol whose docblock states exactly the+ property (a) asks for (`src/core/brain/agent-backend/types.ts:9-11`). Any design+ that invents a new registry shape without reconciling with this one ships two+ idioms for one job.++3. **There are three different adapter families with three different selection+ models.** Session adapters sniff-with-override+ (`src/core/brain/sessions/import.ts:191-204`); memory backends select by+ explicit id or config key (`src/core/brain/agent-backend/registry.ts:45-48`);+ transcript runtimes and agent-source providers run *all* members with no+ selection at all (`src/core/discipline/transcripts/index.ts:37`,+ `src/core/brain/agent-source/registry.ts:18`). A single registry cannot serve+ all three without deciding which model it imposes on the other two.++4. **The existing adapter identity is not house-idiom-compliant**, so it cannot be+ the seed of an adapter-kind vocabulary as-is: `SessionAdapterId` is a bare+ string union (`src/core/brain/sessions/types.ts:108`) with no frozen object and+ no members array, and `isSessionAdapterId` takes `string`, not `unknown`+ (`src/core/brain/sessions/registry.ts:27`). It is absent from the census.++5. **(b)'s premise — "a lease acquired and released per write" — does not describe+ the ingest path.** On `src/core/brain/ingest/`, nothing is locked at all:+ `updateManifest` (`content-manifest.ts:227-239`) and `recordCompleted`+ (`checkpoint.ts:170-194`) are *unlocked* read-modify-writes of shared files, and+ `appendGitRecords` (`git/store.ts:178-215`) is an unlocked read-modify-append.+ The real defect is a missing lock, not a too-granular one. Reframing (b) as+ "hold a lease" without saying which shared state it protects would ship a lease+ over writes that never contended and leave the two files that do contend+ unprotected.++6. **Holding one lease for a whole ingest directly contradicts the batch-plan+ design.** `src/core/brain/ingest/batch-plan.ts:9-11` exists so the caller can+ dispatch each batch as a **parallel subagent**, each calling+ `brain_ingest_source`. A whole-ingest lease either serialises those batches+ (removing the feature's reason to exist) or refuses them outright — the brain+ sync lock has **no retry by design** (`src/core/brain/sync-lockfile.ts:13-15`),+ so the second, third and fourth subagent fail immediately with `ELOCKED`.++7. **A long-held lease under `Brain/` makes `brain doctor` report an uncertainty+ on every ingest.** `scanStaleLocks` lists every `.lock` under the brain root+ (`src/core/brain/sync-lockfile.ts:123-127`) and the probe deliberately cannot+ distinguish a live holder from a crash leftover+ (`src/core/brain/doctor/uncertainty-probes.ts:125-148`). Today locks are held+ for milliseconds so the window is negligible; a minutes-long ingest lease makes+ the report fire routinely and trains operators to ignore it.++8. **The "long-held lock blocks an MCP read" fear is unfounded; the real casualty+ is MCP writes.** Brain reads take no lock anywhere, and the search store's read+ mode explicitly never locks (`src/core/search/store.ts:96-97`; only+ `mode: "write"` acquires, `src/core/search/store/writer-lock.ts:56-63`). What a+ held lease would block is a concurrent MCP *write* — and it would block it with+ an immediate `ELOCKED` rather than a wait, surfacing as+ `BrainCollisionError(sourceLock)` (`src/core/brain/preference-txn.ts:185-190`).++9. **A crash while an ingest lease is held is unrecoverable without an operator.**+ The sync primitive has no stale window at all+ (`src/core/brain/sync-lockfile.ts:13-21`); the exit hook only fires on normal+ exit (`:40-53`). The only precedent for a long-held lease pairs it with a+ forward/backward-recoverable journal+ (`src/core/brain/skill-proposals.ts:633`, `:836-861`) — an ingest lease without+ an equivalent leaves the vault wedged after one SIGKILL.++10. **Two silent-empty results exist today and are in scope for the "no fallbacks+ that silently do nothing" rule**: the transcript resolvers collapsing+ "absent / unreadable / genuinely idle" into `fileCount: 0`+ (`src/core/discipline/transcripts/claude-code.ts:21`, `:27`, `:34`, `:44`), and+ a session-import dry run reporting `signals_created: 0` and+ `facts_extracted: 0` indistinguishably from a real run that wrote nothing+ (`src/core/brain/sessions/import.ts:260-264`,+ `src/core/brain/fact-extract.ts:389`).++11. **`ingestSource` sits on tier 0 with no dry-run at any layer** — core, SDK and+ MCP alike. Making "dry-runs stay inert" true for the ingest path is not a+ matter of preserving an existing behaviour; the behaviour has to be built+ first (`src/core/brain/ingest/ingest.ts:60-79`,+ `src/mcp/brain/ingest-tools.ts:41-81`).++---++## What a design must not assume++- **Do not assume ingest currently locks anything.** It does not+ (`src/core/brain/ingest/ingest.ts`, `src/core/brain/git/store.ts:211-214`). "Hold+ the lease for the whole ingest instead of per write" describes a refactor of a+ discipline that is absent.+- **Do not assume one process performs one ingest.** The batch planner exists to+ fan out across processes (`src/core/brain/ingest/batch-plan.ts:9-11`). A+ process-scoped lease and a plan-scoped lease are different objects.+- **Do not assume the lock primitive waits.** `acquireLockSync` has no retry and no+ stale window (`src/core/brain/sync-lockfile.ts:13-21`); `withFileLock` retries 3+ times over 750 ms (`src/core/reliability/lock.ts:34-39`). Neither will queue+ behind a multi-minute holder.+- **Do not assume a lock is re-entrant.** Every primitive here fails a second+ acquire of the same target from the same process+ (`src/core/brain/sync-lockfile.ts:72-80`). Any lease target must be disjoint from+ every target the inner writes take: the continuity month shard+ (`src/core/brain/continuity/store.ts:291`), the idempotency month shard+ (`src/core/brain/idempotency-ledger.ts:157`), the log directory+ (`src/core/brain/log.ts:243`), the preference file+ (`src/core/brain/preference-txn.ts:182`), and the search index path+ (`src/core/search/store/writer-lock.ts:43`).+- **Do not assume an adapter registry can be a single frozen array.** The three+ existing families disagree on whether selection is by sniff, by id, or absent+ (§2, divergence 3).+- **Do not assume `SessionAdapterId` can be reused as the adapter-kind+ vocabulary.** It fails three of the four idiom requirements+ (`src/core/brain/sessions/types.ts:108`,+ `src/core/brain/sessions/registry.ts:27`).+- **Do not assume a dry-run counter today means "what would be written".** It means+ "what was written", which is zero by construction+ (`src/core/brain/sessions/import.ts:260-264`).+- **Do not assume a crash leaves recoverable state.** Absent a journal, a held sync+ lock survives the crash and blocks every subsequent write until an operator+ removes the file by hand (`src/core/brain/doctor/uncertainty-probes.ts:141-147`).++### Not established in this pass++- The lock and dry-run behaviour of `bank-import`, `graph-import`, `okf-import`,+ `telegram-capture` and `scan-inline` (named at §1.7, not traced).+- Whether the truth-ingest MCP op has its own gate; only the CLI `--ingest` flag+ path was read (`src/cli/brain/help-text.ts:433-436`).+- Whether `emitGatedTelemetry` can itself fail in a way that leaves a continuity+ shard lock held (`src/core/brain/dedup-telemetry.ts:115-127` was read; the helper+ body was not).diff --git a/docs/brainstorm/nothing-runs-unwatched/recon/progress-reporting.md b/docs/brainstorm/nothing-runs-unwatched/recon/progress-reporting.mdnew file mode 100644index 00000000..e0aeefb3--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/recon/progress-reporting.md@@ -0,0 +1,622 @@+# Recon — incremental progress/status reporting (t_62bb944a)++Read-only reconnaissance against `feat/nothing-runs-unwatched`, based on+v1.47.0 (`aa818084`). Every claim below carries a `path:LINE` anchor that+was read directly. Where a claim could not be established from source it+says so.++---++## 1. Inventory of genuinely long-running operations++The repository already has a canonical list of what it considers long: the+safeguard operation vocabulary at+`src/core/brain/safeguard.ts:26` —+`export type SafeguardOperation = "dream" | "reindex" | "bridges" | "clusters" | "maintenance"`.+That module was itself created from an upstream-mirage task (`t_06784b8d`,+docblock `src/core/brain/safeguard.ts:1-21`) and describes exactly the same+population this task is about. Any progress design should treat that union+as the existing definition of "long-running" rather than inventing a second+one.++### Countable-unit table++`known?` = is the total number of units available BEFORE the loop starts.++| Operation | Entry point | Unit iterated | Total known before loop? |+|---|---|---|---|+| Incremental index | `indexVault` — `src/core/search/indexer.ts:296` (body `indexInto`, `:303`) | markdown files, then chunks per file | **NO** |+| Full rebuild | `reindexVault` — `src/core/search/indexer.ts:920` | delegates to one `indexVault` call at `src/core/search/indexer.ts:969` | **NO** (inherits) |+| Embeddings build | `runEmbeddingPhase` — `src/core/search/indexer.ts:816` | super-batches of chunks | **YES** |+| Embeddings backfill | `planVectorBackfill` — `src/core/search/vector-backfill.ts:85` | chunks lacking a vector | **YES** |+| Event-anchor backfill | `planEventAnchorBackfill` — `src/core/search/event-anchor-backfill.ts:84` | documents | **YES** |+| Dream pass | `dream` — `src/core/brain/dream.ts:101` | phases (each with its own inner item loop) | **YES** |+| Maintenance lane | `runMaintenance` — `src/core/brain/maintenance/lane.ts:121` | named tasks | **YES** |+| Bridge discovery | `discoverBridges` — `src/core/brain/link-graph/bridge-discovery.ts:88` | candidate documents | **YES** |+| Community detection | `detectCommunities` — `src/core/brain/link-graph/communities.ts:76` | propagation sweeps × nodes | **CEILING ONLY** |+| Heal/enrichment pass | `runHealEnrichment` — `src/core/brain/heal-run.ts:43` | vault pages, twice (two passes) | **YES** |+| Hygiene scan | `runHygieneScan` — `src/core/brain/hygiene/scan.ts:38` | detectors | **YES** |+| Brain doctor | `runDoctor` — `src/core/brain/doctor.ts:202` | checks (static 30-entry registry) | **YES** |+| Memory bench | `runMemoryBench` — `src/core/bench/phases.ts:65` | 5 named phases, then questions | **YES** |+| Recall benchmark | `runRecallBenchmark` — `src/core/search/benchmark.ts:189` | queries, **concurrent** | **YES, but unordered** |+| Link-ratchet measure | `measureVault` — `src/core/search/link-ratchet.ts:269` | vault copy → forced index → recount | **NO** |+| Backlink index | `buildBacklinkIndex` — `src/core/brain/backlinks.ts:98` | five directory collectors | **NO** |+| Stale scan | `findStaleEntries` — `src/core/brain/temporal/stale-watch.ts:63` | three directory sub-scans | **NO** |++### Why index/reindex cannot report a fraction++The index driver is a generator consumed as it goes:+`src/core/search/indexer.ts:324` — `for (const file of walkVault(config)) {`,+where `walkVault` is `export function* walkVault(...): Generator<WalkedFile>`+at `src/core/search/walker.ts:51`. Nothing materializes the file list first.+The one pre-known set is the *previously indexed* documents,+`src/core/search/indexer.ts:313` (`store.listDocuments()`), which is used for+the deletion sweep — it is not a denominator for this run (a first index has+zero of them, and new files are not in it).++A count is obtainable only by walking twice; the repo does exactly that where+it needs one: `src/core/search/link-ratchet.ts:256` —+`return [...walkVault(config)].length;`, with the docblock at+`src/core/search/link-ratchet.ts:248-253` explaining the materialization+trade. So for index/reindex a progress report can be a **monotonic counter+plus a phase label**, never a percentage, unless the design is willing to pay+a second full directory walk before the run.++The embedding side is the opposite: `src/core/search/indexer.ts:845` —+`const pending = store.findChunksWithoutEmbeddings();` — an array, followed by+`src/core/search/indexer.ts:879` — `for (let i = 0; i < pending.length; i += superBatch)`.+`i / pending.length` is an exact fraction. `planVectorBackfill` even reports+that denominator today as a dry-run field (`pending`,+`src/core/search/vector-backfill.ts:93` and the `VectorBackfillResult.pending`+declaration at `src/core/search/vector-backfill.ts:60`).++So a single progress event shape has to carry an OPTIONAL total. The two+halves of one `o2b search index --embeddings` run genuinely differ: file phase+= counter only, embed phase = counter + total.++### Existing phase vocabularies (do not invent a third)++- Dream: `DREAM_PHASE` at `src/core/brain/dream-phases.ts:19`+ (`close, reconcile, synthesize, heal, log`), reporting order+ `DREAM_PHASE_ORDER` at `src/core/brain/dream-phases.ts:33`, and+ `DreamPhaseSummary { phase, metrics: Readonly<Record<string, number>> }`+ at `src/core/brain/dream-phases.ts:46-49` — a phase label plus integer+ counters is already the house shape.+- Dream execution-order journal: `WORKRUN_PHASE` at+ `src/core/brain/dream-workrun.ts:50-63` (ten identifiers), written per+ transition by `WorkrunHandle.checkpoint(phase, payload?)`+ (`src/core/brain/dream-workrun.ts:71`) into+ `Brain/log/dream-runs/<run-id>.jsonl` (`openWorkrun`,+ `src/core/brain/dream-workrun.ts:79`). Emitted at+ `src/core/brain/dream.ts:235-236` and+ `src/core/brain/dream-apply.ts:106,107,112,120`.+- Bench: durable resumable phases via `completeBenchPhase`, guarded by+ `phaseDone(checkpoint, "<phase>")` at `src/core/bench/phases.ts:73,79,87,107,116`.++Dream's workrun journal is the closest existing thing to a live progress+stream — but it goes to a FILE, not to a caller, and it is opened only on the+mutating path (`src/core/brain/dream.ts:236`, inside the destructive-snapshot+callback), so a dry-run dream emits no phase markers at all.++### Operations the task named that are not what it implies++- "the nightly dream pass" — `dream` iterates PHASES, not notes+ (`src/core/brain/dream.ts:101`, straight-line stage sequence at+ `:120,125,139,140,145,156,165,239,277`). Per-item counts exist inside+ `applyDreamPlan` (`src/core/brain/dream-apply.ts:88`, loops at `:143,176,232,267,330`),+ but the top level has no single denominator. Progress for dream is+ phase-shaped, not fraction-shaped.+- "large maintenance sweeps" — the only thing in the repo actually named a+ maintenance sweep is `runMaintenance` (`src/core/brain/maintenance/lane.ts:121`),+ and it is a 4-item task list (`src/core/brain/maintenance/lane.ts:141-143`),+ whose members are dream / reindex / bridges / clusters. It is a+ *dispatcher* over the other long operations, not a long operation of its own.+ Its per-task boundary is already recorded to the journal+ (`appendJournal`, `src/core/brain/maintenance/lane.ts:170`) with `name`,+ `ok`, `duration_ms` — i.e. exactly a phase-progress record, written after+ each task rather than streamed.++### Operations the task missed++`runHealEnrichment` (`src/core/brain/heal-run.ts:43`) is a two-pass rewrite+over every vault page (`listVaultPages` at `src/core/brain/heal-run.ts:53` —+count known) and runs INSIDE the dream pass when `heal_enrich` is on+(gate resolved at `src/core/brain/dream.ts:110`). `measureVault`+(`src/core/search/link-ratchet.ts:269`) copies the entire vault with+`cpSync` (`:283`), forces a full index (`:285`), then walks again to count+(`:295`) — four sequential phases with no shared progress channel.+`buildBacklinkIndex` (`src/core/brain/backlinks.ts:98`) is a full rebuild on+every call with no incremental path, and `auditMoc`+(`src/core/brain/link-graph/moc-audit.ts:107`) calls it.++---++## 2. MCP progress-token support++### There is no MCP SDK++`package.json` declares exactly one runtime dependency —+`"proper-lockfile": "^4.1.2"` (`package.json:56-58`) — plus dev deps+(`@types/bun`, `@types/node`, `@types/proper-lockfile`, `oxfmt`, `oxlint`,+`typescript`) and three optionals (`@node-rs/jieba`, `sqlite-vec`,+`tiny-segmenter`). A repo-wide grep for `modelcontextprotocol`,+`RequestHandlerExtra`, `sendNotification`, `progressToken`, `progress_token`,+`notifications/progress`, and `_meta` over `src/`, `scripts/`, and+`package.json` returns **zero** matches in any MCP context (the only `_meta`+hits are unrelated: `producer_meta` in `src/core/brain/portability/okf.ts:137`+and `session_meta` in the session adapters).++The server is hand-rolled JSON-RPC 2.0: `MCPServer` at `src/mcp/server.ts:69`,+protocol constants at `src/mcp/protocol.ts:11-20`+(`PROTOCOL_VERSION = "2025-06-18"`). **There is no SDK to expose+`_meta.progressToken` or to send `notifications/progress`. Both would have to+be implemented here.**++### The exact seam, and what it drops today++`handleToolsCall` — `src/mcp/server.ts:319`:++```+const name = params["name"]; // src/mcp/server.ts:320+const argsRaw = params["arguments"] ?? {}; // src/mcp/server.ts:325+```++Those are the only two keys read from `params`. A client's+`params._meta.progressToken` is read by nothing and silently discarded. That+is where a token would be picked up.++The single handler invocation seam is `invokeToolHandler` —+`src/mcp/server.ts:167` — which both `tools/call` (`src/mcp/server.ts:237`)+and the CLI bridge `callTool` (`src/mcp/server.ts:147`) go through. Its+docblock names it "Single seam through which every tool handler runs"+(`src/mcp/server.ts:153-166`), and it is already the site of the+unknown-argument gate and the route-latency timer. It is the natural place to+attach a progress sink.++### The handler signature today, verbatim++`src/mcp/tool-contract.ts:83-86`:++```ts+ readonly handler: (+ ctx: ServerContext,+ args: Record<string, unknown>,+ ) => Promise<unknown> | unknown;+```++`ServerContext` is `src/mcp/tool-contract.ts:30-72`: `vault`, `configPath`,+`repoRoot`, optional `capabilityReport`, optional `artifactStore`, and+`agentName` as a getter. There is **no** third `extra` parameter, no request+id, no notification channel. A per-request progress sink would either be a+new optional `ServerContext` field (but the context is currently+per-SERVER, built by the getter at `src/mcp/server.ts:140`, not per-request)+or a new third handler parameter — a signature change across all 88 tool+registrations.++### Neither transport can currently emit an unsolicited frame++- stdio: `serveStdio` writes only what `handleRequest` returns —+ `src/mcp/stdio.ts:67-68` (`const response = await server.handleRequest(...); if (response !== null) writeFrame(stdout, response);`).+ `writeFrame` is a private function taking a `JsonRpcResponse`+ (`src/mcp/stdio.ts:73`); it cannot be handed a notification object without+ a type change, and it is not reachable from a handler.+- HTTP: one request → one response → connection closed.+ `src/mcp/http.ts:159` (`const response = await mcp.handleRequest(jsonReq);`)+ then a single write. The SSE branch is `src/mcp/http.ts:168` →+ `writeSse` (`src/mcp/http.ts:282`), whose body is+ `res.end(\`event: message\ndata: ${JSON.stringify(response)}\n\n\`)`+ (`src/mcp/http.ts:292`) — `res.end`, i.e. exactly one event, then closed.+ `docs/mcp.md:289-291` documents this: "clients that send+ `Accept: text/event-stream` receive a single SSE `message` event for the+ same JSON-RPC response." There is no persistent GET stream, no session+ resumption, no `Mcp-Session-Id` reuse (a fresh UUID is minted per+ `initialize` at `src/mcp/http.ts:165` and never stored).++So MCP progress requires: (a) reading `params._meta.progressToken`, (b) a+writer handle plumbed from the transport down to the handler, and (c) for+HTTP, converting the SSE branch from `res.end` to a held-open stream.+(a) and (b) are contained; (c) is a transport rewrite.++### Capabilities++`initialize` advertises only `tools` and `resources`+(`src/mcp/server.ts:275-278`). Nothing else is negotiated. Note that+progress notifications are not a server capability in the spec — the client+opts in per-request by sending a token — so no capability change is strictly+required, but `docs/mcp.md:14-18` would be inaccurate until updated.++### Which MCP tools actually run for minutes++`src/mcp/search-tools.ts:5-9` states plainly: "Index management verbs+(`index`, `reindex`, `check`) are intentionally NOT exposed over MCP — they+are operator business, never agent business (design doc §3, principle 5)."+Confirmed: the only MCP call site of `indexVault` is inside+`brain_maintenance` (`src/mcp/brain/admin-tools.ts:317`). The MCP surfaces+that can genuinely run long are therefore:++- `brain_maintenance` → `runMaintenance` at `src/mcp/brain/admin-tools.ts:302`,+ which runs dream (`:311`), indexVault (`:317`), discoverBridges (`:329`),+ detectCommunities (`:358`).+- `brain_dream` → `dream(...)` at `src/mcp/brain/feedback-tools.ts:467`+ (preview) and `:484` (apply).+- `brain_bridges` → `discoverBridges` at `src/mcp/brain/knowledge-tools.ts:170`.+- `brain_clusters` → `detectCommunities` at `src/mcp/brain/knowledge-tools.ts:252`.+- `brain_brief` runs a dry-run dream at `src/mcp/brain/brief-tools.ts:361`.+- `brain_deep_synthesis` → `deepSynthesis` at `src/mcp/brain/knowledge-tools.ts:351`+ (bounded search, but one full `walkVault` at `src/core/brain/deep-synthesis.ts:389`).++Incidental finding: `brain_bridges` and `brain_clusters` pass **no**+`safeguard` (`src/mcp/brain/knowledge-tools.ts:170-174` and `:252-255`),+while the maintenance-lane copies of the same calls do+(`src/mcp/brain/admin-tools.ts:332,358`). Those two MCP tools have no+deadline today.++---++## 3. CLI output substrate++### There is no single JSON emission point++`src/cli/output.ts` (52 lines) is the nominal shared printer:+`ok` (`:10`), `okJson` (`:15`), `fail` (`:20`), `info` (`:26`),+`writeJson(payload, replacer?)` (`:35-38`), `failWith` (`:47`). Its docblock+at `src/cli/output.ts:30-34` claims it "centralises the format so subcommands+don't each repeat the same `JSON.stringify(...) + "\n"` boilerplate". That is+not what the tree looks like:++- `src/cli/output.ts` is imported by 11 files; `writeJson` has 4 real call+ sites (`src/cli/vault/verbs/map.ts:25`, `profile.ts:29`, `status.ts:43`,+ `inspect.ts:70`).+- `okJson` has roughly 280 call sites, all reached through the barrel+ re-export at `src/cli/brain/helpers.ts:98`, and it hard-codes an+ `{ok:true, ...}` envelope (`src/cli/output.ts:15`) — so it is the `brain`+ family's emitter, not the CLI's.+- Everything else writes its own: ~520 `process.stdout.write` calls across+ `src/cli`, of which ~119 shape JSON inline. Representative:+ `src/cli/search/verbs/indexing.ts:104-109`, `src/cli/main.ts:819`,+ `src/cli/brain/verbs/dream.ts:229` and `:404`.+- Formatting is not uniform either: the `search` family emits compact+ single-line JSON (`src/cli/search/verbs/indexing.ts:104`,+ `src/cli/search/verbs/query.ts:164`), most others pretty-print with+ `null, 2`.++`console.log` appears **zero** times in `src/cli`.++### How `--json` routes, and the buffering trap++`--json` is auto-injected into every flag schema —+`src/cli/argparse.ts:39-40`. Dispatch splits into two families at+`src/cli/main.ts:900-903`:++```+if (wantsJsonFlag(rest) && !ownsInternalJson(command, rest)) {+ return await withJsonFallback(command, run);+}+```++`COMMANDS_WITH_INTERNAL_JSON` is the 12-entry fact table at+`src/cli/json-helpers.ts:45-58`: `status, install, update, tool-call,+secrets, brain, search, vault, discipline, partner, doctor, onboarding`.++**The trap:** for every command NOT in that set, `withJsonFallback`+(`src/cli/json-helpers.ts:88`) monkey-patches BOTH `process.stdout.write`+and `process.stderr.write` into string accumulators+(`src/cli/json-helpers.ts:97-106`), restores them in a `finally`+(`:112-113`), and emits one envelope at the end (`:116-119`). Any progress a+wrapped command writes — to either stream — is invisible until the run+finishes, which defeats the entire point.++That is survivable only because the long commands live under `search` and+`brain`, both of which ARE in the internal-JSON set+(`src/cli/json-helpers.ts:51-52`) and therefore unwrapped. A progress design+must state that dependency explicitly; it is load-bearing and undocumented.++### The stdout/stderr boundary today++There is **no** runtime guard forbidding stdout writes. `src/cli/stdout-guard.ts`+is misleadingly named — it maps stdout *stream errors* to exits: `EPIPE_CODE`+(`:16`), `isEpipeError` (`:23`), `handleStdoutError` (`:39`, EPIPE → exit 0),+`installStdoutEpipeGuard` (`:66`), installed once at `src/cli/main.ts:1007`.++What actually enforces the boundary is three partial mechanisms:++1. **The core layering test** — `tests/core/layering.test.ts:20-24` bans+ `process.exit`, `process.stdout.write`, and `console.log(` anywhere in+ `src/core`; its docblock (`tests/core/layering.test.ts:1-11`) states the+ rule: "The CLI owns exit codes and stdout formatting; src/core must never+ terminate the process or write to stdout directly. Fail-soft diagnostics+ on stderr … stay allowed." **This is why `onFile` exists** — core cannot+ print, so it must hand events out. Any progress design that has core+ printing fails this test.+2. **The advisory rail** — `src/cli/advisory-rail.ts`. `advisoryIsLegal` at+ `src/cli/advisory-rail.ts:85-88` refuses to write when+ `jsonRequested && ownsInternalJson(...)`, with named outcomes+ `emitted` / `suppressed-machine-stream` / `unregistered-code`+ (`src/cli/advisory-rail.ts:53-60`). Its docblock (`:15-20`) states the+ rule: "Twelve top-level commands render their own JSON, and their stdout is+ a payload a caller parses; one stray advisory line breaks it." Routing+ through it is voluntary.+3. **`withJsonFallback`'s buffering** — containment, not prohibition.++### What already prints intermediate lines++| Site | What | Stream | Gate |+|---|---|---|---|+| `src/cli/search/verbs/indexing.ts:142-147` | `` `${e.kind}\t${e.path}${msg}\n` `` per file, `o2b search index` | stderr | `--verbose` |+| `src/cli/search/verbs/indexing.ts:184-186` | `` `${e.kind}\t${e.path}\n` `` per file, `o2b search reindex` | stderr | `--verbose` |+| `src/cli/search/verbs/check.ts:255-262` (`announceScan`, called `:311`) | one PRE-scan wait estimate | stderr | `--integrity` |+| `src/cli/search/verbs/watch.ts:63-67` | `` `synced N change(s): +A ~U =E` `` per debounced flush | stderr | always (`o2b search watch`) |++The `announceScan` docblock at `src/cli/search/verbs/check.ts:249-254` is the+nearest thing to a written stream policy: "It goes to stderr in both report+shapes … stdout under `--json` is a payload a caller parses."++`o2b brain dream` prints **nothing** while working — all output lands after+completion (`src/cli/brain/verbs/dream.ts:229`, `:404`). Same for `o2b doctor`+(`src/cli/main.ts:347`).++There is no spinner, no `\r` redraw, no percent counter, and no `ora`-style+dependency anywhere (`package.json:56-58` has one runtime dep). There is no+NDJSON output mode and no `--stream` flag on any command.++---++## 4. Existing counters / metrics++`src/core/brain/metrics.ts` is a **post-hoc, run-level** sink, not a live+counter substrate:++- `appendMetric(vault, {surface, runAt, payload})` —+ `src/core/brain/metrics.ts:83` — appends ONE JSONL line per RUN to+ `Brain/metrics/<surface>.jsonl` (`surfacePath`, `:67`), envelope+ `{schema:"o2b.metrics.v1", surface, run_at, payload}` (`:91-96`).+- The docblock at `src/core/brain/metrics.ts:9-11` is explicit: "Records are+ RUN-LEVEL (one per index run, discovery pass, benchmark or tuning run)".+- Contract documented for external consumers at `docs/metrics.md:1-40`+ (surfaces: `index`, `bridge_discovery`, `communities`, `recall_benchmark`,+ `self_tuning`, `dream_stage`).+- 18 call sites, all AFTER the work completes, e.g.+ `src/core/search/indexer.ts:612` (guarded by+ `if (stats.added + stats.updated + stats.deleted > 0)` at `:608`).++**Conclusion:** a progress reporter cannot reuse this. Reusing it would mean+appending a vault file per progress tick, which turns telemetry into an I/O+amplifier and pollutes a documented dashboard contract whose evolution rule+(`src/core/brain/metrics.ts:16-19`) treats semantic changes as a version bump.+The right reuse is the *shape* — `{surface/phase, integer payload}` — not+the sink.++The other in-flight counter substrate is `MutableStats` /+`EmbeddingPhaseTally`:+`src/core/search/indexer.ts:790-793` declares+`EmbeddingPhaseTally { embeddingsComputed: number; embeddingsRetries: number }`+and its docblock (`:785-789`) explains it was extracted precisely so the+embed phase can serve both the index run and the standalone backfill. That is+a live, mutated-in-place counter object already threaded through both callers+— the closest existing thing to a shared progress accumulator, though it is+read only at the end (`freezeStats`, `src/core/search/indexer.ts:175`).++---++## 5. Prior art for a cross-cutting optional callback++The house idiom exists and is used in exactly this shape. Every instance is+an optional readonly field on an options interface, invoked with `?.`:++| Anchor | Field |+|---|---|+| `src/core/search/indexer.ts:110` | `readonly onFile?: (event: IndexProgressEvent) => void;` |+| `src/core/search/rerank/index.ts:56` | `readonly onTelemetry?: (event: RerankTelemetryEvent) => void;` |+| `src/core/brain/notes/note-walk.ts:62` | `readonly onOversize?: (file: NoteWalkFile, sizeBytes: number) => void;` |+| `src/core/brain/inject-failopen.ts:66` | `readonly audit?: (source, error: unknown) => void;` |+| `src/core/brain/health/remediation.ts:168` | `readonly log?: (message: string) => void;` |+| `src/core/fs-atomic.ts:78` | `readonly validate?: (candidate: string) => void;` |+| `src/core/brain/link-graph/communities.ts:220` | `readonly writeNote?: (path: string, content: string) => void;` |++**`onFile` is the direct precedent and it is already a progress channel.**+`IndexProgressEvent` — `src/core/search/indexer.ts:98-102`:++```ts+export interface IndexProgressEvent {+ readonly path: string;+ readonly kind: "added" | "updated" | "unchanged" | "deleted" | "error";+ readonly message?: string;+}+```++Fired at `src/core/search/indexer.ts:347`, `:363`, `:469`, `:472`, `:477`,+`:485`. Consumed at exactly two sites, both writing tab-separated lines to+stderr behind `--verbose`: `src/cli/search/verbs/indexing.ts:142` and `:184`.+`reindexVault` forwards it through the spread at+`src/core/search/indexer.ts:969` (`{ ...opts, force: !resume }`).++The second, stronger idiom is the **safeguard** — the cross-cutting optional+parameter threaded through this exact operation set:+`readonly safeguard?: Safeguard` appears at+`src/core/search/indexer.ts:115`, `src/core/search/indexer.ts:799`,+`src/core/search/vector-backfill.ts:49`, `src/core/brain/dream-types.ts:212`,+`src/core/brain/dream-stage.ts:100`,+`src/core/brain/link-graph/bridge-discovery.ts:76`,+`src/core/brain/link-graph/communities.ts:69`. It is invoked as+`opts.safeguard?.checkpoint()` at `src/core/brain/dream.ts:104,198,209,224,269,310`,+`src/core/search/indexer.ts:328,882`,+`src/core/brain/link-graph/bridge-discovery.ts:96,135`,+`src/core/brain/link-graph/communities.ts:79,95`. The interface is three+members (`src/core/brain/safeguard.ts:71-78`) and has a no-op constructor+`noopSafeguard` (`src/core/brain/safeguard.ts:95`).++**Every safeguard `checkpoint()` call is already at the exact iteration+boundary a progress tick belongs at.** A progress reporter that follows the+house idiom is: one more optional field on the same options interfaces, one+more call beside each existing `checkpoint()`, invoked with `?.`.++Two things about that idiom the design must respect:++1. `Safeguard.checkpoint()` is **synchronous and returns void**+ (`src/core/brain/safeguard.ts:72`). So is `onFile`. A progress callback+ must be synchronous too — see §7.+2. The safeguard resolves its own config ladder in core+ (`resolveSafeguardTimeoutMs`, `src/core/brain/safeguard.ts:131`) and+ fails soft on an unparseable value (`parseSeconds`, `:150-155`), with the+ docblock at `src/core/brain/safeguard.ts:16-21` stating the ladder. A+ progress reporter's on/off decision should follow the same pattern rather+ than inventing a new config surface.++For the CLI half, the *policy* precedent is `src/cli/advisory-rail.ts` in+full: one module that (1) resolves what to say from a registered CODE and+refuses to accept prose from a caller (`src/cli/advisory-rail.ts:8-15`),+and (2) decides whether the stream is legal to write to+(`advisoryIsLegal`, `:85-88`). A structured progress emitter should be that+module's twin, not 500 more `process.stdout.write` calls.++---++## Divergences++Things in t_62bb944a's framing that do not survive contact with the source.++1. **"No streaming/incremental background-command output surface was found …+ This confirms the feature (progress reporting on long ops) is absent."**+ Wrong for the CLI. `IndexProgressEvent` + `onFile`+ (`src/core/search/indexer.ts:98-110`) is a real per-file progress channel+ wired to stderr at `src/cli/search/verbs/indexing.ts:142` and `:184`.+ `o2b search watch` streams a per-flush line unconditionally+ (`src/cli/search/verbs/watch.ts:63-67`). The gap is that progress is+ unstructured, un-counted, and exists on exactly one operation — not that+ it is absent. This is a *generalize and structure* task, not a *create*.++2. **"MCP supports progress notifications via a progress token"** — true of+ the spec, but the task's "thread MCP progress-notification support through+ the tools" implies an SDK that already carries the token. There is no SDK+ (`package.json:56-58`; zero `modelcontextprotocol` references anywhere).+ `handleToolsCall` reads only `params["name"]` and `params["arguments"]`+ (`src/mcp/server.ts:320,325`), and neither transport can write an+ unsolicited frame (`src/mcp/stdio.ts:67-68`; `src/mcp/http.ts:292` uses+ `res.end`). This is not "plumbing through" — it is implementing progress+ notifications, plus an SSE transport rewrite for the HTTP half.++3. **"Reindex/embeddings/dream are the operations most likely to run for+ minutes … an agent driving OSB over MCP cannot tell a slow run from a hung+ one."** Reindex and embeddings are **not reachable over MCP at all** by+ design: `src/mcp/search-tools.ts:5-9` — "Index management verbs (`index`,+ `reindex`, `check`) are intentionally NOT exposed over MCP — they are+ operator business, never agent business". The only MCP path to `indexVault`+ is as one of four tasks inside `brain_maintenance`+ (`src/mcp/brain/admin-tools.ts:317`). So the MCP half of this task covers+ `brain_maintenance`, `brain_dream`, `brain_bridges`, `brain_clusters`,+ `brain_brief` — a much smaller set than the framing suggests, and two of+ those (`brain_bridges`, `brain_clusters`) run without even a deadline+ today (`src/mcp/brain/knowledge-tools.ts:170,252`).++4. **"`o2b` CLI: already streams to a terminal for interactive runs."**+ Partly false. Only `o2b search index|reindex --verbose` and+ `o2b search watch` stream. `o2b brain dream` and `o2b doctor` print+ nothing until they finish (`src/cli/brain/verbs/dream.ts:229`,+ `src/cli/main.ts:347`). There is no spinner or tick anywhere.++5. **"large maintenance sweeps"** as a peer of reindex/dream. `runMaintenance`+ (`src/core/brain/maintenance/lane.ts:121`) is a gate + lease + 4-task+ dispatcher whose tasks ARE dream and reindex+ (`src/cli/brain/verbs/maintenance.ts:130-186`,+ `src/mcp/brain/admin-tools.ts:307-360`). Treating it as a fourth long+ operation double-counts. Its correct role in this design is as the+ *aggregator* that forwards a child operation's progress upward with a task+ label.++6. **"a low-risk ergonomic win."** The MCP half is not low-risk: it needs a+ request-scoped channel where the current `ServerContext` is server-scoped+ (built by the getter at `src/mcp/server.ts:140`), a change to the handler+ contract at `src/mcp/tool-contract.ts:83` shared by 88 registered tools,+ and an HTTP transport that holds a connection open instead of+ `res.end`-ing (`src/mcp/http.ts:292`). The task's own escape hatch — "If+ MCP progress plumbing proves heavier than the payoff, the CLI-only slice+ still stands on its own" — is the accurate read of this codebase.++7. **The codegraph hint about `jobsFilePath` at `src/cli/discipline-install.ts:19`**+ — could not be verified as still accurate; not checked, and irrelevant+ either way since the task correctly rules the job-console model out.++---++## What a design must not assume++1. **Do not assume a denominator.** `indexVault` walks a generator+ (`src/core/search/indexer.ts:324`, `src/core/search/walker.ts:51`). The+ event shape must make `total` optional, and a UI must render a bare+ counter when it is absent. Materializing the walk to get a total costs a+ second full directory traversal (`src/core/search/link-ratchet.ts:256`) —+ if the design wants it, it must say so and pay for it, not pretend it is+ free.++2. **Do not assume the callback can be `async`.** `dream`+ (`src/core/brain/dream.ts:101`), `discoverBridges`+ (`src/core/brain/link-graph/bridge-discovery.ts:88`), `detectCommunities`+ (`src/core/brain/link-graph/communities.ts:76`), `runDoctor`+ (`src/core/brain/doctor.ts:202`), `runHygieneScan`+ (`src/core/brain/hygiene/scan.ts:38`) and `stageDream`+ (`src/core/brain/dream-stage.ts:238`) are all **synchronous**. A+ `(event) => Promise<void>` sink cannot be awaited inside them, and Bun runs+ SQLite synchronously anyway (`src/core/brain/safeguard.ts:5-7`). The sink+ must be `(event) => void`, matching `onFile`+ (`src/core/search/indexer.ts:110`) and `Safeguard.checkpoint`+ (`src/core/brain/safeguard.ts:72`). This directly constrains the MCP half:+ a synchronous sink cannot `await` a write, so the MCP progress writer must+ buffer or write synchronously.++3. **Do not let core print.** `tests/core/layering.test.ts:20-24` fails the+ build on any `process.stdout.write` or `console.log(` in `src/core`. Core+ emits events; only `src/cli` and `src/mcp` may write them.++4. **Do not write progress to stdout for the twelve internal-JSON commands.**+ `src/cli/json-helpers.ts:45-58` names them; `search` and `brain` are both+ in the set, so their stdout is a caller-parsed payload+ (`src/cli/advisory-rail.ts:15-20`). Progress belongs on stderr, matching+ every existing precedent (`src/cli/search/verbs/indexing.ts:142`,+ `src/cli/search/verbs/check.ts:255-262`,+ `src/cli/search/verbs/watch.ts:63`).++5. **Do not write progress at all from a `withJsonFallback`-wrapped command.**+ `src/cli/json-helpers.ts:97-106` buffers stdout AND stderr for the whole+ run and releases one envelope at the end+ (`src/cli/json-helpers.ts:116-119`). Progress there is not degraded — it is+ silently swallowed and then dumped at completion, which is worse than+ nothing because it looks like it worked. If a long operation ever moves+ outside `COMMANDS_WITH_INTERNAL_JSON`, its progress disappears. That+ dependency must be asserted, not assumed.++6. **Do not assume MCP tools can reach reindex or embeddings.** They cannot+ (`src/mcp/search-tools.ts:5-9`). Any MCP progress work targets+ `brain_maintenance`, `brain_dream`, `brain_bridges`, `brain_clusters`.++7. **Do not emit a natural-language sentence as the progress payload.** The+ repo has a hard rule against caller-supplied prose on structured surfaces+ — `src/cli/advisory-rail.ts:8-15` ("There is deliberately no parameter+ through which a caller can supply a command or a sentence: prose cannot+ enter this surface") — and the same rule is why `IndexProgressEvent.kind`+ (`src/core/search/indexer.ts:100`) and `DREAM_PHASE`+ (`src/core/brain/dream-phases.ts:19`) are stable identifiers rather than+ labels. A progress event must carry a phase identifier and integer counts;+ any human sentence is rendered at the edge, from that identifier.++8. **Do not reuse `Brain/metrics/` as the progress sink.** It is a documented+ run-level dashboard contract (`docs/metrics.md:1-40`,+ `src/core/brain/metrics.ts:9-19`) with one append per RUN. Per-tick+ appends would break it and hammer the disk.++9. **Do not introduce a silent no-op path.** `opts.onProgress?.(…)` with no+ sink attached is fine — that is the existing `onFile` /+ `safeguard?.checkpoint()` idiom, where absence means "nobody asked". What+ is NOT acceptable is a progress surface that is wired but discards events+ because the transport cannot carry them (the HTTP `res.end` case,+ `src/mcp/http.ts:292`): that would report liveness support that does not+ exist. Either the HTTP transport holds the stream open, or the MCP progress+ surface must refuse the token on HTTP and say why.++10. **Do not assume the dream workrun journal is a live stream.** It is a+ file (`Brain/log/dream-runs/<run-id>.jsonl`,+ `src/core/brain/dream-workrun.ts:79-88`), it is opened only on the+ mutating path (`src/core/brain/dream.ts:236`), and `checkpoint` is a+ silent no-op after `finalize`/`interrupt`+ (`src/core/brain/dream-workrun.ts:103`). It is the right *vocabulary*+ source and the right *emission points*, but it is not a channel to a+ caller.diff --git a/docs/brainstorm/nothing-runs-unwatched/recon/provider-sunset.md b/docs/brainstorm/nothing-runs-unwatched/recon/provider-sunset.mdnew file mode 100644index 00000000..cdd7f69c--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/recon/provider-sunset.md@@ -0,0 +1,587 @@+# Recon: announced provider/model sunset warning (t_e7a226ce)++Read-only reconnaissance against `feat/nothing-runs-unwatched` at v1.47.0+(`package.json:3`). Every claim below carries an anchor to a line actually read.+Where the source refused to settle a question, that is said plainly.++---++## 1. The presets catalog++**Where it is.** `src/core/search/embeddings/presets.ts`. The whole file was+read.++**What a preset is today.** `EmbeddingModelPreset` at+`src/core/search/embeddings/presets.ts:30-67`, seven fields:++| field | line | note |+| --- | --- | --- |+| `model` | `:32` | the string sent to the endpoint; also the catalog key |+| `label` | `:34` | short human label for CLI listings |+| `dimension` | `:36` | native embedding width |+| `inputWindowTokens` | `:53` | declared max input, from the model's published spec |+| `multilingual` | `:55` | trained for cross-lingual retrieval |+| `note` | `:57` | one-line guidance shown beside the model |+| `queryPrefix` / `passagePrefix` | `:64`, `:66` | optional, e5-family instruction prefixes |++**Keying.** There is no map. `EMBEDDING_MODEL_PRESETS` is a frozen array of six+entries (`presets.ts:75-138`), and lookup is a linear scan on exact model string:+`findEmbeddingPreset` at `presets.ts:144-146` (`p.model === model`). No+normalisation, no family heuristic — `presets.ts:161-166` states the refusal to+infer a window from a name explicitly, because `e5` prefixes are a property of+the instruction format while a window differs between checkpoints of one family.++**Is it a closed vocabulary?** No, and the file says so at `presets.ts:6-10`:+"Advisory only: the free-form custom `--model` entry stays first-class, and OSB+targets arbitrary OpenAI-compatible endpoints, so a preset is guidance … never a+constraint." The array is `Object.freeze`d (`:75`) — frozen as a *value*, not as+a *vocabulary*.++**Where it is consumed.** Three call sites, and only three:++1. `src/cli/search/verbs/provider-registry.ts:215` — passed as `ops.presets`+ into the shared registry-CRUD dispatcher. The `presets` action renders the+ catalog at `provider-registry.ts:116-127`; note `:115` — "`presets` is a+ static catalog listing; it needs no vault/config", so the verb runs before+ `resolveConfig` and knows nothing about what the operator is actually using.+ The human rendering at `:121-124` prints only `model`, `dimension`,+ the multilingual tag and `note`; `inputWindowTokens` is *not* printed. The+ `--json` arm at `:118` dumps the array verbatim, so it does print every field.+2. `src/cli/search/verbs/provider-registry.ts:184` — `RECOMMENDED_EMBEDDING_MODEL`+ (`presets.ts:141`, the first entry) is the default for `--model` when omitted+ on `search provider add`.+3. `src/core/search/indexer.ts:41` → `declaredInputWindowTokens` at+ `indexer.ts:705`, inside `censusChunkWindow` (`indexer.ts:694-739`). This is+ the only *diagnostic* consumer.++`resolveEmbeddingPrefixes` (`presets.ts:232-245`) is a fourth internal consumer,+used by the embed path.++**Where a per-preset sunset field would go, and what it would break.**++- It goes on `EmbeddingModelPreset` as an optional field, beside+ `inputWindowTokens`. Optional matters: five of the six presets are open+ checkpoints on Hugging Face with no vendor shutdown authority at all, so a+ required field would force an invented value onto every row — the exact defect+ `presets.ts:158-159` names ("reported as a check that did not run - never as a+ pass").+- What breaks structurally: **nothing compiles-wrong** for an optional field.+ `provider-registry.ts:118` (`JSON.stringify(ops.presets)`) would start emitting+ the new key in `o2b search provider presets --json` — an additive payload+ change, but a payload change. `tests/core/search/embeddings.presets.test.ts:15`+ iterates every preset asserting per-field invariants; a new field with its own+ invariant belongs there.+- What breaks *semantically*: the catalog's stated purpose is "known-good+ embedding models surfaced when a user registers an OpenAI-compatible provider"+ (`presets.ts:4-6`). A curated list of *recommendations* that also carries+ *obituaries* is two catalogs in one file. A dying model has no business being+ `RECOMMENDED_EMBEDDING_MODEL` (`presets.ts:141` takes index 0 unconditionally)+ nor being defaulted into a new provider profile at+ `provider-registry.ts:184` — and nothing in either site would consult a sunset+ field unless it were wired to.++---++## 2. How the configured provider/model is resolved at runtime++**The chain.** `resolveSearchConfig` at `src/core/search/index.ts:394` onwards.++1. Config file → flat string map. `src/core/search/index.ts:401-403` calls+ `discoverConfig(opts.configPath).data`, which is+ `parseSimpleYaml(readConfigText(resolved))` (`src/core/config.ts:211`).+ `parseSimpleYaml` (`src/core/config.ts:153-174`) is a line-splitter producing+ `Record<string, string>` — **flat only**. `src/core/config.ts:194-196` states+ it "skips whatever it cannot represent (comments, blank lines, nested+ blocks)". A nested block in the o2b config file is silently dropped.+2. Provider name: `index.ts:464-470`, `envOrConfig(env, config,+ "OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER", "embedding_provider")`.+3. Registry expansion first-but-lower-precedence: `resolveRegistryProvider`+ (`index.ts:377-393`) returns non-null only for a name that is neither null nor+ a built-in (`BUILTIN_PROVIDERS`, `index.ts:369-373`). It is fail-soft — a bad+ registry yields `null` (`index.ts:390-392`).+4. `const provider = registryExpansion ? "openai-compat" : parseProvider(rawProvider)`+ (`index.ts:467`). `parseProvider` (`index.ts:358-366`) accepts exactly four+ strings and throws otherwise. So **the resolved provider is a closed union of+ four**: `openai-compat | zeroentropy | local | disabled`.+5. Model: `index.ts:481-486` reads `embedding_model` /+ `OPEN_SECOND_BRAIN_EMBEDDING_MODEL`, then `index.ts:492`:+ `const model = explicitModel ?? registryExpansion?.model ?? null`.+ **No validation of any kind is applied to the model string.**+6. Registry profiles: `ProviderProfile.defaultModel` (`embeddings/registry.ts:26`)+ is validated only for non-emptiness (`registry.ts:115-117`). The profile name+ is slug-checked (`registry.ts:99-105`) and reserved names refused+ (`registry.ts:106-111`); the model is not checked against anything.+7. At census/status time the *effective* model comes from `activeEmbeddingModel`+ (`indexer.ts:641-647`): `local` → `LOCAL_EMBEDDING_MODEL`, otherwise+ `config.semantic.model ?? storedModel` — i.e. it can also come from the+ index's own `embedding_model` state cell.++**The critical answer: yes, a user can configure a model outside the catalog,+and this is the normal case, not the edge case.**++Evidence beyond the type: the tool's *own onboarding text* recommends an+off-catalog model. `src/cli/main.ts:266-267` prints++```+ embedding_base_url: "https://openrouter.ai/api/v1"+ embedding_model: "google/gemini-embedding-2-preview"+```++`google/gemini-embedding-2-preview` is not in `EMBEDDING_MODEL_PRESETS`+(`presets.ts:75-138`) — and it is a *preview* model, precisely the class most+likely to be decommissioned. `findEmbeddingPreset` returns `null` for it+(`presets.ts:145`), which `tests/core/search/embeddings.presets.test.ts:32-34`+pins for a custom model.++**Consequence for the design, stated as the source demands it.** A sunset check+keyed on the catalog can only ever speak about catalog members. For everything+else it must say **"this model is unknown to the curated catalog, so no sunset+statement was made"** — never "no sunset announced". The codebase already has+this exact distinction implemented once, for the input window:+`declaredInputWindowTokens` (`presets.ts:168-171`) returns `null` meaning+UNKNOWN, and `presets.ts:150-159` spells out why it is deliberately *not* shaped+like `pricePerMillionTokens` (`signature.ts:59-63`, which answers `0` for an+unlisted model): "An unknown window has the opposite polarity - treating it as+'fits' would report a passing check for a condition nobody measured, which is+the misleading silence this census exists to remove." A sunset date has the same+polarity as a window, not as a price. The wire-level precedent is+`ChunkWindowCensus`'s `window-undeclared` verdict (`src/core/search/types.ts:186-193`)+mapping to its own diagnostic code (`types.ts:218`).++**Also unestablished by the catalog: the provider.** The task asks the warning to+name "the provider". The four resolved provider values (`index.ts:358-366`) are+transport kinds, not vendors — `openai-compat` says nothing about whose endpoint+it is. The vendor identity, when there is one, lives in `embedding_base_url`+(`index.ts:475-480`) or in a registry profile's `baseUrl`+(`embeddings/registry.ts:25`), both free-form URLs with no validation beyond+non-emptiness (`registry.ts:112-114`). I could not find any place in the tree+that maps a base URL to a vendor identity.++---++## 3. Embedding identity, and what a model change costs++**Identity.** `EmbeddingIdentity` at `src/core/search/embeddings/signature.ts:15-19`+is the triple `{ provider, model, dimension }`. `embeddingSignature`+(`signature.ts:37-42`) canonicalises it to `<provider>:<model>:<dimension>` with+NFC + trim + lowercase (`signature.ts:27-29`) and a `?` sentinel for nulls+(`signature.ts:25`). `LOCAL_EMBEDDING_MODEL = "hashing-ngram-v1"`+(`signature.ts:22`). `isStaleSignature` (`signature.ts:227-229`) is plain string+inequality.++**What happens when the model changes under an existing index.** There *is* an+invalidation path, it is real, and it is gated:++- The index records three ABI tokens: `embedding_model`, `embedding_dimension`,+ `embedding_vec_version` (`src/core/search/store/embedding-abi.ts:29-34`,+ keys at `src/core/search/store/state.ts:33-34`).+- On **read open**, `Store.resolveEmbeddingAbi`+ (`src/core/search/store.ts:224-233`) compares recorded against runtime+ (`store.ts:226-228`), and under mode `fail` throws+ `SearchError("EMBEDDING_DIMENSION_MISMATCH", …)` (`store.ts:232`).+- The mode is operator config. `src/core/brain/policy/blocks/integrity.ts:68`+ — **default is `warn`, not `fail`** — with `:88` showing `fail` only under the+ strict profile. `store.ts:188-191` notes the drift list is structurally empty+ when the gate is `off`.+- A mismatch whose *recorded* side is `null` (a store predating the stamp) is+ reported but never refused: `contradictedAbiFields`+ (`embedding-abi.ts:81-83`) filters to `expected !== null`, and+ `embedding-abi.ts:72-77` explains why.+- The single remediation string is `EMBEDDING_ABI_FIX_COMMAND =+ "o2b search reindex --embeddings"` (`embedding-abi.ts:25`), rendered by+ `formatEmbeddingAbiDrift` (`embedding-abi.ts:90-97`), reused by+ `search check` (`indexer.ts:1488-1494`) and surfaced as `embedding_abi:` in+ both report shapes (`src/cli/search/verbs/check.ts:437-439`, `:394-397`).++So: **not silent nonsense — but by default only a warning**, and only once the+model has *already* changed. The sunset warning is the strictly earlier signal:+it fires while the config is still correct and the index still valid. Nothing in+the ABI machinery can fire before the operator edits the model, which is the gap+t_e7a226ce identifies. What the ABI path does establish is the cost the sunset+warning is warning *about*: a model change invalidates every stored vector and+the remedy is a full re-embed of the corpus, named at `embedding-abi.ts:25`.++---++## 4. The doctor / diagnostics check idiom++### The registry is not the checks++`src/core/brain/diagnostics.ts:348-435` — the lines the task body cites — are+**registry entries**, not checks. `DIAGNOSTIC_SIGNALS`+(`diagnostics.ts:125` … `:718`) is a `ReadonlyMap<string, DiagnosticSignal>`+whose entries are `{ code, issueClass, nextCommand, autoRepairable }`+(`diagnostics.ts:77-86`). The entries at `:371-459` name search-config *states*;+the code that detects them lives in `src/core/search/` and+`src/core/brain/doctor/`. See Divergences.++### Anatomy of a doctor check++- **Contract**: `src/core/brain/doctor/check.ts` — `DoctorCheck` has+ `failSoft: boolean` and `run(ctx, out): void`. `DoctorCheckContext` carries+ `vault`, `now: Date`, `config: BrainConfig | undefined`, `dbPath`,+ `configPath`, `knownBasenames`, `idIndex`, `preferences`, `logs`.+- **Registration**: append to the frozen `DOCTOR_CHECKS` array in+ `src/core/brain/doctor.ts:132-166`. Order is contractual+ (`doctor.ts:126-130`). The runner is `doctor.ts:264-282`; a `failSoft` check's+ throw is swallowed there (`:277-281`).+- **Finding shape**: `DoctorIssue` at `src/core/brain/types.ts:1977-2010` —+ `severity`, `code`, optional `path`, `message`, optional `field`, `target`,+ `sources`.+- **Severity vocabulary**: exactly two values.+ `export type DoctorSeverity = "warning" | "error"` at+ `src/core/brain/types.ts:1971`. There is no `info`. Partitioning is+ `doctor.ts:294-296`.+- **Message**: a free string, rendered by `renderIssueLine` in the CLI.+- **`nextCommand`**: never written at the finding site. It is resolved from the+ registry — `resolveNextStep` (`src/core/brain/next-step.ts:36-43`, returns+ `null` for an unregistered code) or `requireNextStep`+ (`next-step.ts:67-71`, throws `UnregisteredNextStepError`). The JSON key is+ `NEXT_COMMAND_KEY = "next_command"` (`next-step.ts:79`). New consumers MUST use+ `next-step.ts`, not the lenient `resolveSignal`+ (`diagnostics.ts:719-731, 732-740`), which fabricates a generic+ `o2b brain doctor` hint for unknown codes.++### Severity → process exit++`src/cli/brain/verbs/doctor.ts:212-214`:++```+if (result.errors.length > 0) return 1;+if (result.warnings.length > 0 && flags["strict"]) return 2;+return 0;+```++A `warning` therefore exits **0** unless `--strict` is passed, in which case+**2**. The `uncertain` stream deliberately does not feed the exit code+(`doctor.ts:156-162`).++For contrast, `o2b search check` has its own table:+`SEARCH_CHECK_EXIT = { ok: 0, fatal: 1, providerUnreachable: 5, probeIncomplete: 6 }`+(`src/cli/search/verbs/check.ts:107-112`), computed by `exitCodeForCheck`+(`check.ts:129-144`).++### What the doctor-exit census requires — precisely++`tests/core/brain/doctor-exit-census.test.ts`. It enumerates the population from+source, not from the tables: `doctor.ts` plus every `.ts` under+`src/core/brain/doctor/` recursively (`:74-85`, `:113-117`), plus modules+followed through `import { …_CODE… } from "./…"` statements (`:91-111`).+Two code shapes are read: `code: "<literal>"` (`:127`) and+`const <NAME>_CODE = "<literal>";` (`:130`).++A new doctor check must satisfy all of:++1. **Classified exactly once.** Its code is in `DIAGNOSTIC_SIGNALS` **or** in+ `DOCTOR_EXIT_EXCLUSIONS`, never both, never neither (`:235-248`).+2. **If registered, it must be added to the pinned list.**+ `DOCTOR_REGISTERED_CODES` (`:177-200`, currently 22 entries) is asserted+ equal, as a sorted newline-joined string, to the doctor codes present in the+ registry (`:250-258`). Adding a registered doctor code without editing this+ array fails. The docblock at `:163-176` states this is deliberate — "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."+3. **If excluded instead**, the reason must be ≥ 80 characters+ (`MIN_REASON_LENGTH`, `:203`; asserted `:266-272`) and must **not** contain an+ `o2b <verb>` invocation (`INVOCATION_RE`, `:206`; asserted `:274-279`) —+ "a code with one belongs in the registry".+4. **The code must be syntactically readable.** A `code:` value that is neither a+ string literal nor a `*_CODE` identifier fails `:296-303` unless declared in+ `NON_LITERAL_CODE_SITES` (`:145-161`).+5. **Non-vacuity floors** at `:281-292` (`codes.length > 35`, registered `> 14`,+ excluded `> 20`, source paths `> 10`) rise as codes are added; adding one+ never breaks them.++Additionally, any new `DIAGNOSTIC_SIGNALS` entry must pass the registry prose+guard in `tests/core/brain/next-step.test.ts:58-70`: `nextCommand` must match+`STRUCTURAL_COMMAND_RE` (`:29-30`) — `o2b` plus one-to-three verb words plus only+long flags or `<placeholder>` arguments — and contain no `.!?;,:`+(`SENTENCE_PUNCTUATION_RE`, `:33`), no newline, no double space.++And any new closed vocabulary (e.g. a sunset verdict enum) whose values cross the+TypeScript boundary into a `--json` payload must register in+`tests/core/architecture/verdict-vocabulary-census.test.ts` with the+frozen-object / members-list / type-guard trio — the file's own rule at `:1-26`,+and `PROVIDER_PROBE` is registered there at `:494-505` for exactly this reason.++---++## 5. Time++**There is an injectable clock seam, and the doctor already uses it.**++- `DoctorCheckContext.now: Date` (`src/core/brain/doctor/check.ts:26`) —+ "Wall clock for the age-based lints, so tests can pin it."+- Supplied by `runDoctor`: `now: opts.now ?? new Date()`+ (`src/core/brain/doctor.ts:371`), with `now?: Date` declared on the options at+ `src/core/brain/doctor/report.ts:24`.+- A check consumes it by destructuring: `run({ vault, now }, …)` in+ `src/core/brain/doctor/stale-dependency-check.ts:438`, passed on at `:441`.++**The v1.47.0 "refuse a declared instant later than the reading clock" idiom.**+`src/core/search/authored-at.ts`. `usableAuthoredAtSeconds`+(`authored-at.ts:39-47`) takes `nowMs` as a parameter and returns `null` for+`authoredAtSeconds * 1000 > nowMs` (`:45`). The module header states the+discipline verbatim at `:16-17`: "Pure and injectable: the caller passes the+clock, so nothing here reads `Date.now()`". `:33-37` explains why a refusal+returns `null` rather than a clamped substitute — "Clamping to the reading clock+instead would leave the document at the top of the freshness curve forever,+which is the defect rather than its fix."++The same shape exists in the Brain layer: `src/core/brain/stale-dependency.ts:420`+drops a state whose `changed_at` parses to `> nowMs`, with the rationale at+`:394-396` ("a `valid_until` in the future has not closed yet").++**Where `Date.now()`/`new Date()` is called directly**, for contrast:+`src/core/search/store/sql.ts:13-15` (`nowIso`), `src/core/brain/time.ts:100-107`+(`isoSecond`/`isoDate`, both defaulting `d: Date = new Date()`).+`src/core/brain/time.ts:87-95` shows the preferred alternative — `fileAgeMs`+takes `nowMs` as a required parameter, "so a caller that already holds a pinned+clock cannot accidentally measure against a second, later one mid-scan".++**`indexCheck` has no clock at all.** Reading `src/core/search/indexer.ts:1331-1473`+end to end: no `Date`, no `now`, no time parameter. `IndexCheckOptions`+(`indexer.ts:1319-1329`) carries only `probeProvider`. A sunset comparison placed+in `search check` would be the first time-dependent statement in that report, and+would need a new seam.++**Date format in this codebase.** Two accepted shapes, one parser:+`parseIsoUtc` (`src/core/brain/health/iso-time.ts:20-23`) accepts date-only+`YYYY-MM-DD` (`ISO_DATE_ONLY_RE`, `:12`) and expands it to `T00:00:00Z` before+`Date.parse` — explicitly "so the millisecond result is identical on every engine+and peer, never drifting to a local-midnight interpretation" (`:15-18`).+`isValidIsoInstant` (`:30-32`) is the loud-rejection predicate. Frontmatter+emits UTC via `isoSecond` → `YYYY-MM-DDTHH:MM:SSZ` and `isoDate` →+`YYYY-MM-DD` (`src/core/brain/time.ts:100-107`). Everything is UTC; I found no+timezone-aware date handling anywhere in the tree. The doctor already has a code+for a malformed one: `iso-invalid`, excluded from the registry with the reason at+`src/core/brain/doctor-exits.ts:185-191`.++Note the polarity clash to design around: a sunset date is a *future* instant and+therefore legitimately `> nowMs`, which is the exact condition both+`authored-at.ts:45` and `stale-dependency.ts:420` refuse. The v1.47.0 idiom to+reuse here is the *injectable-clock parameter*, not the future-refusal predicate.++---++## 6. Where sunset metadata could honestly come from++Four options are visible in this tree. Evidence and failure modes only; no+recommendation.++### (a) A static field on `EmbeddingModelPreset`++Fits `presets.ts:30-67` mechanically (see §1). Precedent: `inputWindowTokens`+(`:53`) is exactly this — a third-party fact hardcoded from published specs, with+per-entry source comments (`:80-81`, `:92`, `:102-104`, `:112`, `:121-122`,+`:131-133`).++- **Stale**: a date passes, the model is already gone, and the check keeps+ warning about a shutdown in the past — or, worse, a vendor *postpones* and the+ tool warns about a date that no longer exists. The binary is the only source of+ truth and the operator cannot correct it without a release.+- **Absent**: the model is off-catalog (§2 — the normal case, including this+ tool's own onboarding recommendation at `src/cli/main.ts:267`). The check+ cannot speak. It must say "unknown to the catalog", which the codebase already+ models via `null`-means-UNKNOWN (`presets.ts:150-159`) and the+ `window-undeclared` verdict (`src/core/search/types.ts:186-193`).+- Note also: five of six presets are open checkpoints with no vendor able to+ announce a shutdown, so the field would be absent on most rows even in-catalog.++### (b) A config-declared date++The o2b config file is flat `Record<string, string>` — `parseSimpleYaml`+(`src/core/config.ts:153-174`), nested blocks silently dropped+(`src/core/config.ts:194-196`). So this can only be a scalar key such as+`embedding_model_sunset: "2026-11-01"`, resolved through the same+`envOrConfig` idiom as every other search key (`index.ts:481-486`), and it+describes exactly one model — the one currently configured.++`Brain/_brain.yaml` is the other config surface and *does* support nested blocks+(`src/core/brain/policy/blocks/`, e.g. `integrity.ts:104`), so a per-provider map+could live there — but it is read by the Brain layer, not by+`resolveSearchConfig`, and `DoctorCheckContext.config` (`doctor/check.ts:28`) is+already that type.++- **Stale**: an operator writes a date, the vendor moves it, nobody edits the+ file. The tool warns confidently about a wrong date. Nothing can detect this.+- **Absent**: silence. And silence here is the defect this project keeps fixing —+ the check must distinguish "operator declared no date" from "no shutdown+ exists", which a single optional key cannot do on its own.+- **Malformed**: covered by the existing predicate `isValidIsoInstant`+ (`health/iso-time.ts:30-32`) and the existing `iso-invalid` disposition+ (`doctor-exits.ts:185-191`) — reject loudly, never treat as absent.++### (c) A fetched registry (network)++**The project's stance, as found:**++- `presets.ts:9-10`: "No server, no network - the list is consulted entirely at+ registration time."+- `src/cli/search/verbs/check.ts:507-511`: the provider probe is "The one+ outbound call this verb makes", opt-*out* via `--no-probe`, and `--no-probe`+ exists "for the caller who cannot spend a network round-trip - an air-gapped+ machine, a tight CI loop".+- `src/core/brain/runtime-notices.ts:8-9`: notices are computed "deterministically+ - no network, no LLM, no DB open".+- `src/core/doctor-readiness.ts:257-261`: a key-less remote provider is refused+ locally rather than "making a credential-free outbound request whose only+ possible outcome is an auth error".+- The vault deliberately has no git transport — see CHANGELOG v1.47.0, "the vault+ has no git transport and deliberately never will, a constraint written verbatim+ in seven design documents".+- `tests/core/architecture/egress-census.test.ts` polices *outbound vault+ content*, not inbound fetches, so it would not by itself block a registry+ fetch — but every module docblock above treats an unrequested network call as a+ cost that must be declared.++Failure modes: **stale** — a cached registry is the same lie as (a) with more+machinery; **absent/unreachable** — the check did not run, and per+`check.ts:140-143` and `provider-probe.ts:21-28` that is a first-class third+answer requiring its own state, not a fold into pass or fail.++### (d) An operator-declared date per provider profile++`ProviderProfile` (`src/core/search/embeddings/registry.ts:23-34`) is a+persisted, editable JSON record at+`Brain/search/embedding-providers.json` (`registry.ts:52-54`), loaded fail-soft+(`registry.ts:73-88`) and validated field by field (`registry.ts:98-124`). Adding+an optional `sunsetAt` there gives a per-provider, per-model, operator-owned date+that survives upgrades, is not baked into the binary, and is already+round-tripped through `add`/`show`/`list` in+`src/cli/search/verbs/provider-registry.ts`.++- **Stale**: same as (b) — the operator's date, nobody's job to refresh.+- **Absent**: only registered profiles have one. A provider configured purely+ through `embedding_base_url` + `embedding_model` (the path `src/cli/main.ts:266-268`+ actually recommends) has no profile at all, so there is nowhere to put the+ date. `isProfile` (`registry.ts:61-70`) would need to keep accepting profiles+ without the field or every existing registry file becomes unparseable —+ fail-soft loading (`registry.ts:73-79`) means a validation tightening here+ degrades to "empty registry", i.e. the provider silently stops resolving.++---++## Divergences++Every point where t_e7a226ce's framing did not survive contact with the source.++1. **"`src/core/brain/diagnostics.ts:348-435` already hosts adjacent search-config+ checks."** It does not host *checks*. Those lines are entries in the+ `DIAGNOSTIC_SIGNALS` registry (`diagnostics.ts:125`–`:718`), which maps a code+ to a `nextCommand` string (`diagnostics.ts:77-86`). No detection runs there.+ The detection for `search-chunk-window-undeclared` is `censusChunkWindow` in+ `src/core/search/indexer.ts:694-739`; the capability-tier states at+ `diagnostics.ts:371-398` are resolved by `src/core/search/capability-tier.ts`.+ A new check therefore needs **two** edits in two layers, not one.++2. **"provider not configured / disabled" is not a doctor check either.** It is+ `resolveSemanticCapability` consumed by `indexCheck`+ (`src/core/search/indexer.ts:1340`, `:1401-1404`) and by `probeEmbeddingProvider`+ (`src/core/doctor-readiness.ts:275-282`). The registry entries at+ `diagnostics.ts:371-388` deliberately point at `o2b search check`, not at an+ edit command, because "no verb in this tool writes one" (`diagnostics.ts:366-370`).++3. **"a curated presets catalog exists but no sunset registry" — the catalog is+ also the wrong shape for one.** Five of its six entries+ (`presets.ts:75-138`) are open-weight checkpoints (`intfloat/…`, `BAAI/…`,+ `sentence-transformers/…`, `Alibaba-NLP/…`) with no vendor decommission+ authority. The models that actually get decommissioned — hosted, versioned,+ preview — are precisely the ones **not** in the catalog. The three model names+ that appear in `EMBEDDING_PRICING` (`signature.ts:51-56`:+ `text-embedding-3-small`, `text-embedding-3-large`, `text-embedding-ada-002`)+ are hosted OpenAI models and are in *that* table but not in the presets+ catalog at all. So the repo already keeps a second, disjoint list of+ vendor-hosted model names, and neither list is the other's superset.++4. **"warns … the warning names the provider".** The resolved provider is one of+ four transport kinds (`index.ts:358-366`), not a vendor. Vendor identity, when+ it exists, is only inferable from a free-form `embedding_base_url`+ (`index.ts:475-480`) or profile `baseUrl` (`registry.ts:25`), and no code in+ the tree maps a URL to a vendor.++5. **"the migration command".** There is exactly one relevant command already+ named in the tree and it is a *reindex*, not a migration:+ `EMBEDDING_ABI_FIX_COMMAND = "o2b search reindex --embeddings"`+ (`embedding-abi.ts:25`). Nothing in this tool writes a config key — stated at+ `diagnostics.ts:366-370` and again at `diagnostics.ts:443-446` and `:455-457`+ — so "switch to model X" cannot be a command. The existing precedent for this+ exact shape is `search-chunk-window-undeclared`, whose `nextCommand` is+ `o2b search provider presets` (`diagnostics.ts:451-458`): the catalog is+ pointed at *because* the config edit has no verb.++6. **"a diagnostics/doctor check" — the two candidate homes are not+ interchangeable, and neither is free.**+ - `o2b brain doctor`: has the clock seam (`doctor/check.ts:26`), has the+ severity vocabulary, is bound by the doctor-exit census (§4). But **no+ doctor check currently resolves search config**; the only index-aware check+ is `doctor/store-integrity.ts:34-36`, which uses `ctx.dbPath` and never+ `resolveSearchConfig`. The `core/brain → core/search` import edge does+ already exist (`src/core/brain/runtime-notices.ts:32` imports+ `resolveSearchConfig` from `../search/index.ts`), so the edge is permitted.+ - `o2b search check`: already owns the provider question and the exit codes+ 5/6, but has **no clock** (`indexer.ts:1331-1473`) and no severity ladder —+ only `warnings[]`, `fatal[]`, `recommendations[]`+ (`src/core/search/types.ts:407` onward, rendered at `check.ts:446-452`).+ The task body names neither, and picking one is a real decision.++7. **The companion framing is right, and the source makes the boundary sharper+ than "now vs later".** The probe answers in a five-member closed vocabulary+ (`PROVIDER_PROBE`, `src/core/search/provider-probe.ts:58-64`) about *this+ endpoint, this instant*, with the whole point being that `timed-out` and+ `skipped` are not verdicts (`provider-probe.ts:21-28`). A sunset check makes+ no call and produces no probe state. There is no duplication risk — but there+ is a **precedence** question the task does not raise: `exitCodeForCheck`+ (`check.ts:129-144`) already orders faults by how basic they are, and a+ provider proved unreachable *today* plus a shutdown announced for *next month*+ are two true statements about one endpoint that would both want to be said.++8. **"surfacing the risk weeks ahead" implies a threshold the source has no+ convention for.** I found no configured "warn N days before" window anywhere+ in the search or doctor layers. The nearest thing is+ `MS_PER_DAY`/`msToWholeDays` (`src/core/brain/time.ts:57-75`), a pure unit+ conversion with no policy attached.++---++## What a design must not assume++- **Do not assume the configured model is in the catalog.** It usually is not+ (§2), and this tool's own onboarding text recommends one that is not+ (`src/cli/main.ts:267`).+- **Do not report "unknown to the catalog" as "no sunset announced".** These are+ different statements. The codebase has already ruled on this polarity twice:+ `presets.ts:150-159` (unknown window ≠ fits) and+ `src/core/search/types.ts:186-193` + `:218` (`window-undeclared` gets its own+ verdict and its own diagnostic code). The price table's opposite convention+ (`signature.ts:59-63`, unknown → 0) is explicitly called out as safe only+ because its fallback makes a gate *decline* to fire.+- **Do not assume a `warning` severity produces a non-zero exit.** It exits 0+ unless `--strict` (`src/cli/brain/verbs/doctor.ts:212-214`).+- **Do not assume the provider name identifies a vendor.** Four transport kinds,+ no vendor mapping (`index.ts:358-366`).+- **Do not assume a nested config block will be read.** `parseSimpleYaml` drops+ them silently (`src/core/config.ts:153-174`, `:194-196`). Only `Brain/_brain.yaml`+ takes nesting (`src/core/brain/policy/blocks/`).+- **Do not read `Date.now()` inside the check.** Take the clock as a parameter —+ `DoctorCheckContext.now` (`doctor/check.ts:26`) if in the doctor,+ a new explicit parameter if in `search check`, following+ `authored-at.ts:16-17` and `time.ts:87-95`.+- **Do not reuse the future-instant refusal.** `authored-at.ts:45` and+ `stale-dependency.ts:420` both discard instants later than now; a sunset date+ is *supposed* to be later than now.+- **Do not write the command at the finding site.** Register it in+ `DIAGNOSTIC_SIGNALS` and resolve through `next-step.ts:36-43` / `:67-71`; the+ string must pass `STRUCTURAL_COMMAND_RE`+ (`tests/core/brain/next-step.test.ts:29-30`) — no punctuation, no prose.+- **Do not add a doctor code without editing `DOCTOR_REGISTERED_CODES`**+ (`tests/core/brain/doctor-exit-census.test.ts:177-200`, asserted `:250-258`).+- **Do not assume a stale date is detectable.** No option in §6 can tell a+ correct date from one the vendor has since moved. Whatever the source, the+ design has to say where the number came from and when it was last true, or it+ will eventually assert a shutdown that did not happen — which is the same class+ of defect as the silence it is trying to remove.+- **Do not assume `search check` and `brain doctor` can share the finding shape.**+ They have different vocabularies (`DoctorSeverity` at `types.ts:1971` vs+ `warnings`/`fatal`/`recommendations` at `src/core/search/types.ts:407`+) and+ different exit tables (`doctor.ts:212-214` vs `check.ts:107-112`).diff --git a/docs/brainstorm/nothing-runs-unwatched/review/claims-and-refusals.md b/docs/brainstorm/nothing-runs-unwatched/review/claims-and-refusals.mdnew file mode 100644index 00000000..4cd2b1e9--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/review/claims-and-refusals.md@@ -0,0 +1,748 @@+# Claims and refusals — independent review++Scope: the ownership statement, the provider sunset check, the readiness+reclassification and the codegraph switch, the recovery-point liveness check, and+the host-pressure gate with its failure streak. Branch `feat/nothing-runs-unwatched`+against `main`.++Method: read the diff, then reproduce. Where a claim could be settled by running+something, it was run — a scratch copy of `src/ hooks/ plugins/ tests/` under+`/tmp` for mutation tests, scratch `bun test` files for behaviour, `tsc` for the+type-level claims, and this host's own cgroup layout for the pressure probe. No+source file in the repository was modified. One working-tree modification was+already present when I arrived (`tests/core/doctor.test.ts`); it is not mine, and+finding 7 is about it.++Findings are ordered by severity within each confidence class.++Note on moving ground: the branch tip advanced from `751fbb17` to `ceb8b1e3` while+this review was running. Everything below was verified against `751fbb17` and+re-checked against `ceb8b1e3` where the new commit touched it; finding 7 is closed by+it and finding 8 is half-closed. Nothing else moved.++---++## CONFIRMED — reproduced++### 1. The ownership statement asserts where the search index lives without checking++`src/core/install/ownership.ts:300`++The first line of the block an operator reads after a successful install says, with+no condition attached:++> Your brain is `<vault>`. Every memory this tool writes is a Markdown file under+> it, **and the search index beside them is a rebuildable SQLite file in the same+> vault.**++Two lines below, the enumeration contradicts it (`relocated_search_index`, id at+`ownership.ts:100`): the index can be relocated anywhere by+`OPEN_SECOND_BRAIN_SEARCH_DB` or `search_db_path`.++Reproduced by rendering the statement with the override set:++```+$ OPEN_SECOND_BRAIN_SEARCH_DB=/var/tmp/elsewhere/index.sqlite bun run <render>+ Your brain is /tmp/vault-x. Every memory this tool writes is a Markdown file+ under it, and the search index beside them is a rebuildable SQLite file in the+ same vault.+ ...+ - relocated search index — OPEN_SECOND_BRAIN_SEARCH_DB, or the search_db_path+ config key, when either is set+```++The fact is measurable and is one call away from where it is printed:+`ownershipFor` (`src/cli/install/install.ts`, the `resolveSearchConfig` call) already+resolves the search config, whose `dbPath` is `resolveIndexPath`'s answer. Nothing+passes it into `DataOwnershipInput`.++**Failure scenario.** An operator who relocated the index onto a scratch volume+reads a printed guarantee that a copy of every indexed chunk travels with the vault.+It does not.++**Confidence: high.** This is the one clause of the statement that makes an+unconditional claim about a path other than the vault, and it is the only clause+whose input was available and not taken.++---++### 2. The closing sentence re-asserts the claim the block spent twenty lines qualifying++`src/core/install/ownership.ts:322-326`++```+ Delete the vault and the memory is gone. What stays behind is the machine-local+ list above; `o2b uninstall` removes the parts this tool put there.+```++Both halves are contradicted inside the same printed block:++- "Delete the vault and the memory is gone" is exactly the unqualified sentence the+ module docblock (`ownership.ts:4-8`) says is FALSE, and the counterexample is row+ one of the list printed immediately above it — the opencode session spool, whose+ own note reads "Nothing in this tool prunes them, so on a machine using that+ integration this is memory content living outside your vault."+- "`o2b uninstall` removes the parts this tool put there" over-claims.+ `src/cli/uninstall.ts` removes the config directory (guarded by+ `isSafeLocalConfigDir`) and, with `--remove-cli`, the `~/.local/bin` symlinks. It+ does not touch the opencode spool, the `~/.codex/config.toml` fence, the reminder+ markers, the bench-run artifacts, or a relocated index — five of the nine rows.++The renderer already carries the hedge two lines earlier ("`N` of those can hold+memory content rather than plumbing, which is why the first line says what this tool+WRITES rather than everything you have ever said to it") and then throws it away in+the closing sentence.++**Confidence: high.** Read directly off the rendered output reproduced in finding 1.++---++### 3. The census that is supposed to make finding 2 impossible cannot see an async writer++`tests/core/install/ownership.test.ts:167`++```ts+const WRITE_RE =+ /(?:writeFileSync|appendFileSync|mkdirSync|symlinkSync|copyFileSync|mkdtempSync)\(/;+```++The whole argument for `OUT_OF_VAULT_STATE` being a list rather than prose+(`ownership.ts:29-35`) is that this sweep "demands each be attributed to an entry+here or excused" — "so a new out-of-vault location cannot ship without the sentence+learning about it".++Reproduced in a scratch copy of the tree. Adding `src/core/scratch-spool.ts`:++```ts+import { writeFile, mkdir } from "node:fs/promises";+import { homedir } from "node:os";+import { join } from "node:path";++export async function spoolTurn(text: string): Promise<void> {+ const dir = join(homedir(), ".local", "share", "open-second-brain", "scratch");+ await mkdir(dir, { recursive: true });+ await writeFile(join(dir, "turns.jsonl"), text + "\n", { flag: "a" });+}+```++— a module that appends raw conversation turns to a home-rooted spool, i.e. the+exact shape of the `opencode_session_spool` row the enumeration exists for —++```+15 pass 0 fail+```++Control: the same module written with `appendFileSync` **is** caught —++```+Received: "src/core/scratch-spool2.ts"+(fail) no out-of-vault write escapes the enumeration > every writer is either+ attributed to an entry or excused in writing+14 pass 1 fail+```++So the test works, and its guarantee is scoped to the synchronous `*Sync` family+only. Uncovered: `fs/promises` (`writeFile`, `appendFile`, `mkdir`, `cp`, `rename`),+`renameSync`, `cpSync`, `createWriteStream`, `Bun.write`, and `openSync`+`writeSync`.++**Failure scenario.** The next integration that spools sessions — the natural way to+write one today is `await writeFile(...)` — ships with the ownership statement+silently unaware of it, which is the defect the module was built to make impossible.++**Confidence: high (reproduced both ways).**++---++### 4. "No account, no server … nothing to cancel" is checked against one of at least three third-party services++`src/core/install/ownership.ts:303` and `src/cli/install/install.ts` (`ownershipFor`)++The blanket claim is qualified by exactly one measured input,+`third_party_embedding_configured`. Two other operator-configurable outbound+services exist in the tree and neither is consulted:++- **Reranker.** `search_rerank_enabled` / `search_rerank_base_url` /+ `search_rerank_env_key` (`src/core/search/index.ts:584,603,612`) drive+ `src/core/search/rerank/cross-encoder.ts:85`, which POSTs the query **and the+ candidate document text** to that endpoint under an API key. That is a third-party+ account holding vault text, by the statement's own definition.+- **Telegram capture.** `src/core/brain/capture/telegram-capture.ts:418,433` long-polls+ `https://api.telegram.org` with a bot token. The token is an account with a third+ party, and the messages it carries are capture content that lives on Telegram's+ servers.++**Failure scenario.** An operator running the reranker reads "no account, no server,+no sync endpoint … nothing to cancel" and takes it as an inventory. It is an+inventory of one integration.++**Confidence: high** for the reranker (config keys, API key, document text in the+request body); **high** for Telegram as an account claim.++---++### 5. The enumeration is a static table printed as a measurement++`src/core/install/ownership.ts:243-252`, docblock claim at `ownership.ts:23-27`++> So the statement is COMPOSED rather than written … **Every one of those is a+> measurement; none is an assumption.**++Three inputs are measured: the resolved vault, the backing verdict, and the+embedding flag. The nine rows are not. They are printed unconditionally, under a+sentence that reads as a statement of fact about *this* machine:++```+ Copy the vault and the memory goes with it. These 9 things live outside it and+ do not travel in the copy:+```++On a machine that has never run the opencode plugin, never run `o2b install-cli`,+never run `o2b brain protect --target codex`, never run `o2b brain bench`, and set no+`search_db_path`, five of those nine do not exist.++The one row that *is* parameterised makes it worse rather than better.+`withAdapterTargets` is fed `defaultRegistry.targets()` — every adapter this build+registers, verified as `aider, copilot-cli, cursor, gemini-cli, generic, grok, kiro,+opencode, pi` — so the statement names nine runtimes' config files as places state+was left, on a machine where one target was installed. `probeInstalledRuntimes`+(`src/core/doctor-readiness.ts`) already answers that question by calling each+adapter's own `verify(env)`; the ownership path calls `targets()` instead.++**Failure scenario.** The operator is handed a nine-item cleanup list, most of which+is not on their disk, by a surface whose stated purpose is not saying more than it+knows. The over-claim is the mirror of the defect this release removes.++**Confidence: high.** `targets()` vs. `verify()` is a one-line read; the+unconditional rows are visible in the rendered output above.++---++### 6. The recovery-point check is silent when the history exists and lists nothing++`src/core/brain/doctor/recovery-point-liveness.ts:116` with+`src/core/brain/snapshot.ts:1129-1140`++The docblock (`recovery-point-liveness.ts:32-44`) states three states and asserts:++> a directory that IS there and cannot be enumerated throws, and that is neither+> answer — it reaches the uncertain stream naming why.++Only `readdirSync` failure throws (`snapshot.ts:1119`). Every *per-entry* failure+inside `listSnapshots` is swallowed with `continue`: a name whose `validateRunId`+fails (`:1131`), and a `statSync` that throws (`:1138`). A populated+`Brain/.snapshots/` in which no entry survives both filters returns `[]`, which the+check reads as `kind: "empty"` — "No state-changing pass has ever run" — and returns+without a warning and without an uncertain entry.++Reproduced with a scratch `bun test`:++```+issues: [] uncertain: []+2 pass+```++Case A: `Brain/.snapshots/20240101T000000Z.tar.zst` as a dangling symlink →+`statSync` throws → skipped → `[]`.+Case B: archives present with an unrecognised suffix (`.tar.gz`) → filtered → `[]`.++The shipped test (`tests/core/brain/doctor/recovery-point-liveness.test.ts:136`) covers+only the `chmod 000` directory, i.e. the one path that does throw.++**Failure scenario.** A vault synced with preserved ownership — a shape this project+designs for, and the scenario the uncertain stream's own docblock cites — where the+archives are not stattable by this user. The doctor reports a clean bill on a vault+whose rollback history it could not read at all.++**Confidence: high (reproduced).**++---++### 7. RESOLVED DURING REVIEW — the codegraph switch shipped one commit ahead of its test++`tests/core/doctor.test.ts:259`, against `src/core/partner/codegraph.ts:314`++At `751fbb17` — the branch tip when this review started — `checkCodegraph` already+returned `codegraphDisabledResult()` instead of `null`, while the test still asserted+the old behaviour. Reproduced by extracting that commit's copy of the file and+running it against the branch source:++```+(fail) doctor aggregator > omits code_graph when partner.codegraph.disabled is true+23 pass 1 fail+```++`ceb8b1e3` ("fix(tests): stop the doctor suites paying for a partner they never+assert on") landed mid-review and reconciles it. **No action needed.** Recorded+because the shape is worth noticing: a behaviour change and the test that pins it+rode in separate commits, so the branch was red at a pushable tip for the length of+that gap.++---++### 8. The partner consult is unbounded, and only the test-side cost was removed++`src/core/partner/codegraph.ts:243,258`++Both `Bun.spawnSync` calls — `codegraph status --help` and `codegraph status --json`+— are issued with `cmd`, `stdout`, `stderr`, `env` and **no `timeout`** (verified+after `ceb8b1e3`: the file still contains no `timeout` key). `doctor()` calls them+synchronously, and `doctor()` has three callers: the CLI, the MCP `vault_health`+tool, and the OpenClaw extension.++Measured on this host, where codegraph is installed:++```+doctor() → 4285 ms+doctor({partner:{codegraph:{disabled:true}}}) → 0 ms+```++Before `ceb8b1e3` that made `tests/core/doctor.test.ts` "returns at least the vault+check" time out at the 5000 ms default:++```+(fail) doctor aggregator > returns at least the vault check [5999.41ms]+ ^ this test timed out after 5000ms.+```++`ceb8b1e3` fixes that by passing `partner: { codegraph: { disabled: true } }` in the+suites and setting the env var in the three MCP suites — i.e. it removes the cost+from the tests, with a commit message that measures it honestly (21.55 s → 0.652 s).+The production path is unchanged: `vault_health` over MCP still pays the four+seconds by default on any machine with the binary on PATH, and a partner CLI that+hangs blocks `doctor()` for as long as it hangs, with no deadline, no refusal and no+progress record.++The new config docblock (`src/core/config.ts`, `resolvePartnerCodegraphDisabled`)+names the cost precisely — "asking it costs seconds against a cold HOME" — and+answers it with an opt-out rather than a budget. In a release that gave four MCP+tools a progress token and a cancel seam, the one synchronous subprocess in the+doctor got neither.++**Confidence: high (measured, and re-verified after `ceb8b1e3`).**++---++### 9. The pressure gate reads a cgroup that is never the process's own++`src/core/brain/maintenance/host-pressure.ts:51-52,169-183`++`probeCpuQuota()` reads exactly two absolute paths:++```ts+const CGROUP_V2_CPU_MAX = "/sys/fs/cgroup/cpu.max";+const CGROUP_V1_CPU_QUOTA = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us";+```++Under cgroup v2 the **root cgroup carries no `cpu.max`** — the file exists on every+child, not on the root. The process's own cgroup is found in `/proc/self/cgroup`,+which this module never reads. Demonstrated on this host:++```+$ ls /sys/fs/cgroup/cpu.max+ls: cannot access '/sys/fs/cgroup/cpu.max': No such file or directory+$ cat /proc/self/cgroup+0::/user.slice/user-1001.slice/session-9028.scope+$ cat /sys/fs/cgroup/user.slice/user-1001.slice/session-9028.scope/cpu.max+max 100000+```++So `readFirstLine(v2)` returns `null`, `readFirstLine(v1)` returns `null` on a+v2-only host, and `probeCpuQuota()` returns `false`. The docblock's justification for+that `false` (`:164-168`) is:++> When neither interface is present there is no bandwidth controller to be limited+> by, which is a real answer — `false` — rather than an absence.++That inference does not hold. Absence at the root path says nothing about the cgroup+the process is in, and the effective limit is the minimum over the whole ancestor+chain, not one file.++**Failure scenario.** A systemd unit with `CPUQuota=50%`, or a container whose limit+is expressed on its own cgroup path rather than at the mount root. `measureHostPressure`+skips the `cpuQuotaInForce` refusal and returns+`percent = loadavg1m / availableParallelism() * 100` — the host's run queue over a CPU+count the process may not have — which is precisely the "confident number where the+metric is degenerate" the module's opening paragraph exists to forbid. The gate then+lets heavy work through on a machine it believes is idle, or closes on a machine that+is not.++**Confidence: high** that the wrong path is read (demonstrated); **high** that a+quota in force is therefore missed; not directly reproduced with a live quota, since+no cgroup on this host carries one.++---++### 10. `readFirstLine` conflates absent with unreadable, and the comment says the caller separates them++`src/core/brain/maintenance/host-pressure.ts:150-158`++```ts+} catch {+ // Absent and unreadable are told apart by the caller, which knows+ // which of the two interfaces it asked for.+ return null;+}+```++The caller does not tell them apart. `probeCpuQuota` treats `null` from v2 as "try+v1" and `null` from v1 as "no interface exists" → `false`. An `EACCES` on an existing+`cpu.max` (a restricted `/sys` mount, a hardened runtime) is therefore reported as+"no quota in force", not as `cpu_quota_unknown`.++The comment is a claim about a behaviour the code does not have — which also leaves+`HOST_PRESSURE_UNMEASURABLE_REASON.cpuQuotaUnknown` reachable only through the+narrow case of an *empty or unparseable but readable* `cpu.max` (see finding 13).++**Confidence: high (read directly).**++---++## PLAUSIBLE — reasoned, not executed against a live trigger++### 11. `declaration_malformed` has no producer++`src/core/search/embeddings/sunset.ts:451` and `:159-164` in+`src/core/brain/doctor/embedding-sunset-check.ts`++```ts+if (declaration !== undefined && declaration.model === model) {+ if (!isValidIsoInstant(declaration.sunsetAt)) {+ return undetermined(model, ...declarationMalformed, reviewedAt);+ }+```++The only producer of `cfg.embeddings` is `parseEmbeddingsBlock`+(`src/core/brain/policy/blocks/embeddings.ts:98-108`), which validates `sunset_at`+with the **same** `isValidIsoInstant` and throws `BrainConfigError` otherwise. A+declaration that reaches the classifier has therefore already been proved+well-formed. The state, its reason member, and the four-sentence message in+`undeterminedMessage` can be produced only by a test calling+`classifyEmbeddingSunset` directly.++This is the defect class the release names: a declared surface with no producer.+`tests/core/architecture/verdict-vocabulary-census.test.ts` does not catch it and+says so explicitly at `:405-410` — it asserts object/list/guard agreement, not+reachability.++**Confidence: high** that the path is dead in production; **medium** on severity —+it is dead code plus an unreachable operator message, not a wrong answer.++### 12. `survey_entry_malformed` likewise++`sunset.ts:488`. Every row of `EMBEDDING_SUNSET_SURVEY` is built from+`OPENAI_FIRST_GENERATION_SHUTDOWN` (a valid literal) or `null`, so no shipped entry+can trip it. Defensible as a guard over shipped data, but its only producer is an+injected survey.++### 13. Four of the five host-pressure refusal reasons have no realistic producer++`src/core/brain/maintenance/host-pressure.ts:83-94`++- `parallelismUnknown` — `availableParallelism()` is specified to return ≥ 1.+- `loadAverageInvalid` — `loadavg()[0]` is a finite non-negative double on every+ platform that implements it.+- `cpuQuotaUnknown` — only an empty/unparseable but readable `cpu.max`; finding 10+ routes the realistic failure (EACCES) to `false` instead.+- `platformBlind` — `win32` only, and `resolveDefaultConfigPath`+ (`src/core/config.ts:127`) refuses win32 by name with the note that "nothing here+ (no adapter, no install document, no path handling) targets Windows".++That leaves `cpuQuotaInForce` as the sole producible refusal, and finding 9 says it+is under-produced. The module's own headline argument — "on the platform Node and+Bun do not implement it for, it returns `[0, 0, 0]`" — is about a platform this build+declines to configure itself on.++**Confidence: medium-high.** Each individually is a reading of a spec or of another+module; together they say the refusal vocabulary is wider than what the probe can+reach.++### 14. A streak refusal is printed and exited as a failure — against this branch's own precedent++`src/cli/brain/verbs/maintenance.ts:265,274`++```ts+ok(` ${t.name}: ${t.ok ? "ok" : `FAILED (${t.error})`} in ${t.duration_ms}ms`);+...+return result.tasks.some((t) => !t.ok) ? 1 : 0;+```++`refuseOnStreak` mints `refused: true` and `failure_streak: N` on+`MaintenanceTaskResult` precisely so a refusal is not read as an attempt, and the+journal row deliberately omits `ok` for the same reason+(`src/core/brain/maintenance/lane.ts`, the `entry:` comment). The human renderer+reads neither field and prints `FAILED`; the exit code is 1, identical to four+genuinely broken passes.++This is the same question `doctorExitCode` answers correctly forty lines of diff+away (`src/cli/main.ts:313-321`): a run that did not attempt gets its own number,+`DOCTOR_EXIT.probeIncomplete = 6`, pinned against `SEARCH_CHECK_EXIT.probeIncomplete`.+The maintenance verb spends no new code and collapses the distinction the unit was+built to draw. `--json` is fine — it emits the whole task record.++**Confidence: high on the behaviour, high on the inconsistency.**++### 15. The streak refusal is a function of a ring buffer, so it clears itself++`src/core/brain/maintenance/journal.ts:119` with `MAINTENANCE_JOURNAL_CAP = 500`++`consecutiveTaskFailures` walks `listJournal(vault)`, which reads only what+`sweepJournal` has kept: the newest 500 lines. The lane writes four task rows per+run plus gate rows, so roughly 125 runs of history are retained. A permanently broken+task that has tripped its limit keeps producing one `refused:streak` row per run —+and those rows, plus the other three tasks' rows, push its three original `run/ok:false`+rows off the tail. Once they roll off, `consecutiveTaskFailures` returns 0 and the+task is retried as if nothing had happened.++Nothing reports that. The refusal the operator was told to clear with `--force`+un-refuses itself on a schedule that depends on how chatty the journal is.++**Confidence: medium-high** — the arithmetic is direct; I did not drive 125 lane runs+to watch it happen.++### 16. The sunset horizon expires negatives whose justification cannot expire++`src/core/search/embeddings/sunset.ts:510-515`++`EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS = 365` is applied to every negative+identically. Two classes of negative are in the table and only one is observational:++- `text-embedding-3-{small,large}`, `text-embedding-ada-002` — sourced as "not listed+ in any deprecation entry … as of the review date". A claim about the world; it+ should expire, and the entry note says so.+- `hashing-ngram-v1` — sourced as "this build ships the local embedder, so this+ project is the only party that could".+- The six `EMBEDDING_MODEL_PRESETS` open-weight checkpoints — sourced as "there is no+ operator of a hosted endpoint with the authority to decommission the model itself".++The last two classes are structural: they are facts about who could announce+anything, not observations that go stale. After `reviewedAt + 365d` (2026-08-15 ++365 = 2027-08-15) they degrade to `undetermined/survey_stale` all the same.++**Failure scenario.** On 2027-08-16 every vault on the default local provider gains a+standing `[UNSURE] embedding-model-sunset-undetermined` finding whose message reads+"the decommission survey covers hashing-ngram-v1 and records no announcement, but it+was reviewed … more than 365 days ago" — about a model this repository ships and is+the only party able to retire. That is a report of ignorance the build does not have.++**Confidence: medium-high.** The mechanism is certain; whether the noise matters is a+judgement, but it is noise-by-construction on the default configuration.++### 17. `ownershipFor` swallows a config-resolution failure without saying so++`src/cli/install/install.ts`, the `try { resolveSearchConfig(...) } catch { }` in+`ownershipFor`++```ts+} catch {+ // A config that will not resolve is not evidence of a cloud account.+}+```++The conservative direction is right; the silence is not. An operator whose search+config throws (an out-of-range `search_chunk_size`, an unparseable key) reads the+unqualified "nothing to cancel" with no indication that the clause was skipped+because the check could not run. The branch's own standard elsewhere — the sunset+check's `pushUncertain` on the same failure (`embedding-sunset-check.ts:198-208`) —+is to emit the "could not be resolved" record. `DataOwnership` has no field for it.++**Confidence: high on behaviour, medium on severity.**++### 18. The third-party clause is decided by provider kind, not by endpoint host++`src/cli/install/install.ts` (`ownershipFor`) and `src/core/install/ownership.ts:284`++```ts+networked = semantic.provider !== "local" && semantic.provider !== "disabled";+```++`EmbeddingProviderName` is `"openai-compat" | "disabled" | "local" | "zeroentropy"`+(`src/core/search/types.ts:931`) — four *transport* kinds, as `sunset.ts:80-84` itself+points out. `openai-compat` pointed at `http://localhost:11434` is the documented way+to run Ollama or LM Studio, and it prints:++> embedding requests send vault text to the endpoint in `embedding_base_url`, which+> is a third-party account this tool neither owns nor cancels.++`semantic.baseUrl` is resolved on the same object and would settle it (a loopback or+private-range host is not a third-party account).++**Confidence: high** that the over-claim fires for a local OpenAI-compatible server.++### 19. Minor: the census walk errors on any dangling symlink++`tests/core/install/ownership.test.ts:183` uses `statSync` inside `walk`, which throws+on a broken link anywhere under `src/`, `hooks/`, `plugins/`. Observed while setting+up the scratch copy (`plugins/codex/skills` is a symlink): three tests error rather+than fail with a finding. `lstatSync`, or a `try`/skip, would keep the census+reporting instead of crashing.++### 20. Minor: the MCP `brain_maintenance` contract is stale about `force`++`src/mcp/brain/admin-tools.ts:472,477`++> "force bypasses the soft gates, never the lease" … `force: "Bypass window and busy+> gates (run)."`++`force` now also bypasses the **pressure** gate and the **streak refusal**, and it is+the only documented route out of a streak refusal (`refuseOnStreak`'s message says+"re-run with `--force`"). An MCP-only operator whose lane has refused a task reads a+schema that does not mention the state they are in.++---++## Answers to the questions asked++**1. Is every claim these surfaces print actually checked?** No — findings 1, 2, 4,+5, 18. Three separate clauses of the ownership statement assert things the composer+had the inputs to measure and did not: where the index lives, which runtimes hold+managed blocks, and whether the configured embedding endpoint is a third party. Two+more (the "nothing to cancel" blanket and the uninstall promise) are checked against+one integration out of three and against a verb that removes two rows out of nine.++I swept for out-of-vault writes myself rather than trusting the enumeration: home-,+XDG-, temp- and `env.home`-rooted writers across `src/`, `hooks/`, `plugins/`, plus+async and non-`Sync` write APIs, plus CWD-rooted writes, plus `bin/`, `install/`,+`openclaw/`, `scripts/`, `templates/`, `skills/`. I found no *currently shipping*+out-of-vault location that the nine rows miss. What I found is that the mechanism+guaranteeing that stays true does not cover the async half of the filesystem API+(finding 3), and that `src/cli/uninstall.ts` — which the statement names — is not in+the swept population at all (it only removes).++**2. Are the verdicts reachable?** The vault-backing vocabulary is fully reachable+(`durable`/`volatile`/`layered` by filesystem, all three undetermined reasons by+platform, path and magic number). The sunset vocabulary has two unreachable reason+members (findings 11, 12); its states are all reachable, and `announced` has a real+shipped producer (the sixteen first-generation OpenAI rows, with a past date, which+is the arm that matters). The host-pressure refusal vocabulary is the weak one:+four of five reasons have no realistic producer (finding 13), and the fifth is+under-produced (finding 9). The census test explicitly does not check reachability,+so nothing in the suite covers any of this.++**3. The sunset check.** A positive does depend on shipped data, and the asymmetry is+right: positives survive a stale survey, negatives expire. The degradation is honest+for the hosted-model negatives and category-wrong for the structural ones (finding+16). `unsurveyed` is genuinely distinguishable from `none_announced` on every surface+I could find: `none_announced` returns silently, `unsurveyed` pushes an uncertain+entry with its own code, and the uncertain stream reaches the human `[UNSURE]` lines+(`src/cli/brain/verbs/doctor.ts:195`), the CLI `--json` payload (`:182`) and the MCP+`vault_health` payload (`src/mcp/brain/health-tools.ts:144`). One residual: a+`none_announced` silence is indistinguishable from the check having thrown, because+`runDoctor` swallows a `failSoft` throw with a bare `catch {}` (`src/core/brain/doctor.ts:278`)+and the sunset check's own `try` covers only `resolveSearchConfig`. That mechanism+predates this branch, but it now guards a new check whose entire point is that+silence must mean something specific.++**4. The pressure gate.** The refusal paths are correct *given the probe*, and the+probe is wrong (findings 9, 10). No path produces a number when the refusals fire;+the problem is that the quota refusal does not fire when it should. The+open-and-said-so behaviour **is** distinguishable in the journal: an unmeasurable+reading writes its own `pressure:unmeasurable` row with `pressure_reason` before the+lane proceeds (`lane.ts`, the two-line comment), and a gate that evaluated and passed+writes nothing at all. Two caveats: with `--force`, `evaluateGates` is never called,+so nothing is journaled about pressure and that is indistinguishable from an+unconfigured gate; and a *measured* passing reading is not journaled either, so the+percentage the gate saw when it let work through is unrecoverable.++**5. The streak.** A refusal cannot deepen the streak it reports —+`consecutiveTaskFailures` `continue`s past any row whose verdict is not `run`, and+`refused:streak` rows carry no `ok`. A transient failure cannot become permanent by+accumulation: a single success breaks the walk. There is no state requiring manual+file surgery — `--force` clears it on both the CLI and the MCP tool. Two things do go+the other way: the refusal is *reported* as a failure (finding 14), and it *clears+itself* as journal rows roll off the 500-line cap (finding 15). Also worth naming:+`--force` is lane-wide, so an operator retrying one wedged task necessarily also+overrides the window, busy and pressure gates for the other three.++**6. Does a broken system now exit 0?** No — I looked hard and could not construct+one. `unknown` is routed to `DOCTOR_EXIT.probeIncomplete = 6`, not to 0, in every+path including the `catch` around `runReadinessProbes` (which falls back to+`failed > 0 ? 1 : 6`), and the `--json` `ok` field is now derived from the exit code+rather than from `failed` alone, so it went from too permissive to correct. The+reclassification is strictly stricter than what shipped before: an `unknown` probe+used to exit 0. `runReadinessProbes` is the only consumer of the report and+`cmdDoctor` is its only caller. The one asymmetry worth noting is that an+unresolvable search config surfaces as `fail` from `probeEmbeddingProvider` (which+catches) and as `unknown` from `probeLlmKey` (which does not) — the same condition+reported two ways — but `fail` wins the precedence, so the exit code is right.++**7. Exit codes.** The doctor's new code is consistent and well-pinned:+`DOCTOR_EXIT.probeIncomplete` is asserted equal to `SEARCH_CHECK_EXIT.probeIncomplete`+rather than to `6` (`tests/cli/doctor-exit.test.ts:83`), and the end-to-end test+asserts `not.toBe(ok)` and `not.toBe(failed)` alongside it, so a table collapse fails+loudly. That is the standard the rest of the branch should have been held to, and the+maintenance verb was not (finding 14).++---++## Checked and found sound++An absent finding here is a positive result, not an omission.++- **The unknown-vs-fail reclassification is load-bearing.** Mutated+ `src/core/doctor-readiness.ts:580` back to `READINESS_STATUS.fail` in a scratch copy:+ `tests/core/doctor-readiness.test.ts` went 21 pass / 3 fail, including "a probe that+ throws claims nothing about the surface it could not read". The test cannot pass+ against the old behaviour.+- **The quota refusal is load-bearing.** Deleted the `cpuQuotaInForce` arm from+ `measureHostPressure` in a scratch copy: `tests/core/brain/maintenance/` went+ 37 pass / 1 fail on "a CPU bandwidth quota makes the run queue the wrong machine's".+- **The out-of-vault census does catch the writers it can see.** Control mutation in+ finding 3: a synchronous home-rooted writer is named in the failure message.+- **The closed vocabularies are genuinely closed at the type level.** I suspected+ `Object.freeze({...})` without `as const` in `host-pressure.ts:58,83` and+ `journal.ts:36` had widened the members to `string`, breaking both the guards' return+ types and the discrimination of `HostPressureReading`. It has not: `tsc` rejects+ `const x: MaintenanceVerdict = "totally-bogus-verdict"` and `HostPressureState =+ "totally-bogus-state"` exactly as it rejects the `as const` control+ (`VaultBackingState`), and narrowing to `.reason` inside+ `if (r.state === HOST_PRESSURE.unmeasurable)` compiles. `Object.freeze`'s+ primitive-constrained overload preserves the literals. The only residual is+ cosmetic: `HOST_PRESSURE_STATES` and `MAINTENANCE_VERDICTS` are annotated+ `ReadonlyArray<string>` where their siblings use the member type, so a missing member+ is caught only by the runtime census, not by the compiler.+- **`probeVaultBacking` refuses in the right direction.** Unlisted magic numbers are+ `fs_type_unknown`, not "assumed durable"; the platform gate is by allow-list;+ network filesystems are `durable` with a stated argument; the probe never throws;+ and `filesystem`/`reason` are exclusive by construction. `survivalLine` is+ exhaustive with no default arm, so a fifth state fails the build.+- **The declaration layer is both-or-neither, and enforced at parse time.**+ `parseEmbeddingsBlock` throws on half a declaration rather than dropping it+ (`policy/blocks/embeddings.ts:117`), which is what makes finding 11 a dead branch+ rather than a silent no-op.+- **The sunset disagreement is carried, not erased.** `overrode_survey` /+ `survey_sunset_at` reach the message via `provenance()`, so a declaration that+ contradicts the table names both records.+- **The uncertain stream reaches every reader.** Deduplicated per `(code, path)`,+ capped per code, and serialised into the human `[UNSURE]` lines, the CLI `--json`+ payload and the MCP payload. `unsurveyed` is visible everywhere.+- **The `disabled` codegraph arm has a real producer for all three callers.**+ `codegraphCheckDisabled` resolves the env var / config key when no explicit option+ is passed, and `tests/core/doctor-codegraph-switch.test.ts:91` asserts the *unswitched*+ path actually spawns — so the "the switch stops the spawn" tests are not vacuous.+ The fallback on an unreadable config is the value that changes nothing (check runs),+ not an invented "disabled".+- **The install vault chain is now single-source.** `resolveInstallVault` delegates to+ `resolveVault` and `loadPayload`'s second read of the `vault` config key is gone, so+ the installer and `o2b status` cannot disagree. `tests/cli/install-vault-resolution.test.ts`+ pins the precedence against `resolveVault`'s order rather than restating it.+- **The install `--json` envelope.** One exit (`installJson`), version prepended+ centrally, `data_ownership` spelled once as a named constant, and additive on the+ apply payload rather than re-nested. The ownership close is correctly gated on+ `results.some(r => r.status === "ok")` for `--check`, so a `not-installed` run does+ not congratulate anyone.+- **The onboarding checklist and the install close read one record.** `data_ownership`+ is built once in `buildOnboardingChecklist` from the same `networked` value the+ notices use, so the two surfaces cannot gain fields separately.+- **The streak walk.** Verified by reading: refusal rows are skipped, lease and gate+ rows are skipped, `ok !== false` breaks, and a row that ran with no recorded outcome+ breaks — all four match the docblock.+- **Journal rows for the fourth gate.** `pressure:unmeasurable` is emitted on its own+ line *before* the decision row and never instead of it; `pressure_percent` rides only+ on a measured `skipped:pressure` row. The two facts are never collapsed.+- **`maintenance:` block bounds.** `host_pressure_percent` has no default (an+ unconfigured gate never fires), `failure_streak_limit` defaults to 3 with a stated+ argument, and both are hard errors out of range rather than clamped.+- **Suite state.** With a clean `HOME`, the thirteen test files covering this scope ran+ 246 pass / 1 fail at `751fbb17`, the single failure being the 5 s partner timeout of+ finding 8; `ceb8b1e3` removes that cost from the suite. Findings 7 and 8's test-side+ symptom are therefore closed; finding 8's production half is not.diff --git a/docs/brainstorm/nothing-runs-unwatched/review/cross-cutting.md b/docs/brainstorm/nothing-runs-unwatched/review/cross-cutting.mdnew file mode 100644index 00000000..f275d79c--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/review/cross-cutting.md@@ -0,0 +1,805 @@+# Cross-cutting review — the seams, and the release's argument turned on itself++**Branch:** `feat/nothing-runs-unwatched` · **Base:** `main` · 61 commits, 173 files, +19585/−761+**Scope:** the seams between the four other reviewers — declared-surface reachability, damage from nine+concurrent agents, import cycles and layering, the commit record, operator-surface consistency.+**Not covered here** (other reviewers): the progress spine's own correctness, cancellation semantics,+the honesty of individual claims, locking and race analysis, test/doc completeness per unit.++**Anchors.** Every `path:LINE` below is against branch HEAD `751fbb17`, verified after the fact.+One caveat: while this review was in progress, `src/core/brain/progress.ts` acquired an **uncommitted+working-tree modification** made by something other than me — it adds a `PROGRESS_REASON.failed`+member, a `terminated` one-ending guard on the counter, a positive-integer check on `advance`, and+makes `withProgress`/`withProgressAsync` always emit a terminator. I left it alone rather than revert+another worker's edit. It shifts `src/core/brain/progress.ts` lines after `:117` by +13 and after+`:216` by a further +13; the findings below are unaffected by it, and the new `failed` member **is**+reachable (any throw inside `withProgress` at `bridge-discovery.ts:104`, `communities.ts:95`,+`indexer.ts:327`, `vector-backfill.ts:104`). Worth noting only because it is the same shared-tree+concurrency this review is about, still running.++The branch's thesis: *a system that does long work silently cannot be trusted, and a declared surface+with no producer is a defect.* It caught itself four times during construction. Applying the same+test to the release itself finds **six more declared surfaces with no producer**, five of them added+by this branch, plus one documented claim that is false.++The pattern behind almost all of them is the same, and it is the pattern nine concurrent agents+produce: a mechanism is built, a census or a doc is written asserting it is universal, and the census+checks the half the author could see. `progress-census.test.ts` checks that interfaces *declare* a+sink and never that a caller *passes* one. `docs/mcp.md` asserts four tools are bounded and the agent+who wrote it had edited three of them. `verdict-vocabulary-census.test.ts` checks that a vocabulary's+three parts agree and explicitly waives whether any member is reachable.++| # | finding | severity |+|---|---|---|+| F1 | `docs/mcp.md:116` claims `brain_dream` runs under a deadline; it has none | **high** |+| F2 | The whole `--progress` refusal path is unreachable in every shipped invocation | **high** |+| F3 | `refused` documented as a CLI stream kind that cannot be emitted there | medium |+| F4 | `dream stage\|validate\|apply --progress` parsed, threaded, and dropped in silence | **high** |+| F5 | `vector-backfill` grew the whole spine with no flag, no caller, no cancel | **high** |+| F6 | Three shapes for "the sink threw"; four of six emitters have none | medium |+| F7 | `maintenance run --json` omits `interrupted` where five siblings carry it | medium |+| F8 | `--progress` discoverable on 2 of 7 verbs; invisible on `brain dream` | medium |+| F9 | `completed` means "finished" in four emitters and "started" in the index run | medium |+| F10 | Two shapes for a new policy block; one docblock now documents the wrong symbol | low |+| F11 | A ninth lock-retry ladder beside a generic helper that already existed | low |+| F12 | Five new core→`progress.ts` edges the import-cycle ratchet cannot see | low (latent) |+| F13 | Half-applied seams; a hand-rolled copy of a shared test helper | low |+| F14 | Orphan exports; one vocabulary missing from the census that claims completeness | low |+| F15 | Two spellings for "could not determine" in one release | low |+| F16 | Five new doctor codes and one new config block documented nowhere | low |++---++## Findings++### F1 — `docs/mcp.md:116` says `brain_dream` runs under a deadline. It runs under none. CONFIRMED++`docs/mcp.md:109-118`, added by this branch in commit `e44ee1ae` ("feat(mcp): **the four long tools+are bounded** and observed"), states:++> The MCP surface that can genuinely run for minutes is `brain_dream`, `brain_bridges`,+> `brain_clusters` and `brain_maintenance`. … **Every one of those four also runs under a cooperative+> deadline** resolved from `safeguard_timeout_<operation>_seconds`, then `safeguard_timeout_seconds`,+> then the built-in default.++`grep -c 'safeguard\|Safeguard' src/mcp/brain/feedback-tools.ts` returns **0**. The tool's two `dream()`+call sites — `src/mcp/brain/feedback-tools.ts:469` (the count-guard preview) and+`src/mcp/brain/feedback-tools.ts:491` (the real pass) — pass `dryRun`, `now`, `agentName`, `gates` and+`onProgress`. No `safeguard`. No `signal`.++Commit `e44ee1ae` touched `src/mcp/brain/admin-tools.ts` and `src/mcp/brain/knowledge-tools.ts` and+added safeguards to `brain_bridges` (`knowledge-tools.ts:199`) and `brain_clusters`+(`knowledge-tools.ts:282`). `brain_maintenance` already had one (`admin-tools.ts:300`).+`src/mcp/brain/feedback-tools.ts` was never in that commit — it had been edited by a *different* agent+three commits earlier (`836bd626`, the progress token) to accept `onProgress`. One agent wired progress+into `brain_dream`; another agent bounded three tools and wrote a doc claiming four.++**Failure scenario.** An MCP client calls `brain_dream` with `action: "run"` on a large vault. The pass+walks the whole Brain tree synchronously. There is no deadline to trip and no signal to abort, and+because `dream()` is synchronous the server's event loop is blocked for its entire duration — so the+client cannot even time out and reissue. The operator's `safeguard_timeout_dream_seconds` setting,+which the doc tells them governs this call, does nothing.++`tests/mcp/long-running-tools.test.ts` — the file whose header says "a deadline and a progress tick sit+at the same … safeguard checkpoints" — asserts the deadline for exactly two tools:+`brain_bridges` (`:122`) and `brain_clusters` (`:141`). Nothing asserts it for `brain_dream` or+`brain_maintenance`. The claim is a comment, and the test that would have caught it was not written.++Same class, same file: `brain_brief view=operator` (`src/mcp/brain/brief-tools.ts:366-369`) runs a+full dry-run `dream()` with `onProgress` and **no** safeguard. It is a fifth progress-emitting MCP+tool, absent from the doc's list of four, unbounded and uncancellable.++And its CLI twin was not touched at all: `src/cli/brain/verbs/summary.ts:40` calls+`dream(vault, { dryRun: true })` — no sink, no safeguard, no `onInterrupt()`, no `--progress` flag.+One agent fixed the MCP copy of this call (and wrote a fresh comment there calling it "the slow half+of an operator summary on a large vault"); the CLI copy of the identical call is unchanged.+`src/core/brain/review-candidates.ts:102` is a third instance of the same dry-run `dream()` with none+of the three.++Two agents also invented two safeguard factories for the same job rather than sharing one:+`graphSafeguard` (`src/mcp/brain/knowledge-tools.ts:102-110`) and `laneSafeguard`+(`src/mcp/brain/admin-tools.ts:297-303`).++---++### F2 — The entire `--progress` refusal path is unreachable in every shipped invocation. CONFIRMED++`src/cli/progress-rail.ts:91-94`:++```ts+export function progressIsLegal(stream: ProgressStream): boolean {+ if (!stream.jsonRequested) return true;+ return ownsInternalJson(stream.command, stream.argv);+}+```++`ownsInternalJson` (`src/cli/json-helpers.ts:68-73`) returns `true` immediately when+`COMMANDS_WITH_INTERNAL_JSON.has(command)`. That set (`src/cli/json-helpers.ts:45-58`) contains+`"brain"` and `"search"`.++Every production call site of `attachProgress` passes one of those two:++| call site | `command` |+|---|---|+| `src/cli/brain/verbs/dream.ts:407` | `"brain"` |+| `src/cli/brain/verbs/bridges.ts:160` | `"brain"` |+| `src/cli/brain/verbs/clusters.ts:267` | `"brain"` |+| `src/cli/brain/verbs/architect.ts:44` | `"brain"` |+| `src/cli/brain/verbs/maintenance.ts:150` | `"brain"` |+| `src/cli/search/verbs/indexing.ts:99-103` (index and reindex) | `"search"` |++So `progressIsLegal` is `() => true` for every input the shipped CLI can construct. Consequently:++- `PROGRESS_OUTCOME.suppressedBufferedStream` (`src/cli/progress-rail.ts:62`) has no producer.+- `PROGRESS_REASON.streamBuffered` (`src/core/brain/progress.ts:117`) has no producer.+- `ProgressAttachment.reason` (`src/cli/progress-rail.ts:124`) is never set.+- `reportProgressRefusal` (`src/cli/progress-rail.ts:178-186`) is a no-op at all six call sites; the+ line `progress: not emitted (<reason>)` (`src/cli/progress-rail.ts:185`) can never be printed.+- The `argv` field of `ProgressStream` (`src/cli/progress-rail.ts:45`) is decorative — `ownsInternalJson`+ short-circuits on `command` before reading it.+- `docs/cli-reference.md:724` promises "when a stream cannot carry it the verb says+ `progress: not emitted (<reason>)`". No operator will ever see that string.++The only exercise of the branch is `tests/cli/progress-rail.test.ts:50-59`, which constructs a stream+with `command: "cron-recipe"` — **not a top-level command**; `cron-recipe` is a *module* name+(`src/cli/cron-recipe.ts`). `src/cli/main.ts` dispatches no such command. The test passes because the+input is fabricated, so it cannot fail for any reason an operator can produce.++This is the branch's own rule ("no declared surfaces with no producer") violated by the branch's own+edge module, with 40 lines of docblock (`src/cli/progress-rail.ts:14-28`, `:78-89`) and a dedicated+test arguing for a branch nothing enters. **Defect**, not an honest rare state: the rail was written+against a hazard (`withJsonFallback` buffering stderr) that structurally cannot reach it.++---++### F3 — `PROGRESS_KIND.refused` is documented as a CLI stream kind and is never emitted there. CONFIRMED++`docs/cli-reference.md:724` states the NDJSON `kind` "is one of the schema's fixed set (`started`,+`advanced`, `finished`, `stopped`, **`refused`**)".++`progressCounter` (`src/core/brain/progress.ts:210-265`) has exactly four emit paths — `start` →+`started`, `advance` → `advanced`, `finish` → `finished`, `stop` → `stopped`. There is no `refuse()`.+The only `refused` value in the tree is `ProgressRefusal.kind` (`src/mcp/progress.ts:161`), a+**different shape** on a **different channel** (`result._meta` on an MCP response), never a+`ProgressEvent` and never on stderr.++A caller who writes a parser against the documented set will branch on a `kind` the CLI cannot produce.+Combined with F2, two of the five documented kinds are unreachable on the surface the sentence+describes.++The vocabulary member itself is defensible — the census test's own rationale (`tests/core/architecture/+verdict-vocabulary-census.test.ts:404-410`) accepts members with no producer so a guard can read a+future release's value. The **documentation** is the defect.++---++### F4 — `o2b brain dream stage|validate|apply --progress` parses the flag and drops it silently. CONFIRMED++`src/core/brain/dream-stage.ts:107` declares `onProgress`, with a paragraph of rationale ("a caller who+asked to watch a staged pass watches the same five stages"), and threads it to `dream()` at+`:252`, `:368` and `:407`.++Nothing passes it.++- CLI: `src/cli/brain/verbs/dream.ts:109` parses `progress`; the attachment is built at `:406-409`,+ which is **inside the `run` path**. The staged actions run earlier (`:249-253` for `stage`,+ `:270-274` for `validate`/`apply`) and construct their options as `{ now, safeguard, agentName }`.+- MCP: `src/mcp/brain/feedback-tools.ts:414` builds `stageOpts = { now, ...agentName }` and calls+ `stageDream(ctx.vault, stageOpts)` at `:417`, discarding the `onProgress` the handler received at+ `:343`.++**Failure scenario.** An agent driving `brain_dream` with `action: "stage"` over stdio sends a+`progressToken`. The server reads it (`src/mcp/server.ts:367`), builds a live sink, does **not** issue a+refusal (because `onProgress !== undefined`, `src/mcp/server.ts:372`), runs a full dry-run consolidation+pass, and emits zero notifications. The client is told nothing and sees nothing — which the module+header of `src/mcp/progress.ts:1-33` names as precisely the failure this unit exists to remove+("accepted by the wire and then discarded without a word").++Same shape on the CLI: `o2b brain maintenance status --progress` parses the flag+(`src/cli/brain/verbs/maintenance.ts:68`) and returns at `:82-102` before any attachment is made.++---++### F5 — `o2b search vector-backfill` grew the full spine on this branch and has no flag to reach it. CONFIRMED++Commit `c82c4e53` added to `src/core/search/vector-backfill.ts`: `onProgress` (`:63`), a run-owning+counter (`:98-104`), a stage (`:106`) and `withProgressAsync`. `signal` (`:57`) was already declared.++`src/cli/search/verbs/vector-backfill.ts:96-99` calls `planVectorBackfill(cfg, { apply, forceCost })`.+No `onProgress`, no `signal`, no `safeguard`, no `onInterrupt()`. The verb file was not touched by this+branch. `src/cli/command-manifest.ts:579` declares the command with no `progress` flag.++It is the third embedding-loop builder in the CLI — the same loop `search index` and `search reindex`+now report and can be stopped — and it is the only one left both unwatchable and un-interruptible.+`VectorBackfillOptions.onProgress` is a declared surface with **no producer anywhere in `src/`**.++This is exactly the gap `tests/core/architecture/progress-census.test.ts` was built to close, and it+does not close it: the census (`:116-135`) asserts that an interface *declaring* `safeguard?:` also+*declares* `onProgress?:`. It never asserts that any caller passes either. An interface can satisfy the+census and emit nothing to nobody, which is what happened here.++**The census's blind spot is the release's own argument, inverted.** The design doc's rule is+"a mechanism which must be called by hand is a mechanism that will be missed, and the answer is+declaration plus a census." The census that shipped checks the declaration half only. Every one of+F4, F5 and the row below is invisible to it.++The same blind spot leaves seven of the nine index-build call sites unwired. Only+`src/cli/search/verbs/indexing.ts:185` and `:259` (and the maintenance lanes at+`src/cli/brain/verbs/maintenance.ts:186` / `src/mcp/brain/admin-tools.ts:324`, which pass a safeguard+and a sink but nothing to `onFile`) supply the seam. These pass none of `safeguard`, `signal` or+`onProgress`:++| call site | what it is |+|---|---|+| `src/core/maintenance/ensure-current.ts:211` | `await reindexVault(config)` — the **foreground** self-heal, a full rebuild |+| `src/core/search/pipeline/store-open.ts:50` | `await reindexVault(config)` — auto-rebuild on store open |+| `src/cli/search/verbs/query.ts:96` | `await indexVault(cfg)` — auto-index before a query |+| `src/core/search/link-ratchet.ts:283` | `await indexVault(config, { force: true })` |+| `src/cli/search/verbs/watch.ts:59` | `indexVault(cfg, {…})` — no `onProgress` |++The foreground self-heal is the sharpest of these: `ensureVaultCurrent` in non-background mode runs an+unbounded, unobservable, uninterruptible full rebuild on a path that F13's own sibling+(`startSelfHealReindex`) took care to instrument in the background case.++**A latent non-terminating stream, of exactly the shape commit `751fbb17` claims to have removed.**+`scanProject` (`src/core/brain/architect/scan.ts:347-360`) builds its own counter, calls+`progress.start(ARCHITECT_STAGE.walk)` at `:351`, and **returns without `finish()` or `stop()`**. It+does not use `withProgress`, the helper written in that very commit for that very rule. It is safe+today only because its sole in-tree caller, `generateArchDocs` (`generate.ts:313`), owns a second+counter that terminates — but `ScanProjectOptions` is exported and advertises `onProgress`+(`scan.ts:144`), and a successful standalone `scanProject(root, { onProgress })` emits `started`,+`advanced`… and then silence, which is the shape of a completed, a crashed and a hung run at once.+The abort path *is* covered (`walkTree`, `scan.ts:214-228`). Latent, not live — but the exemption is+undocumented, so the next caller inherits it silently.++---++### F6 — Three shapes for "the progress sink threw", and four of the six emitters have none. CONFIRMED++`src/core/brain/progress.ts:186-199` states the rule: "a broken edge stream — a closed pipe, a renderer+defect — must not abort a consolidation pass that is otherwise succeeding … With no reporter supplied+the throw propagates."++Three independent implementations of that one rule now exist:++1. **`progressCounter({ onSinkError })`** — `src/core/brain/progress.ts:199`. Used only by `dream`+ (`src/core/brain/dream.ts:162`), which turns the fault into a `DreamWarning` with code+ `progress-sink-failed` (`src/core/brain/dream.ts:125`, `:136-143`).+2. **`guardedSink()`** — `src/core/brain/architect/generate.ts:262-277`, a hand-rolled second copy of+ the same detach-and-report logic, whose own docblock (`:252-260`) explains it exists because a run+ spans two counters. It surfaces as `GenerateArchDocsResult.progressFault`+ (`src/core/brain/architect/generate.ts:357`), the `progress_fault` JSON key+ (`src/cli/brain/verbs/architect.ts:71`) and a third refusal wording,+ `progress: observer failed (…)` (`src/cli/brain/verbs/architect.ts:84`).+3. **Nothing at all** — `src/core/brain/link-graph/bridge-discovery.ts:102`,+ `src/core/brain/link-graph/communities.ts:88`, `src/core/search/indexer.ts:325`,+ `src/core/search/vector-backfill.ts:102`. These construct `progressCounter(op, sink)` with no+ options object, so per the spine's own docblock **the throw propagates and kills the operation**.++**Failure scenario (PLAUSIBLE, transport-dependent).** Over MCP stdio the sink is+`(event) => send(progressNotification(token, event))` (`src/mcp/progress.ts:154`), and `send` writes to+`process.stdout` (`src/mcp/stdio.ts:47`). If that write throws synchronously — a destroyed stream after+a client disconnect — `brain_dream` reports the fault on its summary and completes, while+`brain_bridges` and `brain_clusters` abort the tool call and return an error envelope. Same client,+same pipe, two different outcomes, decided by which agent wrote which module.++Two consequences worth naming separately:++- The wordings do not agree. `progress: not emitted (<reason>)` (unreachable, F2),+ `progress: observer failed (<message>)` (architect only), and a `DreamWarning` in a JSON payload+ (dream only) are three answers to one question on one CLI. Commit `e7b047e8` is titled+ "refactor(cli): **one wording** for a refused rail and a stopped run"; it unified two of them and left+ the third.+- `progress_fault` is a declared `--json` field with, in practice, no reachable producer: the only+ production sink (`src/cli/progress-rail.ts:146-155`) throws only on an unknown event `kind`, which+ cannot occur because the producer is in the same process. Listed as such in the table below.++---++### F7 — `o2b brain maintenance run --json` is the one interrupted verb whose payload omits `interrupted`. CONFIRMED++Five verbs route a stop through `reportInterrupted` (`src/cli/interrupt.ts:121-125`), which writes+`{ ok: false, interrupted: true, message }`:+`src/cli/search/verbs/indexing.ts:204` and `:288`, `src/cli/brain/verbs/bridges.ts:217`,+`src/cli/brain/verbs/clusters.ts:352`, `src/cli/brain/verbs/architect.ts:90`,+`src/cli/brain/verbs/dream.ts:425`.++The maintenance verb does not. It writes its normal payload at `src/cli/brain/verbs/maintenance.ts:262`+(`okJson({ verdict: result.verdict, tasks: result.tasks })`) and then returns the interrupt code at+`:274` with no field explaining it.++**Failure scenario.** A cron wrapper runs `o2b brain maintenance run --json`, an operator sends SIGTERM,+the wrapper receives exit 143 and a document that says `verdict: "run"` with four tasks marked+`ok: false`. It cannot distinguish "the operator stopped this lane" from "all four passes are broken" —+which the code comment at `:270-273` says is exactly the distinction it is preserving. The exit code+carries it; the document does not.++Related: `src/cli/brain/verbs/dream.ts:342-347` open-codes a sixth copy of `reportInterrupted`'s body+for the staged path instead of calling the helper introduced two commits earlier for that purpose.++---++### F8 — `--progress` is discoverable on 2 of 7 verbs. CONFIRMED++Commit `6d6ea805` is titled "fix(cli): the index builders **advertise the flag they now parse**" and+adds `flag("progress", "boolean")` to `src/cli/command-manifest.ts:538` (index) and `:548` (reindex).+The five brain verbs that also parse it got nothing:++| verb | parses | usage const | `command-manifest.ts` | per-verb doc line |+|---|---|---|---|---|+| `search index` | `indexing.ts:175` | n/a | yes `:538` | `cli-reference.md:848` |+| `search reindex` | `indexing.ts:233` | n/a | yes `:548` | prose only |+| `brain architect` | `architect.ts:32` | yes `:27` | **no** (`:292`, no flags) | `cli-reference.md:273` |+| `brain bridges` | `bridges.ts:56` | yes `:48` | **no** (`:278`) | `cli-reference.md:335` |+| `brain clusters` | `clusters.ts:131` | yes `:54` | **no** (`:279`) | `cli-reference.md:336` |+| `brain maintenance` | `maintenance.ts:68` | yes `:52` | **no** (`:189`) | `cli-reference.md:325` |+| `brain dream` | `dream.ts:109` | **no** (`:61-65`) | **no** (`:121-126`, which *does* carry a flags array with `step` and `gate`) | **none** |++`o2b brain dream` — the verb the design doc opens with ("`o2b brain dream` prints its first character+after it has finished") — is the one verb where `--progress` appears in no usage string, no manifest+entry and no per-verb documentation line. It exists only in the prose paragraph at+`docs/cli-reference.md:724`, which says "the same verbs" without naming them. Tab-completion and+`o2b help --json` do not offer it anywhere under `brain`.++The manifest is admittedly sparse for brain verbs generally, so this is drift *introduced by this+release*, not a pre-existing hole: one agent fixed the discoverability gap for its two verbs and named+the fix in a commit subject; five sibling verbs shipped the same flag without it.++---++### F9 — `completed` means "finished" in four emitters and "started" in the index run. CONFIRMED++`ProgressEvent.completed` is declared as "Units **finished** in this stage so far"+(`src/core/brain/progress.ts:149`).++- `src/core/brain/architect/generate.ts:243` advances **after** `atomicWriteFileSync`. Honest.+- `src/core/brain/dream.ts:209`, `:363`, `:406`, `:414` advance after each phase. Honest.+- `src/core/search/indexer.ts:359` advances at the **top** of the per-file loop, before the file is read+ or upserted.+- `src/core/search/indexer.ts:943` advances by `batch.length` **before** `provider.embed(texts)` at+ `:946` — the network call the whole phase is waiting on.++**Failure scenario.** `o2b search index --embeddings --progress` on 4 000 pending chunks with a+super-batch of 512. The stream reaches `{"stage":"embed","completed":4000,"total":4000}` while the last+512 vectors are still in flight at the provider. If that call then fails, the operator has been told+100 % of the embedding phase completed and then watched the command exit non-zero. An agent using the+counter to decide whether a retry is needed reads the wrong number.++Adjacent, same class:++- `src/core/brain/dream.ts:211` starts stage `plan` with `total = scan.preferences.length` and **never+ advances it** — there is no `progress.advance(DREAM_STAGE.plan)` anywhere. The planning phase emits+ one event, `0 of N`, then jumps to `apply`. A declared denominator with no producer of increments.+- `src/core/brain/link-graph/bridge-discovery.ts:103` and `:156` both call+ `progress.start(BRIDGE_STAGE)` for the **same stage name** — the second with a total. `start` resets+ `completed` and re-emits `started` (`src/core/brain/progress.ts:241-247`), so a bridges run emits the+ same stage's `started` twice and a client tracking stage transitions resets its bar mid-run. No other+ emitter does this.+- `src/core/brain/link-graph/communities.ts:94` passes `maxIterations` as `total`, but label+ propagation converges early, so the run habitually `finished`es at `completed < total`. `total` is a+ ceiling there and a denominator everywhere else, against the field's own declaration.++`tests/core/architecture/progress-census.test.ts` checks that stage *identifiers* are not prose. It+checks nothing about counter semantics, which is why all four of these coexist.++---++### F10 — Two shapes for a new policy block, and one docblock now documents the wrong symbol. CONFIRMED++Two `_brain.yaml` blocks were added by two agents in two commits (`0196dc28` maintenance, `1c89bf04`+embeddings). They are wired differently:++| | `maintenance` | `embeddings` |+|---|---|---|+| parser registered in `policy/validate.ts` | `:106` | `:113` |+| loader in `policy/load.ts` | `loadMaintenanceConfigSafe` `:272` | **none** |+| re-exported from the `policy.ts` barrel | `:59`, `:102-110` | **none** |+| consumer reaches it via | the barrel / `policy/load.ts` (`maintenance/lane.ts:37`) | a **direct** `policy/blocks/` import (`src/core/brain/doctor/embedding-sunset-check.ts:61`) |++`src/core/brain/doctor/embedding-sunset-check.ts:61` is the **only** module outside+`src/core/brain/policy/` in the entire tree that imports from `policy/blocks/`. Every other block+— active, lessons, guardrails, integrity, health, temporal, link-graph, notes, sessions, maintenance —+is reached through `src/core/brain/policy.ts`. Nothing enforces the barrel, so this is convention drift+rather than a break, but it is a second shape for one mechanism inside one release.++**Partial-merge artefact, same file.** `src/core/brain/policy/load.ts:248-260` is a docblock that names+`active.most_applied`, `BRAIN_MOST_APPLIED_DEFAULTS`, "the digest" and "the section is the operator's+own list of the rules they lean on". It is now attached to `loadMaintenanceConfigSafe` (`:272`), which+has its own docblock at `:261-271`. `loadActiveMostAppliedSafe` (`:277`) — the symbol the first+docblock was written for — is now undocumented. One agent inserted a declaration between an existing+comment and the symbol it described. Harmless at runtime; it is the signature the brief asked me to+look for.++---++### F11 — A ninth lock-retry ladder, added beside a generic helper that already existed. CONFIRMED (observational)++`acquireLockSyncWithRetry` (`src/core/brain/sync-lockfile.ts:159-175`) is new: a **wall-clock** budget+(5 s) with a **jittered** sleep, and a 40-line docblock arguing from first principles why an attempt+count is the wrong quantity. Adopted by `git/store.ts:193`, `ingest/checkpoint.ts:188`,+`ingest/content-manifest.ts:237`, `architect/generate.ts:340`.++The tree already contained eight, all still in place and none touched or exempted:++| module | shape | backend |+|---|---|---|+| **`src/core/reliability/lock.ts:22` `withFileLock`** | the **generic** helper, `retries ?? 3` | `proper-lockfile` |+| `src/core/search/store/writer-lock.ts:37` | 10 attempts × fixed 50 ms | `proper-lockfile` |+| `src/core/search/store/writer-lock.ts:88` | `retries: {3, factor 1}` + heartbeat | `proper-lockfile` |+| `src/core/brain/log.ts:238` | 10 × 50 ms | `proper-lockfile` |+| `src/core/brain/secrets/store.ts:90` | 20 attempts | `proper-lockfile` |+| `src/core/brain/portability/profiles.ts:160` | fixed attempts × fixed ms | `proper-lockfile` |+| `src/core/config.ts:449`, `:532` | two inline `for` loops in one file | `proper-lockfile` |+| `src/core/brain/inline-rewrite.ts:56` | `retries: {30, factor 1.2, 30–500 ms}` | `proper-lockfile` |++The new one is the only wall-clock/jittered member and the only one not built on `proper-lockfile`.+Its three new consumers — `git/store.ts`, `ingest/checkpoint.ts`, `ingest/content-manifest.ts` — are+read-modify-write on JSON/JSONL files, which is exactly `withFileLock`'s stated use case+(already used by `src/core/brain/schema-mutate.ts:197` and `src/core/brain/health-baseline.ts:58`).++This is not a bug — the mkdir-based `acquireLockSync` is the primitive the rest of `Brain/` uses, so+the new helper is consistent with its neighbours. It is the branch adding a ninth answer to a question+it also declares it has settled, without mentioning the generic answer already in the tree.++Worth flagging for the locking reviewer rather than deciding here: `Bun.sleepSync` blocks the thread,+so an ingest fold contending inside the long-lived MCP server can stall the event loop for up to five+seconds.++---++### F12 — Five new core→`progress.ts` edges are invisible to the import-cycle ratchet. CONFIRMED (latent)++`tests/core/architecture/import-cycles.test.ts:24-28` states the project's rule deliberately:+`import type … from "…"` **is** an edge, "the `type` keyword is one word, dropping it is invisible in+review". `:35` excludes `import("…")` in a type position, because it "pulls in no module".++Five of the six new progress-emitting modules reference the sink through the *inline* form rather than a+top-level `import type`:++| site | form | has a static import too? |+|---|---|---|+| `src/core/brain/dream-types.ts:219` | `import("./progress.ts").ProgressSink` | **no** — untracked edge |+| `src/core/search/indexer.ts:140` | inline | yes (`:67-72`) |+| `src/core/search/indexer.ts:855` (`EmbeddingPhaseOptions.progress`) | inline | yes |+| `src/core/search/vector-backfill.ts:63` | inline | yes (`:43`) |+| `src/core/brain/link-graph/communities.ts:76` | inline | yes (`:33`) |+| `src/core/brain/link-graph/bridge-discovery.ts:83` | inline | yes |+| `src/core/brain/architect/{scan,generate}.ts` | top-level `import type` | — |++No cycle exists today: `progress.ts` imports only `safeguard.ts`. But `dream-types.ts` now carries a+real type dependency on `progress.ts` that the ratchet does not count, and the branch has established+the inline form as the house style for this type in four modules. A future edge added the same way+closes a loop the ratchet stays green on. The two idioms in one release are also plain drift — two+agents, two habits.++**I ran the repository's own guards and both pass:** `tests/core/architecture/import-cycles.test.ts`+and `tests/core/layering.test.ts`, 6 tests, 0 fail. No new `process.exit` / `process.stdout.write` /+`console.log` in `src/core`; no `src/core` → `src/cli` or `src/mcp` import added.++---++### F13 — Half-applied seams and one hand-rolled copy of a shared test helper. CONFIRMED (low)++Three smaller artefacts of the same concurrency, each a mechanism applied to some of its sites:++**`dispatchByView` gained a fourth parameter; one of its two call sites passes it.**+`src/mcp/brain/shared.ts:194` now takes `onProgress?`, with a docblock (`:170-178`) stating that "a+dispatcher that silently swallowed it would make a view which DOES run long … look like a tool that+emits no progress rather than one whose progress was discarded in transit". `src/mcp/brain/brief-tools.ts:495`+forwards it. `src/mcp/brain/analytics-tools.ts:249` does not — its handler+(`:242-244`) never took the parameter. Defensible today (no `brain_analytics` view runs long), but it+is the exact behaviour the new docblock names as the thing to avoid, in the other file that uses the+function it was written for.++**Doctor codes are exported constants in one file and copied literals in another.**+`src/core/brain/doctor-exits.ts:207`, `:216` and `:225` hard-code+`"embedding-model-sunset-unsurveyed"`, `"embedding-model-sunset-undetermined"` and+`"recovery-point-unmeasured"` — strings that are exported one import away at+`src/core/brain/doctor/embedding-sunset-check.ts:81`, `:84` and+`src/core/brain/doctor/recovery-point-liveness.ts:68`. `src/core/brain/diagnostics.ts:466-470` argues+that the literal is deliberate there (importing the constant would let the census follow the import+back); the `doctor-exits.ts` exclusions carry no such justification and read as copies. A rename in+either new module leaves an orphaned exclusion whose only symptom is a code the exit census then+rejects.++**`tests/cli/brain-dream-progress.test.ts:60-74` hand-rolls `progressRecords`** byte-for-byte from+`tests/helpers/progress-records.ts:23` — minus the `try/catch` around `JSON.parse` that the helper+carries specifically so "another writer's brace-leading line" does not "blame this reader for someone+else's stderr". Five sibling progress tests import the helper; the dream one does not. The dream test+(`66610032`) predates the helper's extraction (`96dd769e`) and was never migrated, so the one verb+whose stderr is busiest is checked by the one copy without the guard. None of the six new progress+tests uses `CLI_SPAWN_BUDGET_MS` (`tests/helpers/cli-timeout.ts:41`) either, though six other CLI test+files adopted it on this branch.++---++### F14 — Orphan exports and one missing census registration. CONFIRMED++Exported by a new module and imported **nowhere** in `src/`, `tests/`, `hooks/` or `scripts/`:++| symbol | site | note |+|---|---|---|+| `EXIT_TERMINATED` | `src/cli/interrupt.ts:40` | The 143 exit is produced through `EXIT_FOR_SIGNAL` (`:47-50`); the named constant is read by nothing, and **no test asserts 143 anywhere** — `grep -rn '143\|SIGTERM' tests/` finds no coverage of the SIGTERM half of the contract documented at `docs/cli-reference.md:724`. Contrast `EXIT_INTERRUPTED`, asserted in two test files. |+| `progressNotification` | `src/mcp/progress.ts:125` | Used only by `progressSink` in the same file. Exported for no reader. |+| `SELF_HEAL_REINDEX_SURFACE` | `src/core/maintenance/self-heal-reindex.ts:47` | Referenced only inside its own file. |+| `readSelfHealReindexRows` | `src/core/maintenance/self-heal-reindex.ts:176` | Imported only by `tests/core/maintenance/self-heal-reindex.test.ts`. No shipped surface renders these rows. (Not a broken promise — `docs/metrics.md` tells external consumers to read the JSONL directly — but the reader is dead weight in `src/`.) |+| `ProgressStream`, `ProgressOutcome` | `src/cli/progress-rail.ts:41`, `:65` | Types with no external consumer. |+| `StatfsProbe`, `VaultBackingOptions` | `src/core/vault-backing.ts` | Injection seams used only by tests. |+| `HostPressureMeasured`, `HostPressureUnmeasurable` | `src/core/brain/maintenance/host-pressure.ts:130`, `:138` | Constituent types of an exported union; never named elsewhere. |+| `MaintenanceGateDecision` | `src/core/brain/maintenance/lane.ts:100` | The new return type of `evaluateGates` (`:166`), never named by any caller. |+| `HostPressureGate` | `src/core/brain/maintenance/lane.ts:70` | |+| `normalizePreCompactLabel` | `src/core/brain/pre-compact-extract.ts:121` | |+| `ProactiveRecallScore` | `src/core/bench/failure-modes.ts:158` | |+| `SessionAdapterRegistry` | `src/core/brain/sessions/registry.ts:34` | |+| `DATA_OWNERSHIP_KEY`, `installJson` | `src/cli/install/render.ts:50`, `:58` | File-private in practice. |++**A repeated shape, nine times over.** The branch mints the house closed-vocabulary quartet — `X`+object, `XS` list, `isX` guard, `XState` type alias — in nine independent modules. In **every one**+the object, list and guard are consumed and the exported **type alias is dead**: `ProgressKind`+(`progress.ts:74`), `ProgressOutcome` (`progress-rail.ts:65`), `HostPressureState`+(`host-pressure.ts:69`), `SelfHealReindexOutcome` (`self-heal-reindex.ts:92`),+`EmbeddingSunsetState` / `…UndeterminedReason` / `…Source` (`sunset.ts:116`, `:149`, `:190`),+`VaultBackingUndeterminedReason` (`vault-backing.ts:102`), `TranscriptScan`+(`transcripts/types.ts:29`), `ImportWriteMode` (`sessions/import.ts:148`). Nine agents applied one+template without any of them checking whether the type half is ever named. Harmless, but it is the+clearest single fingerprint of the build pattern in the tree.++(I checked one claim that rests on a dead type and it holds: `src/core/install/ownership.ts:254-257`+says `survivalLine`'s `switch` is "Exhaustive over `VaultBackingState` … a fifth state added to that+vocabulary fails this file to build". `VaultBackingState` appears in that file only inside a JSDoc+`{@link}`, but the switch discriminates on `backing.state` and the function's declared `string` return+makes TS2366 fire under `strict` the moment the union grows. The comment is true.)++**Missing census registration.** `tests/core/architecture/verdict-vocabulary-census.test.ts:18-21` says+"Every vocabulary the wave introduces registers below". `PROGRESS_OUTCOME` /+`PROGRESS_OUTCOMES` / `isProgressOutcome` (`src/cli/progress-rail.ts:55-76`) is a complete trio+introduced by this wave and is **not** in the census — the only new trio that is missing. (The census+already reaches outside `src/core`: it registers `src/mcp/registry-guard.ts` and+`src/mcp/brain/lifecycle-file-tools.ts`, so the layer is not the reason.) Its sibling+`PROGRESS_KIND`/`PROGRESS_REASON` are registered at `:721` and `:730`.++---++### F15 — Two spellings for "the reason we could not determine", in one release. CONFIRMED (low)++The tree already carried both conventions before this branch (`PROVIDER_PROBE` uses kebab,+`MATERIALIZE_UNKNOWN_REASON` uses snake), so this is not a break — but the branch adds five new reason+vocabularies to one release and splits them:++| vocabulary | spelling | example |+|---|---|---|+| `PROGRESS_REASON` (`progress.ts:100`) | kebab | `timed-out`, `transport-single-response`, `stream-buffered` |+| `PROGRESS_OUTCOME` (`progress-rail.ts:55`) | kebab | `suppressed-buffered-stream` |+| `VAULT_BACKING_UNDETERMINED_REASON` (`vault-backing.ts:92`) | snake | `probe_unsupported`, `fs_type_unknown` |+| `HOST_PRESSURE_UNMEASURABLE_REASON` (`host-pressure.ts:83`) | snake | `platform_blind`, `cpu_quota_in_force` |+| `EMBEDDING_SUNSET_UNDETERMINED_REASON` (`sunset.ts:137`) | snake | `model_unresolved`, `survey_stale` |++All five land in a `reason`-shaped field of a JSON payload an operator or agent parses. A caller+handling `"timed-out"` and `"survey_stale"` in the same switch is reading one release's output.+Doctor codes are consistently kebab (`recovery-point-stale`, `embedding-model-sunset-unsurveyed`) and+maintenance verdicts consistently colon-prefixed (`skipped:pressure`, matching the pre-existing+`skipped:window`), so those two are clean.++---++### F16 — Undocumented operator-visible surfaces added by this branch. CONFIRMED (low)++Five new doctor codes — `recovery-point-stale`, `recovery-point-unmeasured`,+`embedding-model-sunset-announced`, `embedding-model-sunset-unsurveyed`,+`embedding-model-sunset-undetermined` — appear nowhere under `docs/` outside the brainstorm folder,+while the doctor **exit-code** change they ride with is documented in detail+(`docs/cli-reference.md:61-83`). The new `embeddings:` config block is in the config template+(`src/core/brain/config-template.ts:370-388`) but in no doc, while its sibling `maintenance:` block is+documented at `docs/cli-reference.md:330`. `docs/mcp.md` also still documents the pre-rename+`exact`/`fallback` token-impact enum.++---++## Section 1 — the full enumeration: every declared surface, and whether an input reaches it++`✔` = a real input in a shipped configuration produces it. `✖` = no such input exists.+`~` = reachable only outside a supported configuration, or only after a future date.++### Progress spine (U1/U2)++| declared surface | site | reachable | by what input |+|---|---|---|---|+| `PROGRESS_SCHEMA "o2b.progress.v1"` | `progress.ts:56` | ✔ | every event |+| `PROGRESS_KIND.started` | `progress.ts:67` | ✔ | `--progress` on any of 6 verbs; MCP token |+| `PROGRESS_KIND.advanced` | `:68` | ✔ | any iteration checkpoint |+| **`PROGRESS_KIND.refused`** | `:69` | **✖** | no `ProgressEvent` producer — **F3** (defect in the doc, honest as a vocabulary member) |+| `PROGRESS_KIND.stopped` | `:70` | ✔ | Ctrl-C, or an elapsed safeguard deadline |+| `PROGRESS_KIND.finished` | `:71` | ✔ | normal completion |+| `PROGRESS_REASON.aborted` | `:102` | ✔ | SIGINT/SIGTERM → `SafeguardAbortError` |+| `PROGRESS_REASON.timedOut` | `:104` | ✔ | `safeguard_timeout_*_seconds` elapsing |+| `PROGRESS_REASON.transportSingleResponse` | `:111` | ✔ | `o2b mcp --transport http` + `_meta.progressToken` |+| **`PROGRESS_REASON.streamBuffered`** | `:117` | **✖** | **F2 — defect** |+| `ProgressEvent.total` | `:155` | ✔ | embed / plan / render / candidates / sweep stages |+| `ProgressCounterOptions.onSinkError` | `:199` | ✔ | passed only by `dream` — **F6** |+| `PROGRESS_OUTCOME.emitted` | `progress-rail.ts:57` | ✔ | `--progress` |+| **`PROGRESS_OUTCOME.suppressedBufferedStream`** | `:62` | **✖** | **F2 — defect** |+| **`ProgressAttachment.reason`** | `:124` | **✖** | **F2 — defect** |+| **`progress: not emitted (…)` line** | `:185` | **✖** | **F2 — defect** |+| **`progress_fault` (`--json`, architect)** | `architect.ts:71` | **✖ in practice** | only if the CLI sink throws; it can throw only on an unknown `kind`, impossible in-process — **F6** |+| `interrupted: true` (`--json`) | `interrupt.ts:122` | ✔ | Ctrl-C on 5 verbs; **absent on maintenance — F7** |+| exit `130` `EXIT_INTERRUPTED` | `interrupt.ts:37` | ✔ | SIGINT during a long verb |+| exit `143` `EXIT_TERMINATED` | `interrupt.ts:40` | ✔ (produced) | SIGTERM; **the exported constant has no reader and no test — F14** |+| `params._meta.progressToken` | `mcp/progress.ts:97` | ✔ | any MCP client; **declared in no `inputSchema`, advertised in no `initialize` capability** |+| `notifications/progress` | `:46` | ✔ | stdio + token |+| `result._meta["open-second-brain/progress"]` refusal | `:53`, `:173` | ✔ | HTTP transport + token |+| `--progress` on index/reindex | `indexing.ts:175`, `:233` | ✔ | flag |+| `--progress` on architect/bridges/clusters/maintenance `run` | see F8 | ✔ | flag (undiscoverable — **F8**) |+| `--progress` on `brain dream run` | `dream.ts:109` | ✔ | flag (undocumented anywhere — **F8**) |+| **`--progress` on `brain dream stage\|validate\|apply`** | `dream.ts:109` | **✖** | parsed, dropped, no refusal — **F4, defect** |+| **`--progress` on `brain maintenance status`** | `maintenance.ts:68` | **✖** | parsed, early return — **F4, defect** |+| **`VectorBackfillOptions.onProgress`** | `vector-backfill.ts:63` | **✖** | no producer in `src/` — **F5, defect** |+| **`DreamStageOptions.onProgress`** | `dream-stage.ts:107` | **✖** | no producer in `src/` — **F4, defect** |++### Vault backing (U8)++| surface | site | reachable | by what input |+|---|---|---|---|+| `VAULT_BACKING.durable` | `vault-backing.ts:57` | ✔ | Linux vault on ext4/btrfs/xfs/zfs/nfs/… |+| `VAULT_BACKING.volatile` | `:59` | ✔ | vault under a tmpfs `/tmp` or `/dev/shm` |+| `VAULT_BACKING.layered` | `:61` | ✔ | vault on a container overlayfs |+| `VAULT_BACKING.undetermined` | `:63` | ✔ | any non-Linux host |+| `…REASON.probeUnsupported` | `:94` | ✔ | **every macOS run** — the whole durability half of the ownership close is silent on a first-class platform. Honest, but the common case, not the rare one |+| `…REASON.pathUnreadable` | `:96` | ✔ | vault path removed between config write and probe |+| `…REASON.fsTypeUnknown` | `:98` | ✔ | 9p under WSL, exfat, squashfs, ecryptfs |+| `DataOwnership.outside_vault[]` (9 rows) | `ownership.ts:86-182` | ✔ | emitted **unconditionally** — an enumeration of what the tool *can* leave outside, not a detection of what *is* there. Row wording is conditional, so honest; a reader treating it as detection would be misled |+| `third_party_embedding_configured` | `ownership.ts:227` | ✔ | networked embedding provider configured |+| `schema_version: 1` on `install --apply --json` | `render.ts:56` | ✔ | constant, additive |++### Provider sunset (U9)++| surface | site | reachable | by what input |+|---|---|---|---|+| `EMBEDDING_SUNSET.announced` | `sunset.ts:106` | ✔ | any of 16 shipped first-gen OpenAI models, or an operator declaration |+| `EMBEDDING_SUNSET.noneAnnounced` | `:108` | ✔ | `text-embedding-3-small` |+| `EMBEDDING_SUNSET.unsurveyed` | `:110` | ✔ | any off-catalog model — the normal case, incl. the model onboarding suggests |+| `EMBEDDING_SUNSET.undetermined` | `:112` | ✔ | `model_unresolved`, or an unreadable search config |+| `…REASON.modelUnresolved` | `:139` | ✔ | semantic search on, `embedding_model` unset |+| **`…REASON.surveyStale`** | `:141` | **~** | clock-gated: first fires **2027-08-16** (`reviewedAt: "2026-08-15"` + 365 d). A hard-coded fuse: every operator on a surveyed-negative model starts getting `embedding-model-sunset-undetermined` on that date unless the table is refreshed. Honest state, but a scheduled future regression |+| **`…REASON.surveyEntryMalformed`** | `:143` | **✖** | every shipped survey row is a valid literal. Honest defensive guard against a future table edit |+| **`…REASON.declarationMalformed`** | `:145` | **✖** | `parseEmbeddingsBlock` (`blocks/embeddings.ts:100`) already rejects with `BrainConfigError` using **the same** `isValidIsoInstant` predicate. Provably dead on the config path — a second check of a fact already enforced |+| `EMBEDDING_SUNSET_SOURCE.{declaration,survey,none}` | `:182-186` | ✔ | all three |+| `embeddings.sunset_model` / `sunset_at` | `blocks/embeddings.ts:52-53` | ✔ | `_brain.yaml`; both-or-neither enforced |+| doctor `embedding-model-sunset-announced` | `embedding-sunset-check.ts:78` | ✔ | announced with ≤ 90 days remaining |+| doctor `embedding-model-sunset-unsurveyed` | `:81` | ✔ | off-survey model |+| doctor `embedding-model-sunset-undetermined` | `:84` | ✔ | 2 of its 4 reasons |++### Host pressure and the lane (U6)++| surface | site | reachable | by what input |+|---|---|---|---|+| `maintenance.host_pressure_percent` | `blocks/maintenance.ts:103` | ✔ | opt-in key; unset by default |+| `maintenance.failure_streak_limit` | `:111` | ✔ | default 3, active without opt-in |+| `HOST_PRESSURE.measured` | `host-pressure.ts:60` | ✔ | gate configured, no refusal fires |+| `HOST_PRESSURE.unmeasurable` | `:62` | ✔ | via the quota reasons |+| **`…REASON.platformBlind`** | `:85` | **~** | `win32` only, and `src/core/config.ts:128` throws `UnsupportedPlatformError` on win32. Reachable only by forcing `OPEN_SECOND_BRAIN_CONFIG` on a platform this build states it does not support |+| `…REASON.cpuQuotaInForce` | `:87` | ✔ | any container with `--cpus` |+| `…REASON.cpuQuotaUnknown` | `:89` | ✔ | malformed `cpu.max` / `cpu.cfs_quota_us` |+| **`…REASON.parallelismUnknown`** | `:91` | **✖** | `availableParallelism()` always returns an integer ≥ 1; the only injectable `HostPressureProbe` seam is set by tests |+| **`…REASON.loadAverageInvalid`** | `:93` | **✖** | `loadavg()` on linux/darwin always returns three finite non-negative numbers |+| `MAINTENANCE_VERDICT.skippedPressure` | `journal.ts:38` | ✔ | measured ≥ threshold |+| `MAINTENANCE_VERDICT.refusedStreak` | `:41` | ✔ | 3 journaled consecutive failures |+| `MAINTENANCE_VERDICT.pressureUnmeasurable` | `:43` | ✔ | any unmeasurable reading |++*Assessment of the four unreachable/near-unreachable arms above:* `parallelismUnknown` and+`loadAverageInvalid` are honest defensive guards against inputs the standard library cannot produce —+acceptable, and the module is right to check refusals before arithmetic. `platformBlind` is different:+the design doc cites Windows load-average behaviour as the *motivating* case, and the build refuses to+run on Windows. That is a member argued from a platform this release does not ship to.++### Self-heal reindex (U5)++| surface | site | reachable | by what input |+|---|---|---|---|+| `SELF_HEAL_SPAWN.spawned` | `self-heal-reindex.ts:59` | ✔ | schema bump + background `ensureVaultCurrent` |+| `SELF_HEAL_SPAWN.skippedWriterLock` | `:61` | ✔ | a second session losing the lock probe |+| `SELF_HEAL_REINDEX_OUTCOME.completed` | `:86` | ✔ | the detached child finishing |+| `SELF_HEAL_REINDEX_OUTCOME.failed` | `:88` | ✔ | the child throwing, or being stopped |+| `--self-heal` on `search reindex` | `indexing.ts:236` | ✔ | machine-only; set by `ensure-current.ts:37` |+| `EnsureCurrentResult.reindexSpawn` | `ensure-current.ts:43` | ✔ | background mode |+| `readSelfHealReindexRows` | `:176` | **✖ as a consumer** | no production caller — **F14** |++### Doctor, readiness, partner (U8/U9 + doctor unit)++| surface | site | reachable | by what input |+|---|---|---|---|+| exit `0` / `1` `DOCTOR_EXIT` | `main.ts:299-300` | ✔ | pre-existing values, tabled |+| exit `6` `DOCTOR_EXIT.probeIncomplete` | `main.ts:301` | ✔ | `--readiness` with ≥1 `unknown` probe. **Deliberate alias of `SEARCH_CHECK_EXIT.probeIncomplete = 6`** (`check.ts:111`); precedence one-way at `main.ts:318-319`, so `1` never hides behind `6`. Consistent |+| `readiness_summary` (`probes`/`failed`/`unknown`) | `main.ts:394-398` | ✔ | `doctor --readiness --json` |+| `READINESS_STATUS.unknown` from a timeout | `doctor-readiness.ts:580` | ✔ | probe exceeding its budget |+| `recovery-point-stale` | `recovery-point-liveness.ts:65` | ✔ | newest archive > 30 days |+| `recovery-point-unmeasured` | `:68` | ✔ | `listSnapshots` throwing (perm/EIO). Its second arm — an unparseable `created_at` — is unreachable, since the field is always `toISOString()` output |+| `partner_codegraph_disabled` + `OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED` | `config.ts:1038-1039` | ✔ | config key or env var; default off |+| `code_graph` "silenced by" line | `partner/codegraph.ts:376-382` | ✔ | switch on |++### Bench, sessions, transcripts (U7/U10)++| surface | site | reachable | by what input |+|---|---|---|---|+| `RECALL_FAILURE.{know_to_ask,false_fire,faulted}` | `failure-modes.ts:87-91` | ✔ | operator-authored fixture questions |+| `o2b.bench.v2` schema + `failure_modes.*` fields | `bench/types.ts:23` | ✔ | `o2b brain bench` with a fixture. **No fixture ships in the npm tarball** (`package.json` `files` omits `tests/`), so reachable from a checkout or an operator-authored dataset only |+| `SESSION_ADAPTER_ID.{claude,codex,hermes,opencode,grok}` | `sessions/types.ts:34-38` | ✔ | `--format <id>` |+| `IMPORT_WRITE_MODE.{applied,dry_run}` + `write_mode`, `signals_withheld`, `facts_withheld` | `sessions/import.ts:143`, `import-session.ts:161-167` | ✔ | `brain import-session [--dry-run]` |+| `TRANSCRIPT_SCAN.{collected,idle,root_absent,unreadable}` | `transcripts/types.ts:22-28` | ✔ | all four; `unreadable` from a permission-denied transcript home |+| `TOKEN_COUNT_METHOD.{tokenizer,heuristic}` | `token-impact.ts:85-87` | ✔ | `brain_token_impact` `method`; legacy `exact`/`fallback` still accepted on read but no longer advertised — `docs/mcp.md` is stale |++---++## Section 4 — the commit record++**Verified intact.** Machine checks:++- `git diff main...HEAD --name-only` and the union of `git log main..HEAD --name-only` are **identical+ sets** (`diff` exit 0). No file was touched and then lost, and no file exists in the tree that no+ commit accounts for.+- No commit subject or body contains `revert`; no commit reverts an earlier one.+- No conflict markers (`<<<<<<<`/`=======`/`>>>>>>>`) anywhere in `src/`, `tests/`, or the brainstorm+ folder.+- No duplicated top-level `export function|const|class|interface|type` name inside any changed file —+ the usual signature of a botched merge.+- All 61 commits carry one author. Content is present and coherent.++**Sweeps confirmed, as reported.** Three commits carry files that belong to a different unit's subject:++| commit | subject | swept-in files |+|---|---|---|+| `5d6363e0` | `feat(benchmark): bound the query fan-out` | `src/cli/install/install.ts`, `src/cli/install/render.ts`, `tests/cli/install-json-shape.test.ts` |+| `c493f4e7` | `fix(architect): render the same bytes on a differently-collating host` | `src/core/brain/sessions/{import,registry,types}.ts`, `tests/core/brain/sessions/adapter-registry.test.ts` |+| `e7116b12` | `fix(cli): cancellation reaches both dream entry points, not one` | `src/cli/brain/verbs/import-session.ts` |++The *content* of the swept files is intact — each is a coherent, complete change and each has its own+tests. The cost is bisectability, not correctness: `git log --oneline -- src/core/brain/sessions/` now+attributes the session-adapter registry to an architect rendering fix.++**One file whose final state is a partial merge of two agents' intentions:**+`src/core/brain/policy/load.ts:248-280` — see **F10**. A declaration was inserted between an existing+docblock and the symbol it documented, so `loadMaintenanceConfigSafe` carries two docblocks (one about+`active.most_applied`) and `loadActiveMostAppliedSafe` carries none. This is the only instance I found.++---++## What I checked and found sound++- **Import cycles and layering.** `bun test tests/core/architecture/import-cycles.test.ts+ tests/core/layering.test.ts` — 6 pass, 0 fail. No new cycle. No `src/core` → `src/cli`/`src/mcp`+ import. No `process.exit`, `process.stdout.write` or `console.log` added under `src/core`. The one+ caveat is the ratchet-invisible inline type form (**F12**), which is latent, not live.+- **Exit-code consistency across surfaces.** `DOCTOR_EXIT.probeIncomplete = 6` deliberately reuses+ `SEARCH_CHECK_EXIT.probeIncomplete = 6` for the same meaning, with the same one-way precedence+ (proved failure outranks unmeasured) in both `doctorExitCode` (`main.ts:317-320`) and+ `exitCodeForCheck` (`check.ts:129-144`). `INSTALL_EXIT` (`install.ts:58-64`) does not collide with+ either — its `5` is `mcpUnreachable`, `search check`'s `5` is `providerUnreachable`, and the two verbs+ answer disjoint questions. `130`/`143` are the shell's own convention and collide with nothing.+- **Flag naming.** One spelling, one polarity, everywhere: `--progress` is boolean and opt-in on all+ seven verbs. No `--quiet` / `--no-progress` / `--progress=none` divergence. `--self-heal` appears only+ where its producer spawns it.+- **MCP transport decision.** The refusal is genuinely structural, not a flag: `src/mcp/http.ts:52`+ constructs `MCPServer` without `sendNotification`, and `src/mcp/stdio.ts:47` and `:131` supply one.+ A token over HTTP therefore cannot be silently honoured, and the refusal rides on `result._meta` on+ both the success and the error envelope (`src/mcp/server.ts:377`, `:384`). `serveStdioFromString`+ frames notifications through the same `frameLine` as responses, so the test harness cannot report the+ feature as absent.+- **Vocabulary trios really are closed.** I type-checked `MaintenanceVerdict`, `HostPressureState` and+ `VaultBackingState` against a non-member literal under `--strict`; all three reject it. The+ `Object.freeze({...})` form without `as const` used in `journal.ts:33` and `host-pressure.ts:58` still+ yields literal unions — my initial suspicion that those two had widened to `string` was wrong.+- **Vocabulary census coverage.** 15 of the 16 new trios are registered in+ `tests/core/architecture/verdict-vocabulary-census.test.ts`, and the census carries its own+ self-check suite (`:912-972`) so a broken audit cannot pass silently. Only `PROGRESS_OUTCOME` is+ missing (**F14**).+- **Lock adoption is complete where it was claimed.** `acquireLockSyncWithRetry` reached all four+ read-modify-write sites the recon named (`git/store.ts:193`, `ingest/checkpoint.ts:188`,+ `ingest/content-manifest.ts:237`, `architect/generate.ts:340`), and each holds the read and the write+ in one critical section rather than only the write.+- **`isWriterLockHeld` is honestly advisory.** `src/core/search/store/writer-lock.ts:70-73` throws+ rather than collapsing an unreadable lock to `false`, and its caller+ (`src/core/maintenance/ensure-current.ts:127-133`) records the probe failure by name and spawns+ anyway rather than silently declining to self-heal. `reindexTriggered` is set from the decision+ (`:207`) rather than optimistically, so a run that declined does not claim it started one.+- **The install-vault chain disagreement is genuinely fixed.** `resolveInstallVault`+ (`src/cli/install/install.ts:135-137`) now delegates to `resolveVault`, the same chain every other+ verb uses.diff --git a/docs/brainstorm/nothing-runs-unwatched/review/locks-and-races.md b/docs/brainstorm/nothing-runs-unwatched/review/locks-and-races.mdnew file mode 100644index 00000000..2d123028--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/review/locks-and-races.md@@ -0,0 +1,658 @@+# Locks, races and durability — independent review of `feat/nothing-runs-unwatched`++Scope: everything this branch changed about concurrency, locking and durability —+the new ingest locking, `acquireLockSyncWithRetry`, the architect's write lock and+plan-then-write ordering, the process-wide embedding ceiling and the `Semaphore`+itself, the bounded benchmark fan-out, the self-heal reindex herd, the maintenance+lease/journal as touched by the new gate and streak, and their tests.++Method: read the interleavings, then break the production code in a throwaway+`git worktree` and re-run the tests to see whether they catch the defect. Every+CONFIRMED item below was reproduced. **No modification was left in the tree**; the+scratch worktree was removed.++Findings are ordered most severe first.++---++## CONFIRMED++### C1. The retrying lock blocks the whole event loop — Ctrl-C, timers and progress all stop for up to 5 seconds++`src/core/brain/sync-lockfile.ts:170`++```ts+Bun.sleepSync(1 + Math.floor(Math.random() * RETRY_SLEEP_CEILING_MS));+```++`Bun.sleepSync` is a synchronous block. The retry loop therefore does not "wait" —+it freezes the single JavaScript thread for the entire budget. Nothing else in the+process runs: no timer, no progress emission, no signal handler, no other MCP tool+call.++Reproduced (2-second budget against a held lock):++```+threw after 2012 ms: lock busy: /tmp/probe-XXXXXX/.open-second-brain/content-manifest.json.lock+timer ticks during the 2s wait: 0 | SIGINT handled during wait: 0+SIGINT handled after wait: 1+```++A SIGINT delivered 200 ms into the wait was queued and only ran when the wait+finished. Failure scenario, concretely:++- **CLI.** `src/cli/interrupt.ts` is this branch's headline: "Ctrl-C reaches the+ operation". An operator who presses Ctrl-C while `generateArchDocs` is parked in+ `acquireLockSyncWithRetry` (`src/core/brain/architect/generate.ts:340`) gets no+ response for up to 5 s. Pressing it a second time — the documented escape for a+ hung synchronous pass — is worse: `process.once` means the second SIGINT falls+ through to the default handler, which kills the process without running the+ `process.on("exit")` hook that unlinks the lock (see P4).+- **MCP server.** `updateManifest` / `recordCompleted` / `appendGitRecords` run+ in-process. A 5 s stall there stalls *every* concurrent tool call and every+ progress notification the branch just added — including the ones the branch added+ so that "nothing runs unwatched".+- **Ingest.** Three locked call sites per source; worst case ~15 s of dead process+ per source before the ingest fails.++The docblock at `sync-lockfile.ts:133-137` argues the deadline exists "to make that+surface as a loud `ELOCKED` instead of a hang". The `ELOCKED` is indeed loud, but+the wait preceding it *is* a hang from every observer's point of view.++**Confidence: high (reproduced).**++### C2. A non-finite budget spins forever, uninterruptibly++`src/core/brain/sync-lockfile.ts:163-172`++```ts+const deadline = Date.now() + budgetMs;+for (;;) {+ try { return acquireLockSync(target); }+ catch (err) {+ if (code !== "ELOCKED") throw err;+ if (Date.now() >= deadline) throw err; // NaN >= NaN → false, always+ Bun.sleepSync(...);+ }+}+```++With `budgetMs = NaN`, `deadline` is `NaN` and `Date.now() >= NaN` is `false` on+every iteration. Combined with C1 the process is wedged with no timer, no signal+handling and no way out but `SIGKILL`.++Reproduced: `acquireLockSyncWithRetry(target, Number.NaN)` against a held lock was+still spinning when a 6-second `timeout` killed it (exit 124).++Only tests pass an explicit budget today, so this is latent — but it is exactly the+class of defect this same branch hardened one file over. `requireCap`+(`src/core/search/embeddings/http-util.ts:118-124`) exists because "a cap this+module cannot honour is named rather than quietly reinterpreted". `budgetMs`+receives no such treatment, and its failure mode is strictly worse than the one that+did.++**Confidence: high (reproduced).**++### C3. The stale-lock escape route the docblock names does not cover two of the three new lock sites++`src/core/brain/sync-lockfile.ts:134-137` (claim) vs `:180-184` (code)++The retry docblock justifies the 5-second deadline like this:++> Reaching it does not mean "busy", it means something is wrong — most likely a+> `.lock` left by a crashed process, which `brain doctor` reports via+> {@link scanStaleLocks} …++`scanStaleLocks` is called from exactly one place,+`src/core/brain/doctor/uncertainty-probes.ts:138`, with `dirs.brain` — i.e. it walks+`<vault>/Brain/` only. But two of the three new locks are not under `Brain/`:++| lock target | resolved path |+|---|---|+| content manifest (`content-manifest.ts:73`) | `<vault>/.open-second-brain/content-manifest.json.lock` |+| ingest checkpoint (`checkpoint.ts:97`) | `<vault>/.open-second-brain/ingest-checkpoints/<planId>.json.lock` |+| git record store (`git/store.ts:193`) | `<vault>/Brain/projects/git/<key>/commits.jsonl.lock` ✓ |+| architect (`architect/generate.ts:340`) | `<vault>/Brain/projects/arch/<key>.lock` ✓ |++Reproduced: with a lock present at+`<vault>/.open-second-brain/content-manifest.json.lock`,+`scanStaleLocks(join(vault, "Brain"))` returns `[]`.++Failure scenario: a crashed ingest leaves a manifest lock behind. Every subsequent+ingest freezes 5 s (C1) and then fails `ELOCKED`. The operator runs `brain doctor`,+which the docblock told them is the surface for this, and it reports **nothing**.+The `ELOCKED` message does name the file, so recovery is possible — but not by the+route the code says to take.++**Confidence: high (reproduced).**++### C4. `Semaphore` cannot detect an over-release, and `peakInFlight` hides it precisely when the bound breaks++`src/core/search/embeddings/http-util.ts:165-172`, `:147-149`++The hand-off fix is correct for the interleaving it targets (see the "sound"+section). What it does not do is defend the permit count:++```ts+release(): void {+ this.held--; // may go negative+ const next = this.waiters.shift();+ if (next) { next(); return; }+ this.permits++; // may exceed `limit`+}+```++There is no `if (this.permits >= this.limit) throw`. Two spurious `release()` calls+permanently widen the ceiling. Reproduced:++```+limit: 2 | real concurrent holders: 4 | semaphore reports peakInFlight: 2+```++Both halves matter:++1. The bound is broken — four holders against a ceiling of two.+2. `peakInFlight` still reads **2**, because `held` was driven negative by the same+ spurious releases. The docblock at `:146` says "never above `limit`" and the class+ docblock says the counter exists "because a bound nothing can observe is a bound+ nothing can verify". The instrument reads clean in exactly the failure it was+ built to catch.++No current call site over-releases — all three (`openai-compat.ts:312`,+`zeroentropy.ts:131`, `benchmark.ts:246`) are `acquire()` … `try/finally release()`.+But `provider-semaphore.ts` has just promoted this object from per-call to+**process-wide and shared between callers**, so a future extra release in any one+caller silently raises the outbound-request ceiling for every other caller in the+process, including the indexer. That is a new blast radius introduced by this branch+with no guard added alongside it.++**Confidence: high (reproduced).**++### C5. The architect's lock test cannot tell "locked around the read-modify-write" from "locked around the writes only"++`tests/core/brain/architect.test.ts` — "the notes are written inside one lock, which+is released afterwards"; production at `src/core/brain/architect/generate.ts:340`.++The test asserts only that `<dir>.lock` exists at each `advanced` progress event,+and is gone afterwards. Every `advanced` event is emitted from the write loop+(`generate.ts:241`), which runs *after* all planning reads. So the assertion is blind+to where the lock was taken relative to the reads.++Reproduced: in a scratch worktree I moved `acquireLockSyncWithRetry(dir)` out of+`generateRun` and into `renderNotes`, wrapping **only** the write loop — the exact+lost-update defect ("a lock that starts after the read does not prevent a lost+update"). Result:++```+19 pass, 0 fail (tests/core/brain/architect.test.ts + architect-progress.test.ts)+```++The docblock at `generate.ts:333-339` makes the strongest claim on this branch —+"two architect runs on the same repo would still read the same 'before' state and+erase each other's merge" — and **no test anywhere exercises two concurrent architect+runs**. Compare the ingest path, which does it properly with four real processes+behind a barrier (see the "sound" section). The architect got the same lock and none+of the same evidence.++The production code is, as written, correct: `planNote`'s `readFileSync` and+`atomicWriteFileSync` are both inside the critical section. The finding is that+nothing holds it there.++**Confidence: high (reproduced).**++### C6. A streak-refused task is a permanently red lane whose only exit disables every gate the operator configured++`src/core/brain/maintenance/lane.ts:255-263`, `:325-345`;+`src/cli/brain/verbs/maintenance.ts:275`++Once `consecutiveTaskFailures(vault, task) >= limit`, the task is never run+unforced, so the streak can never be cleared by a success. The refusal result+carries `ok: false`, and the CLI returns `result.tasks.some((t) => !t.ok) ? 1 : 0` —+so the nightly cron lane exits 1 forever, and the human line renders the refusal as+`reindex: FAILED (refused: 3 consecutive journaled failures …)`.++The only escape the code offers is `--force`, and `--force` is **lane-wide**: it+bypasses the window, the busy gate and the operator's brand-new+`host_pressure_percent` gate for *every* task, not just the refused one. There is no+`--force-task <name>`. So the remedy for one broken task is to run the whole heavy+lane with the operator's own load protection switched off.++Two related honesty problems in the same area:++- `src/core/brain/policy/blocks/maintenance.ts:50-53` argues against a limit of 1+ because it "converts a self-healing outage into a manual one". The default of 3 has+ the identical property once reached — it only requires three occurrences. A+ provider outage spanning three nightly runs produces a permanent manual-only+ refusal, and the docblock reads as if the default avoided that.+- The lane's own vocabulary work insists "a refusal is not an attempt"+ (`lane.ts:341-343`), yet the human-readable line prints it as `FAILED`.++**Confidence: high (read + exit-code path traced).**++### C7. The embedding ceiling's stated INVARIANT is per-endpoint; the key is per-(identity, endpoint)++`src/core/search/embeddings/provider-semaphore.ts:5-7`++> INVARIANT: across every concurrent `embed()` call in this process, at most+> `embedding_concurrency` embedding requests are in flight against **one resolved+> provider endpoint**.++The key is `JSON.stringify([embeddingSignature({provider, model, dimension}), endpoint])`+(`:70-81`). Two models — or two configured dimensions — against the same host are two+keys and therefore two independent budgets. `2 × embedding_concurrency` requests can be+in flight against one endpoint, which is the quantity a provider's rate limit actually+counts.++This is deliberate: `tests/core/search/embeddings.concurrency-ceiling.test.ts:195`+("two identities on one endpoint do not share a ceiling") asserts it, and the "What+the key is, and why" section argues for it. The defect is the INVARIANT line, which+states a property the code does not provide and which a reader will take at face+value when sizing `embedding_concurrency` against a provider quota.++Note the two negative tests here (`:195` and `:209`) cannot fail against+over-sharing — I confirmed both still pass with the registry bypassed. They pin the+partition, not the ceiling.++**Confidence: high (read + test behaviour confirmed).**++### C8. The self-heal rows pair on a pid, in a file the module says carries nothing machine-local++`src/core/maintenance/self-heal-reindex.ts:29-41`++> They pair on the child's pid … Nothing machine-local is written into a row — no db+> path, no host — because a synced vault carries it to peers where it is false.++A pid *is* machine-local, and it is the pairing key. The rows land in+`Brain/metrics/self_heal_reindex.jsonl` (`src/core/brain/metrics.ts:67`), which the+same docblock says is "synced across devices". Consequences:++- Device A writes `{decision: spawned, pid: 4242}`; device B writes+ `{outcome: completed, pid: 4242}` from an unrelated run. After sync they pair, and+ the test's own pairing rule (`self-heal-reindex.test.ts:141`,+ `completed?.pid === spawned?.pid`) reports a vanished child as completed.+- Pids are reused within one host too, so the same collision happens on a single+ device over a long-lived vault.++There is no run id / nonce to pair on instead, and the surface has no retention cap+(`metrics.ts` has no sweep), so the collision space only grows.++**Confidence: high (read; the sync claim is the module's own).**++### C9. "A spawn row with no terminal row is a child that vanished" is false for at least three other states++`src/core/maintenance/self-heal-reindex.ts:32-34`++The pair is genuinely diagnostic for SIGKILL. It is not diagnostic *of* SIGKILL,+because the same evidence is produced by:++1. **A child that is still running.** A full reindex of a real vault takes minutes;+ for that whole window the pair looks identical to a kill. The test at+ `self-heal-reindex.test.ts:122-126` asserts precisely this state ("the child's+ terminal row is not there yet") as the *correct* observation, then polls — but a+ later reader has no poll and no way to tell.+2. **A child that threw before it could arm the recording.**+ `src/cli/search/verbs/indexing.ts:252` runs `resolveConfig(flags)` *outside* the+ try, before `startedAt` at `:254`. An unreadable or missing `--config`, a bad+ `--vault`, or a `parseFlags` refusal all exit with no outcome row at all.+3. **A child whose recording itself failed.** `append()`+ (`self-heal-reindex.ts:158-169`) swallows every error — a read-only vault, a full+ disk, a `MetricSurfaceError` — by design. A child that completed successfully but+ could not write its row is indistinguishable from a child that was killed.++"A child that never started" *is* distinguishable, correctly: `Bun.spawn` throwing+means `recordSelfHealSpawn(spawned)` at `ensure-current.ts:163` is never reached and+the outer catch pushes `search-reindex: …` into `errors`, leaving no row of either+kind. Credit where due — that half of the question is answered well.++**Confidence: high (read; call ordering verified).**++### C10. One of the five ingest race tests cannot fail++`tests/core/brain/ingest/concurrent-shared-writes.test.ts:249-269` — "the manifest+stays parseable JSON after concurrent writers".++With the lock removed from `acquireLockSyncWithRetry`, four of the five tests in the+file went red; this one stayed green. It has to: `atomicWriteFileSync` renames a+complete file into place, so the manifest is parseable regardless of locking. The+test's own sibling docblock says so (`:11-14`, "Atomicity is not exclusivity"). It+certifies a property the lock does not provide and the absence of the lock does not+threaten.++Harmless on its own — but it is the one test in this file that would let a+lock regression through, and it sits under a `describe` block titled "the shared+files are not corrupted by the race".++**Confidence: high (reproduced).**++---++## PLAUSIBLE++### P1. The herd thinning is near-zero in the scenario it was written for++`src/core/maintenance/ensure-current.ts:126-140`++The docblock is honest about the *mechanism* — "Two callers can both find the lock+free and both spawn — the window between the probe and the child's own+`acquireWriterLock` is not closed by anything here" — and honest about the remedy's+limits ("this only thins the herd"). What it does not state is the window's+**magnitude**, and the magnitude is what decides whether the fix works.++The window spans: `Bun.spawn` → cold Bun start → module graph load → flag parse →+`resolveConfig` → `reindexVault`'s `acquireWriterLock`. That is hundreds of+milliseconds, not microseconds. The motivating scenario is "a schema bump makes every+session that starts afterwards find the index stale at once" — i.e. N parents probing+inside that same window. All of them see the lock free, and all of them spawn. The+fix helps sessions that start *after* some child has taken the lock, which is not the+herd described.++There is no test for it: `tests/core/maintenance/self-heal-reindex.test.ts` covers+one parent with the lock genuinely held (good — real contention, and it does catch+the fix) and one parent with it free. Nothing exercises two parents racing.++A remedy that would close it — have the child take the lock and the parent wait for+the *lock* rather than the spawn, or have the parent write a short-lived spawn+intent marker before `Bun.spawn` and have peers check that too — is not attempted or+discussed.++**Confidence: medium-high (reasoned; window magnitude not measured end-to-end).**++### P2. The 5-second budget is not generous "against a hold measured in milliseconds", because the holds are O(store size) and there is no fairness++`src/core/brain/sync-lockfile.ts:133-134`, `src/core/brain/git/store.ts:200-208`,+`src/core/brain/ingest/content-manifest.ts:236-248`++Two of the critical sections are linear in the data they guard:++- `appendGitRecordsLocked` calls `readRecords`, which reads and `JSON.parse`s **every+ line** of `commits.jsonl` before appending. On a repo with tens of thousands of+ commits that is not milliseconds.+- `updateManifest` spreads the entire manifest object and rewrites the whole file.++The retry has no queue and no fairness: each contender independently draws+`[1, 25] ms` and races. A waiter can lose many draws in a row. The premise the+budget rests on — "a hold measured in milliseconds", so "reaching it … means+something is wrong" — fails when `ingest/batch-plan.ts` does what it exists to do and+dispatches many parallel subagents against a large store. The observable outcome is a+hard `ELOCKED` failure of a perfectly healthy ingest, reported to the operator as a+crashed-process lock.++The jitter itself is sound: `1 + floor(random() * 25)` is redrawn every attempt, so+contenders genuinely decorrelate and do not converge on a common tick. That part of+the docblock holds.++**Confidence: medium (reasoned; not reproduced at scale).**++### P3. "No half-refreshed prefix" holds for `RegionError` and for the deadline — not for a write failure or a crash++`src/core/brain/architect/generate.ts:239-244`, and the module docblock at `:19-23`++Planning-before-writing genuinely removes the two failure modes it names, and the+test at `architect.test.ts` ("a corrupted note aborts the run before any note is+written") is a real test of the `RegionError` case. But the write loop is still a+loop over N `atomicWriteFileSync` calls:++```ts+for (const plan of plans) {+ if (plan.text !== null) atomicWriteFileSync(plan.path, plan.text);+ progress.advance(ARCHITECT_STAGE.render);+}+```++An `ENOSPC` / `EACCES` / `EIO` on the k-th write, or a SIGKILL, leaves k−1 notes+refreshed beside N−k+1 stale ones — the exact "half-refreshed tree" the module+docblock says the design prevents. The renderer's own comment concedes the shape of+this ("the write loop is the cheap part … that must not be left half-done") but+"must not" is an aspiration, not a mechanism. The header's flat claim at `:19-21`+overstates what the code delivers; scoping it to "a corrupted-sentinel abort" (which+the very next sentence does) would make it true.++**Confidence: medium-high (reasoned; the loop is unambiguous).**++### P4. A second Ctrl-C leaves an ingest lock nothing reclaims++`src/cli/interrupt.ts:91` (`process.once`) + `src/core/brain/sync-lockfile.ts:43`+(`process.on("exit")`)++`process.on("exit")` runs on a normal exit and on `process.exit()`. It does **not**+run when the default SIGINT/SIGTERM disposition terminates the process. `onInterrupt`+uses `process.once` deliberately, so the second interrupt falls through to that+default — which is the right call for a hung synchronous pass, and is exactly when a+process is most likely to be inside `Bun.sleepSync` holding or waiting on a lock.++The result is a `.lock` on disk that:++- nothing breaks on a timer — unlike `src/core/search/store/writer-lock.ts:18`,+ which gives the *search* writer lock a 60-second stale window so "a SIGKILL never+ wedges the index for longer than this window";+- `brain doctor` cannot see, for the manifest and checkpoint (C3);+- now costs 5 seconds of frozen process per attempt before failing (C1).++The asymmetry is worth naming: this branch added a stale-aware advisory probe to the+lock that already self-heals, and added retrying waits to the lock that does not.++**Confidence: medium-high (mechanism verified; the exact Bun signal disposition not+re-tested here).**++### P5. The ceiling registry never evicts, and a conflict surfaces mid-run++`src/core/search/embeddings/provider-semaphore.ts:59`, `:92-106`++`const ceilings = new Map<string, Semaphore>()` has no eviction. In a long-lived MCP+server that switches vaults (`brain_switch_vault`) or whose config changes model,+base URL or dimension, entries accumulate for the process lifetime, each retaining+its `waiters` array. Bounded in practice by the number of distinct configurations+seen, which is small — but "small" is a property of usage, not of the code, and the+module is explicitly about process-lifetime state.++Separately: `providerSemaphore` is called from inside `embed()`+(`openai-compat.ts:288`, `zeroentropy.ts:115`), so a ceiling conflict is raised after+batching has already been computed, on whichever `embed()` happens to be second. The+refusal is explicit and names `embedding_concurrency` (good), but it fires at an+arbitrary point in a run rather than at config resolution, where "two live+configurations disagree" is actually decidable.++**Confidence: medium (reasoned).**++### P6. The benchmark ceiling test asserts the gate's own counter, and that counter is never reset++`src/core/search/benchmark.ts:47`, `:55-57`;+`tests/core/search/benchmark-concurrency.test.ts:61`++`expect(_benchmarkQueryPeakForTests()).toBe(BENCHMARK_QUERY_CONCURRENCY)` reads+`queryGate.peakInFlight` — the semaphore's own bookkeeping, not the number of+`search()` calls actually overlapping. A production change that took a permit and+released it *before* calling `search()` would still saturate the counter to 8 while+bounding nothing. The honest instrument is the one the embedding test uses: a probe+inside the thing being bounded (`embeddings.concurrency-ceiling.test.ts:119-135`+counts in-flight HTTP requests at the server).++Also, `peak` is a process-lifetime high-water mark on a module-scoped semaphore with+no reset hook — deliberate for `tuneRecall`, but it means the assertion is+order-dependent if any other test in the same process ever exercises the benchmark+first.++**Confidence: medium (reasoned).**++### P7. `sweepJournal`'s "the one point where no other writer can race the journal" is not true, and this branch added another unleased writer++`src/core/brain/maintenance/lane.ts:300-302`, `journal.ts:92-102`, `lane.ts:215-234`++`sweepJournal` is a read → write-temp → rename. `appendJournal` is `O_APPEND`, which+is safe against *other appends* but not against a concurrent rewrite: a line appended+between the sweep's `readLines` and its `renameSync` is lost.++Gate-refusal rows are appended **before** `acquireLease` — that is the design+(`journal.ts:83-87` says so). So a second lane process that is gate-refused while a+first holds the lease and sweeps can lose its row. This branch adds one more unleased+append to that window: the `pressure:unmeasurable` notice at `lane.ts:219-226`, which+is written on *every* invocation on a host where the metric is degenerate (any+container with a CPU quota — `host-pressure.ts:210-212`).++Impact is observability only: task-outcome rows, which are the streak's input, are+written under the lease by the same process that sweeps, so the decision input is not+corrupted. Still, the comment asserts a property the code does not have, on a file+that this branch has just made load-bearing for a refusal decision.++**Confidence: medium (reasoned).**++### P8. A killed lease holder wedges the lane for 30 minutes, and `--force` is documented not to help++`src/core/brain/maintenance/lease.ts:59-83`, `lane.ts:213` (`MAINTENANCE_LEASE_TTL_MS`)++The lease self-frees by expiry, which is the right design, and the holder string+includes `@${process.pid}` (`cli/brain/verbs/maintenance.ts:129-131`) so two+processes cannot accidentally share a holder and both "re-entrantly renew" into+mutual-exclusion loss. Good.++But the TTL is 30 minutes and `--force` deliberately does not bypass the lease. There+is no `maintenance release` verb — `src/cli/brain/verbs/maintenance.ts` exposes `run`+and `status` only. After a SIGKILLed lane, the operator's options are to wait up to+30 minutes or to delete `<vault>/.open-second-brain/maintenance.sqlite` by hand. That+is the "manual file surgery" the review brief asks about; it is pre-existing, but the+branch's new streak refusal makes forced runs a routine operator action and therefore+makes this reachable more often.++**Confidence: medium (reasoned; pre-existing).**++### P9. `acquireLockSync` says the doctor reads the lock body; it does not++`src/core/brain/sync-lockfile.ts:85-87` vs+`src/core/brain/doctor/uncertainty-probes.ts:132-147`++> The contents are purely diagnostic — the doctor surface reads them when reporting+> stale locks.++`staleLockProbe` emits `{ code, path, message }` and never opens the file. The pid+and timestamp stamped into every lock — the two facts an operator needs to decide+whether a lock is abandoned, which is the judgment the probe explicitly delegates to+them — are written and then thrown away. Pre-existing, but it is the second load the+new retry docblock puts on a doctor surface that is weaker than advertised (see C3).++**Confidence: high on the mismatch, low on impact.**++---++## Checked and found sound++- **`acquireLockSyncWithRetry`'s core contract.** Only `ELOCKED` is retried; every+ other error propagates on the first attempt; the sole `return` is a successful+ `acquireLockSync`, so **there is no path that proceeds unlocked**. The expired+ budget rethrows the original error, which carries `code === "ELOCKED"`, `.path`,+ and a message naming the lock file — verified directly. `budgetMs <= 0` degrades+ cleanly to a single attempt (the deadline check runs after the first try). The+ jitter is redrawn per attempt and genuinely decorrelates contenders.+ (Bounds: C1, C2, P2.)++- **All three ingest sites lock the *whole* read-modify-write, not just the write.**+ Verified line by line: `content-manifest.ts:236-248` (spread of `readManifest`+ inside), `checkpoint.ts:187-206` (`readCheckpoint` + union + write inside),+ `git/store.ts:191-197` (`readRecords` + dedup + append inside, via the extracted+ `appendGitRecordsLocked`). No lost-update window remains at any of the three.++- **`tests/core/brain/ingest/concurrent-shared-writes.test.ts` creates real+ contention and would have caught the pre-fix code.** Four real `bun` children, a+ shared wall-clock start instant with a 1.5 s lead and a `Bun.sleepSync(1)` spin+ barrier — the docblock at `:61-66` names process-startup stagger as the thing the+ barrier defeats, which is the right worry, correctly addressed. Reproduced: with+ the lock neutralised, 4 of the 5 tests fail —++ ```+ (fail) updateManifest … missing 75 of the expected entries+ (fail) recordCompleted … 75 completed items lost+ (fail) appendGitRecords … the shared sha landed twice, not once+ (fail) acquireLockSyncWithRetry — an expired budget is loud+ ```++ This is the strongest test work on the branch. (Caveat: C10.)++- **The `Semaphore` hand-off fix is correct for the interleaving it targets.** The+ releaser transfers its permit directly and the resumed acquirer does not decrement+ again, so the permit is never observable as free between the wake and the+ continuation. A fresh `acquire()` arriving in the same synchronous turn as the+ release queues instead of stealing. Reproduced: reverting to the pool form+ (`permits++` on release, `permits--` after the await) makes+ `embeddings.concurrency-ceiling.test.ts:26` go red with `peak = 2` against a+ ceiling of 1. The test is a real test. No permit is leaked on a throw at any call+ site — all three use `try/finally` — and no waiter can be stranded: every queued+ waiter is resolved by some `release()`, and the abort paths in `openai-compat.ts`+ and `zeroentropy.ts` check `cancel.signal.aborted` *after* acquiring and still fall+ through the `finally`. (Bounds: C4.)++- **The process-wide ceiling actually spans the process, and its test proves it.**+ Reproduced: forcing `providerSemaphore` back to `new Semaphore(limit)` per call+ makes 4 of the 9 ceiling tests fail, including both of the "two overlapping+ `embed()` calls share one budget" cases and the ZeroEntropy mirror. The key is+ correctly built from the **configured** dimension rather than `provider.dimension`,+ which does prevent the ceiling from moving when the dimension is learned from the+ first response; excluding the API key is right, both for the rotation reason given+ and for not parking a secret in a process-lived map key. A conflicting limit is+ refused rather than reconciled, and the refusal names `embedding_concurrency`.+ (Bounds: C7, P5.)++- **`isWriterLockHeld` is honest.** Same `stale` window and same `realpath: false` as+ both acquire paths, so its answer agrees with what an acquire would do; it does not+ collapse a stat failure to `false`; and `ensure-current.ts:130-140` correspondingly+ records the probe failure into `errors` and spawns anyway rather than silently+ declining. The docblock's "ADVISORY, and only that" is accurate about what the+ function guarantees. (Bounds: P1, on how much the advisory buys.)++- **`self-heal-reindex.ts` picks the right surface for the right reason.** The+ argument for the metrics JSONL over the maintenance journal (run-level rows,+ `O_APPEND` single lines, no lock on the hook path, and a journal whose verdict+ vocabulary genuinely does not fit) holds up against both files. The fail-soft+ `append()` on a server-start path is the right trade. The child records `failed`+ before rethrowing, so the row survives whatever the caller's stderr points at, and+ a stopped rebuild is correctly recorded as a rebuild that did not happen — the+ staging database is abandoned and never swapped in. `--self-heal` changes nothing+ about the rebuild itself. (Bounds: C8, C9.)++- **`host-pressure.ts` refuses instead of inventing.** Two-state reading; every+ refusal reason named; the refusals are checked before the arithmetic; the gate is+ left **open** on `unmeasurable` and the reason is journaled on its own line, so a+ degenerate metric never reads as a quiet host. `evaluateGates` probes the host only+ after window and busy have passed, so a closed earlier gate honestly leaves no+ reading. The tests inject `readPressure` and assert the measurement count, so+ "never measures when unconfigured" and "never probes behind a closed gate" are both+ real assertions.++- **The streak's counting rules are right, even where its policy is not.** A success+ ends the walk; gate refusals, lease skips and `refused:streak` rows are all skipped+ because they are not `verdict === run`, so a refusal provably cannot deepen the+ streak it reports (`journal.ts:141-150`, asserted at+ `maintenance.test.ts` "A refusal is not an attempt"); a `run` row with no `ok`+ stops the walk, erring toward running. The streak is read inside the lease, so it+ cannot race another lane. `MAINTENANCE_FAILURE_STREAK_LIMIT_MIN = 1` makes the+ `limit = 0` brick-the-lane case unreachable through config. (Bounds: C6.)++- **The maintenance lease itself.** Single conditional upsert with a read-back+ confirmation, so two processes cannot both win; a positive-TTL guard with an+ explicit rationale for why a zero TTL would silently destroy mutual exclusion;+ holder strings carry the pid so re-entrant renewal cannot be triggered by two+ different processes; `releaseLease` is in a `finally` and is holder-scoped.+ (Bounds: P8.)++- **The benchmark gate is module-scoped for the correct reason** — `tuneRecall`'s+ 24-way grid would otherwise bound each call at 8 while the process ran 192 — and+ `queryGate.acquire()` sits outside the `try` with `release()` inside the `finally`,+ which is the right shape (a failed acquire must not release). (Bounds: P6.)++- **`requireCap` is a genuine improvement.** The old `Math.max(1, cap | 0)` really did+ wrap a ceiling above 2^31−1 negative and then clamp it to 1 — the largest ceiling an+ operator can configure becoming the smallest possible. The test at+ `embeddings.concurrency-ceiling.test.ts:68-76` pins it with a reachable value, and+ the refusals at `:78-83` cover 0, negative, fractional and NaN. Folding the+ concurrency cap into the same `CAP_FIELD` vocabulary is DRY done right.++---++## What I did not cover++Progress plumbing, the MCP progress-token work, the sunset/doctor checks, the bench+failure-mode fixtures, install/ownership and the census tests — all outside the+concurrency, locking and durability scope.++Note for whoever reads this next: at review time the working tree also carried+unrelated uncommitted edits to `tests/core/doctor.test.ts`,+`tests/mcp/config-read-failure-tools.test.ts` and `tests/mcp/mcp.test.ts` from+concurrent work by another author. They are not mine and I did not touch them.diff --git a/docs/brainstorm/nothing-runs-unwatched/review/progress-and-cancellation.md b/docs/brainstorm/nothing-runs-unwatched/review/progress-and-cancellation.mdnew file mode 100644index 00000000..d491636f--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/review/progress-and-cancellation.md@@ -0,0 +1,653 @@+# Independent review — the progress spine and the cancellation wiring++Branch `feat/nothing-runs-unwatched` against `main`. Scope as assigned:+`src/core/brain/progress.ts`, `safeguard.ts`, `src/cli/progress-rail.ts`,+`src/cli/interrupt.ts`, every emitter, the CLI verbs that attach them, and+the progress tests including `tests/core/architecture/progress-census.test.ts`.++Everything under CONFIRMED was reproduced by running code — either the+repository's own modules in a throwaway `git worktree`, or the shipped test+suite against a deliberately broken copy of production. The worktree was+removed and `git status` is clean; nothing in the tree was modified.++The release's thesis is that a mechanism which must be called by hand will+be missed, and that the answer is declaration plus a census. The findings+below are, almost without exception, instances of that same thesis applied+to this branch: the census is syntactic and does not reach the properties+the release cares about, and the two headline mechanisms — the terminator+and the interrupt — are each provably removable without turning a single+test red.++---++## CONFIRMED++### 1. Ctrl-C cannot stop four of the six operations, because they are fully synchronous++`src/cli/interrupt.ts:80` (`onInterrupt`), `src/core/brain/safeguard.ts:155`+(`checkpoint`), `src/core/brain/dream.ts:174` (`dreamRun`),+`src/core/brain/link-graph/communities.ts:98`,+`src/core/brain/link-graph/bridge-discovery.ts:107`,+`src/core/brain/architect/generate.ts:301`.++`onInterrupt` aborts an `AbortController` from a `process.once("SIGINT")`+handler. A Node/Bun signal handler is a JavaScript callback dispatched from+the event loop. `dreamRun`, `detectCommunitiesRun`, `discoverBridgesRun` and+`generateRun` are all declared `function`, not `async`, and contain no+`await` — so from the moment the pass starts until the moment it returns,+the process never re-enters the event loop and the handler cannot run. The+signal is pending, `signal.aborted` stays `false`, and every+`safeguard.checkpoint()` inside the pass passes.++Reproduced twice. First, the platform fact in isolation: a SIGINT delivered+0.3 s into a 2 s synchronous loop left `controller.signal.aborted === false`+for all 15.8 million iterations, and became `true` only on the next event-loop+turn. Second, end to end against this repository's own modules — `onInterrupt()`+plus `createSafeguard({operation:"dream", signal})`, calling `checkpoint()` in+a synchronous loop exactly as `dream` does:++```+{"checkpoints":26780673,"stoppedByCtrlC":false,"receivedDuringRun":null}+```++26.7 million checkpoints ran with the interrupt pending; `SafeguardAbortError`+was never thrown; `interrupt.received()` was still `null` when the pass ended.++**Failure scenario.** Operator runs `o2b brain dream` on a large vault, presses+Ctrl-C. Nothing happens. The pass runs to completion and writes every artifact+it was going to write. Only the *second* Ctrl-C stops it — by killing the+process outright, which is the SIGKILL-equivalent outcome this unit was+written to replace.++The module header already knows the shape of this ("a JavaScript timer cannot+interrupt a fully-synchronous CPU hang on a single thread, and neither can a+cooperative signal") but frames it as the pathological hang case. It is in+fact the *normal* case for `dream`, `bridges`, `clusters` and `architect`:+those four are synchronous end to end, so the cooperative signal is+unobservable for their entire duration, not merely during a hang. Only the+index run (which awaits real I/O — `provider.embed`) and the maintenance lane+(which awaits between tasks) can see it.++This makes `SafeguardAbortError` reachable in production only from the index+path, in a release whose stated purpose was to give that class a producer.+The core test that "proves the wiring" (`dream-progress.test.ts:158`) passes a+*pre-aborted* `AbortController` straight into `dream`, which exercises the+`createSafeguard` priority rule and nothing about signal delivery. Its own+comment concedes it declines to race a real interrupt.++Confidence: high. The synchronous-execution fact is checkable by inspection;+both reproductions used production code.++### 2. The first Ctrl-C is now swallowed, and the verb still exits 0++`src/cli/interrupt.ts:91` (`process.once(name, listener)`), and every verb+that calls `onInterrupt()` outside the region that checks the signal:+`src/cli/brain/verbs/bridges.ts:161`, `clusters.ts:139`, `dream.ts:409`,+`architect.ts:52`, `src/cli/search/verbs/indexing.ts` (both builders),+`src/cli/brain/verbs/maintenance.ts:157`.++Registering a SIGINT listener suppresses the default terminate behaviour for+as long as it is registered. The handle is open across work that never+consults the signal: `Store.open`, `writeBridgeProposals`, `appendMetric`,+`materializeClusterNotes`, `reportIndexRun`, `resolveSearchConfig`, the whole+reindex swap. A Ctrl-C landing in any of those windows is absorbed — the+controller aborts, nobody reads it, and the verb completes normally.++Reproduced with the repository's `onInterrupt`:++```+{"received":"SIGINT","aborted":true}+verb returned 0 after a Ctrl-C nobody acted on+exit=0+```++**Failure scenario.** `o2b brain bridges discover` has finished scanning and is+writing proposals. Operator presses Ctrl-C. The keystroke does nothing visible;+the command writes the file, prints its report, and exits 0. Before this branch+the same keystroke killed the process immediately. Only+`maintenance.ts:274` consults `interrupt.received()` after the fact; the other+five verbs check `instanceof SafeguardAbortError` only, so an absorbed signal+leaves no trace at all.++Combined with finding 1, the net effect on `dream`, `bridges`, `clusters` and+`architect` is that Ctrl-C responsiveness is strictly *worse* after this+branch than before it: the first press used to terminate, and now does nothing.++Confidence: high.++### 3. Removing the terminator from the entire index run breaks no test++`src/core/search/indexer.ts:320-330` (`indexInto` / `withProgressAsync`),+`tests/cli/search-index-progress.test.ts`.++The branch's final commit is titled "a stream that stops arriving has reported+nothing". I deleted the `withProgressAsync` wrapper from `indexInto` so that+`o2b search index --progress` and `o2b search reindex --progress` emit+`started` and `advanced` records and then simply stop — no `finished`, no+`stopped`, ever. Result:++```+tests/cli/search-index-progress.test.ts + tests/core/search → 1319 pass, 0 fail+tests/core/architecture + progress rails → 159 pass, 0 fail+```++Neither CLI progress test for the index asserts a terminator; both stop at+`records.length > 0` and `operation === "reindex"`. Only+`tests/core/brain/dream-progress.test.ts` and+`tests/core/brain/architect-progress.test.ts` assert `finished`, and only for+their own operations. The bridges, clusters, maintenance and architect CLI+progress tests assert no terminator either (`grep` for `finished` in those five+files returns nothing).++**What this means.** The property the release is named for is untested for the+operation most likely to run for minutes.++Confidence: certain (reproduced).++### 4. `withProgress` emits no terminator on a crash — the documented contract is the opposite++`src/core/brain/progress.ts:282` (`withProgress`), `:295` (`withProgressAsync`).++The docblock opens: *"Run `body` and terminate `counter` exactly once,+whichever way it ends."* The code terminates on success and on a safeguard+stop only; `progressReasonForError` returns `null` for anything else and no+event is emitted. Reproduced:++```+events on a crash: ["started"]+```++The second paragraph of the same docblock argues the case for not calling a+crash a cancellation — which is right — but the conclusion drawn is silence,+and silence is the exact failure mode the module's own three-way argument+rejects ("a stream that simply STOPS arriving is the shape of a completed run,+a crashed run and a hung run all at once"). There is no `failed` arm in+`PROGRESS_KIND` to carry the third case.++**Reachable production scenario.** `generateArchDocs`: `scanProject` emits+`started:walk` and N `advanced:walk` records, then `mkdirSync` on the vault+arch directory fails with EACCES, or `acquireLockSyncWithRetry(dir)`+(`generate.ts:340`) exhausts its retries. Neither is a safeguard error, so the+render counter — which has no stage open — emits nothing, the walk counter is+never terminated, and the stream ends mid-walk. Same for `dream`: any plain+throw inside `dreamRun` (malformed `_brain.yaml` reaching `loadBrainConfig`, an+`atomicWriteFileSync` failure in the apply stage) leaves the stream on+`started:scan` forever. The CLI prints a prose error on stderr, but the+structured stream an adapter parses carries no terminator.++Confidence: certain for the counter behaviour (reproduced); high for the+production paths (read, not run).++### 5. The counter enforces neither monotonicity nor a terminal state++`src/core/brain/progress.ts:248` (`advance`), `:258` (`finish`), `:261` (`stop`).++`ProgressEvent.completed` is documented as *"Units finished in this stage so+far. Monotonic within a stage."* and the event shape as *"Integers and+identifiers only."* `assertTotal` guards the denominator; nothing guards the+numerator, and nothing marks the counter terminal. Reproduced in one run:++```+["started:scan:0/3","advanced:scan:-5/3","advanced:scan:94/3","advanced:scan:95.5/3",+ "finished:scan:95.5/3","advanced:scan:96.5/3","finished:scan:96.5/3","stopped:scan:96.5/3"]+```++`completed` went negative, exceeded `total` by 31×, became fractional, and the+stream carried an `advanced` **after** `finished` plus three terminators. The+asymmetry is the defect: a bad `total` is "a loud defect, not a wrong number",+a bad `by` is a wrong number reported confidently.++`finish()` and `stop()` before any `start()` emit nothing at all (also+reproduced: `no-stage terminators emitted: []`), which is why finding 4's+architect path is silent rather than merely mis-labelled.++Confidence: certain (reproduced).++### 6. The census passes four different ways of taking a safeguard and reporting nothing++`tests/core/architecture/progress-census.test.ts:116-135` (the rule),+`:92-110` (`interfaceBlocks`), `:204-218` (the sync check).++I added each of the following to `src/core/brain/`, one at a time, and ran the+census. All four passed (6 pass, 0 fail). A positive control —+`export interface EvadePlainOptions { readonly safeguard?: Safeguard; }` —+correctly failed, so the census works only for the exact shape it recognises.++| Evasion | Why it passes |+|---|---|+| `interface X { readonly safeguard: Safeguard }` (required, not optional) | The file filter is `source.includes("safeguard?:")` and the member regex is `/\breadonly safeguard\?:/`. A required safeguard is invisible. |+| `type X = { readonly safeguard?: Safeguard }` | `interfaceBlocks` matches `interface\s+(\w+)[^{]*\{` only. A type-alias options object is never enumerated. |+| `interface X<T extends { k: string }> { readonly safeguard?: Safeguard }` | The header regex's `[^{]*` cannot cross the `{` inside the generic constraint, so brace-matching starts inside the constraint and the block "body" is `k: string`. The real body is never scanned. |+| A `Promise`-returning sink split over three lines | The sync check is line-based (`if (!line.includes("onProgress?:")) continue`), so a declaration whose return type is on a later line never meets the `Promise<` test. |++The generics case is the one to fix first: it does not merely fail to flag a+violation, it silently mis-parses a block that *is* in the population.++Beyond the parser, the rule itself is declaration-only. Nothing checks that a+declared `onProgress` is ever read, that a counter is ever built, that a+terminator is ever emitted, or that any CLI verb attaches a sink. An interface+satisfies the census by declaring a field it ignores.++Confidence: certain (reproduced, with positive control).++### 7. The "no prose" rule does not cover the three emitters that use a bare stage constant++`tests/core/architecture/progress-census.test.ts:160-202`,+`src/core/brain/link-graph/bridge-discovery.ts:87`,+`src/core/brain/link-graph/communities.ts:78`,+`src/core/search/vector-backfill.ts:107`.++Test 4 matches `start(` followed by either `CONST.member` or a `"literal"`, and+`advance(` followed by a `"literal"`. Test 5 matches only+`const \w*STAGE = Object.freeze({...})`. Three emitters declare their stage as+a bare string constant — `const BRIDGE_STAGE = "candidates"`,+`const COMMUNITY_STAGE = "sweep"`, `const VECTOR_BACKFILL_STAGE = "plan"` —+which is neither a dotted member reference nor an inline literal nor a frozen+object, so **neither** test ever sees its value.++Reproduced. I rewrote both link-graph constants to prose:++```ts+const BRIDGE_STAGE = "Scanning candidate pairs, please wait...";+const COMMUNITY_STAGE = "Propagating labels ACROSS the graph";+```++Census: 6 pass, 0 fail. The CLI-level guards would catch it for `clusters`+(`brain-clusters-progress.test.ts` matches `STAGE_IDENTIFIER`) but not for+`bridges`, whose progress test never inspects `stage`, and not for the+standalone vector backfill, which has no CLI progress test at all.++Confidence: certain (reproduced).++### 8. The whole cancellation wiring can be deleted with no test failure++Every `signal: interrupt.signal` in `src/cli/brain/verbs/{dream,bridges,clusters,architect,maintenance}.ts`+and `src/cli/search/verbs/indexing.ts`.++I removed the signal from all six verbs — the complete U3 wiring, leaving+`onInterrupt()` registered but connected to nothing — and ran+`tests/cli` + `dream-progress` + `tests/core/architecture`:++```+1339 pass, 0 fail (181 files, 141.92 s)+```++The only assertions the branch offers for the interrupt are+`expect(EXIT_INTERRUPTED).toBe(130)` (a constant compared to a literal) and+`reportInterrupted` called with a hand-constructed `SafeguardAbortError`. No+test drives a signal through a verb into an operation.++Confidence: certain (reproduced).++### 9. `search reindex --progress` reports `finished` before the rebuild is swapped in++`src/core/search/indexer.ts:1028` (`indexVault` returns, terminating the+stream) vs `:1032-1044` (marker clear, `tryUnlink`, `tryRename`,+`renameSync`).++`reindexVault` forwards `onProgress` into `indexVault`, which owns the counter+and calls `finish()` when the staging build completes. The atomic swap that+actually makes the rebuild real happens *after* that, outside any counter.++**Failure scenario.** `renameSync(newPath, config.dbPath)` fails (ENOSPC, EPERM+on the target directory, a cross-device `dbPath`). A caller tailing the+progress stream has already received `{"kind":"finished"}`; the command then+exits non-zero having left the live index untouched. The terminator said the+run finished; the run did not.++The mirror-image gap: `acquireWriterLock(config.dbPath)` at `:996` can block+for the duration of a competing reindex, and no counter exists yet, so+`--progress` emits nothing at all during the wait — the state the release+describes as indistinguishable from a hang.++Confidence: high (read; not reproduced, since forcing a rename failure needs a+crafted filesystem).++### 10. Cancelling the maintenance lane deepens a failure streak that will eventually refuse the tasks++`src/core/brain/maintenance/lane.ts:272-298` (catch → journal `verdict: run,+ok: false`), `:255-258` + `:324-346` (`refuseOnStreak`),+`src/core/brain/maintenance/journal.ts:141-150` (`consecutiveTaskFailures`),+`src/core/brain/policy/blocks/maintenance.ts:64`+(`MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT = 3`).++The lane runs its four tasks sequentially and catches each one's error into a+journal row with `verdict: "run", ok: false`. `SafeguardAbortError` is not+distinguished — `timed_out` is set for `SafeguardTimeoutError` only. So an+abort is journaled as a failed attempt. `consecutiveTaskFailures` counts+exactly those rows, and `refuseOnStreak` refuses a task at 3.++Worse, the abort signal stays set for the rest of the process, so after the+first task is stopped the remaining three trip on their *first* checkpoint and+are journaled as failures too. One Ctrl-C therefore writes four failure rows,+one per task.++**Failure scenario.** An operator cancels `o2b brain maintenance run` three+times over three nights. On the fourth run every task is refused by name with+`refused: 3 consecutive journaled failures reached the+maintenance.failure_streak_limit of 3; fix the cause, or re-run with --force`,+about passes that never failed. `refuseOnStreak`'s own comment is careful that+a refusal must not deepen the streak it reports — the same care was not taken+for a deliberate stop.++The verb's exit code is right (`maintenance.ts:274` returns 130), but its+`--json` payload reports `ok: false` per task with the abort message as+`error`, so the machine-readable surface still calls a stop a failure.++Confidence: high (read end to end; the streak default and the counting rule+were both verified in source).++### 11. The rail's refusal path has no producer in any shipped call site++`src/cli/progress-rail.ts:55-63` (`PROGRESS_OUTCOME.suppressedBufferedStream`),+`:110-125` (`ProgressAttachment.reason`), `:178-186`+(`reportProgressRefusal`), `src/core/brain/progress.ts:117`+(`PROGRESS_REASON.streamBuffered`), `src/cli/json-helpers.ts:68`+(`ownsInternalJson`).++`progressIsLegal` returns `true` unconditionally when `ownsInternalJson` is+true, and `ownsInternalJson` returns `true` for any argv under `brain` or+`search`. Every production `attachProgress` call site passes+`command: "brain"` or `command: "search"`. Therefore the refusal branch, the+`suppressed-buffered-stream` outcome, the `stream-buffered` reason, the+`ProgressAttachment.reason` field, and the `progress: not emitted (…)` wording+are unreachable from any shipped command.++`tests/cli/progress-report.test.ts:11-15` states this outright: *"Neither is+reachable through `o2b brain …` or `o2b search …`"*. That is an honest note,+but the honest conclusion is that this is a stub — a vocabulary member and an+operator-facing string with no producer, which is the defect class the release+names in its own title.++Related comment-versus-code gap: `ProgressAttachment.reason` is documented as+*"A caller rendering a `--json` payload carries it as a field, so the refusal+is visible on the surface the caller actually reads."* No verb reads+`observation.reason`. `grep` for it across `src/cli/` returns nothing.++Confidence: certain (both facts checked by grep against every call site).++### 12. `OPERATION.maintenance` can never appear on a progress stream, and its timeout key has no reader++`src/core/brain/safeguard.ts:39` and `:51`, `src/cli/brain/verbs/maintenance.ts:162`,+`tests/cli/brain-maintenance-progress.test.ts:78`.++`OPERATION` was promoted from a bare union specifically so "both the timeout+ladder and `ProgressEvent.operation` read from one place". Of the six members,+`maintenance`:++- is never passed to `progressCounter` (the only six call sites are dream,+ bridges, clusters, architect ×2, reindex ×2). The lane forwards the caller's+ sink to the four sub-operations instead — a defensible design, and the CLI+ test *asserts* `records.every(r => r.operation !== OPERATION.maintenance)`;+- is never passed to `resolveSafeguardTimeoutMs` either. `laneSafeguard` builds+ per-task safeguards from the four task operations. So+ `safeguard_timeout_maintenance_seconds`, documented in+ `docs/brainstorm/release-1-0-stability-trust/design.md:40`, is a config key+ nothing reads.++So one member of a vocabulary the census enforces has no producer on either of+the two surfaces the vocabulary exists to unify.++A second consequence of the lane forwarding: one `o2b brain maintenance run+--progress` emits **four** `finished` records (or four `stopped` records on a+cancel), and there is no lane-level terminator at all. A reader cannot tell+from the stream when the lane is done. The rest of the module argues at length+that one run has one terminator; this surface has four and none.++Confidence: certain (grep over every call site) for the no-producer claims;+high for the four-terminator consequence (read).++---++## PLAUSIBLE++### 13. Four of the six emitters let a throwing sink abort the operation++`src/core/brain/progress.ts:182-200` (`ProgressCounterOptions.onSinkError`),+`:234` (`if (opts.onSinkError === undefined) throw error`).++Only `dream.ts:162` and `architect/generate.ts:287` (via `guardedSink`) supply+a fault reporter. `bridge-discovery.ts:102`, `communities.ts:88`,+`indexer.ts:325` and `vector-backfill.ts:102` all call+`progressCounter(op, sink)` with no options, so per the module's own+documented rule the throw propagates out of the operation.++The docblock two paragraphs above says *"Progress is observation, and an+observation must not be able to destroy the thing observed: a broken edge+stream — a closed pipe, a renderer defect — must not abort a consolidation+pass that is otherwise succeeding."* For four of six emitters it can.++**Failure scenario.** A library or MCP caller supplies its own sink to+`discoverBridges` or `detectCommunities` and it throws (closed pipe, a+serialiser that chokes, a renderer defect). The scan aborts and the CLI+reports `bridges discover failed: …` — a scan that had already done its work.+The same sink handed to `dream` degrades gracefully and reports a+`progress-sink-failed` warning. Two behaviours for one condition.++I did not reproduce this against a live `Store`, and I am not confident that+the *CLI's* own sink can throw in practice (`process.stderr.write` on a closed+pipe usually surfaces asynchronously rather than throwing). The asymmetry+itself is certain from the source; the reachability from the CLI is what I am+marking plausible.++### 14. The dream `plan` stage declares a denominator and never counts toward it++`src/core/brain/dream.ts:211`.++`progress.start(DREAM_STAGE.plan, scan.preferences.length)` is the only+statement about that stage. No `advance(DREAM_STAGE.plan)` exists anywhere;+the next progress call is `start(DREAM_STAGE.apply)`. A caller watching a vault+with 4 000 preferences sees `{"stage":"plan","completed":0,"total":4000}` and+then nothing until planning is entirely over. The `total` is a promise of+granularity that is never delivered — arguably worse than the `walk` stage's+honest absence of a denominator.++The same shape, less severely, applies to `apply`, `log` and `finalize`, each+of which advances exactly once at the end of its span, and to+`vector-backfill.ts:107`'s `plan` stage, which starts and never advances.++Confirmed that no test notices: I replaced the denominator with a literal+`999` and deleted `progress.advance(DREAM_STAGE.scan)` outright — 159 tests+across 9 files still passed.++### 15. The embed phase counts work it has not done yet, against a total nothing verifies++`src/core/search/indexer.ts:936` and `:943`.++`progress?.advance(INDEX_STAGE.embed, batch.length)` runs *before*+`await provider.embed(texts)`. `completed` therefore counts units dispatched,+not units finished, contradicting `ProgressEvent.completed`'s+*"Units finished in this stage so far."* On the last super-batch the stream+reports `completed === total` while a network round-trip is still outstanding —+precisely the moment a watcher would conclude the run is wedged if it then+takes 30 s to return.++Nothing tests the denominator: I doubled it (`pending.length * 2`) and every+progress test still passed.++Related, and worth a second look: `search-index-progress.test.ts:81` asserts+`record["total"]` is `undefined` for *every* record on an+`o2b search index --progress` run. That holds only because the test never+passes `--embeddings`, so the `embed` stage never opens. The assertion reads+as a property of the operation and is in fact a property of the fixture.++### 16. `discoverBridges` emits two `started` events for one stage in one run++`src/core/brain/link-graph/bridge-discovery.ts:103` and `:156`.++The outer `start(BRIDGE_STAGE)` exists so an already-expired guard reports a+stop; the inner `start(BRIDGE_STAGE, candidates.length)` adds the denominator.+On the normal path both fire, so the stream carries+`started:candidates:0` (no total) followed by `started:candidates:0/N`. A+renderer that treats `started` as "a new stage began" shows a restart. `dream`+solved the same problem differently — it opens `scan` once, before the first+checkpoint — so the two emitters disagree about how to express one idea.++### 17. The interrupt handle can leak past its `finally`, and the docblock says that must not happen++`src/cli/brain/verbs/maintenance.ts:157` (`onInterrupt()`), `:167`+(`resolveSearchConfig`, outside the try), `:170` (try begins), `:259`+(`release`).++`InterruptHandle.release` is documented *"MUST be called in a `finally`: the+listeners are process-global, and a verb that returns without releasing leaves+a dead controller wired to the next signal."* In `cmdBrainMaintenance`,+`resolveSearchConfig` runs between the handle's creation and the `try`. If it+throws — an unreadable config, an unresolvable db path — control jumps to the+outer catch and `release()` is never reached. The listeners stay registered for+the remainder of the process, which by finding 2 means the operator's next+Ctrl-C is absorbed instead of terminating.++The exposure is bounded (the CLI process exits shortly after), but it is the+exact hazard the docblock names, in the one verb of the six that got the+ordering wrong.++### 18. `onInterrupt`'s docblock describes behaviour the code does not have and a mechanism that does not work that way++`src/cli/interrupt.ts:71-79`.++*"Deliberately not idempotent across concurrent calls: two overlapping handles+would each register a `once` listener and the first signal would abort only one+of them. … a second handle in the same process is a defect worth failing on+rather than a case to paper over."*++Two problems. First, nothing fails: a second `onInterrupt()` returns a normal+handle. Second, the stated failure mode is not what Node does —+`EventEmitter` dispatches a signal to *every* registered listener, so both+controllers would abort. The comment asserts a property, and both halves of the+assertion are wrong.++This matters concretely in `cmdBrainDream`, which creates `stagedInterrupt`+(`dream.ts:242`) for every action including `run`, releases it, and then creates+a second handle at `:409`. The two are sequential rather than overlapping so+nothing breaks today, but the comment is the only thing standing between that+and a future overlap.++### 19. `EXIT_TERMINATED` is exported and consumed by nobody++`src/cli/interrupt.ts:40`, and `EXIT_FOR_SIGNAL` at `:47`.++`EXIT_TERMINATED` has no importer in `src/` or `tests/` (grep). The SIGTERM+code reaches an exit only through `EXIT_FOR_SIGNAL.SIGTERM`, which is built+from `SIGTERM_EXIT` directly. So the module holds three names for two numbers+(`SIGINT_EXIT`/`EXIT_INTERRUPTED`, `SIGTERM_EXIT`/`EXIT_TERMINATED`, plus the+map). One of them is dead. Minor, but this branch's own standard is that a+declared surface with no consumer is a defect.++### 20. `DreamStageOptions.onProgress` is a declared surface with no producer++`src/core/brain/dream-stage.ts:107`, forwarded at `:252`, `:368`, `:407`.++The field is threaded through all three staged-lifecycle entry points and+documented at length (*"a caller who asked to watch a staged pass watches the+same five stages"*). No caller can ask. `src/cli/brain/verbs/dream.ts:249`,+`:276`, `:285` build `stageOpts` with `now`, `safeguard` and `agentName` only;+`src/mcp/brain/feedback-tools.ts:411` builds `{ now, agentName }` only — and+does not even pass a safeguard, so the MCP staged lifecycle has no deadline+either. `o2b brain dream stage --progress` parses the flag and silently+ignores it.++### 21. The documented CLI stream advertises a `kind` it can never carry++`docs/cli-reference.md:724`, `src/core/brain/progress.ts:66-72`.++The docs describe the `--progress` NDJSON stream as carrying `kind` from+`started | advanced | finished | stopped | refused`. `ProgressCounter` has no+method that emits `refused`; the only producer of that kind is+`src/mcp/progress.ts:161`, and it produces a `ProgressRefusal`, a different+shape on a different transport, never a `ProgressEvent`. A CLI caller writing a+handler for `refused` writes dead code. The same applies to+`PROGRESS_REASON.streamBuffered`, which per finding 11 never reaches a+`ProgressEvent` at all.++### 22. A directory the scan cannot read is silently omitted from the architecture facts++`src/core/brain/architect/scan.ts:190` (`catch { return; }`) and `:203`+(`catch { continue; }` around `lstatSync`).++`walk` swallows `readdirSync` and `lstatSync` failures with no notice, no+warning field, and no progress event. A permission-denied subtree lowers+`totalFiles`, changes `languages`, and can drop a whole module from+`modules[]` — and the generated overview note asserts those numbers as fact.+The early `return` also skips `safeguard?.checkpoint()` for that directory.++This predates the branch, but the branch rewrote `walk` and the surrounding+argument is explicitly about not degrading in silence, so it is worth listing+under the standard being applied.++---++## Checked and found sound++So the absence of a finding above is informative, here is what I examined and+did not fault.++- **Vocabulary hygiene.** `PROGRESS_KIND`, `PROGRESS_KINDS`, `PROGRESS_REASON`,+ `PROGRESS_REASONS`, `OPERATION`, `OPERATIONS` and `PROGRESS_OUTCOME` are all+ frozen, all have complete membership arrays, and all have `unknown`-taking+ guards. `tests/core/brain/progress.test.ts:17-42` asserts freeze,+ completeness and guard behaviour against plausible drift (`"Started"`,+ `"aborted "`), not only obvious garbage. This part is genuinely well built.+- **`total` omission.** `emit` spreads `total` conditionally, so a stage with no+ denominator omits the key rather than emitting `total: undefined`;+ `progress.test.ts:75` asserts `Object.hasOwn` is false, which is the right+ assertion. `assertTotal` correctly rejects negatives and fractions, and does+ so even with no sink attached (`progress.test.ts:116`), so a denominator bug+ is loud whether or not anyone is watching.+- **Sink-detach semantics in `dream`.** The `onSinkError` reporter,+ the one-shot `live = false` detach, and the `progress-sink-failed` warning+ carried out on the summary are correct and tested+ (`dream-progress.test.ts:185`, which asserts `calls === 1` — the detach, not+ just the survival). `architect/generate.ts:264` (`guardedSink`) makes the+ same guarantee across the run's two counters, and its reasoning for not+ using `onSinkError` per counter is right.+- **Byte-identity with no observer.** I could not find a path where attaching+ a sink changes what is written, returned or ordered. `dream`'s only+ behavioural difference is the extra warning on sink failure;+ `generateArchDocs` adds `progressFault` to its result but the CLI spreads+ `progress_fault` into the JSON only when non-null, so the envelope is+ unchanged; the indexer passes the counter into `runEmbeddingPhase` without+ altering the phase's logic. `dream-progress.test.ts:117` compares two copies+ of one seeded vault (rather than two bootstraps) and excludes only the tar+ snapshot and the forensically-stamped workrun journal — both exclusions are+ justified and both are argued in the test. `search-index-progress.test.ts:85`+ checks that `--verbose` output is byte-unchanged when `--progress` is added.+ These are good tests.+- **Rail placement.** Progress on stderr, payload on stdout, and the inversion+ against `advisoryIsLegal` under `--json` are correct and, unusually, the+ branch asserts the *fact the reasoning rests on* — that `withJsonFallback`+ patches stderr as well as stdout (`progress-rail.test.ts:93`). That is the+ right way to keep a docblock from quietly becoming false, and it is a pattern+ the rest of this branch would benefit from copying.+- **NDJSON as the wire shape** and `schema` on every record: the+ `progressRecords` helper selects by discriminator rather than by position, so+ a verb cannot pass by emitting something that merely looks like progress.+- **`progressReasonForError` centralisation** is right, and the argument for+ putting it in the spine rather than at five call sites holds.+- **`throwIfAborted` in the index walk** is the one cancellation seam that can+ actually fire, and `reindexSafeguard` deliberately omitting the signal (so+ the abort travels through `throwIfAborted` alone) is consistent.+- **Terminator coverage on every *return* path.** I traced every `return` in+ `dreamRun` (two, both preceded by `finish()`), `discoverBridgesRun` (the+ no-embeddings early return is inside `withProgress`), `detectCommunitiesRun`,+ `indexIntoRun`, `planVectorBackfillRun` and `generateRun`. Normal returns are+ all covered. It is the *throw* paths (finding 4) and the post-terminator work+ in `reindexVault` (finding 9) that are not.+- **`advance` with a mismatched or unopened stage** throws `RangeError` rather+ than mis-attributing the count — the right call, and it throws whether or not+ a sink is attached, so a stage-name typo is a defect in every run rather than+ only in observed ones.+- **The architect's plan-then-write restructure** (`generate.ts:227` `planNote`,+ `:307` the write loop under one lock) genuinely fixes the half-refreshed-prefix+ problem it claims to, and moving the safeguard checkpoints into the planning+ phase only means an aborted architect run has written nothing. The+ `compareStable` replacement for `localeCompare` is a real determinism fix.+- **The lane's decision not to own a counter** is correct on its merits; my+ objection (finding 12) is to the absence of any lane-level terminator, not to+ the forwarding.+- **Exit codes.** 130/143 are the shell's own `128 + signum` convention, do not+ collide with the codes this CLI already spends (0, 1, and `search check` /+ `doctor`'s 6 for an incomplete probe), and `o2b search watch` correctly keeps+ exiting 0 because stopping is how that command ends. The reasoning in+ `interrupt.ts:20-26` is sound. The problem is not the numbers; it is finding+ 2 — that a run which was asked to stop, and did not, still returns 0.diff --git a/docs/brainstorm/nothing-runs-unwatched/review/tests-and-docs.md b/docs/brainstorm/nothing-runs-unwatched/review/tests-and-docs.mdnew file mode 100644index 00000000..53dfb299--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/review/tests-and-docs.md@@ -0,0 +1,526 @@+# Independent review — tests and documentation++**Branch** `feat/nothing-runs-unwatched` · **base** `main` (`aa818084`) · reviewed at `751fbb17`+(re-checked against `ceb8b1e3`, whose only delta is test-timeout bookkeeping and touches nothing below).++**Scope.** Not whether the features are good — whether the branch's own proof stands up. Every+"CAUGHT" and "MISSED" row below was produced by mutating production code in a throwaway `git+worktree`, running the test, and reverting. Nothing was left in the working tree; the proof is at the+bottom of this document.++---++## 1. Falsification table++The mutation was applied to production code (never to a test) in a scratch worktree at branch HEAD,+the named test was run, and the worktree was restored.++### Breaks the suite caught++| # | Test | What I broke | Caught |+|---|---|---|---|+| 1 | `tests/core/brain/architect.test.ts:216` "the language tie-break does not depend on the host collation" | `compareStable` → `a[0].localeCompare(b[0])` in `generate.ts:55` | ✅ byte diff on the `Languages:` line |+| 2 | `tests/hooks/process-ceiling.test.ts:131` "the self-ceiling fires first, by the stated headroom" | `DEFAULT_HOOK_CEILING_MS = 55_000` | ✅ `Expected 8000, received 55000` |+| 3 | `tests/core/architecture/progress-census.test.ts:116` "every options interface that takes a safeguard takes a progress sink" | deleted `readonly onProgress?:` from `ScanProjectOptions` | ✅ names the interface |+| 4 | `tests/core/architecture/progress-census.test.ts:182` "every stage constant maps to identifier values" | `walk: "walk"` → `walk: "walking the project tree"` | ✅ |+| 5 | `tests/core/install/ownership.test.ts:225` "every writer is either attributed to an entry or excused in writing" | added `src/core/zz-new-writer.ts` doing `writeFileSync(join(homedir(), …))` | ✅ names the file |+| 6 | `tests/cli/doctor-exit.test.ts:71` "a proved failure outranks an unmeasured probe" | swapped the two branches of `doctorExitCode` (`src/cli/main.ts:318`) | ✅ `Expected 1, received 6` |+| 7 | `tests/cli/progress-rail.test.ts:50`, `:115` | `progressIsLegal` → `return true` | ✅ 2 failures |+| 8 | `tests/cli/progress-rail.test.ts:86` "an event kind this build does not know is a defect" | `throw new TypeError(…)` → `return` | ✅ |+| 9 | `tests/core/search/embeddings.concurrency-ceiling.test.ts:26` "Semaphore hands a released permit to the waiter" | restored the pool form (`permits++` on release, `permits--` after await) | ✅ `peak` 1 → 2 |+| 10 | `tests/core/search/embeddings.concurrency-ceiling.test.ts:160` "the ceiling spans the process" | `providerSemaphore` always constructs a fresh `Semaphore` | ✅ 4 failures, incl. `peak` 2 → 4 |+| 11 | `tests/core/bench/failure-modes.test.ts:143` "an always-inject strategy scores worse" | `false_fire_rate: 0` in `scoreProactiveRecall` | ✅ |+| 12 | `tests/core/bench/failure-modes.test.ts:270` "the assertion reads delivered contents" | `isolationViolations` → `[]` | ✅ |+| 13 | `tests/core/discipline/transcripts/scan-states.test.ts` (4 tests) | collapsed `unreadable` into `idle` in `classifyTranscriptScan` | ✅ 4 failures |+| 14 | `tests/mcp/progress-token.test.ts:124` "the response frame is identical with and without a token" | added a field to `result.structuredContent` when a token is present | ✅ |+| 15 | `tests/core/brain/ingest/concurrent-shared-writes.test.ts:100` "every source's content hash survives a four-process race" | removed the lock from `updateManifest` | ✅ 74 of 100 entries lost |+| 16 | `tests/core/vault-backing.test.ts:71` "an unrecognised magic number is undetermined, NOT durable" | unknown magic → `{state: durable}` | ✅ |+| 17 | `tests/core/brain/doctor-exit-census.test.ts:237` | added `EMBEDDING_MODEL_SUNSET_EXTRA_CODE` and pushed it, registering nothing | ✅ names the code |+| 18 | `tests/core/brain/doctor-exit-census.test.ts:298` | `code: ["embedding","model","sunset","computed"].join("-")` | ✅ names the expression |+| 19 | `tests/core/architecture/verdict-vocabulary-census.test.ts:906` | dropped `PROGRESS_KIND.started` from `PROGRESS_KINDS` | ✅ 2 problems reported |+| 20 | `tests/cli/brain-architect-progress.test.ts:45` "writes records to stderr and leaves stdout untouched" | rail writes to `process.stdout` | ✅ 2 failures |+| 21 | `tests/core/brain/maintenance/host-pressure.test.ts:49` "…unmeasurable, not idle" | `platformBlind` → `{state: measured, percent: 0}` | ✅ |+| 22 | `tests/core/brain/doctor/recovery-point-liveness.test.ts:150`, `:161` | `ctx.now.getTime()` → `Date.now()` | ✅ 5 failures, incl. the source scan |+| 23 | `tests/core/search/embeddings.sunset.test.ts:228` | `unsurveyed` → `noneAnnounced` for an off-table model | ✅ 4 failures |+| 24 | `tests/cli/cli.test.ts:226` "byte-identical opt-out" | `--readiness` writes an extra line into the base output | ✅ prefix check fails |+| 25 | `tests/core/brain/config-template-ratchet.test.ts:275` | `commented-example` emitted `live` | ✅ 3 failures |+| 26 | `tests/core/brain/sessions/dry-run-honesty.test.ts:77` | `write_mode` always `applied` | ✅ 2 failures |+| 27 | `tests/mcp/long-running-tools.test.ts:122` "brain_bridges discover aborts once its deadline has passed" | removed `safeguard:` from the MCP handler | ✅ |++### Breaks the suite MISSED — a green run over broken code++| # | Test that should have caught it | What I broke | Result |+|---|---|---|---|+| A | `progress-census.test.ts:116` | `export interface ScanProjectOptions` → `export type ScanProjectOptions = {` **and** the sink deleted | ❌ 6 pass, 0 fail |+| B | `progress-census.test.ts:116` | `readonly safeguard?:` → `safeguard?:` **and** the sink deleted | ❌ 6 pass, 0 fail |+| C | `progress-census.test.ts:160` | `progress.advance(ARCHITECT_STAGE.walk)` → ``progress.advance(`walking the project tree`)`` | ❌ 6 pass, 0 fail |+| D | `progress-census.test.ts:204` | sink retyped as an async sink split across three lines (`) => Promise<void>;`) | ❌ 6 pass, 0 fail |+| E | `ownership.test.ts:225` | new module writing to `homedir()` through the repo's own `atomicWriteText` | ❌ 15 pass, 0 fail |+| F | `ownership.test.ts:225` | new module writing to `process.env["HOME"]` via `writeFileSync` | ❌ 15 pass, 0 fail |+| G | `verdict-vocabulary-census.test.ts` | new `src/core/zz-new-vocab.ts` with a duplicate value, a phantom member and a guard that accepts anything | ❌ 63 pass, 0 fail |+| H | `progress-token.test.ts:124` "the response frame is **identical**…" | `result.content` replaced wholesale when a progress token is present | ❌ 1 pass, 0 fail |+| I | **the entire `tests/mcp` + progress suite** | reverted this branch's own fix `354cbd19` — `dispatchByView` drops `onProgress` again | ❌ **882 pass, 0 fail** |+| J | `concurrent-shared-writes.test.ts:250` "the manifest stays parseable JSON" | lock removed from `updateManifest` | ❌ passes while 74 entries are silently lost |++---++## 2. Findings, most severe first++### F1 — A fix made *inside this branch* has no test; reverting it leaves 882 tests green — CONFIRMED++`src/mcp/brain/shared.ts:204` · commit `354cbd19` "fix(mcp): the view dispatcher forwards the sink instead of dropping it"++```ts+ return handler(ctx, args, onProgress);+```++Changing that one line back to `return handler(ctx, args);` — i.e. re-introducing exactly the defect+the branch found and fixed — leaves `bun test tests/mcp tests/cli/progress-rail.test.ts+tests/core/architecture/progress-census.test.ts` at **882 pass / 0 fail**. `grep -rn dispatchByView+tests/` returns nothing. `tests/mcp/long-running-tools.test.ts:244` exercises `brain_maintenance`'s+own fan-out, not the view dispatcher.++The consumer that made the fix necessary is `brain_brief` `view: "operator"`+(`src/mcp/brain/brief-tools.ts:495` → `:368`, which forwards the sink into a dry-run `dream`). No+test sends a `progressToken` to `brain_brief`. This is the single most important gap on the branch:+the release's whole argument is that a silent stream and a working stream must be distinguishable,+and the one regression that would collapse them again is undetectable by its own suite.++### F2 — The progress census has four syntactic bypasses — CONFIRMED++`tests/core/architecture/progress-census.test.ts:92`, `:116`, `:160`, `:204`++**Population it claims to cover:** "an interface that takes a safeguard takes a progress sink, or+carries a written reason why it cannot" (`:16-17`), plus "every `stage:` literal handed to the+counter is an IDENTIFIER" (`:21`) and "the sink type is synchronous" (`:26`).++**What it actually enumerates:** files under `src/` whose text contains the literal `safeguard?:`+(`:122`), then regions opened by `/(?:export\s+)?interface\s+(\w+)[^{]*\{/` (`:94`) whose body+matches `/\breadonly safeguard\?:/` (`:124`); for stages, only files containing the literal+`progressCounter(` (`:169`), scanned by `/\bstart\(\s*(?:[A-Z_]+\.\w+|"([^"]*)")|advance\(\s*"([^"]*)"/`+(`:165`); for sync-ness, single lines containing both `onProgress?:` and `Promise<` (`:213-214`).++Four things a future contributor could write that it would miss — each verified green above:++1. **A type alias instead of an interface** (row A). `type FooOptions = { readonly safeguard?: Safeguard }`+ with no sink is invisible: `interfaceBlocks` only matches the `interface` keyword. This is not+ exotic — it is the normal TS alternative and reviewers do not distinguish them.+2. **`safeguard?:` without `readonly`** (row B). The file filter at `:122` matches, the block filter+ at `:124` does not, so the interface is not even counted in `guarded`.+3. **A template-literal or single-quoted stage** (row C). ``advance(`walking the project tree`)``+ sails through; the very prose the census exists to ban is admitted by the quoting style.+ Additionally, only files that *call* `progressCounter(` are scanned at all, so a helper that+ receives a `ProgressCounter` as a parameter and emits from another module is out of the population+ entirely.+4. **A multi-line async sink** (row D). The check is line-based, so+ `readonly onProgress?: (\n event: ProgressEvent,\n) => Promise<void>;` passes — and so would any+ sink typed through a named alias.++Two further weaknesses that need no experiment: `interfaceBlocks` walks braces without skipping+string or comment content, so a `"{"` in an interface body mis-terminates the block and silently+re-attributes members; and the `readonly onProgress?:` check is purely declarative — an interface can+declare the sink and never call it and the census is satisfied.++The exemption discipline is also thinner than it reads: `:154` only requires+`reason.length >= 80` and the absence of "TODO"/"for now"/"later". Eighty characters of plausible+prose is not a high bar for an exemption that disables the rule for one interface.++### F3 — The ownership completeness census misses the repository's own write idiom — CONFIRMED++`tests/core/install/ownership.test.ts:167`, `:190`, `:150`++**Population it claims to cover:** "every module that writes to a home-, XDG- or temp-rooted path"+(`:13-14`), so that "a new out-of-vault location cannot be added without the sentence learning about+it" (`:15-16`).++**What it actually enumerates:** files under `src/`, `hooks/`, `plugins/` (`:150`) whose+comment-stripped source matches an anchor regex (`:158`) **and** matches+`/(?:writeFileSync|appendFileSync|mkdirSync|symlinkSync|copyFileSync|mkdtempSync)\(/` (`:167`).++Two concrete misses, both verified green:++- **Row E — the house atomic-write helper.** `atomicWriteText(...)` / `atomicWriteFileSync(...)` from+ `src/core/fs-atomic.ts` do not appear in `WRITE_RE`. A module that writes into `homedir()` through+ the repository's *documented* durable-write path — the one every config writer uses — is not in the+ population at all. This is the likeliest way the next out-of-vault location gets added.+- **Row F — `process.env["HOME"]`.** The anchor regex (`:158`) knows `homedir()` and `env.home` but+ not `process.env["HOME"]` (which already appears at `src/core/doctor-readiness.ts:367`) or+ `USERPROFILE`.++Lower severity, same shape: `SWEPT_ROOTS` (`:150`) omits `scripts/`, which ships in `package.json`+`files`; deletions outside the vault (`rmSync`, `unlinkSync`, `renameSync`) are not in `WRITE_RE` at+all, so a module that *removes* out-of-vault state is never enrolled; and the comment stripper+(`:176`) also truncates any line after a `//` inside a string literal.++The `expect(sweep().length).toBeGreaterThan(8)` guard at `:222` protects against the regex dying+entirely, which is real value — but it cannot detect a regex that covers eight of the ten families.++### F4 — The verdict-vocabulary census is a consistency check, not a census — CONFIRMED++`tests/core/architecture/verdict-vocabulary-census.test.ts` (whole file; the branch adds 18 entries,+`:691-895`)++**Population it claims to cover:** by name and by placement beside the write-site and doctor-exit+censuses, the repository's closed verdict vocabularies.++**What it actually enumerates:** a hand-written `CENSUS` array of imports. `grep -n+'readdirSync\|readFileSync\|import.meta.dir'` over the file returns **nothing** — it reads no source+at any point. Every other census on this branch derives its population from the tree; this one does+not, and its docblock does not say so.++Row G: I added `src/core/zz-new-vocab.ts` carrying a frozen object with a duplicate value, a+membership list naming a member no value declares, and a guard that accepts every string — three of+the exact defects `auditVocabulary` exists to detect — and the file ran **63 pass / 0 fail**. Nothing+in the repository requires vocabulary #82 to be registered. The idiom's durability rests entirely on+authors remembering, which is the property the branch's own CHANGELOG argues is insufficient ("a+mechanism which must be called by hand is a mechanism that will be missed").++The drift tests at `:701-767` ("the census itself catches drift") are genuine and I confirmed one of+them by mutation (row 19). They prove `auditVocabulary` works; they do not prove the registry is+complete.++### F5 — The MCP byte-identity claim does not measure the field a client reads — CONFIRMED++`tests/mcp/progress-token.test.ts:73-79`, `:124`++```ts+function stripRunId(frame: JsonObject | undefined): string {+ const clone = JSON.parse(JSON.stringify(frame)) as Record<string, any>;+ delete clone["result"]["content"]; // ← the whole rendered payload+ delete clone["result"]["structuredContent"]["run_id"];+ return JSON.stringify(clone);+}+```++The file header claims (`:13`) "a call with no token is byte-identical to the call the previous+release made, which is what makes the feature additive". `result.content` is the rendered text an+MCP client actually displays. Deleting the entire array — rather than masking the `run_id` *inside*+it, which is all the justification at `:71-74` argues for — means any other divergence in `content`+is unmeasured. Row H: replacing `content` wholesale with+`[{type:"text",text:"WATCHED-RUN-DIFFERENT-BYTES"}]` whenever a progress token is present leaves the+test green. The fix is a one-line change: normalise the run id inside `content` instead of dropping+the member.++By contrast the same test *does* catch a `structuredContent` divergence (row 14), so the claim is+half-measured, not unmeasured.++### F6 — The hook-ceiling relation test pins the default and leaves the override unbounded — CONFIRMED++`hooks/lib/process-ceiling.ts:67-75` · `tests/hooks/process-ceiling.test.ts:131`++The module docblock (`:35-38`) states the test "asserts the RELATION between the two rather than+either number - so changing one without the other fails there instead of silently disarming the+watchdog again". The test asserts `DEFAULT_HOOK_CEILING_MS === hostMs - HEADROOM` and reads+`hooks/hooks.json`. Two gaps:++1. **`resolveHookCeilingMs` has a floor and no ceiling.** `OPEN_SECOND_BRAIN_HOOK_CEILING_MS=60000`+ returns 60 000 against a 10 s host timeout — precisely the "55 s behind a declared 10 s" state the+ docblock says was the bug — and no test covers it. The relation is enforced for the value nobody+ sets and unenforced for the value an operator can set.+2. **A second, unswept declaration of the same host timeout.** `src/core/install/grok-asset.ts:121`+ hard-codes `timeout: 10` into every hook entry the grok installer writes. The test only parses+ `hooks/hooks.json`, so lowering grok's timeout to 5 while leaving `hooks.json` at 10 keeps the+ suite green with an 8 s self-ceiling behind a 5 s host deadline.++`HOOK_HOST_TIMEOUT_SECONDS` also changes the shipped default from 55 s to 8 s, which is a real+behaviour change for anyone whose hooks legitimately take 10–55 s, and it is documented nowhere (see+F9).++### F7 — README's headline "we deliberately did not build this" claim is now false — CONFIRMED++`README.md:15` (untouched by this branch):++> There is no registry of embedding-provider shutdown dates, because the only way to build one is a+> hand-maintained table over an open set of endpoints that would rot in place and be believed.++`src/core/search/embeddings/sunset.ts:328` ships `EMBEDDING_SUNSET_SURVEY` — a hand-maintained table+of models with `sunsetAt` dates and per-row `source` strings, stamped `reviewedAt: "2026-08-15"`,+consumed by the new doctor check at `src/core/brain/doctor/embedding-sunset-check.ts:241`. The module+concedes the rot problem and works around it with a 365-day expiry+(`EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS`, `sunset.ts:239`) — which is a good design, and is exactly+the thing the README says cannot be built. A previous release's stated refusal is now a shipped+feature and the README still advertises the refusal.++This is the strongest class of stale statement the branch produced: not an omitted flag, but a claim+about the project's judgement that its own code contradicts.++### F8 — `docs/observability.md` contradicts itself on the token-impact vocabulary — CONFIRMED++The branch renames `TOKEN_COUNT_METHOD` from `exact`/`fallback` to `tokenizer`/`heuristic`+(`src/core/brain/token-impact.ts:83-88`; the retired labels survive read-only at `:108-110`), updates+`docs/observability.md:103`, and leaves two sites behind:++- `docs/observability.md:42` — "the `method` label (`exact`/`fallback`)". The same file now says both.+- `docs/mcp.md:155` — "`method` exact/fallback" and "`summary` keeps **EXACT** prompt-token savings".++The advertised MCP input-schema enum is now `["tokenizer","heuristic"]`+(`src/mcp/brain/recall-tools.ts:1176`), so a client written from `docs/mcp.md:155` sends a value the+tool rejects.++Related and unresolved: the `summary` **response** keys moved from `by_method.exact` /+`by_method.fallback` to `by_method.tokenizer` / `by_method.heuristic`+(`src/core/brain/token-impact.ts:445-451` vs `main`). `docs/stability.md:12-16` and `:78-84` classify+renaming a documented response field as breaking, and `docs/updating.md` carries no migration note.+Either the rename needs a note or the policy needs an exception — the current state satisfies+neither. **CONFIRMED** as an inconsistency; whether it is a policy violation is a maintainer call.++### F9 — Six user-visible surfaces this branch adds are documented nowhere — CONFIRMED++Verified by grep across `docs/` and `README.md`:++| Surface | Code |+|---|---|+| Doctor check `recovery-point-liveness` and codes `recovery-point-stale` / `recovery-point-unmeasured` | `src/core/brain/doctor/recovery-point-liveness.ts:65,68`; registered `src/core/brain/doctor.ts:168` |+| Doctor check `embedding-sunset-check` and codes `embedding-model-sunset-announced` / `-unsurveyed` / `-undetermined` | `src/core/brain/doctor/embedding-sunset-check.ts:78-84` |+| Config block `embeddings:` with `sunset_model` / `sunset_at` (both-or-neither), written as a commented example into every new `_brain.yaml` | `src/core/brain/policy/blocks/embeddings.ts`; `src/core/brain/config-template.ts` |+| `embedding_concurrency` is now a **process-wide** ceiling shared per provider endpoint, and two live configs that disagree now **throw** | `src/core/search/embeddings/provider-semaphore.ts:88-104` |+| Install "ownership" close-out block, `install --json` `data_ownership` + a new `schema_version: 1` on the apply payload, `onboarding --json` `data_ownership` | `src/core/install/ownership.ts:296-328`; `src/cli/install/render.ts:39,50,60` |+| Hook self-ceiling default 55 s → 8 s, and the `OPEN_SECOND_BRAIN_HOOK_CEILING_MS` override | `hooks/lib/process-ceiling.ts:46-57,70` |++The precedent the branch itself sets makes the doctor omissions conspicuous: `recall-channel-silent`+/ `recall-channel-unmeasured` got a twenty-line section at `docs/cli-reference.md:678-698` for exactly+this shape of check. `sunset` appears nowhere in `docs/` or `README.md` outside `docs/brainstorm/`.++The `embedding_concurrency` change deserves separate weight: it is a **semantic** change to an+existing operator-facing key (per-call → per-process) plus a new runtime `SearchError` an operator can+now hit, and the key appears in no `docs/*.md` file at all.++### F10 — `docs/cli-reference.md` flag listings drifted inside this branch's own edits — CONFIRMED++- `:836-847` — the `search reindex` block lists `--force-cost`, `--embeddings`, `--concurrency`,+ `--db`, `--verbose`, `--cron-template`, `--interval`, `--self-heal` and **not** `--progress`, while+ `src/cli/search/verbs/indexing.ts:233` parses it and `src/cli/command-manifest.ts:548` declares it.+ The sibling `index` line at `:848` *was* updated in the same commit.+- `:703`, `:116` — the `brain dream` forms carry no `--progress`, while `architect` (`:273`),+ `maintenance run` (`:325`), `bridges discover` (`:335`) and `clusters run` (`:336`) all received it.+ Only the prose at `:724` covers dream, by inference.+- `:261` — "`o2b brain bench memory` … quality, latency, and context cost reported separately" is now+ wrong on three counts: four families not three, `o2b.bench.v2` not v1+ (`src/core/bench/types.ts:23`), and `context_cost.est_tokens` renamed to `avg_injected_tokens`.+ `docs/observability.md:107` was updated for all of it; `cli-reference.md:261` was not.+- `docs/mcp.md:109` — "The MCP surface that can genuinely run for minutes is `brain_dream`,+ `brain_bridges`, `brain_clusters` and `brain_maintenance`." `brain_brief` `view: "operator"` also+ emits (`src/mcp/brain/brief-tools.ts:368`), and its own code comment calls it "the slow half of an+ operator summary on a large vault". A client sending a token to `brain_brief` gets frames the doc+ says it will not. (This is F1's blind spot, seen from the documentation side.)+- `docs/cli-reference.md:328` — "A maintenance gate skip exits 0 so cron never alarms on a quiet+ hour", immediately above the new paragraph introducing `failure_streak_limit`. A task refused by the+ streak limit lands with `ok: false` (`src/core/brain/maintenance/lane.ts:341`) and the verb returns+ 1 (`src/cli/brain/verbs/maintenance.ts:275`). The new paragraph never says the run exits 1, nor+ that task results gained `refused` / `failure_streak` fields. An operator reading the two paragraphs+ in order will be surprised by a cron alarm. — CONFIRMED (the older sentence is still true for gate+ skips; the omission is in the new text).++### F11 — Ctrl-C is a headline documented behaviour with no end-to-end test — CONFIRMED++`docs/cli-reference.md:724` promises: "Ctrl-C (or SIGTERM) now reaches these operations: the run+stops at the next checkpoint and exits **130** (SIGINT) or **143** (SIGTERM) … and a second interrupt+is not intercepted".++What is actually tested:++- `tests/cli/progress-report.test.ts:85,103` calls `onInterrupt()` and then calls+ `reportInterrupted(handle, new SafeguardAbortError(...), …)`. No signal is ever delivered, so+ `handle.received()` is `null` and `exitCode()` returns `EXIT_INTERRUPTED` **by its own fallback**+ (`src/cli/interrupt.ts:97`) — the SIGINT branch of `EXIT_FOR_SIGNAL` is never taken.+- `tests/cli/brain-dream-progress.test.ts:119` asserts `EXIT_INTERRUPTED === 130`, a constant against+ a literal.++`grep -rn SIGINT tests/` shows the only real signal delivery on the branch is+`tests/cli/brain-explorer.test.ts:190`, an unrelated verb. `EXIT_TERMINATED` (143) is referenced by+**no** file in `src/` or `tests/` other than its own declaration. Nothing proves that a real SIGINT+to `o2b brain dream --progress` aborts the pass, that the process exits 130, that SIGTERM exits 143,+or that a second interrupt is not intercepted. The file's own docblock argues a real race would be a+lottery, which is fair — but a `Bun.spawn` + `proc.kill("SIGINT")` after the first progress record+appears on stderr is deterministic and is the pattern `brain-explorer.test.ts` already uses.++### F12 — No CHANGELOG entry and no version bump — CONFIRMED++`git diff main...HEAD -- CHANGELOG.md package.json` is empty. `package.json` is still `1.47.0` and the+newest CHANGELOG heading is `## [1.47.0] - 2026-08-15`, describing the *previous* branch. `CLAUDE.md`+requires the entry, the bump and `bun run scripts/sync-version.ts` **inside the feature PR, before the+first push**, and states plainly why: a forgotten bump means `package.json` and the CHANGELOG heading+disagree on `main` and a second PR is needed. As it stands roughly twenty user-visible surfaces would+ship with no release note.++### F13 — Two tests whose names promise more than their bodies check — CONFIRMED++- `tests/core/brain/ingest/concurrent-shared-writes.test.ts:250` "the manifest stays parseable JSON+ after concurrent writers". Its only body assertion is+ `expect(() => JSON.parse(readFileSync(manifestPath(vault)))).not.toThrow()`. Row J: with the lock+ removed from `updateManifest` and 74 of 100 entries lost, this test passes. It sits directly beside+ a test that *does* catch the same break (row 15), so nothing is lost — but as written it is a+ tautology over any well-formed JSON, including `{}`.+- `tests/cli/brain-architect-progress.test.ts:83` "without the flag nobody is watching, and **the run+ is unchanged**" only asserts `returncode === 0` and zero progress records on stderr. "The run is+ unchanged" is checked in a different test (`:63`, `watched.stdout === warm.stdout`); this one's name+ claims a property it does not measure. The same name and body appear in four sibling files.++### F14 — Weak or self-fulfilling assertions found by a second pass — CONFIRMED unless noted++There are **no** `.skip`, `.only`, `.todo`, `.failing`, `skipIf`, or environment-gated tests anywhere+in the 64 changed test files, and no missing `await` on a `.rejects` (commit `761c1877` fixed the one+that existed). The remaining weak spots:++- `tests/cli/brain-dream-progress.test.ts:99` — the "integers and identifiers only" loop has **no**+ `records.length > 0` guard, unlike all five sibling files (`brain-architect-progress.test.ts:74`,+ `brain-bridges-progress.test.ts:68`, `brain-clusters-progress.test.ts:72`,+ `brain-maintenance-progress.test.ts:94`, `search-index-progress.test.ts:75`). Removing `--progress`+ wiring from `o2b brain dream` entirely leaves it green.+- `tests/cli/install-vault-resolution.test.ts:75,81,100` — `canonical()` is+ `resolveVault(configPath) ?? ""` and `resolveInstallVault(null, configPath)` is+ `resolveVault(configPath) ?? ""` (`src/cli/install/install.ts:137-139`). Three assertions compare an+ expression to itself. The file's docblock claims precedence is "pinned by COMPARISON… so a future+ edit to either chain fails this file"; that is false for those three lines (`:74` and `:80` are+ real).+- `tests/cli/progress-rail.test.ts:125` — `expect(progressIsLegal(s)).toBe(!advisoryIsLegal(s))` under+ `jsonRequested: true` is `X === !(!X)` over one shared helper (`progress-rail.ts:93` vs+ `advisory-rail.ts:87`). It did catch row 7 because the mutation broke the shared expression, but as+ a statement about the two rails agreeing it is a tautology. The `jsonRequested: false` loop at+ `:128` is meaningful.+- `tests/core/brain/token-impact.test.ts:291` "records already on disk under the **old** labels are+ still classified" — the comment says "Exactly what the pre-rename code path wrote" but the two+ appended payloads at `:299` and `:305` use `method: "tokenizer"` / `"heuristic"`, the *new* labels.+ The legacy translation at `src/core/brain/token-impact.ts:420` is never exercised through the+ integration path the test names. A change that filtered legacy rows out of `total_samples` — the+ exact regression named — stays green.+- `tests/core/brain/maintenance/host-pressure.test.ts:107` — every assertion is a `typeof` check or+ `expect([measured, unmeasurable]).toContain(reading.state)` over a two-member closed vocabulary.+ Returning `{platform:"", loadAverage1m:NaN, cpuCount:0}` from the real probe leaves it green.+- `tests/helpers/progress-records.ts:28-33` swallows `JSON.parse` failures with `catch { continue; }`.+ Positive uses are safe; the eleven **negative** assertions built on it+ (`brain-architect-progress.test.ts:68,84`, `brain-bridges-progress.test.ts:62,78`,+ `brain-clusters-progress.test.ts:66,85`, `brain-maintenance-progress.test.ts:82,104`,+ `search-index-progress.test.ts:69,96,115`) would all still read `toHaveLength(0)` if a verb+ regressed to emitting *malformed* progress JSON without the flag.+- `tests/cli/install-json-shape.test.ts:162` runs `toContain("manifest")` against a comma-**joined+ string**, so it is substring matching and `manifest_path` would satisfy it. The other three payloads+ in the file are pinned with exact key sets.+- `tests/core/vault-backing.test.ts:171` "the verdict is a function of the filesystem alone" calls a+ pure function twice with the same stub and compares — tautological for a pure function.+- `tests/core/brain/sessions/adapter-registry.test.ts:81` — bare `.toThrow()` with no matcher, in a+ file that elsewhere matches `/claude/`.+- `tests/core/brain/policy/embeddings-block.test.ts:93-99` throws a sentinel inside the `try` whose own+ `catch` asserts on it; it passes today only because the sentinel text does not contain `sunset_at`.+ PLAUSIBLE, low.++### F15 — Timeout budgets that could mask a hang — PLAUSIBLE, by design++`tests/helpers/cli-timeout.ts:41` sets `CLI_SPAWN_BUDGET_MS = 60_000` and six files call+`setDefaultTimeout` with it (`cli.test.ts:19`, `cli-json-contract.test.ts:11`,+`config-read-failure-surfaces.test.ts:38`, `doctor-exit.test.ts:29`, `install-verb.test.ts:29`,+`run-cli-helper.test.ts:19`), replacing previously targeted 30 s markers. The rationale — measured+cold-spawn cost, no working project-wide knob on bun 1.3.14 — is documented and sound, but the cost is+that a CLI path regressing to a 40 s hang now passes silently across six files.++Three assertions are scheduling-races in the *test*, not in the code:+`tests/core/maintenance/self-heal-reindex.test.ts:126` asserts a detached child has **not** finished+at the instant the parent returned; `tests/core/search/benchmark-concurrency.test.ts:61` asserts exact+saturation equality (`toBe(BENCHMARK_QUERY_CONCURRENCY)`) rather than `toBeLessThanOrEqual` plus a+floor; and the exact `probe.peak` equalities in `embeddings.concurrency-ceiling.test.ts` rest on a+25 ms stub latency. All three are the kind that go red on an unusually fast or unusually loaded+runner.++Two tests `chmod 0o000` a directory (`tests/core/discipline/transcripts/scan-states.test.ts:53`,+`tests/core/brain/doctor/recovery-point-liveness.test.ts:139`). Under a root UID — common in container+CI — the read succeeds and these fail loudly rather than passing silently, so the risk is a red build,+not a false green.++---++## 3. What I checked and found sound++**The re-measured byte-identity claim is legitimate — verified.**+`tests/core/brain/snapshot-gate-coverage.test.ts:227` re-pins the dream-output digest from+`6ef6ceb…` to `1944a334…`, with `_brain.yaml` newly excluded from the row set (`:137-145`). The+comment claims "the replacement literal was taken from `main` with the same exclusion applied, and+this branch reproduces it — so it is still a number from a tree without the units it guards". I tested+that claim directly: I created a worktree at `main` (`aa818084`), copied **this branch's** test file+into it unchanged, and ran it — **16 pass / 0 fail**. The digest is a measurement against a tree that+does not contain the units it guards, not a recomputed expectation. The exclusion argument is also+correct: `_brain.yaml` is bootstrap output that `dream` reads and never writes back.++**Byte-identity claims that hold up.** The architect collation fix is proved the hard way — two child+processes, one with a reversed `String.prototype.localeCompare` installed *before* the generator is+imported, comparing rendered bytes (rows 1 and the test's own note that `LC_ALL` alone cannot prove+it, since `Intl.Collator` resolves to `en-US` regardless). `--progress` leaves `--json` stdout+untouched (row 20). `--readiness` leaves the base doctor output untouched (row 24, prefix check). The+config template's live surface and resolved-behaviour identity are both real (row 25).++**Censuses that are genuinely adversarial.** `tests/core/brain/doctor-exit-census.test.ts` enumerates+its population recursively from `src/core/brain/doctor/`, reads two code shapes, and carries a+separate test for the third shape that neither scan can read — I tried both a new unregistered `*_CODE`+constant (row 17) and a computed `code:` expression (row 18) and it named each one. This is the model+the other three censuses should follow.++**Race tests that are real races.** `tests/core/brain/ingest/concurrent-shared-writes.test.ts` spawns+four genuine `bun` children behind a 1.5 s start barrier; removing the lock from `updateManifest` loses+74 of 100 entries and the test names every one (row 15). The semaphore hand-off test constructs the+exact microtask interleaving the pool form loses (row 9), and the process-wide ceiling tests+distinguish four separate identity axes (row 10).++**Negative controls that are non-vacuous.** `failure-modes.test.ts:250` "the strict gate is what+isolates: without it the same fixture leaks" runs the *shipped default* and asserts the leak, so the+gate assertion elsewhere cannot pass for a reason unrelated to isolation; `:278` asserts the converse+(isolation that withholds the caller's own memory is also a failure). `:197` charges a `faulted`+retriever to neither rate. `progress-census.test.ts:133` and `ownership.test.ts:219` both guard against+a sweep that found nothing.++**Documentation that is accurate.** The architect paragraph at `docs/how-it-works.md:1221-1231` — the+single walk, the dot-directory rule, the exact skip list (`node_modules`, `dist`, `build`, `out`,+`coverage`, `vendor`, `target`, `venv`, `__pycache__`), the two stage names and the per-directory+deadline — matches `src/core/brain/architect/scan.ts:34-44,71,130` and `generate.ts:330` exactly.+`docs/metrics.md:69,75-82` and `docs/updating.md:92-100` describe the `self_heal_reindex` two-process+surface correctly. The MCP progress-token section (`docs/mcp.md:51-118`) is accurate apart from the+"which tools report" list (F10). `docs/observability.md:107` is accurate and thorough about what the+bench numbers do *not* say.++**`docs/architecture.md` correctly left untouched.** It is a layer/adapter/responsibility document+(`:5-27`, `:31-60`); nothing this branch changed contradicts it, and `:45` ("expose readiness+diagnostics") remains true under the fail→unknown reclassification.++**`README.md` NOT correctly left untouched** — see F7. Beyond that, `README.md:11` still opens "Open+Second Brain **1.46.0** is about…" while `package.json` says 1.47.0 (pre-existing on `main`, but this+is the natural branch to fix it), and the branch's headline surfaces — a progress rail on every long+pass, Ctrl-C that actually stops a run, MCP progress notifications — are exactly the shape of change+`README.md:105-120` documents for other releases and are absent. `README.md:108` ("An index that+survives interruption") now reads as the narrow case of a general capability.++---++## 4. Recommended order of work++1. Write a test for `dispatchByView` sink forwarding (F1) — send a `progressToken` to `brain_brief`+ `view: "operator"` and assert notification frames arrive.+2. Fix the four progress-census bypasses (F2): match `type X = {` as well as `interface X {`, drop the+ `readonly` requirement from the field pattern, scan for `advance(`/`start(` in every file that+ imports `ProgressCounter` rather than only those calling `progressCounter(`, and normalise+ whitespace before the `Promise<` check.+3. Add `atomicWrite*` and `process.env["HOME"]` to the ownership sweep (F3); add `scripts/` to+ `SWEPT_ROOTS`.+4. Fix `stripRunId` to mask the run id inside `content` instead of deleting the member (F5).+5. Cap `resolveHookCeilingMs` at `HOOK_HOST_TIMEOUT_SECONDS * 1000`, and sweep+ `src/core/install/grok-asset.ts:121` into the relation test (F6).+6. Correct `README.md:15` (F7), `docs/observability.md:42` and `docs/mcp.md:155` (F8).+7. Document the six undocumented surfaces (F9) and fix the five drifted doc statements (F10).+8. Add one real-signal interrupt test (F11).+9. CHANGELOG entry + version bump + `sync-version.ts` (F12).+10. Enumerate the verdict-vocabulary population from source, or state in the file that it is a+ registry rather than a census (F4).++---++## 5. Proof the tree was left clean++Every mutation above was applied inside disposable `git worktree` copies under the session scratchpad,+never in `/srv/projects/open-second-brain`, and each was reverted with `git checkout --` immediately+after its test run. Both scratch worktrees were removed with `git worktree remove --force` and+`git worktree prune`.++```+$ git status --short+?? docs/brainstorm/nothing-runs-unwatched/review/+```++The single untracked entry is the `review/` directory holding this file. No tracked file in the+repository was modified and nothing was committed.diff --git a/docs/brainstorm/nothing-runs-unwatched/variants.md b/docs/brainstorm/nothing-runs-unwatched/variants.mdnew file mode 100644index 00000000..61ece2d1--- /dev/null+++ b/docs/brainstorm/nothing-runs-unwatched/variants.md@@ -0,0 +1,79 @@+# Variants - audit trail++The consultant was Claude Code, run once with the prompt at+`cli-output/prompt.md` and captured verbatim at `cli-output/claude.md`. It+returned three parseable variants and a recommendation, so the fallback+consultant was not run.++The prompt deliberately carried the **corrected** framing rather than the+tracker's original wording. Reconnaissance had already established that most of+the nine task bodies describe a different system - a daemon that caps model+inference, an ingest that locks too often, a scanner whose cost is in rendering.+Variants generated from those premises would have been variants for another+codebase.++## The three variants, verbatim++See `cli-output/claude.md`. In summary:++1. **The observation spine** - one closed-vocabulary lifecycle event emitted+ from the checkpoint boundaries that already exist, delivered through an+ optional sink on the same options object that already carries `safeguard`,+ with a census enumerating every long operation. Complexity large, risk+ medium. Recommended by the consultant.+2. **The claim census** - take the honesty half of the thesis as the organising+ principle: no user-facing assertion ships unless it is a registered claim+ with a resolver, or a registered refusal naming why it cannot be checked.+ Complexity large, risk high.+3. **Wire what is dead, refuse what is unanswerable, delete what was wrong** -+ no new subsystem and no new vocabulary; pair each unit with the mechanism+ that already exists and either connect it or state by name that it cannot be+ connected. Complexity medium, risk low.++## Decision++**Variant 1, with one correction and one graft.**++### Agreement with the recommendation++The consultant's core argument holds against the source. Units 1, 3 and 4 of the+brief really are one seam: the silent consolidation pass, the dead+`SafeguardAbortError` and the herd of detached reindexes are three symptoms of+the same missing channel, and the checkpoint boundaries where a tick belongs are+already carved. Variant 3's decisive weakness is stated in its own trade-offs -+nine local fixes leave nothing that forces the *next* long operation to speak,+which is the exact failure the previous release argued against and then+committed three instances of.++### The correction++Variant 1 lists "MCP gets no progress at all in this release" as an accepted+cost, treating both transports as non-carriers. That is true of HTTP, which+`res.end`s a single SSE event, and false of stdio. The stdio frame writer is+private but reachable, and a third **optional** handler parameter does not force+edits at the 88 registration sites, because a handler declaring two parameters+satisfies a type declaring three. So stdio carries real progress notifications+and HTTP carries a typed refusal. Accepting the consultant's cost here would+have shipped a smaller capability than the codebase supports, and - worse -+would have left the discarded `_meta.progressToken` discarded, which is the+silent-drop defect this release exists to attack.++### The graft++Variant 3's per-unit discipline is kept in full: every unit lands inside a+mechanism this repository already enforces. The maintenance lane's existing gate+set, lease and typed journal carry the pressure gate rather than a new+scheduler. The `agent-backend` registry shape carries the ingest adapters rather+than a second registry idiom. The doctor code census carries the sunset check.+The write-site census's syntactic technique carries the progress census. This is+what the operator's "maximally native integration, no crutches" constraint+means in practice, and Variant 1 alone would have permitted a parallel idiom.++Variant 2 was rejected on evidence rather than on taste. Its own trade-offs+predict "a registry with more refusals than resolvers", and reconnaissance+confirms that prediction: of the claims it would register, the environment+class, the vendor name, the host load average and the exact token count are all+unanswerable in this codebase. A registry whose majority is refusals is a+correct description of the problem and a poor mechanism for fixing it. Its best+idea survives inside Variant 1 anyway - the `refused` member of `PROGRESS_KIND`+gives the unanswerable cases one shared, typed home.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 16a51943..7196b710 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -58,6 +58,56 @@ that can produce it - see [`install/copilot-cli.md`](../install/copilot-cli.md).Every other adapter verifies off disk, so it can report `ok`, `drift`, or`not-installed` but never `mcp-unreachable`.+### `o2b doctor` exit codes++| Code | Meaning |+| ---- | -------- |+| `0` | Every check passed, and with `--readiness` every probe answered |+| `1` | At least one check FAILED, or with `--readiness` at least one probe proved its surface broken |+| `6` | With `--readiness`: no check failed, and at least one probe could not find out |++Code `6` is a behaviour change for `--readiness` runs and is deliberately+the number `o2b search check` already spends on a probe that did not+complete; a test asserts the two cannot drift. A probe that exceeded its+per-check budget used to be counted as a failure and exit `1`, so the same+healthy machine exited `0` when idle and `1` when loaded - the verdict was+a property of the load average rather than of the installation. Such a+probe now reports `unknown` with the elapsed budget as its reason, and an+unmeasured surface is not folded into the `0` that would claim it was+checked either. A proved failure outranks an unmeasured probe, so `1`+never hides behind `6`.++The `--json` shape gains `readiness_summary` (`probes`, `failed`,+`unknown`) beside the existing `readiness` array whenever `--readiness` is+passed, so a caller reads the same three-way answer the exit code carries;+`ok` is read off that exit code, and being two-valued it means only "not+established as healthy" when false.++### The codegraph partner check++`o2b doctor` consults the optional [codegraph](https://github.com/colbymchenry/codegraph)+partner when its CLI is on PATH and the working directory is a code+project, by spawning `codegraph status -j <repo>` once per discovered+project. That costs about 0.7 s against a warm `HOME` and about 5 s+against a cold one, because the partner caches under `HOME`.++`partner_codegraph_disabled: "true"` in the config file, or+`OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED=true` in the environment,+turns that consultation off. Default off, so the doctor behaves exactly as+before unless the switch is set. It is a config key rather than a flag+because the fact it records ("the partner is installed on this machine and+asking it costs seconds") is a property of a machine, and because the+three callers of the doctor include the MCP `vault_health` tool and the+OpenClaw extension, which take no flags. `o2b partner codegraph report` is+unaffected: an answer the operator asked for directly is never suppressed+by a switch about background cost.++A doctor run with the switch on still prints a `code_graph` line saying+which switch silenced it, so a check that did not run is distinguishable+from one that ran and passed. A machine with no codegraph CLI, and a+directory that is not a code project, still both print nothing at all -+those two remain indistinguishable from each other in the doctor's output.+## Brain (observing memory)```text@@ -220,7 +270,7 @@ o2b brain git ingest <repo-path> [--max-count N] - read-only walstatus - per-repo watermarks and record countsfind [text] [--repo K] [--file F] [--author A] [--since S] [--until U] [--limit N] - query ingested history newest-first; no live git on the query pathmine [--repo K] - surface decision-shaped commits as draft ADR candidate notes under Brain/decisions/candidates/ (sha-stable identity, skip-existing)-o2b brain architect <project-path> - deterministic stdlib-only project scan rendered as architecture notes under Brain/projects/arch/<repo-key>/; generated content lives in o2b:begin/o2b:end sentinel regions, operator prose outside regions survives every re-scan byte-for-byte+o2b brain architect <project-path> [--progress] - deterministic stdlib-only project scan rendered as architecture notes under Brain/projects/arch/<repo-key>/; generated content lives in o2b:begin/o2b:end sentinel regions, operator prose outside regions survives every re-scan byte-for-byte```All flags accept `--vault V` and `--json`. The ingest never modifies the scanned repository; every caller-supplied sha is validated against the full-40-hex grammar before it can reach a git argument.@@ -272,16 +322,18 @@ o2b brain label <path> <dimension>=<value> | --remove <dimension>o2b brain attr <path> <field>=<value> | --remove <field> | --show - per-type attribute fields; an undeclared field error lists the declared fields WITH descriptionso2b brain tiers check | restore <path> [--field F] --apply | accept <path> [--field F] - staged repair for identity-tier frontmatter hand-editso2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] | list | rm <name> | run <name> -- <command...> - capability-gated custody; the value enters via stdin, never argv-o2b brain maintenance run [--force] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] | status [--limit N] - quiet-window lease-guarded lane for dream + reindex+o2b brain maintenance run [--force] [--retry <task>] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] [--progress] | status [--limit N] - quiet-window lease-guarded lane for dream + reindex```The schema pack gains four additive ontology fields (`labels`, `link_constraints`, `attributes`, `frontmatter_tiers`) with audited mutations through `o2b brain schema apply`. Link constraints enforce at index materialization: a typed edge whose endpoint page types violate the declared pairs falls back to an untyped link, `o2b brain schema lint` lists each violation, and removing the constraint restores the edges on the next index run. Tier drift detection rides the same index pass - the snapshot keeps the expected value, so reindexes never absorb a hand-edit, and `brain_doctor` warns with the open count. Filter labelled recall with `o2b search <q> --property labels=<dim>/<value>`. Secrets protect against context leakage and vault sync exposure, not against root; every custody operation lands a no-values record in `Brain/log/secret-custody/`. A maintenance gate skip exits 0 so cron never alarms on a quiet hour.+The lane's two vault-side knobs live in `Brain/_brain.yaml` under `maintenance:`, because they answer what the cron line cannot. `host_pressure_percent` adds a fourth gate: skip when the host's one-minute run queue stands at or above that percentage of the CPUs this process may use. Unset by default, which leaves the gate off. Where the metric is degenerate - a platform whose load average is a constant, or a cgroup with a CPU bandwidth quota, where the run queue is the whole host's - the gate stays **open** and the journal carries a separate `pressure:unmeasurable` row naming the reason, so an unreadable host is never reported as a quiet one. `failure_streak_limit` (default 3) refuses a lane task that has failed that many times in a row in the run journal, naming the streak; a single journaled success clears it. The refusal is per task - the other three still run under the same lease - and there are two ways past it: `--retry <task>` (repeatable) attempts just that task with every gate the operator configured still in force, and `--force` runs the whole lane past every soft gate and every refusal. A refused task is reported as `REFUSED`, never `FAILED`, and the run exits **7** rather than 1: nothing was attempted, so nothing failed, but a standing refusal is not the quiet hour that exits 0 either. An attempted failure still exits 1 and outranks a refusal in the same run. The `refused:streak` journal row carries the count it refused on, so the streak does not silently reset when its evidence rolls off the journal cap.+### Link and recall intelligence (since v0.45.0)```text-o2b brain bridges discover [--max N] [--min-similarity X] | list | accept <source> <target> | dismiss <source> <target> - embedding-near link proposals over the vec index, reviewable artifact, accept writes one related: wikilink-o2b brain clusters run [--min-size N] [--batch-size N] [--if-stale] | list - graph-wide community detection; derived digests under Brain/clusters/, regenerated per run; --batch-size materializes in chunks with isolated, reported per-batch failures; --if-stale recomputes only when the freshness verdict is not `fresh` (see "Materialization freshness" below)+o2b brain bridges discover [--max N] [--min-similarity X] [--progress] | list | accept <source> <target> | dismiss <source> <target> - embedding-near link proposals over the vec index, reviewable artifact, accept writes one related: wikilink+o2b brain clusters run [--min-size N] [--batch-size N] [--if-stale] [--progress] | list - graph-wide community detection; derived digests under Brain/clusters/, regenerated per run; --batch-size materializes in chunks with isolated, reported per-batch failures; --if-stale recomputes only when the freshness verdict is not `fresh` (see "Materialization freshness" below)o2b brain vitals [--orphan-threshold N] - aggregate governance scorecard over confirmed preferences: domain_diversity (scope entropy), connectivity_index (mean evidenced_by count), orphan_preferences (below threshold, default 2), gap_pressure (open concept-gap findings ÷ preference count, reused from doctor); records the vault_vitals metrico2b brain benchmark run --dataset <path> [--k N] [--expand] - hit@k + MRR against the live hybrid recall; records the recall_benchmark metrico2b brain tune run --dataset <path> [--k N] | status | reset - bounded self-tuning grid judged by the benchmark; persisted to Brain/search/tuning.json@@ -356,7 +408,7 @@ not be read.### Trusted recall and memory write surface (since v1.35.0)```text-o2b doctor gains --readiness: four functional probes (model-inference key resolvable, embedding provider loadable with model and dims, runtime-adapter construction, installed runtimes verified off disk through each adapter's own verify) with per-check timeouts and outcomes pass, fail with a reason, skipped-not-configured, or unknown-could-not-measure; a failure exits non-zero and an unknown does not; without the flag output stays byte-identical+o2b doctor gains --readiness: four functional probes (model-inference key resolvable, embedding provider loadable with model and dims, runtime-adapter construction, installed runtimes verified off disk through each adapter's own verify) with per-check timeouts and outcomes pass, fail with a reason, skipped-not-configured, or unknown-could-not-measure; a failure and an unmeasured probe exit with different non-zero codes (see "`o2b doctor` exit codes" below); without the flag output stays byte-identicalo2b brain morning-brief renders recalled items as one chronological Recent activity timeline with a per-item structural type marker and a relative age label; the underlying JSON data arrays are unchanged```@@ -667,7 +719,23 @@ Verbs that carry it today: `o2b status`, `o2b brain init`, `bridges list|discove**When there is no command.** About two thirds of the doctor's issue codes resolve to none, because the repair is a judgement over content or an edit whose target shape the finding cannot supply. Those are not silent: `o2b brain doctor` prints `no exit: <code> - <reason>` once per reported code, and `--json` (and MCP `brain_doctor`) carries the same reasons in an additive `no_exit` object beside the issue streams - once per code rather than repeated on each record, because a reason is about a class. Every doctor code is one or the other; `tests/core/brain/doctor-exit-census.test.ts` enumerates them from the detector and fails on a code that is neither, so an unregistered code can no longer mean "nobody got round to it". The key and the lines are absent whenever every reported code has an exit, and on a clean vault.-Long-running operations (dream, `o2b search index | reindex`, bridges discover, clusters run, the maintenance lane) run under a cooperative safeguard deadline: `safeguard_timeout_seconds` (default 600, `0` disables, env `OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`) with per-operation overrides like `safeguard_timeout_dream_seconds`. A tripped deadline aborts at the next checkpoint - between atomic writes - and reports `{ok:false, timed_out:true}` on exit 1; maintenance-lane task results carry `timed_out` per task. The frozen-surface policy lives in `docs/stability.md`; the 0.x to 1.0.0 migration table in `docs/updating.md`.+Long-running operations (dream, `o2b search index | reindex | vector-backfill`, bridges discover, clusters run, architect, the maintenance lane) run under a cooperative safeguard deadline: `safeguard_timeout_seconds` (default 600, `0` disables, env `OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT`) with per-operation overrides like `safeguard_timeout_dream_seconds`. A tripped deadline aborts at the next checkpoint - between atomic writes - and reports `{ok:false, timed_out:true}` on exit 1; maintenance-lane task results carry `timed_out` per task. The frozen-surface policy lives in `docs/stability.md`; the 0.x to 1.0.0 migration table in `docs/updating.md`.++**Watching one.** The same verbs take `--progress`, which writes one newline-delimited JSON record per checkpoint to **stderr** - `{"schema":"o2b.progress.v1","operation":…,"kind":…,"stage":…,"completed":N}`, where `kind` is `started`, `advanced`, `finished` or `stopped`, and `total` is present only where a denominator is known before the loop starts (the embedding phase knows its pending count; the index walk consumes a generator and cannot). A CLI progress stream never carries `refused` - no counter emits it; it is an MCP-only shape on a different transport, so a CLI reader that handles it writes dead code. `stage` is an identifier from the operation's own phase vocabulary, never a sentence. Stdout is untouched, so a `--json` payload is byte-identical with and without the flag, and `o2b search index --verbose` keeps its separate per-file stream unchanged - the two answer different questions. Progress is opt-in for the same reason `--verbose` is; when a stream cannot carry it the verb says `progress: not emitted (<reason>)` rather than writing into a buffer nobody will read in time. `o2b brain maintenance run --progress` forwards the stream of whichever task is running rather than counting its own four steps, so every record names the operation that emitted it. `o2b search reindex --progress` opens a `lock` stage before it waits for the writer lock (that wait can be the length of a competing rebuild) and does not report `finished` until after the `swap` stage that renames the staging build over the live index - the run is not over when the build is. `o2b search vector-backfill --progress` reports under `reindex` too, because the pass IS that run's embedding phase on its own: a `plan` stage while it counts, then the shared `embed` stage with the pending count as its denominator.++Which emitters those verbs actually have is not taken on trust. `tests/cli/progress-emitter-census.test.ts` enumerates every `progressCounter(` call site in `src/` from the source, maps each to the entry point that reaches it, then RUNS each entry point against a fixture and requires records carrying that site's operation and stage to arrive with a terminator. A call site no entry point reaches is a failure, which is how `vector-backfill` - which had grown the whole spine in core with no flag to reach it - was found.++**Stopping one, and what Ctrl-C actually does.** This differs per verb, and the difference is a property of the operation rather than a gap in the wiring. A cooperative interrupt is delivered to a JavaScript signal handler, and a signal handler runs on the event loop; an operation that never yields to the event loop therefore cannot observe one, and merely *registering* a handler would suppress the default terminate and make the keystroke do nothing at all.++| Verb | Ctrl-C / SIGTERM |+| --- | --- |+| `o2b search index`, `o2b search reindex` | Stops the run at the next checkpoint - between files, between embed batches, never mid-write - and exits **130** (SIGINT) or **143** (SIGTERM). A stopped rebuild leaves the live index exactly as it found it, because the staging build is abandoned before the swap. |+| `o2b search vector-backfill` | Stops **between embed batches** and exits **130** / **143**; vectors already written stay written, because each chunk commits as it is computed. The dry run and the planning query are synchronous SQLite between two awaits, so a keystroke landing there is not observed at a checkpoint - it ends the process on release instead, which is the same outcome the un-suppressed keystroke would have had. |+| `o2b brain maintenance run` | Stops the lane at a task boundary and exits **130** / **143**. The lane journals the stop and releases its lease, so the vault is never left leased. |+| `o2b brain dream` (including `stage`/`validate`/`apply`), `o2b brain bridges discover`, `o2b brain clusters run`, `o2b brain architect` | **Terminates the process immediately**, the ordinary shell behaviour. These four passes are synchronous end to end, so no cooperative stop is possible and none is claimed. Every artifact they write is written atomically, so a killed pass leaves no half-written note - it leaves the vault as it was before the pass, or after the last completed write. Their deadline (`safeguard_timeout_*_seconds`, above) is the only cooperative stop they have. |+| `o2b search watch` | Exits **0**, unchanged: stopping is how that command ends. |++For the two verbs that do hold a handle, a second interrupt is not intercepted and falls through to the default handler, so a wedged run is always killable by pressing the key twice. And an interrupt that arrives while such a verb is in a region with no checkpoint - opening a store, writing a report - is not swallowed: the verb prints `interrupted: SIGINT arrived while … stopping now` and ends with the signal's code rather than returning 0. A run the operator stopped never exits 0.## Vault scope@@ -788,7 +856,12 @@ o2b search reindex Rebuild the SQLite + FTS5 index from scratch--interval <N>m|h|d sets that recipe's cadence, default 30m; an intervalcron cannot express (seconds, 60m+, 24h+, 28d+) is refused with thereason rather than rendered as a schedule that means something else-o2b search index Incrementally update the index; --embeddings computes vectors+ --self-heal <run-id> records this run's terminal outcome (or its+ failure, by name) on the self_heal_reindex metrics surface under that+ id; set by the detached post-upgrade rebuild, whose streams are all+ ignored, and whose parent mints the id so the two rows pair without a+ machine-local pid+o2b search index Incrementally update the index; --embeddings computes vectors, --progress watches it--force-cost bypasses the embedding cost gate (since v0.36.0)o2b search vector-backfill Run the vector phase ALONE for indexed chunks that have no vector -no vault walk, no re-chunking, no frontmatter pass (since v1.43.0).@@ -796,6 +869,7 @@ o2b search vector-backfill Run the vector phase ALONE for indexed chunks thatconfigured semantic capability tier, and contacts no provider.--apply is the only path that reaches a provider or writes a vector--force-cost bypasses the embedding cost gate for that run+ --progress watches it; Ctrl-C stops it between embed batches--json emits dry_run, capability_tier, capability_code, chunks_total,pending, embedded, retries, plus estimated_cost_usd only when themodel's price is known - a missing price is an absent key, never 0@@ -941,7 +1015,17 @@ is the same one the cost gate uses, applied to the text as it will be sent(instruction prefix included). With the key unset the field is absent andbatching is byte-identical to the fixed `embedding_batch_size` stride; asingle text whose own estimate exceeds the budget is sent alone rather than-dropped or split. `search_fusion_mode`+dropped or split.+`embedding_concurrency` (`OPEN_SECOND_BRAIN_EMBEDDING_CONCURRENCY`, default 4)+bounds embedding requests in flight for one embedding identity - provider,+model and configured dimension - against one resolved endpoint, across the+whole process rather than one call. Two models configured against the same+host are two identities and therefore two budgets, so that host sees up to+`embedding_concurrency x identities` at once: size the knob against the+budget the provider actually meters. Two configurations that ask for+different values on the same identity and endpoint are refused by name+rather than reconciled to one of them.+`search_fusion_mode`(default `linear`) may be set to `rrf` to fuse the keyword and semanticlanes by reciprocal rank (`search_rrf_k`, default 60); `linear` keepsranking bit-identical.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 34b937e5..bc1d9ab5 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -1218,7 +1218,16 @@ notes under `Brain/projects/arch/<repo-key>/`. Generated contentlives between paired `<!-- o2b:begin <id> -->` / `<!-- o2b:end <id>-->` sentinels: regeneration replaces only generated bodies, operatorprose outside regions survives byte-for-byte, and corrupted markers-fail closed before any write. The same release also closes the+fail closed before any write - every note of a run is decided before+the first one is written, so an abort leaves no half-refreshed+prefix. The tree is walked exactly once, and the walk enters no+dot-directory and no build or dependency output (`node_modules`,+`dist`, `build`, `out`, `coverage`, `vendor`, `target`, `venv`,+`__pycache__`); architecture notes describe source, not tooling+state. A run reports its two stages - `walk`, a counter with no+denominator, and `render`, which knows its note count - through the+progress spine, and honours a safeguard deadline at each directory+read. The same release also closes theobservability gap v0.39.0 left open: `brain_query` now emits opt-inrecall telemetry with a kind-only payload, so the supplied preferenceid, topic, or timestamp never lands in a continuity record.diff --git a/docs/mcp.md b/docs/mcp.mdindex 7986d718..0c9570b2 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -48,6 +48,100 @@ schemas are out of scope for that audit - their vocabulary declaresunion-typed fields with no `type` on purpose, and responses are validatedagainst them at request time instead.+### Progress notifications++A client asks for liveness on a long call by putting a token on the+request, `params._meta.progressToken`. Per the specification the token is+a string or an integer; anything else — a boolean, `null`, an object, a+fractional number — is refused with `-32602` naming what arrived, rather+than coerced into a value the client could not match back to its request.+A request with no `_meta`, or a `_meta` carrying other members but no+`progressToken`, asks for nothing and is answered exactly as before.++**What each transport does with the token:**++| Transport | With a token | With no token |+|---|---|---|+| stdio | Emits `notifications/progress` frames as the operation runs, all of them ahead of the response frame | No notification frames at all |+| HTTP | Answers the call normally and carries a typed refusal on `result._meta` | No `_meta` on the result |++stdio owns a duplex newline-delimited stream, so it can write a frame+nobody asked for. Each frame carries the spec's own `progressToken`,+`progress` and (when the operation knows a denominator) `total`, so a+client that knows nothing about Open Second Brain still renders a bar.+The typed event travels beside them under+`params._meta["open-second-brain/progress"]`: `schema`, `operation`,+`kind`, `stage`, `completed`, optional `total` and `reason`. `stage` is+an identifier from the emitting operation's own vocabulary, never a+sentence — the sentence is rendered at the edge.++The HTTP transport answers one request with one response and closes it+(see "Run from the CLI" below), so it cannot carry a notification at all.+Accepting the token and silently dropping the events would advertise+liveness support that does not exist, so the response carries a refusal+instead:++```json+{+ "result": {+ "content": [ ... ],+ "structuredContent": { ... },+ "isError": false,+ "_meta": {+ "open-second-brain/progress": {+ "schema": "o2b.progress.v1",+ "kind": "refused",+ "reason": "transport-single-response",+ "progressToken": "tok-42"+ }+ }+ }+}+```++It rides on `_meta` — MCP's reserved place for implementation metadata,+and the reciprocal of where the request carried the token — because the+two alternatives corrupt a payload a caller parses: `structuredContent`+is validated against the tool's `outputSchema`, and `content[0].text` is+that same payload rendered. The refusal is visible to a client that asked+for progress and entirely absent for one that did not.++**Which tools report.** The MCP surface that can genuinely run for+minutes is `brain_dream`, `brain_bridges`, `brain_clusters` and+`brain_maintenance`. Index management verbs (`index`, `reindex`,+`check`) are deliberately not exposed over MCP, so they are not on this+list. `brain_maintenance` is a dispatcher over the other four+operations and forwards the sink to each task, so its events name the+task that emitted them (`dream`, `reindex`, `bridges`, `clusters`) rather+than the lane. Two more reach a consolidation pass without carrying its+name and report on the same terms: `brain_brief` with `view: "operator"`,+whose operator summary runs a dry-run pass, and+`brain_review_candidates`, whose projection is that same dry run+reshaped.++**Which tools are bounded.** Every call that reaches one of those long+operations runs under a cooperative deadline resolved from+`safeguard_timeout_<operation>_seconds`, then `safeguard_timeout_seconds`,+then the built-in default. Bounded and observed are the same population,+with one stated exception — the row below marked **none**:++| tool | long operation it reaches | deadline | reports |+| --- | --- | --- | --- |+| `brain_dream` (`run`) | `dream`, twice when `expect`/`strict` asks for a guard preview | `dream` — one budget for the whole call, preview included | yes |+| `brain_dream` (`stage`/`validate`/`apply`) | `dream`, through the staged bundle | `dream` | yes |+| `brain_dream` (`step`) | one step (`scan` or `heal-enrich`), not a pass | **none** — the step functions take no guard | no |+| `brain_bridges` (`discover`) | `bridges` | `bridges` | yes |+| `brain_clusters` (`run`) | `clusters` | `clusters` | yes |+| `brain_maintenance` (`run`) | all four, sequentially | one fresh guard per task; a tripped task is a `timed_out` row, not an aborted call | yes, in its tasks' voices |+| `brain_brief` (`view: "operator"`) | `dream`, dry run | `dream` | yes |+| `brain_review_candidates` | `dream`, dry run | `dream` | yes |++The deadline is cooperative, not preemptive: `dream()` and the graph+sweeps are synchronous, so nothing can interrupt them from outside — past+the deadline the operation's next checkpoint throws, at a boundary where+writes are already atomic. Setting `safeguard_timeout_dream_seconds: 0`+disables the deadline for every row above whose budget is `dream`.+## Tool HighlightsThe full server currently advertises 110 tools; the 18 deprecated predecessor@@ -288,7 +382,9 @@ to start without `--api-key`, checks the key on every request using a genericconstant-time comparison, and returns the same `401 Unauthorized` body for amissing or wrong key. JSON responses are the default; clients that send`Accept: text/event-stream` receive a single SSE `message` event for the same-JSON-RPC response.+JSON-RPC response — one event, then the connection closes, which is why a+progress token sent over HTTP is refused by name rather than honoured (see+"Progress notifications" above).## Runtime capability windowdiff --git a/docs/metrics.md b/docs/metrics.mdindex 9b2ed43c..5aa0e8f7 100644--- a/docs/metrics.md+++ b/docs/metrics.md@@ -17,6 +17,7 @@ Brain/metrics/├── communities.jsonl├── recall_benchmark.jsonl├── self_tuning.jsonl+├── self_heal_reindex.jsonl└── dream_stage.jsonl```@@ -65,11 +66,29 @@ writes, and a metric record is a summary, not a report.| `dream_stage` | `o2b brain dream stage` / `apply`, MCP `brain_dream` (since 1.0.0) | `action` (`stage`/`apply`), `run_id`, `proposals`, `sources`, `changed`; apply adds `new_unconfirmed`, `confirmed`, `retired` counts || `prompt_prefix` | decision-panel commit (opt-in `promptPrefixMetric`), context-pack consume (opt-in `promptPrefix`) | `kind` (`write_session`/`context_pack`), `prefix_hash` (sha-256 of the stable preamble), `prefix_chars`, `call_count`, `stable_count` || `vault_vitals` | `o2b brain vitals` | `preferences_scanned`, `domain_diversity`, `connectivity_index`, `orphan_count`, `gap_pressure` |+| `self_heal_reindex` | `ensureVaultCurrent` (parent) and `o2b search reindex --self-heal <run-id>` (child) | parent row: `decision` (`spawned` / `skipped_writer_lock`), `run_id` (on `spawned`). Child row: `outcome` (`completed` / `failed`), `run_id`, `duration_ms`, `error` (on `failed`) |Payload fields marked "(lane runs)" appear only on maintenance-laneemissions. All fields are additive-optional from a consumer's pointof view: render what is present, ignore what is unknown.+`self_heal_reindex` is the one surface written by two processes. The+post-upgrade rebuild is spawned detached with every stream ignored, so+the parent records what it decided to do and the child records how it+ended; the two pair on the `run_id` the parent mints and passes to the+child on its command line. Not a pid: a pid is machine-local, and these+rows sync, so two devices' pid spaces (and one device's pid reuse) pair+rows from unrelated runs.++A `spawned` row with no terminal row beside it means only that no+terminal outcome was recorded. The child may have been killed or reaped+with its session; it may still be running (a full reindex takes+minutes); it may have died before the recording was armed; or its own+fail-soft append may have failed on a read-only vault or a full disk.+The rows describe a per-device index from inside a synced vault, so a+row says a self-heal ran on some device, never that this device's index+is stale.+## Reading- Newest records sit at the end of each file; the bundled readerdiff --git a/docs/observability.md b/docs/observability.mdindex ba2aa11b..429222fd 100644--- a/docs/observability.md+++ b/docs/observability.md@@ -100,10 +100,10 @@ No-consumer regression tests cover each gated surface, so a future call site can- `brain_recall_telemetry` `operation: "cost"` (MCP) and `o2b brain recall-telemetry cost` fold WRITE volume against the read telemetry above: memory-write ops (Brain-log `feedback`/`apply-evidence`/`note` verbs plus `host_memory_write` continuity records) are counted per period and reported alongside reads as a write-vs-read ratio, a `write_heavy` flag, and a rough weighted cost signal. Weights (`--write-cost`/`--read-cost`, default 1 each) model "some tools charge on write, some on read"; `--write-heavy-ratio` (default 1) sets the write-heavy threshold. Read-only; period-scoped by `--since`/`--until`. `brain_create_note` file creation emits no telemetry event today and is not counted.- `brain_context_receipts` and `o2b brain context-receipts` inspect served-context receipts.- `brain_route_metrics` (MCP, `operation: "list"|"summary"`) reads route-level MCP tool latency. `list` returns raw `mcp_route_latency` records (filter by `tool`/`status`/`since`/`until`/`limit`); `summary` rolls each tool up into count, error count, and min/avg/max plus p50/p95/p99 latency, ordered slowest-first so an operator can identify which endpoint blocks an agent turn by route rather than by aggregate benchmark. Records are emitted only when `mcp_route_metrics_enabled` is on (default off); read-only.-- `brain_token_impact` (MCP, `operation: "record"|"outcome"|"list"|"summary"`) is the durable value-of-memory ledger. `record` posts one context pack's tokenizer-exact prompt-token delta (`baseline_tokens` − `packed_tokens`, labelled `method: exact|fallback`) plus an optional modeled inference-avoidance estimate (`modeled_avoided_inferences` × `modeled_tokens_per_inference`); `outcome` posts a `first_pass`/`repair`/`retry` result. `summary` keeps the two ledgers STRICTLY SEPARATE: `prompt_token_delta` reports the measured net/saved/added tokens with a per-`method` split (so an exact count is never averaged in with a fallback estimate), while `modeled_inference_avoidance` reports the raw modeled figure and a `calibrated_savings_tokens` dampened by the observed first-pass rate from posted outcomes (null until an outcome exists — uncalibrated, not zero). `list` returns raw samples (filter by `pack_id`/`method`/`host`/`since`/`until`/`limit`); `summary` accepts `max_samples` to bound aggregation. Writes are emitted only when `token_impact_ledger_enabled` is on (default off) and are payload-safe (counts + opaque `pack_id` only, never prompts or recalled text); `list`/`summary` read regardless of the gate. Aggregates are recomputed from the continuity store on every read, so they survive restarts.+- `brain_token_impact` (MCP, `operation: "record"|"outcome"|"list"|"summary"`) is the durable value-of-memory ledger. `record` posts one context pack's prompt-token delta (`baseline_tokens` − `packed_tokens`, labelled `method: tokenizer|heuristic` — how the CALLER produced the counts, never how accurate they are; the ledger counts nothing itself and verifies neither. Samples written under the retired `exact`/`fallback` labels are still read and classified) plus an optional modeled inference-avoidance estimate (`modeled_avoided_inferences` × `modeled_tokens_per_inference`); `outcome` posts a `first_pass`/`repair`/`retry` result. `summary` keeps the two ledgers STRICTLY SEPARATE: `prompt_token_delta` reports the net/saved/added tokens with a per-`method` split (so a tokenizer-produced count is never averaged in with a heuristic estimate), while `modeled_inference_avoidance` reports the raw modeled figure and a `calibrated_savings_tokens` dampened by the observed first-pass rate from posted outcomes (null until an outcome exists — uncalibrated, not zero). `list` returns raw samples (filter by `pack_id`/`method`/`host`/`since`/`until`/`limit`); `summary` accepts `max_samples` to bound aggregation. Writes are emitted only when `token_impact_ledger_enabled` is on (default off) and are payload-safe (counts + opaque `pack_id` only, never prompts or recalled text); `list`/`summary` read regardless of the gate. Aggregates are recomputed from the continuity store on every read, so they survive restarts.- `brain_event_trace` (MCP) and `o2b brain event-trace` join the Brain log to the continuity store: given a logged event (by day, `--at` stamp, kind, or `--session-id`), they resolve the continuity records attached to it via the stable correlation ids above (`session_id`, `turn_id`, and artifact `sourceRefs`), so an operator can answer "which context was supplied to this action?" from one surface. Each attached record reports `joinedBy` (`session` / `turn` / `artifact`); open the full record through the per-kind readers (`context-receipts show`, `recall-telemetry`, `generation-reports show`). Read-only; `private` records are dropped unless explicitly kept.- `brain_generation_reports` (MCP, actions `record`/`list`/`summary`) and `o2b brain generation-reports record|list|summary|show` post and read inbound LLM generation traces. `summary` rolls up call counts, the always-present local token estimate, agent-reported usage where present, and a per-path linkage map so a memory path resolves back to the generation reports that produced or consumed it.- `o2b brain continuity export --format atof|atif` renders the store as standard trajectory formats (ATOF JSONL event stream; ATIF v1.7 one document per session) for replay and eval tooling. Read-only; `private` records never reach an export file. Mapping decisions: `docs/brainstorm/memory-observability-suite/atof-atif-mapping.md`.-- `o2b brain bench memory` measures recall quality over disposable fixture vaults and reports quality, latency, and context cost as separate families (`o2b.bench.v1` report schema).+- `o2b brain bench memory` measures memory quality over disposable fixture vaults and reports quality, latency, context cost, and failure modes as separate families (`o2b.bench.v2` report schema). Beyond the retrieval categories it scores three failure modes the retrieval questions cannot see: `proactive_recall` drives `decideRecallInject` over the fixture and reports `know_to_ask_failure_rate` and `false_fire_rate` (both denominated in decisions, so a strategy that always injects scores worse than one that abstains correctly); `write_fidelity` grades the provenance that survives the shipped extraction, insertion and dedup path with no model call; `source_isolation` asserts on delivered context-pack contents under a requested owner scope and gates at zero. `context_cost.avg_injected_tokens` is `estimateTokens` over the strings the bench actually injected — the suite's one token estimator. Two things the numbers do NOT say: `recall_inject_enabled` is off by default, so the proactive metric describes a capability rather than delivered behaviour, and `integrity.owner_scope_delivery` is off by default, so an isolation fixture must set it to `fail` or the gate is vacuous. The committed baseline is `tests/fixtures/bench/failure-modes.baseline.json`, compared by `tests/core/bench/failure-modes-baseline.test.ts` inside the ordinary `bun test` gate.Consumers should treat unknown record kinds and unknown payload fields as fine - skip what you do not recognize (the store and read-model already behave this way).diff --git a/docs/updating.md b/docs/updating.mdindex 33c23582..3af03a3d 100644--- a/docs/updating.md+++ b/docs/updating.md@@ -89,6 +89,15 @@ hands-off:detached reindex), so startup never blocks; and as a safety net the searchread path self-heals a stale/missing index on first query.+A schema bump makes every session that starts afterwards find the index stale+at once, so the spawn is checked against the index writer lock first: a rebuild+that can already be seen to lose is not started at all. That check reads an+instant and cannot exclude anything - the writer lock still does that - so a+child can still lose a real race, and it now says so. Every detached rebuild+records what it decided and how it ended on the `self_heal_reindex` metrics+surface (`docs/metrics.md`), because the child runs with its streams pointed at+nothing and a failure would otherwise be reported nowhere.+It is **state-driven, not version-stamped.** Each step keys off actual on-diskstate - the search index `schema_version`, the `_brain.yaml` pending-changesplan, directory existence - rather than a "last version" marker. This is@@ -152,3 +161,4 @@ These properties are locked by tests; do not weaken them:- `tests/cli/install-cli.test.ts` — idempotent reclaim and conservative self-heal.- `tests/core/search/self-heal.test.ts` — search rebuilds a stale/missing index on read.- `tests/core/maintenance/ensure-current.test.ts` — state-driven migration, idempotent, never throws.+- `tests/core/maintenance/self-heal-reindex.test.ts` — the herd is thinned against the writer lock, and a detached rebuild's outcome is readable.diff --git a/hooks/lib/process-ceiling.ts b/hooks/lib/process-ceiling.tsindex 2ae6c579..f1a71f16 100644--- a/hooks/lib/process-ceiling.ts+++ b/hooks/lib/process-ceiling.ts@@ -16,11 +16,45 @@** Note: a JavaScript timer cannot interrupt a fully-synchronous CPU hang on a* single thread; the realistic hook hangs are asynchronous (network fetch,- * fs stall on a mounted volume), which this covers. The host runtime's own- * per-hook timeout remains a second line of defence.+ * fs stall on a mounted volume), which this covers. That limit is exactly why+ * the host's own per-hook timeout is the OUTER bound and this ceiling sits+ * inside it: the host can kill a wedged process this timer cannot reach.+ *+ * ## Which deadline is authoritative+ *+ * The host's is. It is enforced from outside the process, it survives a+ * synchronous hang, and every entry in `hooks/hooks.json` declares it. What+ * this module adds is a CLEAN exit just before that deadline: a hook killed by+ * the host writes no audit line and leaves no record of why it stopped, while+ * one that hits this ceiling runs `onExpire` and exits 0.+ *+ * That only works if this ceiling is strictly SMALLER than the declared host+ * timeout. It was not: the default was 55 s behind a declared 10 s, so under+ * the shipped configuration the self-ceiling could never once have fired and+ * the module's "second line of defence" was in fact the first and only one.+ * The default is now derived from the declared timeout, and+ * `tests/hooks/process-ceiling.test.ts` asserts the RELATION between the two+ * rather than either number - so changing one without the other fails there+ * instead of silently disarming the watchdog again.+ */++/**+ * The per-hook timeout every entry in `hooks/hooks.json` declares, in+ * seconds. Mirrored here because JSON cannot import a constant; the test+ * suite reads the file and asserts the two agree.+ */+export const HOOK_HOST_TIMEOUT_SECONDS = 10;++/**+ * How far in front of the host's deadline this ceiling fires. It buys the+ * `onExpire` side effect - a single audit-line append - and the exit, which+ * is comfortably under two seconds even on a loaded machine with a slow+ * filesystem.*/+export const HOOK_CEILING_HEADROOM_MS = 2_000;-export const DEFAULT_HOOK_CEILING_MS = 55_000;+/** Derived, never typed twice: see the module docblock for the ordering. */+export const DEFAULT_HOOK_CEILING_MS = HOOK_HOST_TIMEOUT_SECONDS * 1_000 - HOOK_CEILING_HEADROOM_MS;/** Floor below which a configured ceiling is treated as a typo and ignored. */const MIN_HOOK_CEILING_MS = 1_000;diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 059ff083..6bea96ec 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.47.0",+ "version": "1.48.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/openclaw/index.js b/openclaw/index.jsindex abeb484d..ebd0cb8e 100644--- a/openclaw/index.js+++ b/openclaw/index.js@@ -1689,6 +1689,16 @@ function resolveAgentName(configPath) {return value;return "agent";}+function resolveConfigFlag(envKey, configKey, configPath) {+ const env = process.env[envKey]?.trim();+ const raw = env || discoverConfig(configPath).data[configKey]?.trim();+ return raw === "true" || raw === "1";+}+var PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED";+var PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled";+function resolvePartnerCodegraphDisabled(configPath) {+ return resolveConfigFlag(PARTNER_CODEGRAPH_DISABLED_ENV, PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY, configPath);+}function expandTilde(p) {if (p === "~")return homedir();@@ -2233,29 +2243,43 @@ function findCodeProjects(opts) {}return found;}+function isCodegraphUnanswered(result) {+ return result.ok === false && "unanswered" in result;+}+function partnerEnv() {+ return process.env;+}function defaultWhichCodegraph() {if (typeof Bun !== "undefined" && typeof Bun.which === "function") {- const found = Bun.which(CODEGRAPH_CLI.bin);+ const found = Bun.which(CODEGRAPH_CLI.bin, { PATH: partnerEnv()["PATH"] });return found ?? null;}return null;}var CODEGRAPH_PROJECT_PATH_USAGE_TOKEN = /\[path\]/;var HELP_FLAG = "--help";-function defaultDetectProjectPathSupport() {+var CODEGRAPH_PARTNER_TIMEOUT_MS = 1e4;+function timedOut(proc) {+ return proc.exitedDueToTimeout === true;+}+function defaultDetectProjectPathSupport(timeoutMs = CODEGRAPH_PARTNER_TIMEOUT_MS) {try {const proc = Bun.spawnSync({cmd: [CODEGRAPH_CLI.bin, CODEGRAPH_CLI.statusSubcommand, HELP_FLAG],stdout: "pipe",- stderr: "pipe"+ stderr: "pipe",+ env: partnerEnv(),+ timeout: timeoutMs});+ if (timedOut(proc))+ return false;const help = new TextDecoder().decode(proc.stdout) + new TextDecoder().decode(proc.stderr);return CODEGRAPH_PROJECT_PATH_USAGE_TOKEN.test(help);} catch {return false;}}-function defaultRunStatusJson(projectPath) {+function defaultRunStatusJson(projectPath, timeoutMs = CODEGRAPH_PARTNER_TIMEOUT_MS) {try {const proc = Bun.spawnSync({cmd: [@@ -2265,8 +2289,12 @@ function defaultRunStatusJson(projectPath) {projectPath],stdout: "pipe",- stderr: "pipe"+ stderr: "pipe",+ env: partnerEnv(),+ timeout: timeoutMs});+ if (timedOut(proc))+ return { ok: false, unanswered: true, waitedMs: timeoutMs };const stdout = new TextDecoder().decode(proc.stdout).trim();const stderr = new TextDecoder().decode(proc.stderr).trim();if (!proc.success) {@@ -2292,7 +2320,7 @@ function defaultRunStatusJson(projectPath) {}function checkCodegraph(opts, deps) {if (opts.disabled)- return null;+ return codegraphDisabledResult();const projects = findCodeProjects(opts);if (projects.length === 0)return null;@@ -2302,18 +2330,32 @@ function checkCodegraph(opts, deps) {return null;}if (projects.length === 1) {- return evaluateProjectStatus(projects[0], deps);+ return evaluateProjectStatus(projects[0], deps).result;}- const detectFn = deps?.detectProjectPathSupport ?? defaultDetectProjectPathSupport;+ const detectFn = deps?.detectProjectPathSupport ?? (() => defaultDetectProjectPathSupport(partnerTimeout(deps)));if (!detectFn()) {- const first = evaluateProjectStatus(projects[0], deps);+ const first = evaluateProjectStatus(projects[0], deps).result;return {name: "code_graph",ok: first.ok,- message: `${first.message}; note: codegraph CLI has no per-query project_path support - reported 1 of ${projects.length} discovered projects only`+ message: `${first.message}; note: codegraph CLI did not report per-query project_path support - reported 1 of ${projects.length} discovered projects only`};}- const results = projects.map((project) => evaluateProjectStatus(project, deps));+ const results = [];+ let unanswered = false;+ for (const project of projects) {+ if (unanswered) {+ results.push({+ name: "code_graph",+ ok: false,+ message: `code project at ${project}: not consulted - ${CODEGRAPH_CLI.bin} did not answer for ` + "an earlier project in this workspace, so nothing is claimed here about this index"+ });+ continue;+ }+ const evaluated = evaluateProjectStatus(project, deps);+ unanswered = evaluated.unanswered;+ results.push(evaluated.result);+ }const header = `${projects.length} code projects:`;return {name: "code_graph",@@ -2322,41 +2364,62 @@ function checkCodegraph(opts, deps) {`)};}+function partnerTimeout(deps) {+ return deps?.timeoutMs ?? CODEGRAPH_PARTNER_TIMEOUT_MS;+}+function codegraphDisabledResult() {+ return {+ name: "code_graph",+ ok: true,+ message: `check disabled by ${PARTNER_CODEGRAPH_DISABLED_ENV} / ` + `${PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY}: ${CODEGRAPH_CLI.bin} was not consulted, ` + "so nothing is claimed here about any index"+ };+}function evaluateProjectStatus(project, deps) {const indexDir = join2(project, ".codegraph");let indexed;try {indexed = statOrAbsent(indexDir)?.isDirectory() === true;} catch (exc) {- return {+ return answered({name: "code_graph",ok: false,message: `code project at ${project}: index directory unreadable: ${exc.message ?? exc}`,fix: `chmod u+rx "${indexDir}"`- };+ });}if (!indexed) {- return {+ return answered({name: "code_graph",ok: false,message: `code project at ${project}: not indexed (run: ${codegraphInitCommand(project)})`- };+ });}- const runFn = deps?.runStatusJson ?? defaultRunStatusJson;+ const runFn = deps?.runStatusJson ?? ((path) => defaultRunStatusJson(path, partnerTimeout(deps)));const status = runFn(project);- if (!status.ok) {+ if (isCodegraphUnanswered(status)) {return {+ result: {+ name: "code_graph",+ ok: false,+ message: `code project at ${project}: ${CODEGRAPH_CLI.bin} ` + `${CODEGRAPH_CLI.statusSubcommand} did not answer within ${status.waitedMs}ms and was ` + "stopped, so NOTHING is claimed here about this index - a probe that did not complete " + "is not an index that failed",+ fix: `${CODEGRAPH_CLI.bin} ${CODEGRAPH_CLI.statusSubcommand} ${CODEGRAPH_CLI.statusJsonFlag} ${project}`+ },+ unanswered: true+ };+ }+ if (!status.ok) {+ return answered({name: "code_graph",ok: false,message: `code project at ${project}: codegraph status failed: ${status.error}`- };+ });}if (!status.data.initialized) {- return {+ return answered({name: "code_graph",ok: false,message: `code project at ${project}: not indexed (run: ${codegraphInitCommand(project)})`- };+ });}const nodes = status.data.nodeCount ?? 0;const files = status.data.fileCount ?? 0;@@ -2369,11 +2432,14 @@ function evaluateProjectStatus(project, deps) {indexRoot: resolveRealpath(status.data.worktreeMismatch?.indexRoot ?? status.data.projectPath ?? null),worktreeRoot: resolveRealpath(status.data.worktreeMismatch?.worktreeRoot ?? project)});- return {+ return answered({name: "code_graph",ok: true,message: health.ok ? base : `${base}; graph-health: ${summarizeGraphHealth(health)} - run: o2b partner codegraph report`- };+ });+}+function answered(result) {+ return { result, unanswered: false };}function resolveRealpath(value) {if (!value)@@ -2682,6 +2748,16 @@ function checkOpenclawInstallability(repoRoot) {}return results;}+function codegraphCheckDisabled(opts) {+ const explicit = opts.partner?.codegraph?.disabled;+ if (explicit !== undefined)+ return explicit;+ try {+ return resolvePartnerCodegraphDisabled(opts.config ?? undefined);+ } catch {+ return false;+ }+}function doctor(opts) {const results = [];results.push(checkVaultWriteable(opts.vault));@@ -2699,7 +2775,7 @@ function doctor(opts) {cwd: opts.cwd ?? process.cwd(),vault: opts.vault,scanExtraPaths: opts.partner?.codegraph?.scanExtraPaths,- disabled: opts.partner?.codegraph?.disabled+ disabled: codegraphCheckDisabled(opts)});if (cg)results.push(cg);diff --git a/package.json b/package.jsonindex 8c4c30e5..4e434954 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.47.0",+ "version": "1.48.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 9ffca070..37cc8309 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.47.0"+version: "1.48.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 2afd724f..8ff4a40a 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.47.0",+ "version": "1.48.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 9ffca070..37cc8309 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.47.0"+version: "1.48.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 cc432094..23cc2236 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.47.0"+version = "1.48.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 014a9fee..fc883a2c 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -532,13 +532,16 @@ export const VERB_HELP: Record<string, string> = {"no-values record in Brain/log/secret-custody/. Protects against\n" +"context leakage and vault sync exposure - not against root.\n",maintenance:- "usage: o2b brain maintenance run [--force] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] | status [--limit N] [--vault <path>] [--json]\n" ++ "usage: o2b brain maintenance run [--force] [--retry <task>] [--window H-H] [--tz ZONE] [--busy-minutes N] [--busy-threshold N] | status [--limit N] [--vault <path>] [--json]\n" +"Quiet-window, lease-guarded lane for heavy passes. run gates on the\n" +"local-time window (unset = always open), recent interactive query-rate\n" +"from recall telemetry, and an expiring SQLite lease no second worker\n" +"can grab, then executes dream, reindex, bridges, and clusters\n" +- "stale-first. --force bypasses\n" +- "the soft gates but never the lease. Every attempt - including gate\n" ++ "stale-first. A task that has failed maintenance.failure_streak_limit\n" ++ "times in a row is REFUSED by name (exit 7) while the others still run;\n" ++ "--retry <task> attempts that one task with every gate still in force,\n" ++ "and --force bypasses the soft gates and every refusal, never the\n" ++ "lease. Every attempt - including gate\n" +"refusals - lands in a bounded journal; status renders lease + journal.\n",audit:"usage: o2b brain audit <pref-id> [--vault <path>] [--json]\n" +diff --git a/src/cli/brain/snapshot-render.ts b/src/cli/brain/snapshot-render.tsindex 3f64a30e..4ab6354b 100644--- a/src/cli/brain/snapshot-render.ts+++ b/src/cli/brain/snapshot-render.ts@@ -18,9 +18,11 @@*/import type { BrainManifestDerivedStore } from "../../core/brain/manifest.ts";-import type {- BrainSnapshotListingError,- RestoreDerivedStoreResult,+import {+ describeSnapshotEntrySkip,+ type BrainSnapshotListingError,+ type RestoreDerivedStoreResult,+ type SnapshotEntrySkip,} from "../../core/brain/snapshot.ts";/**@@ -99,3 +101,22 @@ export function renderDerivedStoreRestore(outcome: RestoreDerivedStoreResult): sexport function renderSnapshotListingFailure(err: BrainSnapshotListingError): string {return `${err.message}; an unreadable snapshots directory is not an empty history`;}++/**+ * Wording for archives that ARE in the directory and are missing from the+ * listing below.+ *+ * Both listing surfaces need it for the same reason they need the sentence+ * above: a listing that quietly drops the archives it could not describe+ * reads exactly like a vault that never had them, and an operator hunting+ * the recovery point they took last week would act on the wrong one. It+ * does not fail the verb - the rows that survived are still the answer to+ * the question asked - so it goes to stderr while the listing goes to+ * stdout, and both `--json` payloads carry the same entries as data.+ */+export function renderSnapshotListingSkips(skipped: ReadonlyArray<SnapshotEntrySkip>): string {+ return (+ `warning: ${skipped.length} archive(s) in the snapshots directory could not be listed, so ` ++ `this listing is INCOMPLETE: ${skipped.map(describeSnapshotEntrySkip).join(", ")}`+ );+}diff --git a/src/cli/brain/verbs/architect.ts b/src/cli/brain/verbs/architect.tsindex eab8f92e..97d16bb9 100644--- a/src/cli/brain/verbs/architect.ts+++ b/src/cli/brain/verbs/architect.ts@@ -3,25 +3,59 @@* t_929da8a2): deterministic architecture notes for a code project,* generated into the vault through the sentinel-region engine so* operator edits survive every re-scan.+ *+ * The scan and the render have emitted through the progress spine and+ * accepted a cooperative deadline since U1/U11, and+ * `safeguard_timeout_architect_seconds` has resolved through the ladder+ * since `OPERATION.architect` was added - but this verb built no+ * safeguard and attached no rail, so both were declared surfaces with+ * nothing behind them. This is their consumer.*/import { generateArchDocs } from "../../../core/brain/architect/generate.ts";import { RegionError } from "../../../core/brain/regions.ts";+import {+ createSafeguard,+ OPERATION,+ resolveSafeguardTimeoutMs,+} from "../../../core/brain/safeguard.ts";+import { attachProgress, reportProgressRefusal } from "../../progress-rail.ts";import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";+const USAGE = "usage: o2b brain architect <project-path> [--vault V] [--progress] [--json]";+export async function cmdBrainArchitect(argv: string[]): Promise<number> {const { flags, positional } = parse(argv, {vault: { type: "string" },+ progress: { type: "boolean" },json: { type: "boolean" },});+ const asJson = flags["json"] === true;const target = positional[0];- if (!target) {- return fail("usage: o2b brain architect <project-path> [--vault V] [--json]");- }+ if (!target) return fail(USAGE);++ // Progress is opt-in: attaching a sink by default would change the+ // stderr of every existing invocation. The rail decides whether the+ // stream can carry it at all.+ const observation =+ flags["progress"] === true+ ? attachProgress({ command: "brain", argv: ["architect"], jsonRequested: asJson })+ : null;+ // No interrupt handle: `generateRun` is synchronous end to end, so a+ // signal handler cannot run while it does (see `interrupt.ts`). Leaving+ // SIGINT alone keeps the keystroke lethal, and the plan-then-write+ // restructure means a killed scan has written nothing.try {- const vault = brainVerbContext(flags).vault;- const res = generateArchDocs(vault, target);- if (flags["json"] === true) {+ const { config, vault } = brainVerbContext(flags);+ reportProgressRefusal(observation);+ const res = generateArchDocs(vault, target, {+ safeguard: createSafeguard({+ operation: OPERATION.architect,+ timeoutMs: resolveSafeguardTimeoutMs(OPERATION.architect, config ?? undefined),+ }),+ ...(observation?.sink !== undefined ? { onProgress: observation.sink } : {}),+ });+ if (asJson) {okJson({ok: true,repo_key: res.repoKey,@@ -31,6 +65,10 @@ export async function cmdBrainArchitect(argv: string[]): Promise<number> {created: res.created,updated: res.updated,unchanged: res.unchanged,+ // Conditional, so a run whose observer never failed - and every+ // run with no observer at all - emits exactly the payload it+ // emitted before this field had a consumer.+ ...(res.progressFault !== null ? { progress_fault: res.progressFault } : {}),});return 0;}@@ -39,6 +77,12 @@ export async function cmdBrainArchitect(argv: string[]): Promise<number> {`${res.updated} updated, ${res.unchanged} unchanged`,);ok(`overview: ${res.overviewPath}`);+ // The generation succeeded and the caller's stream did not. Carried+ // out rather than swallowed: an observer that died mid-run explains+ // a stream that stops before the last note.+ if (res.progressFault !== null) {+ process.stderr.write(`progress: observer failed (${res.progressFault})\n`);+ }return 0;} catch (err) {if (err instanceof RegionError) {diff --git a/src/cli/brain/verbs/bench.ts b/src/cli/brain/verbs/bench.tsindex 2d678e53..045bb8aa 100644--- a/src/cli/brain/verbs/bench.ts+++ b/src/cli/brain/verbs/bench.ts@@ -76,7 +76,12 @@ export async function cmdBrainBench(argv: string[]): Promise<number> {);process.stdout.write(`latency_ms: avg ${report.latency_ms.avg} max ${report.latency_ms.max}\n`);process.stdout.write(- `context_cost: avg_chars ${report.context_cost.avg_chars} est_tokens ${report.context_cost.est_tokens}\n`,+ `context_cost: avg_chars ${report.context_cost.avg_chars} avg_injected_tokens ${report.context_cost.avg_injected_tokens}\n`,+ );+ process.stdout.write(+ `failure_modes: know_to_ask ${report.failure_modes.know_to_ask_failure_rate} ` ++ `false_fire ${report.failure_modes.false_fire_rate} ` ++ `isolation_violations ${report.failure_modes.source_isolation_violations}\n`,);process.stdout.write(`judge: ${report.judge.status}\n`);for (const question of report.questions) {diff --git a/src/cli/brain/verbs/bridges.ts b/src/cli/brain/verbs/bridges.tsindex 74509b32..c8e7f9aa 100644--- a/src/cli/brain/verbs/bridges.ts+++ b/src/cli/brain/verbs/bridges.ts@@ -27,6 +27,7 @@ import {import { appendMetric } from "../../../core/brain/metrics.ts";import {createSafeguard,+ OPERATION,resolveSafeguardTimeoutMs,SafeguardTimeoutError,} from "../../../core/brain/safeguard.ts";@@ -37,11 +38,12 @@ import { Store } from "../../../core/search/store.ts";import { SearchError } from "../../../core/search/types.ts";import { parseFrontmatter } from "../../../core/vault.ts";import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";+import { attachProgress, reportProgressRefusal } from "../../progress-rail.ts";import { nextCommandField } from "../../../core/brain/next-step.ts";import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";const USAGE =- "usage: o2b brain bridges discover [--max N] [--min-similarity X] | list | " ++ "usage: o2b brain bridges discover [--max N] [--min-similarity X] [--progress] | list | " +"accept <source> <target> | dismiss <source> <target> [--vault <path>] [--json]";export async function cmdBrainBridges(argv: string[]): Promise<number> {@@ -49,6 +51,7 @@ export async function cmdBrainBridges(argv: string[]): Promise<number> {vault: { type: "string" },max: { type: "string" },"min-similarity": { type: "string" },+ progress: { type: "boolean" },json: { type: "boolean" },});const asJson = flags["json"] === true;@@ -146,6 +149,20 @@ export async function cmdBrainBridges(argv: string[]): Promise<number> {}const now = new Date();+ // Progress is opt-in: attaching a sink by default would change the+ // stderr of every existing invocation, and this CLI's one streaming+ // precedent (`o2b search index --verbose`) is opt-in for the same+ // reason. The rail decides whether the stream can carry it at all.+ const observation =+ flags["progress"] === true+ ? attachProgress({ command: "brain", argv: ["bridges"], jsonRequested: asJson })+ : null;+ reportProgressRefusal(observation);+ // No interrupt handle: `discoverBridgesRun` is synchronous end to end,+ // so a signal handler cannot run while it does (see `interrupt.ts`).+ // Leaving SIGINT alone keeps the keystroke lethal, which is the only+ // way this scan can actually be stopped. Proposals are written in one+ // atomic write after the scan, so a killed run leaves no half file.try {const dismissed = readDismissedBridges(vault);const report = discoverBridges(store, {@@ -153,9 +170,10 @@ export async function cmdBrainBridges(argv: string[]): Promise<number> {...(minSimilarity !== undefined ? { minSimilarity } : {}),dismissed,safeguard: createSafeguard({- operation: "bridges",- timeoutMs: resolveSafeguardTimeoutMs("bridges", config ?? undefined),+ operation: OPERATION.bridges,+ timeoutMs: resolveSafeguardTimeoutMs(OPERATION.bridges, config ?? undefined),}),+ ...(observation?.sink !== undefined ? { onProgress: observation.sink } : {}),});const path = writeBridgeProposals(vault, report, { now });try {diff --git a/src/cli/brain/verbs/clusters.ts b/src/cli/brain/verbs/clusters.tsindex 0dcae622..bddf725c 100644--- a/src/cli/brain/verbs/clusters.ts+++ b/src/cli/brain/verbs/clusters.ts@@ -23,6 +23,7 @@ import { appendMetric } from "../../../core/brain/metrics.ts";import { brainConfigPath } from "../../../core/brain/paths.ts";import {createSafeguard,+ OPERATION,resolveSafeguardTimeoutMs,SafeguardTimeoutError,} from "../../../core/brain/safeguard.ts";@@ -43,11 +44,13 @@ import { Store } from "../../../core/search/store.ts";import { SearchError } from "../../../core/search/types.ts";import { listVaultPages, parseFrontmatter } from "../../../core/vault.ts";import { emitNextStep, type AdvisoryStream } from "../../advisory-rail.ts";+import { attachProgress, reportProgressRefusal } from "../../progress-rail.ts";import { nextCommandField } from "../../../core/brain/next-step.ts";import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";const USAGE =- "usage: o2b brain clusters run [--min-size N] [--batch-size N] [--if-stale] | list [--vault <path>] [--json]";+ "usage: o2b brain clusters run [--min-size N] [--batch-size N] [--if-stale] [--progress] | " ++ "list [--vault <path>] [--json]";/** Vault-relative directory holding the materialized cluster notes. */const CLUSTERS_DIR_REL = join("Brain", "clusters");@@ -123,6 +126,7 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {"min-size": { type: "string" },"batch-size": { type: "string" },"if-stale": { type: "boolean" },+ progress: { type: "boolean" },json: { type: "boolean" },});const asJson = flags["json"] === true;@@ -252,14 +256,28 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {}const now = new Date();+ // Progress is opt-in: attaching a sink by default would change the+ // stderr of every existing invocation, and this CLI's one streaming+ // precedent (`o2b search index --verbose`) is opt-in for the same+ // reason. The rail decides whether the stream can carry it at all.+ const observation =+ flags["progress"] === true+ ? attachProgress({ command: "brain", argv: ["clusters"], jsonRequested: asJson })+ : null;+ reportProgressRefusal(observation);+ // No interrupt handle: `detectCommunitiesRun` is synchronous end to+ // end, so a signal handler cannot run while it does (see+ // `interrupt.ts`). Leaving SIGINT alone keeps the keystroke lethal,+ // which is the only way this pass can actually be stopped.try {const safeguard = createSafeguard({- operation: "clusters",- timeoutMs: resolveSafeguardTimeoutMs("clusters", config ?? undefined),+ operation: OPERATION.clusters,+ timeoutMs: resolveSafeguardTimeoutMs(OPERATION.clusters, config ?? undefined),});const communities = detectCommunities(store, {...(minSize !== undefined ? { minSize } : {}),safeguard,+ ...(observation?.sink !== undefined ? { onProgress: observation.sink } : {}),});// O(1) from the snapshot detectCommunities just built (same index// revision -> cache hit, no second graph rebuild).diff --git a/src/cli/brain/verbs/dream.ts b/src/cli/brain/verbs/dream.tsindex a567b866..fe2016c2 100644--- a/src/cli/brain/verbs/dream.ts+++ b/src/cli/brain/verbs/dream.ts@@ -45,11 +45,13 @@ import {} from "../../../core/brain/dream-stage.ts";import {createSafeguard,+ OPERATION,resolveSafeguardTimeoutMs,SafeguardTimeoutError,} from "../../../core/brain/safeguard.ts";import { nextCommandField } from "../../../core/brain/next-step.ts";import { emitNextStep } from "../../advisory-rail.ts";+import { attachProgress, reportProgressRefusal } from "../../progress-rail.ts";import { brainVerbContext, fail, ok, okJson, parse, parseOptionalIsoDate } from "../helpers.ts";// The runnable set is read from the step registry, never retyped: a@@ -102,6 +104,7 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {strict: { type: "boolean" },step: { type: "string" },gate: { type: "string-array" },+ progress: { type: "boolean" },json: { type: "boolean" },});const asJson = flags["json"] === true;@@ -200,10 +203,16 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {const { value: now, error: nowErr } = parseOptionalIsoDate(flags, "now");if (nowErr) return fail(nowErr);+ // No signal: `dreamRun` is synchronous end to end, so a signal handler+ // cannot run while it does (see `interrupt.ts`). The deadline is the+ // only cooperative stop a dream pass has; SIGINT is left with its+ // default meaning so the keystroke still kills the process, and every+ // artifact a pass writes goes through `atomicWriteFileSync`, so being+ // killed leaves no half-written note.const guard = () =>createSafeguard({- operation: "dream",- timeoutMs: resolveSafeguardTimeoutMs("dream", config ?? undefined),+ operation: OPERATION.dream,+ timeoutMs: resolveSafeguardTimeoutMs(OPERATION.dream, config ?? undefined),});if (wantsStep) {@@ -233,11 +242,32 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {return 0;}+ // The staged actions that RUN a pass watch the same five stages the+ // inline run does. `DreamStageOptions` has declared `onProgress` and+ // threaded it through all three of those entry points since U1; this is+ // the caller that asks. A stream that reached only one of the two entry+ // points would be the half-wired mechanism this release exists to+ // remove.+ //+ // `discard` and `list` are excluded because they run no pass and have+ // nothing to report, and `run` because it falls through this block to+ // the inline pass below, which attaches its own. Attaching here for+ // `run` too would build two observers for one pass and report a refusal+ // twice.+ const STAGED_PASSES = new Set(["stage", "validate", "apply"]);+ const stagedObservation =+ flags["progress"] === true && STAGED_PASSES.has(action)+ ? attachProgress({ command: "brain", argv: ["dream", action], jsonRequested: asJson })+ : null;+ reportProgressRefusal(stagedObservation);+ const stagedProgress =+ stagedObservation?.sink !== undefined ? { onProgress: stagedObservation.sink } : {};try {if (action === "stage") {const bundle = stageDream(vault, {now: now ?? new Date(),safeguard: guard(),+ ...stagedProgress,...(agent ? { agentName: agent } : {}),});if (asJson) {@@ -259,6 +289,7 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {const stageOpts = {now: now ?? new Date(),safeguard: guard(),+ ...stagedProgress,...(agent ? { agentName: agent } : {}),};if (action === "validate") {@@ -379,6 +410,15 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {}}+ // Progress is opt-in: attaching a sink by default would change the+ // stderr of every existing invocation, and this CLI's one streaming+ // precedent (`o2b search index --verbose`) is opt-in for the same+ // reason. The rail decides whether the stream can carry it at all.+ const observation =+ flags["progress"] === true+ ? attachProgress({ command: "brain", argv: ["dream"], jsonRequested: asJson })+ : null;+ reportProgressRefusal(observation);let summary;try {summary = dream(vault, {@@ -386,6 +426,7 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {dryRun: Boolean(flags["dry-run"]),...(agent ? { agentName: agent } : {}),safeguard: guard(),+ ...(observation?.sink !== undefined ? { onProgress: observation.sink } : {}),...(gates !== null ? { gates } : {}),});} catch (exc) {@@ -395,7 +436,6 @@ export async function cmdBrainDream(argv: string[]): Promise<number> {}return fail(`dream failed: ${(exc as Error).message ?? exc}`);}-for (const w of summary.warnings ?? []) {process.stderr.write(`warning: ${w.code}: ${w.message}\n`);}diff --git a/src/cli/brain/verbs/import-session.ts b/src/cli/brain/verbs/import-session.tsindex 4a575b97..e1b85a52 100644--- a/src/cli/brain/verbs/import-session.ts+++ b/src/cli/brain/verbs/import-session.ts@@ -1,6 +1,10 @@import { statSync } from "node:fs";import { resolveAgentName, resolveSessionCaptureRoles } from "../../../core/config.ts";-import { importSession, importSessionPath } from "../../../core/brain/sessions/import.ts";+import {+ importSession,+ importSessionPath,+ IMPORT_WRITE_MODE,+} from "../../../core/brain/sessions/import.ts";import { SessionImportError, type SessionAdapterId } from "../../../core/brain/sessions/types.ts";import {isSessionAdapterId,@@ -154,9 +158,13 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {files: result.files.map((f) => ({file: f.file,format: f.format,+ write_mode: f.write_mode,turns_scanned: f.turns_scanned,signals_created: f.signals_created,+ signals_withheld: f.signals_withheld,signals_deduped: f.signals_deduped,+ facts_extracted: f.facts_extracted,+ facts_withheld: f.facts_withheld,tool_replays: f.tool_replays,malformed: f.malformed,filtered_turns: f.filtered_turns,@@ -170,8 +178,15 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {for (const f of result.files) {ok(`file: ${f.file}`);ok(` format: ${f.format}`);+ ok(` write_mode: ${f.write_mode}`);ok(` turns_scanned: ${f.turns_scanned}`);ok(` signals_created: ${f.signals_created}`);+ // Printed only on a rehearsal, where it is the whole answer; an+ // applied run's withheld count is zero by construction.+ if (f.write_mode === IMPORT_WRITE_MODE.dryRun) {+ ok(` signals_withheld: ${f.signals_withheld}`);+ ok(` facts_withheld: ${f.facts_withheld}`);+ }ok(` signals_deduped: ${f.signals_deduped}`);ok(` tool_replays: ${f.tool_replays}`);ok(` filtered_turns: ${f.filtered_turns}`);diff --git a/src/cli/brain/verbs/maintenance.ts b/src/cli/brain/verbs/maintenance.tsindex 88456615..215d1b2c 100644--- a/src/cli/brain/verbs/maintenance.ts+++ b/src/cli/brain/verbs/maintenance.ts@@ -4,14 +4,14 @@* (--window H-H, unset = always open), recent interactive query-rate,* and the expiring SQLite lease, then executes dream, reindex,* bridges, and clusters stale-first; --force bypasses the soft gates- * but never the lease.+ * and every streak refusal but never the lease, while --retry <task>+ * (repeatable) bypasses the streak refusal for that task alone and+ * leaves every gate in force.* `status` renders the lease holder and recent journal. Designed as* the cron entry point: a dead dashboard hour surfaces as* skipped:window in the journal instead of a contended vault.*- * Exit codes: 0 on success (including a gate skip - cron must not- * alarm on a quiet hour), 1 on an operational failure, 2 on usage- * errors.+ * Exit codes: see {@link MAINTENANCE_EXIT}.*/import { dream } from "../../../core/brain/dream.ts";@@ -25,7 +25,12 @@ import {materializeClusterNotes,} from "../../../core/brain/link-graph/communities.ts";import { appendMetric } from "../../../core/brain/metrics.ts";-import { createSafeguard, resolveSafeguardTimeoutMs } from "../../../core/brain/safeguard.ts";+import {+ createSafeguard,+ OPERATION,+ resolveSafeguardTimeoutMs,+ type Operation,+} from "../../../core/brain/safeguard.ts";import { isoSecond } from "../../../core/brain/time.ts";import { Store } from "../../../core/search/store.ts";import { currentLease, MAINTENANCE_LEASE_NAME } from "../../../core/brain/maintenance/lease.ts";@@ -34,33 +39,76 @@ import {MAINTENANCE_BUSY_THRESHOLD,runMaintenance,type DailyWindow,+ type MaintenanceTask,} from "../../../core/brain/maintenance/lane.ts";import { listJournal } from "../../../core/brain/maintenance/journal.ts";import { resolveAgentName } from "../../../core/config.ts";import { indexVault, resolveSearchConfig } from "../../../core/search/index.ts";+import { onInterrupt } from "../../interrupt.ts";+import { attachProgress, reportProgressRefusal } from "../../progress-rail.ts";import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";const USAGE =- "usage: o2b brain maintenance run [--force] [--window H-H] [--tz ZONE] " +- "[--busy-minutes N] [--busy-threshold N] | status [--limit N] [--vault <path>] [--json]";+ "usage: o2b brain maintenance run [--force] [--retry <task>] [--window H-H] [--tz ZONE] " ++ "[--busy-minutes N] [--busy-threshold N] [--progress] | status [--limit N] " ++ "[--vault <path>] [--json]";++/**+ * What this verb's exit code says, and why a refusal has its own number.+ *+ * 0 covers a gate skip as well as a clean pass: a quiet hour, a busy+ * vault and a loaded host are self-resolving conditions and cron must+ * not alarm on them. 1 means a task was ATTEMPTED and failed.+ *+ * A streak refusal is neither. Nothing ran, so 1 would report a failure+ * this run did not have - the same collapse the lane's own row avoids by+ * carrying no `ok` - and every failure behind the refusal was already+ * reported as a 1 on the run that produced it. But 0 would tell a+ * nightly cron that a lane which has stopped doing a heavy pass is+ * healthy, and it is not: a refusal stands until an operator clears it,+ * which is exactly the condition an exit code exists to surface.+ *+ * So it gets its own number, on the precedent this repository already+ * set for "the run did not attempt" - `DOCTOR_EXIT.probeIncomplete` and+ * `SEARCH_CHECK_EXIT.probeIncomplete`. It is not 6, because 6 means "the+ * probe could not find out" on both of those surfaces and this run found+ * out precisely: it names the task and the streak.+ *+ * Precedence follows `exitCodeForCheck`: a proved failure keeps the+ * generic code even when another task was also refused, so the specific+ * number never masks the more basic finding.+ */+export const MAINTENANCE_EXIT = Object.freeze({+ ok: 0,+ failed: 1,+ usage: 2,+ refused: 7,+} as const);++export type MaintenanceExit = (typeof MAINTENANCE_EXIT)[keyof typeof MAINTENANCE_EXIT];++/** The four long operations the lane dispatches, in its own order. */+type LaneOperation = Extract<Operation, "dream" | "reindex" | "bridges" | "clusters">;export async function cmdBrainMaintenance(argv: string[]): Promise<number> {const { flags, positional } = parse(argv, {vault: { type: "string" },force: { type: "boolean" },+ retry: { type: "string-array" },window: { type: "string" },tz: { type: "string" },"busy-minutes": { type: "string" },"busy-threshold": { type: "string" },limit: { type: "string" },agent: { type: "string" },+ progress: { type: "boolean" },json: { type: "boolean" },});const op = positional[0];const asJson = flags["json"] === true;if (op !== "run" && op !== "status") {process.stderr.write(`${USAGE}\n`);- return 2;+ return MAINTENANCE_EXIT.usage;}const { config, vault } = brainVerbContext(flags);@@ -72,7 +120,7 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {const limit = limitRaw !== undefined ? Number(limitRaw) : 10;if (!Number.isInteger(limit) || limit < 1) {process.stderr.write("brain maintenance status: --limit must be a positive integer\n");- return 2;+ return MAINTENANCE_EXIT.usage;}const lease = currentLease(vault, { name: MAINTENANCE_LEASE_NAME, now });const journal = listJournal(vault, limit);@@ -81,10 +129,14 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {ok(lease === null ? "lease: free" : `lease: ${lease.holder} until ${lease.expiresAt}`);ok(`journal (${journal.length} recent):`);for (const e of journal) {- ok(` ${e.ts} ${e.verdict}${e.task ? ` ${e.task} ${e.ok ? "ok" : "FAILED"}` : ""}`);+ // A refusal row names its task but records no outcome, because+ // the task never ran; rendering it as FAILED would report an+ // attempt that did not happen.+ const outcome = e.ok === undefined ? "" : ` ${e.ok ? "ok" : "FAILED"}`;+ ok(` ${e.ts} ${e.verdict}${e.task ? ` ${e.task}${outcome}` : ""}`);}}- return 0;+ return MAINTENANCE_EXIT.ok;}let window: DailyWindow | undefined;@@ -97,7 +149,7 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {process.stderr.write(`brain maintenance run: --window must be H-H with hours 0..23, got: ${windowRaw}\n`,);- return 2;+ return MAINTENANCE_EXIT.usage;}window = { startHour, endHour, tz: (flags["tz"] as string | undefined) ?? "UTC" };}@@ -107,38 +159,78 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {process.stderr.write("brain maintenance run: --busy-minutes/--busy-threshold must be positive integers\n",);- return 2;+ return MAINTENANCE_EXIT.usage;}const holder =((flags["agent"] as string | undefined)?.trim() || resolveAgentName(config)) +`@${process.pid}`;+ // Progress is opt-in, on the same terms as every other long verb: a+ // sink attached by default would change the stderr of every cron+ // invocation that has ever run this lane.+ //+ // The lane is a DISPATCHER over four long operations, not a fifth+ // one, so it forwards the caller's sink to each task instead of+ // counting tasks itself. A lane-owned counter would emit "1 of 4"+ // and then say nothing for the length of a full reindex, which is+ // the silence this release exists to remove - and it would ALSO+ // double-count, because each of the four already reports its own+ // stages. Forwarding needs no change to `MaintenanceTask`: the tasks+ // are built here, so the sink reaches them by closure, and every+ // record names the operation that emitted it, which is exactly what+ // tells a reader which task the lane is currently inside. The MCP+ // lane took the same decision for the same reason; a second shape+ // here would make the two surfaces disagree about one mechanism.+ const observation =+ flags["progress"] === true+ ? attachProgress({ command: "brain", argv: ["maintenance"], jsonRequested: asJson })+ : null;+ reportProgressRefusal(observation);+ const laneProgress = observation?.sink !== undefined ? { onProgress: observation.sink } : {};+ // Everything that can throw before the lane starts happens BEFORE the+ // handle exists. `release` MUST run for every handle - it removes+ // process-global listeners and settles a signal nobody acted on - and+ // a throw between `onInterrupt()` and the `try` would skip it. This+ // was the one verb of the six that had the ordering wrong.+ const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });+ // Ctrl-C reaches the lane between tasks: `runMaintenance` awaits each+ // one, so a signal delivered during a task is dispatched before the+ // next task's first checkpoint. The lane records the abort as that+ // task's failure and releases the lease in its own `finally`, so the+ // vault is never left leased by a stopped run.+ const interrupt = onInterrupt(OPERATION.maintenance);// One fresh deadline per lane task: each long pass gets its own// budget (per-op key -> global -> default), created lazily so the// clock starts when the task starts, not when the lane is gated.- const laneSafeguard = (operation: "dream" | "reindex" | "bridges" | "clusters") =>+ const laneSafeguard = (operation: LaneOperation) =>createSafeguard({operation,timeoutMs: resolveSafeguardTimeoutMs(operation, config ?? undefined),+ signal: interrupt.signal,});- const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });- const result = await runMaintenance(vault, {- now,- holder,- force: flags["force"] === true,- ...(window !== undefined ? { window } : {}),- busy: { minutes: busyMinutes, threshold: busyThreshold },- tasks: [+ let result: Awaited<ReturnType<typeof runMaintenance>>;+ try {+ // Built once and read twice - the lane runs these, and `--retry` is+ // checked against their names. A second hard-coded list of the same+ // four names is a list that can disagree with this one.+ //+ // Inside the `try`, because the check below can return: a return+ // between `onInterrupt()` and the `try` would skip `release`.+ const laneTasks: ReadonlyArray<MaintenanceTask> = [{name: "dream",run: async () => {- dream(vault, { now, safeguard: laneSafeguard("dream") });+ dream(vault, { now, safeguard: laneSafeguard(OPERATION.dream), ...laneProgress });},},{name: "reindex",run: async () => {- await indexVault(searchConfig, { safeguard: laneSafeguard("reindex") });+ await indexVault(searchConfig, {+ safeguard: laneSafeguard(OPERATION.reindex),+ signal: interrupt.signal,+ ...laneProgress,+ });},},// Link-recall-intelligence passes ride the same lease, after@@ -151,7 +243,8 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {try {const report = discoverBridges(store, {dismissed: readDismissedBridges(vault),- safeguard: laneSafeguard("bridges"),+ safeguard: laneSafeguard(OPERATION.bridges),+ ...laneProgress,});writeBridgeProposals(vault, report, { now });try {@@ -179,7 +272,8 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {const store = await Store.open(searchConfig, { mode: "read" });try {const communities = detectCommunities(store, {- safeguard: laneSafeguard("clusters"),+ safeguard: laneSafeguard(OPERATION.clusters),+ ...laneProgress,});const materialized = materializeClusterNotes(vault, communities, { store, now });try {@@ -202,27 +296,82 @@ export async function cmdBrainMaintenance(argv: string[]): Promise<number> {}},},- ],- });+ ];+ const retryTasks = stringArrayFlag(flags["retry"]);+ const unknownRetries = retryTasks.filter(+ (name) => !laneTasks.some((task) => task.name === name),+ );+ if (unknownRetries.length > 0) {+ // Named, not ignored: a typo that silently retried nothing would+ // leave the operator reading a refusal they thought they had just+ // asked past.+ process.stderr.write(+ `brain maintenance run: --retry names no lane task: ${unknownRetries.join(", ")} ` ++ `(tasks: ${laneTasks.map((task) => task.name).join(", ")})\n`,+ );+ return MAINTENANCE_EXIT.usage;+ }+ result = await runMaintenance(vault, {+ now,+ holder,+ force: flags["force"] === true,+ ...(window !== undefined ? { window } : {}),+ busy: { minutes: busyMinutes, threshold: busyThreshold },+ ...(retryTasks.length > 0 ? { retryTasks } : {}),+ tasks: laneTasks,+ });- if (asJson) okJson({ verdict: result.verdict, tasks: result.tasks });- else {- ok(`maintenance: ${result.verdict}`);- for (const t of result.tasks) {- ok(` ${t.name}: ${t.ok ? "ok" : `FAILED (${t.error})`} in ${t.duration_ms}ms`);+ if (asJson) okJson({ verdict: result.verdict, tasks: result.tasks });+ else {+ ok(`maintenance: ${result.verdict}`);+ for (const t of result.tasks) {+ // A refused task never ran, so it is neither `ok` nor FAILED and+ // has no duration to report - printing `in 0ms` would describe an+ // attempt that did not happen. The lane's row omits `ok` for the+ // same reason; this line agrees with it.+ if (t.refused === true) ok(` ${t.name}: REFUSED (${t.error})`);+ else ok(` ${t.name}: ${t.ok ? "ok" : `FAILED (${t.error})`} in ${t.duration_ms}ms`);+ }+ }+ // A stopped lane is reported as stopped, not as four failures. The+ // lane catches each task's abort and journals it, so without this the+ // run would exit 1 - a code that says "these passes are broken" about+ // passes the operator simply cancelled. The report above is written+ // first either way: the journal is what makes the stop auditable.+ //+ // Decided INSIDE the try, before `release`: the acknowledgement and+ // the exit code are the same decision, and a `release` that ran+ // first would re-raise the signal this arm is in the middle of+ // reporting.+ if (interrupt.received() !== null) {+ interrupt.acknowledge();+ return interrupt.exitCode();}+ // An attempted failure outranks a refusal: see {@link MAINTENANCE_EXIT}.+ if (result.tasks.some((t) => !t.ok && t.refused !== true)) return MAINTENANCE_EXIT.failed;+ return result.tasks.some((t) => t.refused === true)+ ? MAINTENANCE_EXIT.refused+ : MAINTENANCE_EXIT.ok;+ } finally {+ interrupt.release();}- return result.tasks.some((t) => !t.ok) ? 1 : 0;} catch (exc) {const message = `maintenance ${op} failed: ${(exc as Error).message ?? exc}`;if (asJson) {okJson({ ok: false, message });- return 1;+ return MAINTENANCE_EXIT.failed;}return fail(message);}}+/** A repeatable flag's values; a flag never passed is an empty list. */+function stringArrayFlag(raw: unknown): string[] {+ return Array.isArray(raw)+ ? raw.filter((value): value is string => typeof value === "string")+ : [];+}+function numberFlag(raw: unknown, fallback: number): number | null {if (raw === undefined) return fallback;const value = Number(raw);diff --git a/src/cli/brain/verbs/rollback.ts b/src/cli/brain/verbs/rollback.tsindex 8365db83..bea5d1dd 100644--- a/src/cli/brain/verbs/rollback.ts+++ b/src/cli/brain/verbs/rollback.ts@@ -4,6 +4,7 @@ import {extractSnapshotToTemp,type ExtractSnapshotResult,type SnapshotInfo,+ type SnapshotListing,} from "../../../core/brain/snapshot.ts";import { restoreSnapshotWithRecoveryPoint } from "../../../core/brain/snapshot-gate.ts";import {@@ -14,7 +15,6 @@ import {readManifestSidecar,renderManifestDriftJson,renderManifestDriftMarkdown,- type BrainManifestDerivedStore,} from "../../../core/brain/manifest.ts";import { diffBrainTrees } from "../../../core/brain/snapshot-diff.ts";import { renderDiffJson, renderDiffMarkdown } from "../../../core/brain/snapshot-diff-render.ts";@@ -35,6 +35,7 @@ import {renderDerivedStoreCoverage,renderDerivedStoreRestore,renderSnapshotListingFailure,+ renderSnapshotListingSkips,renderSnapshotReason,} from "../snapshot-render.ts";@@ -56,9 +57,9 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {if (!flags["list"] && positional.length < 1)return fail("brain rollback requires a <run_id> argument (or --list to enumerate snapshots)");- let snaps: SnapshotInfo[];+ let listing: SnapshotListing;try {- snaps = listSnapshots(vault);+ listing = listSnapshots(vault);} catch (exc) {// A directory nobody could read must never be rendered as a vault// with no recovery points: that is the answer an operator would act@@ -66,14 +67,29 @@ export async function cmdBrainRollback(argv: string[]): Promise<number> {if (exc instanceof BrainSnapshotListingError) return fail(renderSnapshotListingFailure(exc));throw exc;}+ const snaps: SnapshotInfo[] = listing.snapshots;+ // One archive nobody could describe is the same failure one level down:+ // it is absent from the list an operator picks a run id out of, and from+ // the `snapshot not found` sentence below. Named rather than dropped.+ if (listing.skipped.length > 0) {+ process.stderr.write(renderSnapshotListingSkips(listing.skipped) + "\n");+ }if (flags["list"]) {if (flags["json"]) {+ // The payload stays the bare array it has always been - re-nesting+ // it to carry the skipped entries would break every script reading+ // this verb, for a fact the warning above has already stated and+ // that `o2b brain snapshot log --json` carries as data.process.stdout.write(JSON.stringify(snaps, null, 2) + "\n");return 0;}if (snaps.length === 0) {- ok("no snapshots available");+ ok(+ listing.skipped.length > 0+ ? "no snapshots could be listed (see the warning above; the directory is not empty)"+ : "no snapshots available",+ );return 0;}ok("run_id\tcreated_at\treason\tsize_bytes\tderived_store");diff --git a/src/cli/brain/verbs/snapshot.ts b/src/cli/brain/verbs/snapshot.tsindex 170de5b1..72d55e44 100644--- a/src/cli/brain/verbs/snapshot.ts+++ b/src/cli/brain/verbs/snapshot.ts@@ -4,6 +4,7 @@ import {extractSnapshotToTemp,type ExtractSnapshotResult,type SnapshotInfo,+ type SnapshotListing,} from "../../../core/brain/snapshot.ts";import { diffBrainTrees } from "../../../core/brain/snapshot-diff.ts";import { renderDiffJson, renderDiffMarkdown } from "../../../core/brain/snapshot-diff-render.ts";@@ -17,6 +18,7 @@ import { brainVerbContext, fail, ok, parse, usageError } from "../helpers.ts";import {renderDerivedStoreCoverage,renderSnapshotListingFailure,+ renderSnapshotListingSkips,SNAPSHOT_UNKNOWN_LABEL,} from "../snapshot-render.ts";@@ -84,13 +86,20 @@ export async function cmdBrainSnapshotLog(argv: string[]): Promise<number> {// failure of the listing, not a listing of nothing - so it is reported// before either output shape, and neither the empty-history line below// nor an empty `--json` array can stand in for it.- let all: SnapshotInfo[];+ let listing: SnapshotListing;try {- all = listSnapshots(vault);+ listing = listSnapshots(vault);} catch (exc) {if (exc instanceof BrainSnapshotListingError) return fail(renderSnapshotListingFailure(exc));throw exc;}+ const all = listing.snapshots;+ // Same rule one level down: an archive that is on disk and could not be+ // described is missing from every count below, so the incompleteness is+ // said out loud rather than left to be inferred from a shorter table.+ if (listing.skipped.length > 0) {+ process.stderr.write(renderSnapshotListingSkips(listing.skipped) + "\n");+ }// The reason filter compares against what the SIDECAR recorded, so a// snapshot whose reason is unknown is never swept into a named bucket by@@ -100,7 +109,11 @@ export async function cmdBrainSnapshotLog(argv: string[]): Promise<number> {if (flags["json"]) {process.stdout.write(- JSON.stringify({ total: snaps.length, snapshots: snaps.map(renderLogJson) }, null, 2) + "\n",+ JSON.stringify(+ { total: snaps.length, snapshots: snaps.map(renderLogJson), skipped: listing.skipped },+ null,+ 2,+ ) + "\n",);return 0;}@@ -109,7 +122,14 @@ export async function cmdBrainSnapshotLog(argv: string[]): Promise<number> {// Zero, not an error: the directory was read (an unreadable one was// reported above) and the answer is none. The filter is echoed so an// operator who mistyped a valid reason can see which one was applied.- ok(reason === undefined ? "no snapshots available" : `no snapshots with reason '${reason}'`);+ // "None" is qualified when archives were skipped, because "no+ // snapshots available" over a directory holding archives nobody could+ // describe is the sentence this listing must never print.+ const none =+ listing.skipped.length > 0+ ? "no snapshots could be listed (see the warning above; the directory is not empty)"+ : "no snapshots available";+ ok(reason === undefined ? none : `no snapshots with reason '${reason}'`);return 0;}ok(LOG_COLUMNS.join("\t"));@@ -175,14 +195,20 @@ export async function cmdBrainSnapshotDiff(argv: string[]): Promise<number> {}const [a, b] = positional;// Same reason as the log verb: "snapshot not found" over a directory- // nobody could read names the wrong cause.- let snaps: SnapshotInfo[];+ // nobody could read names the wrong cause. And an archive that could not+ // be described is exactly the archive an operator is most likely to be+ // asking about here, so it is named before the not-found line below.+ let listing: SnapshotListing;try {- snaps = listSnapshots(vault);+ listing = listSnapshots(vault);} catch (exc) {if (exc instanceof BrainSnapshotListingError) return fail(renderSnapshotListingFailure(exc));throw exc;}+ const snaps = listing.snapshots;+ if (listing.skipped.length > 0) {+ process.stderr.write(renderSnapshotListingSkips(listing.skipped) + "\n");+ }if (!snaps.some((s) => s.run_id === a)) {process.stderr.write(`snapshot not found: ${a}; run \`o2b brain snapshot log\` to enumerate.\n`,diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex b7f1ac97..49b47039 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -535,6 +535,7 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({flag("force-cost", "boolean"),flag("concurrency", "string"),flag("verbose", "boolean"),+ flag("progress", "boolean"),]),command("reindex", "Rebuild the search index", [flag("vault", "string"),@@ -544,8 +545,10 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({flag("force-cost", "boolean"),flag("concurrency", "string"),flag("verbose", "boolean"),+ flag("progress", "boolean"),flag("cron-template", "boolean"),flag("interval", "string"),+ flag("self-heal", "string"),]),command("watch", "Watch the vault and incrementally sync the index on .md edits"),command("status", "Print search index status"),@@ -572,9 +575,22 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({command("rerank-provider", "Manage reranker provider profiles"),command("rerank-fit", "Diagnose whether the configured reranker fits this vault's queries"),command("plan", "Preview the should-read shortlist for a query without reading the notes"),+ // The whole `parseFlags` schema, for the reason the two builders+ // above give: there is no per-verb `--help` on this family, so a+ // flag the manifest does not model is a flag neither help nor+ // completions can offer. `--progress` arrived here last and would+ // have been the third such flag.command("vector-backfill","Compute vectors for indexed chunks that have none (dry-run unless --apply)",+ [+ flag("vault", "string"),+ flag("config", "string"),+ flag("db", "string"),+ flag("apply", "boolean"),+ flag("force-cost", "boolean"),+ flag("progress", "boolean"),+ ],),command("event-anchor-backfill",diff --git a/src/cli/install/install.ts b/src/cli/install/install.tsindex 8b6d7c26..ebc0eb3b 100644--- a/src/cli/install/install.ts+++ b/src/cli/install/install.ts@@ -28,13 +28,16 @@import { homedir } from "node:os";import { parseFlags } from "../argparse.ts";-import { defaultConfigPath, discoverConfig } from "../../core/config.ts";+import { defaultConfigPath, discoverConfig, resolveVault } from "../../core/config.ts";import { defaultRegistry } from "../../core/install/registry.ts";// The canonical adapter set registers itself into `defaultRegistry` at// module-load time via this barrel (single source of the adapter list).import "../../core/install/adapters/all.ts";import { buildPayload, PayloadError } from "../../core/install/payload.ts";+import { renderDataOwnership } from "../../core/install/ownership.ts";+import type { DataOwnership } from "../../core/install/ownership.ts";+import { measureDataOwnership } from "../../core/install/ownership-measure.ts";import { InstallError } from "../../core/install/types.ts";import type { ApplyOpts, InstallEnv, VerifyResult } from "../../core/install/types.ts";import {@@ -43,6 +46,7 @@ import {renderDetectJson,renderDetectTable,renderPlan,+ renderPlanJson,renderVerifyJson,renderVerifyTable,} from "./render.ts";@@ -110,9 +114,33 @@ function parseInstallArgs(argv: string[]): ParsedInstallArgs {class UsageError extends Error {}+/**+ * The vault this verb installs FOR, resolved through the one chain the+ * rest of the CLI uses.+ *+ * `--vault` comes first because it is the operator naming the directory in+ * the same breath as the command; everything below it is+ * {@link resolveVault} verbatim - `VAULT_DIR`, the project pointer, the+ * active profile, then the config `vault` key - so the path written into+ * an agent's MCP entry is the path every other verb operates on.+ *+ * This verb used to carry its own chain (`--vault` then the config key+ * then `VAULT_DIR`), which put `VAULT_DIR` LAST where the canonical+ * resolver puts it FIRST and consulted neither pointers nor profiles. On a+ * machine with both settings the installer wrote one vault into the MCP+ * config while `o2b status` read another, and nothing reported the split.+ *+ * The absent case stays the empty string rather than `null`: every caller+ * here refuses it by name (`runCheck`, {@link loadPayload}) and an+ * `InstallEnv.vault` is typed `string`.+ */+export function resolveInstallVault(explicitVault: string | null, configPath: string): string {+ return explicitVault ?? resolveVault(configPath) ?? "";+}+function buildInstallEnv(args: ParsedInstallArgs): InstallEnv {const cfg = discoverConfig(args.config).data;- const vault = args.vault ?? cfg["vault"] ?? process.env["VAULT_DIR"] ?? "";+ const vault = resolveInstallVault(args.vault, args.config);const env = { ...process.env } as Record<string, string>;if (cfg["agent_name"]) env["VAULT_AGENT_NAME"] = cfg["agent_name"];if (cfg["timezone"]) env["VAULT_TIMEZONE"] = cfg["timezone"];@@ -142,7 +170,12 @@ function buildApplyOpts(function loadPayload(args: ParsedInstallArgs, env: InstallEnv) {const cfg = discoverConfig(args.config).data;- const vault = env.vault || cfg["vault"];+ // `env.vault` is already {@link resolveInstallVault}'s answer, and that+ // chain ends on the same `vault` config key this used to re-read as a+ // fallback. Keeping the second read would mean an empty `env.vault`+ // could still produce a payload built against a key the canonical+ // resolver had just declined - a third precedence, in one function.+ const vault = env.vault;if (!vault) {throw new UsageError("o2b install: vault not configured. Pass --vault <path>, set VAULT_DIR, or run `o2b init`.",@@ -155,6 +188,31 @@ function loadPayload(args: ParsedInstallArgs, env: InstallEnv) {});}+/**+ * The data-ownership close, for a run that established something.+ *+ * Built here rather than inside a renderer so BOTH surfaces consume one+ * value: the human block and the `data_ownership` JSON field are two views+ * of this record, which is what stops them being added separately - the+ * failure mode the install verb already had, where the human `--check`+ * table is pinned byte-for-byte against the install documents and the JSON+ * twin was pinned by nothing.+ *+ * Every measurement the statement needs is taken by+ * {@link measureDataOwnership}, which the onboarding checklist calls too -+ * the two surfaces cannot disagree about where the index landed or which+ * outbound integrations are configured, because they ask the same+ * function. This verb supplies only what it alone owns: the resolved vault+ * and the live adapter registry.+ */+function ownershipFor(env: InstallEnv, configPath: string): DataOwnership {+ return measureDataOwnership({+ vault: env.vault,+ configPath,+ adapterTargets: defaultRegistry.targets(),+ });+}+export async function cmdInstall(argv: string[]): Promise<number> {let args: ParsedInstallArgs;try {@@ -224,7 +282,7 @@ function runTarget(args: ParsedInstallArgs): number {// Plan-only (no --apply, no --check) — print and return.if (!args.apply) {if (args.json) {- process.stdout.write(JSON.stringify({ schema_version: 1, plan }, null, 2) + "\n");+ process.stdout.write(renderPlanJson(plan));} else {process.stdout.write(renderPlan(plan));}@@ -233,10 +291,15 @@ function runTarget(args: ParsedInstallArgs): number {try {const result = adapter.apply(plan, payload, env, opts);+ // An apply that returned changed the machine, so the close fires+ // unconditionally here - unlike verify, where exit 0 also covers a+ // runtime nobody installed.+ const ownership = ownershipFor(env, args.config);if (args.json) {- process.stdout.write(renderApplyJson(result));+ process.stdout.write(renderApplyJson(result, ownership));} else {process.stdout.write(renderApplyResult(result));+ process.stdout.write(renderDataOwnership(ownership));}return INSTALL_EXIT.ok;} catch (e) {@@ -280,10 +343,16 @@ function runCheck(args: ParsedInstallArgs): number {}const results: VerifyResult[] = [];for (const a of targets) results.push(a.verify(env));+ // Exit 0 is NOT the trigger. `not-installed` is also 0, deliberately -+ // the operator never asked for that runtime - so a close fired on the+ // code would be the entire output of a run where the install did+ // nothing, congratulating an operator on a brain nothing points at.+ const ownership = results.some((r) => r.status === "ok") ? ownershipFor(env, args.config) : null;if (args.json) {- process.stdout.write(renderVerifyJson(results));+ process.stdout.write(renderVerifyJson(results, ownership));} else {process.stdout.write(renderVerifyTable(results));+ if (ownership !== null) process.stdout.write(renderDataOwnership(ownership));}return exitCodeForVerify(results);}diff --git a/src/cli/install/render.ts b/src/cli/install/render.tsindex d25ee655..3813c837 100644--- a/src/cli/install/render.ts+++ b/src/cli/install/render.ts@@ -4,8 +4,22 @@* Two surfaces: human-readable text (default) and JSON (`--json`).* Both forms describe the same data so the agent can switch on* `--json` without losing detail.+ *+ * ## One envelope, because there used to be four+ *+ * This verb has four modes and each built its own `--json` payload. Three+ * declared `schema_version: 1`; apply - the only mode that CHANGES the+ * machine - declared none, and the plan payload was assembled inline in+ * `install.ts` rather than here at all. No test asserted a field name in+ * any of them, while the human `--check` table is pinned byte-for-byte+ * against the `install/<runtime>.md` documents.+ *+ * {@link installJson} is the single exit now, so a payload cannot be+ * emitted without a version, and `tests/cli/install-json-shape.test.ts`+ * pins the key set of all four.*/+import type { DataOwnership } from "../../core/install/ownership.ts";import type {ApplyResult,DetectResult,@@ -13,6 +27,40 @@ import type {VerifyResult,} from "../../core/install/types.ts";+/**+ * The version every payload below declares.+ *+ * Still 1 after apply gained the key: the field is ADDITIVE on a payload+ * that previously had no version to compare against, and the three modes+ * that already said 1 describe the same shapes they always did. A consumer+ * pinning `=== 1` keeps working, which a bump would have broken to+ * announce a change that took nothing away.+ */+export const INSTALL_JSON_SCHEMA_VERSION = 1;++/**+ * The machine-readable half of the ownership close.+ *+ * Named once, for the reason `NEXT_COMMAND_KEY` is: the CLI renderer and+ * anything that reads the payload back must not drift on the spelling.+ * NOT `handoff` - that name already means the operator-readable session+ * notes under `Brain/handoffs/`, and one word for two records is how a+ * field becomes unsearchable.+ */+export const DATA_OWNERSHIP_KEY = "data_ownership";++/**+ * Serialise one `--json` payload.+ *+ * The version is prepended here rather than spelled at each call site -+ * the whole reason the apply payload could ship without one.+ */+export function installJson(payload: Readonly<Record<string, unknown>>): string {+ return (+ JSON.stringify({ schema_version: INSTALL_JSON_SCHEMA_VERSION, ...payload }, null, 2) + "\n"+ );+}+export interface DetectTableRow {readonly target: string;readonly status: string;@@ -55,16 +103,23 @@ export function renderDetectTable(rows: ReadonlyArray<DetectResult>): string {}export function renderDetectJson(rows: ReadonlyArray<DetectResult>): string {- const payload = {- schema_version: 1,+ return installJson({targets: rows.map((r) => ({target: r.target,status: r.status,config_path: r.configPath,notes: r.notes,})),- };- return JSON.stringify(payload, null, 2) + "\n";+ });+}++/**+ * The plan payload. It lived inline in `install.ts` and moves here so all+ * four `--json` shapes are readable in one file - the arrangement that+ * would have made the missing version on apply obvious.+ */+export function renderPlanJson(plan: InstallPlan): string {+ return installJson({ plan });}export function renderPlan(plan: InstallPlan): string {@@ -104,8 +159,17 @@ export function renderApplyResult(result: ApplyResult): string {return lines.join("\n");}-export function renderApplyJson(result: ApplyResult): string {- return JSON.stringify(result, null, 2) + "\n";+/**+ * The apply payload.+ *+ * The version is added BESIDE the result's own fields rather than nesting+ * the result under a key: a consumer reading `.manifest` or+ * `.steps_executed` keeps working and gains a version it never had, which+ * a re-nesting would have broken to announce a change that took nothing+ * away.+ */+export function renderApplyJson(result: ApplyResult, ownership: DataOwnership): string {+ return installJson({ ...result, [DATA_OWNERSHIP_KEY]: ownership });}export function renderVerifyTable(rows: ReadonlyArray<VerifyResult>): string {@@ -122,6 +186,12 @@ export function renderVerifyTable(rows: ReadonlyArray<VerifyResult>): string {return lines.join("\n");}-export function renderVerifyJson(rows: ReadonlyArray<VerifyResult>): string {- return JSON.stringify({ schema_version: 1, targets: rows }, null, 2) + "\n";+export function renderVerifyJson(+ rows: ReadonlyArray<VerifyResult>,+ ownership: DataOwnership | null,+): string {+ return installJson({+ targets: rows,+ ...(ownership === null ? {} : { [DATA_OWNERSHIP_KEY]: ownership }),+ });}diff --git a/src/cli/interrupt.ts b/src/cli/interrupt.tsnew file mode 100644index 00000000..e5458e5d--- /dev/null+++ b/src/cli/interrupt.ts@@ -0,0 +1,280 @@+/**+ * Ctrl-C reaches the operations that can hear it (nothing-runs-unwatched, U3).+ *+ * The cooperative-cancellation contract was already written and never+ * connected. `createSafeguard` accepts a `signal`, checks it in priority+ * over the deadline, and throws `SafeguardAbortError` - a class kept+ * deliberately distinct from `SafeguardTimeoutError` so, in its own+ * words, "the watch shutdown coordinator can treat an intentional abort+ * as a clean stop rather than a failure". Not one production call site+ * passed a signal, so that class was unreachable and every long verb had+ * exactly one way to stop: the deadline, or SIGKILL.+ *+ * This module is the missing half, and it is deliberately smaller than+ * the half that was first written here.+ *+ * ## Why four of the six operations get no handle at all+ *+ * A Node/Bun signal handler is a JavaScript callback dispatched from the+ * event loop. `dreamRun`, `detectCommunitiesRun`, `discoverBridgesRun`+ * and `generateRun` are declared `function`, not `async`, and contain no+ * `await`: from the moment the pass starts until the moment it returns,+ * the process never re-enters the event loop, so the handler cannot run.+ * Measured against these exact modules - a real SIGINT delivered 0.3 s+ * into a synchronous `checkpoint()` loop - 27,356,853 checkpoints ran+ * with the signal pending, `SafeguardAbortError` was never thrown, and+ * `received()` was still `null` when the loop ended. One turn of the+ * event loop later it was `"SIGINT"`. The signal was never lost; it was+ * unobservable for the entire duration of the work.+ *+ * `safeguard.ts` already states the general form of this - "a JavaScript+ * timer cannot interrupt a fully-synchronous CPU hang on a single+ * thread" - and frames it as the pathological case. For these four it is+ * the NORMAL case: they are synchronous end to end, so the whole pass is+ * a region no cooperative signal can enter.+ *+ * Making them `async` does not fix it and would hide it. An `await` on a+ * resolved promise is a MICROtask, and microtasks drain without ever+ * yielding to libuv: 4,810,652 `await Promise.resolve()` iterations with+ * a SIGINT pending, and `received()` still `null`. Only a macrotask yield+ * (`setImmediate`) lets the handler run, at ~184 k yields/s against+ * ~13.7 M synchronous checkpoints/s. An async rewrite would therefore+ * have to insert a purpose-built macrotask yield at every checkpoint+ * across 137 call sites - and if any one of them used a plain `await`, it+ * would reproduce this exact false claim invisibly.+ *+ * So the honest answer is not to make the handler work where it cannot.+ * It is to install it only where the operation actually yields, and to+ * leave the default disposition in place everywhere else - where the+ * keystroke keeps doing what it did before this branch existed: killing+ * the process at once. Those four write atomically (`atomicWriteFileSync`+ * in dream, plan-then-write under one lock in architect), so a pass+ * killed mid-way leaves no half-written artifact.+ *+ * ## Why an unobserved signal still ends the run+ *+ * Registering a listener suppresses the default terminate for as long as+ * it is registered, and every verb holds the handle across work that+ * never consults the signal: `Store.open`, a proposal write, a report+ * render, the reindex swap. A Ctrl-C landing there aborted a controller+ * nobody read, and the verb returned 0 - a success code for a run the+ * operator stopped. So {@link InterruptHandle.release} reconciles: a+ * signal that arrived and was never acknowledged is re-raised, which ends+ * the process the way the keystroke would have. Suppressing the default+ * is a loan against the operation acting on it, and `release` is where+ * the loan is called in.+ *+ * `process.once` rather than `process.on`, following the one working+ * teardown in the repository, `IndexWatchRunner`'s: a SECOND interrupt is+ * not intercepted and falls through to the default handler that+ * force-kills.+ *+ * The exit code is the shell's own convention rather than a new project+ * vocabulary: 128 plus the signal number. It matters that it is not 0.+ * `o2b search watch` exits 0 when interrupted because stopping IS how+ * that command ends; a consolidation pass interrupted half-way did not+ * do what it was asked, and reporting that as success is exactly the+ * misleading quiet this release removes.+ */++import { OPERATION, type Operation } from "../core/brain/safeguard.ts";++import { okJson } from "./output.ts";++const SIGINT_EXIT = 130;+const SIGTERM_EXIT = 143;++/**+ * Exit code for a run the operator stopped with Ctrl-C. 128 + SIGINT(2).+ */+export const EXIT_INTERRUPTED = SIGINT_EXIT;++/** Exit code for a run stopped by SIGTERM. 128 + SIGTERM(15). */+export const EXIT_TERMINATED = SIGTERM_EXIT;++/** The signals a long foreground verb listens for. */+const HANDLED_SIGNALS = Object.freeze(["SIGINT", "SIGTERM"] as const);++type HandledSignal = (typeof HANDLED_SIGNALS)[number];++const EXIT_FOR_SIGNAL: Readonly<Record<HandledSignal, number>> = Object.freeze({+ SIGINT: EXIT_INTERRUPTED,+ SIGTERM: EXIT_TERMINATED,+});++/**+ * Whether each long operation yields to the event loop while it runs.+ *+ * One table rather than a convention followed six times, for the reason+ * `progressReasonForError` lives in the spine: the fact that decides+ * whether a handle may be opened is the fact a reader needs, and six+ * copies of it are six chances for the seventh verb to guess. A new+ * member of `OPERATION` cannot compile without answering here, which is+ * the point - the question is easy to answer and impossible to ask+ * yourself unprompted.+ *+ * `reindex` awaits real I/O between files and between embed batches, and+ * checks `throwIfAborted` at both boundaries. The maintenance lane awaits+ * between its four tasks, so a signal delivered during one task is seen+ * before the next one starts - which is also why the lane's own+ * sub-passes are listed `false` here and cancelled through the lane+ * rather than on their own.+ */+const YIELDS_TO_EVENT_LOOP: Readonly<Record<Operation, boolean>> = Object.freeze({+ [OPERATION.dream]: false,+ [OPERATION.bridges]: false,+ [OPERATION.clusters]: false,+ [OPERATION.architect]: false,+ [OPERATION.reindex]: true,+ [OPERATION.maintenance]: true,+});++/**+ * Whether a cooperative interrupt can reach `operation` at all.+ *+ * The predicate a verb consults before it decides to advertise Ctrl-C,+ * and the predicate `docs/cli-reference.md` is written from.+ */+export function interruptIsObservable(operation: Operation): boolean {+ return YIELDS_TO_EVENT_LOOP[operation];+}++export interface InterruptHandle {+ /** Hand this to `createSafeguard`; the next checkpoint throws when set. */+ readonly signal: AbortSignal;+ /** Which signal arrived, or `null` while none has. */+ readonly received: () => HandledSignal | null;+ /**+ * The exit code for the signal that arrived, or {@link EXIT_INTERRUPTED}+ * when a stop is reported without one - an abort raised by a caller+ * rather than by a key press.+ */+ readonly exitCode: () => number;+ /**+ * Declare that the run has acted on the interrupt: it stopped at a+ * checkpoint and the verb is about to return {@link exitCode}. Called+ * for you by {@link reportInterrupted}; a verb that reports a stop its+ * own way - the maintenance lane does, from its journal - calls it+ * directly.+ *+ * Without it {@link release} cannot tell a stop that was honoured from+ * a signal that was swallowed, and it must assume the latter, because+ * assuming the former is how a stopped run exits 0.+ */+ readonly acknowledge: () => void;+ /**+ * Stop listening, and settle an interrupt nobody acted on.+ *+ * MUST be called in a `finally`: the listeners are process-global, and+ * a verb that returns without releasing leaves a dead controller wired+ * to the next signal. When a signal arrived and {@link acknowledge} was+ * never called, this does not return - it re-raises, ending the process+ * as the un-suppressed keystroke would have.+ */+ readonly release: () => void;+}++/** Thrown when a handle is asked for on behalf of an operation that cannot see it. */+export class UnobservableInterruptError extends Error {+ readonly operation: Operation;++ constructor(operation: Operation) {+ super(+ `${operation} runs to completion without yielding to the event loop, so a ` ++ "signal handler cannot run while it does. Opening a handle would only " ++ "suppress the default terminate and swallow the operator's Ctrl-C; leave " ++ "the signal alone so the keystroke still stops the process.",+ );+ this.name = "UnobservableInterruptError";+ this.operation = operation;+ }+}++/**+ * Listen for an interrupt for the duration of one `operation`.+ *+ * Throws {@link UnobservableInterruptError} for an operation that cannot+ * observe one. A handle that installed nothing would be worse than the+ * throw: the call site would read as cancelled-on-request and behave as+ * uncancellable, which is the state this module was written to end.+ *+ * Concurrent handles are not supported and are not defended against. Node+ * dispatches a signal to EVERY registered listener, so two overlapping+ * handles both abort - the hazard is not a missed abort but a `release`+ * on one handle re-raising a signal the other already acted on. Long+ * verbs are one-per-process here; `cmdBrainDream` opens its staged handle+ * and the inline one sequentially, never at once.+ */+export function onInterrupt(operation: Operation): InterruptHandle {+ if (!interruptIsObservable(operation)) throw new UnobservableInterruptError(operation);++ const controller = new AbortController();+ let received: HandledSignal | null = null;+ let acknowledged = false;+ let released = false;+ const listeners = new Map<HandledSignal, () => void>();++ for (const name of HANDLED_SIGNALS) {+ const listener = (): void => {+ received = name;+ controller.abort();+ };+ listeners.set(name, listener);+ process.once(name, listener);+ }++ return Object.freeze({+ signal: controller.signal,+ received: () => received,+ exitCode: () => (received === null ? EXIT_INTERRUPTED : EXIT_FOR_SIGNAL[received]),+ acknowledge: () => {+ acknowledged = true;+ },+ release: () => {+ if (released) return;+ released = true;+ for (const [name, listener] of listeners) process.removeListener(name, listener);+ listeners.clear();+ if (received === null || acknowledged) return;+ const signal = received;+ process.stderr.write(+ `interrupted: ${signal} arrived while ${operation} was in a region that does not ` ++ "check for it, so the run could not stop at a boundary; stopping now\n",+ );+ // Our listeners are gone, so with nothing else holding this signal+ // the default disposition is back and this call does not return.+ process.kill(process.pid, signal);+ // Reached only when another subsystem in this process still holds a+ // listener for the signal and absorbed the re-raise. The run must+ // still not report success, so it ends here by exit code instead.+ process.exit(EXIT_FOR_SIGNAL[signal]);+ },+ });+}++/**+ * Report a run the operator stopped, and give back its exit code.+ *+ * The long verbs that reach this arm all say the same two things: the+ * stop is not a crash, and it is not a success. Written once here rather+ * than retyped per verb, for the reason `progressReasonForError` lives in+ * the spine rather than at each of the operations - copies of one fact+ * are chances for one of them to report a deliberate stop as a failure,+ * which is the distinction `SafeguardAbortError` exists to keep.+ *+ * Acknowledging is part of reporting, not a second step a caller could+ * forget: a stop that has been reported has been acted on, and `release`+ * must not then re-raise it.+ *+ * A `--json` caller gets the refusal as a document because its stdout is a+ * payload it parses; a human gets the line on stderr, where the verb's+ * other diagnostics already are. The two are exclusive: a JSON run that+ * also wrote the prose line would put the same fact on two streams, and a+ * human run has no document to put it in.+ */+export function reportInterrupted(handle: InterruptHandle, error: Error, asJson: boolean): number {+ handle.acknowledge();+ if (asJson) okJson({ ok: false, interrupted: true, message: error.message });+ else process.stderr.write(`${error.message}\n`);+ return handle.exitCode();+}diff --git a/src/cli/main.ts b/src/cli/main.tsindex 8e8f0c02..6b1b5061 100644--- a/src/cli/main.ts+++ b/src/cli/main.ts@@ -281,6 +281,45 @@ function writeSearchInitBlock(vault: string, configPath: string, stream: Advisor);}+/**+ * Every code `o2b doctor` can return, named once so the returns below and+ * the tests read the same table.+ *+ * `probeIncomplete` carries the value `o2b search check` already spends on+ * a probe that did not complete, so one number means one thing across this+ * CLI; the assertion that they agree lives in the tests. It exists because+ * the other two numbers were both wrong for that finding. A readiness+ * probe whose budget elapsed used to be counted as a failure and exit 1,+ * which made a loaded machine report a healthy installation as broken;+ * classifying it honestly (see `READINESS_STATUS.unknown`) would otherwise+ * have moved it into the 0 that says the opposite. A run that could not+ * find out is neither, and now says so.+ */+export const DOCTOR_EXIT = Object.freeze({+ ok: 0,+ failed: 1,+ probeIncomplete: 6,+} as const);++export type DoctorExit = (typeof DOCTOR_EXIT)[keyof typeof DOCTOR_EXIT];++/**+ * The exit this run earned, from the counts rather than from what was+ * printed.+ *+ * Precedence follows `exitCodeForCheck` in `search/verbs/check.ts`: a+ * PROVED failure keeps the generic code even when a probe also failed to+ * complete, so the specific code never masks the more basic finding.+ */+export function doctorExitCode(+ failedChecks: number,+ readiness: ReadinessReport | null,+): DoctorExit {+ if (failedChecks > 0 || (readiness?.failed ?? 0) > 0) return DOCTOR_EXIT.failed;+ if ((readiness?.unknown ?? 0) > 0) return DOCTOR_EXIT.probeIncomplete;+ return DOCTOR_EXIT.ok;+}+async function cmdDoctor(argv: string[]): Promise<number> {const { flags } = parseFlags(argv, {vault: { type: "string" },@@ -305,7 +344,7 @@ async function cmdDoctor(argv: string[]): Promise<number> {if (parity) results.push(parity);} catch (exc) {process.stderr.write(`error: doctor failed: ${(exc as Error).message ?? exc}\n`);- return 1;+ return DOCTOR_EXIT.failed;}const failed = results.filter((r) => !r.ok).length;@@ -318,14 +357,23 @@ async function cmdDoctor(argv: string[]): Promise<number> {readiness = await runReadinessProbes({ vault, config, cwd: process.cwd() });} catch (exc) {process.stderr.write(`error: doctor readiness failed: ${(exc as Error).message ?? exc}\n`);- return 1;+ // The readiness run itself did not complete, so it established+ // nothing about readiness - but a base check that already failed is a+ // proved fault and outranks it, exactly as inside `doctorExitCode`.+ return failed > 0 ? DOCTOR_EXIT.failed : DOCTOR_EXIT.probeIncomplete;}}- const readinessFailed = readiness?.failed ?? 0;+ const exitCode = doctorExitCode(failed, readiness);if (flags["json"]) {const payload = {- ok: failed === 0 && readinessFailed === 0,+ // Read off the same exit code the process returns, so the two+ // surfaces of one command cannot give contradictory answers. It is+ // two-valued and so cannot distinguish a proved failure from a run+ // that could not find out - `false` means only "not established as+ // healthy". WHICH of the two it was is in `readiness_summary`, in+ // each probe's own `status`, and in the exit code itself.+ ok: exitCode === DOCTOR_EXIT.ok,checks: results.map((r) => ({name: r.name,ok: r.ok,@@ -340,12 +388,20 @@ async function cmdDoctor(argv: string[]): Promise<number> {detail: p.detail,duration_ms: p.durationMs,})),+ // The counts the human shape has always printed on its summary+ // line, so a caller reading JSON is not the only one who has to+ // reduce the array to learn that something went unmeasured.+ readiness_summary: {+ probes: readiness.probes.length,+ failed: readiness.failed,+ unknown: readiness.unknown,+ },}: {}),summary: { total: results.length, failed },};process.stdout.write(JSON.stringify(payload, sortedReplacer, 2) + "\n");- return failed === 0 && readinessFailed === 0 ? 0 : 1;+ return exitCode;}for (const r of results) {@@ -354,13 +410,13 @@ async function cmdDoctor(argv: string[]): Promise<number> {// operator can fix it without leaving the doctor output.if (!r.ok && r.fix) process.stdout.write(` fix: ${r.fix}\n`);}- // Scriptable aggregate: a summary line plus the 0/1 exit make `o2b doctor`- // usable as a setup/CI gate.+ // Scriptable aggregate: a summary line plus the {@link DOCTOR_EXIT} code+ // make `o2b doctor` usable as a setup/CI gate.process.stdout.write(`\ndoctor: ${results.length} checks, ${failed} failed\n`);if (readiness) {process.stdout.write(- `\nreadiness: ${readiness.probes.length} probes, ${readinessFailed} failed` ++ `\nreadiness: ${readiness.probes.length} probes, ${readiness.failed} failed` +(readiness.unknown > 0 ? `, ${readiness.unknown} unknown\n` : `\n`),);for (const p of readiness.probes) {@@ -382,7 +438,7 @@ async function cmdDoctor(argv: string[]): Promise<number> {process.stdout.write(`[${tag}] ${p.name}: ${p.detail}\n`);}}- return failed === 0 && readinessFailed === 0 ? 0 : 1;+ return exitCode;}/**@@ -662,7 +718,9 @@ async function cmdMcp(argv: string[]): Promise<number> {process.stderr.write(`[mcp] ${serverName} ${SERVER_VERSION} listening on ${handle.url} (vault=${vault})\n`,);- await new Promise<void>((resolve) => handle.server.once("close", resolve));+ // `closed` rather than `resolve`: this module imports `resolve` from+ // `node:path`, and shadowing it here hid that import inside the closure.+ await new Promise<void>((closed) => handle.server.once("close", closed));return 0;}diff --git a/src/cli/onboarding.ts b/src/cli/onboarding.tsindex d8d7da5f..f741c324 100644--- a/src/cli/onboarding.ts+++ b/src/cli/onboarding.ts@@ -16,6 +16,13 @@ import { existsSync, readdirSync } from "node:fs";import { join } from "node:path";import { discoverConfig } from "../core/config.ts";+import { defaultRegistry } from "../core/install/registry.ts";+// The canonical adapter set registers itself on import of this barrel; the+// ownership statement enumerates the runtime configs those adapters own,+// so it has to see the same list the installer does.+import "../core/install/adapters/all.ts";+import type { DataOwnership } from "../core/install/ownership.ts";+import { measureDataOwnership } from "../core/install/ownership-measure.ts";import { resolveSearchConfig } from "../core/search/index.ts";import {collectRuntimeNotices,@@ -40,6 +47,22 @@ export interface OnboardingChecklist {readonly notices: ReadonlyArray<RuntimeNotice>;/** True when every required (non-optional) step is satisfied. */readonly complete: boolean;+ /**+ * What the operator owns and where it is, as a structured record.+ *+ * It rides HERE because this checklist is the one machine-readable+ * next-action surface that already serialises whole (`o2b onboarding+ * --json`), and an agent deciding what to do next is exactly the reader+ * who needs to know that the vault is the artifact and what does not+ * travel inside it.+ *+ * Deliberately NOT rendered into the human checklist: the prose form is+ * the close `o2b install --apply` and a passing `o2b install --check`+ * print, and repeating it on every `o2b init` would turn a statement+ * into noise. Both surfaces read this same record, so neither can gain+ * a field the other lacks.+ */+ readonly data_ownership: DataOwnership;}export interface OnboardingOptions {@@ -168,7 +191,17 @@ export function buildOnboardingChecklist(...(opts.env !== undefined ? { env: opts.env } : {}),});- return { vault, steps, notices, complete };+ // Measured by the same function the install verb's close calls, so the+ // two surfaces cannot answer differently about where the search index+ // landed or which outbound integrations are configured. This checklist+ // supplies only the vault and the live adapter registry.+ const data_ownership = measureDataOwnership({+ vault,+ ...(opts.configPath === undefined ? {} : { configPath: opts.configPath }),+ adapterTargets: defaultRegistry.targets(),+ });++ return { vault, steps, notices, complete, data_ownership };}/** Render the checklist as a human-readable block for the CLI. */diff --git a/src/cli/progress-rail.ts b/src/cli/progress-rail.tsnew file mode 100644index 00000000..fa3c4470--- /dev/null+++ b/src/cli/progress-rail.ts@@ -0,0 +1,209 @@+/**+ * The progress emission rail (nothing-runs-unwatched, U1).+ *+ * Twin of `advisory-rail.ts`, and deliberately built the same way: one+ * module owns what reaches the stream, so the rule cannot drift verb by+ * verb. It answers the same two questions that rail does, about a+ * different stream.+ *+ * 1. WHAT to write. A `ProgressEvent` carries an operation identifier, a+ * stage identifier and integers. There is no parameter through which+ * a caller can supply a sentence: the human line is rendered here,+ * from the identifiers, exactly as the advisory rail refuses prose.+ * 2. WHETHER it is legal to write it. Progress goes to **stderr**,+ * never stdout - every intermediate-output precedent in this CLI is+ * on stderr, and twelve top-level commands own their stdout as a+ * payload a caller parses. But stderr is not unconditionally safe:+ * `withJsonFallback` monkey-patches stdout AND stderr into string+ * accumulators for the whole run and releases one envelope at the+ * end. A progress line there is not degraded, it is invisible until+ * the run finishes and then dumped at once - which reads as though+ * it had worked. So the rail refuses, by name, rather than writing+ * into a buffer.+ *+ * That second reason is the one thing here that is not obvious from the+ * code it guards, and it rests on a fact about a different module. The+ * fact is asserted in `tests/cli/progress-rail.test.ts` rather than+ * trusted: if `withJsonFallback` ever stops patching stderr, the test+ * says so instead of this comment quietly becoming false.+ */++import {+ PROGRESS_REASON,+ isProgressKind,+ type ProgressEvent,+ type ProgressSink,+} from "../core/brain/progress.ts";++import { ownsInternalJson } from "./json-helpers.ts";++/** The stream an emission is being considered for. */+export interface ProgressStream {+ /** Top-level `o2b` command, e.g. `brain`. */+ readonly command: string;+ /** Argv tail after the top-level command, as `main` dispatched it. */+ readonly argv: ReadonlyArray<string>;+ /**+ * Whether the caller asked for JSON, read from the verb's PARSED flags.+ * Never a raw-argv scan - a positional whose text happens to contain+ * the flag would otherwise silence a legitimate stream.+ */+ readonly jsonRequested: boolean;+}++/** Why an emission did or did not reach stderr. Every case is named. */+export const PROGRESS_OUTCOME = Object.freeze({+ /** Lines were written to stderr as the operation ran. */+ emitted: "emitted",+ /**+ * The command's streams are buffered for the whole run, so a line would+ * surface only at the end. Refused rather than written into the buffer.+ *+ * NO SHIPPED COMMAND REACHES THIS TODAY, and the reason is worth being+ * exact about rather than leaving a reader to discover by grep. The+ * refusal is reached when a caller asks for JSON on a command `main`+ * WRAPS in `withJsonFallback`. Both families that emit progress -+ * `brain` and `search` - own their own JSON, so `ownsInternalJson` is+ * true for them and `progressIsLegal` returns true unconditionally.+ * Every production `attachProgress` call site is in one of those two.+ *+ * So this is not a stub waiting for a producer: it is the decision the+ * rail must make, currently made the same way every time because the+ * population asking is currently uniform. Deleting the branch would not+ * remove a dead path, it would remove the check - and the first verb on+ * a wrapped command to take `--progress` would then write its stream+ * into an accumulator that releases at the end, which reads as though+ * it had worked. `progress-report.test.ts` drives the branch directly+ * and pins the reachability claim above, so the day that verb exists+ * the claim fails instead of quietly going stale.+ */+ suppressedBufferedStream: "suppressed-buffered-stream",+} as const);++export type ProgressOutcome = (typeof PROGRESS_OUTCOME)[keyof typeof PROGRESS_OUTCOME];++/** Membership list for {@link isProgressOutcome}. */+export const PROGRESS_OUTCOMES: ReadonlyArray<ProgressOutcome> = Object.freeze([+ PROGRESS_OUTCOME.emitted,+ PROGRESS_OUTCOME.suppressedBufferedStream,+]);++/** Whether `value` is an outcome this build understands. */+export function isProgressOutcome(value: unknown): value is ProgressOutcome {+ return typeof value === "string" && (PROGRESS_OUTCOMES as ReadonlyArray<string>).includes(value);+}++/**+ * True when progress may be written for `stream`.+ *+ * Under `--json` this is the exact INVERSE of `advisoryIsLegal`, and the+ * inversion is not an accident to be tidied away. One wrapper decides+ * both. Where it is installed it accumulates stdout, which makes an+ * advisory line harmless - and it accumulates stderr, which makes a+ * progress line worthless, because progress is only worth anything while+ * the operation is still running. So the same buffering that legalises+ * one surface disqualifies the other. `progress-rail.test.ts` pins the+ * relation, so a reader who notices the two predicates disagree finds the+ * reason asserted rather than has to guess which one is backwards.+ */+export function progressIsLegal(stream: ProgressStream): boolean {+ if (!stream.jsonRequested) return true;+ return ownsInternalJson(stream.command, stream.argv);+}++/**+ * One newline-delimited JSON record per event.+ *+ * NDJSON rather than a human sentence because the caller this exists for+ * is an adapter or a script tailing stderr, and because a partial line is+ * self-evidently partial. The event is written as it stands: it already+ * carries its own schema discriminator, so a reader can tell a progress+ * line from any other stderr traffic without parsing prose.+ */+export function renderProgressLine(event: ProgressEvent): string {+ return `${JSON.stringify(event)}\n`;+}++/** What one rail attachment decided, in full. */+export interface ProgressAttachment {+ readonly outcome: ProgressOutcome;+ /**+ * The sink to hand to the operation, or `undefined` when the rail+ * refused. Undefined is the house idiom for "nobody asked" - passing a+ * sink that discards would make a refusal indistinguishable from a run+ * that produced no events.+ */+ readonly sink: ProgressSink | undefined;+ /**+ * Present only on a refusal, naming why.+ *+ * Read by {@link reportProgressRefusal} and by nothing else. An earlier+ * docblock here claimed a `--json` verb carries it as a payload field;+ * none does, and none can today, because a refusal only happens on a+ * command whose JSON is wrapped rather than rendered by the verb. The+ * refusal reaches the operator on stderr, which is where it belongs and+ * where the wording is written once.+ */+ readonly reason?: typeof PROGRESS_REASON.streamBuffered;+}++/**+ * Decide whether to observe `stream`, and return the sink if so.+ *+ * `write` is injectable so a test can read what would reach the terminal+ * without the terminal; production callers omit it.+ */+export function attachProgress(+ stream: ProgressStream,+ write: (chunk: string) => void = (chunk) => {+ process.stderr.write(chunk);+ },+): ProgressAttachment {+ if (!progressIsLegal(stream)) {+ return Object.freeze({+ outcome: PROGRESS_OUTCOME.suppressedBufferedStream,+ sink: undefined,+ reason: PROGRESS_REASON.streamBuffered,+ });+ }+ const sink: ProgressSink = (event) => {+ // A kind this build does not know cannot be rendered honestly, and+ // silently dropping it would hide a version skew between a core that+ // emits and an edge that renders. It cannot arrive from outside - the+ // producer is in this process - so it is a defect, not input.+ if (!isProgressKind(event.kind)) {+ throw new TypeError(`progress: unknown event kind ${JSON.stringify(event.kind)}`);+ }+ write(renderProgressLine(event));+ };+ return Object.freeze({ outcome: PROGRESS_OUTCOME.emitted, sink });+}++/**+ * Tell the caller its request for progress was declined, and why.+ *+ * A refusal that produced no line would be indistinguishable from an+ * operation that simply had nothing to report - the caller would watch a+ * silent stream and conclude the run had hung. So the reason is named on+ * stderr, in the one wording every verb shares.+ *+ * Written BEFORE the operation starts rather than after it. A caller told+ * at the end that nobody was watching learns it too late to do anything+ * with; worse, an operation that is then interrupted or fails never+ * reaches its own epilogue at all, so a refusal reported there would go+ * missing exactly when the caller most needed to know why the stream was+ * empty.+ *+ * `null` is the shape a verb holds when nobody asked for progress at all,+ * and it is silent by construction: `reason` is set only on a refusal, so+ * there is a fact to report or there is not.+ */+export function reportProgressRefusal(+ attachment: ProgressAttachment | null,+ write: (chunk: string) => void = (chunk) => {+ process.stderr.write(chunk);+ },+): void {+ if (attachment === null || attachment.reason === undefined) return;+ write(`progress: not emitted (${attachment.reason})\n`);+}diff --git a/src/cli/search/verbs/indexing.ts b/src/cli/search/verbs/indexing.tsindex 8e0bcf47..0238b380 100644--- a/src/cli/search/verbs/indexing.ts+++ b/src/cli/search/verbs/indexing.ts@@ -7,16 +7,32 @@*/import { formatDegradationNotice } from "../../../core/integrity/degradation.ts";-import { createSafeguard, resolveSafeguardTimeoutMs } from "../../../core/brain/safeguard.ts";+import {+ createSafeguard,+ resolveSafeguardTimeoutMs,+ SafeguardAbortError,+} from "../../../core/brain/safeguard.ts";import {chunkWindowDiagnosticCode,indexVault,reindexVault,+ SearchError,serializeChunkWindowCensus,} from "../../../core/search/index.ts";import type { ChunkWindowCensus, IndexStats } from "../../../core/search/index.ts";+import {+ recordSelfHealOutcome,+ SELF_HEAL_REINDEX_OUTCOME,+} from "../../../core/maintenance/self-heal-reindex.ts";import { nextCommandField } from "../../../core/brain/next-step.ts";+import { OPERATION } from "../../../core/brain/safeguard.ts";import { emitNextSteps } from "../../advisory-rail.ts";+import { onInterrupt, reportInterrupted } from "../../interrupt.ts";+import {+ attachProgress,+ reportProgressRefusal,+ type ProgressAttachment,+} from "../../progress-rail.ts";import { CronTemplateError, renderCronTemplate } from "../../search-cron-template.ts";import {flagBoolean,@@ -34,7 +50,7 @@ import {* 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";+const SAFEGUARD_OPERATION = OPERATION.reindex;/** Terminal state both builders reach when the index covers every document. */const INDEX_BUILT = "search-index-built";@@ -55,6 +71,9 @@ const EVENT_ANCHORS_PENDING = "event-anchors-pending";/** Default flush cadence for the generated `reindex --cron-template`. */const DEFAULT_CRON_INTERVAL = "30m";+/** Top-level command both builders live under, for the rails. */+const SEARCH_COMMAND = "search";+function reindexSafeguard(flags: SearchVerbFlags): ReturnType<typeof createSafeguard> {return createSafeguard({operation: SAFEGUARD_OPERATION,@@ -62,6 +81,31 @@ function reindexSafeguard(flags: SearchVerbFlags): ReturnType<typeof createSafeg});}+/**+ * Attach the progress rail for one builder run, and say at once when the+ * stream cannot carry it.+ *+ * Progress is opt-in: attaching a sink by default would change the stderr+ * of every existing invocation, and the older stream on this very command+ * - `--verbose` - is opt-in for the same reason. The two are different+ * channels answering different questions and both are additive, so+ * neither suppresses the other.+ *+ * Written once for both builders: they take the same decision from the+ * same flags, and two copies would be two chances for one of them to+ * observe a run the other would not.+ */+function observeIndexRun(flags: SearchVerbFlags, verb: string): ProgressAttachment | null {+ if (!flagBoolean(flags, "progress")) return null;+ const attachment = attachProgress({+ command: SEARCH_COMMAND,+ argv: [verb],+ jsonRequested: flagBoolean(flags, "json"),+ });+ reportProgressRefusal(attachment);+ return attachment;+}+/*** True when the run this `stats` describes left the index covering every* document, which is what the `search-index-built` class ("search index@@ -129,28 +173,57 @@ export async function cmdSearchIndex(argv: ReadonlyArray<string>): Promise<numbe"force-cost": { type: "boolean" },concurrency: { type: "string" },verbose: { type: "boolean" },+ progress: { 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`);- }- },- });+ const observation = observeIndexRun(flags, "index");+ const interrupt = onInterrupt(OPERATION.reindex);+ let stats: IndexStats;+ try {+ stats = await indexVault(cfg, {+ safeguard: reindexSafeguard(flags),+ embeddings: flagBoolean(flags, "embeddings"),+ force: flagBoolean(flags, "force"),+ forceCost: flagBoolean(flags, "force-cost"),+ // The cancellation seam `indexVault` already declares and checks -+ // between files and between embed batches, never mid-write - with+ // nothing production-side to trip it until now.+ signal: interrupt.signal,+ onFile: (e) => {+ if (verbose) {+ const msg = e.message ? ` ${e.message}` : "";+ process.stderr.write(`${e.kind}\t${e.path}${msg}\n`);+ }+ },+ ...(observation?.sink !== undefined ? { onProgress: observation.sink } : {}),+ });+ } catch (err) {+ if (err instanceof SafeguardAbortError) {+ return reportInterrupted(interrupt, err, flagBoolean(flags, "json"));+ }+ throw err;+ } finally {+ interrupt.release();+ }reportIndexRun(stats, cfg, argv, flagBoolean(flags, "json"));return 0;}+/**+ * Rebuild the index from scratch.+ *+ * `--self-heal <run-id>` marks the run as the automatic post-upgrade+ * rebuild that `ensureVaultCurrent` spawns detached, with every stream+ * ignored because there is no terminal to write to. It changes nothing+ * about the rebuild; it only makes the run's terminal outcome - success or+ * the failure by name - land on the `self_heal_reindex` metrics surface+ * under the run id the parent minted, which is the only place such a run+ * can be read from afterwards and the only thing its two rows pair on.+ */export async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<number> {const { flags } = parseFlags(argv, {...VAULT_FLAGS,@@ -159,8 +232,10 @@ export async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<numconcurrency: { type: "string" },json: { type: "boolean" },verbose: { type: "boolean" },+ progress: { type: "boolean" },"cron-template": { type: "boolean" },interval: { type: "string" },+ "self-heal": { type: "string" },});if (flagBoolean(flags, "cron-template")) {const intervalRaw = flagString(flags, "interval") ?? DEFAULT_CRON_INTERVAL;@@ -176,19 +251,112 @@ export async function cmdSearchReindex(argv: ReadonlyArray<string>): Promise<numthrow 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,- });+ const selfHeal = flagString(flags, "self-heal");+ const startedAt = Date.now();+ // Read before the config, and the config read is inside the recording:+ // `resolveConfig` used to run outside it, so a self-heal child that died+ // on an unresolvable `--config` left its parent's spawn row unpaired -+ // evidence a reader was told to interpret as a child that vanished.+ const cfg = resolveSelfHealConfig(flags, selfHeal, startedAt);+ const observation = observeIndexRun(flags, "reindex");+ const interrupt = onInterrupt(OPERATION.reindex);+ let stats: IndexStats;+ try {+ stats = await reindexVault(cfg, {+ safeguard: reindexSafeguard(flags),+ embeddings: flagBoolean(flags, "embeddings"),+ forceCost: flagBoolean(flags, "force-cost"),+ signal: interrupt.signal,+ onFile: flagBoolean(flags, "verbose")+ ? (e) => process.stderr.write(`${e.kind}\t${e.path}\n`)+ : undefined,+ ...(observation?.sink !== undefined ? { onProgress: observation.sink } : {}),+ });+ } catch (err) {+ // The only report a self-heal run's failure ever gets. Recorded before+ // the rethrow so the row exists whatever the caller's stderr is+ // pointed at, and the rethrow is unchanged so an operator running this+ // by hand still sees the error and the exit code they always saw.+ //+ // A stopped rebuild is recorded here too, and correctly: the staging+ // database was abandoned and never swapped in, so this run left the+ // live index exactly as it found it - which is a rebuild that did not+ // happen, whoever asked for it to stop.+ if (selfHeal !== undefined) {+ recordSelfHealOutcome(+ cfg.vault,+ SELF_HEAL_REINDEX_OUTCOME.failed,+ selfHeal,+ Date.now() - startedAt,+ describeFailure(err),+ );+ }+ if (err instanceof SafeguardAbortError) {+ return reportInterrupted(interrupt, err, flagBoolean(flags, "json"));+ }+ throw err;+ } finally {+ interrupt.release();+ }+ if (selfHeal !== undefined) {+ recordSelfHealOutcome(+ cfg.vault,+ SELF_HEAL_REINDEX_OUTCOME.completed,+ selfHeal,+ Date.now() - startedAt,+ );+ }reportIndexRun(stats, cfg, argv, flagBoolean(flags, "json"));return 0;}+/**+ * `resolveConfig`, with a self-heal child's failure recorded before it is+ * rethrown.+ *+ * The vault comes off the `--vault` flag rather than the resolved config,+ * because the config is the thing that just failed - and the parent always+ * passes `--vault`, so the value is there for exactly the runs that own a+ * spawn row. A child invoked WITHOUT `--vault` whose config will not+ * resolve still records nothing: there is no vault to record into, and+ * inventing one would write a row into a directory nobody asked about.+ * That residue is named in `self-heal-reindex.ts`, case 3.+ *+ * The error is always rethrown, unchanged: this adds a row, it does not+ * soften a failure.+ */+function resolveSelfHealConfig(+ flags: SearchVerbFlags,+ selfHealRunId: string | undefined,+ startedAt: number,+): ResolvedSearchConfig {+ try {+ return resolveConfig(flags);+ } catch (err) {+ const vault = flagString(flags, "vault");+ if (selfHealRunId !== undefined && vault !== undefined) {+ recordSelfHealOutcome(+ vault,+ SELF_HEAL_REINDEX_OUTCOME.failed,+ selfHealRunId,+ Date.now() - startedAt,+ describeFailure(err),+ );+ }+ throw err;+ }+}++/**+ * One line naming what failed. A {@link SearchError} leads with its CODE:+ * the row is read back by an operator and by tests, and a code survives a+ * message reword where the prose does not.+ */+function describeFailure(err: unknown): string {+ if (err instanceof SearchError) return `${err.code}: ${err.message}`;+ return err instanceof Error ? err.message : String(err);+}+/*** The census verdict on THIS surface: the shared wire shape plus the* registered exit for its state. The exit belongs here and not in thediff --git a/src/cli/search/verbs/vector-backfill.ts b/src/cli/search/verbs/vector-backfill.tsindex e82aa904..3e7497fa 100644--- a/src/cli/search/verbs/vector-backfill.ts+++ b/src/cli/search/verbs/vector-backfill.ts@@ -13,10 +13,37 @@* provider or writes a vector. The shape follows* `brain/verbs/authored-at-backfill.ts` line for line, including the log* append whose failure is reported on stderr rather than swallowed.+ *+ * ## Where the interrupt can and cannot land+ *+ * This verb holds a real cancellation handle, and it is the only one of+ * the long verbs whose answer needed checking rather than assuming.+ * `interruptIsObservable` answers per OPERATION, and this pass runs under+ * `OPERATION.reindex`, which the table marks observable - but the table's+ * reason is about the index BUILDERS, so it has to hold here on its own+ * terms. It does, for the half of the run that is long:+ * `runEmbeddingPhase` awaits a provider round trip per super-batch and+ * calls `throwIfAborted` at every batch boundary, which is real I/O and+ * therefore a real yield to the event loop.+ *+ * It does NOT hold for the plan: counting vectorless chunks is a+ * synchronous SQLite query between two awaits, so a keystroke landing+ * inside it is not observed at a checkpoint. That is not a hole this verb+ * papers over - it is exactly what `release()` is for. An interrupt that+ * arrived and that nothing acknowledged is re-raised there, so the run+ * ends the way the un-suppressed keystroke would have, rather than+ * returning 0 for a pass the operator stopped. The plan is milliseconds;+ * the embedding phase is the part an operator would ever want to stop.*/import { appendLogEvent } from "../../../core/brain/log.ts";import { nextCommandField } from "../../../core/brain/next-step.ts";+import {+ createSafeguard,+ OPERATION,+ resolveSafeguardTimeoutMs,+ SafeguardAbortError,+} from "../../../core/brain/safeguard.ts";import { isoSecond } from "../../../core/brain/time.ts";import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";import { resolveAgentName } from "../../../core/config.ts";@@ -30,9 +57,12 @@ import {type VectorBackfillResult,} from "../../../core/search/vector-backfill.ts";import { emitNextStep } from "../../advisory-rail.ts";+import { onInterrupt, reportInterrupted } from "../../interrupt.ts";import { info, ok } from "../../output.ts";+import { attachProgress, reportProgressRefusal } from "../../progress-rail.ts";import {flagBoolean,+ flagString,parseFlags,resolveConfig,resolveConfigPath,@@ -87,16 +117,46 @@ export async function cmdSearchVectorBackfill(argv: ReadonlyArray<string>): Prom...VAULT_FLAGS,apply: { type: "boolean" },"force-cost": { type: "boolean" },+ progress: { type: "boolean" },json: { type: "boolean" },});const cfg = resolveConfig(flags);const apply = flagBoolean(flags, "apply");const jsonRequested = flagBoolean(flags, "json");- const result = await planVectorBackfill(cfg, {- apply,- forceCost: flagBoolean(flags, "force-cost"),- });+ // Opt-in, for the reason the index builders give: attaching a sink by+ // default would change the stderr of every existing invocation.+ const observation = flagBoolean(flags, "progress")+ ? attachProgress({ command: "search", argv: ["vector-backfill"], jsonRequested })+ : null;+ reportProgressRefusal(observation);++ // Everything that can throw happens BEFORE the handle exists: `release`+ // removes process-global listeners and settles a signal nobody acted+ // on, and a throw between `onInterrupt()` and the `try` would skip it.+ const interrupt = onInterrupt(OPERATION.reindex);+ let result: VectorBackfillResult;+ try {+ result = await planVectorBackfill(cfg, {+ apply,+ forceCost: flagBoolean(flags, "force-cost"),+ // The three seams this module declared and nothing produced until+ // now. The deadline is the `reindex` budget off the same ladder the+ // builders read, because this pass IS that run's embedding phase on+ // its own - a second key for one phase would let the two disagree.+ safeguard: createSafeguard({+ operation: OPERATION.reindex,+ timeoutMs: resolveSafeguardTimeoutMs(OPERATION.reindex, flagString(flags, "config")),+ }),+ signal: interrupt.signal,+ ...(observation?.sink !== undefined ? { onProgress: observation.sink } : {}),+ });+ } catch (err) {+ if (err instanceof SafeguardAbortError) return reportInterrupted(interrupt, err, jsonRequested);+ throw err;+ } finally {+ interrupt.release();+ }if (apply && result.embedded > 0) {try {diff --git a/src/core/bench/failure-modes.ts b/src/core/bench/failure-modes.tsnew file mode 100644index 00000000..0f4e8a5d--- /dev/null+++ b/src/core/bench/failure-modes.ts@@ -0,0 +1,223 @@+/**+ * The four ways agent memory fails, scored against shipped code+ * (t_72d6eb23).+ *+ * The existing bench measures whether a query finds the right note. That+ * is one failure mode out of several, and not the one operators complain+ * about. This module adds the scorers for the rest, and it is deliberately+ * narrow: it decides what a decision MEANS, and the phase pipeline decides+ * when to make one. Everything here is pure.+ *+ * ## 1. Proactive know-to-ask, with a false-fire term+ *+ * Measured by driving `decideRecallInject`+ * (`src/core/brain/recall-inject.ts`) - an explicitly I/O-free+ * function with an injectable retriever - over a controlled vault. Two+ * things must be said plainly about what this measures.+ *+ * First, WHAT SHIPS IS NOT WHAT IS MEASURED. `decideRecallInject` sits+ * behind `recall_inject_enabled`, which defaults OFF (`src/core/config.ts`).+ * Calling the function directly is what makes the metric possible at all,+ * but the number it produces describes a CAPABILITY the code has, not+ * behaviour a default install delivers. The always-on injection path+ * (`hooks/active-inject.ts`) makes no relevance decision whatsoever - it+ * injects `Brain/active.md` wholesale every session - so there is nothing+ * there to score.+ *+ * Second, THE PRESSURE IS ON THE FLOOR, NOT THE GATE.+ * `evaluateSurfacingGate` (`src/core/search/surfacing-gate.ts`) fails open+ * by design: every non-empty, non-duplicate, non-slash, non-shell prompt+ * retrieves, so its false-fire rate is ~1 by construction and scoring it+ * would be theatre. The only+ * discriminating bound in the decision core is+ * `RECALL_INJECT_CONFIDENCE_FLOOR`, so that is where the anti-gaming term+ * bites: {@link scoreProactiveRecall} counts a false fire exactly as+ * heavily as a silent miss, which is what makes a strategy that always+ * injects score strictly worse than one that abstains correctly.+ *+ * A measured caveat that belongs with the number: through the shipped+ * keyword lane the top-ranked result's score is pinned at the configured+ * keyword weight (0.65 by default), because `rankResults` min-max+ * normalizes the lane. `below_floor` is therefore unreachable via the+ * default retriever today, and the abstain that actually fires on an+ * off-topic prompt is `no_matches`. The floor is still the term under+ * pressure - it is simply not, today, the term that fires.+ *+ * ## 2. Write-back fidelity+ *+ * Graded on the shipped write path with no model call, because there is no+ * other kind: the server never calls a model on any write path by stated+ * architectural contract (`src/mcp/brain/context-tools.ts`, "The calling+ * agent generates; the Brain never does"). So there is no extractor seam+ * to inject - the question a fidelity fixture actually answers is what+ * structured intake stands in for a real agent's distillation, and whether+ * the PROVENANCE survives segmentation, insertion and dedup intact.+ *+ * ## 3. Cross-source isolation+ *+ * Asserted on delivered pack CONTENTS, never on `hiddenByOwnerScope`: that+ * counter is surfaced only under `warn`, where it counts items that WERE+ * delivered, and under `fail` it is deliberately unreported. And it is run+ * under a fixture that sets `integrity.owner_scope_delivery: fail`,+ * because the shipped default is `off` - with no scope evaluated, nothing+ * can be violated and a zero-gate would be vacuous.+ *+ * ## 4. Injected tokens+ *+ * Not a failure mode but a cost, so it stays in the report's cost family+ * rather than here - see `context_cost.avg_injected_tokens`, which the+ * pipeline computes with {@link estimateTokens} and nothing else.+ */++import { estimateTokens } from "../brain/text/tokenizer.ts";+import type { RecallInjectDecision, RecallResultSet } from "../brain/recall-inject.ts";+import { resolveSearchConfig, search } from "../search/index.ts";++/**+ * How one proactive-recall decision failed, or nothing when it was right.+ *+ * Three members because three different repairs apply. A silent miss means+ * the retrieval or the floor is too strict; a false fire means the+ * opposite; a fault means the retriever itself broke, which is neither and+ * must never be folded into either - a harness counting its own breakage+ * as a memory failure reports a number about itself.+ */+export const RECALL_FAILURE = Object.freeze({+ /** Memory held the answer and stayed silent. */+ knowToAsk: "know_to_ask",+ /** Memory spoke up when it had nothing worth saying. */+ falseFire: "false_fire",+ /** The decision core reported an error rather than a decision. */+ faulted: "faulted",+} as const);++/** Closed union over {@link RECALL_FAILURE}. */+export type RecallFailure = (typeof RECALL_FAILURE)[keyof typeof RECALL_FAILURE];++/** Membership list; every surface renders its vocabulary from this array. */+export const RECALL_FAILURES: ReadonlyArray<RecallFailure> = Object.freeze([+ RECALL_FAILURE.knowToAsk,+ RECALL_FAILURE.falseFire,+ RECALL_FAILURE.faulted,+]);++/** Narrow a value read back off disk or across a tool boundary. */+export function isRecallFailure(value: unknown): value is RecallFailure {+ return typeof value === "string" && (RECALL_FAILURES as ReadonlyArray<string>).includes(value);+}++/**+ * The retriever the bench hands to `decideRecallInject`: the shipped+ * search pipeline over the disposable fixture vault.+ *+ * Mirrors `defaultRecallRetriever`, which adapts `searchAcrossVaults` the+ * same way; the difference is only which search entry point is wrapped,+ * because a bench vault has no registered recall sources to cross.+ */+export function benchRecallRetriever(+ config: ReturnType<typeof resolveSearchConfig>,+ limit: number,+): (query: string) => Promise<RecallResultSet> {+ return async (query) => {+ const outcome = await search(config, { query, limit });+ return Object.freeze({+ candidates: Object.freeze(+ outcome.results.map((result) =>+ Object.freeze({+ path: result.path,+ title: result.title,+ score: result.score,+ searchType: result.searchType,+ startLine: result.startLine,+ endLine: result.endLine,+ }),+ ),+ ),+ total: outcome.total,+ });+ };+}++/**+ * What one decision costs the score, given what the fixture expected.+ *+ * `null` is a pass. An `error` decision is never charged to either rate:+ * it is the harness failing, and attributing it to memory would make a+ * broken retriever look like a cautious one.+ */+export function classifyRecallDecision(+ expectInject: boolean,+ decision: RecallInjectDecision,+): RecallFailure | null {+ if (decision.kind === "error") return RECALL_FAILURE.faulted;+ if (decision.kind === "inject") return expectInject ? null : RECALL_FAILURE.falseFire;+ return expectInject ? RECALL_FAILURE.knowToAsk : null;+}++/** The two proactive-recall rates over a set of classified decisions. */+export interface ProactiveRecallScore {+ readonly decisions: number;+ readonly know_to_ask_failure_rate: number;+ readonly false_fire_rate: number;+ readonly faults: number;+}++/**+ * Score a run of classified decisions.+ *+ * Both rates are denominated in DECISIONS, not in their own expectation+ * class, and that is the anti-gaming term. Per-class denominators would+ * let a strategy that always injects post a know-to-ask rate of 0 and hide+ * its false fires in a rate nobody reads; sharing one denominator means+ * every false fire displaces a pass, so the always-inject strategy is+ * strictly worse than one that abstains correctly whenever the fixture+ * contains a single prompt memory should stay quiet about.+ */+export function scoreProactiveRecall(+ failures: ReadonlyArray<RecallFailure | null>,+): ProactiveRecallScore {+ const decisions = failures.length;+ const count = (kind: RecallFailure): number =>+ failures.filter((failure) => failure === kind).length;+ return Object.freeze({+ decisions,+ know_to_ask_failure_rate: rate(count(RECALL_FAILURE.knowToAsk), decisions),+ false_fire_rate: rate(count(RECALL_FAILURE.falseFire), decisions),+ faults: count(RECALL_FAILURE.faulted),+ });+}++/**+ * The forbidden ids a pack actually delivered.+ *+ * Deliberately reads the delivered CONTENTS rather than a counter: the one+ * counter that exists (`hiddenByOwnerScope`) is reported only under `warn`,+ * where its meaning is inverted, and is withheld under `fail` on purpose.+ * A zero-gate has to look at what came back.+ */+export function isolationViolations(+ deliveredIds: ReadonlyArray<string>,+ forbiddenIds: ReadonlyArray<string>,+): ReadonlyArray<string> {+ return Object.freeze(forbiddenIds.filter((id) => deliveredIds.includes(id)));+}++/**+ * The single token estimator this suite is allowed to use.+ *+ * Re-exported by name so the bench has exactly one import site to point at+ * and `tests/core/bench/token-estimator.test.ts` has exactly one thing to+ * assert. Five mutually disagreeing estimators exist in this repo+ * (`ceil(utf8_bytes/4)`, `ceil(utf16_len/4)`, a word count, an inline+ * `ceil(chars/4)` the bench used to carry, and a ledger over integers a+ * caller supplied); the bench converges on {@link estimateTokens} because+ * it is the one the Brain-side accounting already uses everywhere and the+ * only one that documents its own heuristic.+ */+export function injectedTokens(injected: string): number {+ return estimateTokens(injected);+}++function rate(count: number, total: number): number {+ return total > 0 ? Math.round((count / total) * 1000) / 1000 : 0;+}diff --git a/src/core/bench/fixture.ts b/src/core/bench/fixture.tsindex 7e000cac..5b1f3574 100644--- a/src/core/bench/fixture.ts+++ b/src/core/bench/fixture.ts@@ -179,6 +179,30 @@ function parseQuestion(raw: unknown, index: number): BenchQuestion {...(positiveInt(record["max_total_chars"]) !== undefined? { max_total_chars: positiveInt(record["max_total_chars"]) }: {}),+ ...(nonEmptyString(record["prompt"]) !== undefined+ ? { prompt: nonEmptyString(record["prompt"]) }+ : {}),+ // `expect_inject` is the one boolean field, and `false` is its most+ // load-bearing value (the anti-gaming half of the fixture), so it is+ // read by type rather than by truthiness.+ ...(typeof record["expect_inject"] === "boolean"+ ? { expect_inject: record["expect_inject"] }+ : {}),+ ...(nonEmptyString(record["intake_text"]) !== undefined+ ? { intake_text: nonEmptyString(record["intake_text"]) }+ : {}),+ ...(stringArray(record["expected_labels"]) !== undefined+ ? { expected_labels: stringArray(record["expected_labels"]) }+ : {}),+ ...(stringArray(record["expected_provenance"]) !== undefined+ ? { expected_provenance: stringArray(record["expected_provenance"]) }+ : {}),+ ...(nonEmptyString(record["agent_scope"]) !== undefined+ ? { agent_scope: nonEmptyString(record["agent_scope"]) }+ : {}),+ ...(stringArray(record["forbidden_ids"]) !== undefined+ ? { forbidden_ids: stringArray(record["forbidden_ids"]) }+ : {}),});validateQuestionShape(question);return question;@@ -198,6 +222,27 @@ function validateQuestionShape(question: BenchQuestion): void {if (question.category === "budget" && (question.expected_ids ?? []).length === 0) {throw new Error(`bench fixture: question ${question.id} needs expected_ids`);}+ if (question.category === "proactive_recall") {+ if (question.prompt === undefined || question.expect_inject === undefined) {+ throw new Error(+ `bench fixture: question ${question.id} (proactive_recall) needs prompt and expect_inject`,+ );+ }+ }+ if (question.category === "write_fidelity") {+ if (question.intake_text === undefined || (question.expected_labels ?? []).length === 0) {+ throw new Error(+ `bench fixture: question ${question.id} (write_fidelity) needs intake_text and expected_labels`,+ );+ }+ }+ if (question.category === "source_isolation") {+ if (question.agent_scope === undefined || (question.forbidden_ids ?? []).length === 0) {+ throw new Error(+ `bench fixture: question ${question.id} (source_isolation) needs agent_scope and forbidden_ids`,+ );+ }+ }}function isBenchCategory(value: string): value is BenchCategory {diff --git a/src/core/bench/phases.ts b/src/core/bench/phases.tsindex b2a8d948..7da7d03a 100644--- a/src/core/bench/phases.ts+++ b/src/core/bench/phases.ts@@ -18,7 +18,22 @@ import { join } from "node:path";import { packContext } from "../brain/context-pack.ts";import { loadNormalizedContinuityRecords } from "../brain/continuity/read-model.ts";+import type { ContinuityRecord } from "../brain/continuity/types.ts";+import { extractPreCompactRecords } from "../brain/pre-compact-extract.ts";+import {+ decideRecallInject,+ RECALL_INJECT_MAX_NOTES,+ type RecallInjectDecision,+} from "../brain/recall-inject.ts";import { resolveSearchConfig, search } from "../search/index.ts";+import {+ benchRecallRetriever,+ classifyRecallDecision,+ injectedTokens,+ isolationViolations,+ scoreProactiveRecall,+ type RecallFailure,+} from "./failure-modes.ts";import { fixtureHash, materializeBenchVault } from "./fixture.ts";import { runJudge } from "./judge.ts";import {@@ -57,9 +72,47 @@ interface RetrievedQuestion {readonly paths?: ReadonlyArray<string>;/** Normalized turn texts (session_handoff). */readonly turn_texts?: ReadonlyArray<string>;- /** Pack item ids and character count (budget). */+ /** Pack item ids (budget, source_isolation). */readonly item_ids?: ReadonlyArray<string>;+ /** Characters of context this question injected, when it injected any. */readonly context_chars?: number;+ /** `estimateTokens` over the same string `context_chars` measured. */+ readonly injected_tokens?: number;+ /** The decision core's verdict, verbatim (proactive_recall). */+ readonly recall_decision?: RecallInjectDecision;+ /** Normalized label tokens the extractor recovered (write_fidelity). */+ readonly labels?: ReadonlyArray<string>;+ /** Provenance keys present on every extracted record (write_fidelity). */+ readonly provenance_keys?: ReadonlyArray<string>;+ /** Whether a second identical extraction produced the same record ids. */+ readonly dedup_stable?: boolean;+}++/**+ * The search configuration every phase uses.+ *+ * `resolveSearchConfig` still reads `process.env`, and overrides are+ * applied last and win, so pinning the semantic lane off here is what+ * makes the harness's network-freedom an invariant instead of an+ * inherited accident. Pinning it OFF rather than onto the offline+ * `LocalProvider` is deliberate: the bench's scoring is keyword+ * containment, so an embedding lane would add a second ranking signal to+ * a number nobody asked to include, and cost time for it.+ *+ * Exported so the invariant is assertable directly. It has to be: a test+ * that sets the env vars and compares two reports passes whether or not+ * the override is there, because reaching the embedding lane also needs+ * an index built with embeddings, which this harness does not build. The+ * resolved config is where the difference is real, so that is what the+ * test reads.+ *+ * One residual, named rather than implied: `resolveSearchConfig` parses+ * the provider name BEFORE merging overrides, so an env var naming a+ * provider it does not recognise makes this throw. That is a loud, named+ * failure rather than a silently different bench.+ */+export function benchSearchConfig(vault: string): ReturnType<typeof resolveSearchConfig> {+ return resolveSearchConfig({ vault, overrides: { semantic: { enabled: false } } });}export async function runMemoryBench(opts: BenchRunOptions): Promise<BenchReport> {@@ -79,14 +132,14 @@ export async function runMemoryBench(opts: BenchRunOptions): Promise<BenchReport// Phase: index - one warmup search triggers the store self-heal so// the FTS index exists before any timed retrieval.if (!phaseDone(checkpoint, "index")) {- const config = resolveSearchConfig({ vault });+ const config = benchSearchConfig(vault);await search(config, { query: "warmup", limit: 1 });checkpoint = completeBenchPhase(run.runDir, checkpoint, "index");}// Phase: retrieve - run every question once, persist raw results.if (!phaseDone(checkpoint, "retrieve")) {- const config = resolveSearchConfig({ vault });+ const config = benchSearchConfig(vault);mkdirSync(benchResultsDir(run.runDir), { recursive: true });// Deliberately sequential: per-question latency_ms must not include// contention from sibling searches running on the same store.@@ -151,19 +204,110 @@ async function retrieveQuestion(),};}- // budget+ if (question.category === "proactive_recall") {+ // The shipped decision core, driven directly over the fixture vault.+ // The retriever is a PARAMETER of that function, which is the only+ // reason this is measurable offline at all.+ const decision = await decideRecallInject(+ question.prompt ?? "",+ benchRecallRetriever(config, question.top_k ?? RECALL_INJECT_MAX_NOTES),+ );+ // An abstain injects nothing, and zero is the honest cost of nothing -+ // not an absent measurement.+ const brief = decision.kind === "inject" ? decision.brief : "";+ return {+ id: question.id,+ latency_ms: Date.now() - startedAt,+ recall_decision: decision,+ context_chars: brief.length,+ injected_tokens: injectedTokens(brief),+ };+ }+ if (question.category === "write_fidelity") {+ return retrieveWriteFidelity(vault, question, startedAt);+ }+ // budget and source_isolation both deliver a context pack; the+ // isolation question additionally requests an owner scope, which is+ // only honoured when the fixture's `Brain/_brain.yaml` sets+ // `integrity.owner_scope_delivery: fail` - the shipped default is+ // `off`, under which no scope is evaluated and the question is vacuous.const pack = packContext(vault, {maxTokens: question.max_tokens ?? 1000,...(question.max_total_chars !== undefined ? { maxTotalChars: question.max_total_chars } : {}),+ ...(question.agent_scope !== undefined ? { agentScope: question.agent_scope } : {}),});+ const body = pack.items.map((item) => item.body).join("\n");return {id: question.id,latency_ms: Date.now() - startedAt,item_ids: pack.items.map((item) => item.id),- context_chars: pack.items.reduce((sum, item) => sum + item.body.length, 0),+ context_chars: body.length,+ injected_tokens: injectedTokens(body),};}+/**+ * Run the shipped write path twice over the same intake and record what+ * survived.+ *+ * Twice on purpose: the second pass is the dedup measurement. Extraction+ * keys on (session, turn range, label, content hash), so a faithful write+ * path must return the SAME record ids the second time and append+ * nothing. A path that re-appends looks identical on a single run.+ *+ * No model is called, and none could be: the server never calls one on+ * any write path. What the fixture supplies is the structured intake that+ * stands in for an agent's distillation.+ */+function retrieveWriteFidelity(+ vault: string,+ question: BenchQuestion,+ startedAt: number,+): RetrievedQuestion {+ const input = {+ sessionId: `bench-${question.id}`,+ turnStart: "turn-1",+ turnEnd: "turn-2",+ text: question.intake_text ?? "",+ createdAt: BENCH_WRITE_FIDELITY_INSTANT,+ };+ const first = extractPreCompactRecords(vault, input);+ const second = extractPreCompactRecords(vault, input);+ const provenance = new Set<string>(first.records.flatMap(provenanceKeys));+ return {+ id: question.id,+ latency_ms: Date.now() - startedAt,+ labels: first.records.map((record) => String(record.payload["extract_type"] ?? "")),+ // Present on EVERY record, not on any: a provenance field that+ // survives only sometimes has not survived.+ provenance_keys: [...provenance].filter((key) =>+ first.records.every((record) => provenanceKeys(record).includes(key)),+ ),+ dedup_stable:+ first.records.length > 0 &&+ JSON.stringify(first.records.map((r) => r.id)) ===+ JSON.stringify(second.records.map((r) => r.id)),+ };+}++/**+ * Every provenance name one extracted record carries.+ *+ * Both levels count: the record envelope carries `id`, `kind`,+ * `createdAt` and `sourceRefs`, and the payload carries the+ * session/turn/hash keys. A fixture asks for either by name.+ */+function provenanceKeys(record: ContinuityRecord): ReadonlyArray<string> {+ return [...Object.keys(record), ...Object.keys(record.payload)];+}++/**+ * Fixed authoring instant for write-fidelity extraction. Extraction+ * defaults `createdAt` to wall clock, which would make the record ids -+ * and therefore the whole report - differ on every run.+ */+const BENCH_WRITE_FIDELITY_INSTANT = "2026-06-01T00:00:00.000Z";+function readRetrieved(runDir: string, questionId: string): RetrievedQuestion {const path = join(benchResultsDir(runDir), `${questionId}.json`);if (!existsSync(path)) {@@ -181,6 +325,9 @@ function evaluateQuestion(category: question.category,latency_ms: retrieved.latency_ms,...(retrieved.context_chars !== undefined ? { context_chars: retrieved.context_chars } : {}),+ ...(retrieved.injected_tokens !== undefined+ ? { injected_tokens: retrieved.injected_tokens }+ : {}),};if (RETRIEVAL_CATEGORIES.has(question.category)) {const paths = retrieved.paths ?? [];@@ -207,6 +354,15 @@ function evaluateQuestion(}return Object.freeze({ ...base, pass: true });}+ if (question.category === "proactive_recall") {+ return evaluateProactiveRecall(question, retrieved, base);+ }+ if (question.category === "write_fidelity") {+ return evaluateWriteFidelity(question, retrieved, base);+ }+ if (question.category === "source_isolation") {+ return evaluateSourceIsolation(question, retrieved, base);+ }if (question.category === "session_handoff") {const texts = retrieved.turn_texts ?? [];if (question.expected_turns !== undefined && texts.length < question.expected_turns) {@@ -241,6 +397,105 @@ function evaluateQuestion(return Object.freeze({ ...base, pass: true });}+/** Shared prefix of every evaluated question, built once by the caller. */+type ResultBase = Pick<+ BenchQuestionResult,+ "id" | "category" | "latency_ms" | "context_chars" | "injected_tokens"+>;++function evaluateProactiveRecall(+ question: BenchQuestion,+ retrieved: RetrievedQuestion,+ base: ResultBase,+): BenchQuestionResult {+ const decision = retrieved.recall_decision;+ if (decision === undefined) {+ return Object.freeze({+ ...base,+ pass: false,+ failure: "no recall decision was persisted for this question",+ });+ }+ const failure = classifyRecallDecision(question.expect_inject === true, decision);+ if (failure === null) return Object.freeze({ ...base, pass: true });+ return Object.freeze({+ ...base,+ pass: false,+ recall_failure: failure,+ failure: `${failure}: decision was ${describeDecision(decision)}`,+ });+}++/** One decision as a diffable one-liner. Classifications only, no prose. */+function describeDecision(decision: RecallInjectDecision): string {+ if (decision.kind === "abstain") return `abstain(${decision.reason})`;+ if (decision.kind === "error") return `error(${decision.fault})`;+ return `inject(${decision.noteCount} notes)`;+}++function evaluateWriteFidelity(+ question: BenchQuestion,+ retrieved: RetrievedQuestion,+ base: ResultBase,+): BenchQuestionResult {+ const labels = retrieved.labels ?? [];+ const expected = question.expected_labels ?? [];+ if (JSON.stringify(labels) !== JSON.stringify(expected)) {+ return Object.freeze({+ ...base,+ pass: false,+ failure: `labels [${labels.join(", ")}] do not match expected [${expected.join(", ")}]`,+ });+ }+ const present = retrieved.provenance_keys ?? [];+ const missing = (question.expected_provenance ?? []).filter((key) => !present.includes(key));+ if (missing.length > 0) {+ return Object.freeze({+ ...base,+ pass: false,+ failure: `provenance lost on the write path: ${missing.join(", ")}`,+ });+ }+ if (retrieved.dedup_stable !== true) {+ return Object.freeze({+ ...base,+ pass: false,+ failure: "a second identical intake did not resolve to the same records",+ });+ }+ return Object.freeze({ ...base, pass: true });+}++function evaluateSourceIsolation(+ question: BenchQuestion,+ retrieved: RetrievedQuestion,+ base: ResultBase,+): BenchQuestionResult {+ const ids = retrieved.item_ids ?? [];+ const leaked = isolationViolations(ids, question.forbidden_ids ?? []);+ if (leaked.length > 0) {+ return Object.freeze({+ ...base,+ pass: false,+ isolation_violations: leaked.length,+ failure: `delivered memory owned by another agent: ${leaked.join(", ")}`,+ });+ }+ // The converse invariant: a scope must isolate without narrowing what+ // the caller legitimately owns. Without this a pack that returned+ // NOTHING would score a perfect isolation result.+ const missing = (question.expected_ids ?? []).filter((id) => !ids.includes(id));+ if (missing.length > 0) {+ return Object.freeze({+ ...base,+ pass: false,+ isolation_violations: 0,+ failure: `scoping withheld the caller's own memory: ${missing.join(", ")}`,+ });+ }+ return Object.freeze({ ...base, pass: true, isolation_violations: 0 });+}+function buildReport(run: BenchRunHandle,fixture: BenchFixture,@@ -258,13 +513,21 @@ function buildReport(}}const latencies = results.map((result) => result.latency_ms);- const contextChars = results- .map((result) => result.context_chars)- .filter((value): value is number => typeof value === "number");- const avgChars =- contextChars.length > 0- ? Math.round(contextChars.reduce((sum, value) => sum + value, 0) / contextChars.length)- : 0;+ const avgChars = mean(results.map((result) => result.context_chars));+ // The suite's ONE token number, from the ONE estimator. The inline+ // `ceil(avg_chars / 4)` that stood here was a sixth formula in a repo+ // that already had five, and it did not even import the shared helper -+ // so it disagreed with every token figure the Brain reports. Averaged+ // over the same population as `avg_chars` so the two are comparable.+ const avgInjectedTokens = mean(results.map((result) => result.injected_tokens));+ const recallFailures: ReadonlyArray<RecallFailure | null> = results+ .filter((result) => result.category === "proactive_recall")+ .map((result) => result.recall_failure ?? null);+ const proactive = scoreProactiveRecall(recallFailures);+ const isolationTotal = results.reduce(+ (sum, result) => sum + (result.isolation_violations ?? 0),+ 0,+ );return Object.freeze({schema: BENCH_REPORT_SCHEMA,run_id: run.runId,@@ -288,7 +551,12 @@ function buildReport(}),context_cost: Object.freeze({avg_chars: avgChars,- est_tokens: Math.ceil(avgChars / 4),+ avg_injected_tokens: avgInjectedTokens,+ }),+ failure_modes: Object.freeze({+ know_to_ask_failure_rate: proactive.know_to_ask_failure_rate,+ false_fire_rate: proactive.false_fire_rate,+ source_isolation_violations: isolationTotal,}),judge: Object.freeze({status: judge.status,@@ -310,3 +578,10 @@ function buildReport(function round3(value: number): number {return Math.round(value * 1000) / 1000;}++/** Mean over the values that are present, rounded; 0 when none are. */+function mean(values: ReadonlyArray<number | undefined>): number {+ const present = values.filter((value): value is number => typeof value === "number");+ if (present.length === 0) return 0;+ return Math.round(present.reduce((sum, value) => sum + value, 0) / present.length);+}diff --git a/src/core/bench/types.ts b/src/core/bench/types.tsindex dfba85b4..ef83b34c 100644--- a/src/core/bench/types.ts+++ b/src/core/bench/types.ts@@ -9,7 +9,18 @@* judge-model evaluation is an optional external command.*/-export const BENCH_REPORT_SCHEMA = "o2b.bench.v1";+/**+ * Bumped from `v1` for U10: `context_cost.est_tokens` was replaced by+ * `context_cost.avg_injected_tokens`. The old field averaged+ * `ceil(avg_chars / 4)` over an inline formula that did not even import+ * the shared helper; the new one is `estimateTokens` applied to the+ * strings the bench actually injected. Same family, different meaning and+ * a different number, so the schema says so rather than letting a stored+ * report be read under the wrong rule.+ */+import type { RecallFailure } from "./failure-modes.ts";++export const BENCH_REPORT_SCHEMA = "o2b.bench.v2";export const BENCH_PHASES = ["ingest", "index", "retrieve", "evaluate", "report"] as const;export type BenchPhase = (typeof BENCH_PHASES)[number];@@ -21,6 +32,11 @@ export const BENCH_CATEGORIES = ["multi_evidence","session_handoff","budget",+ // The failure-mode suite (t_72d6eb23). Each drives a different shipped+ // seam, so none of them can be expressed as a retrieval question.+ "proactive_recall",+ "write_fidelity",+ "source_isolation",] as const;export type BenchCategory = (typeof BENCH_CATEGORIES)[number];@@ -60,10 +76,28 @@ export interface BenchQuestion {readonly session_id?: string;readonly expected_turns?: number;readonly expected_text?: string;- /** budget: pack item ids that must fit inside the budget. */+ /** budget / source_isolation: pack item ids that must be delivered. */readonly expected_ids?: ReadonlyArray<string>;readonly max_tokens?: number;readonly max_total_chars?: number;+ /** proactive_recall: the user prompt the decision core sees. */+ readonly prompt?: string;+ /**+ * proactive_recall: whether memory SHOULD speak up for this prompt.+ * `false` is the anti-gaming half of the fixture - a prompt the vault+ * has nothing useful to say about, where injecting is the failure.+ */+ readonly expect_inject?: boolean;+ /** write_fidelity: the labelled prose a host flushes before compaction. */+ readonly intake_text?: string;+ /** write_fidelity: normalized label tokens the extractor must recover, in order. */+ readonly expected_labels?: ReadonlyArray<string>;+ /** write_fidelity: payload keys that must survive onto every record. */+ readonly expected_provenance?: ReadonlyArray<string>;+ /** source_isolation: the owner scope the delivery is requested under. */+ readonly agent_scope?: string;+ /** source_isolation: pack item ids that must NOT be delivered. */+ readonly forbidden_ids?: ReadonlyArray<string>;}export interface BenchFixture {@@ -81,8 +115,14 @@ export interface BenchQuestionResult {/** One-line reason when pass is false. */readonly failure?: string;readonly latency_ms: number;- /** Pack character count (budget questions). */+ /** Characters of context this question injected, when it injected any. */readonly context_chars?: number;+ /** {@link estimateTokens} over the same string `context_chars` measured. */+ readonly injected_tokens?: number;+ /** proactive_recall: which failure mode fired, absent when none did. */+ readonly recall_failure?: RecallFailure;+ /** source_isolation: forbidden ids the pack actually delivered. */+ readonly isolation_violations?: number;}export interface BenchReport {@@ -98,7 +138,28 @@ export interface BenchReport {readonly by_category: Readonly<Record<string, { passed: number; total: number }>>;};readonly latency_ms: { readonly avg: number; readonly max: number };- readonly context_cost: { readonly avg_chars: number; readonly est_tokens: number };+ /**+ * Cost, kept apart from quality on purpose (the MemScore lesson stated+ * at the top of this file). `avg_injected_tokens` is the fourth+ * failure-mode metric and it lives HERE rather than in `failure_modes`+ * because a token count is a cost, not a failure - collapsing it into+ * the failure block is exactly the conflation this type exists to+ * prevent. Both fields are averaged over the questions that injected+ * something, so they describe the same population.+ */+ readonly context_cost: { readonly avg_chars: number; readonly avg_injected_tokens: number };+ /**+ * The three ways memory fails that are not "the query missed"+ * (t_72d6eb23). Both rates share one denominator - every decision the+ * proactive-recall questions produced - which is what stops a strategy+ * that always injects from scoring well; see `failure-modes.ts`.+ * `source_isolation_violations` is a COUNT and gates at zero.+ */+ readonly failure_modes: {+ readonly know_to_ask_failure_rate: number;+ readonly false_fire_rate: number;+ readonly source_isolation_violations: number;+ };readonly judge: { readonly status: "skipped" | "ran" | "error"; readonly detail?: string };readonly questions: ReadonlyArray<BenchQuestionResult>;}diff --git a/src/core/brain/architect/generate.ts b/src/core/brain/architect/generate.tsindex e007ba91..a52ecf2c 100644--- a/src/core/brain/architect/generate.ts+++ b/src/core/brain/architect/generate.ts@@ -16,6 +16,24 @@* Module REMOVAL keeps the old module note on disk (the operator may* have annotated it); the overview's module region reflects only the* current scan, so stale notes become unlinked rather than deleted.+ *+ * One run is one critical section: every note is planned, then written,+ * with the sync lock held across both. Planning before writing is what+ * makes a corrupted-sentinel abort - and an elapsed deadline - leave NO+ * half-refreshed prefix on disk, and the lock is what stops two runs on+ * the same repo from reading the same "before" state and erasing each+ * other's merge.+ *+ * Planning does NOT cover a failure of the writing itself. Planning+ * removes the error class that arises while DECIDING a note's bytes; an+ * ENOSPC, EACCES or EIO on the k-th of N notes arises while placing them,+ * and leaves k-1 refreshed beside the rest. No filesystem swaps N files+ * into place at once, so that state is reachable and cannot be rolled+ * back. What makes it survivable is that the loop is idempotent - every+ * note's bytes are a function of the scanned facts plus the prose already+ * outside its regions - so a re-run repairs any prefix. What makes it+ * actionable is {@link ArchWriteError}, which names the note that failed+ * and how far the run got.*/import { existsSync, mkdirSync, readFileSync } from "node:fs";@@ -23,25 +41,75 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";import { repoKey as deriveRepoKey } from "../git/identity.ts";+import { OPERATION, progressCounter, progressReasonForError } from "../progress.ts";+import type { ProgressCounter, ProgressSink } from "../progress.ts";import { buildRegionDocument, mergeRegions } from "../regions.ts";import type { Region } from "../regions.ts";-import { scanProject } from "./scan.ts";+import type { Safeguard } from "../safeguard.ts";+import { acquireLockSyncWithRetry, LOCK_WAIT_INTERACTIVE_MS } from "../sync-lockfile.ts";+import { ARCHITECT_STAGE, scanProject } from "./scan.ts";import type { ModuleFact, ProjectFacts } from "./scan.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";+export interface GenerateArchDocsOptions {+ /** Where a caller watches the run. Absence means nobody asked. */+ readonly onProgress?: ProgressSink;+ /**+ * Cooperative deadline, checked per directory read while scanning and+ * per note while planning - never between two writes.+ */+ readonly safeguard?: Safeguard;+}+export interface GenerateArchDocsResult {readonly repoKey: string;readonly dir: string;readonly overviewPath: string;readonly modulePaths: ReadonlyArray<string>;+ /**+ * What this run did to the notes: how many it wrote for the first time,+ * how many it rewrote, and how many it found already correct. They sum+ * to `1 + modulePaths.length` and go out on the CLI's JSON envelope.+ *+ * Each one is the verdict of a READ - `planNote` compares what is on+ * disk against what the facts say - so the three are only true of the+ * disk if that read and the write that follows it are one critical+ * section. They are consequently what a concurrent run can falsify:+ * two runs whose reads both preceded either write both report having+ * created the same note. That is the property+ * `architect-concurrent-runs.test.ts` holds down.+ */readonly created: number;readonly updated: number;readonly unchanged: number;+ /**+ * The message of the first failure of the caller's progress sink, or+ * `null` when there was none (and when no sink was supplied).+ *+ * An observer must not be able to destroy what it observes - a closed+ * pipe cannot be allowed to abort a generation that is otherwise+ * succeeding - but it must not vanish either, so the fault is carried+ * out on the result the caller already reads and the sink is detached+ * for the rest of the run. Only the first is reported: after it there+ * is no attached sink left to fail again.+ */+ readonly progressFault: string | null;+}++/**+ * Codepoint order, not `localeCompare`: ICU collation varies with the+ * runtime locale, so a collator-based tie-break renders different bytes+ * for the same tree on two hosts - and byte-identical regeneration is+ * this module's whole contract. Every other ordering in the scanner+ * already uses plain `toSorted()`; this is the one that did not.+ */+function compareStable(a: string, b: string): number {+ return a < b ? -1 : a > b ? 1 : 0;}function languagesLine(languages: Readonly<Record<string, number>>): string {const entries = Object.entries(languages).toSorted(- (a, b) => b[1] - a[1] || a[0].localeCompare(b[0]),+ (a, b) => b[1] - a[1] || compareStable(a[0], b[0]),);if (entries.length === 0) return "none detected";return entries@@ -106,74 +174,283 @@ function frontmatter(kind: string, key: string, extra: ReadonlyArray<string>): sreturn ["---", `kind: ${kind}`, `repo_key: ${key}`, ...extra, "---", ""].join("\n");}+/** What one note's regeneration turned out to be. */+const NOTE_DISPOSITION = Object.freeze({+ created: "created",+ updated: "updated",+ unchanged: "unchanged",+} as const);++type NoteDisposition = (typeof NOTE_DISPOSITION)[keyof typeof NOTE_DISPOSITION];++/** One note's decided bytes, before any of them are on disk. */+interface PlannedNote {+ readonly path: string;+ /** The bytes to write, or `null` when the note is already correct. */+ readonly text: string | null;+ readonly disposition: NoteDisposition;+}+/**- * Write or refresh one region-bearing note. Returns its disposition.- * Throws RegionError (fail-closed) when the existing file's sentinels- * are corrupted - the file is never partially rewritten.+ * Decide one region-bearing note's bytes WITHOUT writing them.+ *+ * Planning is separated from writing so that a `RegionError` - the+ * fail-closed verdict on corrupted sentinels - aborts the run before its+ * first byte instead of after the notes that happened to come earlier.+ * The prefix left on disk used to be a deterministic function of module+ * order, which made it predictable but no less wrong: an operator asked+ * to repair one note found the rest of the tree already half-refreshed.*/-function upsertNote(- path: string,- head: string,- regions: ReadonlyArray<Region>,-): "created" | "updated" | "unchanged" {+function planNote(path: string, head: string, regions: ReadonlyArray<Region>): PlannedNote {if (!existsSync(path)) {- atomicWriteFileSync(path, `${head}\n${buildRegionDocument(regions)}`);- return "created";+ return {+ path,+ text: `${head}\n${buildRegionDocument(regions)}`,+ disposition: NOTE_DISPOSITION.created,+ };}const existing = readFileSync(path, "utf8");const merged = mergeRegions(existing, regions);- if (merged === existing) return "unchanged";- atomicWriteFileSync(path, merged);- return "updated";+ if (merged === existing) return { path, text: null, disposition: NOTE_DISPOSITION.unchanged };+ return { path, text: merged, disposition: NOTE_DISPOSITION.updated };}-/** Generate or refresh architecture notes for one project tree. */-export function generateArchDocs(vault: string, projectRoot: string): GenerateArchDocsResult {- // Vault-identity write guard (context-integrity-gates, Unit J).- assertVaultIdentityForWrite(vault);- const facts = scanProject(projectRoot);- const key = deriveRepoKey(facts.root);- const dir = join(vault, "Brain", "projects", "arch", key);- mkdirSync(join(dir, "modules"), { recursive: true });+/**+ * A note could not be written, part-way through the write loop.+ *+ * The notes before it are already renamed into place and the notes after+ * it still hold their previous bytes. `rename(2)` is atomic per file and+ * nothing swaps N files at once, so this partial state is reachable and+ * cannot be undone by the loop that produced it. It is repairable, not+ * recoverable in place: one run is a pure function of the scanned facts+ * plus the prose outside each note's regions, so re-running once the+ * cause is fixed rewrites every note, the untouched suffix included.+ *+ * The counts are the reason this type exists. The native errno names a+ * temp file the caller never asked for - `atomicWriteFileSync` writes a+ * sibling and renames it - and says nothing about how much of the tree+ * already moved, which is the one fact an operator needs to know a+ * re-run is not optional.+ */+export class ArchWriteError extends Error {+ /** The note whose write failed. */+ readonly path: string;+ /** Notes whose new bytes are already on disk. */+ readonly written: number;+ /** Notes still holding their previous bytes, this one included. */+ readonly pending: number;- let created = 0;- let updated = 0;- let unchanged = 0;- const tally = (outcome: "created" | "updated" | "unchanged"): void => {- if (outcome === "created") created += 1;- else if (outcome === "updated") updated += 1;- else unchanged += 1;- };+ constructor(path: string, written: number, pending: number, cause: unknown) {+ super(+ `failed to write architecture note ${path} after refreshing ` ++ `${written} of ${written + pending} note(s): ${errorMessage(cause)} - ` ++ "the tree is partially refreshed; fix the cause and re-run, which " ++ "rewrites every note and preserves prose outside the regions",+ { cause },+ );+ this.name = "ArchWriteError";+ this.path = path;+ this.written = written;+ this.pending = pending;+ }+}- const overviewPath = join(dir, "overview.md");- tally(- upsertNote(- overviewPath,+/** How many of `plans` ended in `disposition`. */+function countOf(plans: ReadonlyArray<PlannedNote>, disposition: NoteDisposition): number {+ return plans.filter((plan) => plan.disposition === disposition).length;+}++/** Where one module's note lives. One definition, two call sites. */+function modulePath(dir: string, module: ModuleFact): string {+ return join(dir, "modules", `${module.name}.md`);+}++/**+ * Plan every note, then write them - in that order, and never+ * interleaved.+ *+ * The deadline is checked while PLANNING only. A run that stops at a+ * checkpoint has therefore written nothing at all, and the write loop -+ * the cheap part, 7.9 ms of a 396 ms run on this repository - is allowed+ * to finish rather than being interrupted between two notes.+ *+ * A write that FAILS is the case a deadline policy cannot reach. The loop+ * cannot un-rename the notes already placed, so it reports how far it got+ * instead of implying it got nowhere: see {@link ArchWriteError}.+ */+function renderNotes(+ dir: string,+ key: string,+ facts: ProjectFacts,+ opts: GenerateArchDocsOptions,+ progress: ProgressCounter,+): ReadonlyArray<PlannedNote> {+ const plans: PlannedNote[] = [];+ opts.safeguard?.checkpoint();+ plans.push(+ planNote(+ join(dir, "overview.md"),frontmatter("arch-overview", key, [`repo_path: ${facts.root}`]),overviewRegions(facts, key),),);-- const modulePaths: string[] = [];for (const module of facts.modules) {- const path = join(dir, "modules", `${module.name}.md`);- modulePaths.push(path);- tally(- upsertNote(- path,+ opts.safeguard?.checkpoint();+ plans.push(+ planNote(+ modulePath(dir, module),frontmatter("arch-module", key, [`module: ${module.name}`]),moduleRegions(module),),);}+ const toWrite = plans.filter((plan) => plan.text !== null).length;+ let written = 0;+ for (const plan of plans) {+ if (plan.text !== null) {+ try {+ atomicWriteFileSync(plan.path, plan.text);+ } catch (error) {+ throw new ArchWriteError(plan.path, written, toWrite - written, error);+ }+ written += 1;+ }+ // A note is complete when its bytes are on disk, or when they were+ // already the right bytes - so an unchanged note advances too.+ progress.advance(ARCHITECT_STAGE.render);+ }+ return plans;+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++/**+ * Wrap a caller's sink so one broken stream cannot abort the run, and+ * report the first failure exactly once.+ *+ * `progressCounter` already refuses to let a throwing sink escape when it+ * is given a reporter - but a run spans TWO counters here, the scan's and+ * the renderer's, and a fault reported per counter would tell the caller+ * twice about one closed pipe. Detaching happens here, once, for the+ * whole run.+ */+function guardedSink(+ sink: ProgressSink | undefined,+ onFault: (message: string) => void,+): ProgressSink | undefined {+ if (sink === undefined) return undefined;+ let live = true;+ return (event) => {+ if (!live) return;+ try {+ sink(event);+ } catch (error) {+ live = false;+ onFault(errorMessage(error));+ }+ };+}++/** Generate or refresh architecture notes for one project tree. */+export function generateArchDocs(+ vault: string,+ projectRoot: string,+ opts: GenerateArchDocsOptions = {},+): GenerateArchDocsResult {+ const progressFaults: string[] = [];+ const sink = guardedSink(opts.onProgress, (message) => progressFaults.push(message));+ const progress = progressCounter(OPERATION.architect, sink);+ try {+ return generateRun(vault, projectRoot, opts, sink, progress, progressFaults);+ } catch (error) {+ // A stop the operator asked for, or a deadline that elapsed, is a+ // fact about the run - reported on the stream before the error+ // travels on. Anything else is a failure, and a failure is its own+ // report.+ const reason = progressReasonForError(error);+ if (reason !== null) progress.stop(reason);+ throw error;+ }+}++function generateRun(+ vault: string,+ projectRoot: string,+ opts: GenerateArchDocsOptions,+ sink: ProgressSink | undefined,+ progress: ProgressCounter,+ progressFaults: ReadonlyArray<string>,+): GenerateArchDocsResult {+ // Vault-identity write guard (context-integrity-gates, Unit J).+ assertVaultIdentityForWrite(vault);+ // The scan opens the `walk` stage on its own counter over the same+ // sink; this counter opens `render` and is the one that terminates.+ const facts = scanProject(projectRoot, {+ ...(sink === undefined ? {} : { onProgress: sink }),+ ...(opts.safeguard === undefined ? {} : { safeguard: opts.safeguard }),+ });+ const key = deriveRepoKey(facts.root);+ const dir = join(vault, "Brain", "projects", "arch", key);+ mkdirSync(join(dir, "modules"), { recursive: true });++ // Every note's path is a function of the FACTS, not of the order the+ // writes happen to complete in - `module_paths` is a documented part of+ // the CLI's JSON envelope, and it must not become a schedule report.+ const overviewPath = join(dir, "overview.md");+ const modulePaths = facts.modules.map((module) => modulePath(dir, module));++ // The note count is known only now, and it is known exactly: one+ // overview plus one note per detected module. Unlike the walk, this+ // stage has a denominator.+ progress.start(ARCHITECT_STAGE.render, 1 + facts.modules.length);++ // One critical section over every note, held across the reads AND the+ // writes. Atomicity is not exclusivity: a whole file is renamed into+ // place, so no reader sees torn bytes, yet two architect runs on the+ // same repo would still read the same "before" state and erase each+ // other's merge. Every other Brain read-modify-write takes this lock;+ // this one did not. It cannot stop an operator editing a note in the+ // same millisecond - nothing here can - but that race was never the+ // one the module could do something about.+ //+ // What the race costs is worth naming exactly, because the answer is+ // not torn bytes and a byte comparison will therefore never find it.+ // One run's output is a pure function of the facts plus the prose+ // outside each region, so two runs on one repo compute the same bytes+ // and whichever writes last leaves the same file either way. The loss+ // lands in the REPORT: each run planned from a state the other had+ // already replaced, so both tell the operator they created notes only+ // one of them created. `architect-concurrent-runs.test.ts` is the+ // discriminating test, and the tally is its instrument.+ //+ // The INTERACTIVE budget, not the default. Waiting on this lock is a+ // synchronous freeze of the whole process, and this process has a+ // progress stream and an operator's Ctrl-C behind it. The default is+ // sized for the ingest fan-out, where several processes contend by+ // design and the waiter is a short-lived worker with nothing else to+ // run; a second architect run over the same repo is not that workload.+ // One second absorbs a genuine brief overlap and refuses the rest by+ // name, rather than parking a watched terminal for five.+ const handle = acquireLockSyncWithRetry(dir, LOCK_WAIT_INTERACTIVE_MS);+ let plans: ReadonlyArray<PlannedNote>;+ try {+ plans = renderNotes(dir, key, facts, opts, progress);+ } finally {+ handle.release();+ }+ progress.finish();+return Object.freeze({repoKey: key,dir,overviewPath,modulePaths: Object.freeze(modulePaths),- created,- updated,- unchanged,+ created: countOf(plans, NOTE_DISPOSITION.created),+ updated: countOf(plans, NOTE_DISPOSITION.updated),+ unchanged: countOf(plans, NOTE_DISPOSITION.unchanged),+ progressFault: progressFaults[0] ?? null,});}diff --git a/src/core/brain/architect/scan.ts b/src/core/brain/architect/scan.tsindex 1d5da3dd..f99b0be3 100644--- a/src/core/brain/architect/scan.ts+++ b/src/core/brain/architect/scan.ts@@ -10,13 +10,28 @@* Module detection prefers `src/<dir>` children, then `packages/<dir>`,* and degrades to a single `root` module on flat layouts rather than* guessing.+ *+ * The tree is walked exactly ONCE and every fact is derived from that one+ * traversal, because the walk is where this module's wall clock lives -+ * a scan of this repository is dominated by `statx` and `getdents64`.+ * What the walk refuses to enter is decided by {@link isSkippedDir},+ * which carries the measurement behind that decision.*/import { existsSync, lstatSync, readdirSync, readFileSync } from "node:fs";import { basename, extname, join, resolve } from "node:path";+import { OPERATION, progressCounter, progressReasonForError } from "../progress.ts";+import type { ProgressCounter, ProgressSink } from "../progress.ts";+import type { Safeguard } from "../safeguard.ts";++/**+ * Build outputs and dependency trees the walk never enters, for the ones+ * that are conventionally NOT dot-named. The dot-named members this list+ * used to carry (`.git`, `.venv`, `.next`, `.cache`) are covered by the+ * rule in {@link isSkippedDir} and would be duplicates here.+ */const SKIP_DIRS = new Set([- ".git","node_modules","dist","build",@@ -24,13 +39,38 @@ const SKIP_DIRS = new Set(["coverage","vendor","target",- ".venv","venv","__pycache__",- ".next",- ".cache",]);+/**+ * Whether a DIRECTORY named `name` is one the scan refuses to enter.+ * A file that happens to share one of those names is still a file.+ *+ * Two rules, and deliberately no ignore-file parsing.+ *+ * A dot-named directory is tooling state - agent worktrees, CI+ * definitions, caches, editor state - and architecture notes describe+ * none of it. Measured on this repository: of the 24124 files the scan+ * visited, 21422 (88%) are inside a dot directory, and 21113 of those+ * are one agent-worktree tree under `.claude/`.+ *+ * `.gitignore` was measured against the same tree before being rejected.+ * Honouring every `.gitignore` in it - nested files included - removes+ * exactly 12 of the directories the walk enters, holding 207 files, and+ * every one of them is already inside a dot directory. The 21k-file cost+ * this rule exists for appears in NO `.gitignore`: it is excluded by+ * `.git/info/exclude`, which is local state a project does not ship. A+ * gitignore matcher is real semantics - negation, anchoring,+ * directory-only patterns, precedence across nested files - and on the+ * repository it was proposed for it would have bought nothing the two+ * rules above do not, at the price of a surface that can silently+ * mis-scan every other project.+ */+function isSkippedDir(name: string): boolean {+ return name.startsWith(".") || SKIP_DIRS.has(name);+}+const ENTRY_CANDIDATES = ["src/index.ts","src/index.js",@@ -45,6 +85,9 @@ const ENTRY_CANDIDATES = [const TEST_LAYOUTS = ["tests", "test", "__tests__", "spec"];+/** Where modules are looked for, in preference order. */+const MODULE_BASES = ["src", "packages"];+export interface ModuleFact {readonly name: string;/** Project-relative POSIX path. */@@ -75,21 +118,71 @@ export interface ProjectFacts {const TOP_FILES_CAP = 20;+/**+ * The two stages of one architect run, in the order they run.+ *+ * Declared here rather than beside the renderer because this module is+ * the leaf of the pair's import edge, and because the two names only mean+ * anything together: `walk` is a counter with no denominator (the file+ * count is not known until the walk ends), `render` has one (the note+ * count is `1 + modules.length`, known the moment the walk is over).+ */+export const ARCHITECT_STAGE = Object.freeze({+ walk: "walk",+ render: "render",+} as const);++export interface ScanProjectOptions {+ /**+ * Where a caller watches the walk. Absence means nobody asked.+ *+ * The scan opens the `walk` stage and never closes the stream: the+ * render stage of the same run follows it, and one run has one+ * terminator. This is the shape `runIndex` and `runEmbeddingPhase`+ * already use for the two halves of an index run.+ */+ readonly onProgress?: ProgressSink;+ /**+ * Cooperative deadline, checked once per directory read. That is the+ * walk's only natural boundary: everything between two `readdirSync`+ * calls is a bounded loop over one directory's entries.+ */+ readonly safeguard?: Safeguard;+}+interface WalkStats {files: number;languages: Record<string, number>;+ /** Project-relative POSIX paths of every file, in walk order. */paths: string[];+ /** Project-relative POSIX paths of every directory the walk entered. */+ dirs: string[];+}++/** Count one file's extension, the single place the mapping is defined. */+function tallyExtension(languages: Record<string, number>, path: string): void {+ const ext = extname(path).toLowerCase();+ if (ext !== "") languages[ext] = (languages[ext] ?? 0) + 1;}-function walk(dir: string, stats: WalkStats, prefix: string): void {+function walk(+ dir: string,+ stats: WalkStats,+ prefix: string,+ progress: ProgressCounter,+ safeguard: Safeguard | undefined,+): void {let entries: string[];try {entries = readdirSync(dir);} catch {return;}+ // One directory read, one boundary: the deadline is checked before the+ // count is claimed, so a tripped scan never reports work it abandoned.+ safeguard?.checkpoint();+ progress.advance(ARCHITECT_STAGE.walk);for (const entry of entries.toSorted()) {- if (SKIP_DIRS.has(entry)) continue;const abs = join(dir, entry);const rel = prefix === "" ? entry : `${prefix}/${entry}`;let stat;@@ -102,43 +195,90 @@ function walk(dir: string, stats: WalkStats, prefix: string): void {}if (stat.isSymbolicLink()) continue;if (stat.isDirectory()) {- walk(abs, stats, rel);+ if (isSkippedDir(entry)) continue;+ stats.dirs.push(rel);+ walk(abs, stats, rel, progress, safeguard);continue;}stats.files += 1;stats.paths.push(rel);- const ext = extname(entry).toLowerCase();- if (ext !== "") stats.languages[ext] = (stats.languages[ext] ?? 0) + 1;+ tallyExtension(stats.languages, entry);}}-function statsFor(dir: string): WalkStats {- const stats: WalkStats = { files: 0, languages: {}, paths: [] };- walk(dir, stats, "");- return stats;-}--function listDirs(dir: string): ReadonlyArray<string> {- let entries: string[];+/**+ * The one traversal, reporting a stop on the stage it stopped in.+ *+ * The stage a deadline interrupts is this counter's, so this is where the+ * `stopped` event belongs - the renderer's counter has not opened a stage+ * yet and could only report the stop into silence.+ */+function walkTree(+ root: string,+ progress: ProgressCounter,+ safeguard: Safeguard | undefined,+): WalkStats {+ const stats: WalkStats = { files: 0, languages: {}, paths: [], dirs: [] };try {- entries = readdirSync(dir);- } catch {- return [];+ walk(root, stats, "", progress, safeguard);+ return stats;+ } catch (error) {+ const reason = progressReasonForError(error);+ if (reason !== null) progress.stop(reason);+ throw error;}- return entries- .toSorted()- .filter((entry) => !SKIP_DIRS.has(entry))- .filter((entry) => {- try {- const stat = lstatSync(join(dir, entry));- return !stat.isSymbolicLink() && stat.isDirectory();- } catch {- return false;- }- });}-function readManifest(root: string): ManifestFact | null {+/** What one subtree of an already-walked tree contains. */+interface SubtreeStats {+ readonly files: number;+ readonly languages: Record<string, number>;+ /** Subtree-relative POSIX paths. */+ readonly paths: ReadonlyArray<string>;+}++/**+ * The stats of `prefix` read out of the whole-tree walk, with no second+ * traversal: the walk already visited every file under it, and a path is+ * under `prefix` exactly when it starts with `prefix/`.+ */+function subtreeStats(total: WalkStats, prefix: string): SubtreeStats {+ const head = `${prefix}/`;+ const paths = total.paths+ .filter((path) => path.startsWith(head))+ .map((p) => p.slice(head.length));+ const languages: Record<string, number> = {};+ for (const path of paths) tallyExtension(languages, path);+ return { files: paths.length, languages, paths };+}++/**+ * Direct child directories of `base`, from the same walk. Sorted, because+ * module order decides the rendered note order and must not depend on+ * traversal order.+ */+function childDirs(total: WalkStats, base: string): ReadonlyArray<string> {+ const head = `${base}/`;+ return total.dirs+ .filter((dir) => dir.startsWith(head) && !dir.slice(head.length).includes("/"))+ .map((dir) => dir.slice(head.length))+ .toSorted();+}++/**+ * A manifest and the object it was parsed from. The raw object travels+ * with the fact because entry-point detection needs `main` and `bin`,+ * which the fact does not carry - reading and parsing `package.json` a+ * second time to reach them was two syscalls and a parse for data+ * already in memory, and left two readers that could disagree about+ * what the file said.+ */+interface ManifestRead {+ readonly fact: ManifestFact;+ readonly raw: Record<string, unknown>;+}++function readManifest(root: string): ManifestRead | null {const path = join(root, "package.json");if (!existsSync(path)) return null;try {@@ -147,56 +287,49 @@ function readManifest(root: string): ManifestFact | null {typeof raw["dependencies"] === "object" && raw["dependencies"] !== null? Object.keys(raw["dependencies"] as Record<string, unknown>).toSorted(): [];- return Object.freeze({- name: typeof raw["name"] === "string" ? raw["name"] : null,- version: typeof raw["version"] === "string" ? raw["version"] : null,- description: typeof raw["description"] === "string" ? raw["description"] : null,- dependencies: Object.freeze(deps),- });+ return {+ fact: Object.freeze({+ name: typeof raw["name"] === "string" ? raw["name"] : null,+ version: typeof raw["version"] === "string" ? raw["version"] : null,+ description: typeof raw["description"] === "string" ? raw["description"] : null,+ dependencies: Object.freeze(deps),+ }),+ raw,+ };} catch {return null;}}-function detectModules(root: string): ReadonlyArray<ModuleFact> {- for (const base of ["src", "packages"]) {- const baseDir = join(root, base);- if (!existsSync(baseDir)) continue;- const dirs = listDirs(baseDir);+function moduleFact(name: string, path: string, stats: SubtreeStats): ModuleFact {+ return Object.freeze({+ name,+ path,+ files: stats.files,+ languages: Object.freeze(stats.languages),+ topFiles: Object.freeze(stats.paths.toSorted().slice(0, TOP_FILES_CAP)),+ });+}++function detectModules(total: WalkStats): ReadonlyArray<ModuleFact> {+ for (const base of MODULE_BASES) {+ const dirs = childDirs(total, base);if (dirs.length === 0) continue;return Object.freeze(- dirs.map((name) => {- const stats = statsFor(join(baseDir, name));- return Object.freeze({- name,- path: `${base}/${name}`,- files: stats.files,- languages: Object.freeze(stats.languages),- topFiles: Object.freeze(stats.paths.toSorted().slice(0, TOP_FILES_CAP)),- });- }),+ dirs.map((name) =>+ moduleFact(name, `${base}/${name}`, subtreeStats(total, `${base}/${name}`)),+ ),);}- // Flat layout: the project root is the single module.- const stats = statsFor(root);- return Object.freeze([- Object.freeze({- name: "root",- path: ".",- files: stats.files,- languages: stats.languages,- topFiles: Object.freeze(stats.paths.toSorted().slice(0, TOP_FILES_CAP)),- }),- ]);-}--function detectEntryPoints(root: string, manifest: ManifestFact | null): ReadonlyArray<string> {+ // Flat layout: the project root is the single module, and the root walk+ // IS its walk - nothing is traversed a second time to learn that.+ return Object.freeze([moduleFact("root", ".", total)]);+}++function detectEntryPoints(root: string, manifest: ManifestRead | null): ReadonlyArray<string> {const points = new Set<string>();if (manifest !== null) {- const raw = JSON.parse(readFileSync(join(root, "package.json"), "utf8")) as Record<- string,- unknown- >;+ const raw = manifest.raw;if (typeof raw["main"] === "string") points.add(raw["main"]);if (typeof raw["bin"] === "object" && raw["bin"] !== null) {for (const value of Object.values(raw["bin"] as Record<string, unknown>)) {@@ -211,17 +344,19 @@ function detectEntryPoints(root: string, manifest: ManifestFact | null): Readonl}/** Scan one project tree into deterministic structural facts. */-export function scanProject(projectRoot: string): ProjectFacts {+export function scanProject(projectRoot: string, opts: ScanProjectOptions = {}): ProjectFacts {const root = resolve(projectRoot);const manifest = readManifest(root);- const total = statsFor(root);+ const progress = progressCounter(OPERATION.architect, opts.onProgress);+ progress.start(ARCHITECT_STAGE.walk);+ const total = walkTree(root, progress, opts.safeguard);const testLayout = TEST_LAYOUTS.find((layout) => existsSync(join(root, layout))) ?? null;return Object.freeze({root,- name: manifest?.name ?? basename(root),- manifest,+ name: manifest?.fact.name ?? basename(root),+ manifest: manifest?.fact ?? null,entryPoints: detectEntryPoints(root, manifest),- modules: detectModules(root),+ modules: detectModules(total),testLayout,totalFiles: total.files,languages: Object.freeze(total.languages),diff --git a/src/core/brain/config-template.ts b/src/core/brain/config-template.tsindex 3f4eea91..1acc07b7 100644--- a/src/core/brain/config-template.ts+++ b/src/core/brain/config-template.ts@@ -54,6 +54,7 @@ import {LESSONS_CORROBORATION_MIN_DEFAULT,LESSONS_HALF_LIFE_DAYS_DEFAULT,LESSONS_LIMIT_DEFAULT,+ MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT,MOST_APPLIED_LIMIT_DEFAULT,MOST_APPLIED_WINDOW_DAYS_DEFAULT,STANDING_RULES_MAX_CHARS_DEFAULT,@@ -366,6 +367,26 @@ export const BRAIN_CONFIG_TEMPLATE: ReadonlyArray<BrainTemplateBlock> = Object.f]),],},+ {+ key: "embeddings",+ doc: [+ "Your own record of a decommission announcement you have read, for",+ "the model you have configured. It layers OVER the survey compiled",+ "into this build, which goes stale between releases; a declaration",+ "here is reported immediately. The two keys are declared together",+ "or not at all - a date with no model would re-target itself the",+ "next time you switched models.",+ ],+ emit: "commented-example",+ keys: [+ example("sunset_model", "text-embedding-3-small", [+ "Exact model string, matched against the configured embedding_model.",+ ]),+ example("sunset_at", "2027-03-01", [+ "Announced decommission date, ISO-8601 (YYYY-MM-DD) or timestamp.",+ ]),+ ],+ },{key: "hygiene",doc: ["Continuity-hygiene pass."],@@ -415,6 +436,40 @@ export const BRAIN_CONFIG_TEMPLATE: ReadonlyArray<BrainTemplateBlock> = Object.fdef("vault_instruction_file", L.vault_instruction_file),],},+ {+ key: "maintenance",+ doc: [+ "Quiet-window maintenance lane (`o2b brain maintenance run`).",+ "The window and the busy threshold are flags on that verb - they",+ "belong to the schedule that invokes it. These two belong to the",+ "vault, because they answer what the cron line cannot: how much of",+ "this machine a background pass may take, and how many times a task",+ "may fail before re-running it stops being a retry.",+ ],+ emit: "commented-default",+ keys: [+ example("host_pressure_percent", 150, [+ "Skip heavy work when the host's one-minute run queue stands at or",+ "above this percentage of the CPUs this process may use (150 = half",+ "again as many runnable tasks as CPUs). Unset by default, which",+ "leaves the gate off - a number here would start refusing work on",+ "vaults whose operator never asked for the gate.",+ "Where the metric is degenerate - a platform whose load average is a",+ "constant, or a cgroup with a CPU bandwidth quota, where the run",+ "queue is the whole host's - the gate stays OPEN and the journal",+ "carries a pressure:unmeasurable line saying which. It never reports",+ "an unreadable host as a quiet one.",+ ]),+ def("failure_streak_limit", MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT, [+ "Refuse a lane task that has failed this many times in a row in the",+ "run journal, instead of retrying it; --force runs it anyway. A",+ "single success clears the streak. Nothing here supervises a",+ "repeating failure, and the lane runs tasks stale-first, so a",+ "permanently broken task would otherwise take the lease first on",+ "every pass.",+ ]),+ ],+ },{key: "notes",doc: [diff --git a/src/core/brain/diagnostics.ts b/src/core/brain/diagnostics.tsindex 33dfaaaa..85b410ea 100644--- a/src/core/brain/diagnostics.ts+++ b/src/core/brain/diagnostics.ts@@ -457,6 +457,38 @@ export const DIAGNOSTIC_SIGNALS: ReadonlyMap<string, DiagnosticSignal> = new MapnextCommand: "o2b search provider presets",autoRepairable: false,},+ {+ // How long since a state-changing pass left a recovery point.+ // The exit is the LISTING verb rather than a command that makes+ // one: a snapshot is a side effect of dream, upgrade and the+ // memory import, so "take a snapshot" is not a thing an operator+ // does, and the listing is what answers the question the finding+ // raises - when the last recovery point was taken and for what.+ // Spelled as a literal, not imported from the check that produces+ // it: importing a `*_CODE` identifier from this module into a+ // doctor check would make the census follow the import back and+ // read every registry entry below as a doctor code. Same reason+ // `recall-channel-silent` is a literal here.+ code: "recovery-point-stale",+ issueClass: "newest recovery point older than the liveness window",+ nextCommand: "o2b brain snapshot log",+ autoRepairable: false,+ },+ {+ // An announced decommission of the configured embedding model,+ // inside the warning window. The exit is the curated catalog for+ // the same reason `search-chunk-window-undeclared` points there:+ // the act this finding asks for is CHOOSING a replacement model,+ // and switching models is a config key no verb in this tool+ // writes. The re-embed that follows the edit is named in the+ // warning's own prose rather than invented as the command here,+ // because running it before the key changes would rebuild the+ // index against the model that is going away.+ code: "embedding-model-sunset-announced",+ issueClass: "configured embedding model has an announced decommission date",+ nextCommand: "o2b search provider presets",+ autoRepairable: false,+ },{code: "git-history-absent",issueClass: "no ingested git history",diff --git a/src/core/brain/doctor-exits.ts b/src/core/brain/doctor-exits.tsindex 75871f4d..5e324cbe 100644--- a/src/core/brain/doctor-exits.ts+++ b/src/core/brain/doctor-exits.ts@@ -203,6 +203,33 @@ const EXCLUSIONS: ReadonlyArray<DoctorExitExclusion> = ["is not derivable from the malformed text, and the event itself stays valid, so nothing " +"is lost by leaving it reported",},+ {+ code: "embedding-model-sunset-unsurveyed",+ reason:+ "the configured model is outside the shipped decommission survey, and the repair is for " ++ "somebody to look up whether its provider has announced anything - a question about the " ++ "world, answered by reading a vendor's notice rather than by any edit to this vault. The " ++ "finding says only that no statement was made, which is deliberately not the same as " ++ "saying no decommission exists",+ },+ {+ code: "embedding-model-sunset-undetermined",+ reason:+ "the check ran and reached no verdict, for one of three reasons it names in the finding: " ++ "the configuration resolved no model, the survey is older than its horizon so its record " ++ "of no announcement has expired, or a shipped survey entry carries an unparseable date. " ++ "The first is an edit to a config file whose intended value only the operator knows, and " ++ "the other two are defects in this build rather than in the vault being examined",+ },+ {+ code: "recovery-point-unmeasured",+ reason:+ "the recovery-point history is there and the walk over it was refused. What repairs that " ++ "depends on why - a permission an operator has to decide to grant, a directory owned by " ++ "another user after a sync that preserved ownership, or storage that has started failing - " ++ "and the archives themselves must never be removed to make a listing succeed, since they " ++ "are the only way back from a mistake",+ },{code: "recall-channel-unmeasured",reason:diff --git a/src/core/brain/doctor.ts b/src/core/brain/doctor.tsindex 784c5e5b..7569afb7 100644--- a/src/core/brain/doctor.ts+++ b/src/core/brain/doctor.ts@@ -69,7 +69,9 @@ import {readAllLogRecords,readAllPreferenceRecords,} from "./doctor/records.ts";+import { embeddingSunsetCheck } from "./doctor/embedding-sunset-check.ts";import { recallChannelCoverageCheck } from "./doctor/recall-channel-coverage.ts";+import { recoveryPointLivenessCheck } from "./doctor/recovery-point-liveness.ts";import { removedToolReferenceCheck } from "./doctor/removed-tool-checks.ts";import { makeStaleDependencyCheck } from "./doctor/stale-dependency-check.ts";import { auditStaleDependencies } from "./stale-dependency.ts";@@ -163,6 +165,8 @@ const DOCTOR_CHECKS: ReadonlyArray<DoctorCheck> = Object.freeze([vaultMarkerProbe,staleLockProbe,recallChannelCoverageCheck,+ recoveryPointLivenessCheck,+ embeddingSunsetCheck,]);// ----- Entry point ----------------------------------------------------------diff --git a/src/core/brain/doctor/embedding-sunset-check.ts b/src/core/brain/doctor/embedding-sunset-check.tsnew file mode 100644index 00000000..1d563cc7--- /dev/null+++ b/src/core/brain/doctor/embedding-sunset-check.ts@@ -0,0 +1,261 @@+/**+ * Warn before the embedding model is decommissioned, not after+ * (t_e7a226ce).+ *+ * The index stamps the embedding model into its ABI tokens, so changing+ * the model invalidates every stored vector and the only remedy is a full+ * re-embed of the corpus. That machinery fires AFTER the operator has+ * already changed the model, and by default only as a warning. This check+ * is the strictly earlier signal: it speaks while the config is still+ * correct and the index still valid, so a migration can be scheduled+ * rather than met.+ *+ * ## Why it lives in `o2b brain doctor`+ *+ * `o2b search check` owns the provider question and the 5/6 exit codes,+ * but it has no clock at all - reading it end to end there is no `Date`,+ * no `now`, no time parameter - so a date comparison there would need a+ * new seam. This doctor already carries `DoctorCheckContext.now`, injected+ * by `runDoctor` precisely so age-based lints can be pinned, plus the+ * severity ladder and the `uncertain` stream a check needs to say what it+ * could not establish. It is the first doctor check to resolve search+ * config; the `core/brain -> core/search` import edge already exists+ * (`runtime-notices.ts`).+ *+ * ## The three answers, and why two of them are not silence+ *+ * | verdict | outcome |+ * |------------------|----------------------------------------------------|+ * | announced, near | warning, naming the model and the date |+ * | announced, far | nothing - the condition does not hold yet |+ * | none_announced | nothing - the survey looked and found nothing |+ * | unsurveyed | uncertain: NO statement was made about this model |+ * | undetermined | uncertain, naming which half could not be reached |+ *+ * `unsurveyed` is deliberately not folded into `none_announced`.+ * `embedding_model` is a free string with zero validation and this tool's+ * own onboarding text recommends a preview model that no catalog here+ * carries, so off-survey is the NORMAL case - and reporting "no sunset+ * announced" for a model nobody looked up is the misleading silence this+ * release removes. It reaches the `uncertain` stream rather than the+ * warning stream because it is not a defect in the vault and it does not+ * move the exit code.+ *+ * ## What the message may not say+ *+ * It never names a vendor. The resolved provider is one of four TRANSPORT+ * kinds - `openai-compat` says nothing about whose endpoint it is - and+ * vendor identity exists only inside a free-form `embedding_base_url` that+ * nothing in this tree maps. A message naming one would be inferring it+ * from a URL.+ *+ * And the exit is not a config edit: no verb in this tool writes a config+ * key. The registered command is the curated catalog, following+ * `search-chunk-window-undeclared`, which points at+ * `o2b search provider presets` for exactly this reason - the operator's+ * next act is choosing a replacement model, and the catalog is what lists+ * the candidates.+ */++import { resolveSearchConfig } from "../../search/index.ts";+import { resolveEmbeddingSunsetDeclaration } from "../policy.ts";+import {+ classifyEmbeddingSunset,+ EMBEDDING_SUNSET,+ EMBEDDING_SUNSET_SOURCE,+ EMBEDDING_SUNSET_SURVEY,+ EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS,+ EMBEDDING_SUNSET_UNDETERMINED_REASON,+ type EmbeddingSunsetSurvey,+ type EmbeddingSunsetVerdict,+} from "../../search/embeddings/sunset.ts";+import { LOCAL_EMBEDDING_MODEL } from "../../search/embeddings/signature.ts";+import type { DoctorIssue } from "../types.ts";+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";+import { pushUncertain } from "./uncertain-stream.ts";++/** A decommission date is declared and is inside the warning window. */+export const EMBEDDING_MODEL_SUNSET_ANNOUNCED_CODE = "embedding-model-sunset-announced";++/** The configured model is outside the survey; no statement was made. */+export const EMBEDDING_MODEL_SUNSET_UNSURVEYED_CODE = "embedding-model-sunset-unsurveyed";++/** The check ran and could establish no verdict; the message says which half. */+export const EMBEDDING_MODEL_SUNSET_UNDETERMINED_CODE = "embedding-model-sunset-undetermined";++/**+ * How far ahead of a declared date the warning starts.+ *+ * A quarter, because the remedy is a full re-embed of the corpus and that+ * is a scheduling decision rather than a command an operator runs between+ * two other things: it costs provider budget, it takes as long as the+ * vault is large, and the replacement model has to be chosen and its+ * dimension settled first. Warning a year out would be noise; warning a+ * week out would be an emergency.+ */+export const EMBEDDING_SUNSET_WARNING_WINDOW_DAYS = 90;++/** The cost the warning is warning about, named once. */+const MIGRATION_COST =+ "changing the model invalidates every stored vector, so the migration is a full re-embed of " ++ "the corpus";++/**+ * The provenance clause every message carries.+ *+ * It states that the claim is about a MODEL STRING and rests on a survey+ * with a review date - which is the honest form for a fact hardcoded from+ * a published announcement, and the sentence that lets an operator judge+ * how much to trust it.+ */+function provenance(verdict: EmbeddingSunsetVerdict): string {+ if (verdict.source !== EMBEDDING_SUNSET_SOURCE.declaration) {+ return `this rests on a decommission survey last reviewed ${verdict.surveyed_at}, which records model strings and identifies nobody's endpoint`;+ }+ const base =+ "this is the date declared in embeddings.sunset_at in Brain/_brain.yaml, which outranks the survey compiled into this build";+ if (!verdict.overrode_survey) return base;+ // A silent override is how the wrong record survives, so both are named+ // and the operator decides which to correct.+ const held =+ verdict.survey_sunset_at === null+ ? "recorded no announcement for it"+ : `records ${verdict.survey_sunset_at}`;+ return `${base}. Note the disagreement: that survey, reviewed ${verdict.surveyed_at}, ${held} - one of the two is out of date`;+}++function announcedMessage(verdict: EmbeddingSunsetVerdict): string {+ const days = verdict.days_remaining ?? 0;+ const when =+ days < 0+ ? `passed ${Math.abs(days)} days ago`+ : `${days} days away, inside the ${EMBEDDING_SUNSET_WARNING_WINDOW_DAYS}-day window`;+ return (+ `the configured embedding model ${verdict.model} has an announced decommission date of ` ++ `${verdict.sunset_at}, ${when}. Plan the move now: ${MIGRATION_COST}. Note ${provenance(verdict)}`+ );+}++function undeterminedMessage(verdict: EmbeddingSunsetVerdict): string {+ switch (verdict.reason) {+ case EMBEDDING_SUNSET_UNDETERMINED_REASON.modelUnresolved:+ return (+ "semantic search is enabled but the configuration resolved no embedding model, so there " ++ `was nothing to check for an announced decommission. ${provenance(verdict)}`+ );+ case EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyStale:+ return (+ `the decommission survey covers ${verdict.model} and records no announcement, but it was ` ++ `reviewed ${verdict.surveyed_at}, more than ${EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS} days ` ++ "ago. A negative is a claim about the world and it expires, so this build will not report " ++ "it as a clean bill of health"+ );+ case EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyEntryMalformed:+ return (+ `the decommission survey entry for ${verdict.model} carries a date this build cannot ` ++ "parse, so no verdict was reached. That is a defect in the shipped table rather than in " ++ "this vault"+ );+ case null:+ // Unreachable: `undetermined` always carries a reason, and the+ // arm exists so a fourth reason fails to compile here rather than+ // producing an empty sentence.+ return `no verdict was reached for ${verdict.model}, and this build recorded no reason`;+ }+}++function unsurveyedMessage(verdict: EmbeddingSunsetVerdict): string {+ return (+ `the configured embedding model ${verdict.model} is outside this build's decommission survey ` ++ `(reviewed ${verdict.surveyed_at}), so NO sunset statement was made about it. That is not the ` ++ "same as no decommission having been announced - nobody here looked this model up. If it is " ++ `retired under you, ${MIGRATION_COST}`+ );+}++/**+ * Build the check against `survey`.+ *+ * A factory, following `makeStaleDependencyCheck`: the survey is data the+ * check reads rather than logic it owns, so injecting it makes every+ * verdict reachable from a test without editing the shipped table.+ */+export function makeEmbeddingSunsetCheck(+ survey: EmbeddingSunsetSurvey = EMBEDDING_SUNSET_SURVEY,+): DoctorCheck {+ return {+ failSoft: true,+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {+ let semantic;+ try {+ semantic = resolveSearchConfig({ vault: ctx.vault, configPath: ctx.configPath }).semantic;+ } catch (err) {+ pushUncertain(out.uncertain, {+ code: EMBEDDING_MODEL_SUNSET_UNDETERMINED_CODE,+ path: ctx.configPath ?? ctx.vault,+ message:+ "the search configuration could not be resolved, so the configured embedding model " ++ `could not be checked for an announced decommission: ${+ err instanceof Error ? err.message : String(err)+ }`,+ });+ return;+ }+ // No model is in use, so there is no decommission to be ahead of.+ // Not silence about a defect: the disabled state has its own+ // reported class (`semantic-capability-disabled`) with its own exit,+ // and repeating it here would meet an operator with two findings for+ // one condition.+ if (!semantic.enabled || semantic.provider === "disabled") return;++ // The local embedder ships inside this build and carries no model+ // string in the configuration, so it is named the way the index+ // names it rather than reported as unresolved.+ const model = semantic.provider === "local" ? LOCAL_EMBEDDING_MODEL : semantic.model;+ // The operator's layer, read straight off the context rather than+ // loaded here: `_brain.yaml` is already resolved once per pass, and+ // a second read could disagree with the one every other check saw.+ // A vault with no declaration yields `null`, which means "consult+ // the survey" and never "no shutdown exists".+ const declared = resolveEmbeddingSunsetDeclaration(ctx.config);+ const verdict = classifyEmbeddingSunset(+ model,+ ctx.now.getTime(),+ survey,+ declared ?? undefined,+ );++ switch (verdict.state) {+ case EMBEDDING_SUNSET.noneAnnounced:+ return;+ case EMBEDDING_SUNSET.announced:+ if ((verdict.days_remaining ?? 0) > EMBEDDING_SUNSET_WARNING_WINDOW_DAYS) return;+ out.issues.push({+ severity: "warning",+ code: EMBEDDING_MODEL_SUNSET_ANNOUNCED_CODE,+ path: ctx.configPath ?? ctx.vault,+ target: verdict.model ?? "",+ message: announcedMessage(verdict),+ } satisfies DoctorIssue);+ return;+ case EMBEDDING_SUNSET.unsurveyed:+ pushUncertain(out.uncertain, {+ code: EMBEDDING_MODEL_SUNSET_UNSURVEYED_CODE,+ path: ctx.configPath ?? ctx.vault,+ message: unsurveyedMessage(verdict),+ });+ return;+ case EMBEDDING_SUNSET.undetermined:+ pushUncertain(out.uncertain, {+ code: EMBEDDING_MODEL_SUNSET_UNDETERMINED_CODE,+ path: ctx.configPath ?? ctx.vault,+ message: undeterminedMessage(verdict),+ });+ return;+ }+ },+ };+}++/** The registered instance, reading the shipped survey. */+export const embeddingSunsetCheck: DoctorCheck = makeEmbeddingSunsetCheck();diff --git a/src/core/brain/doctor/recovery-point-liveness.ts b/src/core/brain/doctor/recovery-point-liveness.tsnew file mode 100644index 00000000..92e76dc3--- /dev/null+++ b/src/core/brain/doctor/recovery-point-liveness.ts@@ -0,0 +1,234 @@+/**+ * How long since anything left a recovery point - and what that cannot+ * tell you (t_1037d94e).+ *+ * ## Why this reports liveness ONLY+ *+ * The check a durability question asks for is "is the job registered, and+ * did it run". The first half has no referent in this product. Nothing+ * here registers a scheduled job: every scheduled-job surface in the tree+ * is a recipe RENDERER that prints text for the operator's own scheduler+ * and writes nothing (`src/cli/cron-recipe.ts`, `search-cron-template.ts`,+ * `partner-codegraph-cron.ts` all say so at their own site). There is no+ * record whose presence could be looked up, and the host's crontab is out+ * of reach of a tool that never installed anything into it.+ *+ * So PRESENCE is unobservable, and a check reporting "durability job+ * missing" would be inventing the fact it claims to have measured. What+ * IS observable is the age of the artifact a durability pass leaves+ * behind. That is what this reports, and {@link SCHEDULE_UNOBSERVABLE_CLAUSE}+ * is carried in every message so a reader is never left assuming the+ * other half was checked.+ *+ * ## Why the recovery point, and not some other artifact+ *+ * `Brain/.snapshots/<run_id>.tar.zst` is the one artifact whose whole+ * purpose is surviving a mistake. It is written before every+ * state-changing pass - dream, upgrade, the Claude-memory import - so its+ * age is the age of the last point the vault can be rolled back to. The+ * search index is a poor substitute: it is derived and rebuildable, so a+ * stale index costs a rebuild rather than a memory.+ *+ * ## The four states, and why an empty history is not one of them+ *+ * {@link listSnapshots} draws the distinctions this check needs, and they+ * are reused rather than re-implemented:+ *+ * - an ABSENT directory is an empty history: no archives and nothing+ * skipped. No state-changing pass has ever run, so there is no+ * schedule to have missed and no artifact to be stale. Reporting here+ * would be reporting an expectation nobody set.+ * - a POPULATED directory gives a newest mtime, which is measurable.+ * - a directory that IS there and cannot be enumerated throws, and that+ * is neither answer - it reaches the uncertain stream naming why.+ * - an ARCHIVE that is named in the directory and could not be described+ * - a `stat` that failed, a run id this build will not accept - is+ * reported to the same stream, whether or not other archives survived.+ * When none did, the vault has a history nobody could read and that is+ * emphatically not "no pass has ever run"; when some did, the measured+ * age is the newest READABLE one's and the entry nobody could stat may+ * be newer, so the number is an upper bound and the reader is told the+ * listing was partial.+ *+ * ## Not the durability gate+ *+ * `src/core/brain/gates/durability.ts` is unrelated despite the name: it+ * classifies extracted-fact TEXT as worth keeping versus transient noise,+ * has no I/O and no notion of storage at all. Two meanings of "durable"+ * sharing one module would be a namespace, not an abstraction, so this+ * check lives beside its siblings in `doctor/` instead.+ *+ * The clock is {@link DoctorCheckContext.now}, never a global read, so+ * every age below is pinnable from a test.+ */++import { msToWholeDays } from "../time.ts";+import {+ describeSnapshotEntrySkip,+ listSnapshots,+ type SnapshotEntrySkip,+ type SnapshotInfo,+} from "../snapshot.ts";+import { snapshotsDir } from "../paths.ts";+import type { DoctorIssue } from "../types.ts";+import type { DoctorCheck, DoctorCheckContext, DoctorFindings } from "./check.ts";+import { pushUncertain } from "./uncertain-stream.ts";++/** The newest recovery point is older than the window. */+export const RECOVERY_POINT_STALE_CODE = "recovery-point-stale";++/**+ * The recovery-point history is there and some or all of it could not be+ * read - the directory refused enumeration, or an archive inside it could+ * not be described. One code for both because the consequence is one+ * thing: the age reported here is not the age of the newest recovery+ * point, and the message says which of the two happened.+ */+export const RECOVERY_POINT_UNMEASURED_CODE = "recovery-point-unmeasured";++/**+ * How old the newest recovery point may be before it is reported.+ *+ * Wide enough that a vault used occasionally is not nagged - a snapshot is+ * a side effect of a state-changing pass, not a nightly chore - and narrow+ * enough that a vault whose passes silently stopped is reported while the+ * change that stopped them is still findable. It matches the recall+ * channel's coverage window for the same reason: a month is the coarsest+ * period over which "nothing happened" is still a fact about this vault+ * rather than about the calendar.+ */+export const RECOVERY_POINT_LIVENESS_WINDOW_DAYS = 30;++/**+ * The half of the durability question this check did NOT answer, carried+ * verbatim in every finding it produces.+ *+ * Exported so the tests assert the disclaimer is present without pinning+ * the prose around it, and so the two findings cannot drift into two+ * differently-worded admissions of the same gap.+ */+export const SCHEDULE_UNOBSERVABLE_CLAUSE =+ "whether a schedule exists was NOT checked: nothing in this tool registers a scheduled job - " ++ "every cron surface renders a recipe for your own scheduler and writes nothing - so a schedule " ++ "that stopped and a schedule that was never installed leave identical evidence";++function describe(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++/** The newest recovery point's age in whole days, or why there is none. */+type RecoveryPointAge =+ /** At least one archive; `days` is the newest one's age. */+ | { readonly kind: "measured"; readonly days: number; readonly runId: string }+ /** No archive has ever been written; nothing to be stale. */+ | { readonly kind: "empty" }+ /** The history is there and could not be read. */+ | { readonly kind: "unreadable"; readonly reason: string };++/**+ * How many skipped entries are named before the message stops listing+ * them. Three, because the sentence has to stay readable next to the+ * clause it shares a line with, and the count that precedes them is the+ * fact a reader acts on - the names are there so the first one can be+ * looked at without another command.+ */+const MAX_NAMED_SKIPS = 3;++/** `<name> (<reason>: <detail>)` for the first few, then a count. */+function describeSkips(skipped: ReadonlyArray<SnapshotEntrySkip>): string {+ const named = skipped.slice(0, MAX_NAMED_SKIPS).map(describeSnapshotEntrySkip).join(", ");+ const rest = skipped.length - Math.min(skipped.length, MAX_NAMED_SKIPS);+ return rest > 0 ? `${named}, and ${rest} more` : named;+}++function newestRecoveryPoint(infos: ReadonlyArray<SnapshotInfo>, now: Date): RecoveryPointAge {+ if (infos.length === 0) return { kind: "empty" };+ let newest = infos[0]!;+ let newestMs = Date.parse(newest.created_at);+ for (const info of infos.slice(1)) {+ const ms = Date.parse(info.created_at);+ if (Number.isFinite(ms) && (!Number.isFinite(newestMs) || ms > newestMs)) {+ newest = info;+ newestMs = ms;+ }+ }+ if (!Number.isFinite(newestMs)) {+ return {+ kind: "unreadable",+ reason: `no recovery point carried a parseable timestamp (newest was ${newest.run_id})`,+ };+ }+ return {+ kind: "measured",+ days: msToWholeDays(now.getTime() - newestMs),+ runId: newest.run_id,+ };+}++/** One uncertain entry, worded once, for every way this check came up short. */+function unmeasured(ctx: DoctorCheckContext, out: DoctorFindings, what: string): void {+ pushUncertain(out.uncertain, {+ code: RECOVERY_POINT_UNMEASURED_CODE,+ path: snapshotsDir(ctx.vault),+ message: `${what}. Note that ${SCHEDULE_UNOBSERVABLE_CLAUSE}`,+ });+}++export const recoveryPointLivenessCheck: DoctorCheck = {+ failSoft: true,+ run(ctx: DoctorCheckContext, out: DoctorFindings): void {+ let listing;+ try {+ listing = listSnapshots(ctx.vault);+ } catch (err) {+ unmeasured(+ ctx,+ out,+ `the recovery-point history exists and could not be read (${describe(err)}), so the age ` ++ "of the newest one is unknown",+ );+ return;+ }++ const age = newestRecoveryPoint(listing.snapshots, ctx.now);+ if (listing.skipped.length > 0) {+ // Reported whether or not any archive survived, because the two+ // shapes are wrong in different directions: with none left there is+ // a history nobody could read, and with some left the age below is+ // only the newest READABLE one's.+ unmeasured(+ ctx,+ out,+ age.kind === "measured"+ ? `${listing.skipped.length} archive(s) in the recovery-point history could not be ` ++ `read - ${describeSkips(listing.skipped)} - so the age reported below is that of ` ++ "the newest READABLE recovery point and an entry skipped here may be newer"+ : `the recovery-point history is populated and no archive in it could be read - ` ++ `${describeSkips(listing.skipped)} - so whether a recovery point exists at all is ` ++ "unknown. This is NOT a vault that has never taken one",+ );+ }+ if (age.kind === "empty") return;+ if (age.kind === "unreadable") {+ unmeasured(+ ctx,+ out,+ `the recovery-point history exists and could not be read (${age.reason}), so the age ` ++ "of the newest one is unknown",+ );+ return;+ }+ if (age.days <= RECOVERY_POINT_LIVENESS_WINDOW_DAYS) return;+ out.issues.push({+ severity: "warning",+ code: RECOVERY_POINT_STALE_CODE,+ path: snapshotsDir(ctx.vault),+ target: age.runId,+ message:+ `the newest recovery point (${age.runId}) is ${age.days} days old, past the ` ++ `${RECOVERY_POINT_LIVENESS_WINDOW_DAYS}-day window. A snapshot is written before every ` ++ "state-changing pass, so this measures how long since one ran - and " ++ SCHEDULE_UNOBSERVABLE_CLAUSE,+ } satisfies DoctorIssue);+ },+};diff --git a/src/core/brain/doctor/uncertainty-probes.ts b/src/core/brain/doctor/uncertainty-probes.tsindex 19685e63..83480dfe 100644--- a/src/core/brain/doctor/uncertainty-probes.ts+++ b/src/core/brain/doctor/uncertainty-probes.ts@@ -115,11 +115,18 @@ export const vaultMarkerProbe: DoctorCheck = {},};-/** Code for a `.lock` file the doctor found under the Brain tree. */+/** Code for a `.lock` file the doctor found in one of OSB's vault directories. */const STALE_LOCK_CODE = "stale-lock";/**- * Report every `.lock` file under `Brain/`.+ * Report every `.lock` file in the directories OSB writes into the vault.+ *+ * The scan takes the VAULT and enumerates its own roots+ * ({@link scanStaleLocks}). This probe used to pass `brainDirs(vault).brain`+ * and so walked `Brain/` alone, which silently missed the content manifest+ * and the ingest checkpoint in `.open-second-brain/` - the two locks a+ * crashed parallel ingest is most likely to leave behind, and the ones the+ * retry docblock points an operator here to find.** Deliberately NOT age-filtered and deliberately not removed. The lock* primitive is a single-attempt exclusive create with no breaker, by@@ -133,9 +140,7 @@ const STALE_LOCK_CODE = "stale-lock";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)) {+ for (const lockPath of scanStaleLocks(vault)) {pushUncertain(uncertain, {code: STALE_LOCK_CODE,path: lockPath,diff --git a/src/core/brain/dream-stage.ts b/src/core/brain/dream-stage.tsindex f7bd5508..afba5ac1 100644--- a/src/core/brain/dream-stage.ts+++ b/src/core/brain/dream-stage.ts@@ -98,6 +98,13 @@ export interface DreamStageOptions {readonly now: Date;/** Forwarded to the underlying dream pass. */readonly safeguard?: DreamOptions["safeguard"];+ /**+ * Forwarded to the underlying dream pass. Staging IS a dream call, so+ * a caller who asked to watch a staged pass watches the same five+ * stages; a second counter here would report them twice under a+ * different operation name.+ */+ readonly onProgress?: DreamOptions["onProgress"];readonly agentName?: string;}@@ -242,6 +249,7 @@ export function stageDream(vault: string, opts: DreamStageOptions): DreamStageBunow: opts.now,dryRun: true,...(opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),+ ...(opts.onProgress !== undefined ? { onProgress: opts.onProgress } : {}),...(opts.agentName !== undefined ? { agentName: opts.agentName } : {}),});const plan = projectDreamPlan(summary);@@ -357,6 +365,7 @@ export function validateDreamBundle(now: opts.now,dryRun: true,...(opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),+ ...(opts.onProgress !== undefined ? { onProgress: opts.onProgress } : {}),...(opts.agentName !== undefined ? { agentName: opts.agentName } : {}),});const recomputed = projectDreamPlan(summary);@@ -395,6 +404,7 @@ export function applyDreamBundle(const summary = dream(vault, {now: opts.now,...(opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),+ ...(opts.onProgress !== undefined ? { onProgress: opts.onProgress } : {}),...(opts.agentName !== undefined ? { agentName: opts.agentName } : {}),});diff --git a/src/core/brain/dream-types.ts b/src/core/brain/dream-types.tsindex dbd71f77..8ee75fcc 100644--- a/src/core/brain/dream-types.ts+++ b/src/core/brain/dream-types.ts@@ -210,6 +210,13 @@ export interface DreamOptions {* pass spots and reports it.*/readonly safeguard?: import("./safeguard.ts").Safeguard;+ /**+ * Live progress observer (nothing-runs-unwatched, U1). Optional, and+ * its absence means nobody asked - the pass behaves exactly as before.+ * Emitted at the same boundaries `safeguard` is checked at, because a+ * run worth guarding with a deadline is a run worth reporting on.+ */+ readonly onProgress?: import("./progress.ts").ProgressSink;/*** Per-run gate overrides (no-dead-ends, Unit E). Additive: omitted, the* run reads every gate from `Brain/_brain.yaml` exactly as before.diff --git a/src/core/brain/dream.ts b/src/core/brain/dream.tsindex a92d112d..3163e187 100644--- a/src/core/brain/dream.ts+++ b/src/core/brain/dream.ts@@ -68,6 +68,12 @@ 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 { buildIntentReview } from "./intent-review.ts";+import {+ OPERATION,+ progressCounter,+ progressReasonForError,+ type ProgressCounter,+} from "./progress.ts";import { regenerateLessonsQuiet } from "./lessons.ts";import { brainDirsForWrite, dreamWorkrunPath } from "./paths.ts";import { loadBrainConfig } from "./policy.ts";@@ -98,9 +104,97 @@ export { scanBrain } from "./dream-scan.ts";// ----- Main entry ----------------------------------------------------------+/**+ * Execution stages of one pass, in the order they run.+ *+ * Neither existing vocabulary fits: `DREAM_PHASE` is the REPORTING order+ * of the summary, and `WORKRUN_PHASE` marks the points where a phase's+ * durable output has already landed - both are about what finished, and+ * progress is about what is happening. These five name the spans between+ * the safeguard checkpoints, which is where the wall-clock actually goes.+ *+ * So one operation has two stage vocabularies, and a reader will trip on+ * it, because `log` is a member of both and means different things: here+ * it is the span during which the audit tail is written, and in+ * `DREAM_PHASE` it is the summary section that reports what that span+ * did. If you are reading a progress record, this is the list it draws+ * from; if you are reading `DreamRunSummary.phases`, that is the other+ * one. Merging them would mean either reporting spans the summary does+ * not have or emitting progress for phases that never execute.+ */+const DREAM_STAGE = Object.freeze({+ scan: "scan",+ plan: "plan",+ apply: "apply",+ log: "log",+ finalize: "finalize",+} as const);++/** Code carried on the summary when the caller's progress sink failed. */+const PROGRESS_SINK_FAULT_CODE = "progress-sink-failed";++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++/**+ * Carry a failed progress sink onto the summary the caller already reads.+ * Only the first fault is reported: the sink is detached after it, so a+ * second entry could only describe the same broken stream twice.+ */+function noteProgressFaults(warnings: DreamWarning[], faults: ReadonlyArray<string>): void {+ const first = faults[0];+ if (first === undefined) return;+ warnings.push({+ code: PROGRESS_SINK_FAULT_CODE,+ message: `progress reporting stopped after the sink threw: ${first}`,+ });+}++/**+ * Run one consolidation pass.+ *+ * A thin shell around {@link dreamRun} for one reason: a pass that stops+ * at a checkpoint - because the operator interrupted it, or because the+ * deadline elapsed - must say so on the progress stream before the error+ * leaves. Without this the stream would simply end, and a caller could+ * not tell a cancelled pass from a crashed one from a hung one, which is+ * the whole distinction `SafeguardAbortError` exists to preserve.+ */export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {+ // A caller's progress sink is an observer, and an observer must not be+ // able to destroy what it observes: a closed pipe or a renderer defect+ // cannot be allowed to abort a pass that is otherwise succeeding. Nor+ // may it vanish - the fault is carried out on the summary the caller+ // already reads, once, and the sink is detached for the rest of the run.+ const progressFaults: string[] = [];+ const progress = progressCounter(OPERATION.dream, opts.onProgress, {+ onSinkError: (error) => progressFaults.push(errorMessage(error)),+ });+ try {+ return dreamRun(vault, opts, progress, progressFaults);+ } catch (error) {+ const reason = progressReasonForError(error);+ if (reason !== null) progress.stop(reason);+ throw error;+ }+}++function dreamRun(+ vault: string,+ opts: DreamOptions,+ progress: ProgressCounter,+ progressFaults: ReadonlyArray<string>,+): DreamRunSummary {const now = opts.now ?? new Date();const dryRun = opts.dryRun === true;+ // The stage opens BEFORE the first checkpoint, not after it. A guard+ // that is already past its deadline - or a signal already aborted -+ // trips here, and a counter with no stage open emits nothing, so the+ // stream would report a pass that was stopped instantly as a pass that+ // never spoke. Those are the two cases this release exists to keep+ // apart.+ progress.start(DREAM_STAGE.scan);opts.safeguard?.checkpoint();const cfg = loadBrainConfig(vault);// Per-run gate resolution (no-dead-ends, Unit E): the override wins for@@ -121,7 +215,9 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// can emit `skip-corrupted-frontmatter` log entries without// aborting.const scan = scanBrain(vault);+ progress.advance(DREAM_STAGE.scan);const intentReview = buildIntentReview(vault, { now });+ progress.start(DREAM_STAGE.plan, scan.preferences.length);// 1-2. Plan per-topic transitions: new unconfirmed preferences,// same-sign noted-redundant moves, rebuttal accumulation.@@ -172,6 +268,11 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {regenerateActiveQuiet(vault, { now });regenerateLessonsQuiet(vault, { now });}+ // A run that changed nothing still finished. Reporting it as an+ // unterminated stream would make an idempotent rerun - the common+ // case - indistinguishable from a pass that died in planning.+ progress.finish();+ noteProgressFaults(warnings, progressFaults);return buildNoOpSummary({runId,dryRun,@@ -196,6 +297,7 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {let snapshotPathStr: string | undefined;// Honor an already-expired deadline BEFORE spending snapshot I/O.opts.safeguard?.checkpoint();+ progress.start(DREAM_STAGE.apply);// v0.12.0 Brain Integrity Suite: durable workrun for the dream pass.// Opened lazily on the mutation path (no workrun on dry-run or@@ -267,6 +369,8 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// this run is on disk, so a deadline that has passed stops the run here// rather than part-way through the audit tail.opts.safeguard?.checkpoint();+ progress.advance(DREAM_STAGE.apply);+ progress.start(DREAM_STAGE.log);// v0.12.0 Brain Integrity Suite: build the gated-slug set once so the// log body and the DreamRunSummary stay consistent — both views must@@ -308,12 +412,17 @@ export function dream(vault: string, opts: DreamOptions = {}): DreamRunSummary {// already past its budget still reached `finalized`. Tripping here// leaves the workrun dangling, which is the documented contract.opts.safeguard?.checkpoint();+ progress.advance(DREAM_STAGE.log);+ progress.start(DREAM_STAGE.finalize);// v0.12.0 Brain Integrity Suite: finalise the durable workrun// immediately before constructing the summary. Any crash building// the summary leaves the workrun dangling for the next pass to// spot. `workrun` is null on dry-run / pre-mutation paths.workrun?.finalize();+ progress.advance(DREAM_STAGE.finalize);+ progress.finish();+ noteProgressFaults(warnings, progressFaults);return buildChangedSummary({runId,diff --git a/src/core/brain/fact-extract.ts b/src/core/brain/fact-extract.tsindex bfb47c58..8d263ced 100644--- a/src/core/brain/fact-extract.ts+++ b/src/core/brain/fact-extract.ts@@ -217,6 +217,12 @@ export interface RouteFactsInput {export interface RouteFactsResult {readonly created: number;+ /**+ * Facts a dry run would have written. Zero on a real run, so `created: 0`+ * plus `withheld: n` is a rehearsal and `created: 0` plus `withheld: 0` is+ * a pass that genuinely found nothing durable to write.+ */+ readonly withheld: number;readonly deduped: number;/*** Facts the durability gate (A2) rejected as transient operational@@ -305,10 +311,16 @@ function entityAnchors(anchorables: ReadonlyArray<AnchorableEntity>, factText: s* the capture boundary; both seams pin that order with tests.*/export function routeExtractedFacts(vault: string, input: RouteFactsInput): RouteFactsResult {- if (input.facts.length === 0) return { created: 0, deduped: 0, durabilityRejected: 0 };+ if (input.facts.length === 0) {+ return { created: 0, withheld: 0, deduped: 0, durabilityRejected: 0 };+ }let created = 0;+ let withheld = 0;let deduped = 0;let durabilityRejected = 0;+ // A dry run never touches `input.dedup`, so a fact repeated within one+ // rehearsal has to be recognised here to be forecast once.+ const withheldHashes = new Set<string>();let entityIndex: ReturnType<typeof buildEntityIndex>;try {entityIndex = buildEntityIndex(vault);@@ -386,7 +398,15 @@ export function routeExtractedFacts(vault: string, input: RouteFactsInput): Rout}continue;}- if (input.dryRun) continue;+ if (input.dryRun) {+ if (withheldHashes.has(hash)) {+ deduped++;+ continue;+ }+ withheldHashes.add(hash);+ withheld++;+ continue;+ }const anchors = entityAnchors(anchorables, fact.text);const topic = `fact-${fact.family}`;try {@@ -414,5 +434,5 @@ export function routeExtractedFacts(vault: string, input: RouteFactsInput): Rout// One unwritable fact must not break capture; the next turn retries.}}- return { created, deduped, durabilityRejected };+ return { created, withheld, deduped, durabilityRejected };}diff --git a/src/core/brain/git/store.ts b/src/core/brain/git/store.tsindex 3410e038..504d5f76 100644--- a/src/core/brain/git/store.ts+++ b/src/core/brain/git/store.ts@@ -27,6 +27,7 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";import { isFullSha } from "./reader.ts";+import { acquireLockSyncWithRetry } from "../sync-lockfile.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";export interface GitCommitRecord {@@ -174,6 +175,13 @@ function readRecords(vault: string, repoKey: string): ReadonlyArray<GitRecord> {* Append records, deduplicating commits by sha and tags by* (name, target) against everything already on disk AND earlier* entries of the same batch.+ *+ * The dedup read and the append are ONE critical section under the+ * sync lock. Appending is atomic enough that no line is ever torn, but+ * dedup is a read-modify-append: two processes ingesting overlapping+ * history at once would both find a sha absent and both write it, so+ * the store's identity guarantee holds only while the read and the+ * append cannot interleave.*/export function appendGitRecords(vault: string,@@ -182,6 +190,19 @@ export function appendGitRecords(): AppendGitRecordsResult {// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);+ const handle = acquireLockSyncWithRetry(commitsPath(vault, repoKey));+ try {+ return appendGitRecordsLocked(vault, repoKey, records);+ } finally {+ handle.release();+ }+}++function appendGitRecordsLocked(+ vault: string,+ repoKey: string,+ records: ReadonlyArray<GitRecord>,+): AppendGitRecordsResult {const existing = readRecords(vault, repoKey);const seenShas = new Set<string>();// Tag identity is (name, target): a RETARGETED tag (same name, newdiff --git a/src/core/brain/ingest/checkpoint.ts b/src/core/brain/ingest/checkpoint.tsindex 94b71086..335c1ccf 100644--- a/src/core/brain/ingest/checkpoint.ts+++ b/src/core/brain/ingest/checkpoint.ts@@ -29,6 +29,7 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";import { canonicalNotePath } from "../../path-safety.ts";+import { acquireLockSyncWithRetry } from "../sync-lockfile.ts";import { isoSecond } from "../time.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";@@ -166,6 +167,12 @@ function sameSet(a: readonly string[], b: readonly string[]): boolean {* disabled, or the completed set (and hence the serialized bytes) unchanged. The* `updated_at` stamp is only bumped when the set actually grows, so a re-record* of an already-recorded set leaves the file byte-identical.+ *+ * The read, the union and the write are ONE critical section under the sync+ * lock. A plan's items are dispatched to parallel subagents, so two of them+ * finishing at once would otherwise each write back the completed set they+ * read - and the later write would erase the earlier item, silently turning a+ * done item back into pending work on the next resume.*/export function recordCompleted(vault: string,@@ -177,20 +184,26 @@ export function recordCompleted(if (!checkpointingEnabled()) return false;// Vault-identity write guard (context-integrity-gates, Unit J).assertVaultIdentityForWrite(vault);- const prev = readCheckpoint(vault, planId);- const merged = new Set<string>(prev?.completed ?? []);- for (const p of paths) merged.add(canonicalNotePath(p));- const completed = [...merged].toSorted();- if (prev && sameSet(prev.completed, completed)) return false;- const next: IngestCheckpoint = {- schema_version: SCHEMA_VERSION,- plan_id: planId,- source_dir: canonicalNotePath(sourceDir),- completed,- updated_at: isoSecond(now),- };- atomicWriteFileSync(checkpointPath(vault, planId), serialize(next));- return true;+ const path = checkpointPath(vault, planId);+ const handle = acquireLockSyncWithRetry(path);+ try {+ const prev = readCheckpoint(vault, planId);+ const merged = new Set<string>(prev?.completed ?? []);+ for (const p of paths) merged.add(canonicalNotePath(p));+ const completed = [...merged].toSorted();+ if (prev && sameSet(prev.completed, completed)) return false;+ const next: IngestCheckpoint = {+ schema_version: SCHEMA_VERSION,+ plan_id: planId,+ source_dir: canonicalNotePath(sourceDir),+ completed,+ updated_at: isoSecond(now),+ };+ atomicWriteFileSync(path, serialize(next));+ return true;+ } finally {+ handle.release();+ }}/**diff --git a/src/core/brain/ingest/content-manifest.ts b/src/core/brain/ingest/content-manifest.tsindex 70d46073..ab684b03 100644--- a/src/core/brain/ingest/content-manifest.ts+++ b/src/core/brain/ingest/content-manifest.ts@@ -34,6 +34,7 @@ import { join } from "node:path";import { atomicWriteFileSync } from "../../fs-atomic.ts";import { canonicalNotePath } from "../../path-safety.ts";+import { acquireLockSyncWithRetry } from "../sync-lockfile.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";/** Only schema version currently understood. Unknown versions are refused. */@@ -223,19 +224,32 @@ export function classifyPaths(* has been deleted is dropped from the manifest (so it will re-classify as* `new` if it ever reappears). Writes atomically and skips the write entirely* when nothing changed. Returns `true` when the manifest was rewritten.+ *+ * The read, the merge and the write are ONE critical section, held under the+ * same sync lock every other Brain read-modify-write takes. Atomicity alone is+ * not enough: `atomicWriteFileSync` renames a complete file into place, so no+ * reader sees torn bytes, but two processes that both read the manifest before+ * either wrote it would each write back a snapshot missing the other's entry.+ * The batch planner dispatches sources across parallel subagents, so that+ * overlap is the designed case rather than a rare one.*/export function updateManifest(vault: string, paths: readonly string[]): boolean {- const entries: Record<string, string> = { ...readManifest(vault).entries };- for (const path of paths) {- const canonical = canonicalNotePath(path);- const abs = join(vault, canonical);- if (existsSync(abs)) {- entries[canonical] = hashPath(abs);- } else {- delete entries[canonical];+ const handle = acquireLockSyncWithRetry(manifestPath(vault));+ try {+ const entries: Record<string, string> = { ...readManifest(vault).entries };+ for (const path of paths) {+ const canonical = canonicalNotePath(path);+ const abs = join(vault, canonical);+ if (existsSync(abs)) {+ entries[canonical] = hashPath(abs);+ } else {+ delete entries[canonical];+ }}+ return writeManifestAtomic(vault, entries);+ } finally {+ handle.release();}- return writeManifestAtomic(vault, entries);}/** Recursively collect regular-file relative paths under `dir` (POSIX slashes). */diff --git a/src/core/brain/link-graph/bridge-discovery.ts b/src/core/brain/link-graph/bridge-discovery.tsindex 57caaa3e..f13ae2d9 100644--- a/src/core/brain/link-graph/bridge-discovery.ts+++ b/src/core/brain/link-graph/bridge-discovery.ts@@ -38,6 +38,7 @@ import { ENTITY_STATUS_SCOPE, vaultPageInStatusScope } from "../entities/page-scimport { resolveNotePath } from "../note-path.ts";import type { SchemaPack } from "../schema-pack.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";+import { OPERATION, progressCounter, withProgress, type ProgressCounter } from "../progress.ts";export const BRIDGE_DEFAULT_MIN_SIMILARITY = 0.8;export const BRIDGE_DEFAULT_MAX_PROPOSALS = 10;@@ -74,8 +75,17 @@ export interface DiscoverBridgesOptions {* per scanned candidate document.*/readonly safeguard?: import("../safeguard.ts").Safeguard;+ /**+ * Live progress observer (nothing-runs-unwatched, U1). Emitted at the+ * same boundaries the deadline is checked at; absence means nobody+ * asked and the scan behaves exactly as before.+ */+ readonly onProgress?: import("../progress.ts").ProgressSink;}+/** The one stage this scan has: it walks candidates and compares them. */+const BRIDGE_STAGE = "candidates";+/** Canonical unordered pair key. */export function bridgePairKey(a: string, b: string): string {return [a, b].toSorted().join("::");@@ -88,6 +98,16 @@ export function bridgePairKey(a: string, b: string): string {export function discoverBridges(store: Store,opts: DiscoverBridgesOptions = {},+): BridgeDiscoveryReport {+ const progress = progressCounter(OPERATION.bridges, opts.onProgress);+ progress.start(BRIDGE_STAGE);+ return withProgress(progress, () => discoverBridgesRun(store, opts, progress));+}++function discoverBridgesRun(+ store: Store,+ opts: DiscoverBridgesOptions,+ progress: ProgressCounter,): BridgeDiscoveryReport {const minSimilarity = opts.minSimilarity ?? BRIDGE_DEFAULT_MIN_SIMILARITY;const maxProposals = Math.max(1, opts.maxProposals ?? BRIDGE_DEFAULT_MAX_PROPOSALS);@@ -130,9 +150,14 @@ export function discoverBridges(// Best similarity per unordered pair.const best = new Map<string, BridgeProposal>();+ // The denominator is known here and only here: `candidates` was+ // materialised and sliced above, unlike the index walk which consumes a+ // generator and can never report a fraction.+ progress.start(BRIDGE_STAGE, candidates.length);for (const candidate of candidates) {// Cooperative deadline: abort between candidates (read-only scan).opts.safeguard?.checkpoint();+ progress.advance(BRIDGE_STAGE);const chunks = store.chunksForDocument(candidate.id).slice(0, BRIDGE_CHUNKS_PER_DOC);for (const chunk of chunks) {const embedding = store.embeddingForChunk(chunk.id);diff --git a/src/core/brain/link-graph/communities.ts b/src/core/brain/link-graph/communities.tsindex a07418d8..91fba5fd 100644--- a/src/core/brain/link-graph/communities.ts+++ b/src/core/brain/link-graph/communities.ts@@ -30,6 +30,7 @@ import type { Store } from "../../search/store.ts";import { getGraphSnapshot } from "./graph-index.ts";import { atomicWriteFileSync } from "../../fs-atomic.ts";import { isoSecond } from "../time.ts";+import { OPERATION, progressCounter, withProgress, type ProgressCounter } from "../progress.ts";import { formatFrontmatter, parseFrontmatter } from "../../vault.ts";import { assertVaultIdentityForWrite } from "../vault-identity.ts";@@ -67,15 +68,40 @@ export interface DetectCommunitiesOptions {* per propagation sweep.*/readonly safeguard?: import("../safeguard.ts").Safeguard;+ /**+ * Live progress observer (nothing-runs-unwatched, U1). Emitted at the+ * same boundaries the deadline is checked at; absence means nobody+ * asked and the pass behaves exactly as before.+ */+ readonly onProgress?: import("../progress.ts").ProgressSink;}+/** The one stage this pass has: it propagates labels, sweep by sweep. */+const COMMUNITY_STAGE = "sweep";+/*** Deterministic label propagation over the store's resolved link* graph. Read-only.*/export function detectCommunities(store: Store, opts: DetectCommunitiesOptions = {}): Community[] {- const minSize = Math.max(2, opts.minSize ?? COMMUNITY_DEFAULT_MIN_SIZE);const maxIterations = Math.max(1, opts.maxIterations ?? COMMUNITY_MAX_ITERATIONS);+ const progress = progressCounter(OPERATION.clusters, opts.onProgress);+ // `maxIterations` is a CEILING, not a denominator: propagation stops as+ // soon as no label changes, so the run usually ends well short of it.+ // Reported anyway, because a ceiling a reader can see is better than a+ // counter with no scale at all - and the stream's `finished` event is+ // what says the pass ended, not the counter reaching the total.+ progress.start(COMMUNITY_STAGE, maxIterations);+ return withProgress(progress, () => detectCommunitiesRun(store, opts, progress, maxIterations));+}++function detectCommunitiesRun(+ store: Store,+ opts: DetectCommunitiesOptions,+ progress: ProgressCounter,+ maxIterations: number,+): Community[] {+ const minSize = Math.max(2, opts.minSize ?? COMMUNITY_DEFAULT_MIN_SIZE);opts.safeguard?.checkpoint();// Resolved undirected adjacency + pathById come from the memoized@@ -93,6 +119,7 @@ export function detectCommunities(store: Store, opts: DetectCommunitiesOptions =for (let iteration = 0; iteration < maxIterations; iteration++) {// Cooperative deadline: abort between sweeps (read-only pass).opts.safeguard?.checkpoint();+ progress.advance(COMMUNITY_STAGE);let changed = false;const next = new Map<number, number>();for (const node of nodes) {diff --git a/src/core/brain/maintenance/host-pressure.ts b/src/core/brain/maintenance/host-pressure.tsnew file mode 100644index 00000000..253f991a--- /dev/null+++ b/src/core/brain/maintenance/host-pressure.ts@@ -0,0 +1,501 @@+/**+ * Host pressure, measured honestly or refused by name (t_992f0c33).+ *+ * The quiet-window lane already gates heavy work on a measured pressure+ * signal - interactive query rate. This module supplies the second one:+ * how loaded the MACHINE is, normalised so a threshold means the same+ * thing on a laptop and on a build box.+ *+ * ## Why this is mostly refusals+ *+ * `os.loadavg()` is the only dependency-free run-queue reading available,+ * and it does not mean what its name suggests everywhere:+ *+ * - on the platform Node and Bun do not implement it for, it returns+ * `[0, 0, 0]` - a constant, not a measurement, and indistinguishable+ * from a genuinely idle host;+ * - inside a cgroup with a CPU BANDWIDTH quota it still reports the+ * whole host's run queue, while the denominator this module divides+ * by is the CPU count the process may be scheduled on. A quota bounds+ * how much CPU TIME the cgroup may consume without changing that+ * count, so the ratio would be computed from two numbers that do not+ * describe the same machine.+ *+ * Whether that second case holds is asked of the cgroup this process is+ * actually in - `/proc/self/cgroup` and every ancestor of the path it+ * names - never of the hierarchy root, which under cgroup v2 carries no+ * `cpu.max` at all. {@link probeCpuQuota} says what each answer rests on.+ *+ * A gate that answered "idle" in either case would be the silent no-op+ * this project forbids: it would read exactly like a quiet host, and the+ * operator would have no way to tell that the gate never evaluated. So+ * the reading is a two-state value - a number, or a named reason there is+ * no number - following the precedent of+ * `UnsupportedPlatformError` in `src/core/config.ts`, which refuses to+ * invent a Windows config path rather than return "a plausible-looking+ * answer to a question this build cannot answer".+ *+ * The caller decides what to do with a refusal. The lane leaves its gate+ * OPEN and journals the reason, because refusing to maintain a vault+ * forever on a platform where the metric does not exist would be a worse+ * failure than not having the gate at all.+ */++import { availableParallelism, loadavg, platform } from "node:os";+import { readFileSync } from "node:fs";+import { join } from "node:path";++/**+ * Platforms whose load average is a constant rather than a measurement.+ * Named rather than inferred, exactly as `UNSUPPORTED_CONFIG_PLATFORMS`+ * is: which platforms report a real run queue is a fact about the+ * runtime, not something to discover by seeing whether the number moves.+ *+ * This is reachable rather than theoretical. `UNSUPPORTED_CONFIG_PLATFORMS`+ * does not refuse win32 outright - `resolveDefaultConfigPath` bows out of+ * the `$HOME/.config` CONVENTION there and says so, leaving+ * `OPEN_SECOND_BRAIN_CONFIG` and `XDG_CONFIG_HOME` as two working ways to+ * run this build on Windows - so a maintenance lane can and does reach+ * this refusal on a real host.+ */+const LOAD_AVERAGE_BLIND_PLATFORMS: ReadonlyArray<string> = Object.freeze(["win32"]);++/** cgroup v2 CPU bandwidth interface file: `"<quota|max> <period>"`. */+const CGROUP_V2_CPU_MAX = "cpu.max";+/** cgroup v1 CPU bandwidth interface file: microseconds, or `-1` for none. */+const CGROUP_V1_CPU_QUOTA = "cpu.cfs_quota_us";+/** The cgroup v2 token meaning "no bandwidth limit". */+const CGROUP_V2_UNLIMITED = "max";+/** The v1 controller whose quota this asks about. */+const CGROUP_V1_CPU_CONTROLLER = "cpu";+/** The only platform with a cgroup hierarchy to consult. */+const CGROUP_PLATFORM = "linux";++/** Whether a pressure reading is a number or a named absence. */+export const HOST_PRESSURE = Object.freeze({+ /** A normalised percentage of this host's usable capacity. */+ measured: "measured",+ /** No number: the accompanying reason says which question failed. */+ unmeasurable: "unmeasurable",+});++export const HOST_PRESSURE_STATES: ReadonlyArray<string> = Object.freeze(+ Object.values(HOST_PRESSURE),+);++export type HostPressureState = (typeof HOST_PRESSURE)[keyof typeof HOST_PRESSURE];++export function isHostPressureState(value: unknown): value is HostPressureState {+ return typeof value === "string" && HOST_PRESSURE_STATES.includes(value);+}++/**+ * Why no pressure number could be produced.+ *+ * Separate from the state for the reason every `*_UNDETERMINED_REASON`+ * vocabulary in this repository is separate from its verdict: one guard+ * over both would let `cpu_quota_in_force` be read back off a journal row+ * where a load percentage belongs.+ */+export const HOST_PRESSURE_UNMEASURABLE_REASON = Object.freeze({+ /** This platform's load average is a constant, not a run queue. */+ platformBlind: "platform_blind",+ /** A CPU bandwidth quota applies: the run queue is the host's, not ours. */+ cpuQuotaInForce: "cpu_quota_in_force",+ /**+ * The quota question could not be answered: the interface exists and+ * refused to be read, its contents did not parse, or which cgroup this+ * process belongs to could not be established. Neither answer is+ * provable, and `false` would be the one that lets a wrong number out.+ */+ cpuQuotaUnknown: "cpu_quota_unknown",+ /** No usable CPU count to normalise the run queue by. */+ parallelismUnknown: "parallelism_unknown",+ /** The run-queue reading itself is not a finite, non-negative number. */+ loadAverageInvalid: "load_average_invalid",+});++export const HOST_PRESSURE_UNMEASURABLE_REASONS: ReadonlyArray<string> = Object.freeze(+ Object.values(HOST_PRESSURE_UNMEASURABLE_REASON),+);++export type HostPressureUnmeasurableReason =+ (typeof HOST_PRESSURE_UNMEASURABLE_REASON)[keyof typeof HOST_PRESSURE_UNMEASURABLE_REASON];++export function isHostPressureUnmeasurableReason(+ value: unknown,+): value is HostPressureUnmeasurableReason {+ return typeof value === "string" && HOST_PRESSURE_UNMEASURABLE_REASONS.includes(value);+}++/**+ * The raw facts a reading is computed from, gathered in one place so the+ * arithmetic and the refusal rules can be tested without a machine that+ * happens to be loaded, containerised, or running Windows.+ */+export interface HostPressureProbe {+ /** `process.platform`. */+ readonly platform: string;+ /** One-minute run-queue average, as the platform reports it. */+ readonly loadAverage1m: number;+ /** CPUs this process may be scheduled on. */+ readonly cpuCount: number;+ /**+ * Whether a CPU bandwidth limit applies: `true` a limit was read off+ * this process's own cgroup or one of its ancestors, `false` every+ * interface on that chain declares none (or this platform has no such+ * controller at all), `null` the question could not be answered - see+ * {@link probeCpuQuota} for the three ways that happens.+ */+ readonly cpuQuotaInForce: boolean | null;+}++export interface HostPressureMeasured {+ readonly state: typeof HOST_PRESSURE.measured;+ /** Run queue as a percentage of usable capacity; 100 means fully subscribed. */+ readonly percent: number;+ readonly load_average_1m: number;+ readonly cpu_count: number;+}++export interface HostPressureUnmeasurable {+ readonly state: typeof HOST_PRESSURE.unmeasurable;+ readonly reason: HostPressureUnmeasurableReason;+}++export type HostPressureReading = HostPressureMeasured | HostPressureUnmeasurable;++function unmeasurable(reason: HostPressureUnmeasurableReason): HostPressureUnmeasurable {+ return { state: HOST_PRESSURE.unmeasurable, reason };+}++/**+ * Where the quota probe reads from.+ *+ * Two absolute paths and a platform, injected rather than hardcoded, so+ * the walk below can be driven over a real directory tree with real+ * permissions - including a `cpu.max` that exists and refuses to be read,+ * which is the case this module got wrong and which no amount of+ * arithmetic-level testing could have reached.+ */+export interface CgroupSource {+ /** `process.platform`. */+ readonly platform: string;+ /** File naming the cgroups this process belongs to; `/proc/self/cgroup`. */+ readonly selfCgroupPath: string;+ /** Mount root of the cgroup hierarchy; `/sys/fs/cgroup`. */+ readonly cgroupRoot: string;+}++/** What one read of a cgroup interface file found. */+type InterfaceRead =+ | { readonly kind: "text"; readonly text: string }+ /** No such file. Says nothing about any other cgroup in the chain. */+ | { readonly kind: "absent" }+ /** The file is there and this process may not read it. */+ | { readonly kind: "unreadable"; readonly detail: string };++/**+ * Read one file, keeping ABSENT and UNREADABLE apart.+ *+ * They used to be one `null`, under a comment claiming the caller told+ * them apart - which it did not, so an `EACCES` on an existing `cpu.max`+ * (a restricted `/sys` mount, a hardened runtime) was reported as "no+ * quota in force". They are two different facts here because the walk+ * below does two different things with them: an absent interface means+ * keep looking up the chain, an unreadable one means stop and say so.+ */+function readInterface(path: string): InterfaceRead {+ try {+ return { kind: "text", text: readFileSync(path, "utf8") };+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR") return { kind: "absent" };+ return { kind: "unreadable", detail: err instanceof Error ? err.message : String(err) };+ }+}++/** Which cgroups this process is in, as `/proc/self/cgroup` reports them. */+interface CgroupMembership {+ /** The unified (v2) path, e.g. `/user.slice/session-9.scope`, or `null`. */+ readonly v2Path: string | null;+ /** The v1 `cpu` controller's mount name and path, or `null`. */+ readonly v1: { readonly controllers: string; readonly path: string } | null;+}++/**+ * Parse `/proc/self/cgroup`.+ *+ * Every line is `<hierarchy-id>:<controllers>:<path>`. The unified+ * hierarchy is the line with id `0` and an empty controller list; a v1+ * hierarchy is any line whose comma-separated controller list contains+ * `cpu`. A hybrid host has both, and the v2 line is preferred because a+ * quota expressed there is the one the kernel enforces.+ */+function parseSelfCgroup(text: string): CgroupMembership {+ let v2Path: string | null = null;+ let v1: CgroupMembership["v1"] = null;+ for (const raw of text.split("\n")) {+ const line = raw.trim();+ if (line === "") continue;+ const first = line.indexOf(":");+ const second = line.indexOf(":", first + 1);+ if (first < 0 || second < 0) continue;+ const id = line.slice(0, first);+ const controllers = line.slice(first + 1, second);+ const path = line.slice(second + 1);+ if (id === "0" && controllers === "") {+ v2Path = path;+ continue;+ }+ if (controllers.split(",").includes(CGROUP_V1_CPU_CONTROLLER)) v1 = { controllers, path };+ }+ return { v2Path, v1 };+}++/**+ * Every cgroup directory from the named one up to the mount root.+ *+ * The effective bandwidth limit is the MINIMUM over the whole ancestor+ * chain, so a quota on `user.slice` binds a process in+ * `user.slice/session-9.scope` exactly as one on the leaf does. Reading a+ * single directory would answer for one link of that chain.+ */+function ancestorDirs(root: string, path: string): string[] {+ const parts = path.split("/").filter((p) => p !== "");+ const dirs: string[] = [];+ for (let i = parts.length; i >= 0; i--) dirs.push(join(root, ...parts.slice(0, i)));+ return dirs;+}++/** How one interface file's contents answered, or that it did not. */+type QuotaVerdict = "in_force" | "unlimited" | "unparseable";++/** `"<quota|max> <period>"`. */+function parseV2Quota(text: string): QuotaVerdict {+ const token = text.split("\n", 1)[0]?.trim().split(/\s+/)[0];+ if (token === undefined || token === "") return "unparseable";+ return token === CGROUP_V2_UNLIMITED ? "unlimited" : "in_force";+}++/** Microseconds per period, or `-1` for "no limit". */+function parseV1Quota(text: string): QuotaVerdict {+ const first = text.split("\n", 1)[0]?.trim() ?? "";+ const quota = Number(first);+ if (first === "" || !Number.isFinite(quota)) return "unparseable";+ return quota > 0 ? "in_force" : "unlimited";+}++/**+ * What one hierarchy had to say.+ *+ * `unknown` and `no_interface` are separate members for the reason this+ * whole module exists: a file that refused to be read and a controller+ * that is not enabled are different facts, and collapsing them is what+ * turned an `EACCES` into "no quota in force".+ */+type ChainAnswer = "in_force" | "unlimited" | "unknown" | "no_interface";++/**+ * Walk one chain of cgroup directories, leaf first, looking for a+ * bandwidth limit. An absent interface on one link says nothing about the+ * next, so the walk continues; an unreadable or unparseable one stops it.+ */+function walkChain(+ dirs: ReadonlyArray<string>,+ file: string,+ parse: (text: string) => QuotaVerdict,+): ChainAnswer {+ let sawInterface = false;+ for (const dir of dirs) {+ const read = readInterface(join(dir, file));+ if (read.kind === "absent") continue;+ if (read.kind === "unreadable") return "unknown";+ sawInterface = true;+ const verdict = parse(read.text);+ if (verdict === "in_force") return "in_force";+ if (verdict === "unparseable") return "unknown";+ }+ return sawInterface ? "unlimited" : "no_interface";+}++/** The three answers a walked chain maps onto, or `undefined` to keep looking. */+function fromChain(answer: ChainAnswer): boolean | null | undefined {+ if (answer === "in_force") return true;+ if (answer === "unlimited") return false;+ if (answer === "unknown") return null;+ return undefined;+}++/**+ * Whether a CPU bandwidth quota applies to this process.+ *+ * `true` a limit is in force, `false` there is provably none, `null` the+ * question could not be answered - and that third value is not a+ * formality. This used to read `/sys/fs/cgroup/cpu.max` and nothing else.+ * Under cgroup v2 the ROOT cgroup carries no `cpu.max`: the file exists on+ * every child and never on the root, so the read missed on every v2 host,+ * fell through to a v1 path that does not exist there either, and returned+ * `false` - "no bandwidth controller" - about a process that might be+ * inside a `CPUQuota=50%` unit. `measureHostPressure` then divided the+ * HOST's run queue by a CPU count the process may not have, which is the+ * confident-number-over-a-degenerate-metric this module opens by+ * forbidding.+ *+ * So the cgroup this process is actually in is read from+ * `/proc/self/cgroup` first, and the interface is looked up on it and on+ * every ancestor, because the effective limit is the minimum over the+ * chain.+ *+ * The three refusals, each its own answer rather than a shrug:+ *+ * - `/proc/self/cgroup` unreadable, or naming no hierarchy this build+ * understands: which cgroup governs this process is unknown, so+ * nothing may be claimed about its quota.+ * - an interface file that exists and refuses to be read, or whose+ * contents do not parse.+ * - on Linux, a chain on which no interface file exists at all: the+ * cpu controller is not enabled here, and no bandwidth limit can be+ * applied through a controller that is not there - `false`.+ *+ * A platform with no cgroups at all (macOS) is `false` for the same+ * reason and not `null`: the question is answerable there and the answer+ * is that there is no such controller.+ */+export function probeCpuQuota(src: CgroupSource = liveCgroupSource()): boolean | null {+ if (src.platform !== CGROUP_PLATFORM) return false;++ const self = readInterface(src.selfCgroupPath);+ if (self.kind !== "text") return null;+ const membership = parseSelfCgroup(self.text);++ if (membership.v2Path !== null) {+ const answer = fromChain(+ walkChain(ancestorDirs(src.cgroupRoot, membership.v2Path), CGROUP_V2_CPU_MAX, parseV2Quota),+ );+ // Answered - including "unknown" - it is the answer. Only+ // `no_interface` falls through, and only to a v1 hierarchy this+ // process was also told it belongs to (the hybrid layout).+ if (answer !== undefined) return answer;+ if (membership.v1 === null) return false;+ }++ if (membership.v1 === null) return null;+ // The v1 cpu controller is mounted under its controller list+ // (`cpu,cpuacct` on most hosts) or under the bare controller name.+ const mounts = [membership.v1.controllers, CGROUP_V1_CPU_CONTROLLER].filter(+ (m, i, all) => all.indexOf(m) === i,+ );+ for (const mount of mounts) {+ const answer = fromChain(+ walkChain(+ ancestorDirs(join(src.cgroupRoot, mount), membership.v1.path),+ CGROUP_V1_CPU_QUOTA,+ parseV1Quota,+ ),+ );+ if (answer !== undefined) return answer;+ }+ // Named a cpu hierarchy and found no interface under either mount: the+ // controller is not enabled where this build can see it.+ return false;+}++/** The live paths, read at call time so a test never has to patch a module. */+export function liveCgroupSource(): CgroupSource {+ return {+ platform: platform(),+ selfCgroupPath: "/proc/self/cgroup",+ cgroupRoot: "/sys/fs/cgroup",+ };+}++/**+ * Everything {@link readHostPressureProbe} reads, in one injectable+ * record.+ *+ * The three runtime readings are functions rather than values because+ * two of them are syscalls that a runtime may not implement, and this+ * module's whole argument is that an unavailable reading must arrive as a+ * named refusal rather than as a plausible number or a thrown error.+ */+export interface HostPressureIo extends CgroupSource {+ /** `os.loadavg()`. */+ readonly loadAverage: () => ReadonlyArray<number>;+ /** `os.availableParallelism()`. */+ readonly cpuCount: () => number;+}++export const LIVE_HOST_PRESSURE_IO: HostPressureIo = Object.freeze({+ ...liveCgroupSource(),+ platform: platform(),+ loadAverage: () => loadavg(),+ cpuCount: () => availableParallelism(),+});++/**+ * Gather the live facts.+ *+ * `platform` is a property read that cannot fail. The other two are+ * syscall-backed (`uv_loadavg`, `uv_available_parallelism`) and a runtime+ * that does not implement one throws rather than returning a wrong+ * number - so each is caught and turned into the value+ * {@link measureHostPressure} already names: `NaN` is+ * `load_average_invalid`, a non-count is `parallelism_unknown`. That is+ * why this function does not throw: not because the reads cannot fail,+ * but because a failure has somewhere honest to go.+ */+export function readHostPressureProbe(+ io: HostPressureIo = LIVE_HOST_PRESSURE_IO,+): HostPressureProbe {+ let loadAverage1m: number;+ try {+ loadAverage1m = io.loadAverage()[0] ?? Number.NaN;+ } catch {+ loadAverage1m = Number.NaN;+ }+ let cpuCount: number;+ try {+ cpuCount = io.cpuCount();+ } catch {+ cpuCount = Number.NaN;+ }+ return {+ platform: io.platform,+ loadAverage1m,+ cpuCount,+ cpuQuotaInForce: probeCpuQuota(io),+ };+}++/**+ * Turn a probe into a reading: a normalised percentage, or the named+ * reason there is no number. The refusals are checked before the+ * arithmetic, because every one of them would otherwise produce a+ * plausible number from an implausible input.+ */+export function measureHostPressure(+ probe: HostPressureProbe = readHostPressureProbe(),+): HostPressureReading {+ if (LOAD_AVERAGE_BLIND_PLATFORMS.includes(probe.platform)) {+ return unmeasurable(HOST_PRESSURE_UNMEASURABLE_REASON.platformBlind);+ }+ if (probe.cpuQuotaInForce === null) {+ return unmeasurable(HOST_PRESSURE_UNMEASURABLE_REASON.cpuQuotaUnknown);+ }+ if (probe.cpuQuotaInForce) {+ return unmeasurable(HOST_PRESSURE_UNMEASURABLE_REASON.cpuQuotaInForce);+ }+ if (!Number.isInteger(probe.cpuCount) || probe.cpuCount < 1) {+ return unmeasurable(HOST_PRESSURE_UNMEASURABLE_REASON.parallelismUnknown);+ }+ if (!Number.isFinite(probe.loadAverage1m) || probe.loadAverage1m < 0) {+ return unmeasurable(HOST_PRESSURE_UNMEASURABLE_REASON.loadAverageInvalid);+ }+ return {+ state: HOST_PRESSURE.measured,+ percent: (probe.loadAverage1m / probe.cpuCount) * 100,+ load_average_1m: probe.loadAverage1m,+ cpu_count: probe.cpuCount,+ };+}diff --git a/src/core/brain/maintenance/journal.ts b/src/core/brain/maintenance/journal.tsindex 22210fa4..27158a5d 100644--- a/src/core/brain/maintenance/journal.ts+++ b/src/core/brain/maintenance/journal.ts@@ -11,20 +11,64 @@ import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } fimport { mkdirSync } from "node:fs";import { dirname, join } from "node:path";import { assertVaultIdentityForWrite } from "../vault-identity.ts";+import type { HostPressureUnmeasurableReason } from "./host-pressure.ts";export const MAINTENANCE_JOURNAL_CAP = 500;-export type MaintenanceVerdict = "run" | "skipped:window" | "skipped:busy" | "skipped:lease";+/**+ * What one journal row records.+ *+ * A closed vocabulary rather than a bare union because these values are+ * persisted to `.open-second-brain/maintenance-runs.jsonl` and read back+ * by whichever build runs next - across an upgrade, that is not the build+ * that wrote them. The guard is the boundary for a row this build does+ * not understand.+ *+ * Two of the members are not decisions about whether to run:+ * `pressure:unmeasurable` is a NOTICE that a gate could not evaluate, and+ * it is emitted on its own line beside the decision, never instead of it.+ * `refused:streak` is a per-task refusal, so it appears among the task+ * rows rather than in place of them.+ */+export const MAINTENANCE_VERDICT = Object.freeze({+ /** The gates were open; the row's task ran (or the lane ran). */+ run: "run",+ skippedWindow: "skipped:window",+ skippedBusy: "skipped:busy",+ /** Host pressure was measured and stood at or above the configured percentage. */+ skippedPressure: "skipped:pressure",+ skippedLease: "skipped:lease",+ /** This task has failed too many times in a row to retry unforced. */+ refusedStreak: "refused:streak",+ /** The host-pressure gate could not evaluate; it was left open. */+ pressureUnmeasurable: "pressure:unmeasurable",+});++export const MAINTENANCE_VERDICTS: ReadonlyArray<string> = Object.freeze(+ Object.values(MAINTENANCE_VERDICT),+);++export type MaintenanceVerdict = (typeof MAINTENANCE_VERDICT)[keyof typeof MAINTENANCE_VERDICT];++export function isMaintenanceVerdict(value: unknown): value is MaintenanceVerdict {+ return typeof value === "string" && MAINTENANCE_VERDICTS.includes(value);+}export interface MaintenanceJournalEntry {readonly ts: string;readonly holder: string;readonly verdict: MaintenanceVerdict;- /** Present on per-task rows; absent on gate-refusal rows. */+ /** Present on per-task rows; absent on lane-level gate-refusal rows. */readonly task?: string;readonly ok?: boolean;readonly duration_ms?: number;readonly error?: string;+ /** Host pressure the gate read, on a `skipped:pressure` row. */+ readonly pressure_percent?: number;+ /** Why the gate could not read one, on a `pressure:unmeasurable` row. */+ readonly pressure_reason?: HostPressureUnmeasurableReason;+ /** Consecutive journaled failures behind a `refused:streak` row. */+ readonly streak?: number;}function journalPath(vault: string): string {@@ -75,6 +119,65 @@ export function listJournal(vault: string, limit?: number): MaintenanceJournalEnreturn limit !== undefined ? out.slice(0, Math.max(0, limit)) : out;}+/**+ * How many times in a row `task` has failed since its newest success.+ *+ * The count is the portable stand-in for a crash-loop counter: nothing in+ * this project survives an invocation except what is on disk, and the+ * journal already records every attempt with its outcome. Two properties+ * make it usable as a refusal input:+ *+ * - a single success ENDS the count, because the walk stops at the+ * newest row that is not a failure - a transient fault therefore+ * cannot accumulate into a permanent refusal;+ * - only rows that record a completed ATTEMPT are counted. A gate+ * refusal and a lease skip are not attempts, so they cannot deepen a+ * streak.+ *+ * A row that ran but recorded no outcome stops the walk as well: refusing+ * work on evidence this build cannot read is the wrong direction to err.+ *+ * ## Why a `refused:streak` row ends the walk by ADDING its own count+ *+ * This journal is a ring buffer ({@link MAINTENANCE_JOURNAL_CAP}), and a+ * lane that writes several rows per pass retires roughly a hundred passes'+ * history. Counted naively, a refused task's three `run/ok:false` rows are+ * pushed off the tail by the very refusal rows they cause, and the count+ * silently returns to zero - the refusal un-refusing itself on a schedule+ * set by how chatty the journal is, with no event anywhere.+ *+ * So the refusal row is read as what it is: the journal's own durable+ * record of the count that was reached. The walk stops there and returns+ * the failures NEWER than it plus the number it recorded, which is the+ * same total those rolled-off rows would have produced. It cannot inflate+ * a streak - a refusal reproduces the number it was given, never one more+ * - and it cannot outlive a recovery, because a success is newer than+ * every refusal it follows and stops the walk first.+ *+ * Residual, stated rather than hidden: below the limit no refusal row+ * exists, so a streak whose rows roll off is counted only from what is+ * retained. That undercount errs toward RUNNING the task, which is the+ * direction this function already errs in for an unreadable outcome.+ */+export function consecutiveTaskFailures(vault: string, task: string): number {+ let streak = 0;+ for (const entry of listJournal(vault)) {+ if (entry.task !== task) continue;+ if (entry.verdict === MAINTENANCE_VERDICT.refusedStreak) {+ // A row from a build that did not record the number carries no+ // evidence, so it is skipped rather than read as a zero.+ if (Number.isInteger(entry.streak) && (entry.streak ?? 0) >= 0) {+ return streak + (entry.streak ?? 0);+ }+ continue;+ }+ if (entry.verdict !== MAINTENANCE_VERDICT.run) continue;+ if (entry.ok !== false) break;+ streak += 1;+ }+ return streak;+}+function readLines(path: string): string[] {if (!existsSync(path)) return [];return readFileSync(path, "utf8")diff --git a/src/core/brain/maintenance/lane.ts b/src/core/brain/maintenance/lane.tsindex bc667fef..a3bcd560 100644--- a/src/core/brain/maintenance/lane.ts+++ b/src/core/brain/maintenance/lane.ts@@ -1,27 +1,71 @@/*** Quiet-window maintenance lane (write-time-integrity-governance,- * t_166d1226). Heavy passes (dream, reindex) run through three gates:+ * t_166d1226; host pressure and the failure streak, t_992f0c33). Heavy+ * passes (dream, reindex) run through four gates:*- * 1. window - a configured local-time hour window (tz-aware,- * midnight wrap supported); unconfigured = always open.- * 2. busy - recent interactive query-rate from the existing- * recall-telemetry continuity records; a vault without- * telemetry counts as quiet.- * 3. lease - the expiring SQLite lease; never bypassable, even- * with --force, because two concurrent heavy passes on- * one vault is the exact failure this lane exists to- * prevent.+ * 1. window - a configured local-time hour window (tz-aware,+ * midnight wrap supported); unconfigured = always open.+ * 2. busy - recent interactive query-rate from the existing+ * recall-telemetry continuity records; a vault without+ * telemetry counts as quiet.+ * 3. pressure - the host's normalised run queue, from+ * `maintenance.host_pressure_percent`; unconfigured =+ * always open. Where the metric is degenerate the gate+ * stays open and journals WHY, on its own line, so a+ * platform that cannot measure pressure never looks+ * like a quiet one.+ * 4. lease - the expiring SQLite lease; never bypassable, even+ * with --force, because two concurrent heavy passes on+ * one vault is the exact failure this lane exists to+ * prevent.*- * `--force` bypasses the soft gates (window, busy) for an operator- * who wants the pass NOW; tasks run stale-first (least-recently- * succeeded first, never-run before everything) and every attempt is- * journaled.+ * Then, per task, a consecutive-failure streak read off the journal:+ * a task that has failed `maintenance.failure_streak_limit` times in a+ * row is refused by name rather than retried, because nothing here+ * supervises a repeating failure and the lane's stale-first ordering+ * would otherwise hand a permanently broken task the lease first on+ * every pass.+ *+ * ## Two escapes, and why the narrow one exists+ *+ * A refusal is per task and the other tasks still run - but it stands+ * until something clears it, and only a SUCCESS clears it. So there has+ * to be a way to attempt the refused task again.+ *+ * `force` is the wide one: it bypasses the soft gates (window, busy,+ * pressure) and every streak refusal, for an operator who wants the pass+ * NOW. Making it the only way out was the defect: an operator whose+ * reindex is deterministically broken had to run the whole heavy lane+ * with their own window, busy and host-pressure protection switched off+ * in order to retry one task.+ *+ * {@link RunMaintenanceOptions.retryTasks} is the narrow one: it bypasses+ * the streak refusal for the tasks it NAMES and nothing else. Every gate+ * the operator configured still decides, the lease still decides, and a+ * task it does not name is still refused. It clears no state and writes+ * no row of its own: the attempt's own outcome row is what ends the+ * streak if it succeeds, and what deepens it if it does not, so a retry+ * that keeps failing costs one lane slot per invocation the operator+ * chose to make - not a standing exemption.+ *+ * Tasks run stale-first (least-recently succeeded first, never-run+ * before everything) and every attempt is journaled.*/import { listRecallTelemetry } from "../recall-telemetry.ts";import { capOutput, SafeguardTimeoutError } from "../safeguard.ts";+import { loadMaintenanceConfigSafe } from "../policy/load.ts";import { acquireLease, MAINTENANCE_LEASE_NAME, releaseLease } from "./lease.ts";-import { appendJournal, listJournal, sweepJournal, type MaintenanceVerdict } from "./journal.ts";+import {+ appendJournal,+ consecutiveTaskFailures,+ listJournal,+ MAINTENANCE_VERDICT,+ sweepJournal,+ type MaintenanceJournalEntry,+ type MaintenanceVerdict,+} from "./journal.ts";+import { HOST_PRESSURE, measureHostPressure, type HostPressureReading } from "./host-pressure.ts";/** Default lease TTL: generous enough for a full reindex + dream. */export const MAINTENANCE_LEASE_TTL_MS = 30 * 60 * 1000;@@ -43,11 +87,40 @@ export interface BusyGate {readonly threshold: number;}+export interface HostPressureGate {+ /** Skip when the normalised run queue is at or above this percentage. */+ readonly percent: number;+}+export interface EvaluateGatesOptions {readonly now: Date;/** Absent = the window gate is always open (neutral default). */readonly window?: DailyWindow;readonly busy?: BusyGate;+ /**+ * Absent = the host-pressure gate is not configured and never fires.+ * {@link runMaintenance} fills it from the vault's `maintenance:`+ * block when the caller does not name one.+ */+ readonly pressure?: HostPressureGate;+ /** Injectable measurement; defaults to reading this host. */+ readonly readPressure?: () => HostPressureReading;+}++/**+ * What the soft gates decided, and what the pressure gate saw while+ * deciding it.+ *+ * The reading is returned alongside the verdict rather than folded into+ * it because "the host was too loaded" and "this host cannot say how+ * loaded it is" are different facts that the caller must journal on+ * different lines: one is a decision not to run, the other is a gate+ * that did not evaluate while the lane ran anyway.+ */+export interface MaintenanceGateDecision {+ readonly verdict: MaintenanceVerdict;+ /** Absent unless the host-pressure gate was reached and configured. */+ readonly pressure?: HostPressureReading;}/** Cap for persisted per-task error strings (journal + results). */@@ -61,8 +134,17 @@ export interface MaintenanceTask {export interface RunMaintenanceOptions extends EvaluateGatesOptions {readonly holder: string;readonly tasks: ReadonlyArray<MaintenanceTask>;- /** Bypass window and busy gates - never the lease. */+ /**+ * Bypass the window, busy and pressure gates and every streak refusal -+ * never the lease.+ */readonly force?: boolean;+ /**+ * Task names to attempt past their streak refusal, this run only. Every+ * gate still applies; a name that is not a registered task is the+ * caller's to reject, because only the caller knows what it registered.+ */+ readonly retryTasks?: ReadonlyArray<string>;readonly leaseTtlMs?: number;}@@ -73,6 +155,10 @@ export interface MaintenanceTaskResult {readonly error?: string;/** True when the task tripped its cooperative safeguard deadline. */readonly timed_out?: boolean;+ /** True when the failure streak refused the task instead of running it. */+ readonly refused?: true;+ /** Consecutive journaled failures behind a refusal. */+ readonly failure_streak?: number;}export interface RunMaintenanceResult {@@ -97,10 +183,18 @@ export function dailyWindowContains(now: Date, window: DailyWindow): boolean {return hour >= window.startHour || hour < window.endHour;}-/** Evaluate the soft gates; the lease is checked at run time. */-export function evaluateGates(vault: string, opts: EvaluateGatesOptions): MaintenanceVerdict {+/**+ * Evaluate the soft gates; the lease is checked at run time.+ *+ * The gates are ordered cheapest-first and, more importantly,+ * least-surprising-first: window and busy decide exactly as they did+ * before this gate existed, and the host is only probed once both have+ * let the pass through. A closed earlier gate therefore leaves no+ * pressure reading, which is honest — nothing was measured.+ */+export function evaluateGates(vault: string, opts: EvaluateGatesOptions): MaintenanceGateDecision {if (opts.window !== undefined && !dailyWindowContains(opts.now, opts.window)) {- return "skipped:window";+ return { verdict: MAINTENANCE_VERDICT.skippedWindow };}const busy = opts.busy ?? {minutes: MAINTENANCE_BUSY_MINUTES,@@ -108,8 +202,19 @@ export function evaluateGates(vault: string, opts: EvaluateGatesOptions): Mainte};const since = new Date(opts.now.getTime() - busy.minutes * 60_000).toISOString();const recent = listRecallTelemetry(vault, { since });- if (recent.length >= busy.threshold) return "skipped:busy";- return "run";+ if (recent.length >= busy.threshold) return { verdict: MAINTENANCE_VERDICT.skippedBusy };++ if (opts.pressure === undefined) return { verdict: MAINTENANCE_VERDICT.run };+ const pressure = (opts.readPressure ?? measureHostPressure)();+ // Unmeasurable leaves the gate OPEN. Closing it would stop this vault+ // being maintained at all wherever the metric is degenerate, and+ // treating the degenerate reading as a number would report a loaded+ // host as an idle one - which is the failure the reading exists to+ // make impossible. The caller journals the reason.+ if (pressure.state === HOST_PRESSURE.measured && pressure.percent >= opts.pressure.percent) {+ return { verdict: MAINTENANCE_VERDICT.skippedPressure, pressure };+ }+ return { verdict: MAINTENANCE_VERDICT.run, pressure };}/**@@ -123,24 +228,69 @@ export async function runMaintenance(opts: RunMaintenanceOptions,): Promise<RunMaintenanceResult> {const nowIso = opts.now.toISOString();+ // Vault-side policy: the pressure threshold the caller did not name,+ // and the streak limit. An unreadable `_brain.yaml` raises here rather+ // than resolving to defaults - both knobs decide whether heavy work+ // starts, so a silent revert would run a pass the operator had gated.+ const policy = loadMaintenanceConfigSafe(vault);if (opts.force !== true) {- const verdict = evaluateGates(vault, opts);- if (verdict !== "run") {- appendJournal(vault, { ts: nowIso, holder: opts.holder, verdict });- return { verdict, tasks: [] };+ const gate: EvaluateGatesOptions = {+ now: opts.now,+ ...(opts.window !== undefined ? { window: opts.window } : {}),+ ...(opts.busy !== undefined ? { busy: opts.busy } : {}),+ ...(opts.readPressure !== undefined ? { readPressure: opts.readPressure } : {}),+ ...resolvePressureGate(opts.pressure, policy.host_pressure_percent),+ };+ const decision = evaluateGates(vault, gate);+ // Two lines, never one: a gate that could not evaluate is its own+ // row, so the journal never leaves an operator to infer from a+ // running lane that the pressure gate was open because the host was+ // quiet.+ if (decision.pressure?.state === HOST_PRESSURE.unmeasurable) {+ appendJournal(vault, {+ ts: nowIso,+ holder: opts.holder,+ verdict: MAINTENANCE_VERDICT.pressureUnmeasurable,+ pressure_reason: decision.pressure.reason,+ });+ }+ if (decision.verdict !== MAINTENANCE_VERDICT.run) {+ appendJournal(vault, {+ ts: nowIso,+ holder: opts.holder,+ verdict: decision.verdict,+ ...(decision.pressure?.state === HOST_PRESSURE.measured+ ? { pressure_percent: decision.pressure.percent }+ : {}),+ });+ return { verdict: decision.verdict, tasks: [] };}}const ttl = opts.leaseTtlMs ?? MAINTENANCE_LEASE_TTL_MS;if (!acquireLease(vault, { holder: opts.holder, ttlMs: ttl, now: opts.now })) {- appendJournal(vault, { ts: nowIso, holder: opts.holder, verdict: "skipped:lease" });- return { verdict: "skipped:lease", tasks: [] };+ appendJournal(vault, {+ ts: nowIso,+ holder: opts.holder,+ verdict: MAINTENANCE_VERDICT.skippedLease,+ });+ return { verdict: MAINTENANCE_VERDICT.skippedLease, tasks: [] };}try {const ordered = orderStaleFirst(vault, opts.tasks);+ const retry = new Set(opts.retryTasks ?? []);const results: MaintenanceTaskResult[] = [];for (const task of ordered) {+ const refusal =+ opts.force === true || retry.has(task.name)+ ? undefined+ : refuseOnStreak(vault, task.name, policy.failure_streak_limit);+ if (refusal !== undefined) {+ results.push(refusal.result);+ appendJournal(vault, { ts: nowIso, holder: opts.holder, ...refusal.entry });+ continue;+ }const startedAt = Date.now();let ok = true;let error: string | undefined;@@ -170,7 +320,7 @@ export async function runMaintenance(appendJournal(vault, {ts: nowIso,holder: opts.holder,- verdict: "run",+ verdict: MAINTENANCE_VERDICT.run,task: task.name,ok,duration_ms: duration,@@ -180,12 +330,54 @@ export async function runMaintenance(// The cap rewrite happens only here, while the lease is held -// the one point where no other writer can race the journal.sweepJournal(vault);- return { verdict: "run", tasks: results };+ return { verdict: MAINTENANCE_VERDICT.run, tasks: results };} finally {releaseLease(vault, { holder: opts.holder, name: MAINTENANCE_LEASE_NAME });}}+/**+ * The pressure gate to evaluate: the caller's, else the vault's, else+ * none. There is deliberately no third source and no default number - an+ * unconfigured gate never fires.+ */+function resolvePressureGate(+ named: HostPressureGate | undefined,+ configured: number | null,+): { pressure?: HostPressureGate } {+ if (named !== undefined) return { pressure: named };+ if (configured !== null) return { pressure: { percent: configured } };+ return {};+}++/** The task-result and journal rows of a streak refusal, or `undefined` to run. */+function refuseOnStreak(+ vault: string,+ task: string,+ limit: number,+):+ | { result: MaintenanceTaskResult; entry: Omit<MaintenanceJournalEntry, "ts" | "holder"> }+ | undefined {+ const streak = consecutiveTaskFailures(vault, task);+ if (streak < limit) return undefined;+ // The number is in the message because the journal row and the task+ // result are read on different surfaces, and an operator who sees only+ // one of them still has to know how deep the hole is and how to climb+ // out of it.+ const error =+ `refused: ${streak} consecutive journaled failures reached the ` ++ `maintenance.failure_streak_limit of ${limit}; fix the cause, then re-run with ` ++ `--retry ${task} to attempt this task alone with every other gate still in force, ` ++ `or --force to run the whole lane past every soft gate`;+ return {+ result: { name: task, ok: false, duration_ms: 0, error, refused: true, failure_streak: streak },+ // No `ok` on the row: a refusal is not an attempt, and recording one+ // as a failed attempt would deepen the very streak it reports until+ // no success could ever clear it.+ entry: { verdict: MAINTENANCE_VERDICT.refusedStreak, task, streak, error },+ };+}+function orderStaleFirst(vault: string, tasks: ReadonlyArray<MaintenanceTask>): MaintenanceTask[] {const lastSuccess = new Map<string, string>();for (const entry of listJournal(vault)) {diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.tsindex 40689811..e11c491c 100644--- a/src/core/brain/policy.ts+++ b/src/core/brain/policy.ts@@ -56,6 +56,7 @@ export {loadFeedbackDefaultScopeSafe,loadGuardrailsConfigSafe,loadIntegrityConfigSafe,+ loadMaintenanceConfigSafe,loadNotesConfigSafe,loadSnapshotDerivedStorePolicySafe,loadSnapshotRetentionSafe,@@ -98,6 +99,15 @@ export {LESSONS_LIMIT_MAX,LESSONS_LIMIT_MIN,} from "./policy/blocks/lessons.ts";+export {+ BRAIN_MAINTENANCE_DEFAULTS,+ MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT,+ MAINTENANCE_FAILURE_STREAK_LIMIT_MAX,+ MAINTENANCE_FAILURE_STREAK_LIMIT_MIN,+ MAINTENANCE_HOST_PRESSURE_PERCENT_MAX,+ MAINTENANCE_HOST_PRESSURE_PERCENT_MIN,+ resolveMaintenance,+} from "./policy/blocks/maintenance.ts";export {BRAIN_GUARDRAIL_DEFAULTS,INSTRUCTION_FILE_MAX_LINES_CEILING,@@ -114,3 +124,4 @@ export { BRAIN_TEMPORAL_DEFAULTS, resolveTemporal } from "./policy/blocks/temporexport { 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";+export { resolveEmbeddingSunsetDeclaration } from "./policy/blocks/embeddings.ts";diff --git a/src/core/brain/policy/blocks/embeddings.ts b/src/core/brain/policy/blocks/embeddings.tsnew file mode 100644index 00000000..d0c0fb96--- /dev/null+++ b/src/core/brain/policy/blocks/embeddings.ts@@ -0,0 +1,127 @@+/**+ * The `embeddings:` block — an operator's own record of a decommission+ * announcement they have read.+ *+ * One reason to change: what this vault knows about its embedding model's+ * lifecycle that this build's shipped survey does not.+ *+ * ## Why the block exists at all+ *+ * The sunset survey is a static table compiled into the binary. Its+ * unfixable weakness is that it goes stale between releases: a vendor+ * announces a shutdown, or moves one, and the table cannot learn until+ * somebody ships. This block is the layer that does not depend on the+ * build being current — an operator who has just read the announcement+ * records it here, and the check reports it immediately.+ *+ * It is deliberately an ADDITIONAL layer rather than the only source. A+ * declaration on its own cannot distinguish "the operator declared+ * nothing" from "no shutdown exists", and collapsing those two is the+ * exact defect the sunset check was built to remove. The survey keeps+ * answering `unsurveyed` / `none_announced` / `undetermined` on its own+ * terms; this block only ever adds a positive.+ *+ * ## Why two scalars rather than a model-to-date map+ *+ * `_brain.yaml` is read by a hand-rolled two-level indent parser, and the+ * validator's key index is built BY CONSTRUCTION from the keys each block+ * checks for — so a block with arbitrary model-shaped sub-keys would+ * report every one of them as an unknown key on every load. Two declared+ * scalars fit the grammar and the index exactly, and an operator has one+ * configured model at a time.+ *+ * ## Why the model is named rather than implied+ *+ * `sunset_model` could have been left out, with the date taken to mean+ * "whatever `embedding_model` currently is". That would silently+ * re-target the declaration the next time the operator switched models,+ * asserting one vendor's shutdown date about a different vendor's model.+ * The pair is therefore both-or-neither: half a declaration is an+ * operator who meant something that did not take effect, which is a+ * refusal rather than a default.+ */++import type { BrainConfig, BrainEmbeddingsConfig } from "../../types.ts";+import { isValidIsoInstant } from "../../health/iso-time.ts";+import { BrainConfigError } from "../errors.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";+import type { EmbeddingSunsetDeclaration } from "../../../search/embeddings/sunset.ts";++const BLOCK = "embeddings";++const MODEL_KEY = "sunset_model";+const DATE_KEY = "sunset_at";++/**+ * The declaration this vault carries, or `null` when it carries none.+ *+ * `null` here means "the operator declared nothing", which the sunset+ * classifier treats as "consult the survey" — never as "no shutdown+ * exists". That distinction is the whole reason this is a layer over the+ * survey rather than a replacement for it.+ */+export function resolveEmbeddingSunsetDeclaration(+ cfg: BrainConfig | undefined,+): EmbeddingSunsetDeclaration | null {+ const block = cfg?.embeddings;+ if (block === undefined) return null;+ const model = block.sunset_model;+ const sunsetAt = block.sunset_at;+ // Both-or-neither is enforced at parse time; this is the read-side+ // consequence of that rule rather than a second, laxer one.+ if (model === undefined || sunsetAt === undefined) return null;+ return { model, sunsetAt };+}++/**+ * Shape:+ * embeddings:+ * sunset_model: "text-embedding-3-small" # exact model string+ * sunset_at: "2027-03-01" # ISO date/timestamp+ */+export function parseEmbeddingsBlock(ctx: BlockParseContext): BrainEmbeddingsConfig | undefined {+ const obj = openBlock(ctx, BLOCK);+ if (obj === undefined) return undefined;++ const partial: Record<string, unknown> = {};+ if (MODEL_KEY in obj) {+ const v = obj[MODEL_KEY];+ if (typeof v !== "string" || v.trim() === "") {+ throw new BrainConfigError(+ "must be a non-empty model string, matched exactly against the configured embedding_model",+ `${BLOCK}.${MODEL_KEY}`,+ ctx.source,+ );+ }+ partial[MODEL_KEY] = v;+ }+ if (DATE_KEY in obj) {+ const v = obj[DATE_KEY];+ if (typeof v !== "string" || !isValidIsoInstant(v)) {+ throw new BrainConfigError(+ "must be an ISO-8601 date (YYYY-MM-DD) or timestamp",+ `${BLOCK}.${DATE_KEY}`,+ ctx.source,+ );+ }+ partial[DATE_KEY] = v;+ }+ // Half a declaration is refused rather than ignored. A date with no+ // model would have to mean "whatever is configured", which re-targets+ // itself on the next model change; a model with no date declares+ // nothing at all. Either way the operator wrote something that would+ // not take effect, and silently dropping it is how a setting an+ // operator believes is in force turns out not to be.+ const declaredModel = MODEL_KEY in partial;+ const declaredDate = DATE_KEY in partial;+ if (declaredModel !== declaredDate) {+ throw new BrainConfigError(+ `${MODEL_KEY} and ${DATE_KEY} are declared together or not at all; found only ` ++ `${declaredModel ? MODEL_KEY : DATE_KEY}`,+ BLOCK,+ ctx.source,+ );+ }+ warnUnknownKeys(ctx, obj, [MODEL_KEY, DATE_KEY], BLOCK);+ return partial as BrainEmbeddingsConfig;+}diff --git a/src/core/brain/policy/blocks/maintenance.ts b/src/core/brain/policy/blocks/maintenance.tsnew file mode 100644index 00000000..1e4cfb3d--- /dev/null+++ b/src/core/brain/policy/blocks/maintenance.ts@@ -0,0 +1,129 @@+/**+ * The `maintenance:` block (t_992f0c33) — the two knobs of the+ * quiet-window lane that are policy rather than invocation.+ *+ * One reason to change: what stops the lane from starting heavy work.+ * The window and the busy threshold stay CLI flags because they belong+ * to the schedule that invokes the lane; these two belong to the vault,+ * because both answer a question the invoking cron line cannot: how much+ * of this machine the operator is willing to let a background pass take,+ * and how many times a task may fail before re-running it is no longer a+ * retry but a loop.+ *+ * Out-of-range values are hard errors. Every reader here follows the+ * policy stated in `../field-checks.ts`: a knob that silently clamped+ * would be indistinguishable from the operator never having set it, and+ * for a gate that is the worst possible failure - the operator would+ * believe a bound is in force that is not.+ */++import type {+ BrainConfig,+ BrainMaintenanceConfig,+ ResolvedBrainMaintenanceConfig,+} from "../../types.ts";+import { readBoundedInt } from "../field-checks.ts";+import { openBlock, warnUnknownKeys, type BlockParseContext } from "../key-index.ts";++const BLOCK = "maintenance";++/**+ * Floor of the host-pressure threshold, as a percentage of usable CPU+ * capacity. One rather than zero: at zero the gate would close on a+ * perfectly idle host too, which is not a pressure gate but a way to+ * disable the lane - and the way to disable the lane is to stop invoking+ * it, where the decision is visible.+ */+export const MAINTENANCE_HOST_PRESSURE_PERCENT_MIN = 1;++/**+ * Ceiling of the same threshold. Ten times subscribed is far past any+ * host an operator would still call usable, so a larger number is a typo+ * (a ratio written where a percentage belongs) rather than an intent.+ */+export const MAINTENANCE_HOST_PRESSURE_PERCENT_MAX = 1000;++/**+ * Consecutive journaled failures after which a task is refused without+ * `--force`.+ *+ * Three, and the two neighbouring values are why. At one, any transient+ * fault - a provider 503, a momentarily full disk, a lock lost to a+ * concurrent editor - becomes a standing refusal an operator has to+ * clear by hand; that converts a self-healing outage into a manual one.+ * Three does not abolish that property, it only raises the bar: an+ * outage spanning three scheduled runs reaches the limit too, and then+ * the task is refused until an operator retries it. What makes that+ * acceptable is the shape of the escape rather than the number - the+ * refusal is per task, the other tasks keep running, and `--retry+ * <task>` attempts the refused one without switching off the window,+ * busy and host-pressure gates the operator configured. At five or ten,+ * a deterministically broken task keeps+ * costing a full lane slot on every scheduled run for days, and because+ * the lane orders tasks stale-first a permanently failing task floats to+ * the FRONT of every pass - so it spends the lease before the healthy+ * tasks get it. Three attempts, each with its own fresh safeguard+ * deadline, is past the range a single transient fault spans and short of+ * that starvation; it is also the retry count this repository already+ * treats as "tried enough" in both of its lock ladders+ * (`src/core/reliability/lock.ts`, `src/core/search/store/writer-lock.ts`).+ */+export const MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT = 3;++/** One is the hair trigger: refuse after a single failure. Permitted, not advised. */+export const MAINTENANCE_FAILURE_STREAK_LIMIT_MIN = 1;++/** Past the journal's own useful depth, a larger limit stops meaning anything. */+export const MAINTENANCE_FAILURE_STREAK_LIMIT_MAX = 100;++const KNOWN_KEYS = ["host_pressure_percent", "failure_streak_limit"] as const;++/**+ * Defaults for an absent block. `host_pressure_percent` is `null` rather+ * than a number: the fourth gate has no neutral default, because any+ * number would start refusing work on vaults whose operator never asked+ * for the gate. Unset means the gate is not configured and never fires,+ * exactly as an unconfigured window is always open.+ */+export const BRAIN_MAINTENANCE_DEFAULTS: ResolvedBrainMaintenanceConfig = Object.freeze({+ host_pressure_percent: null,+ failure_streak_limit: MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT,+}) as ResolvedBrainMaintenanceConfig;++/** Merge a parsed `maintenance` block (or `undefined`) with the defaults. */+export function resolveMaintenance(cfg: BrainConfig): ResolvedBrainMaintenanceConfig {+ const m = cfg.maintenance;+ if (m === undefined) return BRAIN_MAINTENANCE_DEFAULTS;+ return {+ host_pressure_percent:+ m.host_pressure_percent ?? BRAIN_MAINTENANCE_DEFAULTS.host_pressure_percent,+ failure_streak_limit: m.failure_streak_limit ?? BRAIN_MAINTENANCE_DEFAULTS.failure_streak_limit,+ };+}++export function parseMaintenanceBlock(ctx: BlockParseContext): BrainMaintenanceConfig | undefined {+ const map = openBlock(ctx, BLOCK);+ if (map === undefined) return undefined;++ const hostPressurePercent = readBoundedInt(+ map,+ "host_pressure_percent",+ MAINTENANCE_HOST_PRESSURE_PERCENT_MIN,+ MAINTENANCE_HOST_PRESSURE_PERCENT_MAX,+ "maintenance.host_pressure_percent",+ ctx.source,+ );+ const failureStreakLimit = readBoundedInt(+ map,+ "failure_streak_limit",+ MAINTENANCE_FAILURE_STREAK_LIMIT_MIN,+ MAINTENANCE_FAILURE_STREAK_LIMIT_MAX,+ "maintenance.failure_streak_limit",+ ctx.source,+ );+ warnUnknownKeys(ctx, map, KNOWN_KEYS, BLOCK);+ return {+ ...(hostPressurePercent !== undefined ? { host_pressure_percent: hostPressurePercent } : {}),+ ...(failureStreakLimit !== undefined ? { failure_streak_limit: failureStreakLimit } : {}),+ };+}diff --git a/src/core/brain/policy/load.ts b/src/core/brain/policy/load.tsindex d4177f7b..86c08e5e 100644--- a/src/core/brain/policy/load.ts+++ b/src/core/brain/policy/load.ts@@ -30,6 +30,7 @@ import { BRAIN_MOST_APPLIED_DEFAULTS, resolveMostApplied } from "./blocks/activeimport { 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_MAINTENANCE_DEFAULTS, resolveMaintenance } from "./blocks/maintenance.ts";import {BRAIN_INTEGRITY_DEFAULTS,BRAIN_INTEGRITY_STRICT_FALLBACK,@@ -244,6 +245,22 @@ export const loadSnapshotDerivedStorePolicySafe = makeAbsentTolerantLoader<Brain}),);+/**+ * Load + resolve the `maintenance:` block, falling back to+ * `BRAIN_MAINTENANCE_DEFAULTS` when the config file is absent — which+ * leaves the host-pressure gate unconfigured, exactly as an operator who+ * has never run `o2b brain init` has never asked for it.+ *+ * An unreadable config raises, and that is the point: both knobs here+ * decide whether heavy work starts, so answering with the defaults would+ * run a pass the operator had gated and retry a task the operator's+ * limit had refused, on a vault that otherwise looks healthy.+ */+export const loadMaintenanceConfigSafe = makeAbsentTolerantLoader(+ resolveMaintenance,+ BRAIN_MAINTENANCE_DEFAULTS,+);+/*** Load + resolve `active.most_applied`, falling back to* `BRAIN_MOST_APPLIED_DEFAULTS` when the config file is absent, so a vaultdiff --git a/src/core/brain/policy/validate.ts b/src/core/brain/policy/validate.tsindex cb564585..854a0bd4 100644--- a/src/core/brain/policy/validate.ts+++ b/src/core/brain/policy/validate.ts@@ -26,11 +26,13 @@ import {import { parseVaultBlock } from "./blocks/vault-scope.ts";import { parseActiveBlock } from "./blocks/active.ts";import { parseLessonsBlock } from "./blocks/lessons.ts";+import { parseMaintenanceBlock } from "./blocks/maintenance.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 { parseEmbeddingsBlock } from "./blocks/embeddings.ts";import { parseHealthBlock } from "./blocks/health.ts";import { parseIntegrityBlock } from "./blocks/integrity.ts";import { parseNotesBlock } from "./blocks/notes.ts";@@ -101,12 +103,14 @@ export function validateBrainConfigDetailed(const vault = parseVaultBlock(ctx);const active = parseActiveBlock(ctx);const lessons = parseLessonsBlock(ctx);+ const maintenance = parseMaintenanceBlock(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 embeddings = parseEmbeddingsBlock(ctx);const integrity = parseIntegrityBlock(ctx);const notes = parseNotesBlock(ctx);const writeBinding = parseWriteBindingBlock(ctx);@@ -129,6 +133,7 @@ export function validateBrainConfigDetailed(...(vault !== undefined ? { vault } : {}),...(active !== undefined ? { active } : {}),...(lessons !== undefined ? { lessons } : {}),+ ...(maintenance !== undefined ? { maintenance } : {}),...(disciplineReport !== undefined ? { discipline_report: disciplineReport } : {}),...(rollup !== undefined ? { rollup } : {}),...(guardrails !== undefined ? { guardrails } : {}),@@ -138,6 +143,7 @@ export function validateBrainConfigDetailed(...(writeBinding !== undefined ? { write_binding: writeBinding } : {}),...(sessions !== undefined ? { sessions } : {}),...(health !== undefined ? { health } : {}),+ ...(embeddings !== undefined ? { embeddings } : {}),...(integrity !== undefined ? { integrity } : {}),...(schema !== undefined ? { schema } : {}),...(hygiene !== undefined ? { hygiene } : {}),diff --git a/src/core/brain/pre-compact-extract.ts b/src/core/brain/pre-compact-extract.tsindex 137fba8a..aed905af 100644--- a/src/core/brain/pre-compact-extract.ts+++ b/src/core/brain/pre-compact-extract.ts@@ -1,3 +1,36 @@+/**+ * Pre-compact continuity extraction: the labelled lines a host flushes+ * before a context window is compacted, captured as `pre_compact_extract`+ * continuity records without an LLM call.+ *+ * ## The recognizer is STRUCTURAL, and that is the whole point+ *+ * This used to carry a five-entry English word list (`decision:`,+ * `commitment:`, `outcome:`, `rule:`, `open question:`) - the only prose+ * recognizer left on any write path, and a direct contradiction of the+ * rule its sibling {@link ../brain/fact-extract.ts} states in its own+ * header: we cannot enumerate the world's languages, so a per-language+ * phrase list is a defect, not a feature. A session captured in Russian,+ * Japanese or Arabic extracted NOTHING, and the zero was indistinguishable+ * from "this session recorded no decisions".+ *+ * What is recognised now is the SHAPE of a labelled line - an opening+ * label, a colon, and a body - exactly as {@link ../graph/agent-scope.ts}+ * treats an owner token: an opaque, language-neutral identifier, never a+ * closed enum. The label itself becomes the record's `extract_type`,+ * normalized to one token. English input is byte-identical to before+ * (`Decision:` -> `decision`, `Open question:` -> `open_question`), so+ * nothing downstream that reads those five values changes; every other+ * script now scores on the same structure instead of scoring zero.+ *+ * Precision beats recall, the same trade the sibling extractor makes: the+ * label may only carry letters, digits, spaces, `-` and `_`, must contain+ * at least one letter (so `10:30` is a clock time, not a label), is capped+ * at {@link LABEL_MAX_WORDS} words and {@link LABEL_MAX_CHARS} characters+ * (so a prose sentence ending in a colon is not a label), and a line whose+ * colon belongs to a URI scheme or a Windows path is refused outright.+ */+import { createHash } from "node:crypto";import {@@ -11,13 +44,6 @@ import type {ContinuitySourceRef,} from "./continuity/types.ts";-export type PreCompactExtractType =- | "decision"- | "commitment"- | "outcome"- | "rule"- | "open_question";-export interface PreCompactExtractInput {readonly sessionId: string;readonly turnStart: string;@@ -52,21 +78,55 @@ export interface PreCompactExtractResult {}interface ExtractedLine {- readonly type: PreCompactExtractType;+ /** Normalized label token - open vocabulary, never a closed enum. */+ readonly type: string;readonly text: string;readonly line: number;}-const LABELS: ReadonlyArray<readonly [RegExp, PreCompactExtractType]> = Object.freeze([- [/^(?:[-*]\s*)?decision\s*:\s*(.+)$/i, "decision"],- [/^(?:[-*]\s*)?commitment\s*:\s*(.+)$/i, "commitment"],- [/^(?:[-*]\s*)?outcome\s*:\s*(.+)$/i, "outcome"],- [/^(?:[-*]\s*)?rule\s*:\s*(.+)$/i, "rule"],- [/^(?:[-*]\s*)?open\s+question\s*:\s*(.+)$/i, "open_question"],-]);+/**+ * A labelled line: an optional list bullet, a label built only from+ * letters, digits, spaces, `-` and `_`, a colon, and a non-empty body.+ * The label class is what makes this structural rather than lexical -+ * it names no word in any language, only the characters a label may use.+ */+const LABELLED_LINE_RE = /^(?:[-*]\s*)?([\p{L}\p{N} _-]+?)\s*:\s*(\S.*)$/u;++/**+ * Lines whose colon is punctuation inside a locator rather than a label+ * separator. A URI scheme (`https://`, `file:///`) and a Windows drive+ * path (`C:\...`) both parse as `label: body` by shape alone, so they are+ * refused BEFORE the shape test rather than patched afterwards.+ */+const LOCATOR_LINE_RE = /^(?:[-*]\s*)?[\p{L}][\p{L}\p{N}+.-]*:(?:\/\/|\\)/u;++/** A label longer than this is prose that happens to end in a colon. */+const LABEL_MAX_CHARS = 32;++/** Likewise: real labels are one to three words ("open question"). */+const LABEL_MAX_WORDS = 3;const DEFAULT_MAX_CHARS = 40_000;+/**+ * Reduce a raw label to the single token recorded as `extract_type`, or+ * `null` when the candidate is not a label at all.+ *+ * NFC + case-fold + collapse each internal whitespace run to `_`, which is+ * the same normalization {@link ../graph/agent-scope.ts} applies to an+ * owner token, plus the word joiner that keeps `Open question` and+ * `open_question` the same key. At least one letter is required so a clock+ * time (`10:30`) or a numbered list (`1: ...`) is never read as a label.+ */+export function normalizePreCompactLabel(raw: string): string | null {+ const trimmed = raw.normalize("NFC").trim();+ if (trimmed.length === 0 || trimmed.length > LABEL_MAX_CHARS) return null;+ if (!/\p{L}/u.test(trimmed)) return null;+ const words = trimmed.split(/\s+/u);+ if (words.length > LABEL_MAX_WORDS) return null;+ return words.join("_").toLowerCase();+}+export function extractPreCompactRecords(vault: string,input: PreCompactExtractInput,@@ -145,14 +205,13 @@ function extractLines(text: string): ExtractedLine[] {for (let index = 0; index < lines.length; index += 1) {const line = lines[index]!.trim();if (line.length === 0) continue;- for (const [pattern, type] of LABELS) {- const match = pattern.exec(line);- const value = match?.[1]?.trim();- if (value !== undefined && value.length > 0) {- items.push({ type, text: value, line: index + 1 });- break;- }- }+ if (LOCATOR_LINE_RE.test(line)) continue;+ const match = LABELLED_LINE_RE.exec(line);+ if (match === null) continue;+ const type = normalizePreCompactLabel(match[1]!);+ const body = match[2]!.trim();+ if (type === null || body.length === 0) continue;+ items.push({ type, text: body, line: index + 1 });}return items;}diff --git a/src/core/brain/progress.ts b/src/core/brain/progress.tsnew file mode 100644index 00000000..b2d07e35--- /dev/null+++ b/src/core/brain/progress.ts@@ -0,0 +1,386 @@+/**+ * The progress spine: what a long operation says while it is still+ * running (nothing-runs-unwatched, unit U1).+ *+ * Every operation this repository already calls long - the ones named by+ * {@link OPERATION} - accepts a `Safeguard` and calls `checkpoint()` at+ * its natural iteration boundaries. Those checkpoints are exactly the+ * boundaries a progress tick belongs at, and until this module none of+ * them emitted one: `o2b brain dream` printed its first character after+ * it had finished, and an agent driving a consolidation pass could not+ * tell a slow run from a hung one.+ *+ * The shape follows the house idiom rather than inventing one. A sink is+ * an OPTIONAL readonly field on the same options interface that already+ * carries `safeguard`, invoked with `?.`, exactly as `onFile`,+ * `onTelemetry`, `onOversize` and `validate` already are. Absence means+ * nobody asked - it is not a swallowed event.+ *+ * Three constraints the shape had to satisfy, all of them from the code+ * rather than from taste:+ *+ * - **The sink is synchronous.** `dream`, `discoverBridges`,+ * `detectCommunities` and `runDoctor` are synchronous functions; an+ * `async` sink could not be awaited inside them, and Bun runs SQLite+ * synchronously anyway. `(event) => void` matches `onFile` and+ * `Safeguard.checkpoint`.+ * - **`total` is optional and its absence means something.** The index+ * driver consumes a generator, so the file count is not known before+ * the walk; materialising it costs a second full traversal. The+ * embedding phase, by contrast, holds an array and knows its+ * denominator exactly. One event shape carries both, and a renderer+ * that sees no `total` must show a bare counter rather than invent a+ * percentage.+ * - **No prose.** `stage` is an identifier drawn from the emitting+ * operation's own phase vocabulary, never a sentence. The sentence is+ * rendered at the edge from the identifier, which is the same rule+ * that keeps caller-supplied prose off the advisory rail.+ * `progress-census.test.ts` enforces the identifier shape over every+ * emission site rather than leaving it to this comment.+ *+ * Core only emits. `tests/core/layering.test.ts` bans stdout writes here,+ * which is why the channel exists at all: the edge decides whether it can+ * carry an event, and one edge - the single-response HTTP MCP transport -+ * honestly cannot, which is what {@link PROGRESS_REASON.transportSingleResponse}+ * is for.+ */++import {+ OPERATION,+ SafeguardAbortError,+ SafeguardTimeoutError,+ type Operation,+} from "./safeguard.ts";++/** Envelope discriminator, so a reader can tell which shape it holds. */+export const PROGRESS_SCHEMA = "o2b.progress.v1";++/**+ * What one progress event says happened. `refused` and `stopped` are+ * first-class arms rather than shades of silence: an operation that was+ * never observed because the transport could not carry the events, and+ * one the operator cancelled, are different facts, and reporting either+ * as an absence of progress would be the misleading quiet this module+ * exists to remove.+ */+export const PROGRESS_KIND = Object.freeze({+ started: "started",+ advanced: "advanced",+ refused: "refused",+ stopped: "stopped",+ finished: "finished",+} as const);++export type ProgressKind = (typeof PROGRESS_KIND)[keyof typeof PROGRESS_KIND];++/** Membership list for {@link isProgressKind}. */+export const PROGRESS_KINDS: ReadonlyArray<ProgressKind> = Object.freeze([+ PROGRESS_KIND.started,+ PROGRESS_KIND.advanced,+ PROGRESS_KIND.refused,+ PROGRESS_KIND.stopped,+ PROGRESS_KIND.finished,+]);++/**+ * Whether `value` is a kind this build understands. Takes `unknown`+ * because the value arrives from a JSON line a caller parsed, or from a+ * notification a different release wrote.+ */+export function isProgressKind(value: unknown): value is ProgressKind {+ return typeof value === "string" && (PROGRESS_KINDS as ReadonlyArray<string>).includes(value);+}++/**+ * Why an operation stopped short, or why its progress could not be+ * carried. A closed set for the same reason `stage` is an identifier:+ * a reader must be able to branch on it, and a free string would let+ * prose in through the back door.+ */+export const PROGRESS_REASON = Object.freeze({+ /** The operator cancelled; the pass stopped at a checkpoint. */+ aborted: "aborted",+ /** The cooperative deadline elapsed; the pass stopped at a checkpoint. */+ timedOut: "timed-out",+ /**+ * A progress token was supplied over a transport that writes one+ * response and closes, so no notification could be sent. Reported+ * rather than dropped: accepting a token and discarding the events+ * would advertise liveness support that does not exist.+ */+ transportSingleResponse: "transport-single-response",+ /**+ * The command's stdout and stderr are buffered for the whole run and+ * released at the end, so a progress line would be invisible until+ * completion and then dumped - which reads as though it had worked.+ */+ streamBuffered: "stream-buffered",+ /**+ * The operation threw. The stream ends here because the run did; the+ * error itself is the caller's to read, and naming it on the stream+ * would put an arbitrary message on a structured surface.+ *+ * This member exists because {@link withProgress} promises to+ * terminate the stream whichever way the run ends, and a crash is a way+ * a run ends. Without it the promise held only for the two safeguard+ * stops, and a crashed run's stream simply stopped arriving - which is+ * the shape of a hung run, and the exact confusion this module exists+ * to remove.+ */+ failed: "failed",+} as const);++export type ProgressReason = (typeof PROGRESS_REASON)[keyof typeof PROGRESS_REASON];++/** Membership list for {@link isProgressReason}. */+export const PROGRESS_REASONS: ReadonlyArray<ProgressReason> = Object.freeze([+ PROGRESS_REASON.aborted,+ PROGRESS_REASON.timedOut,+ PROGRESS_REASON.transportSingleResponse,+ PROGRESS_REASON.streamBuffered,+ PROGRESS_REASON.failed,+]);++/** Whether `value` is a reason this build understands. */+export function isProgressReason(value: unknown): value is ProgressReason {+ return typeof value === "string" && (PROGRESS_REASONS as ReadonlyArray<string>).includes(value);+}++/**+ * One tick. Integers and identifiers only - the sentence a human reads is+ * rendered from these at the edge.+ */+export interface ProgressEvent {+ readonly schema: typeof PROGRESS_SCHEMA;+ /** Which long operation is speaking. */+ readonly operation: Operation;+ readonly kind: ProgressKind;+ /**+ * An identifier from the emitting operation's own phase vocabulary+ * (`DREAM_PHASE`, the index phases, a lane task name). Never prose.+ */+ readonly stage: string;+ /** Units finished in this stage so far. Monotonic within a stage. */+ readonly completed: number;+ /**+ * The stage's denominator, when one is known BEFORE the loop starts.+ * Absent for a stage driven by a generator - see the module header.+ */+ readonly total?: number;+ /** Present on `stopped` and `refused`, absent otherwise. */+ readonly reason?: ProgressReason;+}++/** The observer a long operation calls. Synchronous by construction. */+export type ProgressSink = (event: ProgressEvent) => void;++/**+ * Emits progress for one run of one operation, keeping the per-stage+ * counter so no call site has to.+ *+ * Deliberately NOT a class: the repository's cross-cutting optional+ * observers are all plain functions or frozen objects, and a counter with+ * one live field does not earn a prototype.+ */+export interface ProgressCounter {+ /** Begin a stage. `total` is the denominator when one is known. */+ start(stage: string, total?: number): void;+ /** Advance the current stage by `by` units (default 1). */+ advance(stage: string, by?: number): void;+ /** The run ended normally. */+ finish(): void;+ /** The run ended early, for a named reason. */+ stop(reason: ProgressReason): void;+}++export interface ProgressCounterOptions {+ /**+ * Where a throwing sink is reported, when the caller has somewhere+ * better to put it than the default.+ *+ * Progress is observation, and an observation must not be able to+ * destroy the thing observed: a broken edge stream - a closed pipe, a+ * renderer defect - must not abort a consolidation pass that is+ * otherwise succeeding. Nor may it vanish, so the error is reported+ * **once** and the sink is then detached for the rest of the run.+ * Detaching is the point: a stream that failed on the first tick would+ * otherwise fail on every one, turning one defect into a flood.+ *+ * Supplying this is optional because the DEFAULT is already safe, and+ * that is deliberate. It was optional before with an unsafe default -+ * the throw propagated and took the pass down with it - and a reviewer+ * found the predictable result: one of six emitters supplied a reporter+ * and five did not, so a broken pipe aborted five long operations and+ * left the sixth running. A rule every caller must remember is a rule+ * five of six callers will forget, which is the argument this whole+ * release is built on. The safe behaviour is therefore the one you get+ * by writing nothing.+ */+ readonly onSinkError?: (error: unknown) => void;+}++/** One line of an unknown throw, without assuming it is an Error. */+function describeError(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++/** Guards a denominator so a bad one is a loud defect, not a wrong number. */+function assertTotal(total: number | undefined): void {+ if (total === undefined) return;+ if (!Number.isInteger(total) || total < 0) {+ throw new RangeError(`progress: total must be a non-negative integer, got ${String(total)}`);+ }+}++export function progressCounter(+ operation: Operation,+ sink: ProgressSink | undefined,+ opts: ProgressCounterOptions = {},+): ProgressCounter {+ let stage: string | null = null;+ let completed = 0;+ let total: number | undefined;+ let live = sink !== undefined;+ let terminated = false;++ /**+ * A run ends once. A second terminator, or an event after one, would+ * let a reader see two endings for one run - which is worse than no+ * ending, because it looks well-formed.+ */+ const assertTerminal = (call: string, current: string | null): void => {+ if (!terminated) return;+ throw new RangeError(+ `progress: ${call}() after the ${operation} stream ended (last stage "${current ?? "none"}")`,+ );+ };++ const emit = (kind: ProgressKind, reason?: ProgressReason): void => {+ if (!live || sink === undefined || stage === null) return;+ const event: ProgressEvent = {+ schema: PROGRESS_SCHEMA,+ operation,+ kind,+ stage,+ completed,+ ...(total === undefined ? {} : { total }),+ ...(reason === undefined ? {} : { reason }),+ };+ try {+ sink(event);+ } catch (error) {+ live = false;+ if (opts.onSinkError !== undefined) {+ opts.onSinkError(error);+ return;+ }+ // The default report. Core may not write to stdout - the layering+ // test enforces it - but a fail-soft diagnostic on stderr is the+ // house convention, and stderr is never a protocol channel here:+ // the MCP server speaks on stdout. One line, once, naming the+ // operation whose stream just went dark, so a caller watching an+ // empty stream is told why it is empty.+ process.stderr.write(+ `progress: ${operation} stream detached after the sink threw: ${describeError(error)}\n`,+ );+ }+ };++ return {+ start(nextStage: string, nextTotal?: number): void {+ assertTerminal("start", stage);+ assertTotal(nextTotal);+ stage = nextStage;+ completed = 0;+ total = nextTotal;+ emit(PROGRESS_KIND.started);+ },+ advance(currentStage: string, by = 1): void {+ assertTerminal("advance", stage);+ if (!Number.isInteger(by) || by <= 0) {+ // A stream whose counter can go backwards, or sit still while+ // claiming to advance, describes a run nobody could follow. The+ // increment is a defect from inside this process, not input.+ throw new RangeError(`progress: advance must be a positive integer, got ${String(by)}`);+ }+ if (stage === null) {+ throw new RangeError(`progress: advance("${currentStage}") before any stage started`);+ }+ if (currentStage !== stage) {+ throw new RangeError(`progress: advance("${currentStage}") during stage "${stage}"`);+ }+ completed += by;+ emit(PROGRESS_KIND.advanced);+ },+ finish(): void {+ assertTerminal("finish", stage);+ emit(PROGRESS_KIND.finished);+ terminated = true;+ },+ stop(reason: ProgressReason): void {+ assertTerminal("stop", stage);+ emit(PROGRESS_KIND.stopped, reason);+ terminated = true;+ },+ };+}++/**+ * Run `body` and terminate `counter` exactly once, whichever way it ends.+ *+ * The rule this enforces is the whole point of the vocabulary having a+ * `finished` member at all: a stream that simply STOPS arriving is the+ * shape of a completed run, a crashed run and a hung run all at once, so+ * an emitter that never terminates has reported nothing a reader can act+ * on. Written here rather than at each operation because five copies of+ * one rule are five chances for one of them to be forgotten - which is+ * exactly what happened to three of the five before this helper existed.+ *+ * A stop carries the reason when the error is a safeguard stop, and no+ * reason otherwise: an unexpected throw is a crash, and calling it a+ * cancellation would be an invented fact. The error always propagates.+ */+export function withProgress<T>(counter: ProgressCounter, body: () => T): T {+ try {+ const result = body();+ counter.finish();+ return result;+ } catch (error) {+ counter.stop(progressReasonForError(error) ?? PROGRESS_REASON.failed);+ throw error;+ }+}++/** {@link withProgress} for an operation whose body is asynchronous. */+export async function withProgressAsync<T>(+ counter: ProgressCounter,+ body: () => Promise<T>,+): Promise<T> {+ try {+ const result = await body();+ counter.finish();+ return result;+ } catch (error) {+ counter.stop(progressReasonForError(error) ?? PROGRESS_REASON.failed);+ throw error;+ }+}++/**+ * The reason a safeguard stop corresponds to, or `null` when `error` is+ * not a safeguard stop at all.+ *+ * Lives here rather than at each of the five long operations because the+ * mapping is one fact - a cancellation is `aborted`, an elapsed deadline+ * is `timed-out` - and five copies of it would be five chances to report+ * a deliberate stop as a failure, which is the distinction+ * `SafeguardAbortError` was created to preserve.+ */+export function progressReasonForError(error: unknown): ProgressReason | null {+ if (error instanceof SafeguardAbortError) return PROGRESS_REASON.aborted;+ if (error instanceof SafeguardTimeoutError) return PROGRESS_REASON.timedOut;+ return null;+}++/** Re-exported so a call site needs one import to emit progress. */+export { OPERATION, type Operation };diff --git a/src/core/brain/review-candidates.ts b/src/core/brain/review-candidates.tsindex e18e3234..95682800 100644--- a/src/core/brain/review-candidates.ts+++ b/src/core/brain/review-candidates.ts@@ -18,6 +18,7 @@ import { join, relative } from "node:path";import type { ResolvedSearchConfig } from "../search/types.ts";import { dream } from "./dream.ts";+import type { DreamOptions } from "./dream-types.ts";import type { BrainIntentReviewEntry } from "./intent-review.ts";import { brainDirs } from "./paths.ts";import { scoreSignalNovelty, sortByNovelty, type SignalNoveltyEntry } from "./surprisal.ts";@@ -82,6 +83,21 @@ export interface BuildReviewCandidatesOptions {* unembedded indexes leave the report unchanged.*/readonly searchConfig?: ResolvedSearchConfig;+ /**+ * Cooperative deadline for the dry-run pass below. The projection is+ * read-only, but the pass it projects walks the whole Brain tree+ * synchronously, so a caller that must not be held indefinitely - the+ * MCP server, whose event loop this blocks - passes the same budget it+ * would pass to `dream` directly.+ */+ readonly safeguard?: DreamOptions["safeguard"];+ /**+ * Emitted at the same boundaries `safeguard` is checked at. A run worth+ * bounding is a run worth reporting on, and the pass behind this+ * projection is the same five stages `dream` emits - a caller who asked+ * to watch the pass that decides these candidates watches that one.+ */+ readonly onProgress?: DreamOptions["onProgress"];}/** Active inbox signal files as (id, relPath) refs. */@@ -102,6 +118,8 @@ export async function buildReviewCandidates(const summary = dream(vault, {dryRun: true,...(opts.now ? { now: opts.now } : {}),+ ...(opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),+ ...(opts.onProgress !== undefined ? { onProgress: opts.onProgress } : {}),});let signalNovelty: ReadonlyArray<SignalNoveltyEntry> | undefined;diff --git a/src/core/brain/safeguard.ts b/src/core/brain/safeguard.tsindex 30486ba8..19395076 100644--- a/src/core/brain/safeguard.ts+++ b/src/core/brain/safeguard.ts@@ -22,8 +22,65 @@import { discoverConfig } from "../config.ts";-/** Operations that accept a safeguard. */-export type SafeguardOperation = "dream" | "reindex" | "bridges" | "clusters" | "maintenance";+/**+ * The operations this repository calls long.+ *+ * It was a bare union until the progress spine needed to name the same+ * population - a run that carries a deadline is exactly a run worth+ * reporting on - and a second list would have drifted from this one.+ * Promoted to the four-piece vocabulary the census enforces so the+ * surfaces that name an operation read from one place.+ *+ * `maintenance` is the one member that is a DISPATCHER rather than a+ * pass, and it is worth being exact about what that costs it, because+ * "one vocabulary, every surface" is not true of it:+ *+ * - it never reaches `progressCounter`. The lane forwards the caller's+ * sink to its four sub-operations, so every record names the pass+ * that emitted it - a deliberate choice, asserted by+ * `brain-maintenance-progress.test.ts`, not an omission;+ * - it never reaches {@link resolveSafeguardTimeoutMs} either.+ * `laneSafeguard` builds one deadline per task from that task's own+ * operation, so there is no lane-wide budget to resolve and+ * `safeguard_timeout_maintenance_seconds` is a key nothing reads.+ * It is not documented in `docs/cli-reference.md` for that reason;+ * - it IS the operation the lane's interrupt handle is opened for+ * (`interruptIsObservable` in `src/cli/interrupt.ts`), because the+ * lane awaits between tasks and so is the level at which a Ctrl-C+ * can actually be seen. That is its one producer.+ */+export const OPERATION = Object.freeze({+ dream: "dream",+ reindex: "reindex",+ bridges: "bridges",+ clusters: "clusters",+ maintenance: "maintenance",+ architect: "architect",+} as const);++export type Operation = (typeof OPERATION)[keyof typeof OPERATION];++/** Membership list for {@link isOperation}. */+export const OPERATIONS: ReadonlyArray<Operation> = Object.freeze([+ OPERATION.dream,+ OPERATION.reindex,+ OPERATION.bridges,+ OPERATION.clusters,+ OPERATION.maintenance,+ OPERATION.architect,+]);++/**+ * Whether `value` names an operation this build understands. Takes+ * `unknown` because it arrives from a config key a person typed or from a+ * progress line a caller parsed.+ */+export function isOperation(value: unknown): value is Operation {+ return typeof value === "string" && (OPERATIONS as ReadonlyArray<string>).includes(value);+}++/** Historical name for {@link Operation}, kept so call sites need no edit. */+export type SafeguardOperation = Operation;/** Built-in fallback budget (mirage uses 600s; same scale fits here). */export const SAFEGUARD_DEFAULT_TIMEOUT_SECONDS = 600;diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.tsindex fdc1602b..1eac669c 100644--- a/src/core/brain/sessions/import.ts+++ b/src/core/brain/sessions/import.ts@@ -134,11 +134,43 @@ export function resolveEventInstant(return { instant: new Date(ms), fromTurn: true };}+/**+ * Whether an import's counters describe writes that HAPPENED or writes it+ * would have made. A dry run's `signals_created` is zero by construction,+ * which is also what a real run over a session with nothing in it reports;+ * without this the two results are the same bytes.+ */+export const IMPORT_WRITE_MODE = Object.freeze({+ applied: "applied",+ dryRun: "dry_run",+} as const);++export type ImportWriteMode = (typeof IMPORT_WRITE_MODE)[keyof typeof IMPORT_WRITE_MODE];++export const IMPORT_WRITE_MODES: ReadonlyArray<ImportWriteMode> = Object.freeze([+ IMPORT_WRITE_MODE.applied,+ IMPORT_WRITE_MODE.dryRun,+]);++export function isImportWriteMode(value: unknown): value is ImportWriteMode {+ return typeof value === "string" && (IMPORT_WRITE_MODES as ReadonlyArray<string>).includes(value);+}+export interface ImportSessionResult {readonly file: string;- readonly format: SessionAdapterId;+ /** Id of the adapter that parsed the file; a registry key, not a union. */+ readonly format: string;+ /** Whether the counters below describe writes made or writes forecast. */+ readonly write_mode: ImportWriteMode;readonly turns_scanned: number;readonly signals_created: number;+ /**+ * Signals a dry run would have written. Always 0 under+ * {@link IMPORT_WRITE_MODE.applied} - a real run writes instead of+ * withholding - so the pair (`signals_created`, `signals_withheld`) says+ * which run this was and what it did in one reading.+ */+ readonly signals_withheld: number;readonly signals_deduped: number;readonly tool_replays: number;/** Per-skill invocations captured as skill_invoked continuity records. */@@ -150,6 +182,8 @@ export interface ImportSessionResult {/** Turns whose text was suppressed before any extraction. */readonly suppressed_turns: number;readonly facts_extracted: number;+ /** Facts a dry run would have written. Always 0 on an applied run. */+ readonly facts_withheld: number;readonly facts_deduped: number;readonly recall_turns_imported: number;readonly recall_summary_nodes: number;@@ -224,8 +258,10 @@ export async function importSession(const sessionKey = sessionRefIdentity(absPath, opts.recallSessionId);const errors: { path: string; message: string }[] = [];+ const writeMode = opts.dryRun === true ? IMPORT_WRITE_MODE.dryRun : IMPORT_WRITE_MODE.applied;let turnsScanned = 0;let signalsCreated = 0;+ let signalsWithheld = 0;let signalsDeduped = 0;let toolReplays = 0;let skillInvocations = 0;@@ -233,7 +269,15 @@ export async function importSession(let filteredTurns = 0;let suppressedTurns = 0;let factsExtracted = 0;+ let factsWithheld = 0;let factsDeduped = 0;+ /**+ * Hashes a dry run has already forecast. The dedup index only learns a+ * hash when a signal actually lands, so without this a marker repeated+ * inside one rehearsal would be forecast twice where the real run counts+ * one write and one dedup.+ */+ const withheldHashes = new Set<string>();const recallTurns: SessionTurn[] = [];const filterRoles =opts.filterRoles && opts.filterRoles.length > 0 ? new Set(opts.filterRoles) : null;@@ -258,9 +302,14 @@ export async function importSession(return;}if (opts.dryRun) {- // Mirror scan-inline: dry-run reports the dedup hit count and- // turns scanned, but `signals_created` stays 0 — nothing was- // actually written.+ // Nothing is written, and the result says so: `signals_created` stays+ // 0 and the forecast lands in `signals_withheld` instead.+ if (withheldHashes.has(input.dedupHash)) {+ signalsDeduped++;+ return;+ }+ withheldHashes.add(input.dedupHash);+ signalsWithheld++;return;}const sessionRef = `${sessionKey}#${input.turnId}`;@@ -325,8 +374,10 @@ export async function importSession(Object.freeze({file: absPath,format: adapter.id,+ write_mode: writeMode,turns_scanned: 0,signals_created: 0,+ signals_withheld: 0,signals_deduped: 0,tool_replays: 0,skill_invocations: 0,@@ -335,6 +386,7 @@ export async function importSession(boundary_decision: boundaryDecision,suppressed_turns: 0,facts_extracted: 0,+ facts_withheld: 0,facts_deduped: 0,recall_turns_imported: 0,recall_summary_nodes: 0,@@ -379,6 +431,7 @@ export async function importSession(...(opts.dryRun === true ? { dryRun: true } : {}),});factsExtracted += routed.created;+ factsWithheld += routed.withheld;factsDeduped += routed.deduped;}@@ -519,8 +572,10 @@ export async function importSession(return Object.freeze({file: absPath,format: adapter.id,+ write_mode: writeMode,turns_scanned: turnsScanned,signals_created: signalsCreated,+ signals_withheld: signalsWithheld,signals_deduped: signalsDeduped,tool_replays: toolReplays,skill_invocations: skillInvocations,@@ -528,6 +583,7 @@ export async function importSession(boundary_decision: boundaryDecision,suppressed_turns: suppressedTurns,facts_extracted: factsExtracted,+ facts_withheld: factsWithheld,facts_deduped: factsDeduped,filtered_turns: filteredTurns,recall_turns_imported: recallTurnsImported,@@ -542,7 +598,7 @@ export async function importSession(* the caller, not here), then a per-adapter default, finally* `opts.agent`.*/-function agentLabelForTurn(turn: SessionTurn, adapter: SessionAdapterId, fallback: string): string {+function agentLabelForTurn(turn: SessionTurn, adapter: string, fallback: string): string {void turn; // reserved for future per-turn role-aware fallbackreturn getAdapter(adapter).defaultAgent.trim() || fallback;}diff --git a/src/core/brain/sessions/registry.ts b/src/core/brain/sessions/registry.tsindex eeb318d3..84cb32a2 100644--- a/src/core/brain/sessions/registry.ts+++ b/src/core/brain/sessions/registry.ts@@ -1,12 +1,24 @@/**- * Adapter registry. The single place that knows about every concrete- * session adapter. Adding a fourth runtime is:+ * Session-adapter registry. The single place that knows about every+ * concrete session adapter.+ *+ * Same shape as the memory-backend registry+ * (`src/core/brain/agent-backend/registry.ts`), and for the same reason its+ * protocol states: "adding a runtime means adding ONE module that satisfies+ * this interface and registering it - no changes to the import core, CLI, or+ * MCP surfaces" (`src/core/brain/agent-backend/types.ts:9-11`). A frozen+ * id-keyed map, lookup by id, and an unknown id that fails loudly with the+ * registered set rather than falling back to a wrong parser.+ *+ * Adding a runtime is therefore:** 1. Drop `sessions/<new>.ts` with a `SessionAdapter` export.- * 2. Append to {@link SESSION_ADAPTERS}.- * 3. Add the new id to the `SessionAdapterId` union in `types.ts`.+ * 2. Append it to {@link BUILTIN_SESSION_ADAPTERS}, and its id to+ * `SESSION_ADAPTER_ID` so `--format` accepts it.*- * No other code path changes.+ * Every lookup takes an optional registry, so a caller can resolve against+ * its own adapter set ({@link createSessionAdapterRegistry}) without the+ * built-in map knowing that set exists.*/import { claudeAdapter } from "./claude.ts";@@ -14,9 +26,14 @@ import { codexAdapter } from "./codex.ts";import { grokAdapter } from "./grok.ts";import { hermesAdapter } from "./hermes.ts";import { opencodeAdapter } from "./opencode.ts";-import type { SessionAdapter, SessionAdapterId } from "./types.ts";+import { isSessionAdapterId, type SessionAdapter } from "./types.ts";++export { isSessionAdapterId };++/** An id-keyed adapter set. Insertion order is autodetect probe order. */+export type SessionAdapterRegistry = ReadonlyMap<string, SessionAdapter>;-export const SESSION_ADAPTERS: ReadonlyArray<SessionAdapter> = Object.freeze([+const BUILTIN_SESSION_ADAPTERS: ReadonlyArray<SessionAdapter> = Object.freeze([claudeAdapter,codexAdapter,hermesAdapter,@@ -24,12 +41,45 @@ export const SESSION_ADAPTERS: ReadonlyArray<SessionAdapter> = Object.freeze([grokAdapter,]);-export function isSessionAdapterId(value: string): value is SessionAdapterId {- return SESSION_ADAPTERS.some((a) => a.id === value);+/**+ * Build a registry from an adapter list, preserving order. A repeated id is+ * refused: silently keeping one of two adapters claiming the same id would+ * decide which runtime's transcripts get parsed by insertion order alone.+ */+export function createSessionAdapterRegistry(+ adapters: ReadonlyArray<SessionAdapter>,+): SessionAdapterRegistry {+ const registry = new Map<string, SessionAdapter>();+ for (const adapter of adapters) {+ if (registry.has(adapter.id)) {+ throw new Error(`duplicate SessionAdapter id '${adapter.id}' in registry`);+ }+ registry.set(adapter.id, adapter);+ }+ return registry;}-export function sessionAdapterFormatChoices(): string {- return ["auto", ...SESSION_ADAPTERS.map((a) => a.id)].join("|");+/** The adapters that ship in this tree, keyed by id. */+export const SESSION_ADAPTER_REGISTRY: SessionAdapterRegistry =+ createSessionAdapterRegistry(BUILTIN_SESSION_ADAPTERS);++/** Registered adapters in registration order. */+export function listSessionAdapters(+ registry: SessionAdapterRegistry = SESSION_ADAPTER_REGISTRY,+): ReadonlyArray<SessionAdapter> {+ return Object.freeze([...registry.values()]);+}++/**+ * Every shipped adapter, in registry order. Retained as the flat view the+ * cross-table tests and the CLI help enumerate.+ */+export const SESSION_ADAPTERS: ReadonlyArray<SessionAdapter> = listSessionAdapters();++export function sessionAdapterFormatChoices(+ registry: SessionAdapterRegistry = SESSION_ADAPTER_REGISTRY,+): string {+ return ["auto", ...registry.keys()].join("|");}/**@@ -39,19 +89,26 @@ export function sessionAdapterFormatChoices(): string {* design bug — `tests/core/brain.sessions.registry.test.ts` locks* the cross-table.*/-export function detectAdapter(firstLine: string): SessionAdapter | null {- for (const a of SESSION_ADAPTERS) {- if (a.detect(firstLine)) return a;+export function detectAdapter(+ firstLine: string,+ registry: SessionAdapterRegistry = SESSION_ADAPTER_REGISTRY,+): SessionAdapter | null {+ for (const adapter of registry.values()) {+ if (adapter.detect(firstLine)) return adapter;}return null;}-export function getAdapter(id: SessionAdapterId): SessionAdapter {- for (const a of SESSION_ADAPTERS) {- if (a.id === id) return a;+/** Adapter by id; throws with the registered list on an unknown id. */+export function getAdapter(+ id: string,+ registry: SessionAdapterRegistry = SESSION_ADAPTER_REGISTRY,+): SessionAdapter {+ const adapter = registry.get(id);+ if (adapter === undefined) {+ throw new Error(+ `no SessionAdapter registered with id '${id}' - registered: ${[...registry.keys()].join(", ")}`,+ );}- // The union type makes this unreachable at compile time, but a- // runtime guard keeps the failure mode honest if SESSION_ADAPTERS- // is ever mutated out from under us.- throw new Error(`no SessionAdapter registered with id '${id}'`);+ return adapter;}diff --git a/src/core/brain/sessions/types.ts b/src/core/brain/sessions/types.tsindex e016b862..17758171 100644--- a/src/core/brain/sessions/types.ts+++ b/src/core/brain/sessions/types.ts@@ -14,7 +14,42 @@* entry — no other code path needs to change.*/-export type SessionAdapterId = "claude" | "codex" | "hermes" | "opencode" | "grok";+/**+ * The runtimes whose adapters ship in this tree.+ *+ * Closed, because it is what `--format` is validated against: a value that+ * arrives as a raw CLI string is either one of these or a typo, and+ * {@link isSessionAdapterId} is the boundary between the two. The registry+ * itself is keyed by `string` and open to a caller's own adapter+ * (`createSessionAdapterRegistry`), so this vocabulary answers "which+ * runtimes ship here", not "which adapters can exist" - and+ * `tests/core/brain/sessions/adapter-registry.test.ts` locks the two+ * together for the built-in registry.+ */+export const SESSION_ADAPTER_ID = Object.freeze({+ claude: "claude",+ codex: "codex",+ hermes: "hermes",+ opencode: "opencode",+ grok: "grok",+} as const);++export type SessionAdapterId = (typeof SESSION_ADAPTER_ID)[keyof typeof SESSION_ADAPTER_ID];++/** The shipped adapter ids, in registry order. */+export const SESSION_ADAPTER_IDS: ReadonlyArray<SessionAdapterId> = Object.freeze([+ SESSION_ADAPTER_ID.claude,+ SESSION_ADAPTER_ID.codex,+ SESSION_ADAPTER_ID.hermes,+ SESSION_ADAPTER_ID.opencode,+ SESSION_ADAPTER_ID.grok,+]);++export function isSessionAdapterId(value: unknown): value is SessionAdapterId {+ return (+ typeof value === "string" && (SESSION_ADAPTER_IDS as ReadonlyArray<string>).includes(value)+ );+}export interface SessionToolCall {/** Tool name as emitted by the runtime, e.g. `brain_feedback`. */@@ -38,7 +73,14 @@ export interface SessionTurn {}export interface SessionAdapter {- readonly id: SessionAdapterId;+ /**+ * Registry key. `string` rather than {@link SessionAdapterId} so that+ * registering an adapter is the ONE change adding a runtime requires -+ * a union here would make every new adapter a change to this file too,+ * and would put a test's own adapter outside the type system entirely.+ * The shipped adapters carry ids from {@link SESSION_ADAPTER_ID}.+ */+ readonly id: string;/** Default `agent` label stamped on imported signals for this runtime. */readonly defaultAgent: string;/**diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.tsindex a1d4784b..22d172ec 100644--- a/src/core/brain/snapshot.ts+++ b/src/core/brain/snapshot.ts@@ -294,6 +294,77 @@ export interface SnapshotInfo {readonly reason: BrainSnapshotReason | null;}+/**+ * Why one `.snapshots/` entry could not become a {@link SnapshotInfo}.+ *+ * Both members describe an entry that IS an archive by name - the suffix+ * matched - and could not be turned into a listing row. A file that is not+ * an archive at all (a sidecar manifest, a store archive, an operator's+ * stray note) is not in this vocabulary: it is not a recovery point that+ * could not be read, it is not a recovery point.+ */+export const SNAPSHOT_ENTRY_SKIP_REASON = Object.freeze({+ /** The name carries the archive suffix and the run id inside it does not validate. */+ runIdUnparseable: "run_id_unparseable",+ /** The archive is named in the directory and could not be stat'ed. */+ entryUnreadable: "entry_unreadable",+} as const);++export type SnapshotEntrySkipReason =+ (typeof SNAPSHOT_ENTRY_SKIP_REASON)[keyof typeof SNAPSHOT_ENTRY_SKIP_REASON];++export const SNAPSHOT_ENTRY_SKIP_REASONS: ReadonlyArray<SnapshotEntrySkipReason> = Object.freeze(+ Object.values(SNAPSHOT_ENTRY_SKIP_REASON),+);++export function isSnapshotEntrySkipReason(value: unknown): value is SnapshotEntrySkipReason {+ return (+ typeof value === "string" &&+ (SNAPSHOT_ENTRY_SKIP_REASONS as ReadonlyArray<string>).includes(value)+ );+}++/** One archive-shaped entry that is missing from {@link SnapshotListing.snapshots}. */+export interface SnapshotEntrySkip {+ /** Directory entry name, as `readdir` reported it. */+ readonly name: string;+ /** Absolute path of that entry. */+ readonly path: string;+ readonly reason: SnapshotEntrySkipReason;+ /** The underlying failure, in the words of whatever refused. */+ readonly detail: string;+}++/**+ * One skipped entry as a phrase, spelled once for every surface that+ * reports one: the doctor's uncertain stream and both CLI listings say the+ * same thing about the same file, and a second wording would be a second+ * claim about it.+ */+export function describeSnapshotEntrySkip(skip: SnapshotEntrySkip): string {+ return `${skip.name} (${skip.reason}: ${skip.detail})`;+}++/**+ * What {@link listSnapshots} found: the recovery points it could describe,+ * and the archive-shaped entries it could not.+ *+ * Two fields rather than one array because "these are the recovery points"+ * and "this listing is complete" are two different facts, and the second+ * one used to have no wire at all: every per-entry failure was dropped, so+ * a directory full of archives nobody could stat answered exactly like a+ * vault that had never taken one. Callers that only count archives read+ * {@link snapshots}; callers that tell an operator what their vault+ * contains have to read {@link skipped} too, and the compiler now makes+ * them look at it.+ */+export interface SnapshotListing {+ /** Newest-first by archive mtime. */+ readonly snapshots: SnapshotInfo[];+ /** Empty when every archive-shaped entry became a row. */+ readonly skipped: ReadonlyArray<SnapshotEntrySkip>;+}+/*** Why a prune did not remove what it was asked to.*@@ -369,7 +440,14 @@ export interface PruneSnapshotsResult {* so.*/readonly failed: ReadonlyArray<string>;- /** How many archives are still on disk when the prune returns. */+ /**+ * How many archives the listing could DESCRIBE when the prune returns.+ *+ * An entry `listSnapshots` had to skip - a run id that will not validate,+ * a `stat` that failed - is still on disk and is not in this count, and+ * is not a prune candidate either: this function removes what it can+ * name. {@link SnapshotListing.skipped} is where those are reported.+ */readonly retained: number;/** Why nothing was pruned, or `null` when the prune ran. */readonly refusal: SnapshotPruneRefusal | null;@@ -1099,20 +1177,31 @@ function runArchiveProducer(cmd: string, args: ReadonlyArray<string>, runId: str// ----- listSnapshots / pruneSnapshots --------------------------------------/**- * Enumerate `.snapshots/*.tar.zst` in newest-first order (by mtime).- * Files outside the canonical naming pattern are silently skipped so- * a stray text file in the dir doesn't poison the listing.+ * Enumerate `.snapshots/*.tar.zst` in newest-first order (by mtime),+ * alongside the archive-shaped entries that could not be described.*- * A directory that is not there is an empty history and returns `[]`: no- * snapshot has ever been taken, which is a real answer. A directory that- * IS there and cannot be enumerated throws- * {@link BrainSnapshotListingError} instead, because the two are- * different facts and `[]` for both is what let the listing surfaces- * print "no snapshots available" over a read that never happened.+ * Files outside the canonical naming pattern are skipped and NOT reported:+ * a sidecar manifest, a store archive or a stray text file is not a+ * recovery point, so naming it would be noise.+ *+ * The three answers this returns are three different facts:+ *+ * - a directory that is not there is an empty history: no snapshot has+ * ever been taken, and both fields are empty.+ * - a directory that IS there and cannot be enumerated throws+ * {@link BrainSnapshotListingError}, because `[]` for that too is what+ * let the listing surfaces print "no snapshots available" over a read+ * that never happened.+ * - an archive that is named in the directory and cannot be turned into+ * a row - an unvalidatable run id, or a `stat` that failed - lands in+ * {@link SnapshotListing.skipped}. It used to be dropped with a bare+ * `continue`, which put a populated history nobody could stat and a+ * vault that never took one on the same wire; the caller decides what+ * to say about it, but it can no longer fail to know.*/-export function listSnapshots(vault: string): SnapshotInfo[] {+export function listSnapshots(vault: string): SnapshotListing {const dirs = brainDirs(vault);- if (!existsSync(dirs.snapshots)) return [];+ if (!existsSync(dirs.snapshots)) return { snapshots: [], skipped: [] };let entries: string[];try {entries = readdirSync(dirs.snapshots);@@ -1120,22 +1209,38 @@ export function listSnapshots(vault: string): SnapshotInfo[] {throw new BrainSnapshotListingError(dirs.snapshots, err);}const infos: SnapshotInfo[] = [];+ const skipped: SnapshotEntrySkip[] = [];for (const name of entries) {if (!name.endsWith(SNAPSHOT_ARCHIVE_SUFFIX)) continue;const runId = name.slice(0, -SNAPSHOT_ARCHIVE_SUFFIX.length);- // The `.snapshots/` dir is ours, so a malformed run_id here would- // indicate manual tampering — we keep the listing tolerant and- // skip rather than throw.+ const full = join(dirs.snapshots, name);+ // The `.snapshots/` dir is ours, so a malformed run_id here indicates+ // manual tampering — the listing stays tolerant and keeps describing+ // the archives it can, but the entry is carried out rather than+ // dropped: an operator hunting a recovery point they know they took+ // needs to be told the file is there under a name this build will not+ // accept.try {validateRunId(runId);- } catch {+ } catch (err) {+ skipped.push({+ name,+ path: full,+ reason: SNAPSHOT_ENTRY_SKIP_REASON.runIdUnparseable,+ detail: err instanceof Error ? err.message : String(err),+ });continue;}- const full = join(dirs.snapshots, name);let st;try {st = statSync(full);- } catch {+ } catch (err) {+ skipped.push({+ name,+ path: full,+ reason: SNAPSHOT_ENTRY_SKIP_REASON.entryUnreadable,+ detail: err instanceof Error ? err.message : String(err),+ });continue;}const sidecar = manifestSidecarPath(vault, runId);@@ -1166,7 +1271,7 @@ export function listSnapshots(vault: string): SnapshotInfo[] {// non-timestamped id and we still want them to land where the// operator's mental model expects (most recent first).infos.sort((a, b) => Date.parse(b.created_at) - Date.parse(a.created_at));- return infos;+ return { snapshots: infos, skipped };}/**@@ -1214,11 +1319,11 @@ export function pruneSnapshots(return Object.freeze({deleted: Object.freeze([]),failed: Object.freeze([]),- retained: listSnapshots(vault).length,+ retained: listSnapshots(vault).snapshots.length,refusal: SNAPSHOT_PRUNE_REFUSAL.belowRetentionFloor,});}- const all = listSnapshots(vault);+ const all = listSnapshots(vault).snapshots;if (all.length <= retentionCount) {return Object.freeze({deleted: Object.freeze([]),diff --git a/src/core/brain/sync-lockfile.ts b/src/core/brain/sync-lockfile.tsindex 59ad1a07..eedbc204 100644--- a/src/core/brain/sync-lockfile.ts+++ b/src/core/brain/sync-lockfile.ts@@ -14,16 +14,49 @@* MCP server, dream runs from cron). When it does happen, we prefer a* loud typed error over a silent retry-then-still-fail loop.*+ * ## Why this exists beside `reliability/lock.ts`+ *+ * `withFileLock` there is the general-purpose ladder and it is ASYNC -+ * it awaits `proper-lockfile`. Every consumer of the waiting form here+ * (`updateManifest`, `appendGitRecords`, `recordCompleted`,+ * `generateRun`) is a synchronous function, and `ingestSource` above two+ * of them is synchronous on the published SDK surface, so awaiting a+ * lock would colour that function, its callers and the SDK contract.+ * Two ladders, two reasons; a reader who finds this one and wonders why+ * the other was not used is reading the right question, and this is the+ * answer.+ ** Stale-lock recovery: on normal process exit the cleanup hook unlinks- * any still-held locks. On hard crash (SIGKILL, OOM) the `.lock` file- * stays on disk and the next acquire fails with ELOCKED; the brain- * doctor surfaces these via {@link scanStaleLocks} so an operator can- * remove them by hand.+ * any still-held locks. On hard crash (SIGKILL, OOM, or the second+ * Ctrl-C that falls through to the default SIGINT disposition) the+ * `.lock` file stays on disk and the next acquire fails with ELOCKED;+ * the brain doctor surfaces these via {@link scanStaleLocks} so an+ * operator can remove them by hand.+ *+ * ## Why this lock has no stale window, when the search writer lock does+ *+ * `search/store/writer-lock.ts` treats a lock older than+ * `WRITER_LOCK_STALE_MS` (60 s) as abandoned and takes it over, so a+ * SIGKILL never wedges the index for longer than that. This lock+ * deliberately has no such window, and the asymmetry is not an+ * oversight: the search lock can self-heal only because its holder+ * HEARTBEATS - `acquireWriterLock` passes `update:+ * WRITER_LOCK_HEARTBEAT_MS` so a live holder keeps refreshing the mtime,+ * which is what makes "old mtime" mean "dead holder". A holder of THIS+ * lock is inside a synchronous critical section: the single thread is+ * busy doing the very work the lock protects, so no timer can refresh+ * anything. Here an age threshold would only mean "held for longer than+ * N", which a live writer on a large store reaches honestly - and+ * breaking a live writer's lock corrupts what it protects. So the+ * condition is REPORTED and the judgement is left to the operator; see+ * `doctor/uncertainty-probes.ts`.*/import { closeSync, mkdirSync, openSync, readdirSync, unlinkSync, writeSync } from "node:fs";import { dirname, join } from "node:path";+import { BRAIN_ROOT_REL, DERIVED_STORE_DIR } from "./path-constants.ts";+export interface LockHandle {/** Filesystem path to the underlying `.lock` file. */readonly path: string;@@ -116,13 +149,187 @@ export function acquireLockSync(target: string): LockHandle {}/**- * Walk `root` recursively and return every `.lock` file path. Used by- * `brain_doctor` to surface stale locks left behind by a crashed- * process.+ * How long {@link acquireLockSyncWithRetry} keeps waiting, and the ceiling on+ * one sleep between attempts.+ *+ * The budget is a WALL-CLOCK deadline rather than an attempt count because+ * what a waiter queues behind is other writers' work, not other writers'+ * sleeps: with n processes each folding one source into a shared file, the+ * last arrival waits for up to n-1 whole critical sections. An attempt count+ * bounds the number of naps, which is the wrong quantity.+ *+ * The sleep is JITTERED across `[1, RETRY_SLEEP_CEILING_MS]` rather than+ * fixed. A fixed sleep makes contenders that started together retry in+ * lockstep - they wake on the same tick, one wins, the rest sleep another+ * whole tick - so the same budget buys far fewer real attempts.+ *+ * ## Five seconds, for a different reason than the one first given+ *+ * The budget IS the freeze (see {@link acquireLockSyncWithRetry}), so five+ * seconds is a claim worth checking rather than assuming. The claim made+ * here was that it is "generous against a hold measured in milliseconds".+ * Both halves of that were measured, and the first half is false:+ *+ * | rows in the store | `appendGitRecords` hold | `updateManifest` hold |+ * |---|---|---|+ * | 1 000 | 23 ms | 19 ms |+ * | 10 000 | 134 ms | 81 ms |+ * | 50 000 | 465 ms | 262 ms |+ *+ * The holds are linear in the store they guard - a 50 000-commit repo is+ * most of a second per critical section, not milliseconds. But the hold is+ * not what sizes the budget. Measured across a four-process race over a+ * 400-entry manifest (100 acquisitions), the WAIT distribution is+ * `p50 = 0 ms, p90 = 1 ms, p99 = 732 ms, max = 732 ms`: almost every+ * acquisition is uncontended, and the tail is set by queueing, not by one+ * hold. The tail is long because nothing here is fair - a writer in a loop+ * re-acquires with no backoff at all while every waiter is mid-sleep, so a+ * waiter can lose many draws in a row.+ *+ * That tail is why the budget cannot simply be made small: at 1 000 ms the+ * branch's own designed-contention test (`updateManifest - concurrent+ * writers`, four real processes) starts failing intermittently with+ * `ELOCKED` on a perfectly healthy race - a budget at the p99 of the thing+ * it is meant to absorb is a coin flip. Five seconds is about six times+ * that p99, which is the margin that makes reaching it mean "something is+ * wrong" rather than "busy".+ *+ * What a caller gives up is therefore stated plainly rather than argued+ * away: in the worst case this freezes the process for five seconds. See+ * {@link acquireLockSyncWithRetry} for what bounds that, and+ * {@link LOCK_WAIT_INTERACTIVE_MS} for the callers that refuse to pay it.+ */+export const LOCK_WAIT_BUDGET_MS = 5_000;++/**+ * The budget for a caller whose contention is RARE and whose freeze is+ * expensive - an interactive CLI pass with a progress stream and a Ctrl-C+ * the operator expects to land.+ *+ * The default above is sized for the ingest fan-out: several processes+ * folding results into one file, by design, where a long wait buys a+ * healthy ingest and a freeze costs a short-lived worker nothing. The+ * architect is the opposite case on both counts. Its contender is a second+ * architect run over the same repo, which is not a designed workload, and+ * its process is one an operator is watching: five seconds parked in+ * `Bun.sleepSync` is five seconds of stalled progress events and an+ * undelivered SIGINT. One second is still above the p90 of the measured+ * wait distribution, so a genuine brief overlap is absorbed; beyond that+ * the operator gets a named `ELOCKED` and a prompt back, which is a better+ * answer than a frozen terminal.+ */+export const LOCK_WAIT_INTERACTIVE_MS = 1_000;++const RETRY_SLEEP_CEILING_MS = 25;++/**+ * {@link acquireLockSync} with a bounded wait, for the shared files that+ * PARALLEL processes write by design.+ *+ * The single-attempt policy above is justified by contention being rare -+ * one operator, one MCP server, dream on cron. The ingest path breaks that+ * premise on purpose: `ingest/batch-plan.ts` exists so a caller dispatches+ * each batch as its own subagent, so several processes fold their result+ * into the content manifest, the plan checkpoint and the git record store+ * concurrently. There, an immediate `ELOCKED` would turn a millisecond+ * overlap into a failed ingest.+ *+ * Waiting is bounded and still loud: only `ELOCKED` is retried, any other+ * error propagates at once, and an expired budget rethrows the last+ * `ELOCKED` (which names the lock file) rather than proceeding unlocked.+ * Nothing is ever silently skipped.+ *+ * ## The wait is a FREEZE, and that is the cost+ *+ * `Bun.sleepSync` blocks the single JavaScript thread. This does not "wait",+ * it stops the process: for the whole budget no timer fires, no progress+ * event is emitted, no signal handler runs (a Ctrl-C is queued, not+ * delivered), and inside the MCP server no other tool call proceeds.+ * `tests/core/brain/sync-lockfile.test.ts` pins both halves of that - the+ * freeze is total, and it ends when the budget does.+ *+ * The freeze is accepted rather than removed, for three reasons that were+ * checked rather than assumed:+ *+ * - Removing it is not a local change. The Brain write path is synchronous+ * end to end, and `ingestSource` - the caller that reaches two of these+ * three sites - is a synchronous function on the published SDK surface+ * (`brain/sdk.ts`). An awaited lock would have to colour it, its callers+ * and that contract async for one ingredient. Worth doing on its own+ * terms; not worth smuggling in beside a lock fix.+ * - Shrinking it to a value nobody would notice does not work either: at+ * 1 000 ms the four-process manifest race fails on healthy contention.+ * See {@link LOCK_WAIT_BUDGET_MS} for the measured distribution.+ * - Within ONE process this lock can never be contended. The whole+ * acquire-mutate-release runs inside a single synchronous turn, so a+ * second `brain_ingest_source` call on the same MCP server cannot even+ * begin while the first holds it. An `ELOCKED` inside a server therefore+ * always means a DIFFERENT process - never the parallel fan-out this+ * function exists for. The server can still be frozen by an external+ * writer; what it cannot do is freeze itself.+ *+ * A caller that would rather refuse than freeze says so with+ * {@link LOCK_WAIT_INTERACTIVE_MS}.+ */+export function acquireLockSyncWithRetry(+ target: string,+ budgetMs: number = LOCK_WAIT_BUDGET_MS,+): LockHandle {+ // A budget this loop cannot honour is named rather than quietly+ // reinterpreted, in the same discipline as `requireCap` and the lease's+ // TTL guard. `NaN` is the reason the guard exists: `Date.now() >= NaN` is+ // false forever, so a non-finite budget turned a bounded freeze into an+ // unbounded one that no signal could break. Zero is legal and means+ // exactly one attempt - the deadline is only consulted after a failure.+ if (!Number.isInteger(budgetMs) || budgetMs < 0) {+ throw new Error(`lock wait budgetMs must be an integer >= 0, got ${budgetMs}`);+ }+ const deadline = Date.now() + budgetMs;+ for (;;) {+ try {+ return acquireLockSync(target);+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code !== "ELOCKED") throw err;+ if (Date.now() >= deadline) throw err;+ Bun.sleepSync(1 + Math.floor(Math.random() * RETRY_SLEEP_CEILING_MS));+ }+ }+}++/**+ * Every directory in `vault` a Brain `.lock` can appear under.+ *+ * ENUMERATED here, in the module that owns the lock, rather than chosen by+ * whoever calls the scan. The doctor used to walk one hard-coded root,+ * `<vault>/Brain/` - and two of the three locks the parallel ingest path+ * takes (the content manifest and the plan checkpoint) live in the+ * derived-store directory beside it, so a crashed ingest left a lock the+ * doctor answered `[]` about while it sat plainly on disk.+ *+ * These two are the only directories any lock is taken in today - checked+ * against every path builder that feeds a lock target, not assumed. A new+ * lock site under a third root has to be added here, and+ * the census in `tests/core/brain/sync-lockfile.test.ts` reads the sources+ * to make sure it is: the failure this closes is not one wrong path, it is+ * a scan that silently stops being complete.*/-export function scanStaleLocks(root: string): string[] {+export function lockScanRoots(vault: string): string[] {+ return [join(vault, BRAIN_ROOT_REL), join(vault, DERIVED_STORE_DIR)];+}++/**+ * Walk every {@link lockScanRoots} directory of `vault` recursively and+ * return each `.lock` file path. Used by `brain_doctor` to surface stale+ * locks left behind by a crashed process.+ *+ * Takes the VAULT, not a root, so no caller can narrow the scan to a+ * subset of the places a lock lives. A root that does not exist+ * contributes nothing - `walkLocks` already treats an unreadable+ * directory as empty.+ */+export function scanStaleLocks(vault: string): string[] {const out: string[] = [];- walkLocks(root, out);+ for (const root of lockScanRoots(vault)) walkLocks(root, out);return out;}@@ -150,7 +357,12 @@ function walkLocks(dir: string, out: string[]): void {* Test-only: clear the held-locks tracking set without unlinking. Used* to keep cross-test state from leaking when a test deliberately* leaves a lock on disk for the next test to discover.+ *+ * The leading underscore is this repo's marker for a test-only export,+ * which is exactly what the rule below flags - same disable as+ * `search/benchmark.ts` uses for `_benchmarkQueryPeakForTests`.*/+// oxlint-disable-next-line no-underscore-dangleexport function _resetHeldLocksForTests(): void {heldLocks.clear();}diff --git a/src/core/brain/token-impact.ts b/src/core/brain/token-impact.tsindex b7a1b354..d2589ae4 100644--- a/src/core/brain/token-impact.ts+++ b/src/core/brain/token-impact.ts@@ -7,18 +7,31 @@* telemetry (`recall-telemetry.ts`, `gate-telemetry.ts`), but it could not* answer the core value-of-memory question: "how many prompt tokens did the* memory layer actually keep out of (or add to) the agent call?". This- * surface is the durable ledger that measures exactly that.+ * surface is the durable ledger for exactly that question.** TWO STRICTLY SEPARATED LEDGERS, never conflated into one headline number:*- * 1. EXACT prompt-token delta - the real, measured token cost the memory- * layer contributed. `delta_tokens = baseline_tokens - packed_tokens`- * (positive = tokens KEPT OUT of the prompt, negative = tokens ADDED).- * Each sample is labelled `method: "exact" | "fallback"` so a- * tokenizer-exact count (posted by a host that ran a real BPE- * tokenizer) is never silently averaged in with a heuristic- * `estimateTokens` fallback. The summary keeps a per-method split so- * the honesty of the number is always inspectable.+ * 1. Prompt-token delta - the token cost the memory layer contributed.+ * `delta_tokens = baseline_tokens - packed_tokens` (positive = tokens+ * KEPT OUT of the prompt, negative = tokens ADDED).+ *+ * This surface used to label each sample `method: "exact" |+ * "fallback"`, and the `"exact"` was a claim this module is in no+ * position to make. It COUNTS NOTHING: `baseline_tokens` and+ * `packed_tokens` are integers a caller posted, and nothing here+ * verifies where they came from. Calling one of them exact asserted a+ * property of a number the server never saw produced - and this repo+ * has no exact token count to offer anywhere: there is no BPE+ * tokenizer in the tree, only {@link ../brain/text/tokenizer.ts}'s+ * documented `ceil(utf8_bytes / 4)` heuristic.+ *+ * So the vocabulary now names PROVENANCE instead of ACCURACY - see+ * {@link TOKEN_COUNT_METHOD}. A caller genuinely knows whether a+ * tokenizer produced its number; neither the caller nor this module+ * knows whether that number is exact for the model that will read the+ * prompt. The summary keeps the per-method split, so which lane a+ * figure came from stays inspectable; what it no longer does is+ * certify one lane as truth.** 2. MODELED inference-avoidance - a counterfactual estimate of the* inferences (repairs/retries) the memory layer avoided, valued at@@ -57,8 +70,45 @@ import {type ContinuityRecord,} from "./continuity/types.ts";-/** How the prompt-token counts on a sample were obtained. */-export type TokenCountMethod = "exact" | "fallback";+/**+ * How the prompt-token counts on a sample were PRODUCED - never how+ * accurate they are.+ *+ * Both members describe the caller's method, which the caller knows and+ * this module cannot check. Neither asserts that the resulting integer+ * matches what the model receiving the prompt will actually charge; see+ * this module's header for why the former `exact` / `fallback` pair was a+ * claim the ledger had no standing to make.+ */+export const TOKEN_COUNT_METHOD = Object.freeze({+ /** The caller ran a tokenizer and reported its count. */+ tokenizer: "tokenizer",+ /** The caller estimated, e.g. through `estimateTokens`. */+ heuristic: "heuristic",+} as const);++/** Closed union over {@link TOKEN_COUNT_METHOD}. */+export type TokenCountMethod = (typeof TOKEN_COUNT_METHOD)[keyof typeof TOKEN_COUNT_METHOD];++/** Membership list; every surface renders its vocabulary from this array. */+export const TOKEN_COUNT_METHODS: ReadonlyArray<TokenCountMethod> = Object.freeze([+ TOKEN_COUNT_METHOD.tokenizer,+ TOKEN_COUNT_METHOD.heuristic,+]);++/**+ * The labels this vocabulary replaced, mapped to their successors.+ *+ * A ledger written before the rename is on operators' disks right now.+ * Letting the strict guard reject those rows would drop them out of the+ * per-method split while still counting them in the totals - a silent,+ * misleading loss - so the read path translates them explicitly instead.+ * Writes only ever produce the current members.+ */+const LEGACY_TOKEN_COUNT_METHODS: Readonly<Record<string, TokenCountMethod>> = Object.freeze({+ exact: TOKEN_COUNT_METHOD.tokenizer,+ fallback: TOKEN_COUNT_METHOD.heuristic,+});/** First-pass/repair/retry outcome posted to calibrate the modeled ledger. */export type TokenImpactOutcome = "first_pass" | "repair" | "retry";@@ -80,7 +130,7 @@ export interface TokenImpactInput {readonly baselineTokens: number;/** Prompt-token cost the memory layer actually shipped. */readonly packedTokens: number;- /** Whether the counts are tokenizer-exact or a heuristic fallback estimate. */+ /** How the caller produced the counts - provenance, not accuracy. */readonly method: TokenCountMethod;/** Modeled count of inferences (repairs/retries) the layer is estimated to have avoided. */readonly modeledAvoidedInferences?: number;@@ -129,7 +179,7 @@ export interface TokenImpactMethodStats {readonly net_savings_tokens: number;}-/** EXACT-type prompt-token delta ledger (real measurement). */+/** Prompt-token delta ledger over the counts callers posted. */export interface PromptTokenDeltaSummary {readonly total_samples: number;/** Sum of `delta_tokens` over all samples (signed: + kept out, − added). */@@ -141,8 +191,8 @@ export interface PromptTokenDeltaSummary {/** `net_savings_tokens / total_samples`, rounded to 1 dp; 0 for no samples. */readonly mean_savings_tokens: number;readonly by_method: {- readonly exact: TokenImpactMethodStats;- readonly fallback: TokenImpactMethodStats;+ readonly tokenizer: TokenImpactMethodStats;+ readonly heuristic: TokenImpactMethodStats;};}@@ -178,7 +228,21 @@ export interface TokenImpactSummary {}export function isTokenCountMethod(value: unknown): value is TokenCountMethod {- return value === "exact" || value === "fallback";+ return (+ typeof value === "string" && (TOKEN_COUNT_METHODS as ReadonlyArray<string>).includes(value)+ );+}++/**+ * Narrow a method read back off disk or across a tool boundary, accepting+ * the pre-rename labels through {@link LEGACY_TOKEN_COUNT_METHODS}.+ * Returns `null` for anything else - the caller decides what an+ * unclassifiable sample means, rather than being handed a default.+ */+export function normalizeTokenCountMethod(value: unknown): TokenCountMethod | null {+ if (isTokenCountMethod(value)) return value;+ if (typeof value !== "string") return null;+ return LEGACY_TOKEN_COUNT_METHODS[value] ?? null;}export function isTokenImpactOutcome(value: unknown): value is TokenImpactOutcome {@@ -199,7 +263,7 @@ export function emitTokenImpact<G>(): ContinuityRecord | null {return emitGatedTelemetry(gate, () => {if (!isTokenCountMethod(input.method)) {- throw new TypeError("token impact: method must be 'exact' or 'fallback'");+ throw new TypeError(`token impact: method must be one of ${TOKEN_COUNT_METHODS.join(" | ")}`);}const baseline = nonNegativeCount("baseline_tokens", input.baselineTokens);const packed = nonNegativeCount("packed_tokens", input.packedTokens);@@ -235,7 +299,7 @@ export function emitTokenImpact<G>(/*** Record one first-pass/repair/retry outcome (the `/outcome` calibration* hook), gated and fail-open. Used only to calibrate the modeled ledger -- * it never touches the exact prompt-token delta figures.+ * it never touches the prompt-token delta figures.*/export function recordTokenImpactOutcome<G>(vault: string,@@ -313,7 +377,7 @@ export function listTokenImpactOutcomes(/*** Roll the two ledgers up into a single summary that keeps them strictly- * separated: the EXACT prompt-token delta (with a per-method split) and the+ * separated: the prompt-token delta (with a per-method split) and the* MODELED inference-avoidance figure (calibrated by posted outcomes). A* `limit` bounds only the raw list; `maxSamples` bounds aggregation.*/@@ -337,8 +401,8 @@ export function summarizeTokenImpact(let saved = 0;let added = 0;const byMethod = {- exact: { samples: 0, net: 0 },- fallback: { samples: 0, net: 0 },+ tokenizer: { samples: 0, net: 0 },+ heuristic: { samples: 0, net: 0 },};let modeledSamples = 0;let rawModeled = 0;@@ -351,8 +415,10 @@ export function summarizeTokenImpact(if (delta > 0) saved += delta;else if (delta < 0) added += -delta;}- const method = payload["method"];- if (isTokenCountMethod(method) && delta !== null) {+ // Legacy-aware so a pre-rename row is classified rather than dropped+ // from the split while still counting toward the totals.+ const method = normalizeTokenCountMethod(payload["method"]);+ if (method !== null && delta !== null) {byMethod[method].samples += 1;byMethod[method].net += delta;}@@ -376,13 +442,13 @@ export function summarizeTokenImpact(added_tokens: added,mean_savings_tokens: samples.length > 0 ? round1(net / samples.length) : 0,by_method: Object.freeze({- exact: Object.freeze({- samples: byMethod.exact.samples,- net_savings_tokens: byMethod.exact.net,+ tokenizer: Object.freeze({+ samples: byMethod.tokenizer.samples,+ net_savings_tokens: byMethod.tokenizer.net,}),- fallback: Object.freeze({- samples: byMethod.fallback.samples,- net_savings_tokens: byMethod.fallback.net,+ heuristic: Object.freeze({+ samples: byMethod.heuristic.samples,+ net_savings_tokens: byMethod.heuristic.net,}),}),}),@@ -437,7 +503,7 @@ function resolveModeled(return null;}// Partial modeled input would otherwise default the missing field to 0 and- // look like an exact measurement. Require both together; the throw fail-opens+ // look like a measurement. Require both together; the throw fail-opens// to null (emitGatedTelemetry swallows it), matching the "omit, don't invent"// honesty goal stated in this module's header.if (@@ -471,7 +537,12 @@ function matchesFilter(record: ContinuityRecord, filter: TokenImpactFilter): booconst payload = record.payload;if (filter.host !== undefined && payload["host"] !== filter.host) return false;if (filter.packId !== undefined && payload["pack_id"] !== filter.packId) return false;- if (filter.method !== undefined && payload["method"] !== filter.method) return false;+ if (+ filter.method !== undefined &&+ normalizeTokenCountMethod(payload["method"]) !== filter.method+ ) {+ return false;+ }return true;}diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 0df47949..3d399606 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -1399,6 +1399,29 @@ export interface BrainActiveConfig {* Every field is optional; absence falls back to the `LESSONS_*`* defaults in policy.ts.*/+/**+ * Optional `maintenance:` block (t_992f0c33). Vault-side policy for the+ * quiet-window lane, as written in `_brain.yaml`: every field optional,+ * absent meaning "the resolver's default decides".+ */+export interface BrainMaintenanceConfig {+ /**+ * Skip heavy work when the host's one-minute run queue stands at or+ * above this percentage of usable CPU capacity. Absent = the gate is+ * not configured and never fires.+ */+ readonly host_pressure_percent?: number;+ /** Consecutive journaled failures after which a task is refused unforced. */+ readonly failure_streak_limit?: number;+}++/** {@link BrainMaintenanceConfig} with every field decided. */+export interface ResolvedBrainMaintenanceConfig {+ /** `null` = the host-pressure gate is not configured. */+ readonly host_pressure_percent: number | null;+ readonly failure_streak_limit: number;+}+export interface BrainLessonsConfig {/** Exponential half-life of the recency decay, in days. */readonly half_life_days?: number;@@ -1585,6 +1608,14 @@ export interface BrainConfig {* callers fall back to the `LESSONS_*` defaults in policy.ts.*/readonly lessons?: BrainLessonsConfig;+ /**+ * Optional `maintenance:` block (t_992f0c33). Vault-side policy for the+ * quiet-window lane: the host-pressure gate's threshold and the+ * consecutive-failure limit past which a task is refused unforced.+ * Absent: callers fall back to `BRAIN_MAINTENANCE_DEFAULTS` via+ * `resolveMaintenance`, which leaves the pressure gate unconfigured.+ */+ readonly maintenance?: BrainMaintenanceConfig;/** Optional daily discipline-report configuration (§D). Absent when not configured. */readonly discipline_report?: DisciplineReportConfig;/**@@ -1636,6 +1667,12 @@ export interface BrainConfig {* to `BRAIN_HEALTH_DEFAULTS` via `resolveHealth`.*/readonly health?: BrainHealthConfig;+ /**+ * Optional `embeddings:` block. Carries the operator's own record of a+ * decommission announcement for their embedding model, layered over the+ * survey compiled into this build. Absent: the survey answers alone.+ */+ readonly embeddings?: BrainEmbeddingsConfig;/*** Optional `integrity:` block (context-integrity-gates). Chooses where* refusal begins for the owner-scoped delivery filter and the@@ -1873,6 +1910,18 @@ export interface ResolvedBrainTemporalConfig {* remediation step cap. Absent: callers fall back to* `BRAIN_HEALTH_DEFAULTS` via `resolveHealth`.*/+/**+ * Optional `embeddings:` block. The two keys are declared together or not+ * at all - see `policy/blocks/embeddings.ts` for why half a declaration+ * is a refusal rather than a default.+ */+export interface BrainEmbeddingsConfig {+ /** Exact model string the declaration is about. */+ readonly sunset_model?: string;+ /** Announced decommission date, ISO-8601 date or timestamp. */+ readonly sunset_at?: string;+}+export interface BrainHealthConfig {/** Minimum principle jaccard for a contradiction pair. Float in (0, 1]. */readonly contradiction_jaccard?: number;diff --git a/src/core/config.ts b/src/core/config.tsindex ab52faa0..6e77e6a7 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -306,7 +306,11 @@ export interface TimezoneValidationResult {/** Validate an IANA timezone name without normalising or trimming it. */export function validateTimezoneName(name: string): TimezoneValidationResult {try {- new Intl.DateTimeFormat("en-US", { timeZone: name });+ // Constructing the formatter IS the validation - it throws a+ // RangeError on an unknown zone. Called rather than `new`-ed because+ // the instance is discarded either way, and `new` for its side effect+ // reads as an accident.+ Intl.DateTimeFormat("en-US", { timeZone: name });return { ok: true, error: null };} catch (exc) {return { ok: false, error: (exc as Error).message ?? String(exc) };@@ -1024,6 +1028,42 @@ export function resolveHookStrictEnabled(configPath?: string): boolean {);}+/**+ * Env var and config key of the codegraph partner-check switch. Named+ * rather than inlined because the doctor QUOTES them: the line it prints+ * for a check it did not run has to tell the operator which switch turned+ * it off, and a hand-copied spelling there would drift from the one that+ * is actually read.+ */+export const PARTNER_CODEGRAPH_DISABLED_ENV = "OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED";+export const PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled";++/**+ * Codegraph partner-check switch (nothing-runs-unwatched, U12). Default+ * OFF, so `o2b doctor` consults the partner exactly as it always has.+ *+ * It is an env var plus a config key - the shape every other boolean gate+ * in this file takes - rather than a CLI flag, for two reasons. The+ * property being expressed belongs to a MACHINE ("the partner CLI is+ * installed here and asking it costs seconds against a cold HOME"), not to+ * one invocation, so it wants a place to be written down once. And+ * `doctor()` has three callers - the CLI, the MCP `vault_health` tool and+ * the OpenClaw extension - of which a flag would reach one; the other two+ * take no arguments an operator controls.+ *+ * The switch gates the DOCTOR's automatic consultation only. `o2b partner+ * codegraph report` is the operator asking the partner directly, and an+ * answer they asked for is never suppressed by a switch about background+ * cost.+ */+export function resolvePartnerCodegraphDisabled(configPath?: string): boolean {+ return resolveConfigFlag(+ PARTNER_CODEGRAPH_DISABLED_ENV,+ PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY,+ configPath,+ );+}+/*** Knowledge-gap loop gate (recall-trust-and-write-surface, A3 /* t_67d38036). Default OFF: the opt-in session-start gap agenda anddiff --git a/src/core/discipline/decision.ts b/src/core/discipline/decision.tsindex f35be231..b944473e 100644--- a/src/core/discipline/decision.ts+++ b/src/core/discipline/decision.ts@@ -37,6 +37,17 @@ export function transcriptConfirmed(activity: ActivitySummary): boolean {return (activity.transcripts?.totalFiles ?? 0) > 0;}+/**+ * Runtimes whose transcript store exists and could not be enumerated, so+ * their contribution to `totalFiles` is a lower bound rather than a+ * measurement. Separate from {@link transcriptConfirmed} because the two+ * answer opposite questions: one asks whether activity was seen, this one+ * asks whether the looking worked.+ */+export function transcriptsUnreadable(activity: ActivitySummary): ReadonlyArray<string> {+ return activity.transcripts?.unreadableRuntimes ?? [];+}+export type DisciplineStatus = "ok" | "info" | "alert";export function decideStatus(diff --git a/src/core/discipline/render.ts b/src/core/discipline/render.tsindex abf90e24..f4146b72 100644--- a/src/core/discipline/render.ts+++ b/src/core/discipline/render.ts@@ -1,6 +1,11 @@import { escapeMarkdownV2 as e } from "./telegram.ts";import type { BrainEventCounts } from "./log-counts.ts";-import { transcriptConfirmed, type ActivitySummary, type DisciplineStatus } from "./decision.ts";+import {+ transcriptConfirmed,+ transcriptsUnreadable,+ type ActivitySummary,+ type DisciplineStatus,+} from "./decision.ts";export interface RenderInput {readonly localDate: string;@@ -57,13 +62,17 @@ export function renderReport(r: RenderInput): string {const transcripts = r.activity.transcripts;if (transcripts && transcripts.byRuntime.length > 0) {const parts = transcripts.byRuntime- .filter((b) => b.fileCount > 0 || b.detail)+ // A runtime with nothing to say is omitted; one that could not READ its+ // store has something to say precisely because its count is zero.+ .filter((b) => b.fileCount > 0 || b.detail || b.unreadable.length > 0).map((b) => {const base = `${e(b.runtime)}: ${b.fileCount}`;+ const scanned =+ b.unreadable.length > 0 ? `${base} \\[${e(b.scan)}: ${b.unreadable.length}\\]` : base;if (b.detail) {- return `${base} \\(${b.detail.sessionCount} sessions, ${b.detail.messageCount} messages\\)`;+ return `${scanned} \\(${b.detail.sessionCount} sessions, ${b.detail.messageCount} messages\\)`;}- return base;+ return scanned;});if (parts.length > 0) {lines.push(`\\- transcripts — ${parts.join(", ")}`);@@ -84,6 +93,14 @@ export function renderReport(r: RenderInput): string {"_Sub\\-reason: transcript\\-confirmed — runtime session files dated to this window\\._",);}+ // An unread store is not a quiet one. Without this line the alert would+ // present a permissions failure as evidence about the agent's day.+ const unread = transcriptsUnreadable(r.activity);+ if (unread.length > 0) {+ lines.push(+ `_Sub\\-reason: transcript\\-unreadable — ${e(unread.join(", "))}: store present, not enumerable\\._`,+ );+ }if (complexity?.warning === true) {lines.push("_Sub\\-reason: productivity\\-trap — vault structure grew faster than recorded thinking\\._",diff --git a/src/core/discipline/report.ts b/src/core/discipline/report.tsindex 5d908b29..aa2f83b6 100644--- a/src/core/discipline/report.ts+++ b/src/core/discipline/report.ts@@ -85,18 +85,15 @@ export function runDisciplineReport(opts: RunDisciplineReportOpts): DisciplineRe}const vd = vaultDelta(opts.vault, win);- // Per-runtime session-transcript activity (v0.10.11). Hardened: if- // a resolver throws (unreadable home, missing perms), we degrade- // to zero counts rather than failing the whole report.- let transcripts;- try {- transcripts = collectTranscriptActivity({- dayStartMs: win.startUtc.getTime(),- dayEndMs: win.endUtc.getTime(),- });- } catch {- transcripts = { byRuntime: [], totalFiles: 0 };- }+ // Per-runtime session-transcript activity (v0.10.11). A resolver that+ // cannot read a home no longer needs catching here: the aggregator turns+ // it into an `unreadable` scan state on that runtime's row, which is the+ // whole point - degrading to zero counts made a permissions failure look+ // exactly like a quiet day.+ const transcripts = collectTranscriptActivity({+ dayStartMs: win.startUtc.getTime(),+ dayEndMs: win.endUtc.getTime(),+ });const structuralFilesChanged =repo.reduce((total, row) => total + row.git.filesChanged, 0) +diff --git a/src/core/discipline/transcripts/claude-code.ts b/src/core/discipline/transcripts/claude-code.tsindex 47d54672..20084974 100644--- a/src/core/discipline/transcripts/claude-code.ts+++ b/src/core/discipline/transcripts/claude-code.ts@@ -11,41 +11,52 @@ import { existsSync, readdirSync, statSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";-import type { TranscriptRuntime } from "./types.ts";+import {+ classifyTranscriptScan,+ type TranscriptRuntime,+ type TranscriptScanResult,+} from "./types.ts";export const claudeCodeTranscript: TranscriptRuntime = {runtime: "claudecode",agentHint: "claude-vps-agent",- collect(dayStartMs, dayEndMs, home = homedir()): string[] {+ scan(dayStartMs, dayEndMs, home = homedir()): TranscriptScanResult {const base = join(home, ".claude", "projects");- if (!existsSync(base)) return [];- const out: string[] = [];+ const files: string[] = [];+ const unreadable: string[] = [];+ if (!existsSync(base)) return classifyTranscriptScan(false, files, unreadable);+let entries: string[];try {entries = readdirSync(base);} catch {- return [];+ // The store is there; we simply cannot see inside it. Reporting zero+ // files here without saying so is the defect this scan exists to fix.+ unreadable.push(base);+ return classifyTranscriptScan(true, files, unreadable);}- for (const e of entries) {- const projectDir = join(base, e);- let files: string[];+ for (const entry of entries) {+ const projectDir = join(base, entry);+ let projectFiles: string[];try {- files = readdirSync(projectDir);+ projectFiles = readdirSync(projectDir);} catch {+ unreadable.push(projectDir);continue;}- for (const f of files) {- if (!f.endsWith(".jsonl")) continue;- const full = join(projectDir, f);+ for (const name of projectFiles) {+ if (!name.endsWith(".jsonl")) continue;+ const full = join(projectDir, name);try {- const st = statSync(full);- const ms = st.mtimeMs;- if (ms >= dayStartMs && ms < dayEndMs) out.push(full);+ const ms = statSync(full).mtimeMs;+ if (ms >= dayStartMs && ms < dayEndMs) files.push(full);} catch {- // unreadable file — ignore+ // A file whose mtime cannot be read cannot be placed in or out of+ // the window, so it is uncounted rather than assumed absent.+ unreadable.push(full);}}}- return out;+ return classifyTranscriptScan(true, files, unreadable);},};diff --git a/src/core/discipline/transcripts/codex.ts b/src/core/discipline/transcripts/codex.tsindex d583dc33..32a08029 100644--- a/src/core/discipline/transcripts/codex.ts+++ b/src/core/discipline/transcripts/codex.ts@@ -11,22 +11,37 @@ import { existsSync, readdirSync, statSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";-import type { TranscriptRuntime } from "./types.ts";+import {+ classifyTranscriptScan,+ type TranscriptRuntime,+ type TranscriptScanResult,+} from "./types.ts";++/** Subdirectories of `~/.codex/` that have held session files across releases. */+const CANDIDATE_SUBDIRS: ReadonlyArray<string> = Object.freeze([+ "sessions",+ "session",+ "history",+ ".tmp",+]);++const MAX_DEPTH = 3;export const codexTranscript: TranscriptRuntime = {runtime: "codex",agentHint: "codex-vps-agent",- collect(dayStartMs, dayEndMs, home = homedir()): string[] {+ scan(dayStartMs, dayEndMs, home = homedir()): TranscriptScanResult {const base = join(home, ".codex");- if (!existsSync(base)) return [];- const candidates = ["sessions", "session", "history", ".tmp"];- const out: string[] = [];- for (const sub of candidates) {+ const files: string[] = [];+ const unreadable: string[] = [];+ let rootsPresent = false;+ for (const sub of CANDIDATE_SUBDIRS) {const dir = join(base, sub);if (!existsSync(dir)) continue;- pushJsonInRange(dir, dayStartMs, dayEndMs, out, 3);+ rootsPresent = true;+ pushJsonInRange(dir, dayStartMs, dayEndMs, files, unreadable, MAX_DEPTH);}- return out;+ return classifyTranscriptScan(rootsPresent, files, unreadable);},};@@ -34,28 +49,34 @@ function pushJsonInRange(dir: string,dayStartMs: number,dayEndMs: number,- out: string[],+ files: string[],+ unreadable: string[],depth: number,): void {- if (depth < 0) return;+ if (depth < 0) {+ // The walk stopped short of the bottom, so anything below is uncounted.+ unreadable.push(dir);+ return;+ }let entries: import("node:fs").Dirent[];try {entries = readdirSync(dir, { withFileTypes: true });} catch {+ unreadable.push(dir);return;}- for (const e of entries) {- const full = join(dir, e.name);- if (e.isDirectory()) {- pushJsonInRange(full, dayStartMs, dayEndMs, out, depth - 1);+ for (const entry of entries) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) {+ pushJsonInRange(full, dayStartMs, dayEndMs, files, unreadable, depth - 1);continue;}- if (!e.isFile() || !e.name.endsWith(".json")) continue;+ if (!entry.isFile() || !entry.name.endsWith(".json")) continue;try {- const st = statSync(full);- if (st.mtimeMs >= dayStartMs && st.mtimeMs < dayEndMs) out.push(full);+ const ms = statSync(full).mtimeMs;+ if (ms >= dayStartMs && ms < dayEndMs) files.push(full);} catch {- // unreadable — ignore+ unreadable.push(full);}}}diff --git a/src/core/discipline/transcripts/cursor.ts b/src/core/discipline/transcripts/cursor.tsindex 31a36d4f..aa2c181b 100644--- a/src/core/discipline/transcripts/cursor.ts+++ b/src/core/discipline/transcripts/cursor.ts@@ -13,17 +13,26 @@ import { existsSync, readdirSync, statSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";-import type { TranscriptDetail, TranscriptRuntime } from "./types.ts";+import {+ classifyTranscriptScan,+ type TranscriptDetail,+ type TranscriptRuntime,+ type TranscriptScanResult,+} from "./types.ts";-function findDatabases(home: string): string[] {- const roots = [+/** Every layout a Cursor build has used for per-workspace storage. */+function workspaceStorageRoots(home: string): ReadonlyArray<string> {+ return [join(home, ".config", "Cursor", "User", "workspaceStorage"),join(home, "Library", "Application Support", "Cursor", "User", "workspaceStorage"),// macOS XDG-style fallback used by some Cursor buildsjoin(home, ".cursor", "workspaceStorage"),];+}++function findDatabases(home: string): string[] {const out: string[] = [];- for (const root of roots) {+ for (const root of workspaceStorageRoots(home)) {if (!existsSync(root)) continue;let dirs: import("node:fs").Dirent[];try {@@ -114,20 +123,18 @@ function queryCursorDb(export const cursorTranscript: TranscriptRuntime = {runtime: "cursor",agentHint: "cursor-vps-agent",- collect(dayStartMs, dayEndMs, home = homedir()): string[] {- const roots = [- join(home, ".config", "Cursor", "User", "workspaceStorage"),- join(home, "Library", "Application Support", "Cursor", "User", "workspaceStorage"),- // macOS XDG-style fallback used by some Cursor builds- join(home, ".cursor", "workspaceStorage"),- ];- const out: string[] = [];- for (const root of roots) {+ scan(dayStartMs, dayEndMs, home = homedir()): TranscriptScanResult {+ const files: string[] = [];+ const unreadable: string[] = [];+ let rootsPresent = false;+ for (const root of workspaceStorageRoots(home)) {if (!existsSync(root)) continue;+ rootsPresent = true;let dirs: import("node:fs").Dirent[];try {dirs = readdirSync(root, { withFileTypes: true });} catch {+ unreadable.push(root);continue;}for (const d of dirs) {@@ -135,14 +142,14 @@ export const cursorTranscript: TranscriptRuntime = {const db = join(root, d.name, "state.vscdb");if (!existsSync(db)) continue;try {- const st = statSync(db);- if (st.mtimeMs >= dayStartMs && st.mtimeMs < dayEndMs) out.push(db);+ const ms = statSync(db).mtimeMs;+ if (ms >= dayStartMs && ms < dayEndMs) files.push(db);} catch {- // unreadable — ignore+ unreadable.push(db);}}}- return out;+ return classifyTranscriptScan(rootsPresent, files, unreadable);},collectDetail(dayStartMs, dayEndMs, home = homedir()): TranscriptDetail | null {const dbs = findDatabases(home);diff --git a/src/core/discipline/transcripts/index.ts b/src/core/discipline/transcripts/index.tsindex de94e201..91edc383 100644--- a/src/core/discipline/transcripts/index.ts+++ b/src/core/discipline/transcripts/index.ts@@ -12,7 +12,12 @@import { claudeCodeTranscript } from "./claude-code.ts";import { codexTranscript } from "./codex.ts";import { cursorTranscript } from "./cursor.ts";-import type { TranscriptActivity, TranscriptRuntime } from "./types.ts";+import {+ TRANSCRIPT_SCAN,+ type TranscriptActivity,+ type TranscriptRuntime,+ type TranscriptRuntimeActivity,+} from "./types.ts";export { claudeCodeTranscript, codexTranscript, cursorTranscript };export type { TranscriptActivity, TranscriptRuntime };@@ -30,20 +35,45 @@ export interface CollectTranscriptOpts {readonly runtimes?: ReadonlyArray<TranscriptRuntime>;}+/**+ * Run every registered runtime's scan. A runtime that throws is reported as+ * `unreadable` naming the failure, never dropped: the aggregate feeds an+ * alert whose absence of evidence must not be produced by the aggregator+ * itself.+ */export function collectTranscriptActivity(opts: CollectTranscriptOpts): TranscriptActivity {const runtimes = opts.runtimes ?? DEFAULT_TRANSCRIPT_RUNTIMES;- const byRuntime = [];+ const byRuntime: TranscriptRuntimeActivity[] = [];+ const unreadableRuntimes: string[] = [];let total = 0;for (const r of runtimes) {- const files = r.collect(opts.dayStartMs, opts.dayEndMs, opts.home);- const detail = r.collectDetail?.(opts.dayStartMs, opts.dayEndMs, opts.home) ?? null;+ let scan;+ try {+ scan = r.scan(opts.dayStartMs, opts.dayEndMs, opts.home);+ } catch (err) {+ scan = {+ state: TRANSCRIPT_SCAN.unreadable,+ files: [],+ unreadable: [`${r.runtime}: ${(err as Error).message}`],+ };+ }+ let detail = null;+ try {+ detail = r.collectDetail?.(opts.dayStartMs, opts.dayEndMs, opts.home) ?? null;+ } catch {+ // The detail pass is an enrichment of a count that already stands; its+ // failure is reported by the scan state, not by losing the count.+ }byRuntime.push({runtime: r.runtime,- fileCount: files.length,+ fileCount: scan.files.length,+ scan: scan.state,+ unreadable: scan.unreadable,agentHint: r.agentHint,...(detail ? { detail } : {}),});- total += files.length;+ if (scan.unreadable.length > 0) unreadableRuntimes.push(r.runtime);+ total += scan.files.length;}- return { byRuntime, totalFiles: total };+ return { byRuntime, totalFiles: total, unreadableRuntimes };}diff --git a/src/core/discipline/transcripts/types.ts b/src/core/discipline/transcripts/types.tsindex 6adfc09d..1d6bbcf1 100644--- a/src/core/discipline/transcripts/types.ts+++ b/src/core/discipline/transcripts/types.ts@@ -5,7 +5,76 @@* touched on the report's local day. The discipline-report layer* aggregates these into a `TranscriptActivity` summary which feeds* into the alert decision.+ *+ * A scan therefore has to say WHICH emptiness it found. The count feeds an+ * alert whose whole purpose is to notice a day with no recorded work, so+ * "this runtime is not installed", "its store is there and could not be+ * read" and "the agent genuinely did nothing" cannot share one answer: the+ * middle one is the report failing, and reporting it as the last one is the+ * report lying in the direction of reassurance.+ */++/** What a scan of one runtime's transcript store found. */+export const TRANSCRIPT_SCAN = Object.freeze({+ /** At least one transcript file falls in the window. */+ collected: "collected",+ /** The store was read end to end and holds nothing in the window. */+ idle: "idle",+ /** No store for this runtime exists here - it is not installed. */+ rootAbsent: "root_absent",+ /** A directory exists but could not be enumerated; its files are uncounted. */+ unreadable: "unreadable",+} as const);++export type TranscriptScan = (typeof TRANSCRIPT_SCAN)[keyof typeof TRANSCRIPT_SCAN];++export const TRANSCRIPT_SCANS: ReadonlyArray<TranscriptScan> = Object.freeze([+ TRANSCRIPT_SCAN.collected,+ TRANSCRIPT_SCAN.idle,+ TRANSCRIPT_SCAN.rootAbsent,+ TRANSCRIPT_SCAN.unreadable,+]);++export function isTranscriptScan(value: unknown): value is TranscriptScan {+ return typeof value === "string" && (TRANSCRIPT_SCANS as ReadonlyArray<string>).includes(value);+}++/** One runtime's answer: what it found, and what it could not look at. */+export interface TranscriptScanResult {+ readonly state: TranscriptScan;+ /** Absolute paths of transcript files inside the window. */+ readonly files: ReadonlyArray<string>;+ /**+ * Directories that exist but could not be enumerated. Carried even when+ * `state` is `collected`: a partial read that found something still found+ * less than it should have, and the count alone cannot say so.+ */+ readonly unreadable: ReadonlyArray<string>;+}++/**+ * Classify a completed walk. `rootsPresent` is whether ANY of the runtime's+ * candidate store locations exists - false means the runtime is not+ * installed here, which is the one emptiness that is not a finding.*/+export function classifyTranscriptScan(+ rootsPresent: boolean,+ files: ReadonlyArray<string>,+ unreadable: ReadonlyArray<string>,+): TranscriptScanResult {+ const state = !rootsPresent+ ? TRANSCRIPT_SCAN.rootAbsent+ : files.length > 0+ ? TRANSCRIPT_SCAN.collected+ : unreadable.length > 0+ ? TRANSCRIPT_SCAN.unreadable+ : TRANSCRIPT_SCAN.idle;+ return Object.freeze({+ state,+ files: Object.freeze([...files]),+ unreadable: Object.freeze([...unreadable]),+ });+}export interface TranscriptRuntime {readonly runtime: "claudecode" | "codex" | "cursor";@@ -16,11 +85,11 @@ export interface TranscriptRuntime {*/readonly agentHint: string | null;/**- * Return absolute paths of transcript files that show activity- * inside the half-open day window `[dayStartMs, dayEndMs)`.- * `home` is injectable for tests.+ * Walk this runtime's store for transcript files that show activity+ * inside the half-open day window `[dayStartMs, dayEndMs)`, and report+ * which emptiness produced an empty list. `home` is injectable for tests.*/- collect(dayStartMs: number, dayEndMs: number, home?: string): string[];+ scan(dayStartMs: number, dayEndMs: number, home?: string): TranscriptScanResult;collectDetail?(dayStartMs: number, dayEndMs: number, home?: string): TranscriptDetail | null;}@@ -32,6 +101,10 @@ export interface TranscriptDetail {export interface TranscriptRuntimeActivity {readonly runtime: string;readonly fileCount: number;+ /** Which emptiness (or non-emptiness) produced `fileCount`. */+ readonly scan: TranscriptScan;+ /** Directories whose contents are missing from `fileCount`. */+ readonly unreadable: ReadonlyArray<string>;readonly agentHint: string | null;readonly detail?: TranscriptDetail;}@@ -39,4 +112,9 @@ export interface TranscriptRuntimeActivity {export interface TranscriptActivity {readonly byRuntime: ReadonlyArray<TranscriptRuntimeActivity>;readonly totalFiles: number;+ /**+ * Runtimes whose walk hit a directory it could not read, so `totalFiles`+ * is a lower bound for them rather than a measurement.+ */+ readonly unreadableRuntimes: ReadonlyArray<string>;}diff --git a/src/core/doctor-readiness.ts b/src/core/doctor-readiness.tsindex a3ec4391..53068eb1 100644--- a/src/core/doctor-readiness.ts+++ b/src/core/doctor-readiness.ts@@ -13,8 +13,22 @@* stays byte-identical. Each probe reports exactly one member of* {@link READINESS_STATUS} so an unconfigured surface is never mistaken* for a passing one. Every probe runs under a per-check timeout: a probe- * that would hang becomes a `fail` with a "timed out" reason instead of- * blocking the operator.+ * that would hang becomes an `unknown` with a "timed out" reason instead+ * of blocking the operator.+ *+ * That reason used to be a `fail`, and the correction is unit U12 of+ * nothing-runs-unwatched. A probe whose budget elapsed has not found the+ * surface broken; it has found out nothing at all, which is what `unknown`+ * says and what `fail` cannot. The consequence was measurable rather than+ * theoretical: on a loaded machine `o2b doctor --readiness` exited 1 -+ * "this installation is broken" - for the same system that exited 0 when+ * the box was idle, so the verdict was a property of the load average.+ * `search/provider-probe.ts` had already drawn the line one release+ * earlier for the embedding provider: only a surface that ANSWERED with a+ * refusal is a fault, and a budget that elapsed is one of the ways of+ * saying "I could not find out". The same rule now holds here, and an+ * exception escaping a probe body is classified the same way for the same+ * reason - it is evidence about the probe, not about the surface.** That timeout covers a probe that AWAITS. It cannot cover one that blocks* the event loop, because the timer that would fire is queued behind the@@ -98,6 +112,18 @@ export class ReadinessTimeoutError extends Error {* about the probe's own reach, never a guess about the surface. Both* carry a non-empty detail - see {@link runReadinessProbes}, which* enforces it rather than trusting each probe to remember.+ *+ * A budget that elapsed is `unknown`, not a fifth member. `PROVIDER_PROBE`+ * in `search/provider-probe.ts` does spell `timed-out` separately, and the+ * shapes look alike enough to invite copying it - but that vocabulary has+ * no "could not measure" member for it to collapse into, so `timed-out`+ * IS its way of saying that. Here the member already exists, and its+ * meaning - "the probe could not measure; the detail says what stopped+ * it" - is exactly what an elapsed budget reports. A `timed-out` member+ * beside it would be a second spelling of one fact, split by the+ * particular way the measurement was cut short, which every caller would+ * then have to remember to treat identically. The cause is not lost: it is+ * in the detail, which is never empty and which names the budget.*/export const READINESS_STATUS = Object.freeze({/** The probe ran and the surface answered correctly. */@@ -143,11 +169,13 @@ export interface ReadinessReport {/** Count of probes whose status is `fail`. Drives the non-zero exit code. */readonly failed: number;/**- * Count of probes that could not measure. Deliberately NOT folded into- * `failed`: an unmeasured surface is not a broken one, and the doctor's- * uncertain stream sets the precedent that uncertainty is reported and- * excluded from the exit code. It is counted separately so a caller- * cannot read "0 failed" as "everything was checked".+ * Count of probes that could not measure - an unreadable install+ * manifest, an elapsed budget, a probe body that threw. Deliberately NOT+ * folded into `failed`: an unmeasured surface is not a broken one, and a+ * caller must never read "0 failed" as "everything was checked". It is+ * not folded into a silent 0 either - the CLI spends a distinct exit+ * code on it (`DOCTOR_EXIT.probeIncomplete` in `cli/main.ts`), because+ * both silences say something this run did not establish.*/readonly unknown: number;}@@ -521,10 +549,12 @@ export const DEFAULT_PROBES: ReadonlyArray<NamedProbe> = [/*** Run every readiness probe under its per-check timeout and aggregate the- * outcomes. A probe that throws or times out becomes a `fail` with a- * reason rather than aborting the run, so one broken surface never hides- * the others. `probes` is injectable for testing the timeout and- * aggregation paths deterministically; it defaults to {@link DEFAULT_PROBES}.+ * outcomes. A probe that throws or times out becomes an `unknown` with a+ * reason rather than aborting the run, so one unreadable surface never+ * hides the others and none of them is reported as broken on the strength+ * of a measurement that never completed. `probes` is injectable for+ * testing the timeout and aggregation paths deterministically; it defaults+ * to {@link DEFAULT_PROBES}.*/export async function runReadinessProbes(opts: ReadinessOptions,@@ -540,11 +570,14 @@ export async function runReadinessProbes(try {verdict = await withReadinessTimeout(() => probe.fn(opts), timeoutMs, probe.name);} catch (err) {+ // Neither arm has heard from the surface: one budget elapsed, one+ // probe body threw. Both are reported as what they are - a+ // measurement that did not complete - with the cause in the detail.const detail =err instanceof ReadinessTimeoutError- ? `timed out after ${timeoutMs}ms`- : `probe error: ${(err as Error).message}`;- verdict = { status: READINESS_STATUS.fail, detail };+ ? `timed out after ${timeoutMs}ms, so nothing was established about this surface`+ : `probe error, so nothing was established about this surface: ${(err as Error).message}`;+ verdict = { status: READINESS_STATUS.unknown, detail };}return {name: probe.name,diff --git a/src/core/doctor.ts b/src/core/doctor.tsindex a9f5e292..23e73725 100644--- a/src/core/doctor.ts+++ b/src/core/doctor.ts@@ -18,6 +18,7 @@ import {} from "node:fs";import { dirname, join } from "node:path";+import { resolvePartnerCodegraphDisabled } from "./config.ts";import { statOrAbsent } from "./fs-utils.ts";import { checkCodegraph } from "./partner/codegraph.ts";import type { CheckResult } from "./types.ts";@@ -385,12 +386,50 @@ export interface DoctorOptions {readonly cwd?: string;readonly partner?: {readonly codegraph?: {+ /**+ * Turn the partner check off for this call. Left undefined - which+ * is what every caller in the tree passes - the switch is resolved+ * from the operator's environment and config by+ * {@link resolvePartnerCodegraphDisabled}, so the option has a+ * producer for all three callers of {@link doctor} rather than+ * being settable only in principle.+ */readonly disabled?: boolean;readonly scanExtraPaths?: ReadonlyArray<string>;};};}+/**+ * Whether the operator turned the codegraph partner check off.+ *+ * An explicit caller option wins; otherwise the env var / config key pair+ * decides. A config that is PRESENT but unreadable makes that pair+ * unknowable, and this caller absorbs the {@link ConfigReadError} rather+ * than propagating it - the same trade `appendLogEvent` documents for the+ * device id, and for the same reason. `doctor()` exists to REPORT what an+ * install looks like; raising here would destroy the whole report,+ * including the `config_writeable` check that names the unreadable file+ * and prints the chmod that fixes it. The condition is not swallowed+ * anywhere else: every other caller of the config propagates it, the CLI+ * reports it by name, and the doctor's own config check reports it as a+ * failure whenever a config path was given.+ *+ * The fallback is the value that changes nothing - the check runs, exactly+ * as it did before the switch existed - never an invented "disabled" that+ * would silently stop consulting the partner on the strength of a file+ * nobody could read.+ */+function codegraphCheckDisabled(opts: DoctorOptions): boolean {+ const explicit = opts.partner?.codegraph?.disabled;+ if (explicit !== undefined) return explicit;+ try {+ return resolvePartnerCodegraphDisabled(opts.config ?? undefined);+ } catch {+ return false;+ }+}+export function doctor(opts: DoctorOptions): CheckResult[] {const results: CheckResult[] = [];results.push(checkVaultWriteable(opts.vault));@@ -407,7 +446,7 @@ export function doctor(opts: DoctorOptions): CheckResult[] {cwd: opts.cwd ?? process.cwd(),vault: opts.vault,scanExtraPaths: opts.partner?.codegraph?.scanExtraPaths,- disabled: opts.partner?.codegraph?.disabled,+ disabled: codegraphCheckDisabled(opts),});if (cg) results.push(cg);return results;diff --git a/src/core/install/ownership-measure.ts b/src/core/install/ownership-measure.tsnew file mode 100644index 00000000..07dad46b--- /dev/null+++ b/src/core/install/ownership-measure.ts@@ -0,0 +1,181 @@+/**+ * The measuring half of the ownership statement.+ *+ * `ownership.ts` is pure on purpose - the statement a test asserts on is+ * the statement an operator gets - so everything that reads config, env or+ * disk for it lives here, once, for both surfaces that print it (`o2b+ * install` and the onboarding checklist). They used to measure their own+ * inputs separately, which is how one of them could gain a fact the other+ * lacked.+ *+ * Two rules hold every function below:+ *+ * 1. A check that could not run says so. Nothing here rounds a failure+ * down to "not configured": the search config throwing on an+ * out-of-range key used to leave the statement printing an+ * unqualified "nothing to cancel" on the strength of a check that+ * never happened. That case is now `unchecked` with the thrown+ * message, and the statement prints it.+ * 2. Nothing is inferred from a provider NAME. Whether an endpoint is+ * somebody else's is not something a transport kind can answer - an+ * OpenAI-compatible base URL is the documented way to run Ollama on+ * loopback - so the endpoint is resolved and printed, and the+ * sentence says only what is true of both: this tool does not run it.+ */++import { resolveTelegramBotToken } from "../config.ts";+import { pathIsInside, realpathInsideVault } from "../path-safety.ts";+import { resolveResearchPoolEnv } from "../brain/research/research.ts";+import { resolveSearchConfig } from "../search/index.ts";+import type { ResolvedSearchConfig } from "../search/types.ts";+import {+ buildDataOwnership,+ OUTBOUND_SERVICE,+ OUTBOUND_STATE,+ SEARCH_INDEX_LOCATION,+ type DataOwnership,+ type OutboundMeasurement,+ type OutboundServiceId,+ type SearchIndexVerdict,+} from "./ownership.ts";++export interface MeasureDataOwnershipOptions {+ /** The vault as the canonical resolver answered it. */+ readonly vault: string;+ /** Config file to resolve against; the caller's own resolved path. */+ readonly configPath?: string;+ /** Targets the install registry knows, from the caller that owns the registry. */+ readonly adapterTargets: ReadonlyArray<string>;+}++/**+ * There is deliberately no `env` option.+ *+ * `resolveSearchConfig` and `resolveTelegramBotToken` read `process.env`+ * themselves, so an injected environment would reach one of the four+ * checks and not the other three - a record measured against two+ * different environments, reported as one. Tests set `process.env`+ * instead, which is the environment the statement is actually about.+ */++/**+ * Where the index resolved, and whether that is inside the vault.+ *+ * The containment test is the same two-step one every vault write goes+ * through - lexical first, then realpath - because a `.open-second-brain`+ * directory that is itself a symlink out of the vault would pass the+ * lexical half while the file lives elsewhere. A throw from the realpath+ * half is `unchecked`, never "outside": an unreadable ancestor is not+ * evidence of relocation.+ */+function measureSearchIndex(vault: string, dbPath: string): SearchIndexVerdict {+ let inside: boolean;+ try {+ inside = pathIsInside(dbPath, vault) && realpathInsideVault(dbPath, vault);+ } catch (err) {+ return {+ state: SEARCH_INDEX_LOCATION.unchecked,+ path: null,+ reason: `resolving ${dbPath} against the vault failed: ${(err as Error).message}`,+ };+ }+ return {+ state: inside ? SEARCH_INDEX_LOCATION.insideVault : SEARCH_INDEX_LOCATION.outsideVault,+ path: dbPath,+ reason: null,+ };+}++/** `configured` with the endpoint when there is one, `absent` otherwise. */+function present(configured: boolean, endpoint?: string | null): OutboundMeasurement {+ if (!configured) return { state: OUTBOUND_STATE.absent };+ return {+ state: OUTBOUND_STATE.configured,+ ...(endpoint === null || endpoint === undefined || endpoint === ""+ ? {}+ : { endpoint: endpoint }),+ };+}++/** The two integrations the search config decides. */+function searchOutbound(search: ResolvedSearchConfig): {+ readonly embedding: OutboundMeasurement;+ readonly rerank: OutboundMeasurement;+} {+ const semantic = search.semantic;+ // BOTH halves are required, and the enabled half is not decoration:+ // `embedding_provider` defaults to `openai-compat` whether or not+ // semantic search was ever turned on, so a provider-only test announced+ // a configured cloud endpoint on a default install that has never+ // computed an embedding. Nothing leaves this machine until the feature+ // is enabled. Where it then goes is the base URL, which is printed+ // rather than judged - a loopback endpoint is a third party by no+ // definition worth printing.+ const embeddingNetworked =+ semantic.enabled && semantic.provider !== "local" && semantic.provider !== "disabled";+ // The local rerank kind runs the bundled offline model, so only the+ // `openai-compat` kind reaches an endpoint at all.+ const rerankNetworked = search.rerank.enabled && search.rerank.kind === "openai-compat";+ return {+ embedding: present(embeddingNetworked, semantic.baseUrl),+ rerank: present(rerankNetworked, search.rerank.baseUrl),+ };+}++/**+ * Measure every input the statement needs, then compose it.+ *+ * The search config carries two of the four outbound answers AND the index+ * path, so one failure to resolve it leaves three facts unestablished -+ * all three are reported as such rather than defaulted.+ */+export function measureDataOwnership(opts: MeasureDataOwnershipOptions): DataOwnership {+ let search: ResolvedSearchConfig | null = null;+ let searchFailure = "";+ try {+ search = resolveSearchConfig({+ vault: opts.vault,+ ...(opts.configPath === undefined ? {} : { configPath: opts.configPath }),+ });+ } catch (err) {+ searchFailure = `the search config would not resolve: ${(err as Error).message}`;+ }++ const unchecked: OutboundMeasurement = {+ state: OUTBOUND_STATE.unchecked,+ reason: searchFailure,+ };+ const fromSearch =+ search === null ? { embedding: unchecked, rerank: unchecked } : searchOutbound(search);++ let telegram: OutboundMeasurement;+ try {+ telegram = present(resolveTelegramBotToken(opts.configPath) !== null);+ } catch (err) {+ telegram = {+ state: OUTBOUND_STATE.unchecked,+ reason: `the bot token could not be read: ${(err as Error).message}`,+ };+ }++ const research = resolveResearchPoolEnv(process.env);++ const outbound: Record<OutboundServiceId, OutboundMeasurement> = {+ [OUTBOUND_SERVICE.embedding]: fromSearch.embedding,+ [OUTBOUND_SERVICE.rerank]: fromSearch.rerank,+ [OUTBOUND_SERVICE.telegram]: telegram,+ [OUTBOUND_SERVICE.research]: present(+ research.braveApiKey !== null || research.tavilyApiKey !== null,+ ),+ };++ return buildDataOwnership({+ vault: opts.vault,+ searchIndex:+ search === null+ ? { state: SEARCH_INDEX_LOCATION.unchecked, path: null, reason: searchFailure }+ : measureSearchIndex(opts.vault, search.dbPath),+ adapterTargets: opts.adapterTargets,+ outbound,+ });+}diff --git a/src/core/install/ownership.ts b/src/core/install/ownership.tsnew file mode 100644index 00000000..1a23f01b--- /dev/null+++ b/src/core/install/ownership.ts@@ -0,0 +1,773 @@+/**+ * What an operator actually owns, stated without the counterexamples.+ *+ * The sentence this module exists to print is "every memory is a Markdown+ * file in your own vault; copy it elsewhere, delete it and the brain is+ * gone; there is no service to cancel". As written it is FALSE in four+ * places, and a claim with a known counterexample is precisely the+ * misleading output this release removes:+ *+ * 1. The bundled opencode plugin appends raw conversation turns to+ * `~/.local/share/open-second-brain/opencode/`, and nothing prunes+ * them. On a machine using that integration, memory content lives+ * outside the vault.+ * 2. `installation_secret` in the machine config keys the+ * `vault://<hex>` identity every MCP tool returns, so a vault copied+ * without it silently stops resolving those references.+ * 3. The search index can be relocated out of the vault by+ * `OPEN_SECOND_BRAIN_SEARCH_DB` / `search_db_path`.+ * 4. "No service to cancel" is a blanket claim, and it is false for an+ * operator who configured any outbound integration - vault text has+ * been sent to a third party this tool does not manage.+ *+ * So the statement is COMPOSED rather than written, and every clause it+ * prints is either measured at the moment it is printed or worded so that+ * it is true without measuring. Which of the two applies is not left to+ * the reader:+ *+ * MEASURED, per run - the resolved vault path; the filesystem-backing+ * verdict, which is allowed to say `undetermined`; where the search+ * index actually resolved and whether that is inside the vault+ * ({@link SearchIndexVerdict}); and the state of each+ * {@link OUTBOUND_SERVICES} row, which is allowed to say `unchecked`+ * with the reason the check could not run.+ *+ * NOT MEASURED, and therefore worded as a catalogue - {@link+ * OUT_OF_VAULT_STATE}. These rows are printed unconditionally, so the+ * statement says what this tool CAN leave outside the vault and what+ * creates each one, never that any of them is present on this machine.+ * An earlier version printed the same static list under "these N things+ * live outside it", which is a measurement claim the composer never+ * made; the rows now carry {@link OutOfVaultState.created_by} and+ * {@link OutOfVaultState.removed_by} so the reader can settle presence+ * and cleanup per row instead.+ *+ * {@link OUT_OF_VAULT_STATE} is a real list rather than prose because+ * `tests/core/install/ownership.test.ts` sweeps the tree for modules that+ * BUILD a path rooted outside the vault - home, XDG, temp - and demands+ * each be attributed to an entry here or excused in {@link+ * OUT_OF_VAULT_SWEEP_EXCLUSIONS}. It sweeps path construction rather than+ * write calls because a module that computes such a path and hands it to+ * something else to write is invisible to a call-site matcher, and because+ * the write-call form was blind to this repository's own atomic-write+ * helper and to the whole `fs/promises` family. What that sweep still+ * cannot see is enumerated in {@link SOURCES_INVISIBLE_TO_THE_SWEEP}: a+ * location whose root arrives from config, from an env override or from+ * the working directory carries no anchor token to match on.+ *+ * Pure: nothing here reads the environment or the filesystem, except the+ * backing probe when a verdict is not injected. The vault path, the search+ * index verdict, the installable adapter targets and the outbound-service+ * states are all parameters - so the statement a test asserts on is the+ * statement an operator gets. The measuring half lives in+ * `ownership-measure.ts`, once, for both callers.+ */++import { probeVaultBacking, VAULT_BACKING, type VaultBackingVerdict } from "../vault-backing.ts";++// ----- The enumeration ------------------------------------------------------++/** One durable thing that can live outside the vault. */+export interface OutOfVaultState {+ /** Stable slug; the machine-readable handle for this row. */+ readonly id: string;+ /** What it is, as a noun phrase the statement can print. */+ readonly label: string;+ /** Where it lives, written the way an operator would find it. */+ readonly location: string;+ /**+ * True when this location can hold MEMORY CONTENT rather than plumbing.+ * The whole point of the field: the unqualified ownership sentence is+ * false exactly on the rows where this is true.+ */+ readonly carries_memory: boolean;+ /**+ * What has to have happened for this to exist at all.+ *+ * The rows are a catalogue, not a scan, so this field is what keeps the+ * catalogue from reading as a report about this machine: an operator who+ * never ran the command named here knows the row does not apply to them.+ */+ readonly created_by: string;+ /**+ * How the operator removes it.+ *+ * Named per row because `o2b uninstall` removes two of them and nothing+ * else, and a closing sentence that offered one verb for the whole list+ * was the over-claim this field replaces.+ */+ readonly removed_by: string;+ /** Why it is out there, and what its absence costs on a copy. */+ readonly note: string;+ /**+ * Repo-relative modules that own this path. A trailing `/` matches a+ * directory prefix. The census attributes swept path-builders through+ * this field, so an anchor that rots fails a test rather than silently+ * orphaning a location.+ */+ readonly sources: ReadonlyArray<string>;+}++/**+ * The row whose `location` is completed from the live adapter registry.+ * Named so {@link buildDataOwnership} cannot drift from the entry it+ * rewrites.+ */+const RUNTIME_CONFIG_BLOCKS_ID = "runtime_config_blocks";++/**+ * Everything durable this tool can leave outside the vault.+ *+ * Ordered memory-bearing first: the enumeration is read as a correction to+ * the ownership claim, and the correction that matters most is the one+ * that holds conversation text.+ */+export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze([+ {+ id: "opencode_session_spool",+ label: "opencode session spool",+ location:+ "${OSB_OPENCODE_SPOOL_DIR:-${XDG_DATA_HOME:-~/.local/share}}/open-second-brain/opencode/",+ carries_memory: true,+ created_by: "the bundled opencode plugin, on every opencode session it observes",+ removed_by: "deleting that directory yourself - no verb in this tool prunes or removes it",+ note:+ "Raw conversation turns and tool calls, appended by the bundled opencode plugin before " ++ "anything is distilled into the vault. Nothing in this tool prunes them, so on a machine " ++ "using that integration this is memory content living outside your vault.",+ sources: ["plugins/opencode/open-second-brain.ts", "src/core/brain/sessions/opencode.ts"],+ },+ {+ id: "relocated_search_index",+ label: "relocated search index",+ location: "OPEN_SECOND_BRAIN_SEARCH_DB, or the search_db_path config key, when either is set",+ carries_memory: true,+ created_by: "setting either of those, then running `o2b search index`",+ removed_by: "deleting that file; `o2b search index` rebuilds it from the vault",+ note:+ "Derived and rebuildable, so no memory is LOST by deleting it - but with the override " ++ "pointed outside the vault, a copy of every indexed chunk lives at that path. The first " ++ "line above says where this run resolved it.",+ sources: ["src/core/search/paths.ts"],+ },+ {+ id: "machine_config",+ label: "machine-local plugin config",+ location:+ "$OPEN_SECOND_BRAIN_CONFIG, else ${XDG_CONFIG_HOME:-~/.config}/open-second-brain/config.yaml",+ carries_memory: false,+ created_by: "`o2b init`, and any verb that writes a config key",+ removed_by: "`o2b uninstall --apply-local`",+ note:+ "Holds the pointer to this vault, any embedding_api_key, the device_id your log shards are " ++ "attributed to, and the installation_secret that keys every vault://<hex> reference MCP " ++ "tools have already handed out. A vault copied without it keeps every memory and loses " ++ "those references.",+ sources: ["src/core/config.ts"],+ },+ {+ id: "vault_profiles",+ label: "vault profiles registry",+ location: "profiles.json, beside the config file above",+ carries_memory: false,+ created_by: "`o2b vault profile create <name> <vault>`, and `o2b vault profile switch`",+ removed_by: "`o2b uninstall --apply-local`, which removes the directory it sits in",+ note:+ "The name and absolute path of every registered vault, plus which one is active. Deleting " ++ "a vault leaves its entry here.",+ sources: ["src/core/brain/portability/profiles.ts"],+ },+ {+ id: RUNTIME_CONFIG_BLOCKS_ID,+ label: "managed blocks in each agent's own config",+ location: "each installed runtime's own config file",+ carries_memory: false,+ created_by: "`o2b install --target <t> --apply`, once per runtime you install",+ removed_by: "`o2b uninstall --target <t> --apply`",+ note:+ "They point at this vault; they hold none of it. Which runtimes are installed on this " ++ "machine is not read here - `o2b install --check` answers that.",+ sources: ["src/core/install/adapters/", "src/core/install/grok-asset.ts", "src/cli/aider.ts"],+ },+ {+ id: "cli_symlinks",+ label: "CLI symlinks",+ location: "~/.local/bin/o2b, ~/.local/bin/vault-log, ~/.local/bin/o2b-hook",+ carries_memory: false,+ created_by: "`o2b install-cli`",+ removed_by: "`o2b uninstall --remove-cli`",+ note:+ "Re-pointed automatically at SessionStart when a plugin update rotates the checkout they " ++ "name, so they follow the installation rather than rotting with it.",+ sources: ["src/cli/install-cli.ts", "hooks/active-inject.ts"],+ },+ {+ id: "codex_instruction_fence",+ label: "managed instruction fence in Codex's config",+ location: "~/.codex/config.toml",+ carries_memory: false,+ created_by: "`o2b brain protect --target codex`",+ removed_by: "`o2b brain unprotect --target codex`",+ note:+ "The same verb's claudecode target writes inside the vault instead, so this row is about " ++ "the codex target only.",+ sources: ["src/core/brain/protect.ts"],+ },+ {+ id: "hook_reminder_markers",+ label: "hook reminder markers",+ location: "${O2B_REMINDER_STATE_DIR:-$TMPDIR/o2b-reminder-markers}",+ carries_memory: false,+ created_by: "the post-write reminder hook, once per session id",+ removed_by: "the hook itself, which prunes markers older than 48 hours",+ note:+ "One empty file per session id. It records that a reminder was shown; it records nothing " ++ "that was said.",+ sources: ["hooks/post-write-reminder.ts", "plugins/codex/hooks/post-write-reminder.ts"],+ },+ {+ id: "cron_recipe_artifacts",+ label: "cron recipe scripts and their stamps",+ location:+ "~/.local/bin/<job>.sh, plus ${XDG_STATE_HOME:-~/.local/state}/open-second-brain/ for the " ++ "codegraph resync stamp",+ carries_memory: false,+ created_by:+ "you, following a recipe printed by a `--cron-template` verb - this tool installs none of it",+ removed_by: "deleting the script and the stamp, and removing the crontab line yourself",+ note:+ "The recipes are text on stdout: every write in them is a shell command your own crontab " ++ "runs on your own host. Nothing in this tool creates, updates or removes them.",+ sources: [+ "src/cli/cron-recipe.ts",+ "src/cli/partner-codegraph-cron.ts",+ "src/cli/search-cron-template.ts",+ ],+ },+ {+ id: "bench_run_artifacts",+ label: "benchmark run artifacts",+ location: ".open-second-brain/bench-runs, resolved against the working directory",+ carries_memory: false,+ created_by: "`o2b brain bench`, in whichever directory you ran it from",+ removed_by: "deleting that directory yourself",+ note:+ "Written against the CWD rather than the vault - so they are outside it whenever that " ++ "command was run from anywhere else.",+ sources: ["src/cli/brain/verbs/bench.ts"],+ },+]);++/**+ * Modules the out-of-vault sweep finds that leave no location behind, each+ * with the reason it is not a place an operator will ever find state.+ *+ * The sweep enrols every module that BUILDS a path rooted outside the+ * vault, so this map is larger than the write-call version it replaces and+ * covers three shapes: a module that only reads such a path, a module that+ * computes one and hands it to an attributed writer, and a module whose+ * only such path is created and removed inside the call that made it.+ * Anything an operator could still discover on their machine afterwards+ * belongs in {@link OUT_OF_VAULT_STATE} instead, no matter how small.+ */+export const OUT_OF_VAULT_SWEEP_EXCLUSIONS: ReadonlyMap<string, string> = new Map([+ [+ "src/core/brain/snapshot.ts",+ "its only home- or temp-rooted write is an `mkdtempSync` staging directory that the same " ++ "call removes; the archives it stages are written under Brain/.snapshots inside the vault, " ++ "so nothing it creates outlives the run outside the vault",+ ],+ [+ "src/core/search/link-ratchet.ts",+ "its only temp-rooted write is an `mkdtempSync` scratch directory removed by the same call. " ++ "The ratchet state it actually persists lives inside the vault, so this module leaves " ++ "nothing behind on the machine",+ ],+ [+ "src/core/install/ownership.ts",+ "this module IS the enumeration: the home- and XDG-rooted strings in it are the `location` " ++ "fields the statement prints, and it writes nothing at all - it takes the vault, the " ++ "backing verdict and the measurements as parameters and returns text",+ ],+ [+ "src/cli/install/install.ts",+ "the only out-of-vault path it builds is `InstallEnv.home`, which it hands to the adapters; " ++ "every file written from it belongs to the runtime_config_blocks row, and this verb writes " ++ "nothing outside the vault on its own account",+ ],+ [+ "src/cli/install/init-interactive.ts",+ "same shape as the install verb: it resolves the home directory only to build the InstallEnv " ++ "the adapters receive, and the files that appear from it are the runtime_config_blocks row " ++ "written by those adapters",+ ],+ [+ "src/cli/install/uninstall-target.ts",+ "it builds `InstallEnv.home` to REMOVE what an adapter wrote, per that target's install " ++ "manifest. A verb that only deletes cannot add a location an operator will find, and the " ++ "locations it deletes are the runtime_config_blocks row",+ ],+ [+ "src/cli/update.ts",+ "it rebuilds the same `InstallEnv.home` to re-apply existing install targets after a plugin " ++ "update; the files it can change are the runtime_config_blocks row, and it introduces no " ++ "path of its own outside the vault",+ ],+ [+ "src/cli/uninstall.ts",+ "it only removes: the machine-local config directory (the machine_config row, behind a " ++ "name-and-shape guard) and, with --remove-cli, the cli_symlinks row. The home-rooted " ++ "strings in it are the instructions it prints about those two rows",+ ],+ [+ "src/core/doctor-readiness.ts",+ "it reads `process.env['HOME']` only to build the `InstallEnv` each adapter's own `verify` " ++ "is called with, and every probe in it is read-only by contract - the doctor establishes " ++ "state, it never creates any",+ ],+ [+ "src/core/brain/claude-memory-paths.ts",+ "it resolves and safety-checks the `~/.claude/projects/<slug>/memory` directory this tool " ++ "IMPORTS FROM, refusing any path outside it. The import writes into the vault; nothing " ++ "here creates or touches anything under that home-rooted path",+ ],+ [+ "src/core/discipline/transcripts/claude-code.ts",+ "a read-only transcript scanner: it locates the runtime's own session logs under the home " ++ "directory and reads them. The runtime wrote those files and owns them; this module " ++ "creates nothing and deletes nothing there",+ ],+ [+ "src/core/discipline/transcripts/codex.ts",+ "a read-only transcript scanner: it locates the runtime's own session logs under the home " ++ "directory and reads them. The runtime wrote those files and owns them; this module " ++ "creates nothing and deletes nothing there",+ ],+ [+ "src/core/discipline/transcripts/cursor.ts",+ "a read-only transcript scanner: it locates the runtime's own session logs and workspace " ++ "state under the home directory and reads them. The runtime wrote those files and owns " ++ "them; this module creates nothing and deletes nothing there",+ ],+ [+ "src/core/brain/gates/durability.ts",+ "the temp-directory tokens in it are a REFUSAL list: the gate matches a candidate vault path " ++ "against them so a vault on volatile storage is rejected before anything is written. It " ++ "builds no path and writes nothing anywhere",+ ],+ [+ "src/core/brain/secrets/exec.ts",+ "TMPDIR appears in the environment allow-list handed to a spawned command, so the child gets " ++ "a usable temp directory. This module builds no path from it, and what a spawned command " ++ "writes into its own temp directory is that command's business, not a location this tool leaves",+ ],+]);++/**+ * Declared sources of {@link OUT_OF_VAULT_STATE} rows that the sweep+ * cannot enrol, each with the reason its path carries no anchor to match.+ *+ * This map exists because the docblock above claims the census makes a new+ * out-of-vault location impossible to ship unnoticed, and that claim is+ * true only for paths built from a home-, XDG- or temp-rooted token. A+ * root that arrives from a config key, an env override or the working+ * directory looks like any other relative path in the source, so these+ * rows are held true by their own tests and by review, not by the sweep -+ * and saying which is which is the difference between a census and a+ * claim about a census.+ */+export const SOURCES_INVISIBLE_TO_THE_SWEEP: ReadonlyMap<string, string> = new Map([+ [+ "src/core/search/paths.ts",+ "the relocated index path comes from OPEN_SECOND_BRAIN_SEARCH_DB or search_db_path, an " ++ "operator-supplied absolute path; there is no home or XDG token in the source to match on. " ++ "Where it actually resolved IS measured per run and printed on the first line",+ ],+ [+ "src/cli/brain/verbs/bench.ts",+ "the bench directory is a relative path resolved against the working directory, so it carries " ++ "no root token at all. A CWD-rooted write is invisible to this sweep by construction and " ++ "this row is the only one of its kind",+ ],+ [+ "src/core/brain/sessions/opencode.ts",+ "the spool root is read from OSB_OPENCODE_SPOOL_DIR when set; the plugin that writes the " ++ "turns (plugins/opencode/open-second-brain.ts) does carry the XDG token and IS swept, so " ++ "the location is covered even though this reader is not",+ ],+ [+ "src/core/install/grok-asset.ts",+ "it writes through the install env's injected home rather than naming a root itself; the " ++ "adapter directory it belongs to is swept and attributed to the same row, so the location " ++ "is covered by its sibling",+ ],+ [+ "src/core/brain/portability/profiles.ts",+ "the registry is written beside whatever config file it was handed - `dirname(configPath)` - " ++ "so the root arrives as an argument and no home or XDG token appears in the source. The " ++ "config path itself is built by src/core/config.ts, which IS swept",+ ],+ [+ "hooks/active-inject.ts",+ "it re-points the CLI symlinks by calling `healCliSymlinks` in src/cli/install-cli.ts, which " ++ "is swept and attributed to this same row; the hook names no path of its own, so the " ++ "location is covered by the module that builds it",+ ],+ [+ "src/cli/search-cron-template.ts",+ "the script path it recommends is built by src/cli/cron-recipe.ts, which is swept; this " ++ "module only supplies the job name and body, so it names no root of its own",+ ],+]);++// ----- The measured half ----------------------------------------------------++/**+ * Where the search index turned out to be, relative to the vault.+ *+ * A closed vocabulary rather than a boolean because "could not be+ * established" is a real answer and must not be spelled as `false`: the+ * first line of the statement used to assert the index was "in the same+ * vault" with nothing measured at all, two lines above a row saying it may+ * not be.+ */+export const SEARCH_INDEX_LOCATION = Object.freeze({+ insideVault: "inside_vault",+ outsideVault: "outside_vault",+ unchecked: "unchecked",+} as const);++export type SearchIndexLocationState =+ (typeof SEARCH_INDEX_LOCATION)[keyof typeof SEARCH_INDEX_LOCATION];++export interface SearchIndexVerdict {+ readonly state: SearchIndexLocationState;+ /** The resolved path; null exactly when the state is `unchecked`. */+ readonly path: string | null;+ /** Why it could not be established; null exactly when it was. */+ readonly reason: string | null;+}++/**+ * The state of one outbound integration, as this run found it.+ *+ * `unchecked` carries the reason the check could not run, so a config that+ * will not resolve is reported rather than silently reading as "not+ * configured" - the direction that would print an unqualified "nothing to+ * cancel" on the strength of a check that never happened.+ */+export const OUTBOUND_STATE = Object.freeze({+ configured: "configured",+ absent: "absent",+ unchecked: "unchecked",+} as const);++export type OutboundState = (typeof OUTBOUND_STATE)[keyof typeof OUTBOUND_STATE];++/**+ * The id of every outbound integration this build has.+ *+ * Spelled as a frozen literal map rather than read back off+ * {@link OUTBOUND_SERVICES} so the ids stay a UNION rather than widening+ * to `string`: it is that union which makes {@link+ * DataOwnershipInput.outbound} a total record, and a total record is what+ * stops a fifth integration shipping unmeasured.+ */+export const OUTBOUND_SERVICE = Object.freeze({+ embedding: "embedding_provider",+ rerank: "cross_encoder_rerank",+ telegram: "telegram_capture",+ research: "web_research",+} as const);++/** The id of every row in {@link OUTBOUND_SERVICES}, as a union. */+export type OutboundServiceId = (typeof OUTBOUND_SERVICE)[keyof typeof OUTBOUND_SERVICE];++/** One integration that sends data off this machine once it is configured. */+export interface OutboundService {+ readonly id: OutboundServiceId;+ /** What it is, as the statement prints it. */+ readonly label: string;+ /** What leaves this machine when it is on. */+ readonly sends: string;+ /** The settings that turn it on, named so the operator can find them. */+ readonly settings: string;+}++/**+ * Every outbound integration in this build, as the statement checks them.+ *+ * The blanket "no account, no server, no sync endpoint: nothing to cancel"+ * was qualified by exactly one of these before, so an operator running the+ * cross-encoder reranker - which POSTs the query AND the candidate+ * document text under an API key - read a printed inventory that did not+ * include it. Each row here is measured per run, and the statement says+ * that these are the ones it checked rather than that they are everything+ * that could ever be wired up.+ */+export const OUTBOUND_SERVICES: ReadonlyArray<OutboundService> = Object.freeze([+ {+ id: OUTBOUND_SERVICE.embedding,+ label: "networked embedding endpoint",+ sends: "the text of every indexed chunk, and every semantic query",+ settings: "embedding_provider / embedding_base_url",+ },+ {+ id: OUTBOUND_SERVICE.rerank,+ label: "cross-encoder reranker",+ sends: "each query and the full text of the candidate documents it ranks",+ settings: "search_rerank_enabled / search_rerank_base_url / search_rerank_env_key",+ },+ {+ id: OUTBOUND_SERVICE.telegram,+ label: "Telegram capture bot",+ sends:+ "long-polling requests carrying your bot token, and it captures messages that have " ++ "already passed through Telegram's servers",+ settings: "TELEGRAM_BOT_TOKEN / telegram_bot_token",+ },+ {+ id: OUTBOUND_SERVICE.research,+ label: "web research providers",+ sends: "the search queries the research verbs issue, to whichever provider key is set",+ settings: "TAVILY_API_KEY / BRAVE_API_KEY",+ },+]);++/** One outbound row plus the state this run measured for it. */+export interface OutboundServiceStatus extends OutboundService {+ readonly state: OutboundState;+ /** Why the check could not run; null unless the state is `unchecked`. */+ readonly reason: string | null;+ /** The resolved endpoint, when there was one to resolve; null otherwise. */+ readonly endpoint: string | null;+}++// ----- The composed statement ----------------------------------------------++export interface DataOwnershipInput {+ /** The vault as the canonical resolver answered it, never a raw config key. */+ readonly vault: string;+ /** Where the search index resolved, measured by the caller. */+ readonly searchIndex: SearchIndexVerdict;+ /** Targets the install registry knows, so a new adapter is covered by construction. */+ readonly adapterTargets: ReadonlyArray<string>;+ /**+ * One entry per {@link OUTBOUND_SERVICES} row. A total record rather+ * than a partial one: a fifth integration added to that catalogue stops+ * every caller compiling until it is measured too, which is the property+ * that kept the old single-boolean version from ever being noticed.+ */+ readonly outbound: Readonly<Record<OutboundServiceId, OutboundMeasurement>>;+ /** Injected for tests; probed from {@link vault} when omitted. */+ readonly backing?: VaultBackingVerdict;+}++/** What a caller measured about one outbound integration. */+export interface OutboundMeasurement {+ readonly state: OutboundState;+ /** Required when the state is `unchecked`; ignored otherwise. */+ readonly reason?: string;+ /**+ * The endpoint the configured integration talks to, when the caller+ * resolved one.+ *+ * Printed instead of classifying the host, because classifying it is+ * where the previous version went wrong in the other direction: the+ * provider KIND was read as proof of a third party, so an+ * OpenAI-compatible server on the operator's own loopback address was+ * announced as an account they neither own nor cancel. Naming the+ * endpoint and saying this tool does not run it is true either way, and+ * the operator can see which case they are in.+ */+ readonly endpoint?: string;+}++/**+ * The machine-readable half. It is the same value the human sentence is+ * rendered from - see {@link renderDataOwnership} - so the two surfaces+ * cannot be added separately, which is how the install verb's JSON and+ * human outputs drifted before anything tested either.+ */+export interface DataOwnership {+ readonly vault: string;+ readonly backing: VaultBackingVerdict;+ readonly search_index: SearchIndexVerdict;+ readonly outside_vault: ReadonlyArray<OutOfVaultState>;+ readonly outbound_services: ReadonlyArray<OutboundServiceStatus>;+}++/** Fill the adapter-derived row from the live registry. */+function withAdapterTargets(+ entry: OutOfVaultState,+ targets: ReadonlyArray<string>,+): OutOfVaultState {+ if (entry.id !== RUNTIME_CONFIG_BLOCKS_ID || targets.length === 0) return entry;+ // "installable" rather than "installed": this is the registry's target+ // list, which says what this build CAN write a block into. Reading it as+ // the set of runtimes that hold one is exactly the over-claim the row's+ // `created_by` now prevents.+ return {+ ...entry,+ location: `${entry.location} (installable targets: ${[...targets].toSorted().join(", ")})`,+ };+}++/** Attach the measured state to each outbound row, in catalogue order. */+function outboundStatuses(+ measured: Readonly<Record<OutboundServiceId, OutboundMeasurement>>,+): ReadonlyArray<OutboundServiceStatus> {+ return OUTBOUND_SERVICES.map((service) => {+ const m = measured[service.id];+ return {+ ...service,+ state: m.state,+ reason: m.state === OUTBOUND_STATE.unchecked ? (m.reason ?? UNCHECKED_WITHOUT_REASON) : null,+ endpoint: m.endpoint ?? null,+ };+ });+}++/**+ * What an `unchecked` state says when its caller supplied no reason.+ *+ * Not an empty string and not a silent drop to "not configured": a check+ * that did not run is the one state this statement must never round down,+ * so a caller that forgets the reason still prints a sentence the operator+ * can act on.+ */+const UNCHECKED_WITHOUT_REASON = "the check did not run and reported no reason";++export function buildDataOwnership(input: DataOwnershipInput): DataOwnership {+ return {+ vault: input.vault,+ backing: input.backing ?? probeVaultBacking(input.vault),+ search_index: input.searchIndex,+ outside_vault: OUT_OF_VAULT_STATE.map((entry) =>+ withAdapterTargets(entry, input.adapterTargets),+ ),+ outbound_services: outboundStatuses(input.outbound),+ };+}++/**+ * What the backing verdict lets the statement say about survival.+ *+ * Exhaustive over {@link VaultBackingState} with no default arm: a fifth+ * state added to that vocabulary fails this file to build rather than+ * inheriting whichever sentence happened to be the fallback.+ */+function survivalLine(backing: VaultBackingVerdict): string {+ switch (backing.state) {+ case VAULT_BACKING.durable:+ return `That path is on ${backing.filesystem}, which survives this process and a reboot.`;+ case VAULT_BACKING.volatile:+ return (+ `That path is on ${backing.filesystem}, which is memory-backed: everything in it is ` ++ "gone at reboot. Move the vault to disk before you rely on it."+ );+ case VAULT_BACKING.layered:+ return (+ `That path is on ${backing.filesystem}, a container union mount. Whether it survives ` ++ "this container exiting is not something the host reports, so treat it as unproven."+ );+ case VAULT_BACKING.undetermined:+ return (+ `Whether that path survives this process could not be established: ${backing.detail}. ` ++ "This is stated rather than assumed either way."+ );+ }+}++/**+ * What the measured index location lets the statement say about the index.+ *+ * Exhaustive over {@link SearchIndexLocationState} with no default arm,+ * for the reason {@link survivalLine} has none: the clause this replaces+ * asserted the inside-the-vault arm unconditionally.+ */+function searchIndexLine(index: SearchIndexVerdict): string {+ switch (index.state) {+ case SEARCH_INDEX_LOCATION.insideVault:+ return (+ `The search index is at ${index.path}, inside that vault: a rebuildable SQLite file ` ++ "that travels with a copy of it."+ );+ case SEARCH_INDEX_LOCATION.outsideVault:+ return (+ `The search index is NOT in that vault - it resolved to ${index.path}. It is derived ` ++ "and rebuildable, so no memory is lost by leaving it behind, but a copy of the vault " ++ "does not include it and a copy of every indexed chunk stays at that path."+ );+ case SEARCH_INDEX_LOCATION.unchecked:+ return (+ `Where the search index lives could not be established: ${index.reason}. It is normally ` ++ "inside the vault and can be relocated by OPEN_SECOND_BRAIN_SEARCH_DB or search_db_path, " ++ "so this run cannot tell you which is the case."+ );+ }+}++/** What one outbound row says once its state is known. */+function outboundLine(service: OutboundServiceStatus): string {+ switch (service.state) {+ case OUTBOUND_STATE.configured:+ return (+ `${service.label}: CONFIGURED (${service.settings}) - it sends ${service.sends}` ++ `${service.endpoint === null ? "" : `, to ${service.endpoint}`}. This tool does not run ` ++ "that endpoint and cannot cancel it for you."+ );+ case OUTBOUND_STATE.absent:+ return `${service.label}: not configured (${service.settings})`;+ case OUTBOUND_STATE.unchecked:+ return `${service.label}: NOT CHECKED - ${service.reason} (${service.settings})`;+ }+}++/**+ * Render the statement an operator reads.+ *+ * This is the ONE place the structured value becomes prose, following+ * `renderRuntimeNotices`: the machine-readable field and the sentence a+ * person reads are two views of one record rather than two hand-written+ * copies.+ */+export function renderDataOwnership(ownership: DataOwnership): string {+ const carriers = ownership.outside_vault.filter((e) => e.carries_memory);+ const lines: string[] = [+ "Your data, and where it is:",+ ` Your brain is ${ownership.vault}. Every memory this tool writes is a Markdown file under it.`,+ ` ${searchIndexLine(ownership.search_index)}`,+ ` ${survivalLine(ownership.backing)}`,+ "",+ " Nothing here is a subscription: this tool has no account of its own, no server it phones home to, no sync endpoint and no update check. What can send your text off this machine is an integration you configure, and these are the ones this run checked:",+ ];+ for (const service of ownership.outbound_services) {+ lines.push(` - ${outboundLine(service)}`);+ }+ lines.push(+ " That is what was checked, not a proof that nothing else can reach the network: anything you wire up yourself - your own MCP server, your own hook - is outside what this statement can see.",+ );+ lines.push(+ "",+ ` Copy the vault and the memory in it goes with the copy. This tool can also leave ${ownership.outside_vault.length} kinds of state OUTSIDE the vault, which never travel in a copy. What follows is the catalogue of what it can leave - not a scan of this machine - so each row says what creates it and what removes it:`,+ );+ for (const entry of ownership.outside_vault) {+ lines.push(` - ${entry.label} — ${entry.location}`);+ lines.push(` created by: ${entry.created_by}`);+ lines.push(` removed by: ${entry.removed_by}`);+ lines.push(` ${entry.note}`);+ }+ if (carriers.length > 0) {+ lines.push(+ "",+ ` ${carriers.length} of those can hold memory content rather than plumbing, which is why the first line says what this tool WRITES rather than everything you have ever said to it.`,+ );+ }+ lines.push(+ "",+ ` Deleting the vault deletes every memory inside it, and nothing else. It does not touch the ${ownership.outside_vault.length} kinds of state above - ${carriers.length} of which can hold memory content - and no single verb removes them all: each row names the one that removes it.`,+ "",+ );+ return lines.join("\n");+}diff --git a/src/core/maintenance/ensure-current.ts b/src/core/maintenance/ensure-current.tsindex 0765a4b9..abd82b97 100644--- a/src/core/maintenance/ensure-current.ts+++ b/src/core/maintenance/ensure-current.ts@@ -25,13 +25,33 @@ import { planUpgrade, applyUpgrade } from "../brain/upgrade.ts";import { resolveSearchConfig } from "../search/index.ts";import { reindexVault } from "../search/indexer.ts";import { LATEST_SCHEMA_VERSION, readSchemaVersion } from "../search/schema.ts";+import { isWriterLockHeld } from "../search/store/writer-lock.ts";import type { ResolvedSearchConfig } from "../search/types.ts";+import {+ mintSelfHealRunId,+ recordSelfHealSpawn,+ SELF_HEAL_SPAWN,+ type SelfHealSpawnDecision,+} from "./self-heal-reindex.ts";++/**+ * The flag that tells the child to record its own terminal outcome. It+ * takes the run id this run's rows pair on, so the child never has to+ * invent one the parent could not have written.+ */+const SELF_HEAL_FLAG = "--self-heal";export interface EnsureCurrentResult {/** Vault-relative paths of Brain managed files migrated this run. */readonly brainUpgraded: ReadonlyArray<string>;/** A search reindex was started (background) or completed (foreground). */readonly reindexTriggered: boolean;+ /**+ * In `background` mode, what was done about a reindex this run found+ * necessary. `null` when none was needed, or when the run was in the+ * foreground and there was no child to decide about.+ */+ readonly reindexSpawn: SelfHealSpawnDecision | null;/** Non-empty when nothing ran, e.g. "not-initialized". */readonly skipped: string;/** Best-effort: per-step failures, never thrown. */@@ -80,14 +100,88 @@ function o2bScriptPath(): string {}/**- * Start a reindex without blocking. Spawns a detached `o2b search reindex` so- * it survives a short-lived caller (e.g. a SessionStart hook process), and- * does not tie up a long-lived one (the MCP server). `reindexVault` is- * lock-guarded, so a concurrent rebuild is serialised, not duplicated.+ * Start a reindex without blocking, unless the writer lock is already held.+ *+ * Spawns a detached `o2b search reindex` so the rebuild survives a+ * short-lived caller (a SessionStart hook process) and does not tie up a+ * long-lived one (the MCP server).+ *+ * ## The probe is advisory, and this is not mutual exclusion+ *+ * A schema bump makes every session that starts afterwards find the index+ * stale at once, so N sessions used to spawn N children; one took the lock+ * and the rest spun three seconds and died with their stderr pointed at+ * nothing. {@link isWriterLockHeld} is checked FIRST so a child that can+ * already be seen to lose is never started.+ *+ * That check is a read of an instant, not a claim on it. Two callers can+ * both find the lock free and both spawn - the window between the probe and+ * the child's own `acquireWriterLock` is not closed by anything here, and+ * closing it would mean holding the lock across a spawn, which would hand a+ * detached child a lock its parent owns. `reindexVault`'s lock remains the+ * only exclusion in the system; this only thins the herd, and the loser of+ * a real race now records why it lost.+ *+ * ## How wide that window is, measured, and what the probe therefore buys+ *+ * The window is a cold Bun start plus module load, flag parse and config+ * resolution before `reindexVault` reaches its lock. Measured on a 400-note+ * vault, spawn to lock-held was 710, 753, 723, 737, 710 ms over five runs.+ * So the probe thins NOTHING among callers that probe inside those ~0.7 s:+ * four parents released from one barrier all found the lock free and all+ * spawned (measured 4/4).+ *+ * What it does buy is every caller that arrives AFTER a child has the lock,+ * and on a real vault that is most of them: a rebuild that takes minutes is+ * a minutes-long window in which each new `SessionStart` / `PostCompact`+ * hook is a caller that now starts nothing (measured: a parent 1.5 s behind+ * the first records `skipped_writer_lock`). The simultaneous burst this+ * module's opening paragraph describes is exactly the case it does not+ * help; closing that one needs a claim the parent can make before the+ * spawn, which is a lock with its own staleness policy, not a probe.+ * `tests/core/maintenance/self-heal-reindex.test.ts` pins both halves.+ *+ * The child's streams stay ignored: it is detached and there is no terminal+ * to write to. Its terminal outcome goes to the `self_heal_reindex` metrics+ * surface instead, which `--self-heal <run-id>` arms - the same run id this+ * function records on the spawn row, so the two rows pair without a pid;+ * see `self-heal-reindex.ts` for why the parent cannot record the outcome.*/-function spawnDetachedReindex(vault: string, configPath: string): void {+function startSelfHealReindex(+ vault: string,+ configPath: string,+ dbPath: string,+ errors: string[],+): SelfHealSpawnDecision {+ let lockHeld = false;+ try {+ lockHeld = isWriterLockHeld(dbPath);+ } catch (e) {+ // The probe could not answer. That is reported, not swallowed - and+ // the spawn goes ahead anyway: declining to self-heal because a stat+ // failed would leave a stale index behind with nobody told, while a+ // child that turns out to lose the race now records why.+ errors.push(`writer-lock-probe: ${message(e)}`);+ }+ if (lockHeld) {+ recordSelfHealSpawn(vault, SELF_HEAL_SPAWN.skippedWriterLock);+ return SELF_HEAL_SPAWN.skippedWriterLock;+ }+ // Minted BEFORE the spawn: it is what the child is told to write on its+ // own terminal row, so the pair exists whichever process writes first.+ const runId = mintSelfHealRunId();const proc = Bun.spawn(- [o2bScriptPath(), "search", "reindex", "--vault", vault, "--config", configPath],+ [+ o2bScriptPath(),+ "search",+ "reindex",+ "--vault",+ vault,+ "--config",+ configPath,+ SELF_HEAL_FLAG,+ runId,+ ],{stdin: "ignore",stdout: "ignore",@@ -95,6 +189,8 @@ function spawnDetachedReindex(vault: string, configPath: string): void {},);proc.unref();+ recordSelfHealSpawn(vault, SELF_HEAL_SPAWN.spawned, runId);+ return SELF_HEAL_SPAWN.spawned;}export async function ensureVaultCurrent(@@ -105,11 +201,18 @@ export async function ensureVaultCurrent(const errors: string[] = [];let brainUpgraded: ReadonlyArray<string> = [];let reindexTriggered = false;+ let reindexSpawn: SelfHealSpawnDecision | null = null;// Only an already-initialised vault is an upgrade target. A missing// `_brain.yaml` means "not set up yet" - that is `o2b init`'s job, not ours.if (!existsSync(brainConfigPath(vault))) {- return { brainUpgraded: [], reindexTriggered: false, skipped: "not-initialized", errors: [] };+ return {+ brainUpgraded: [],+ reindexTriggered: false,+ reindexSpawn: null,+ skipped: "not-initialized",+ errors: [],+ };}// 1. Brain managed-file upgrade - idempotent; only when changes are pending@@ -128,16 +231,19 @@ export async function ensureVaultCurrent(const configPath = opts.configPath ?? defaultConfigPath();const config = resolveSearchConfig({ vault, configPath });if (indexNeedsRebuild(config)) {- reindexTriggered = true;if (background) {- spawnDetachedReindex(vault, configPath);+ reindexSpawn = startSelfHealReindex(vault, configPath, config.dbPath, errors);+ // A run that declined to spawn started nothing, and saying it did+ // would report a rebuild that is not this run's.+ reindexTriggered = reindexSpawn === SELF_HEAL_SPAWN.spawned;} else {await reindexVault(config);+ reindexTriggered = true;}}} catch (e) {errors.push(`search-reindex: ${message(e)}`);}- return { brainUpgraded, reindexTriggered, skipped: "", errors };+ return { brainUpgraded, reindexTriggered, reindexSpawn, skipped: "", errors };}diff --git a/src/core/maintenance/self-heal-reindex.ts b/src/core/maintenance/self-heal-reindex.tsnew file mode 100644index 00000000..d9156dd3--- /dev/null+++ b/src/core/maintenance/self-heal-reindex.ts@@ -0,0 +1,254 @@+/**+ * What became of the detached post-upgrade reindex.+ *+ * `ensureVaultCurrent(vault, { background: true })` runs at every full-scope+ * MCP server start and at every `SessionStart` / `PostCompact` hook. After a+ * schema bump, N concurrent agent sessions therefore each spawn a detached+ * `o2b search reindex` with `stdin/stdout/stderr: "ignore"`; one takes the+ * writer lock and the rest fast-fail on it. With no terminal attached and no+ * parent waiting - the child is `unref`ed precisely so it cannot hold a+ * session open - the losers' `INDEX_LOCKED` went nowhere any operator could+ * ever read.+ *+ * ## Why the metrics surface, and not the maintenance journal+ *+ * `src/core/brain/metrics.ts` already declares exactly this contract: one+ * append-only JSONL file per surface, records that are RUN-LEVEL - "one per+ * index run" in its own words - written as single O_APPEND lines so+ * concurrent writers interleave instead of racing a rewrite. A self-heal is+ * an index run, the herd is a set of concurrent writers, and no lock is+ * taken to record a row, so a hook process is never slowed or blocked by+ * one. The maintenance journal+ * (`src/core/brain/maintenance/journal.ts`) was the alternative and does not+ * fit: its rows carry a lease `holder` and a lane `task`, and its verdict+ * vocabulary is closed over the quiet-window lane's gates. Neither is a+ * thing this run has.+ *+ * ## Two rows, and what the pair means+ *+ * The parent records its SPAWN DECISION; the child records its own TERMINAL+ * OUTCOME, because nothing survives to await it. They pair on a RUN ID the+ * parent mints before the spawn and hands to the child on its command line+ * ({@link mintSelfHealRunId}, `o2b search reindex --self-heal <run-id>`).+ *+ * The pid was the obvious pairing key and is the wrong one. A pid is+ * machine-local, which this module forbids on a row two paragraphs down,+ * and it is not even unique on one host: pids are reused, so over the life+ * of a vault a peer's `{decision: spawned, pid: 4242}` and this device's+ * `{outcome: completed, pid: 4242}` pair up and report a vanished child as+ * a finished one. A run id identifies a RUN rather than a process, so it+ * collides with nothing and stays true wherever the row is read.+ *+ * ## What an unpaired spawn row proves, and what it does not+ *+ * A spawn row with no terminal row beside it means exactly one thing: no+ * terminal outcome was recorded for that run. Four states produce it, and+ * only the first is the one the pair was built to catch:+ *+ * 1. the child vanished - SIGKILL, OOM, a host that reaped the session's+ * process group - which is the one failure no in-child recording can+ * report about itself;+ * 2. the child is STILL RUNNING; a full reindex of a real vault takes+ * minutes and looks identical to (1) for that whole window - the+ * row's `runAt` is the only bound on how long it has been going;+ * 3. the child died before it could arm the recording - `parseFlags`+ * refused its argv, or (only when no `--vault` reached it) its+ * configuration would not resolve. Everything after that point is+ * recorded: {@link recordSelfHealOutcome} is called on the config+ * failure path too;+ * 4. the child ran and its own {@link append} failed - a read-only+ * vault, a full disk. That is deliberate (observability never fails+ * the pass it observes) and it is indistinguishable from (1) by+ * construction.+ *+ * A child that never started is distinguishable and correctly so: `Bun.spawn`+ * throwing means no row of either kind is written and the caller's `errors`+ * carries the reason.+ *+ * The rows live under `Brain/`, which is synced across devices, while the+ * index they describe is per-device and rebuildable. So a row states that a+ * self-heal ran on SOME device, never that this device's index is stale;+ * the authority on that is the index's own `schema_version`. Nothing+ * machine-local is written into a row - no db path, no host, no pid -+ * because a synced vault carries it to peers where it is false.+ */++import { randomUUID } from "node:crypto";++import { appendMetric, listMetrics } from "../brain/metrics.ts";++/** Metrics surface these rows are appended to. */+export const SELF_HEAL_REINDEX_SURFACE = "self_heal_reindex";++/**+ * What the parent did about a reindex it found necessary.+ *+ * Separate from {@link SELF_HEAL_REINDEX_OUTCOME} because the two answer+ * different questions in different processes - whether a child was started,+ * and what a started child ended as - and a guard that accepted both would+ * let a refusal to start be read back as a run that finished.+ */+export const SELF_HEAL_SPAWN = Object.freeze({+ /** A detached child was started; its pid is on the row. */+ spawned: "spawned",+ /** Another writer already held the index lock, so nothing was started. */+ skippedWriterLock: "skipped_writer_lock",+} as const);++/** Closed union over {@link SELF_HEAL_SPAWN}. */+export type SelfHealSpawnDecision = (typeof SELF_HEAL_SPAWN)[keyof typeof SELF_HEAL_SPAWN];++/** Membership list, in declaration order. */+export const SELF_HEAL_SPAWN_DECISIONS: ReadonlyArray<SelfHealSpawnDecision> = Object.freeze(+ Object.values(SELF_HEAL_SPAWN),+);++/**+ * `unknown` rather than `string`: the value is read back off a JSONL file+ * that a peer device - or an older release - may have written.+ */+export function isSelfHealSpawnDecision(value: unknown): value is SelfHealSpawnDecision {+ return (+ typeof value === "string" &&+ (SELF_HEAL_SPAWN_DECISIONS as ReadonlyArray<string>).includes(value)+ );+}++/** How a spawned child ended. */+export const SELF_HEAL_REINDEX_OUTCOME = Object.freeze({+ /** The rebuild finished; the index is on the current schema. */+ completed: "completed",+ /** The rebuild threw. The row carries the failure by name. */+ failed: "failed",+} as const);++/** Closed union over {@link SELF_HEAL_REINDEX_OUTCOME}. */+export type SelfHealReindexOutcome =+ (typeof SELF_HEAL_REINDEX_OUTCOME)[keyof typeof SELF_HEAL_REINDEX_OUTCOME];++/** Membership list, in declaration order. */+export const SELF_HEAL_REINDEX_OUTCOMES: ReadonlyArray<SelfHealReindexOutcome> = Object.freeze(+ Object.values(SELF_HEAL_REINDEX_OUTCOME),+);++/** `unknown` for the same reason {@link isSelfHealSpawnDecision} takes it. */+export function isSelfHealReindexOutcome(value: unknown): value is SelfHealReindexOutcome {+ return (+ typeof value === "string" &&+ (SELF_HEAL_REINDEX_OUTCOMES as ReadonlyArray<string>).includes(value)+ );+}++/**+ * Mint the id the two rows of one self-heal pair carry.+ *+ * A UUID and not a timestamp-plus-counter: the two rows are written by two+ * processes on a vault that syncs to peers, so the only uniqueness that+ * holds is the kind that needs no coordination. The `sh-` prefix keeps the+ * value self-describing in a JSONL line an operator reads by eye.+ */+export function mintSelfHealRunId(): string {+ return `sh-${randomUUID()}`;+}++/** One row, narrowed. Exactly one of `decision` / `outcome` is non-null. */+export interface SelfHealReindexRow {+ /** ISO-8601 UTC instant the row describes. */+ readonly runAt: string;+ /** Set on the parent's spawn-decision rows. */+ readonly decision: SelfHealSpawnDecision | null;+ /** Set on the child's terminal rows. */+ readonly outcome: SelfHealReindexOutcome | null;+ /** What the two rows of one run pair on; `null` when no child was started. */+ readonly runId: string | null;+ /** How long the child ran; `null` on a parent row. */+ readonly durationMs: number | null;+ /** The failure, by name; `null` on every row that is not a failure. */+ readonly error: string | null;+}++/**+ * Record the parent's spawn decision. Fail-soft: a metrics-layer problem+ * must never take down a server start or a hook, which is the whole reason+ * this call sits on the startup path at all.+ */+export function recordSelfHealSpawn(+ vault: string,+ decision: SelfHealSpawnDecision,+ runId: string | null = null,+): void {+ append(vault, {+ decision,+ ...(runId === null ? {} : { run_id: runId }),+ });+}++/**+ * Record a child's terminal outcome. Called BY THE CHILD, in its own+ * process, because the parent `unref`ed it and is long gone; `runId` is the+ * one the parent minted and passed on the command line, which is what makes+ * this row the answer to that parent's spawn row.+ */+export function recordSelfHealOutcome(+ vault: string,+ outcome: SelfHealReindexOutcome,+ runId: string,+ durationMs: number,+ error?: string,+): void {+ append(vault, {+ outcome,+ run_id: runId,+ duration_ms: durationMs,+ ...(error === undefined ? {} : { error }),+ });+}++function append(vault: string, payload: Readonly<Record<string, unknown>>): void {+ try {+ appendMetric(vault, {+ surface: SELF_HEAL_REINDEX_SURFACE,+ runAt: new Date().toISOString(),+ payload,+ });+ } catch {+ // Fail-soft, as everywhere in the metrics layer: observability never+ // fails the pass it observes.+ }+}++/**+ * Rows for `vault`, newest first. A row this build cannot narrow - neither+ * a known decision nor a known outcome - is skipped rather than surfaced as+ * a null-null row that a reader would have to guess about.+ */+export function readSelfHealReindexRows(+ vault: string,+ limit?: number,+): ReadonlyArray<SelfHealReindexRow> {+ const cap = limit === undefined ? Number.POSITIVE_INFINITY : Math.max(0, limit);+ const rows: SelfHealReindexRow[] = [];+ for (const record of listMetrics(vault, { surface: SELF_HEAL_REINDEX_SURFACE })) {+ if (rows.length >= cap) break;+ const payload = record.payload;+ const rawDecision: unknown = payload["decision"];+ const rawOutcome: unknown = payload["outcome"];+ const rawRunId: unknown = payload["run_id"];+ const rawDuration: unknown = payload["duration_ms"];+ const rawError: unknown = payload["error"];+ const decision = isSelfHealSpawnDecision(rawDecision) ? rawDecision : null;+ const outcome = isSelfHealReindexOutcome(rawOutcome) ? rawOutcome : null;+ if (decision === null && outcome === null) continue;+ rows.push(+ Object.freeze({+ runAt: record.run_at,+ decision,+ outcome,+ runId: typeof rawRunId === "string" ? rawRunId : null,+ durationMs: typeof rawDuration === "number" ? rawDuration : null,+ error: typeof rawError === "string" ? rawError : null,+ }),+ );+ }+ return Object.freeze(rows);+}diff --git a/src/core/partner/codegraph-report.ts b/src/core/partner/codegraph-report.tsindex 1038c2fa..9e80436d 100644--- a/src/core/partner/codegraph-report.ts+++ b/src/core/partner/codegraph-report.ts@@ -21,6 +21,7 @@ import {CODEGRAPH_CLI,codegraphInitCommand,defaultRunStatusJson,+ isCodegraphUnanswered,defaultWhichCodegraph,findCodeProjects,type CodegraphStatusResult,@@ -279,6 +280,19 @@ function resolveIndexState(}const runFn = deps?.runStatusJson ?? defaultRunStatusJson;const status = runFn(project);+ if (isCodegraphUnanswered(status)) {+ // `error` is the closest of the five states, and the reason carries+ // what it cannot: the partner was stopped at its deadline rather than+ // having reported anything. What matters is that this is NOT+ // `not_indexed` - the state whose remediation is `codegraph init`,+ // which is the wrong thing to run at a partner that is still going.+ return {+ state: "error",+ reason:+ `${CODEGRAPH_CLI.bin} ${CODEGRAPH_CLI.statusSubcommand} did not answer within ` ++ `${status.waitedMs}ms and was stopped; nothing is claimed here about this index`,+ };+ }if (!status.ok) {return { state: "error", reason: status.error };}diff --git a/src/core/partner/codegraph.ts b/src/core/partner/codegraph.tsindex ee327b22..e838f4af 100644--- a/src/core/partner/codegraph.ts+++ b/src/core/partner/codegraph.ts@@ -15,6 +15,10 @@import { existsSync, readdirSync, realpathSync } from "node:fs";import { dirname, join, resolve } from "node:path";+import {+ PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY,+ PARTNER_CODEGRAPH_DISABLED_ENV,+} from "../config.ts";import type { CheckResult } from "../types.ts";import { isDir, statOrAbsent } from "../fs-utils.ts";import { assessGraphHealth, summarizeGraphHealth } from "./codegraph-health.ts";@@ -169,9 +173,44 @@ export interface CodegraphStatusData {readonly selfLoops?: number;}+/**+ * What asking the partner for one project's status produced.+ *+ * Three arms, not two. `unanswered` is separate from `error` because the+ * two are different facts about the world and only one of them is about+ * the index: a partner that exited non-zero has told us something, and a+ * partner that never returned has told us nothing at all. Collapsing them+ * sends an operator to `codegraph init` over a process that is still+ * running. This is the same distinction `DOCTOR_EXIT.probeIncomplete`+ * draws one release earlier - a probe that did not complete is not a probe+ * that failed.+ */+export interface CodegraphUnanswered {+ readonly ok: false;+ /** Present only on this arm; the field the guard below discriminates on. */+ readonly unanswered: true;+ /** The deadline that expired, in milliseconds, as the message quotes it. */+ readonly waitedMs: number;+}+export type CodegraphStatusResult =| { readonly ok: true; readonly data: CodegraphStatusData }- | { readonly ok: false; readonly error: string };+ | { readonly ok: false; readonly error: string }+ | CodegraphUnanswered;++/**+ * Whether the partner never answered.+ *+ * A guard rather than a `kind` field on all three arms, because the two+ * existing arms are a published shape that tests and the report module+ * build by hand; narrowing on a member unique to the new arm adds the+ * distinction without rewriting what already answers.+ */+export function isCodegraphUnanswered(+ result: CodegraphStatusResult,+): result is CodegraphUnanswered {+ return result.ok === false && "unanswered" in result;+}export interface CodegraphCheckDeps {readonly whichCodegraph?: () => string | null;@@ -183,6 +222,19 @@ export interface CodegraphCheckDeps {* only (see {@link defaultDetectProjectPathSupport}).*/readonly detectProjectPathSupport?: () => boolean;+ /**+ * Deadline for each partner invocation, defaulting to+ * {@link CODEGRAPH_PARTNER_TIMEOUT_MS}.+ *+ * It lives on the deps rather than on {@link CodegraphCheckOptions}+ * because it is a seam, not a setting: nothing in the product produces a+ * value for it, and a configurable deadline nobody configures would be+ * one more declared surface with no producer. What it buys is a test+ * that can hang a real partner and watch a real bound end it, instead of+ * asserting against a fake that returns the record the bound would have+ * produced.+ */+ readonly timeoutMs?: number;}export interface CodegraphCheckOptions {@@ -193,11 +245,28 @@ export interface CodegraphCheckOptions {readonly disabled?: boolean;}+/**+ * The lookup path and environment the partner is resolved and run against.+ *+ * Both are read from `process.env` AT CALL TIME and passed explicitly,+ * because `Bun.which` and `Bun.spawn*` otherwise resolve a command against+ * the PATH this process was STARTED with. A long-lived process that+ * updated its own PATH - the MCP server, a host embedding this module,+ * a test standing up a fake partner - would find the binary the snapshot+ * named and never the one the environment now points at, and would report+ * that stale binary's answer as this machine's state.+ */+function partnerEnv(): Readonly<Record<string, string | undefined>> {+ return process.env;+}+export function defaultWhichCodegraph(): string | null {if (typeof Bun !== "undefined" && typeof (Bun as { which?: unknown }).which === "function") {- const found = (Bun as unknown as { which: (cmd: string) => string | null }).which(- CODEGRAPH_CLI.bin,- );+ const found = (+ Bun as unknown as {+ which: (cmd: string, opts?: { PATH?: string | undefined }) => string | null;+ }+ ).which(CODEGRAPH_CLI.bin, { PATH: partnerEnv()["PATH"] });return found ?? null;}return null;@@ -217,13 +286,49 @@ const CODEGRAPH_PROJECT_PATH_USAGE_TOKEN = /\[path\]/;/** The universal flag that makes a CLI print its own usage. */const HELP_FLAG = "--help";-export function defaultDetectProjectPathSupport(): boolean {+/**+ * How long any single partner invocation may take before it is stopped.+ *+ * Both spawns are SYNCHRONOUS and `doctor()` has three callers - the CLI,+ * the MCP `vault_health` tool and the OpenClaw extension - so an unbounded+ * one blocks whichever of them asked, for as long as the partner is stuck.+ * The bound existed nowhere: a wedged partner (a stale lock, an index+ * rebuild that never returns, a stalled network filesystem) hung the+ * doctor with no deadline, no refusal and no record.+ *+ * Ten seconds because this is a CEILING and not a target: a warm+ * `codegraph status -j` over a 27k-node index on the machine this was+ * measured on answers in ~0.7 s, and the partner's own config docblock+ * names seconds against a cold HOME. An order of magnitude of headroom+ * keeps a slow-but-working partner reporting its answer, while a partner+ * that is not coming back stops being everyone else's problem.+ */+export const CODEGRAPH_PARTNER_TIMEOUT_MS = 10_000;++/** Bun reports a killed-by-deadline spawn with its own flag; typed once here. */+function timedOut(proc: { readonly exitedDueToTimeout?: boolean }): boolean {+ return proc.exitedDueToTimeout === true;+}++/**+ * @param timeoutMs deadline for the spawn; see {@link CODEGRAPH_PARTNER_TIMEOUT_MS}.+ * A probe that times out returns `false` for the same reason a probe+ * that throws does - the caller degrades to the first project and says+ * so - and the sentence it produces claims only that support was not+ * REPORTED, never that the partner lacks it.+ */+export function defaultDetectProjectPathSupport(+ timeoutMs: number = CODEGRAPH_PARTNER_TIMEOUT_MS,+): boolean {try {const proc = Bun.spawnSync({cmd: [CODEGRAPH_CLI.bin, CODEGRAPH_CLI.statusSubcommand, HELP_FLAG],stdout: "pipe",stderr: "pipe",+ env: partnerEnv(),+ timeout: timeoutMs,});+ if (timedOut(proc)) return false;const help = new TextDecoder().decode(proc.stdout) + new TextDecoder().decode(proc.stderr);return CODEGRAPH_PROJECT_PATH_USAGE_TOKEN.test(help);} catch {@@ -231,7 +336,10 @@ export function defaultDetectProjectPathSupport(): boolean {}}-export function defaultRunStatusJson(projectPath: string): CodegraphStatusResult {+export function defaultRunStatusJson(+ projectPath: string,+ timeoutMs: number = CODEGRAPH_PARTNER_TIMEOUT_MS,+): CodegraphStatusResult {try {const proc = Bun.spawnSync({cmd: [@@ -242,7 +350,14 @@ export function defaultRunStatusJson(projectPath: string): CodegraphStatusResult],stdout: "pipe",stderr: "pipe",+ env: partnerEnv(),+ timeout: timeoutMs,});+ // Checked BEFORE the output is read, because a partner killed at the+ // deadline usually wrote nothing and would otherwise be reported as+ // "empty status output" - a sentence about what it said, over a+ // process that never said anything.+ if (timedOut(proc)) return { ok: false, unanswered: true, waitedMs: timeoutMs };const stdout = new TextDecoder().decode(proc.stdout).trim();const stderr = new TextDecoder().decode(proc.stderr).trim();if (!proc.success) {@@ -270,20 +385,29 @@ export function defaultRunStatusJson(projectPath: string): CodegraphStatusResult}/**- * Doctor-grade check for codegraph partnership. Returns `null` (skip,- * no doctor output) when the current scope is not a code project, when the- * user has explicitly disabled the check, or when the codegraph CLI is not- * installed — codegraph is an optional partner OSB never installs, so its- * absence must not fail doctor.+ * Doctor-grade check for codegraph partnership. Returns `null` (skip, no+ * doctor output) when the current scope is not a code project or when the+ * codegraph CLI is not installed — codegraph is an optional partner OSB+ * never installs, so its absence must not fail doctor.** Non-null results carry a single `code_graph` `CheckResult` describing- * one of three states: `not_indexed`, `ok`, or `error`.+ * one of four states: `disabled`, `not_indexed`, `ok`, or `error`.+ *+ * `disabled` reports itself instead of returning null, because the switch+ * that produces it would otherwise be a setting that silently does+ * nothing visible: an operator who turned the check off, one whose machine+ * has no codegraph, and one standing in a directory that is not a code+ * project would all read the same empty report. Those two remaining+ * silences are NOT distinguished here, and saying so is the honest form of+ * this docblock: separating them means emitting a `code_graph` line on+ * every machine without the partner, CI included, which is a change to the+ * base doctor output rather than to this switch.*/export function checkCodegraph(opts: CodegraphCheckOptions,deps?: CodegraphCheckDeps,): CheckResult | null {- if (opts.disabled) return null;+ if (opts.disabled) return codegraphDisabledResult();const projects = findCodeProjects(opts);if (projects.length === 0) return null;@@ -302,24 +426,49 @@ export function checkCodegraph(// runs (there is nothing to thread across), so behavior and output are// exactly today's.if (projects.length === 1) {- return evaluateProjectStatus(projects[0]!, deps);+ return evaluateProjectStatus(projects[0]!, deps).result;}// Multi-project workspace. Threading status per project is only sound when// the partner accepts a per-query project path; otherwise every query would// report whatever project the CLI infers from its own cwd, so we degrade to// the first project and say so explicitly.- const detectFn = deps?.detectProjectPathSupport ?? defaultDetectProjectPathSupport;+ const detectFn =+ deps?.detectProjectPathSupport ?? (() => defaultDetectProjectPathSupport(partnerTimeout(deps)));if (!detectFn()) {- const first = evaluateProjectStatus(projects[0]!, deps);+ const first = evaluateProjectStatus(projects[0]!, deps).result;return {name: "code_graph",ok: first.ok,- message: `${first.message}; note: codegraph CLI has no per-query project_path support - reported 1 of ${projects.length} discovered projects only`,+ // "did not report" rather than "has no": the probe reads the+ // partner's own usage text, and a probe that failed or ran out of+ // time reads exactly like a partner without the feature. Saying the+ // stronger thing would be claiming what was not established.+ message: `${first.message}; note: codegraph CLI did not report per-query project_path support - reported 1 of ${projects.length} discovered projects only`,};}- const results = projects.map((project) => evaluateProjectStatus(project, deps));+ // A partner that has already failed to answer once is not asked again:+ // per-project retries would multiply the deadline by the project count,+ // which is how a bound stops bounding anything. The projects that were+ // consequently never consulted are named rather than dropped.+ const results: CheckResult[] = [];+ let unanswered = false;+ for (const project of projects) {+ if (unanswered) {+ results.push({+ name: "code_graph",+ ok: false,+ message:+ `code project at ${project}: not consulted - ${CODEGRAPH_CLI.bin} did not answer for ` ++ "an earlier project in this workspace, so nothing is claimed here about this index",+ });+ continue;+ }+ const evaluated = evaluateProjectStatus(project, deps);+ unanswered = evaluated.unanswered;+ results.push(evaluated.result);+ }const header = `${projects.length} code projects:`;return {name: "code_graph",@@ -328,14 +477,55 @@ export function checkCodegraph(};}+/** The deadline this call runs under. */+function partnerTimeout(deps?: CodegraphCheckDeps): number {+ return deps?.timeoutMs ?? CODEGRAPH_PARTNER_TIMEOUT_MS;+}++/**+ * The `disabled` arm.+ *+ * `ok` is a two-valued field and this state is neither of its two+ * meanings, so the message carries what the flag cannot: which switch+ * turned the check off, and that nothing was asked of the partner. `true`+ * is the lesser wrong of the two - `false` would fail `o2b doctor` for an+ * operator who deliberately asked it to leave the partner alone, turning+ * a preference into a defect. Giving the doctor a third stream so this+ * state stops borrowing `ok` at all is a change to every consumer of+ * {@link CheckResult} (the CLI, the MCP payload, the OpenClaw extension)+ * and is named here rather than smuggled in with a switch.+ */+function codegraphDisabledResult(): CheckResult {+ return {+ name: "code_graph",+ ok: true,+ message:+ `check disabled by ${PARTNER_CODEGRAPH_DISABLED_ENV} / ` ++ `${PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY}: ${CODEGRAPH_CLI.bin} was not consulted, ` ++ "so nothing is claimed here about any index",+ };+}++/** One project's verdict, plus whether the partner failed to answer for it. */+interface EvaluatedProject {+ readonly result: CheckResult;+ /**+ * True when the partner ran out of time rather than answering. Carried+ * beside the result rather than parsed back out of its message, because+ * the aggregate above changes what it DOES on this fact.+ */+ readonly unanswered: boolean;+}+/*** Evaluate one project's codegraph status into a `code_graph` CheckResult,* threading the project path into the status query. This is the exact- * per-project logic (not-indexed / status-failed / indexed + graph-health) that- * the single-project path returns verbatim, so a single-project workspace stays- * byte-identical and a multi-project aggregate reuses one implementation.+ * per-project logic (not-indexed / no-answer / status-failed / indexed ++ * graph-health) that the single-project path returns verbatim, so a+ * single-project workspace stays byte-identical and a multi-project+ * aggregate reuses one implementation.*/-function evaluateProjectStatus(project: string, deps?: CodegraphCheckDeps): CheckResult {+function evaluateProjectStatus(project: string, deps?: CodegraphCheckDeps): EvaluatedProject {const indexDir = join(project, ".codegraph");// 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.@@ -346,37 +536,59 @@ function evaluateProjectStatus(project: string, deps?: CodegraphCheckDeps): Chectry {indexed = statOrAbsent(indexDir)?.isDirectory() === true;} catch (exc) {- return {+ return answered({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 {+ return answered({name: "code_graph",ok: false,message: `code project at ${project}: not indexed (run: ${codegraphInitCommand(project)})`,- };+ });}- const runFn = deps?.runStatusJson ?? defaultRunStatusJson;+ const runFn =+ deps?.runStatusJson ?? ((path: string) => defaultRunStatusJson(path, partnerTimeout(deps)));const status = runFn(project);- if (!status.ok) {+ if (isCodegraphUnanswered(status)) {+ // `ok: false` is the lesser wrong of the two values this field has,+ // for the mirror of the reason `codegraphDisabledResult` chooses+ // `true`: reporting a wedged partner as a pass would be the silent+ // no-op, and the doctor has no third stream to put "did not complete"+ // on without changing every consumer of `CheckResult`. The message+ // therefore carries the distinction the flag cannot.return {+ result: {+ name: "code_graph",+ ok: false,+ message:+ `code project at ${project}: ${CODEGRAPH_CLI.bin} ` ++ `${CODEGRAPH_CLI.statusSubcommand} did not answer within ${status.waitedMs}ms and was ` ++ "stopped, so NOTHING is claimed here about this index - a probe that did not complete " ++ "is not an index that failed",+ fix: `${CODEGRAPH_CLI.bin} ${CODEGRAPH_CLI.statusSubcommand} ${CODEGRAPH_CLI.statusJsonFlag} ${project}`,+ },+ unanswered: true,+ };+ }+ if (!status.ok) {+ return answered({name: "code_graph",ok: false,message: `code project at ${project}: codegraph status failed: ${status.error}`,- };+ });}if (!status.data.initialized) {- return {+ return answered({name: "code_graph",ok: false,message: `code project at ${project}: not indexed (run: ${codegraphInitCommand(project)})`,- };+ });}const nodes = status.data.nodeCount ?? 0;@@ -400,13 +612,18 @@ function evaluateProjectStatus(project: string, deps?: CodegraphCheckDeps): ChecworktreeRoot: resolveRealpath(status.data.worktreeMismatch?.worktreeRoot ?? project),});- return {+ return answered({name: "code_graph",ok: true,message: health.ok? base: `${base}; graph-health: ${summarizeGraphHealth(health)} - run: o2b partner codegraph report`,- };+ });+}++/** A verdict the partner (or the filesystem) actually produced. */+function answered(result: CheckResult): EvaluatedProject {+ return { result, unanswered: false };}/**diff --git a/src/core/path-safety.ts b/src/core/path-safety.tsindex 7d43d4c1..ce689598 100644--- a/src/core/path-safety.ts+++ b/src/core/path-safety.ts@@ -65,6 +65,19 @@ export function realpathInsideVault(target: string, vault: string): boolean {return isLexicallyInside(realAncestor, realVault);}+/**+ * Step 1 of {@link ensureInsideVault} as a non-throwing predicate: does+ * `target` resolve, lexically, to `root` or a descendant of it?+ *+ * Exported for the callers that need the ANSWER rather than the refusal -+ * the ownership statement has to say where the search index actually+ * landed, and a `try`/`catch` around a thrower would collapse "outside the+ * vault" and "the check could not run" into one arm.+ */+export function pathIsInside(target: string, root: string): boolean {+ return isLexicallyInside(resolve(target), resolve(root));+}+function isLexicallyInside(target: string, root: string): boolean {// Windows file paths are case-insensitive at the filesystem level —// `C:\Vault\x.md` and `c:\vault\x.md` resolve to the same inode. Doingdiff --git a/src/core/search/benchmark.ts b/src/core/search/benchmark.tsindex 55bc286c..9d7e4b08 100644--- a/src/core/search/benchmark.ts+++ b/src/core/search/benchmark.ts@@ -19,13 +19,43 @@* free.*/+import { Semaphore } from "./embeddings/http-util.ts";import { search } from "./search.ts";import { SearchError } from "./types.ts";-import type { ResolvedSearchConfig } from "./types.ts";+import type { ResolvedSearchConfig, SearchOutcome } from "./types.ts";/** Default rank depth for hit@k / reciprocal rank. */export const BENCHMARK_DEFAULT_K = 5;+/**+ * Most dataset queries this process runs at once.+ *+ * The dataset is operator-supplied and unbounded in size, and `tuneRecall`+ * multiplies it by the 24-point parameter grid, so the fan-out is the+ * product of two numbers this module does not choose. Eight concurrent+ * hybrid searches keep a benchmark run overlapping its SQLite reads+ * without letting a large dataset - or the grid - open one connection and+ * one query plan per query at the same instant.+ */+export const BENCHMARK_QUERY_CONCURRENCY = 8;++/**+ * The ceiling itself, module-scoped so it spans the process: `tuneRecall`+ * awaits 24 concurrent `runRecallBenchmark` calls, and a gate constructed+ * per call would bound each one at 8 while the process ran 192.+ */+const queryGate = new Semaphore(BENCHMARK_QUERY_CONCURRENCY);++/**+ * Test-only: the high-water mark of concurrent queries this process has+ * reached. The leading underscore is this repo's marker for a test-only+ * export, which is exactly what the rule below flags.+ */+// oxlint-disable-next-line no-underscore-dangle+export function _benchmarkQueryPeakForTests(): number {+ return queryGate.peakInFlight;+}+export interface RecallBenchmarkQuery {readonly id: string;readonly query: string;@@ -184,7 +214,8 @@ export function parseRecallBenchmarkDataset(raw: unknown): RecallBenchmarkDatase/*** Score the dataset against the vault behind `config`. Queries run- * concurrently (read-only); the report order follows the dataset.+ * concurrently (read-only) up to {@link BENCHMARK_QUERY_CONCURRENCY}+ * in flight process-wide; the report order follows the dataset.*/export async function runRecallBenchmark(config: ResolvedSearchConfig,@@ -203,11 +234,17 @@ export async function runRecallBenchmark(const perQuery = await Promise.all(dataset.queries.map(async (q): Promise<RecallBenchmarkQueryResult> => {const depth = q.k ?? k;- const outcome = await search(config, {- query: q.query,- limit: depth,- ...(expand ? { expand: true } : {}),- });+ const permit = await queryGate.acquire();+ let outcome: SearchOutcome;+ try {+ outcome = await search(config, {+ query: q.query,+ limit: depth,+ ...(expand ? { expand: true } : {}),+ });+ } finally {+ permit();+ }const expected = new Set(q.expected);const topK = outcome.results.slice(0, depth);const topKPaths = new Set(topK.map((r) => r.path));diff --git a/src/core/search/embeddings/http-util.ts b/src/core/search/embeddings/http-util.tsindex d99d93c1..79901e32 100644--- a/src/core/search/embeddings/http-util.ts+++ b/src/core/search/embeddings/http-util.ts@@ -4,6 +4,10 @@* config knowledge - so each provider owns its own request/response* mapping while reusing identical batching, concurrency, backoff, and* unit-normalisation semantics.+ *+ * {@link Semaphore} is the one exception to "embedding providers": it is+ * the search layer's only concurrency limiter, and the recall benchmark+ * bounds its query fan-out with it too rather than growing a second one.*/import { SearchError } from "../types.ts";@@ -77,25 +81,151 @@ export function jittered(base: number): number {return Math.max(0, base + jitter);}-/** A minimal counting semaphore for bounded batch concurrency. */+/**+ * The three caps this module enforces, named for the operator-facing+ * config key each one carries, so a refusal says which key to change.+ */+const CAP_FIELD = Object.freeze({+ /** `embedding_batch_size`: how many items one request may carry. */+ size: "batch size",+ /** `embedding_batch_tokens`: how many estimated tokens one request may carry. */+ tokens: "token budget",+ /** `embedding_concurrency`: how many requests may be in flight at once. */+ concurrency: "concurrency ceiling",+});++/**+ * Take a cap EXACTLY as the caller gave it, or refuse it.+ *+ * `Math.max(1, cap | 0)` used to stand at every call site. `| 0` truncates+ * to a signed 32-bit int, so a cap above 2^31-1 wrapped NEGATIVE and the+ * clamp then lifted it to 1: the largest batch - or the widest concurrency+ * ceiling - an operator can ask for silently became the smallest one+ * possible. Nothing is truncated now, and nothing is clamped: a cap this+ * module cannot honour is named rather than quietly reinterpreted into a+ * different request plan than the one configured.+ *+ * All three keys are already refused below 1, at a fraction, and at a+ * non-finite value by config validation (`search/index.ts`), so a resolved+ * config never reaches this guard; it holds the line for programmatic+ * callers that construct a `ResolvedEmbeddingConfig` directly.+ */+function requireCap(cap: number, field: string): number {+ if (!Number.isInteger(cap) || cap < 1) {+ throw new SearchError("INVALID_INPUT", `${field} must be an integer >= 1, got ${cap}`);+ }+ return cap;+}++/**+ * One permit, handed to the acquirer that holds it. Calling it gives the+ * permit back; calling it a second time raises, because the second call+ * is a release of something the caller no longer holds.+ */+export type SemaphorePermit = () => void;++/**+ * A minimal counting semaphore for bounded concurrency.+ *+ * Giving a permit back hands it DIRECTLY to the head of the waiter queue+ * instead of returning it to the pool for the woken waiter to claim+ * later. The pool form over-subscribes by one for every wakeup: between+ * the `permits++` and the waiter's continuation there is a microtask in+ * which a fresh `acquire()` sees a free permit and takes it, and the+ * waiter then decrements past zero. Both run, and the ceiling reads one+ * higher than configured. With a hand-off the permit is never observable+ * as free, so the invariant holds for any interleaving.+ *+ * ## Why a permit rather than a `release()` method+ *+ * An over-release is a CALLER DEFECT, not an input: nothing an operator+ * configures can produce one, only code that gives back a permit it never+ * took or gives one back twice. So it is refused loudly rather than+ * clamped - a clamp would leave the defective call site running, and the+ * whole point of this object is that the number of requests on the wire+ * is the configured number and not a number that drifted.+ *+ * Refusing needs the holder's own record, which is what makes the permit+ * a value instead of a method:+ *+ * - `if (permits >= limit) throw` cannot see the case that matters.+ * With a waiter queued the pool count is 0, so a stray release passes+ * that test and is handed straight to the waiter: one more holder+ * than the ceiling, and no counter moved.+ * - `if (held === 0) throw` misses the same case for the same reason.+ * - A one-shot permit closure decides it locally: the second call knows+ * it is the second call, whatever the pool and queue happen to hold,+ * and code that never acquired has nothing to call.+ *+ * That also repairs the instrument. {@link peakInFlight} counts entries+ * and matched exits ONLY, so it can no longer be driven below the truth+ * by the very releases that break the bound - the failure mode where a+ * ceiling of 2 ran 4 real holders and the counter still reported 2+ * (nothing-runs-unwatched review, C4). A bound nothing can observe is a+ * bound nothing can verify, and a counter the breach silences is worse+ * than none.+ *+ * The ceiling is process-wide and shared between callers+ * (`provider-semaphore.ts`), so one caller's stray release would widen+ * the ceiling for every other caller against the same provider. That is+ * why the guard lives here rather than at any one call site.+ */export class Semaphore {+ /** The ceiling enforced here: the permit count when nothing is held. */+ readonly limit: number;private permits: number;+ private held = 0;+ private peak = 0;private readonly waiters: Array<() => void> = [];- constructor(n: number) {- this.permits = Math.max(1, n | 0);+ constructor(limit: number) {+ this.limit = requireCap(limit, CAP_FIELD.concurrency);+ this.permits = this.limit;}- async acquire(): Promise<void> {+ /**+ * Most permits held at once since construction. Every increment is an+ * acquirer that entered and every decrement is that acquirer's own+ * permit coming back, so this is the true high-water mark of holders -+ * and never above `limit`, as a consequence rather than a coincidence.+ */+ get peakInFlight(): number {+ return this.peak;+ }+ private enter(): SemaphorePermit {+ this.held++;+ if (this.held > this.peak) this.peak = this.held;+ let spent = false;+ return (): void => {+ if (spent) {+ throw new SearchError(+ "INVALID_INPUT",+ `semaphore permit released twice (ceiling ${this.limit}): a second release ` ++ `returns a permit this caller no longer holds and widens the ceiling for ` ++ `every caller sharing it`,+ );+ }+ spent = true;+ this.leave();+ };+ }+ private leave(): void {+ this.held--;+ const next = this.waiters.shift();+ if (next) {+ next();+ return;+ }+ this.permits++;+ }+ /** Take a permit, waiting for one; call the result once to give it back. */+ async acquire(): Promise<SemaphorePermit> {if (this.permits > 0) {this.permits--;- return;+ return this.enter();}+ // The releaser transfers its permit to this waiter, so the resumed+ // acquirer must NOT decrement `permits` again.await new Promise<void>((res) => this.waiters.push(res));- this.permits--;- }- release(): void {- this.permits++;- const next = this.waiters.shift();- if (next) next();+ return this.enter();}}@@ -115,43 +245,9 @@ export function unitNormaliseInPlace(v: number[]): number[] {return v;}-/**- * The two batching caps, named for the operator-facing config key each one- * carries, so a refusal says which key to change.- */-const CAP_FIELD = Object.freeze({- /** `embedding_batch_size`: how many items one request may carry. */- size: "batch size",- /** `embedding_batch_tokens`: how many estimated tokens one request may carry. */- tokens: "token budget",-});--/**- * Take a batching cap EXACTLY as the caller gave it, or refuse it.- *- * `Math.max(1, cap | 0)` used to stand at both call sites. `| 0` truncates- * to a signed 32-bit int, so a cap above 2^31-1 wrapped NEGATIVE and the- * clamp then lifted it to 1: the largest batch an operator can ask for- * silently became the smallest one possible - one HTTP request per item,- * at full `embedding_concurrency`. Nothing is truncated now, and nothing is- * clamped: a cap this packer cannot step by is named rather than quietly- * reinterpreted into a different request plan than the one configured.- *- * Both keys are already refused below 1, at a fraction, and at a- * non-finite value by config validation (`search/index.ts`), so a resolved- * config never reaches this guard; it holds the line for programmatic- * callers that construct a `ResolvedEmbeddingConfig` directly.- */-function requireBatchCap(cap: number, field: string): number {- if (!Number.isInteger(cap) || cap < 1) {- throw new SearchError("INVALID_INPUT", `${field} must be an integer >= 1, got ${cap}`);- }- return cap;-}-/** Split an array into fixed-size chunks. Refuses a step below 1 or fractional. */export function chunkArray<T>(arr: ReadonlyArray<T>, size: number): T[][] {- const step = requireBatchCap(size, CAP_FIELD.size);+ const step = requireCap(size, CAP_FIELD.size);const out: T[][] = [];for (let i = 0; i < arr.length; i += step) out.push(arr.slice(i, i + step) as T[]);return out;@@ -187,8 +283,8 @@ export function chunkArrayByTokenBudget<T>(textOf: (item: T) => string,): T[][] {if (tokenBudget === undefined) return chunkArray(arr, size);- const step = requireBatchCap(size, CAP_FIELD.size);- const budget = requireBatchCap(tokenBudget, CAP_FIELD.tokens);+ const step = requireCap(size, CAP_FIELD.size);+ const budget = requireCap(tokenBudget, CAP_FIELD.tokens);const out: T[][] = [];let current: T[] = [];let currentTokens = 0;diff --git a/src/core/search/embeddings/openai-compat.ts b/src/core/search/embeddings/openai-compat.tsindex 5848db27..dd13ff64 100644--- a/src/core/search/embeddings/openai-compat.ts+++ b/src/core/search/embeddings/openai-compat.ts@@ -4,7 +4,9 @@* Anchored in docs/plans/2026-05-16-brain-search-design.md §11.** Network rules:- * - One concurrent batch per semaphore slot (`embedding_concurrency`).+ * - One concurrent batch per semaphore slot (`embedding_concurrency`),+ * on a ceiling shared PROCESS-WIDE by every provider resolving to the+ * same identity and endpoint - see `provider-semaphore.ts`.* - Each batch contains up to `embedding_batch_size` texts and, when* `embedding_batch_tokens` is set, at most that many estimated tokens* of prefixed text; the batch closes on whichever cap fills first.@@ -27,13 +29,13 @@ import {PAYMENT_REQUIRED_STATUS,RATE_LIMIT_STATUS,RETRYABLE_STATUSES,- Semaphore,chunkArrayByTokenBudget,jittered,parseRetryAfterMs,sleep,unitNormaliseInPlace,} from "./http-util.ts";+import { providerCeilingKey, providerSemaphore } from "./provider-semaphore.ts";/*** Sentinel embedded in a synthetic error message when a batch is cancelled@@ -235,6 +237,12 @@ export class OpenAICompatProvider implements EmbeddingProvider {/** Ordered probe keys; `activeKeyIndex` pins the first that authenticates. */private readonly keys: ReadonlyArray<string>;private activeKeyIndex = 0;+ /**+ * Registry key of the process-wide ceiling this provider shares.+ * Resolved once, from the CONFIGURED identity, so it cannot move when+ * `_dimension` is learned from the first response.+ */+ private readonly ceilingKey: string;constructor(config: ResolvedEmbeddingConfig, opts?: OpenAICompatProviderOptions) {this.config = config;@@ -243,6 +251,7 @@ export class OpenAICompatProvider implements EmbeddingProvider {this._dimension = config.dimension;this.backoffMs = opts?.backoffMs ?? [1000, 2000];this.keys = resolveKeys(config, this.http.apiKey);+ this.ceilingKey = providerCeilingKey(this.name, config, this.http.url);}private get activeKey(): string {@@ -276,7 +285,7 @@ export class OpenAICompatProvider implements EmbeddingProvider {this.config.batchTokens,(b) => b.text,);- const sem = new Semaphore(this.config.concurrency);+ const sem = providerSemaphore(this.ceilingKey, this.config.concurrency);const out: number[][] = new Array(texts.length);// Shared abort controller cancels in-flight siblings and skips@@ -286,7 +295,7 @@ export class OpenAICompatProvider implements EmbeddingProvider {const cancel = new AbortController();const tasks = batches.map(async (batch) => {- await sem.acquire();+ const permit = await sem.acquire();try {if (cancel.signal.aborted) return;const vectors = await this.embedBatchWithRetry(@@ -300,7 +309,7 @@ export class OpenAICompatProvider implements EmbeddingProvider {out[batch[i]!.originalIndex] = vectors[i]!;}} finally {- sem.release();+ permit();}});diff --git a/src/core/search/embeddings/provider-semaphore.ts b/src/core/search/embeddings/provider-semaphore.tsnew file mode 100644index 00000000..7981ee15--- /dev/null+++ b/src/core/search/embeddings/provider-semaphore.ts@@ -0,0 +1,152 @@+/**+ * Process-scoped outbound-request ceilings for the HTTP embedding+ * providers (nothing-runs-unwatched, U4).+ *+ * INVARIANT: across every concurrent `embed()` call in this process, at+ * most `embedding_concurrency` embedding requests are in flight for one+ * (embedding identity, resolved endpoint) PAIR - identity being provider,+ * model and CONFIGURED dimension.+ *+ * The pair, and not the endpoint alone - a difference the operator has to+ * do arithmetic with: N identities configured against one host put up to+ * `N x embedding_concurrency` requests on that host at once. Size the knob+ * against the budget that host actually meters. That shape is deliberate,+ * not an oversight - the argument is under "Why the identity, and not the+ * endpoint alone" below, and this unit's own acceptance criterion states+ * it ("two different provider identities do not share a ceiling", U4).+ *+ * Each provider used to build `new Semaphore(config.concurrency)` INSIDE+ * `embed()`, so the configured ceiling bounded one call rather than the+ * process: two overlapping calls put `2 x embedding_concurrency` requests+ * on the wire. The indexer happens to await its calls one at a time+ * (`search/indexer.ts`), so the over-subscription was latent - but that+ * serialisation is the indexer's own property and no other caller+ * inherits it, and a ceiling that holds only for one caller is not a+ * ceiling.+ *+ * ## What the key is, and why+ *+ * The canonical embedding signature paired with the resolved request URL,+ * encoded as a JSON 2-tuple so no separator can collide with a provider+ * name, a model name, or a URL.+ *+ * - {@link embeddingSignature} is this layer's single statement of "the+ * same embedding configuration", already shared by the provider+ * registry, the cost gate, and the store's corpus fingerprint. A+ * ceiling keyed on anything else would be a second, drifting+ * definition of provider sameness.+ * - The endpoint URL is paired with it because the signature carries no+ * host. `text-embedding-3-small` at api.openai.com and the same model+ * name served by a local runtime are two remote hosts with two rate+ * budgets; one shared ceiling would throttle each on the other's+ * traffic.+ * - The identity is built from the CONFIGURED dimension, never from+ * `provider.dimension`. Both providers LEARN their dimension from the+ * first response when `embedding_dimension` is unset, so a+ * live-dimension key would move a provider from one ceiling to+ * another mid-run and briefly double the in-flight budget.+ * - The API key is deliberately absent. The openai-compat provider+ * rotates probe keys on a 401/403 in the middle of a call; a+ * key-bearing identity would hop budgets at exactly the moment the+ * provider is already under stress, and it would park a secret in a+ * process-lived map key.+ *+ * ## Why the identity, and not the endpoint alone+ *+ * A ceiling cannot be keyed more coarsely than the configuration that+ * supplies its number. `embedding_concurrency` is a field of ONE resolved+ * embedding config, whose identity - what this layer already means by "the+ * same embedding configuration" - is provider, model and dimension, at a+ * base URL. No host-level knob exists for an operator to state a+ * host-level ceiling with. Key this per endpoint and two models on one+ * host land in one bucket carrying two different operator-stated numbers,+ * which {@link providerSemaphore} refuses by design rather than+ * reconciling: adding a second model to a working process would start+ * failing its embeddings, and the operator would have no field to say+ * what they actually meant.+ *+ * It also matches what the dominant provider meters: OpenAI publishes its+ * request and token limits per model against an account tier, so a+ * per-model partition maps onto the counter that returns the 429 rather+ * than onto a host name that nothing counts.+ *+ * Where that is NOT true - a local runtime serving several models off one+ * box, or an account-wide cap - the ceiling against that host is+ * `embedding_concurrency x identities`, per the INVARIANT above. That+ * product is the honest statement of what this module bounds, and it is+ * the number to size against a quota.+ *+ * ## Scope+ *+ * The ceiling covers the batch traffic of `embed()`. A provider's+ * `ping()` issues one pre-flight probe outside it, deliberately: a+ * readiness check that queued behind an indexing run would report a+ * timeout about the queue rather than about the endpoint.+ */++import type { ResolvedEmbeddingConfig } from "../types.ts";+import { SearchError } from "../types.ts";+import { Semaphore } from "./http-util.ts";+import { embeddingSignature } from "./signature.ts";+import type { EmbeddingIdentity } from "./signature.ts";++const ceilings = new Map<string, Semaphore>();++/**+ * The registry key for one provider endpoint: see the module docblock for+ * what each half contributes. `endpoint` is the fully resolved request+ * URL, not the configured base URL, so two providers that map the same+ * base to different paths stay distinct.+ */+export function providerCeilingKey(+ provider: string,+ config: ResolvedEmbeddingConfig,+ endpoint: string,+): string {+ const identity: EmbeddingIdentity = {+ provider,+ model: config.model,+ dimension: config.dimension,+ };+ return JSON.stringify([embeddingSignature(identity), endpoint]);+}++/**+ * The one semaphore that bounds `key`, creating it on first use.+ *+ * Two live configurations that disagree on the ceiling for a single+ * endpoint are refused rather than reconciled. Keeping the first-seen+ * limit would leave the second caller believing a bound is in force that+ * is not, and a semaphore's permit count cannot be widened or narrowed+ * under holders without breaking the invariant for the requests already+ * in flight. The refusal names `embedding_concurrency` because that is+ * the key the operator changes; the remedy is to make the two+ * configurations agree, or to run them in separate processes.+ */+export function providerSemaphore(key: string, limit: number): Semaphore {+ const existing = ceilings.get(key);+ if (existing === undefined) {+ const created = new Semaphore(limit);+ ceilings.set(key, created);+ return created;+ }+ if (existing.limit !== limit) {+ throw new SearchError(+ "INVALID_INPUT",+ `embedding_concurrency disagrees for ${key}: this process already bounds it at ` ++ `${existing.limit}, and a second configuration asks for ${limit}`,+ );+ }+ return existing;+}++/**+ * Test-only: drop every ceiling so a suite starts from an empty process.+ * The leading underscore is this repo's marker for a test-only export+ * (`store-exit.ts`, `sync-lockfile.ts`), which is exactly what the rule+ * below flags.+ */+// oxlint-disable-next-line no-underscore-dangle+export function _resetProviderCeilingsForTests(): void {+ ceilings.clear();+}diff --git a/src/core/search/embeddings/sunset.ts b/src/core/search/embeddings/sunset.tsnew file mode 100644index 00000000..92233200--- /dev/null+++ b/src/core/search/embeddings/sunset.ts@@ -0,0 +1,545 @@+/**+ * Announced decommissions of embedding models (t_e7a226ce).+ *+ * Changing `embedding_model` invalidates every stored vector: the index+ * stamps the model into its ABI tokens and the only remedy is a full+ * re-embed of the corpus (`EMBEDDING_ABI_FIX_COMMAND`). That machinery+ * fires only AFTER the operator has already changed the model. This module+ * is the strictly earlier signal - it fires while the config is still+ * correct and the index still valid, so a migration can be scheduled+ * rather than performed under an index that has just stopped working.+ *+ * ## Where the dates come from, and why+ *+ * Four sources were available and three are refused:+ *+ * - **A network registry.** Refused. This project takes no unrequested+ * outbound call for a fact like this, and says so at every relevant+ * site: the presets catalog is "No server, no network"; runtime+ * notices are computed "deterministically - no network, no LLM, no DB+ * open"; `search check`'s provider probe is the ONE outbound call that+ * verb makes and has an opt-out for the air-gapped caller. A cached+ * registry is also the same staleness as a static table with more+ * machinery, and an unreachable one is a third state to design for.+ * - **A field on `EmbeddingModelPreset`.** Refused. That catalog is a+ * list of RECOMMENDATIONS - its first entry is+ * `RECOMMENDED_EMBEDDING_MODEL` unconditionally and is defaulted into+ * every new provider profile - and a curated list of recommendations+ * that also carries obituaries is two catalogs in one file. Worse, the+ * populations barely overlap: five of its six entries are open-weight+ * checkpoints with no vendor able to announce anything, while the+ * hosted, versioned models that actually get decommissioned live in+ * the disjoint `EMBEDDING_PRICING` table.+ * - **An operator-declared date** (a flat config scalar, or a field on a+ * registry profile). Refused as the SOLE source, because neither can+ * tell "the operator declared nothing" from "no shutdown exists" - one+ * optional key carries both meanings, which is the exact defect this+ * check exists to remove. A profile-borne date additionally cannot+ * reach the configuration this tool's own onboarding recommends, which+ * is a bare `embedding_base_url` + `embedding_model` pair with no+ * profile at all.+ *+ * What ships is a SURVEY: a static table of models somebody actually+ * looked up, each entry carrying either a date or an explicit negative,+ * plus the date the survey as a whole was reviewed. That is the mechanism+ * this repository already uses for third-party facts - `inputWindowTokens`+ * is hardcoded from published specs with a per-entry source comment - and+ * it costs no network call.+ *+ * ## How the survey handles its own staleness+ *+ * The unfixable weakness of a static table is that it goes stale between+ * releases, and the honest response is asymmetric:+ *+ * - A **negative** is a claim about the world and it EXPIRES. Past+ * {@link EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS} from `reviewedAt`,+ * `none_announced` degrades to `undetermined` with `survey_stale`+ * rather than remaining a confident negative nobody re-checked.+ * - A **positive** survives a stale survey. A vendor can move a date,+ * but a shutdown that was announced was announced, and an operator who+ * is told about it can verify it. The verdict carries `surveyed_at` so+ * the message can say how old the claim is.+ * - **Absence** from the survey is `unsurveyed` and is never+ * `none_announced`. `embedding_model` is a free string with zero+ * validation and this tool's own onboarding recommends a preview model+ * that no catalog here carries, so off-survey is the NORMAL case. This+ * is the same polarity `declaredInputWindowTokens` chose for an+ * unlisted window and the opposite of `pricePerMillionTokens`, which+ * may answer 0 for an unknown model only because its fallback makes a+ * gate DECLINE to fire.+ *+ * ## What an entry may honestly claim+ *+ * A negative here is a claim about the MODEL, not about any endpoint+ * serving it. An open-weight checkpoint has no operator who could+ * decommission it - that is the fact the entry records - while the+ * third-party endpoint an operator points `embedding_base_url` at can+ * disappear tomorrow. That is a liveness question and `o2b search check`+ * already owns it with a live probe.+ *+ * Nothing in this module names a vendor. The resolved `provider` is one of+ * four TRANSPORT kinds (`openai-compat`, `zeroentropy`, `local`,+ * `disabled`); vendor identity exists only inside a free-form+ * `embedding_base_url` that nothing in the tree maps, so a message that+ * named one would be inferring it from a URL.+ *+ * Pure and injectable: the clock is a parameter and so is the survey, so+ * every state below is reachable from a test without moving a wall clock+ * or editing the shipped table.+ */++import { isValidIsoInstant, parseIsoUtc } from "../../brain/health/iso-time.ts";+import { EMBEDDING_MODEL_PRESETS } from "./presets.ts";+import { LOCAL_EMBEDDING_MODEL } from "./signature.ts";++// ----- Vocabularies ---------------------------------------------------------++/**+ * What this build can say about one model's decommission.+ *+ * `unsurveyed` and `none_announced` are separate members and that+ * separation is the unit: one says the survey looked and found no+ * announcement, the other says the survey never looked at this model.+ */+export const EMBEDDING_SUNSET = Object.freeze({+ /** The survey declares a decommission date for this model. */+ announced: "announced",+ /** The survey covers this model and records no announcement. */+ noneAnnounced: "none_announced",+ /** The model is outside the survey; no statement either way. */+ unsurveyed: "unsurveyed",+ /** No verdict was reached; {@link EmbeddingSunsetVerdict.reason} says why. */+ undetermined: "undetermined",+} as const);++/** Closed union over {@link EMBEDDING_SUNSET}. */+export type EmbeddingSunsetState = (typeof EMBEDDING_SUNSET)[keyof typeof EMBEDDING_SUNSET];++/** Membership list, ordered from most to least that can be said. */+export const EMBEDDING_SUNSET_STATES: ReadonlyArray<EmbeddingSunsetState> = Object.freeze([+ EMBEDDING_SUNSET.announced,+ EMBEDDING_SUNSET.noneAnnounced,+ EMBEDDING_SUNSET.unsurveyed,+ EMBEDDING_SUNSET.undetermined,+]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isEmbeddingSunsetState(value: unknown): value is EmbeddingSunsetState {+ return (+ typeof value === "string" && (EMBEDDING_SUNSET_STATES as ReadonlyArray<string>).includes(value)+ );+}++/**+ * Why no verdict was reached. A separate vocabulary so a guard cannot let+ * `survey_stale` be read back where a state belongs.+ */+export const EMBEDDING_SUNSET_UNDETERMINED_REASON = Object.freeze({+ /** No embedding model resolved from the configuration. */+ modelUnresolved: "model_unresolved",+ /** The survey's own review date is older than the horizon. */+ surveyStale: "survey_stale",+ /**+ * A survey entry carries a date this build cannot parse.+ *+ * Produced by the SHIPPED table going wrong, which is why it survives+ * while its declaration-side twin did not: the survey is data compiled+ * into the binary and injectable at the check's own factory+ * (`makeEmbeddingSunsetCheck`), so a release that mistypes a date has+ * to say so rather than report the model as un-announced. The+ * operator's declaration has no such gap - see+ * {@link classifyEmbeddingSunset}.+ */+ surveyEntryMalformed: "survey_entry_malformed",+} as const);++/** Closed union over {@link EMBEDDING_SUNSET_UNDETERMINED_REASON}. */+export type EmbeddingSunsetUndeterminedReason =+ (typeof EMBEDDING_SUNSET_UNDETERMINED_REASON)[keyof typeof EMBEDDING_SUNSET_UNDETERMINED_REASON];++/** Membership list for {@link EMBEDDING_SUNSET_UNDETERMINED_REASON}. */+export const EMBEDDING_SUNSET_UNDETERMINED_REASONS: ReadonlyArray<EmbeddingSunsetUndeterminedReason> =+ Object.freeze([+ EMBEDDING_SUNSET_UNDETERMINED_REASON.modelUnresolved,+ EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyStale,+ EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyEntryMalformed,+ ]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isEmbeddingSunsetUndeterminedReason(+ value: unknown,+): value is EmbeddingSunsetUndeterminedReason {+ return (+ typeof value === "string" &&+ (EMBEDDING_SUNSET_UNDETERMINED_REASONS as ReadonlyArray<string>).includes(value)+ );+}++/**+ * Which layer answered.+ *+ * A closed vocabulary rather than a boolean because there are three+ * answers, not two: the operator's declaration, this build's table, and+ * NEITHER - which is what `unsurveyed` and `undetermined` rest on. A+ * boolean would have made "came from the survey" and "came from nowhere"+ * the same value.+ */+export const EMBEDDING_SUNSET_SOURCE = Object.freeze({+ /** The operator declared this date in `Brain/_brain.yaml`. */+ declaration: "declaration",+ /** This build's shipped survey answered. */+ survey: "survey",+ /** Neither layer had anything to say about the model. */+ none: "none",+} as const);++/** Closed union over {@link EMBEDDING_SUNSET_SOURCE}. */+export type EmbeddingSunsetSource =+ (typeof EMBEDDING_SUNSET_SOURCE)[keyof typeof EMBEDDING_SUNSET_SOURCE];++/** Membership list, in precedence order. */+export const EMBEDDING_SUNSET_SOURCES: ReadonlyArray<EmbeddingSunsetSource> = Object.freeze([+ EMBEDDING_SUNSET_SOURCE.declaration,+ EMBEDDING_SUNSET_SOURCE.survey,+ EMBEDDING_SUNSET_SOURCE.none,+]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isEmbeddingSunsetSource(value: unknown): value is EmbeddingSunsetSource {+ return (+ typeof value === "string" && (EMBEDDING_SUNSET_SOURCES as ReadonlyArray<string>).includes(value)+ );+}++// ----- The survey -----------------------------------------------------------++/** One model somebody looked up, and what they found. */+export interface EmbeddingSunsetEntry {+ /** Exact model string, matched the way `findEmbeddingPreset` matches. */+ readonly model: string;+ /**+ * Announced decommission date (`YYYY-MM-DD` or a full ISO instant), or+ * `null` for an explicit surveyed NEGATIVE: this model was looked up and+ * no decommission had been announced as of the survey's review date.+ */+ readonly sunsetAt: string | null;+ /** Where the answer came from. Never empty - a claim owes its origin. */+ readonly source: string;+ /** Anything a reader needs beyond the date itself. */+ readonly note: string;+}++export interface EmbeddingSunsetSurvey {+ /** `YYYY-MM-DD` the whole table was last checked. Bounds every negative. */+ readonly reviewedAt: string;+ readonly entries: ReadonlyArray<EmbeddingSunsetEntry>;+}++/**+ * How long a NEGATIVE stays believable.+ *+ * A year, because that is the period over which "nobody has announced+ * anything" stops being a fact somebody established and becomes a fact+ * nobody re-checked. It bounds only the negatives: an announced date is+ * still reported from an older survey, with its age named.+ */+export const EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS = 365;++const MS_PER_DAY = 24 * 60 * 60 * 1000;++/**+ * Justification shared by every open-weight row below. Stated once because+ * it is one argument, not six: nobody operates these checkpoints, so there+ * is no party with the authority to announce a decommission. The endpoint+ * an operator points at CAN disappear, which is a liveness question+ * `o2b search check` probes live and this table does not answer.+ */+const OPEN_CHECKPOINT_SOURCE =+ "open-weight checkpoint distributed under a public licence: there is no operator of a hosted " ++ "endpoint with the authority to decommission the model itself";++function openCheckpoint(model: string): EmbeddingSunsetEntry {+ return {+ model,+ sunsetAt: null,+ source: OPEN_CHECKPOINT_SOURCE,+ note: "the endpoint serving it can still be withdrawn; that is liveness, not a sunset",+ };+}++/** Where the OpenAI rows below were read from. Cited, not remembered. */+const OPENAI_DEPRECATIONS_URL = "https://developers.openai.com/api/docs/deprecations";++/**+ * The one embedding deprecation that page carries, and the only positive+ * this build can source.+ *+ * Announced 2023-07-06, shut down 2024-01-04, replacement+ * `text-embedding-3-small`. The date is in the PAST, which is not a+ * weakness of the entry - it is the arm that matters most. An operator+ * restoring an old configuration, or copying one out of a years-old+ * tutorial, is told the model is already gone instead of watching the+ * first index build fail against an endpoint that no longer answers.+ */+const OPENAI_FIRST_GENERATION_SHUTDOWN = "2024-01-04";++const OPENAI_FIRST_GENERATION_SOURCE =+ `OpenAI deprecations, announced 2023-07-06, shutdown ${OPENAI_FIRST_GENERATION_SHUTDOWN}, ` ++ `replacement text-embedding-3-small: ${OPENAI_DEPRECATIONS_URL}`;++/**+ * Every model named in that entry, verbatim. Listed rather than pattern+ * matched: `text-search-ada-doc-001` is shut down and+ * `text-embedding-ada-002` is not, so a prefix rule over "ada" would+ * report a live model as decommissioned.+ */+const OPENAI_FIRST_GENERATION_EMBEDDINGS: ReadonlyArray<string> = Object.freeze([+ "text-similarity-ada-001",+ "text-search-ada-doc-001",+ "text-search-ada-query-001",+ "code-search-ada-code-001",+ "code-search-ada-text-001",+ "text-similarity-babbage-001",+ "text-search-babbage-doc-001",+ "text-search-babbage-query-001",+ "code-search-babbage-code-001",+ "code-search-babbage-text-001",+ "text-similarity-curie-001",+ "text-search-curie-doc-001",+ "text-search-curie-query-001",+ "text-similarity-davinci-001",+ "text-search-davinci-doc-001",+ "text-search-davinci-query-001",+]);++/**+ * The hosted models this repository already names in `EMBEDDING_PRICING`.+ *+ * These are SOURCED negatives, not assumed ones: the deprecations page+ * carries exactly one embedding entry and none of these three appears in+ * it. That is a real reading of a real page, which is what separates a+ * negative worth recording from the silence this check exists to remove.+ */+const OPENAI_CURRENT_EMBEDDINGS: ReadonlyArray<string> = Object.freeze([+ "text-embedding-3-small",+ "text-embedding-3-large",+ "text-embedding-ada-002",+]);++/**+ * The shipped survey.+ *+ * Adding an entry is a one-line edit plus a bump of `reviewedAt`; every+ * row owes a `source` and a test enforces it.+ */+export const EMBEDDING_SUNSET_SURVEY: EmbeddingSunsetSurvey = Object.freeze({+ reviewedAt: "2026-08-15",+ entries: Object.freeze([+ ...OPENAI_FIRST_GENERATION_EMBEDDINGS.map((model) => ({+ model,+ sunsetAt: OPENAI_FIRST_GENERATION_SHUTDOWN,+ source: OPENAI_FIRST_GENERATION_SOURCE,+ note: "first-generation OpenAI embedding model; the endpoint stopped answering on the date",+ })),+ ...OPENAI_CURRENT_EMBEDDINGS.map((model) => ({+ model,+ sunsetAt: null,+ source: `not listed in any deprecation entry on ${OPENAI_DEPRECATIONS_URL} as of the review date`,+ note: "a hosted model, so this negative is the one on this table with a real expiry",+ })),+ {+ model: LOCAL_EMBEDDING_MODEL,+ sunsetAt: null,+ source: "this build ships the local embedder, so this project is the only party that could",+ note: "a hashing embedder with no service behind it; retiring it would be a release note",+ },+ ...EMBEDDING_MODEL_PRESETS.map((preset) => openCheckpoint(preset.model)),+ ]),+});++// ----- The classifier -------------------------------------------------------++/**+ * An operator's own record of an announcement they have read.+ *+ * It names its MODEL explicitly rather than meaning "whatever is+ * configured". A declaration that meant the latter would silently+ * re-target itself the next time `embedding_model` changed, asserting one+ * vendor's shutdown date about a different vendor's model - which is the+ * confidently-wrong output this whole unit exists to prevent.+ */+export interface EmbeddingSunsetDeclaration {+ readonly model: string;+ readonly sunsetAt: string;+}++export interface EmbeddingSunsetVerdict {+ readonly state: EmbeddingSunsetState;+ /** The model the verdict is about, or `null` when none resolved. */+ readonly model: string | null;+ /** The declared date, or `null` for every other state. */+ readonly sunset_at: string | null;+ /** Whole days until the date; negative once it has passed. */+ readonly days_remaining: number | null;+ /** Why no verdict was reached, or `null` when one was. */+ readonly reason: EmbeddingSunsetUndeterminedReason | null;+ /** The survey review date this verdict rests on. */+ readonly surveyed_at: string;+ /** Which layer answered. */+ readonly source: EmbeddingSunsetSource;+ /**+ * True when a declaration answered AND the survey held a different+ * answer for the same model. Distinguishes "the survey said nothing+ * about this model" from "the survey disagreed" - one of the two+ * records is then wrong, and hiding either is how a wrong date+ * survives.+ */+ readonly overrode_survey: boolean;+ /**+ * What the survey held for this model when a declaration overrode it: a+ * date, or `null` meaning the survey recorded no announcement. Only+ * meaningful alongside {@link overrode_survey}.+ */+ readonly survey_sunset_at: string | null;+}++function undetermined(+ model: string | null,+ reason: EmbeddingSunsetUndeterminedReason,+ surveyedAt: string,+): EmbeddingSunsetVerdict {+ return {+ state: EMBEDDING_SUNSET.undetermined,+ model,+ sunset_at: null,+ days_remaining: null,+ reason,+ surveyed_at: surveyedAt,+ source: EMBEDDING_SUNSET_SOURCE.none,+ overrode_survey: false,+ survey_sunset_at: null,+ };+}++/**+ * What the survey says about `model` at `nowMs`.+ *+ * Lookup is by exact model string with no family heuristic, for the reason+ * `declaredInputWindowTokens` gives: a lifecycle differs between+ * checkpoints of one family, so inferring a date from a shared prefix+ * would invent the value.+ *+ * Nothing here reads a global clock, and nothing here refuses a FUTURE+ * instant. The future-instant refusals elsewhere in this codebase+ * (`usableAuthoredAtSeconds`, the stale-dependency filter) discard a+ * declared time later than the reading clock; a sunset date is supposed to+ * be later than the reading clock, so only the injectable-clock half of+ * that idiom applies.+ */+export function classifyEmbeddingSunset(+ model: string | null,+ nowMs: number,+ survey: EmbeddingSunsetSurvey = EMBEDDING_SUNSET_SURVEY,+ declaration?: EmbeddingSunsetDeclaration,+): EmbeddingSunsetVerdict {+ const reviewedAt = survey.reviewedAt;+ if (model === null || model.trim() === "") {+ return undetermined(null, EMBEDDING_SUNSET_UNDETERMINED_REASON.modelUnresolved, reviewedAt);+ }+ const entry = survey.entries.find((e) => e.model === model) ?? null;++ // The operator's layer first. It exists BECAUSE a table baked into the+ // binary goes stale between releases, and whoever wrote it has just+ // read the announcement; the survey was frozen at release. A+ // declaration about some OTHER model is not about this one and does not+ // participate - see EmbeddingSunsetDeclaration for why it names its+ // model rather than meaning "whatever is configured".+ if (declaration !== undefined && declaration.model === model) {+ if (!isValidIsoInstant(declaration.sunsetAt)) {+ // Not a verdict, because no vault can reach this. `sunset_at` is+ // validated with this same predicate by `parseEmbeddingsBlock`,+ // which is the ONLY producer of `BrainConfig.embeddings` and throws+ // a `BrainConfigError` naming the key - so an operator who mistypes+ // the date is told at load time, long before any check runs. An+ // `undetermined/declaration_malformed` verdict here would be a+ // reported state with a four-sentence operator message and no input+ // that could produce it, which is the defect this release removes.+ // A caller that reaches this has skipped the parser, and that is a+ // programming error: it gets said rather than turned into a+ // fabricated instant.+ throw new TypeError(+ `classifyEmbeddingSunset: declared sunsetAt for ${model} is not an ISO-8601 instant ` ++ `(${declaration.sunsetAt}); declarations come from parseEmbeddingsBlock, which ` ++ "validates them",+ );+ }+ // A disagreement is carried, not erased: one of the two records is+ // wrong, and a silent override is how the wrong one survives.+ const disagrees = entry !== null && entry.sunsetAt !== declaration.sunsetAt;+ return {+ state: EMBEDDING_SUNSET.announced,+ model,+ sunset_at: declaration.sunsetAt,+ days_remaining: Math.floor((parseIsoUtc(declaration.sunsetAt) - nowMs) / MS_PER_DAY),+ reason: null,+ surveyed_at: reviewedAt,+ source: EMBEDDING_SUNSET_SOURCE.declaration,+ overrode_survey: disagrees,+ survey_sunset_at: disagrees ? entry.sunsetAt : null,+ };+ }++ if (entry === null) {+ return {+ state: EMBEDDING_SUNSET.unsurveyed,+ model,+ sunset_at: null,+ days_remaining: null,+ reason: null,+ surveyed_at: reviewedAt,+ source: EMBEDDING_SUNSET_SOURCE.none,+ overrode_survey: false,+ survey_sunset_at: null,+ };+ }+ if (entry.sunsetAt !== null) {+ if (!isValidIsoInstant(entry.sunsetAt)) {+ // Refused loudly rather than folded into "absent": a date this+ // build cannot read is a defect in the table, and reporting it as+ // "no announcement" would hide the one thing worth fixing.+ return undetermined(+ model,+ EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyEntryMalformed,+ reviewedAt,+ );+ }+ return {+ state: EMBEDDING_SUNSET.announced,+ model,+ sunset_at: entry.sunsetAt,+ days_remaining: Math.floor((parseIsoUtc(entry.sunsetAt) - nowMs) / MS_PER_DAY),+ reason: null,+ surveyed_at: reviewedAt,+ source: EMBEDDING_SUNSET_SOURCE.survey,+ overrode_survey: false,+ survey_sunset_at: null,+ };+ }+ // A surveyed NEGATIVE, and negatives expire.+ const reviewedMs = parseIsoUtc(reviewedAt);+ const staleAfter = reviewedMs + EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS * MS_PER_DAY;+ if (!Number.isFinite(reviewedMs) || nowMs > staleAfter) {+ return undetermined(model, EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyStale, reviewedAt);+ }+ return {+ state: EMBEDDING_SUNSET.noneAnnounced,+ model,+ sunset_at: null,+ days_remaining: null,+ reason: null,+ surveyed_at: reviewedAt,+ source: EMBEDDING_SUNSET_SOURCE.survey,+ overrode_survey: false,+ survey_sunset_at: null,+ };+}diff --git a/src/core/search/embeddings/zeroentropy.ts b/src/core/search/embeddings/zeroentropy.tsindex cdf88ee1..949a976d 100644--- a/src/core/search/embeddings/zeroentropy.ts+++ b/src/core/search/embeddings/zeroentropy.ts@@ -11,7 +11,8 @@** `results` preserves input order (there is no per-item index field), so* vectors map positionally. Network discipline mirrors the OpenAI-compat- * provider: bounded concurrency, per-request timeout, batches closing on+ * provider: concurrency bounded process-wide per provider identity and+ * endpoint (`provider-semaphore.ts`), per-request timeout, batches closing on* whichever of `embedding_batch_size` / `embedding_batch_tokens` fills* first, retry on 429/5xx and network/timeout with jittered backoff,* vectors unit-normalised so cosine equals 1 - L2²/2.@@ -26,12 +27,12 @@ import type { ResolvedEmbeddingConfig } from "../types.ts";import type { EmbeddingProvider, PingResult } from "./contract.ts";import {RETRYABLE_STATUSES,- Semaphore,chunkArrayByTokenBudget,jittered,sleep,unitNormaliseInPlace,} from "./http-util.ts";+import { providerCeilingKey, providerSemaphore } from "./provider-semaphore.ts";const ZEROENTROPY_INPUT_TYPE = "document";@@ -77,6 +78,12 @@ export class ZeroEntropyProvider implements EmbeddingProvider {private readonly http: ResolvedHttp;private readonly backoffMs: ReadonlyArray<number>;private retriesSeen = 0;+ /**+ * Registry key of the process-wide ceiling this provider shares.+ * Resolved once, from the CONFIGURED identity, so it cannot move when+ * `_dimension` is learned from the first response.+ */+ private readonly ceilingKey: string;constructor(config: ResolvedEmbeddingConfig, opts?: ZeroEntropyProviderOptions) {this.config = config;@@ -84,6 +91,7 @@ export class ZeroEntropyProvider implements EmbeddingProvider {this.model = config.model!;this._dimension = config.dimension;this.backoffMs = opts?.backoffMs ?? [1000, 2000];+ this.ceilingKey = providerCeilingKey(this.name, config, this.http.url);}get dimension(): number | null {@@ -104,12 +112,12 @@ export class ZeroEntropyProvider implements EmbeddingProvider {this.config.batchTokens,(b) => b.text,);- const sem = new Semaphore(this.config.concurrency);+ const sem = providerSemaphore(this.ceilingKey, this.config.concurrency);const out: number[][] = new Array(texts.length);const cancel = new AbortController();const tasks = batches.map(async (batch) => {- await sem.acquire();+ const permit = await sem.acquire();try {if (cancel.signal.aborted) return;const vectors = await this.embedBatchWithRetry(@@ -120,7 +128,7 @@ export class ZeroEntropyProvider implements EmbeddingProvider {out[batch[i]!.originalIndex] = vectors[i]!;}} finally {- sem.release();+ permit();}});diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.tsindex d431cc96..79c9f0e3 100644--- a/src/core/search/indexer.ts+++ b/src/core/search/indexer.ts@@ -64,6 +64,12 @@ import { normalizeSchemaToken } from "../brain/schema-vocab.ts";import type { DegradationNotice } from "../integrity/degradation.ts";import { parseFrontmatterTextWithNotices } from "../vault.ts";import { appendMetric } from "../brain/metrics.ts";+import {+ OPERATION,+ progressCounter,+ withProgressAsync,+ type ProgressCounter,+} from "../brain/progress.ts";import { throwIfAborted } from "../brain/safeguard.ts";import { extractEntities } from "./entities.ts";import { compareStamps, formatStampMismatch, type StampMismatch } from "../integrity/stamp.ts";@@ -121,6 +127,17 @@ export interface IndexVaultOptions {* completion, so an aborted run leaves a consistent partial index.*/readonly signal?: AbortSignal;+ /**+ * Live progress observer (nothing-runs-unwatched, U1). Distinct from+ * {@link IndexVaultOptions.onFile}, which reports WHAT happened to each+ * file for the `--verbose` human stream; this reports HOW FAR the run+ * has got, in the one shape every long operation here uses.+ *+ * The walk phase carries no denominator and cannot: `walkVault` is a+ * generator, and counting first costs a second full traversal. The+ * embed phase carries one, because its pending list is an array.+ */+ readonly onProgress?: import("../brain/progress.ts").ProgressSink;}/** Site recorded on the frontmatter notices an index run collects. */@@ -300,10 +317,35 @@ export async function indexVault(return indexInto(config, opts);}+/**+ * @param outerProgress The RUN's counter when the caller owns it.+ * `reindexVault` does, because its run is not over when this build is:+ * the rebuild only becomes real at the swap. A build reporting into a+ * borrowed counter must not terminate it - the owner does that, on the+ * far side of the work this build does not know about.+ */async function indexInto(config: ResolvedSearchConfig,opts?: IndexVaultOptions,storeOverride?: Store,+ outerProgress?: ProgressCounter,+): Promise<IndexStats> {+ if (outerProgress !== undefined) {+ outerProgress.start(INDEX_STAGE.walk);+ return await indexIntoRun(config, outerProgress, opts, storeOverride);+ }+ const progress = progressCounter(OPERATION.reindex, opts?.onProgress);+ progress.start(INDEX_STAGE.walk);+ return await withProgressAsync(progress, () =>+ indexIntoRun(config, progress, opts, storeOverride),+ );+}++async function indexIntoRun(+ config: ResolvedSearchConfig,+ progress: ProgressCounter,+ opts?: IndexVaultOptions,+ storeOverride?: Store,): Promise<IndexStats> {const t0 = Date.now();const ownsStore = !storeOverride;@@ -326,6 +368,7 @@ async function indexInto(// Per-file document upserts are transactional, so a tripped// guard leaves a consistent (partially refreshed) index.opts?.safeguard?.checkpoint();+ progress.advance(INDEX_STAGE.walk);// On-demand cancellation, same boundary as the deadline.throwIfAborted(opts?.signal, "index");// Mark seen FIRST. If anything downstream throws (read fault,@@ -565,6 +608,7 @@ async function indexInto(forceCost: opts?.forceCost === true,...(opts?.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),...(opts?.signal !== undefined ? { signal: opts.signal } : {}),+ progress,});stats.backend = "semantic";stats.deferredReason = null;@@ -788,6 +832,27 @@ async function formatChunkWindowMeasured(* standalone vector backfill without either knowing about the other;* `MutableStats` satisfies it structurally.*/+/**+ * The spans an index run has. `walk` cannot carry a denominator -+ * `walkVault` is a generator and counting first costs a second full+ * traversal - while `embed` always can, because its pending list is an+ * array before the loop starts. One event shape carries all of them.+ *+ * `lock` and `swap` belong to a REBUILD only, and both exist because a+ * rebuild is not over when its build is. `lock` covers the wait on+ * `acquireWriterLock`, which can be the length of a competing reindex and+ * which used to emit nothing at all - the silence this release calls+ * indistinguishable from a hang. `swap` covers the two renames that make+ * the staging build real; before it, the stream reported `finished` while+ * the live index was still the old one.+ */+const INDEX_STAGE = Object.freeze({+ lock: "lock",+ walk: "walk",+ embed: "embed",+ swap: "swap",+} as const);+export interface EmbeddingPhaseTally {embeddingsComputed: number;embeddingsRetries: number;@@ -798,6 +863,19 @@ export interface EmbeddingPhaseOptions {readonly forceCost?: boolean;readonly safeguard?: import("../brain/safeguard.ts").Safeguard;readonly signal?: AbortSignal;+ /**+ * The RUN's progress counter, not a sink of its own.+ *+ * This phase is the half of an index run that can report a fraction -+ * the pending list is an array before the loop starts - but it is a+ * PHASE, not a run: it is called both from `indexInto` and standalone+ * by the vector backfill. Given a sink it would build a second counter,+ * and a stream carrying two terminators cannot say which one ended the+ * run. So the caller that owns the run owns the counter, and this phase+ * borrows it. That is why `progress-census.test.ts` carries a written+ * exemption for this interface rather than a sink.+ */+ readonly progress?: import("../brain/progress.ts").ProgressCounter;}/**@@ -822,6 +900,7 @@ export async function runEmbeddingPhase(const forceCost = opts.forceCost === true;const safeguard = opts.safeguard;const signal = opts.signal;+ const progress = opts.progress;if (!config.semantic.enabled) {throw new SearchError("EMBEDDING_DISABLED",@@ -876,12 +955,14 @@ export async function runEmbeddingPhase(// `embedding_concurrency`.const superBatch = batchSize * Math.max(1, config.semantic.concurrency);+ progress?.start(INDEX_STAGE.embed, pending.length);for (let i = 0; i < pending.length; i += superBatch) {// Cooperative deadline: embedding batches are the other long// phase of an index run - abort between batches, never mid-batch.safeguard?.checkpoint();throwIfAborted(signal, "index");const batch = pending.slice(i, i + superBatch);+ progress?.advance(INDEX_STAGE.embed, batch.length);const texts = batch.map((p) => p.content);const vectors = await provider.embed(texts, "passage");stats.embeddingsRetries += provider.consumeRetryCount?.() ?? 0;@@ -920,12 +1001,37 @@ export async function runEmbeddingPhase(export async function reindexVault(config: ResolvedSearchConfig,opts?: IndexVaultOptions,+): Promise<IndexStats> {+ // The rebuild owns the run's counter from before the lock wait to after+ // the swap, and hands it to the staging build rather than letting that+ // build open one of its own. Two reasons, and they are the same reason+ // twice: a rebuild is not finished when its build is. `indexVault`'s+ // own counter terminated at the end of the build, so a caller tailing+ // the stream read `finished` while the live index was still the old one+ // and the rename that makes the rebuild real had not been attempted -+ // and if that rename then failed (ENOSPC, EPERM, a cross-device+ // `dbPath`), the command exited non-zero after a terminator that said+ // the run had finished.+ const progress = progressCounter(OPERATION.reindex, opts?.onProgress);+ return await withProgressAsync(progress, () => reindexInto(config, progress, opts));+}++async function reindexInto(+ config: ResolvedSearchConfig,+ progress: ProgressCounter,+ opts?: IndexVaultOptions,): Promise<IndexStats> {const newPath = config.dbPath + ".new";const bakPath = config.dbPath + ".bak";mkdirSync(dirname(config.dbPath), { recursive: true });+ // Opened BEFORE the wait, not after it. `acquireWriterLock` can block+ // for the whole duration of a competing reindex, and a stream that+ // emits nothing while it does is the state this release names as+ // indistinguishable from a hang.+ progress.start(INDEX_STAGE.lock, 1);+// Hold the writer lock on the LIVE index path for the whole rebuild +// swap. Keyed on `config.dbPath` (not the `.new` staging path), so a// second concurrent reindex — the double-reindex a schema-bump upgrade@@ -935,6 +1041,7 @@ export async function reindexVault(// live index (INDEX_UNREADABLE, silent data loss). The staging-DB opens// below lock a different path (`.new`), so there is no self-deadlock.const release = await acquireWriterLock(config.dbPath);+ progress.advance(INDEX_STAGE.lock);try {// Build into the temp file with an override config.const tempConfig: ResolvedSearchConfig = Object.freeze({@@ -966,7 +1073,15 @@ export async function reindexVault(// `force: false` on resume lets the fastpath skip the files the// partial build already committed; a fresh build forces every file.- const stats = await indexVault(tempConfig, { ...opts, force: !resume });+ // `onProgress` is dropped from the forwarded options: the build+ // reports into THIS run's counter, passed explicitly, rather than+ // opening a second one over the same sink.+ const stats = await indexInto(+ tempConfig,+ { ...opts, force: !resume, onProgress: undefined },+ undefined,+ progress,+ );// Clear the marker so the swapped-in live index carries no staging// state. Only present when resume was enabled.@@ -980,9 +1095,11 @@ export async function reindexVault(// restoreFromBakIfMissing in store.ts), so it cannot restore the stale// `.bak` over the freshly built index; a genuine crash leaves the lock// stale and the .bak restore on the next Store.open recovers.+ progress.start(INDEX_STAGE.swap, 1);tryUnlink(bakPath);tryRename(config.dbPath, bakPath); // no-op (ENOENT) on fresh reindexrenameSync(newPath, config.dbPath); // must succeed — `newPath` was just built+ progress.advance(INDEX_STAGE.swap);return stats;} finally {await release();diff --git a/src/core/search/store/writer-lock.ts b/src/core/search/store/writer-lock.tsindex e7dcad87..007665b1 100644--- a/src/core/search/store/writer-lock.ts+++ b/src/core/search/store/writer-lock.ts@@ -51,6 +51,30 @@ export function acquireWriterLockSync(path: string): () => void {throw contentionError(lastError);}+/**+ * Whether the writer lock on `dbPath` is held by a live holder RIGHT NOW.+ *+ * ADVISORY, and only that. It answers about the instant it is called: the+ * lock can be taken or released the moment after it returns, so a caller+ * that acts on `false` is not excluded from anything - {@link+ * acquireWriterLock} is the only thing that excludes. What this buys is+ * cheaper contention, not exclusion: a caller about to start a rebuild it+ * can already see will lose can decline to start it at all.+ *+ * Same `stale` window as both acquire paths, so a lock whose holder was+ * SIGKILLed reads as free here exactly when it would be taken over there.+ * A stale lock is reported free without being removed - removing it is the+ * acquiring writer's business.+ *+ * Throws whatever the stat failed with (EACCES, ELOOP). It does NOT+ * collapse an unreadable lock directory to `false`: "the lock is free" and+ * "I could not find out" are different answers, and a caller that treats+ * the second as the first has been told something untrue.+ */+export function isWriterLockHeld(dbPath: string): boolean {+ return lockfile.checkSync(dbPath, { stale: WRITER_LOCK_STALE_MS, realpath: false });+}+/*** Acquire the exclusive writer lock on the LIVE index path. Shared by* `Store.open({ mode: "write" })` and `reindexVault`'s rebuild+swap so bothdiff --git a/src/core/search/vector-backfill.ts b/src/core/search/vector-backfill.tsindex c250d5d8..4a4934c8 100644--- a/src/core/search/vector-backfill.ts+++ b/src/core/search/vector-backfill.ts@@ -40,6 +40,12 @@ import { estimateCostUsd, estimateTokens, pricePerMillionTokens } from "./embeddimport { runEmbeddingPhase } from "./indexer.ts";import { Store } from "./store.ts";import type { ResolvedSearchConfig } from "./types.ts";+import {+ OPERATION,+ progressCounter,+ withProgressAsync,+ type ProgressCounter,+} from "../brain/progress.ts";export interface VectorBackfillOptions {/** When true, compute and store the missing vectors. Default false. */@@ -48,6 +54,13 @@ export interface VectorBackfillOptions {readonly forceCost?: boolean;readonly safeguard?: import("../brain/safeguard.ts").Safeguard;readonly signal?: AbortSignal;+ /**+ * Live progress observer (nothing-runs-unwatched, U1). This verb owns+ * the run - it holds the plan and the gate, and the embedding phase+ * holds the loop - so the counter is built here and lent to the phase.+ * One run, one counter, one terminator.+ */+ readonly onProgress?: import("../brain/progress.ts").ProgressSink;}export interface VectorBackfillResult {@@ -85,6 +98,19 @@ export interface VectorBackfillResult {export async function planVectorBackfill(config: ResolvedSearchConfig,opts: VectorBackfillOptions = {},+): Promise<VectorBackfillResult> {+ const progress = progressCounter(OPERATION.reindex, opts.onProgress);+ progress.start(VECTOR_BACKFILL_STAGE);+ return await withProgressAsync(progress, () => planVectorBackfillRun(config, opts, progress));+}++/** The one stage: the backfill plans, then lends the loop to the phase. */+const VECTOR_BACKFILL_STAGE = "plan";++async function planVectorBackfillRun(+ config: ResolvedSearchConfig,+ opts: VectorBackfillOptions,+ progress: ProgressCounter,): Promise<VectorBackfillResult> {const apply = opts.apply === true;const capability = resolveSemanticCapability(config.semantic);@@ -102,6 +128,7 @@ export async function planVectorBackfill(forceCost: opts.forceCost === true,...(opts.safeguard !== undefined ? { safeguard: opts.safeguard } : {}),...(opts.signal !== undefined ? { signal: opts.signal } : {}),+ progress,});}diff --git a/src/core/vault-backing.ts b/src/core/vault-backing.tsnew file mode 100644index 00000000..9a5ca143--- /dev/null+++ b/src/core/vault-backing.ts@@ -0,0 +1,240 @@+/**+ * What filesystem backs the resolved vault path.+ *+ * This module exists because of what it refuses to answer. The question it+ * was asked was "is this machine local, a cloud sandbox, or an ephemeral+ * container", and no signal a host exposes can settle it:+ *+ * - `/.dockerenv` is written by Docker and by nothing else. Absent is+ * the normal reading under podman, containerd/CRI-O, LXC,+ * systemd-nspawn, and any image that removed it.+ * - `/proc/1/cgroup` carried the classic heuristic on cgroup v1. On a+ * cgroup v2 unified host - what a current kernel gives you - the line+ * is `0::/<path>` inside a container and inside a plain systemd scope+ * alike, so the heuristic is dead rather than weakened.+ * - "cloud sandbox" has no signal that separates it from "container",+ * and "container" is not "ephemeral": a bind-mounted volume inside a+ * container outlives a laptop's `/tmp`.+ *+ * Every one of those signals is ONE-WAY. A positive is decent evidence of+ * containerisation; a negative is evidence of nothing at all. A classifier+ * built on them would answer "local, therefore durable" on exactly the+ * hosts where the answer matters most, which is a confident wrong answer+ * in place of an honest missing one.+ *+ * What CAN be established is narrower and is the claim an ownership+ * statement actually makes: which filesystem backs ONE path. A vault on+ * `tmpfs` is provably gone at reboot. A vault on an overlay is very likely+ * gone at container exit, and is at least not a plain disk. A vault on+ * ext4/xfs/btrfs/zfs is backed by storage that survives the process.+ * Everything else - an unrecognised magic number, a path that will not+ * stat, a platform with no such facility at all - is+ * {@link VAULT_BACKING.undetermined}, with a reason from a SEPARATE+ * vocabulary so a guard can never read a reason back as a verdict.+ *+ * The probe is Linux-only by construction. `statfs(2)`'s `f_type` is a+ * Linux filesystem magic number; the same field on macOS and the BSDs+ * means something else, so every other platform answers+ * `probe_unsupported` rather than being handed a number to misread.+ *+ * Pure and injectable: the platform and the `statfs` call are parameters,+ * so every state below is reachable in a unit test on any host.+ */++import { statfsSync } from "node:fs";++// ----- The verdict vocabulary ----------------------------------------------++/**+ * What the filesystem under a path says about the path's survival.+ *+ * Deliberately absent: any member meaning "local machine", "cloud+ * sandbox" or "ephemeral". See the module docblock - no signal separates+ * them, and naming one would be the guess this design exists to refuse.+ */+export const VAULT_BACKING = Object.freeze({+ /** Backed by storage that survives the process and a reboot. */+ durable: "durable",+ /** Proved memory-backed: the contents are gone at reboot. */+ volatile: "volatile",+ /** Proved container-overlay-backed: survival past container exit unknown. */+ layered: "layered",+ /** No verdict was reached; {@link VaultBackingVerdict.reason} says why. */+ undetermined: "undetermined",+} as const);++/** Closed union over {@link VAULT_BACKING}. */+export type VaultBackingState = (typeof VAULT_BACKING)[keyof typeof VAULT_BACKING];++/** Membership list, in order from most durable to least known. */+export const VAULT_BACKING_STATES: ReadonlyArray<VaultBackingState> = Object.freeze([+ VAULT_BACKING.durable,+ VAULT_BACKING.layered,+ VAULT_BACKING.volatile,+ VAULT_BACKING.undetermined,+]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isVaultBackingState(value: unknown): value is VaultBackingState {+ return (+ typeof value === "string" && (VAULT_BACKING_STATES as ReadonlyArray<string>).includes(value)+ );+}++/**+ * Why the probe reached no verdict.+ *+ * A separate vocabulary rather than three more members on the one above,+ * because a reason is not a verdict: folding them together lets a guard+ * accept `path_unreadable` everywhere a state is expected, and lets a+ * renderer print a cause where a conclusion belongs.+ */+export const VAULT_BACKING_UNDETERMINED_REASON = Object.freeze({+ /** The platform exposes no filesystem-type facility this build can read. */+ probeUnsupported: "probe_unsupported",+ /** The path could not be stat'd at all. */+ pathUnreadable: "path_unreadable",+ /** A filesystem magic number this build does not recognise. */+ fsTypeUnknown: "fs_type_unknown",+} as const);++/** Closed union over {@link VAULT_BACKING_UNDETERMINED_REASON}. */+export type VaultBackingUndeterminedReason =+ (typeof VAULT_BACKING_UNDETERMINED_REASON)[keyof typeof VAULT_BACKING_UNDETERMINED_REASON];++/** Membership list for {@link VAULT_BACKING_UNDETERMINED_REASON}. */+export const VAULT_BACKING_UNDETERMINED_REASONS: ReadonlyArray<VaultBackingUndeterminedReason> =+ Object.freeze([+ VAULT_BACKING_UNDETERMINED_REASON.probeUnsupported,+ VAULT_BACKING_UNDETERMINED_REASON.pathUnreadable,+ VAULT_BACKING_UNDETERMINED_REASON.fsTypeUnknown,+ ]);++/** Narrow a string read back off disk or across a tool boundary. */+export function isVaultBackingUndeterminedReason(+ value: unknown,+): value is VaultBackingUndeterminedReason {+ return (+ typeof value === "string" &&+ (VAULT_BACKING_UNDETERMINED_REASONS as ReadonlyArray<string>).includes(value)+ );+}++// ----- The probe ------------------------------------------------------------++/**+ * One answer. `filesystem` and `reason` are exclusive by construction: a+ * verdict names the filesystem it read, an `undetermined` names why it+ * read none, and neither ever carries both.+ */+export interface VaultBackingVerdict {+ readonly state: VaultBackingState;+ /** Recognised filesystem name, or `null` when the state is undetermined. */+ readonly filesystem: string | null;+ /** Why no verdict was reached, or `null` when one was. */+ readonly reason: VaultBackingUndeterminedReason | null;+ /** One line naming what was probed and what came back. */+ readonly detail: string;+}++/** The `statfs` facility, injectable so every branch is testable. */+export type StatfsProbe = (path: string) => { readonly type: number | bigint };++export interface VaultBackingOptions {+ /** Defaults to `process.platform`, following the house injection style. */+ readonly platform?: string;+ /** Defaults to `node:fs`'s `statfsSync`. */+ readonly statfs?: StatfsProbe;+}++/** The one platform whose `statfs` `f_type` is the magic number below. */+const PROBEABLE_PLATFORM = "linux";++/**+ * Linux filesystem magic numbers, each mapped to the state it proves.+ *+ * Only filesystems whose durability follows FROM THE TYPE are listed. A+ * type that is not here is `fs_type_unknown` rather than assumed durable -+ * the same polarity `declaredInputWindowTokens` uses for an unlisted+ * model, and for the same reason: reporting a pass for a condition nobody+ * measured is the misleading silence this release removes.+ *+ * Network filesystems are listed as durable deliberately. The vault living+ * on someone else's server is an availability question, not a survival+ * one: the bytes outlive this process and this reboot, which is the whole+ * claim the state makes.+ */+const FS_MAGIC: ReadonlyMap<number, { readonly name: string; readonly state: VaultBackingState }> =+ new Map([+ // Memory-backed: provably lost at reboot.+ [0x01021994, { name: "tmpfs", state: VAULT_BACKING.volatile }],+ [0x858458f6, { name: "ramfs", state: VAULT_BACKING.volatile }],+ // Union mount: a container's root by default, survival unknown.+ [0x794c7630, { name: "overlayfs", state: VAULT_BACKING.layered }],+ [0xaad7aaea, { name: "aufs", state: VAULT_BACKING.layered }],+ // Storage that outlives the process and a reboot.+ [0xef53, { name: "ext4", state: VAULT_BACKING.durable }],+ [0x9123683e, { name: "btrfs", state: VAULT_BACKING.durable }],+ [0x58465342, { name: "xfs", state: VAULT_BACKING.durable }],+ [0x2fc12fc1, { name: "zfs", state: VAULT_BACKING.durable }],+ [0xf2f52010, { name: "f2fs", state: VAULT_BACKING.durable }],+ [0x6969, { name: "nfs", state: VAULT_BACKING.durable }],+ [0xff534d42, { name: "cifs", state: VAULT_BACKING.durable }],+ [0x65735546, { name: "fuse", state: VAULT_BACKING.durable }],+ [0x4d44, { name: "vfat", state: VAULT_BACKING.durable }],+ [0x52654973, { name: "reiserfs", state: VAULT_BACKING.durable }],+ ]);++function hex(type: number): string {+ return `0x${type.toString(16)}`;+}++function undetermined(reason: VaultBackingUndeterminedReason, detail: string): VaultBackingVerdict {+ return { state: VAULT_BACKING.undetermined, filesystem: null, reason, detail };+}++/**+ * Probe the filesystem backing `path`.+ *+ * Never throws: a path that will not stat is a verdict, not a fault - this+ * runs beside an ownership statement whose whole point is that it stays+ * honest on hosts it cannot measure.+ */+export function probeVaultBacking(+ path: string,+ opts: VaultBackingOptions = {},+): VaultBackingVerdict {+ const platform = opts.platform ?? process.platform;+ if (platform !== PROBEABLE_PLATFORM) {+ return undetermined(+ VAULT_BACKING_UNDETERMINED_REASON.probeUnsupported,+ `the filesystem backing ${path} was not probed: statfs f_type is a ${PROBEABLE_PLATFORM} ` ++ `magic number and this host is ${platform}`,+ );+ }+ const statfs = opts.statfs ?? statfsSync;+ let type: number;+ try {+ type = Number(statfs(path).type);+ } catch (err) {+ return undetermined(+ VAULT_BACKING_UNDETERMINED_REASON.pathUnreadable,+ `the filesystem backing ${path} could not be read: ${+ err instanceof Error ? err.message : String(err)+ }`,+ );+ }+ const known = FS_MAGIC.get(type);+ if (known === undefined) {+ return undetermined(+ VAULT_BACKING_UNDETERMINED_REASON.fsTypeUnknown,+ `${path} is backed by filesystem type ${hex(type)}, which this build does not recognise`,+ );+ }+ return {+ state: known.state,+ filesystem: known.name,+ reason: null,+ detail: `${path} is backed by ${known.name} (${hex(type)})`,+ };+}diff --git a/src/mcp/brain/admin-tools.ts b/src/mcp/brain/admin-tools.tsindex add3b84f..4731ed6c 100644--- a/src/mcp/brain/admin-tools.ts+++ b/src/mcp/brain/admin-tools.ts@@ -30,7 +30,8 @@ import {materializeClusterNotes,} from "../../core/brain/link-graph/communities.ts";import { appendMetric } from "../../core/brain/metrics.ts";-import { createSafeguard, resolveSafeguardTimeoutMs } from "../../core/brain/safeguard.ts";+import type { ProgressSink } from "../../core/brain/progress.ts";+import { toolSafeguard } from "./shared.ts";import { currentLease } from "../../core/brain/maintenance/lease.ts";import { listJournal } from "../../core/brain/maintenance/journal.ts";import { runMaintenance, type DailyWindow } from "../../core/brain/maintenance/lane.ts";@@ -249,6 +250,7 @@ async function toolBrainSecrets(async function toolBrainMaintenance(ctx: ServerContext,args: Record<string, unknown>,+ onProgress?: ProgressSink,): Promise<Record<string, unknown>> {const op = args["operation"];if (op !== "run" && op !== "status") {@@ -293,12 +295,16 @@ async function toolBrainMaintenance(});// Same per-task deadlines as the CLI lane (t_06784b8d): one fresh// cooperative safeguard per task, budget resolved per-op -> global- // -> default.+ // -> default. The lane is the only surface that wants a guard PER+ // TASK rather than per call, so it names the shared factory four+ // times instead of holding one guard.const laneSafeguard = (operation: "dream" | "reindex" | "bridges" | "clusters") =>- createSafeguard({- operation,- timeoutMs: resolveSafeguardTimeoutMs(operation, ctx.configPath ?? undefined),- });+ toolSafeguard(ctx, operation);+ // The lane is a dispatcher over four long operations, not a fifth one,+ // so it forwards the caller's sink to each task rather than counting+ // tasks itself: every event names the operation that emitted it, which+ // is what tells a reader which of the four the lane is currently in.+ const laneProgress = onProgress ? { onProgress } : {};const result = await runMaintenance(ctx.vault, {now,holder: `${agent}@${process.pid}`,@@ -308,13 +314,16 @@ async function toolBrainMaintenance({name: "dream",run: async () => {- dream(ctx.vault, { now, safeguard: laneSafeguard("dream") });+ dream(ctx.vault, { now, safeguard: laneSafeguard("dream"), ...laneProgress });},},{name: "reindex",run: async () => {- await indexVault(searchConfig, { safeguard: laneSafeguard("reindex") });+ await indexVault(searchConfig, {+ safeguard: laneSafeguard("reindex"),+ ...laneProgress,+ });},},// Same lane contract as the CLI verb (link-recall-intelligence):@@ -329,6 +338,7 @@ async function toolBrainMaintenance(const report = discoverBridges(store, {dismissed: readDismissedBridges(ctx.vault),safeguard: laneSafeguard("bridges"),+ ...laneProgress,});writeBridgeProposals(ctx.vault, report, { now });try {@@ -355,7 +365,10 @@ async function toolBrainMaintenance(run: async () => {const store = await Store.open(searchConfig, { mode: "read" });try {- const communities = detectCommunities(store, { safeguard: laneSafeguard("clusters") });+ const communities = detectCommunities(store, {+ safeguard: laneSafeguard("clusters"),+ ...laneProgress,+ });const materialized = materializeClusterNotes(ctx.vault, communities, { store, now });try {appendMetric(ctx.vault, {diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.tsindex b8befee4..7138347b 100644--- a/src/mcp/brain/brief-tools.ts+++ b/src/mcp/brain/brief-tools.ts@@ -48,7 +48,10 @@ import {coercePositiveInteger,dispatchByView,localizeEnvelope,+ toolSafeguard,} from "./shared.ts";+import type { ProgressSink } from "../../core/brain/progress.ts";+import { OPERATION } from "../../core/brain/safeguard.ts";async function toolBrainMorningBrief(ctx: ServerContext,@@ -309,6 +312,7 @@ async function toolBrainMonthlyReview(async function toolBrainOperatorSummary(ctx: ServerContext,args: Record<string, unknown>,+ onProgress?: ProgressSink,): Promise<Record<string, unknown>> {const topRaw = args["top_actions"];let topActionsN: number | undefined;@@ -358,7 +362,18 @@ async function toolBrainOperatorSummary(let dreamError: string | undefined;if (includeDream) {try {- dreamSummary = dream(ctx.vault, { dryRun: true });+ // The one view behind this dispatcher that runs a consolidation+ // pass. It is a DRY RUN, and it still walks the whole Brain tree,+ // so it is the slow half of an operator summary on a large vault.+ dreamSummary = dream(ctx.vault, {+ dryRun: true,+ // A dry run is still a full synchronous pass over the Brain tree,+ // so it is bounded on the same terms as `brain_dream` itself -+ // the budget the operator set for `dream` governs every MCP call+ // that reaches one, not just the tool that carries its name.+ safeguard: toolSafeguard(ctx, OPERATION.dream),+ ...(onProgress !== undefined ? { onProgress } : {}),+ });} catch (err) {// Surface the failure so callers know the dashboard is missing// verification + dream signals; do not silently produce a@@ -428,7 +443,14 @@ async function toolBrainToday(}const BRIEF_VIEW_HANDLERS: Readonly<- Record<string, (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown>+ Record<+ string,+ (+ ctx: ServerContext,+ args: Record<string, unknown>,+ onProgress?: ProgressSink,+ ) => Promise<unknown> | unknown+ >> = Object.freeze({morning: toolBrainMorningBrief,daily: toolBrainDailyBrief,@@ -457,7 +479,11 @@ const BRIEF_VIEW_HANDLERS: Readonly<*/const AGENT_SCOPE_VIEWS: ReadonlySet<string> = new Set(["morning", "digest"]);-async function toolBrainBrief(ctx: ServerContext, args: Record<string, unknown>): Promise<unknown> {+async function toolBrainBrief(+ ctx: ServerContext,+ args: Record<string, unknown>,+ onProgress?: ProgressSink,+): Promise<unknown> {const view = typeof args["view"] === "string" ? args["view"] : "";const scopeSupplied =AGENT_SCOPE_ARG_NAME in args &&@@ -473,7 +499,7 @@ async function toolBrainBrief(ctx: ServerContext, args: Record<string, unknown>)`owner scoping is supported by view=${[...AGENT_SCOPE_VIEWS].join(", view=")}`,);}- return localizeEnvelope(ctx, await dispatchByView(BRIEF_VIEW_HANDLERS, ctx, args));+ return localizeEnvelope(ctx, await dispatchByView(BRIEF_VIEW_HANDLERS, ctx, args, onProgress));}export const BRIEF_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([diff --git a/src/mcp/brain/feedback-tools.ts b/src/mcp/brain/feedback-tools.tsindex 3702c661..db9291fb 100644--- a/src/mcp/brain/feedback-tools.ts+++ b/src/mcp/brain/feedback-tools.ts@@ -14,6 +14,7 @@ import {type AppendApplyEvidenceInput,} from "../../core/brain/apply-evidence.ts";import { dream, type DreamGateOverrides } from "../../core/brain/dream.ts";+import type { ProgressSink } from "../../core/brain/progress.ts";import {DREAM_GATE_NAMES,DreamGateOverrideError,@@ -64,7 +65,13 @@ import {type ObservedUseEntry,} from "../../core/brain/observed-use.ts";import { coerceStr, coerceBool, coerceIsoDate } from "../coerce.ts";-import { enforceCountGuard, readCountGuardArgs, vaultRelativeSafe } from "./shared.ts";+import {+ enforceCountGuard,+ readCountGuardArgs,+ toolSafeguard,+ vaultRelativeSafe,+} from "./shared.ts";+import { OPERATION } from "../../core/brain/safeguard.ts";/*** Build the slug used in the signal / preference filename. We never let@@ -339,6 +346,7 @@ function readDreamGates(args: Record<string, unknown>): DreamGateOverrides | undasync function toolBrainDream(ctx: ServerContext,args: Record<string, unknown>,+ onProgress?: ProgressSink,): Promise<Record<string, unknown>> {const action = args["action"] ?? "run";if (@@ -409,7 +417,17 @@ async function toolBrainDream(throw new MCPError(INVALID_PARAMS, `brain_dream action=${action}: run_id is required`);}const now = nowDate ?? new Date();- const stageOpts = { now, ...(agent ? { agentName: agent } : {}) };+ // The staged lifecycle runs the same consolidation pass `action=run`+ // does - `stage` previews it, `apply` promotes from it - so it is+ // bounded and reported on the same terms. Without the sink a client+ // that sent a progressToken for `action: "stage"` would be told+ // nothing and see nothing for the whole pass.+ const stageOpts = {+ now,+ safeguard: toolSafeguard(ctx, OPERATION.dream),+ ...(agent ? { agentName: agent } : {}),+ ...(onProgress ? { onProgress } : {}),+ };switch (action) {case "stage": {const bundle = stageDream(ctx.vault, stageOpts);@@ -461,11 +479,20 @@ async function toolBrainDream(}const { expect, strict } = readCountGuardArgs(args);+ // One deadline for the whole tool call, not one per pass. `dream()` is+ // synchronous, so an unbounded call blocks the server's event loop for+ // its entire duration and the client cannot even time out and reissue;+ // what has to be bounded is therefore the call, and a guarded run is+ // two passes over the same tree. Sharing the guard means a slow preview+ // spends the run's budget - which is the honest reading of a budget the+ // operator set for this operation.+ const safeguard = toolSafeguard(ctx, OPERATION.dream);// Only pay for a preview pass when a guard is actually requested; otherwise// the run is byte-identical to before.if (expect !== null || strict) {const preview = dream(ctx.vault, {dryRun: true,+ safeguard,...(nowDate ? { now: nowDate } : {}),...(agent ? { agentName: agent } : {}),// Preview the run being guarded, overrides and all.@@ -481,11 +508,18 @@ async function toolBrainDream(});}+ // The count-guard preview above is deliberately NOT reported on: it is+ // a dry run whose only purpose is to decide whether the run below may+ // happen at all, and a client that saw the same five stages twice+ // would read the second pass as a restart. Progress describes the run+ // the caller asked for.const summary = dream(ctx.vault, {dryRun,+ safeguard,...(nowDate ? { now: nowDate } : {}),...(agent ? { agentName: agent } : {}),...(gates !== undefined ? { gates } : {}),+ ...(onProgress ? { onProgress } : {}),});const changeList = dreamChangeList(summary);diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.tsindex ea8c9850..476db69c 100644--- a/src/mcp/brain/knowledge-tools.ts+++ b/src/mcp/brain/knowledge-tools.ts@@ -25,6 +25,8 @@ import {materializeClusterNotes,} from "../../core/brain/link-graph/communities.ts";import { appendMetric } from "../../core/brain/metrics.ts";+import { OPERATION } from "../../core/brain/safeguard.ts";+import type { ProgressSink } from "../../core/brain/progress.ts";import { parseFrontmatter } from "../../core/vault.ts";import { createTriggers } from "../../core/brain/triggers/store.ts";import {@@ -62,7 +64,7 @@ import { INVALID_PARAMS, MCPError } from "../protocol.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";import { AGENT_SCOPE_SCHEMA, coerceAgentScope, coerceStr, coerceBool } from "../coerce.ts";-import { coercePositiveInteger } from "./shared.ts";+import { coercePositiveInteger, toolSafeguard } from "./shared.ts";/** Forward-looking projection envelope; read-only fold. */function toolBrainForesight(@@ -93,6 +95,7 @@ function toolBrainForesight(async function toolBrainBridges(ctx: ServerContext,args: Record<string, unknown>,+ onProgress?: ProgressSink,): Promise<Record<string, unknown>> {const op = args["operation"];if (op !== "discover" && op !== "list" && op !== "accept" && op !== "dismiss") {@@ -171,6 +174,8 @@ async function toolBrainBridges(...(max !== undefined ? { maxProposals: max as number } : {}),...(minSimilarity !== undefined ? { minSimilarity } : {}),dismissed,+ safeguard: toolSafeguard(ctx, OPERATION.bridges),+ ...(onProgress ? { onProgress } : {}),});writeBridgeProposals(ctx.vault, report, { now });try {@@ -205,6 +210,7 @@ async function toolBrainBridges(async function toolBrainClusters(ctx: ServerContext,args: Record<string, unknown>,+ onProgress?: ProgressSink,): Promise<Record<string, unknown>> {const op = args["operation"];if (op !== "run" && op !== "list") {@@ -249,10 +255,11 @@ async function toolBrainClusters(const store = await Store.open(searchConfig, { mode: "read" });const now = new Date();try {- const communities = detectCommunities(- store,- minSize !== undefined ? { minSize: minSize as number } : {},- );+ const communities = detectCommunities(store, {+ ...(minSize !== undefined ? { minSize: minSize as number } : {}),+ safeguard: toolSafeguard(ctx, OPERATION.clusters),+ ...(onProgress ? { onProgress } : {}),+ });const materialized = materializeClusterNotes(ctx.vault, communities, {store,now,diff --git a/src/mcp/brain/recall-tools.ts b/src/mcp/brain/recall-tools.tsindex 5ba4aff6..fa79316a 100644--- a/src/mcp/brain/recall-tools.ts+++ b/src/mcp/brain/recall-tools.ts@@ -37,7 +37,9 @@ import {} from "../../core/brain/mcp-route-metrics.ts";import {emitTokenImpact,- isTokenCountMethod,+ normalizeTokenCountMethod,+ TOKEN_COUNT_METHOD,+ TOKEN_COUNT_METHODS,isTokenImpactOutcome,listTokenImpact,recordTokenImpactOutcome,@@ -437,7 +439,7 @@ async function toolBrainTokenImpact("brain_token_impact: record requires baseline_tokens and packed_tokens (non-negative integers)",);}- const method = coerceTokenCountMethod(args["method"]) ?? "fallback";+ const method = coerceTokenCountMethod(args["method"]) ?? TOKEN_COUNT_METHOD.heuristic;const modeledAvoided = coerceNonNegativeTokenValue("brain_token_impact","modeled_avoided_inferences",@@ -565,10 +567,17 @@ function tokenImpactFilter(args: Record<string, unknown>): TokenImpactFilter {function coerceTokenCountMethod(raw: unknown): TokenCountMethod | undefined {if (raw === undefined || raw === null) return undefined;const trimmed = typeof raw === "string" ? raw.trim() : raw;- if (!isTokenCountMethod(trimmed)) {- throw new MCPError(INVALID_PARAMS, "brain_token_impact: method must be exact or fallback");+ // Legacy-aware: an adapter still posting the pre-rename `exact` /+ // `fallback` labels is translated rather than rejected, so upgrading the+ // server does not silently stop recording an existing caller's samples.+ const method = normalizeTokenCountMethod(trimmed);+ if (method === null) {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_token_impact: method must be one of ${TOKEN_COUNT_METHODS.join(", ")}`,+ );}- return trimmed;+ return method;}function coerceTokenImpactOutcome(raw: unknown): TokenImpactOutcome | undefined {@@ -1164,9 +1173,9 @@ export const RECALL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},method: {type: "string",- enum: ["exact", "fallback"],+ enum: [...TOKEN_COUNT_METHODS],description:- "How the counts were obtained: a real tokenizer (exact) or a heuristic estimate (fallback, the default). Also a list/summary filter.",+ "How the CALLER produced the counts, never how accurate they are - the server counts nothing. Defaults to 'heuristic'. Also a list/summary filter.",},modeled_avoided_inferences: {type: "number",diff --git a/src/mcp/brain/review-tools.ts b/src/mcp/brain/review-tools.tsindex 7c6d4ca1..ec872a7d 100644--- a/src/mcp/brain/review-tools.ts+++ b/src/mcp/brain/review-tools.ts@@ -13,8 +13,11 @@ import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";import { buildIntentReview } from "../../core/brain/intent-review.ts";import { buildRetentionReview } from "../../core/brain/retention.ts";import { buildReviewCandidates } from "../../core/brain/review-candidates.ts";+import { OPERATION } from "../../core/brain/safeguard.ts";+import type { ProgressSink } from "../../core/brain/progress.ts";import type { ServerContext, ToolDefinition } from "../tool-contract.ts";import { coerceIsoDate } from "../coerce.ts";+import { toolSafeguard } from "./shared.ts";async function toolBrainIntentReview(ctx: ServerContext,@@ -59,6 +62,7 @@ async function toolBrainRetention(async function toolBrainReviewCandidates(ctx: ServerContext,args: Record<string, unknown>,+ onProgress?: ProgressSink,): Promise<Record<string, unknown>> {const nowDate = coerceIsoDate(args, "now");// Surprisal annotation (t_fddfe64a) is best-effort: a resolvable@@ -74,6 +78,11 @@ async function toolBrainReviewCandidates(searchConfig = undefined;}const report = await buildReviewCandidates(ctx.vault, {+ // The projection is read-only, but it runs a full dry-run+ // consolidation pass to produce it - the same pass, and so the same+ // budget, as `brain_dream`.+ safeguard: toolSafeguard(ctx, OPERATION.dream),+ ...(onProgress ? { onProgress } : {}),...(nowDate ? { now: nowDate } : {}),...(searchConfig !== undefined ? { searchConfig } : {}),});diff --git a/src/mcp/brain/shared.ts b/src/mcp/brain/shared.tsindex 97aceb75..48c36957 100644--- a/src/mcp/brain/shared.ts+++ b/src/mcp/brain/shared.ts@@ -17,6 +17,13 @@ import {assertExpectedCount,type CountGuardOptions,} from "../../core/brain/count-guard.ts";+import type { ProgressSink } from "../../core/brain/progress.ts";+import {+ createSafeguard,+ resolveSafeguardTimeoutMs,+ type Operation,+ type Safeguard,+} from "../../core/brain/safeguard.ts";/*** Read the shared `--expect` / `--strict` count-guard arguments from an MCP@@ -52,6 +59,26 @@ export function enforceCountGuard(opts: CountGuardOptions): void {}}+/**+ * A cooperative deadline for one long MCP operation, resolved through the+ * documented ladder: `safeguard_timeout_<operation>_seconds`, then+ * `safeguard_timeout_seconds`, then the built-in default.+ *+ * One factory rather than one per domain module. Three had grown - the+ * maintenance lane's, the graph tools', and none at all for `brain_dream`+ * - and the gap was invisible precisely because each module answered the+ * question locally. `docs/mcp.md` states the ladder once; this is the one+ * place that implements it for the MCP surface, so a tool that reaches a+ * long operation and forgets the deadline is a missing call to a named+ * helper rather than a missing copy of a three-line idiom.+ */+export function toolSafeguard(ctx: ServerContext, operation: Operation): Safeguard {+ return createSafeguard({+ operation,+ timeoutMs: resolveSafeguardTimeoutMs(operation, ctx.configPath ?? undefined),+ });+}+export const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;/**@@ -166,15 +193,31 @@ export function coerceNonNegativeInteger(throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);}+/**+ * Route one consolidated tool's `view` argument to its per-view handler.+ *+ * The progress sink is forwarded rather than dropped. It is optional at+ * every link, so a view that has nothing to report ignores it - but a+ * dispatcher that silently swallowed it would make a view which DOES run+ * long, such as the operator brief's dry-run consolidation pass, look+ * like a tool that emits no progress rather than one whose progress was+ * discarded in transit. Those are the two cases this release exists to+ * keep apart.+ */export function dispatchByView(table: Readonly<Record<string,- (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown+ (+ ctx: ServerContext,+ args: Record<string, unknown>,+ onProgress?: ProgressSink,+ ) => Promise<unknown> | unknown>>,ctx: ServerContext,args: Record<string, unknown>,+ onProgress?: ProgressSink,): Promise<unknown> | unknown {const view = typeof args["view"] === "string" ? args["view"] : "";const handler = table[view];@@ -184,7 +227,7 @@ export function dispatchByView(`view must be one of ${Object.keys(table).join(", ")}; got ${JSON.stringify(args["view"])}`,);}- return handler(ctx, args);+ return handler(ctx, args, onProgress);}/**diff --git a/src/mcp/index.ts b/src/mcp/index.tsindex 29f803a1..1d314ec9 100644--- a/src/mcp/index.ts+++ b/src/mcp/index.ts@@ -14,6 +14,7 @@ export {INVALID_PARAMS,INTERNAL_ERROR,MCPError,+ type JsonRpcNotification,} from "./protocol.ts";export { MCPServer, errorResponse, type JsonRpcRequest, type JsonRpcResponse } from "./server.ts";export { serveHttp, startHttp, type ServeHttpOptions, type HttpServerHandle } from "./http.ts";diff --git a/src/mcp/progress.ts b/src/mcp/progress.tsnew file mode 100644index 00000000..46da79a5--- /dev/null+++ b/src/mcp/progress.ts@@ -0,0 +1,179 @@+/**+ * The progress spine at the MCP boundary (nothing-runs-unwatched, U2).+ *+ * A client asks for liveness by putting a token on the request:+ * `params._meta.progressToken`. Until this module `handleToolsCall` read+ * exactly two keys from `params` - `name` and `arguments` - so the token+ * was accepted by the wire and then discarded without a word. That is the+ * silent drop this release exists to remove, and there are only two+ * honest answers to it: carry the events, or say why they cannot be+ * carried.+ *+ * Which answer a transport gives is decided by whether it can write an+ * unsolicited frame at all, not by a flag. stdio reads and writes a+ * newline-delimited duplex stream, so it hands the server a notification+ * writer and the events go out ahead of the response. The HTTP transport+ * answers one request with one response and closes+ * (`res.end` in `http.ts`), so it hands over nothing, and a token that+ * arrives there is refused by name with+ * {@link PROGRESS_REASON.transportSingleResponse} rather than accepted+ * and dropped - accepting it would advertise liveness support that does+ * not exist.+ *+ * The refusal rides on `result._meta`, which is where MCP reserves room+ * for implementation metadata, and it is the exact reciprocal of where+ * the request carried the token. The two alternatives are both wrong for+ * reasons this repository has already written down: `structuredContent`+ * is validated against the tool's `outputSchema`, so a transport fact+ * there would break the contract a caller parses, and `content[0].text`+ * is that same payload rendered - the advisory rail's rule that a+ * machine-readable stream is not a place to put a remark applies+ * verbatim. `_meta` is absent entirely when no token was sent, so a+ * client that did not ask sees a byte-identical response.+ */++import {+ PROGRESS_KIND,+ PROGRESS_SCHEMA,+ type ProgressEvent,+ type ProgressReason,+ type ProgressSink,+} from "../core/brain/progress.ts";+import { INVALID_PARAMS, JSONRPC_VERSION, MCPError } from "./protocol.ts";+import type { JsonRpcNotification } from "./protocol.ts";++/** Spec method name for a progress notification. */+export const PROGRESS_NOTIFICATION_METHOD = "notifications/progress";++/**+ * The `_meta` member both directions of this feature travel under.+ * Namespaced because `_meta` is a shared extension point: a key without a+ * prefix would collide with the next implementation that wants one.+ */+export const PROGRESS_META_KEY = "open-second-brain/progress";++/**+ * What the MCP specification allows a progress token to be: a string or+ * an integer. Deliberately not `number` - a fractional token is a client+ * defect, and coercing it would hand back a value the client cannot match+ * to the request it sent.+ */+export type ProgressToken = string | number;++/**+ * Why no progress could be carried, addressed to the token that asked.+ *+ * A distinct shape from {@link ProgressEvent} rather than a `refused`+ * event with invented fields: the refusal happens before any operation+ * has spoken, so there is no `operation`, no `stage` and no count to+ * report, and filling those in with zeroes would describe a run that+ * never started.+ */+export interface ProgressRefusal {+ readonly schema: typeof PROGRESS_SCHEMA;+ readonly kind: typeof PROGRESS_KIND.refused;+ readonly reason: ProgressReason;+ readonly progressToken: ProgressToken;+}++/** Names the JSON shape of a rejected value, for an error that must say what was wrong. */+function describeValue(value: unknown): string {+ if (value === null) return "null";+ if (Array.isArray(value)) return "array";+ if (typeof value === "number") return Number.isInteger(value) ? "number" : "fractional number";+ return typeof value;+}++/**+ * The client's progress token, or `undefined` when it asked for none.+ *+ * Throws {@link MCPError} rather than coercing or ignoring: a token the+ * server silently rewrote could not be matched back to the request that+ * carried it, and a token the server silently dropped is the defect this+ * module exists to remove. An absent `_meta`, and a `_meta` carrying+ * other members but no `progressToken`, both mean "nobody asked" and are+ * not errors.+ */+export function readProgressToken(params: Record<string, unknown>): ProgressToken | undefined {+ const meta = params["_meta"];+ if (meta === undefined) return undefined;+ if (typeof meta !== "object" || meta === null || Array.isArray(meta)) {+ throw new MCPError(+ INVALID_PARAMS,+ `tools/call _meta must be an object, got ${describeValue(meta)}`,+ );+ }+ const token = (meta as Record<string, unknown>)["progressToken"];+ if (token === undefined) return undefined;+ if (typeof token === "string") return token;+ if (typeof token === "number" && Number.isInteger(token)) return token;+ throw new MCPError(+ INVALID_PARAMS,+ `tools/call _meta.progressToken must be a string or an integer, got ${describeValue(token)}`,+ );+}++/**+ * One `notifications/progress` frame.+ *+ * `progress` and `total` are the spec's own numeric fields, so a client+ * that knows nothing about this repository still renders a bar; the typed+ * event travels beside them under {@link PROGRESS_META_KEY}, so a client+ * that does gets the stage identifier and the operation name without the+ * server having to render a sentence for either.+ */+export function progressNotification(+ token: ProgressToken,+ event: ProgressEvent,+): JsonRpcNotification {+ return {+ jsonrpc: JSONRPC_VERSION,+ method: PROGRESS_NOTIFICATION_METHOD,+ params: {+ progressToken: token,+ progress: event.completed,+ ...(event.total === undefined ? {} : { total: event.total }),+ _meta: { [PROGRESS_META_KEY]: event },+ },+ };+}++/**+ * A sink that turns each event into a notification frame, or `undefined`+ * when there is nothing to turn them into - no token, or no writer.+ *+ * Synchronous by construction, because the spine's sink is: `dream` and+ * its peers are synchronous functions and cannot await a write inside+ * their own loops.+ */+export function progressSink(+ token: ProgressToken | undefined,+ send: ((notification: JsonRpcNotification) => void) | undefined,+): ProgressSink | undefined {+ if (token === undefined || send === undefined) return undefined;+ return (event: ProgressEvent) => send(progressNotification(token, event));+}++/** The typed refusal a single-response transport answers a token with. */+export function progressRefusal(token: ProgressToken, reason: ProgressReason): ProgressRefusal {+ return {+ schema: PROGRESS_SCHEMA,+ kind: PROGRESS_KIND.refused,+ reason,+ progressToken: token,+ };+}++/**+ * Attach a refusal to a `tools/call` result. With no refusal the result+ * is returned untouched - not cloned with an empty `_meta` - so a call+ * that asked for no progress is byte-identical to the one the previous+ * release answered.+ */+export function withProgressRefusal(+ result: Record<string, unknown>,+ refusal: ProgressRefusal | undefined,+): Record<string, unknown> {+ if (refusal === undefined) return result;+ return { ...result, _meta: { [PROGRESS_META_KEY]: refusal } };+}diff --git a/src/mcp/protocol.ts b/src/mcp/protocol.tsindex b7531a9e..ac4704e2 100644--- a/src/mcp/protocol.ts+++ b/src/mcp/protocol.ts@@ -19,6 +19,22 @@ export const METHOD_NOT_FOUND = -32601;export const INVALID_PARAMS = -32602;export const INTERNAL_ERROR = -32603;+/**+ * A frame the server writes without having been asked for it, addressed+ * to no request id.+ *+ * It lives beside the constants rather than next to `JsonRpcResponse` in+ * `server.ts` because the transports need the shape and the server needs+ * it too: putting it in this leaf keeps the dependency direction+ * downward and leaves `progress.ts` able to build a frame without+ * importing the dispatcher that will send it.+ */+export interface JsonRpcNotification {+ readonly jsonrpc: string;+ readonly method: string;+ readonly params?: unknown;+}+export class MCPError extends Error {readonly code: number;readonly data: unknown;diff --git a/src/mcp/server.ts b/src/mcp/server.tsindex 7093252c..dbfa6af7 100644--- a/src/mcp/server.ts+++ b/src/mcp/server.ts@@ -23,6 +23,15 @@ import {SERVER_NAME,SERVER_VERSION,} from "./protocol.ts";+import type { JsonRpcNotification } from "./protocol.ts";+import {+ progressRefusal,+ progressSink,+ readProgressToken,+ withProgressRefusal,+ type ProgressRefusal,+} from "./progress.ts";+import { PROGRESS_REASON, type ProgressSink } from "../core/brain/progress.ts";import { listResources, listResourceTemplates, readResource } from "./resources.ts";import { buildToolTable, findTool } from "./tools.ts";import type {@@ -55,6 +64,21 @@ export interface MCPServerRuntimeOptions {* injectable so tests get a deterministic directory.*/readonly artifactRunId?: string;+ /**+ * How this transport writes a frame nobody asked for.+ *+ * Supplied by stdio, which owns a duplex newline-delimited stream and+ * can interleave notifications with responses. NOT supplied by the+ * HTTP transport, which answers one request with one response and+ * closes it - and its absence is what makes a `tools/call` carrying a+ * progress token refuse by name there instead of accepting the token+ * and dropping the events.+ *+ * Synchronous, because the progress sink it feeds is: the long+ * operations that emit are synchronous functions and cannot await a+ * write inside their own loops.+ */+ readonly sendNotification?: (notification: JsonRpcNotification) => void;}export interface JsonRpcRequest {@@ -87,6 +111,8 @@ export class MCPServer {* `mcp_route_latency` continuity record is emitted (fail-open).*/private readonly routeMetricsEnabled: boolean;+ /** See {@link MCPServerRuntimeOptions.sendNotification}. */+ private readonly sendNotification: ((notification: JsonRpcNotification) => void) | undefined;constructor(opts: MCPServerOptions, runtimeOpts: MCPServerRuntimeOptions = {}) {this.vault = opts.vault;@@ -102,6 +128,7 @@ export class MCPServer {this.tools = evaluated.tools;this.capabilityReport = evaluated.report;this.routeMetricsEnabled = routeMetricsGate(this.configPath ?? undefined);+ this.sendNotification = runtimeOpts.sendNotification;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.@@ -163,17 +190,23 @@ export class MCPServer {* here rather than in `handleToolsCall` is what makes it cover the CLI* bridge too, while leaving the many tests that call `tool.handler`* directly exactly as they were.+ *+ * `onProgress` is the per-request half of the same idea: one seam, so+ * the request-scoped sink reaches every handler without editing any of+ * the registrations. The CLI bridge passes none - a `callTool` has no+ * client and therefore no token.*/private async invokeToolHandler(tool: ToolDefinition,args: Record<string, unknown>,+ onProgress?: ProgressSink,): Promise<unknown> {assertKnownArguments(tool, args);- if (!this.routeMetricsEnabled) return tool.handler(this.context, args);+ if (!this.routeMetricsEnabled) return tool.handler(this.context, args, onProgress);const start = performance.now();let status: McpRouteStatus = "ok";try {- return await tool.handler(this.context, args);+ return await tool.handler(this.context, args, onProgress);} catch (exc) {status = "error";throw exc;@@ -327,16 +360,28 @@ export class MCPServer {throw new MCPError(INVALID_PARAMS, "tools/call arguments must be an object");}const args = argsRaw as Record<string, unknown>;+ // Read before the handler runs: a malformed token is a request+ // defect, and refusing it after the work has been done would leave+ // the caller unable to tell which half failed.+ const token = readProgressToken(params);+ const onProgress = progressSink(token, this.sendNotification);+ // A token this transport cannot honour is refused by name on the way+ // out - on the error envelope too, because a call that asked for+ // progress and then failed still never got any.+ const refusal: ProgressRefusal | undefined =+ token !== undefined && onProgress === undefined+ ? progressRefusal(token, PROGRESS_REASON.transportSingleResponse)+ : undefined;try {- const structured = await this.invokeToolHandler(tool, args);- return buildMcpToolResult(tool, structured, this.artifactStore);+ const structured = await this.invokeToolHandler(tool, args, onProgress);+ return withProgressRefusal(buildMcpToolResult(tool, structured, this.artifactStore), refusal);} catch (exc) {if (exc instanceof MCPError) throw exc;const message = (exc as Error).message ?? String(exc);// ValueError/TypeError semantics in Python → tool-level error envelope.// OSError in Python → "filesystem error" prefix. We collapse both to a// single tool-level error since JS doesn't distinguish.- return toolError(message);+ return withProgressRefusal(toolError(message), refusal);}}}diff --git a/src/mcp/stdio.ts b/src/mcp/stdio.tsindex 19af71cc..d4eca8ae 100644--- a/src/mcp/stdio.ts+++ b/src/mcp/stdio.ts@@ -10,7 +10,13 @@ import type { Readable, Writable } from "node:stream";import { MCPServer, type MCPServerOptions, type MCPServerRuntimeOptions } from "./server.ts";import { errorResponse, type JsonRpcResponse } from "./server.ts";-import { INVALID_REQUEST, PARSE_ERROR } from "./protocol.ts";+import { INVALID_REQUEST, PARSE_ERROR, type JsonRpcNotification } from "./protocol.ts";++/**+ * Any frame this transport writes: a response to a request, or a+ * notification the server sent on its own initiative (today, progress).+ */+type OutboundFrame = JsonRpcResponse | JsonRpcNotification;export interface ServeStdioOptions {readonly stdin?: Readable;@@ -31,9 +37,17 @@ export async function serveStdio(ioOpts: ServeStdioOptions = {},runtimeOpts: MCPServerRuntimeOptions = {},): Promise<number> {- const server = new MCPServer(ctx, runtimeOpts);const stdin = ioOpts.stdin ?? process.stdin;const stdout = ioOpts.stdout ?? process.stdout;+ // This transport owns a duplex stream, so it CAN write a frame nobody+ // asked for - which is what lets a `tools/call` carrying a progress+ // token be answered with live notifications instead of a refusal. Set+ // after the caller's options so a transport fact cannot be overridden+ // by a runtime option.+ const server = new MCPServer(ctx, {+ ...runtimeOpts,+ sendNotification: (notification) => writeFrame(stdout, notification),+ });const rl = createInterface({ input: stdin, crlfDelay: Infinity });for await (const rawLine of rl) {@@ -70,10 +84,28 @@ export async function serveStdio(return 0;}-function writeFrame(out: Writable, response: JsonRpcResponse): void {- let line = JSON.stringify(response);- if (line.includes("\n")) line = line.replace(/\n/g, " ");- out.write(line + "\n");+/**+ * One frame as the single line this protocol delimits by.+ *+ * Shared by both loops below so a notification and a response are framed+ * by identical code: the format is the contract, and two copies of it+ * could drift apart the moment one of them gained a case.+ */+function frameLine(frame: OutboundFrame): string {+ const line = JSON.stringify(frame);+ return line.includes("\n") ? line.replace(/\n/g, " ") : line;+}++/**+ * Write one frame in ONE `write` call, terminator included.+ *+ * That single call is what keeps a progress notification from landing+ * inside a response: `Writable.write` appends the whole string to the+ * stream's queue atomically, so no other frame can be spliced between a+ * frame's body and its newline.+ */+function writeFrame(out: Writable, frame: OutboundFrame): void {+ out.write(frameLine(frame) + "\n");}/**@@ -82,14 +114,22 @@ function writeFrame(out: Writable, response: JsonRpcResponse): void {* bypass the readline async iteration.** Returns newline-joined output (one JSON-RPC frame per line, trailing newline).+ *+ * It carries notifications on the same terms as the real loop, and+ * frames them through the same {@link frameLine}: a harness that dropped+ * the unsolicited frames would report the progress feature as absent+ * wherever it is used, which is the failure mode this release is about.*/export async function serveStdioFromString(ctx: MCPServerOptions,input: string,opts: MCPServerRuntimeOptions = {},): Promise<string> {- const server = new MCPServer(ctx, opts);const out: string[] = [];+ const server = new MCPServer(ctx, {+ ...opts,+ sendNotification: (notification) => out.push(frameLine(notification)),+ });for (const rawLine of input.split("\n")) {const line = rawLine.trim();if (!line) continue;@@ -98,13 +138,13 @@ export async function serveStdioFromString(request = JSON.parse(line);} catch (exc) {out.push(- JSON.stringify(errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`)),+ frameLine(errorResponse(null, PARSE_ERROR, `invalid JSON: ${(exc as Error).message}`)),);continue;}if (Array.isArray(request)) {out.push(- JSON.stringify(+ frameLine(errorResponse(null,INVALID_REQUEST,@@ -115,11 +155,17 @@ export async function serveStdioFromString(continue;}if (typeof request !== "object" || request === null) {- out.push(JSON.stringify(errorResponse(null, INVALID_REQUEST, "request must be an object")));+ out.push(frameLine(errorResponse(null, INVALID_REQUEST, "request must be an object")));continue;}+ // Sequential on purpose, and not a candidate for `Promise.all`: the+ // frames this loop collects are ordered, and a request that emits+ // progress must have its notifications land between its predecessor's+ // response and its own. Running the calls in parallel would shuffle+ // them.+ // oxlint-disable-next-line no-await-in-loopconst response = await server.handleRequest(request as Record<string, unknown>);- if (response !== null) out.push(JSON.stringify(response));+ if (response !== null) out.push(frameLine(response));}return out.join("\n") + (out.length > 0 ? "\n" : "");}diff --git a/src/mcp/tool-contract.ts b/src/mcp/tool-contract.tsindex b1fa26bb..76da8032 100644--- a/src/mcp/tool-contract.ts+++ b/src/mcp/tool-contract.ts@@ -14,6 +14,7 @@import type { OutputSchema } from "./output-contract.ts";import type { ArtifactStore } from "./artifact-store.ts";+import type { ProgressSink } from "../core/brain/progress.ts";export type ToolScope = "full" | "writer" | "catalog";@@ -80,8 +81,26 @@ export interface ToolDefinition {* for old clients without re-paying their schema in every list.*/readonly hidden?: boolean;+ /**+ * The tool's implementation.+ *+ * The third parameter is per-REQUEST, which is exactly why it is a+ * parameter and not a `ServerContext` field: the context is built once+ * per server (`MCPServer.context`), while a progress token belongs to+ * the single `tools/call` that carried it.+ *+ * It is optional in the type, and TypeScript lets a function of fewer+ * parameters satisfy a type declaring more, so none of the registered+ * tools needed editing to gain it - a handler that cannot report+ * progress simply keeps its two-parameter signature. `undefined` means+ * the client asked for no progress, or the transport could not carry+ * it; in both cases the handler behaves exactly as it did before,+ * because `onProgress` is the same optional-observer idiom the core+ * options interfaces already use.+ */readonly handler: (ctx: ServerContext,args: Record<string, unknown>,+ onProgress?: ProgressSink,) => Promise<unknown> | unknown;}diff --git a/tests/cli/brain-architect-progress.test.ts b/tests/cli/brain-architect-progress.test.tsnew file mode 100644index 00000000..c79ced70--- /dev/null+++ b/tests/cli/brain-architect-progress.test.ts@@ -0,0 +1,102 @@+/**+ * `o2b brain architect` under observation (nothing-runs-unwatched,+ * U1 + U3 + U11).+ *+ * The scan and the render already emit through the U1 sink and already+ * accept a deadline, and `OPERATION.architect` already resolves a budget+ * through the safeguard ladder - but the verb created no safeguard and+ * attached no rail, so `safeguard_timeout_architect_seconds` was a+ * configuration key nothing read. This is that key's consumer, and the+ * stream's.+ *+ * The abort arm is proved against the core rather than by racing a real+ * signal: the scan of this repository takes tens of milliseconds, so a+ * test that pressed Ctrl-C at the right moment would be a lottery.+ */++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 { generateArchDocs } from "../../src/core/brain/architect/generate.ts";+import { createSafeguard, OPERATION, SafeguardAbortError } from "../../src/core/brain/safeguard.ts";+import { progressRecords, STAGE_IDENTIFIER } from "../helpers/progress-records.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let project: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-architect-progress-"));+ project = join(tmp, "demo-app");+ mkdirSync(join(project, "src", "core"), { recursive: true });+ writeFileSync(join(project, "package.json"), JSON.stringify({ name: "demo-app" }));+ writeFileSync(join(project, "src", "core", "engine.ts"), "// x\n");+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("o2b brain architect --progress", () => {+ test("writes records to stderr and leaves stdout untouched", async () => {+ const plain = await runCli(["brain", "architect", project, "--vault", vault, "--json"]);+ // A second run over notes that already exist reports `unchanged`, so+ // the two payloads are compared across identical repeat runs.+ const warm = await runCli(["brain", "architect", project, "--vault", vault, "--json"]);+ const watched = await runCli([+ "brain",+ "architect",+ project,+ "--vault",+ vault,+ "--json",+ "--progress",+ ]);++ expect(plain.returncode).toBe(0);+ expect(watched.returncode).toBe(0);+ expect(watched.stdout).toBe(warm.stdout);++ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ expect(records.every((r) => r["operation"] === OPERATION.architect)).toBe(true);+ expect(progressRecords(warm.stderr)).toHaveLength(0);+ });++ test("integers and identifiers only - no prose on the structured stream", async () => {+ const watched = await runCli(["brain", "architect", project, "--vault", vault, "--progress"]);+ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ for (const record of records) {+ expect(String(record["stage"])).toMatch(STAGE_IDENTIFIER);+ expect(Number.isInteger(record["completed"])).toBe(true);+ }+ });++ test("without the flag nobody is watching, and the run is unchanged", async () => {+ const plain = await runCli(["brain", "architect", project, "--vault", vault]);+ expect(plain.returncode).toBe(0);+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });+});++describe("the safeguard the verb now builds", () => {+ test("a pre-aborted signal stops the pass before it writes", () => {+ const controller = new AbortController();+ controller.abort();+ expect(() =>+ generateArchDocs(vault, project, {+ safeguard: createSafeguard({+ operation: OPERATION.architect,+ timeoutMs: null,+ signal: controller.signal,+ }),+ }),+ ).toThrow(SafeguardAbortError);+ });+});diff --git a/tests/cli/brain-bench.test.ts b/tests/cli/brain-bench.test.tsindex 3f9c4696..cb62098c 100644--- a/tests/cli/brain-bench.test.ts+++ b/tests/cli/brain-bench.test.ts@@ -39,7 +39,7 @@ describe("o2b brain bench memory", () => {context_cost: { avg_chars: number };judge: { status: string };};- expect(report.schema).toBe("o2b.bench.v1");+ expect(report.schema).toBe("o2b.bench.v2");expect(report.quality.total).toBe(6);expect(report.quality.passed).toBe(6);expect(report.judge.status).toBe("skipped");diff --git a/tests/cli/brain-bridges-progress.test.ts b/tests/cli/brain-bridges-progress.test.tsnew file mode 100644index 00000000..30157330--- /dev/null+++ b/tests/cli/brain-bridges-progress.test.ts@@ -0,0 +1,80 @@+/**+ * `o2b brain bridges discover` under observation (nothing-runs-unwatched,+ * U1 + U3).+ *+ * The scan walks every candidate document in the index and, until now,+ * printed its first character after the last comparison. Two properties+ * hold at the boundary: the records go to stderr, and the payload a+ * caller parses does not move by one byte because someone asked to watch.+ */++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 { indexVault } from "../../src/core/search/indexer.ts";+import { OPERATION } from "../../src/core/brain/safeguard.ts";+import { makeConfig } from "../helpers/search-fixtures.ts";+import { progressRecords, STAGE_IDENTIFIER } from "../helpers/progress-records.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-bridges-progress-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeFileSync(join(vault, "a-note.md"), "# A note\n\nCanary deployment content here.\n");+ writeFileSync(join(vault, "b-note.md"), "# B note\n\nUnrelated content entirely.\n");+ await indexVault(+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),+ );+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("o2b brain bridges discover --progress", () => {+ test("writes records to stderr and leaves stdout untouched", async () => {+ const plain = await runCli(["brain", "bridges", "discover", "--vault", vault, "--json"]);+ const watched = await runCli([+ "brain",+ "bridges",+ "discover",+ "--vault",+ vault,+ "--json",+ "--progress",+ ]);++ expect(plain.returncode).toBe(0);+ expect(watched.returncode).toBe(0);+ // `generated_at` lives in the artifact, not the payload, so the two+ // runs are comparable byte for byte.+ expect(watched.stdout).toBe(plain.stdout);++ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ expect(records.every((r) => r["operation"] === OPERATION.bridges)).toBe(true);+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });++ test("integers and identifiers only - no prose on the structured stream", async () => {+ const watched = await runCli(["brain", "bridges", "discover", "--vault", vault, "--progress"]);+ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ for (const record of records) {+ expect(String(record["stage"])).toMatch(STAGE_IDENTIFIER);+ expect(Number.isInteger(record["completed"])).toBe(true);+ }+ });++ test("without the flag nobody is watching, and the run is unchanged", async () => {+ const plain = await runCli(["brain", "bridges", "discover", "--vault", vault]);+ expect(plain.returncode).toBe(0);+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });+});diff --git a/tests/cli/brain-clusters-progress.test.ts b/tests/cli/brain-clusters-progress.test.tsnew file mode 100644index 00000000..ba4de439--- /dev/null+++ b/tests/cli/brain-clusters-progress.test.ts@@ -0,0 +1,87 @@+/**+ * `o2b brain clusters run` under observation (nothing-runs-unwatched,+ * U1 + U3).+ *+ * Label propagation sweeps the whole link graph until no label moves, and+ * the sweep count is a ceiling rather than a schedule - so a caller+ * genuinely cannot tell a slow graph from a stuck one without a stream.+ * The records land on stderr and the payload does 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 { indexVault } from "../../src/core/search/indexer.ts";+import { OPERATION } from "../../src/core/brain/safeguard.ts";+import { makeConfig } from "../helpers/search-fixtures.ts";+import { progressRecords, STAGE_IDENTIFIER } from "../helpers/progress-records.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-clusters-progress-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ const group = ["team-a", "team-b", "team-c", "team-d"];+ for (const name of group) {+ const others = group+ .filter((g) => g !== name)+ .map((g) => `[[${g}]]`)+ .join(" ");+ writeFileSync(join(vault, `${name}.md`), `# ${name}\n\nSee ${others}.\n`);+ }+ await indexVault(+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),+ );+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("o2b brain clusters run --progress", () => {+ test("writes records to stderr and leaves stdout untouched", async () => {+ const plain = await runCli(["brain", "clusters", "run", "--vault", vault, "--json"]);+ const watched = await runCli([+ "brain",+ "clusters",+ "run",+ "--vault",+ vault,+ "--json",+ "--progress",+ ]);++ expect(plain.returncode).toBe(0);+ expect(watched.returncode).toBe(0);+ expect(watched.stdout).toBe(plain.stdout);++ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ expect(records.every((r) => r["operation"] === OPERATION.clusters)).toBe(true);+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });++ test("integers and identifiers only - no prose on the structured stream", async () => {+ const watched = await runCli(["brain", "clusters", "run", "--vault", vault, "--progress"]);+ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ for (const record of records) {+ expect(String(record["stage"])).toMatch(STAGE_IDENTIFIER);+ expect(Number.isInteger(record["completed"])).toBe(true);+ // The sweep ceiling IS known before the loop, unlike the index+ // walk, so this stream carries a denominator a renderer can use.+ expect(Number.isInteger(record["total"])).toBe(true);+ }+ });++ test("without the flag nobody is watching, and the run is unchanged", async () => {+ const plain = await runCli(["brain", "clusters", "run", "--vault", vault]);+ expect(plain.returncode).toBe(0);+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });+});diff --git a/tests/cli/brain-dream-progress.test.ts b/tests/cli/brain-dream-progress.test.tsnew file mode 100644index 00000000..7a167826--- /dev/null+++ b/tests/cli/brain-dream-progress.test.ts@@ -0,0 +1,164 @@+/**+ * `o2b brain dream` under observation, and under a Ctrl-C.+ *+ * Two properties that only exist at the CLI boundary:+ *+ * 1. `--progress` writes newline-delimited records to STDERR while the+ * pass runs, and stdout stays exactly what it was. A progress line+ * on stdout would corrupt the payload `--json` callers parse, which+ * is the whole reason the rail exists.+ * 2. The staged lifecycle carries the same stream: staging IS a dream+ * pass, so `o2b brain dream stage --progress` reports the same five+ * stages under the same operation name rather than nothing at all.+ * 3. This verb does NOT advertise a cooperative interrupt. `dreamRun`+ * is synchronous end to end, so a signal handler cannot run while it+ * does; Ctrl-C keeps its default meaning and kills the process.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { EXIT_INTERRUPTED, interruptIsObservable } from "../../src/cli/interrupt.ts";+import { PROGRESS_KIND } from "../../src/core/brain/progress.ts";+import { OPERATION } from "../../src/core/brain/safeguard.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { runCli } from "../helpers/run-cli.ts";+import { progressRecords } from "../helpers/progress-records.ts";++let vault: string;+let configHome: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-cli-dream-progress-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-cli-dream-progress-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+ for (const [i, date] of ["2026-05-20", "2026-05-21", "2026-05-22"].entries()) {+ writeSignal(vault, {+ topic: "cli-progress",+ signal: "positive",+ agent: "claude",+ principle: "Prefer the cli-progress approach",+ created_at: `${date}T10:00:00Z`,+ date,+ slug: `cli-progress-${i}`,+ scope: "writing",+ });+ }+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++const env = (): Record<string, string> => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });++describe("o2b brain dream --progress", () => {+ test("writes records to stderr and leaves stdout untouched", async () => {+ const plain = await runCli(["brain", "dream", "--dry-run", "--json"], { env: env() });+ const watched = await runCli(["brain", "dream", "--dry-run", "--json", "--progress"], {+ env: env(),+ });++ expect(plain.returncode).toBe(0);+ expect(watched.returncode).toBe(0);+ // The payload a caller parses is byte-identical with and without the+ // observer. Progress that changed stdout would be a regression, not a+ // feature.+ expect(watched.stdout).toBe(plain.stdout);++ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ expect(records.every((r) => r["operation"] === OPERATION.dream)).toBe(true);+ expect(records[0]?.["kind"]).toBe(PROGRESS_KIND.started);+ expect(records.at(-1)?.["kind"]).toBe(PROGRESS_KIND.finished);+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });++ test("is observed once, not once per entry point", async () => {+ // The staged block and the inline pass each attach the rail, and+ // `run` falls THROUGH the staged block to the inline pass. A staged+ // attachment that did not exclude `run` would build two observers for+ // one pass, and the stream would carry every record twice.+ const watched = await runCli(["brain", "dream", "--dry-run", "--progress"], { env: env() });+ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ // One terminator for one run, and one `started` per distinct stage.+ expect(records.filter((r) => r["kind"] === PROGRESS_KIND.finished)).toHaveLength(1);+ const opened = records+ .filter((r) => r["kind"] === PROGRESS_KIND.started)+ .map((r) => r["stage"]);+ expect(opened).toEqual([...new Set(opened)]);+ });++ test("integers and identifiers only - no prose on the structured stream", async () => {+ const watched = await runCli(["brain", "dream", "--dry-run", "--progress"], { env: env() });+ for (const record of progressRecords(watched.stderr)) {+ expect(typeof record["stage"]).toBe("string");+ // An identifier, never a sentence: the human line is rendered from+ // this at the edge, which is the rule that keeps the advisory rail+ // free of caller-supplied prose too.+ expect(String(record["stage"])).toMatch(/^[a-z0-9]+([-_][a-z0-9]+)*$/);+ expect(Number.isInteger(record["completed"])).toBe(true);+ }+ });+});++describe("o2b brain dream stage --progress", () => {+ test("watches the staged pass, which is a dream pass", async () => {+ // `DreamStageOptions.onProgress` was declared and threaded through+ // all three staged entry points with no caller able to ask: the verb+ // parsed `--progress` for `stage` and ignored it, so an operator+ // watching a staged pass saw nothing. This is the producer.+ const watched = await runCli(["brain", "dream", "stage", "--json", "--progress"], {+ env: env(),+ });+ expect(watched.returncode).toBe(0);++ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ // Staging IS a dream call, so the records name `dream` rather than a+ // second operation reporting the same five stages under a new name.+ expect(records.every((r) => r["operation"] === OPERATION.dream)).toBe(true);+ expect(records[0]?.["kind"]).toBe(PROGRESS_KIND.started);+ expect(records.at(-1)?.["kind"]).toBe(PROGRESS_KIND.finished);+ });++ test("stdout is untouched, as it is for the inline pass", async () => {+ const plain = await runCli(["brain", "dream", "stage", "--json"], { env: env() });+ const watched = await runCli(["brain", "dream", "stage", "--json", "--progress"], {+ env: env(),+ });+ expect(plain.returncode).toBe(0);+ expect(watched.returncode).toBe(0);+ // Two runs of `stage` mint different run ids, so the comparison is of+ // the payload's SHAPE rather than its bytes - the run id is the one+ // field that is expected to differ.+ expect(Object.keys(JSON.parse(watched.stdout) as object).toSorted()).toEqual(+ Object.keys(JSON.parse(plain.stdout) as object).toSorted(),+ );+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });+});++describe("stopping a dream pass", () => {+ test("is not advertised as a cooperative interrupt, because it cannot be one", () => {+ // `dreamRun` is synchronous end to end, so a signal handler cannot+ // run while it does and `o2b brain dream` opens no handle. The+ // keystroke keeps its default meaning - it kills the process - which+ // is asserted where it belongs, in `interrupt-observability.test.ts`.+ // What is pinned here is that this verb is not claiming otherwise.+ expect(interruptIsObservable(OPERATION.dream)).toBe(false);+ // And that the code a verb WOULD return is still not a success code,+ // for the two verbs that can reach it.+ expect(EXIT_INTERRUPTED).toBe(130);+ expect(EXIT_INTERRUPTED).not.toBe(0);+ });+});diff --git a/tests/cli/brain-maintenance-progress.test.ts b/tests/cli/brain-maintenance-progress.test.tsnew file mode 100644index 00000000..70877749--- /dev/null+++ b/tests/cli/brain-maintenance-progress.test.ts@@ -0,0 +1,106 @@+/**+ * `o2b brain maintenance run` under observation (nothing-runs-unwatched,+ * U1 + U3).+ *+ * The lane is a dispatcher over four long operations, not a fifth one, so+ * the property that matters here is different from the other verbs': the+ * stream carries the CHILDREN's events, and every record names the+ * operation that emitted it. That is what tells a reader which of the+ * four tasks the lane is currently inside - a counter over the lane's own+ * four steps would say "2 of 4" for twenty minutes and mean nothing.+ */++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 { OPERATION } from "../../src/core/brain/safeguard.ts";+import { progressRecords, STAGE_IDENTIFIER } from "../helpers/progress-records.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let configPath: string;++const env = (): Record<string, string> => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });++/**+ * The lane's own report, reduced to what an observer must not change:+ * the verdict, and each task's name and outcome. Durations are+ * wall-clock and are left out rather than asserted as stable.+ */+function laneReport(stdout: string): unknown {+ const parsed = JSON.parse(stdout) as {+ verdict: string;+ tasks: Array<{ name: string; ok: boolean }>;+ };+ return {+ verdict: parsed.verdict,+ tasks: parsed.tasks.map((t) => `${t.name}:${String(t.ok)}`).toSorted(),+ };+}++beforeEach(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-maint-progress-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\n`);+ writeFileSync(join(vault, "one.md"), "# One\n\nLinks to [[two]].\n");+ writeFileSync(join(vault, "two.md"), "# Two\n\nLinks to [[one]].\n");+ const init = await runCli(["brain", "init", "--vault", vault], { env: env() });+ expect(init.returncode).toBe(0);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("o2b brain maintenance run --progress", () => {+ test("forwards each task's own stream, and leaves stdout untouched", async () => {+ const plain = await runCli(["brain", "maintenance", "run", "--vault", vault, "--json"], {+ env: env(),+ });+ const watched = await runCli(+ ["brain", "maintenance", "run", "--vault", vault, "--json", "--progress"],+ { env: env() },+ );++ expect(plain.returncode).toBe(0);+ expect(watched.returncode).toBe(0);++ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ // The lane never speaks in its own name: every record on this stream+ // was emitted by the task doing the work, which is the whole of the+ // aggregator decision.+ expect(records.every((r) => r["operation"] !== OPERATION.maintenance)).toBe(true);+ const seen = new Set(records.map((r) => String(r["operation"])));+ expect(seen.has(OPERATION.dream)).toBe(true);+ expect(seen.has(OPERATION.reindex)).toBe(true);+ expect(progressRecords(plain.stderr)).toHaveLength(0);++ // The lane's own report is what stdout carries, unchanged: same+ // verdict, same four tasks, same success.+ expect(laneReport(watched.stdout)).toEqual(laneReport(plain.stdout));+ });++ test("integers and identifiers only - no prose on the structured stream", async () => {+ const watched = await runCli(["brain", "maintenance", "run", "--vault", vault, "--progress"], {+ env: env(),+ });+ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ for (const record of records) {+ expect(String(record["stage"])).toMatch(STAGE_IDENTIFIER);+ expect(Number.isInteger(record["completed"])).toBe(true);+ }+ });++ test("without the flag nobody is watching, and the run is unchanged", async () => {+ const plain = await runCli(["brain", "maintenance", "run", "--vault", vault], { env: env() });+ expect(plain.returncode).toBe(0);+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });+});diff --git a/tests/cli/brain-maintenance.test.ts b/tests/cli/brain-maintenance.test.tsindex ab20b9b2..4f83d3cc 100644--- a/tests/cli/brain-maintenance.test.ts+++ b/tests/cli/brain-maintenance.test.ts@@ -5,10 +5,12 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { appendFileSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { dirname, join } from "node:path";+import { MAINTENANCE_EXIT } from "../../src/cli/brain/verbs/maintenance.ts";+import { MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT } from "../../src/core/brain/policy/blocks/maintenance.ts";import { runCli } from "../helpers/run-cli.ts";let tmp: string;@@ -87,3 +89,69 @@ test("a malformed window is a usage error", async () => {);expect(result.returncode).toBe(2);});++/** Seed `task`'s journal with the failures that trip the streak refusal. */+function seedFailureStreak(task: string, count: number): void {+ const path = join(vault, ".open-second-brain", "maintenance-runs.jsonl");+ mkdirSync(dirname(path), { recursive: true });+ for (let i = 0; i < count; i++) {+ appendFileSync(+ path,+ JSON.stringify({+ ts: new Date(Date.now() - (count - i) * 86_400_000).toISOString(),+ holder: `seed@${i}`,+ verdict: "run",+ task,+ ok: false,+ duration_ms: 1,+ error: "seeded failure",+ }) + "\n",+ );+ }+}++test("a refused task is reported as refused, with its own exit code", async () => {+ const init = await runCli(["brain", "init", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(init.returncode).toBe(0);+ seedFailureStreak("dream", MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT);++ const run = await runCli(["brain", "maintenance", "run", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ // Not 1: nothing was attempted, so nothing failed - and not 0, because+ // a heavy pass is standing refused and only an operator can change that.+ expect(run.returncode).toBe(MAINTENANCE_EXIT.refused);+ expect(run.stdout).toContain("dream: REFUSED");+ expect(run.stdout).not.toContain("dream: FAILED");+ // The healthy tasks still ran under the same lease.+ expect(run.stdout).toContain("reindex: ok");+});++test("--retry runs the refused task and names an unknown task as a usage error", async () => {+ const init = await runCli(["brain", "init", "--vault", vault], {+ env: { OPEN_SECOND_BRAIN_CONFIG: configPath },+ });+ expect(init.returncode).toBe(0);+ seedFailureStreak("dream", MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT);++ const typo = await runCli(+ ["brain", "maintenance", "run", "--retry", "dreams", "--vault", vault],+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },+ );+ expect(typo.returncode).toBe(MAINTENANCE_EXIT.usage);+ expect(typo.stderr).toContain("dreams");++ const retried = await runCli(+ ["brain", "maintenance", "run", "--retry", "dream", "--vault", vault, "--json"],+ { env: { OPEN_SECOND_BRAIN_CONFIG: configPath } },+ );+ expect(retried.returncode).toBe(MAINTENANCE_EXIT.ok);+ const payload = JSON.parse(retried.stdout) as {+ tasks: Array<{ name: string; ok: boolean; refused?: boolean }>;+ };+ const dream = payload.tasks.find((t) => t.name === "dream");+ expect(dream?.refused).toBeUndefined();+ expect(dream?.ok).toBe(true);+});diff --git a/tests/cli/brain.snapshot-log.test.ts b/tests/cli/brain.snapshot-log.test.tsindex 5ddd5f0f..06643ec2 100644--- a/tests/cli/brain.snapshot-log.test.ts+++ b/tests/cli/brain.snapshot-log.test.ts@@ -16,12 +16,12 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { chmodSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { chmodSync, mkdtempSync, rmSync, symlinkSync, utimesSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";-import { createSnapshot } from "../../src/core/brain/snapshot.ts";+import { createSnapshot, SNAPSHOT_ENTRY_SKIP_REASON } from "../../src/core/brain/snapshot.ts";import { manifestSidecarPath } from "../../src/core/brain/manifest.ts";import { brainDirs, snapshotPath } from "../../src/core/brain/paths.ts";import { BRAIN_SNAPSHOT_REASON } from "../../src/core/brain/types.ts";@@ -174,7 +174,31 @@ describe("brain snapshot log", () => {test("an empty snapshots directory exits zero under --json too", async () => {const r = await snapshotLog("--json");expect(r.returncode).toBe(0);- expect(JSON.parse(r.stdout)).toEqual({ total: 0, snapshots: [] });+ // `skipped` is empty rather than absent: a consumer reading it to+ // decide whether the listing is complete must not have to tell an old+ // build's silence from this build's "nothing was skipped".+ expect(JSON.parse(r.stdout)).toEqual({ total: 0, snapshots: [], skipped: [] });+ });++ test("an archive nobody could describe is named on stderr and carried in --json", async () => {+ seedSnapshots();+ // A dangling symlink under the archive suffix: `readdir` names it,+ // `stat` refuses it. Dropped silently, this listing would print one+ // fewer row and claim to be the history.+ const dir = brainDirs(vault).snapshots;+ symlinkSync(join(dir, "nowhere.tar.zst"), join(dir, "dream-gone.tar.zst"));++ const text = await snapshotLog();+ expect(text.returncode).toBe(0);+ expect(text.stderr).toContain("INCOMPLETE");+ expect(text.stderr).toContain("dream-gone.tar.zst");++ const r = await snapshotLog("--json");+ const payload = JSON.parse(r.stdout) as {+ skipped: ReadonlyArray<{ name: string; reason: string }>;+ };+ expect(payload.skipped.map((s) => s.name)).toEqual(["dream-gone.tar.zst"]);+ expect(payload.skipped[0]!.reason).toBe(SNAPSHOT_ENTRY_SKIP_REASON.entryUnreadable);});test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(diff --git a/tests/cli/cli-json-contract.test.ts b/tests/cli/cli-json-contract.test.tsindex f7d7882f..9693512c 100644--- a/tests/cli/cli-json-contract.test.ts+++ b/tests/cli/cli-json-contract.test.ts@@ -1,10 +1,13 @@-import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test";import { mkdirSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";import { runCli } from "../helpers/run-cli.ts";+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);+let tempDir: string;let vault: string;let configPath: string;diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.tsindex 9d248c61..761dacf8 100644--- a/tests/cli/cli.test.ts+++ b/tests/cli/cli.test.ts@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test";import {mkdirSync,mkdtempSync,@@ -14,9 +14,12 @@ import { join, resolve } from "node:path";import { BRAIN_INDEX_REL, BRAIN_ROOT_REL } from "../../src/core/brain/paths.ts";import { isReadinessStatus } from "../../src/core/doctor-readiness.ts";import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";import { runCli } from "../helpers/run-cli.ts";+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);+let tmp: string;beforeEach(() => {@@ -220,34 +223,18 @@ describe("doctor", () => {HOME: tmp,});- /**- * Budget for a readiness test that spawns the CLI TWICE to compare the- * opt-out output against the opt-in one. One cold spawn of the real binary- * costs several seconds on a loaded machine, so a pair of them sits above- * bun's 5 s default and these two tests passed only when the spawns- * happened to be warm - the same "the suite's verdict is a function of the- * machine it ran on" defect 1.45.1 fixed for the config env leak. The- * single-spawn sibling below is inside the default budget and keeps it,- * so this constant marks exactly the tests that pay twice.- */- const TWO_SPAWN_TIMEOUT_MS = 30_000;-- test(- "without --readiness the output has no readiness section (byte-identical opt-out)",- async () => {- const plain = await runCli(["doctor", "--vault", tmp], { env: readinessEnv() });- expect(plain.returncode).toBe(0);- expect(plain.stdout).not.toContain("readiness:");-- const withFlag = await runCli(["doctor", "--vault", tmp, "--readiness"], {- env: readinessEnv(),- });- // The readiness run appends its section; the base output is unchanged,- // so the plain output is an exact prefix of the readiness output.- expect(withFlag.stdout.startsWith(plain.stdout)).toBe(true);- },- TWO_SPAWN_TIMEOUT_MS,- );+ test("without --readiness the output has no readiness section (byte-identical opt-out)", async () => {+ const plain = await runCli(["doctor", "--vault", tmp], { env: readinessEnv() });+ expect(plain.returncode).toBe(0);+ expect(plain.stdout).not.toContain("readiness:");++ const withFlag = await runCli(["doctor", "--vault", tmp, "--readiness"], {+ env: readinessEnv(),+ });+ // The readiness run appends its section; the base output is unchanged,+ // so the plain output is an exact prefix of the readiness output.+ expect(withFlag.stdout.startsWith(plain.stdout)).toBe(true);+ });test("--readiness runs the default probes with explicit outcomes", async () => {const r = await runCli(["doctor", "--vault", tmp, "--readiness"], { env: readinessEnv() });@@ -261,27 +248,23 @@ describe("doctor", () => {expect(r.stdout).toContain("[PASS] runtime_adapter_wiring:");});- test(- "--readiness --json omits the readiness key without the flag and adds it with it",- async () => {- const plain = await runCli(["doctor", "--vault", tmp, "--json"], { env: readinessEnv() });- expect(JSON.parse(plain.stdout).readiness).toBeUndefined();-- const withFlag = await runCli(["doctor", "--vault", tmp, "--json", "--readiness"], {- env: readinessEnv(),- });- const parsed = JSON.parse(withFlag.stdout);- expect(Array.isArray(parsed.readiness)).toBe(true);- // The probe set is the default registry; assert it is non-empty and that- // every entry carries a status from the closed vocabulary, rather than- // pinning a count that a new probe changes for no behavioural reason.- expect(parsed.readiness.length).toBeGreaterThan(0);- expect(parsed.readiness.every((p: { status: string }) => isReadinessStatus(p.status))).toBe(- true,- );- },- TWO_SPAWN_TIMEOUT_MS,- );+ test("--readiness --json omits the readiness key without the flag and adds it with it", async () => {+ const plain = await runCli(["doctor", "--vault", tmp, "--json"], { env: readinessEnv() });+ expect(JSON.parse(plain.stdout).readiness).toBeUndefined();++ const withFlag = await runCli(["doctor", "--vault", tmp, "--json", "--readiness"], {+ env: readinessEnv(),+ });+ const parsed = JSON.parse(withFlag.stdout);+ expect(Array.isArray(parsed.readiness)).toBe(true);+ // The probe set is the default registry; assert it is non-empty and that+ // every entry carries a status from the closed vocabulary, rather than+ // pinning a count that a new probe changes for no behavioural reason.+ expect(parsed.readiness.length).toBeGreaterThan(0);+ expect(parsed.readiness.every((p: { status: string }) => isReadinessStatus(p.status))).toBe(+ true,+ );+ });test("--readiness exits 1 with a fail reason when a probe fails", async () => {// A key-requiring embedding provider (openai-compat) with no key makes thediff --git a/tests/cli/config-read-failure-surfaces.test.ts b/tests/cli/config-read-failure-surfaces.test.tsindex fca1d63b..37f4c95e 100644--- a/tests/cli/config-read-failure-surfaces.test.ts+++ b/tests/cli/config-read-failure-surfaces.test.ts@@ -21,12 +21,21 @@* result.*/-import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { afterEach, beforeEach, describe, expect, setDefaultTimeout, 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";+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";++// Every test here spawns `o2b`, and a test that overruns leaves its spawn+// running past `afterEach`: the late `chmod` in `withUnreadableConfig`+// restores the NEXT test's config file, so the next test reads a config it+// made unreadable and fails for a reason that has nothing to do with it.+// The budget is what stops one slow spawn from being reported as two bugs.+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);+const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");const CLI_ENTRY = join(REPO_ROOT, "src", "cli", "main.ts");diff --git a/tests/cli/doctor-exit.test.ts b/tests/cli/doctor-exit.test.tsnew file mode 100644index 00000000..12b1196d--- /dev/null+++ b/tests/cli/doctor-exit.test.ts@@ -0,0 +1,137 @@+/**+ * `o2b doctor --readiness` exit codes (nothing-runs-unwatched, unit U12).+ *+ * The verb used to answer with two numbers for three findings. A probe+ * whose budget elapsed was counted as a failure and exited 1, so the same+ * healthy machine exited 0 when idle and 1 when loaded; classifying that+ * probe honestly as `unknown` then moved it into the other silence, and it+ * would have exited 0 - "everything checked out" - for a run that checked+ * nothing. Both readings are wrong, so a run that could not find out gets+ * its own number.+ *+ * That number is 6, the one `o2b search check` already spends on a probe+ * that did not complete, and the pin below is the same one that verb keeps+ * against `o2b install --check`: one number, one meaning across this CLI.+ */++import { afterEach, beforeEach, describe, expect, setDefaultTimeout, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { DOCTOR_EXIT, doctorExitCode } from "../../src/cli/main.ts";+import { SEARCH_CHECK_EXIT } from "../../src/cli/search/verbs/check.ts";+import { READINESS_STATUS, type ReadinessReport } from "../../src/core/doctor-readiness.ts";+import { manifestPath } from "../../src/core/install/manifest.ts";+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";+import { runCli } from "../helpers/run-cli.ts";++setDefaultTimeout(CLI_SPAWN_BUDGET_MS);++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-doctor-exit-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** A readiness report with the counts under test and one matching probe. */+function report(failed: number, unknown: number): ReadinessReport {+ return {+ probes: [+ {+ name: "unit_probe",+ status: failed > 0 ? READINESS_STATUS.fail : READINESS_STATUS.unknown,+ detail: "unit",+ durationMs: 1,+ },+ ],+ failed,+ unknown,+ };+}++describe("doctorExitCode", () => {+ test("a clean run exits 0 and a proved failure exits 1", () => {+ expect(doctorExitCode(0, null)).toBe(DOCTOR_EXIT.ok);+ expect(doctorExitCode(1, null)).toBe(DOCTOR_EXIT.failed);+ expect(doctorExitCode(0, report(1, 0))).toBe(DOCTOR_EXIT.failed);+ });++ test("a probe that did not complete is neither a pass nor a failure", () => {+ const code = doctorExitCode(0, report(0, 1));+ expect(code).toBe(DOCTOR_EXIT.probeIncomplete);+ expect(code).not.toBe(DOCTOR_EXIT.ok);+ expect(code).not.toBe(DOCTOR_EXIT.failed);+ });++ test("a proved failure outranks an unmeasured probe, so the specific code never masks it", () => {+ // Same precedence rule `exitCodeForCheck` follows: the more basic+ // finding keeps the generic code even when both are present.+ expect(doctorExitCode(1, report(0, 1))).toBe(DOCTOR_EXIT.failed);+ expect(doctorExitCode(0, report(1, 1))).toBe(DOCTOR_EXIT.failed);+ });++ test("the table is a table and agrees with the verb that set the precedent", () => {+ const codes = Object.values(DOCTOR_EXIT);+ expect(new Set(codes).size).toBe(codes.length);+ // `o2b search check` already spends 6 on a probe that did not complete;+ // a script that learned the number there must not learn a second one.+ expect(DOCTOR_EXIT.probeIncomplete).toBe(SEARCH_CHECK_EXIT.probeIncomplete);+ expect(DOCTOR_EXIT.ok).toBe(SEARCH_CHECK_EXIT.ok);+ });+});++describe("o2b doctor --readiness end to end", () => {+ /**+ * Semantic search off and HOME pinned so the only probe with anything to+ * say about this machine is the installed-runtimes one, whose input this+ * test writes.+ */+ const env = () => ({+ OPEN_SECOND_BRAIN_CONFIG: "",+ XDG_CONFIG_HOME: "",+ VAULT_DIR: "",+ OPEN_SECOND_BRAIN_SEARCH_SEMANTIC: "false",+ HOME: tmp,+ });++ test("an install manifest that will not parse exits 6, not 0 and not 1", async () => {+ // The manifest exists, so "nothing is installed" is not the answer; it+ // is unreadable, so neither is "installed and healthy". The probe says+ // it could not measure, and the exit code says so too.+ mkdirSync(join(tmp, ".open-second-brain"), { recursive: true });+ writeFileSync(manifestPath(tmp), "{ this is not json", "utf8");++ const r = await runCli(["doctor", "--vault", tmp, "--readiness"], { env: env() });+ expect(r.stdout).toContain("[UNKNOWN] installed_runtimes:");+ expect(r.returncode).toBe(DOCTOR_EXIT.probeIncomplete);+ expect(r.returncode).not.toBe(DOCTOR_EXIT.ok);+ expect(r.returncode).not.toBe(DOCTOR_EXIT.failed);+ });++ test("the same vault with a readable manifest exits 0, so 6 is earned and not ambient", async () => {+ const r = await runCli(["doctor", "--vault", tmp, "--readiness"], { env: env() });+ expect(r.returncode).toBe(DOCTOR_EXIT.ok);+ });++ test("--json carries the same three-way answer the exit code does", async () => {+ mkdirSync(join(tmp, ".open-second-brain"), { recursive: true });+ writeFileSync(manifestPath(tmp), "{ this is not json", "utf8");++ const r = await runCli(["doctor", "--vault", tmp, "--readiness", "--json"], { env: env() });+ expect(r.returncode).toBe(DOCTOR_EXIT.probeIncomplete);+ const parsed = JSON.parse(r.stdout);+ expect(parsed.readiness_summary.unknown).toBe(1);+ expect(parsed.readiness_summary.failed).toBe(0);+ expect(+ parsed.readiness.some(+ (p: { name: string; status: string }) =>+ p.name === "installed_runtimes" && p.status === READINESS_STATUS.unknown,+ ),+ ).toBe(true);+ });+});diff --git a/tests/cli/install-json-shape.test.ts b/tests/cli/install-json-shape.test.tsnew file mode 100644index 00000000..883cbfa8--- /dev/null+++ b/tests/cli/install-json-shape.test.ts@@ -0,0 +1,180 @@+/**+ * Every `o2b install --json` payload, pinned.+ *+ * The human side of this verb was already pinned byte-for-byte: each+ * `install/<runtime>.md` carries an expected-output block and+ * `tests/docs/install-verify-conformance.test.ts` renders the real+ * `verify()` against it. The machine side was pinned by nothing. Four+ * modes emit four different payloads, three declared `schema_version: 1`+ * and the fourth - apply, the only mode that actually changes the machine -+ * declared no version at all, and no test asserted a single field name in+ * any of them.+ *+ * That asymmetry is the defect: a field added to the human table breaks a+ * documented block and names the file to edit, while the same field+ * forgotten on the JSON twin breaks nothing. This file removes the second+ * half of the asymmetry by naming the key set of every payload.+ *+ * Known wire inconsistency, pinned rather than fixed here: the plan+ * payload serialises `InstallPlan` verbatim, so it carries `postNotes` in+ * camelCase while every other payload in this family uses snake_case+ * (`config_path`, `fix_hint`, `steps_executed`). Renaming it is a wire+ * break with no consumer asking for it; pinning it is what makes the+ * rename a deliberate act rather than an accident.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { INSTALL_JSON_SCHEMA_VERSION } from "../../src/cli/install/render.ts";+import { runCli as baseRunCli, type RunCliOptions, type RunResult } from "../helpers/run-cli.ts";++// Same reason as `install-verb.test.ts`: the adapters resolve the home+// directory at module-load time, so each call needs a fresh process to+// honour this file's per-case temp HOME.+function runCli(args: ReadonlyArray<string>, opts: RunCliOptions = {}): Promise<RunResult> {+ return baseRunCli(args, { ...opts, subprocess: true });+}++let vault: string;+let home: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-ijs-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-ijs-h-"));+ configPath = join(home, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\nagent_name: "claude-vps"\ntimezone: "UTC"\n`);+});++afterEach(() => {+ for (const p of [vault, home]) {+ try {+ rmSync(p, { recursive: true, force: true });+ } catch {}+ }+});++function envBase() {+ return {+ HOME: home,+ OPEN_SECOND_BRAIN_CONFIG: configPath,+ VAULT_DIR: vault,+ VAULT_AGENT_NAME: "claude-vps",+ VAULT_TIMEZONE: "UTC",+ };+}++async function payloadOf(args: ReadonlyArray<string>): Promise<Record<string, unknown>> {+ const r = await runCli(args, { env: envBase() });+ expect(`${args.join(" ")} exit ${r.returncode}\n${r.stderr}`).toBe(`${args.join(" ")} exit 0\n`);+ return JSON.parse(r.stdout) as Record<string, unknown>;+}++/**+ * Every case here spawns a real `o2b` child, which costs about two seconds+ * of module graph on an unloaded machine. The default five would make this+ * file fail for being slow rather than for being wrong.+ */+const CLI_TIMEOUT_MS = 30_000;++/** Sorted key list, so a failure names the field rather than a count. */+function keys(value: unknown): string {+ return Object.keys(value as object)+ .toSorted()+ .join(",");+}++describe("every install --json payload declares its schema version", () => {+ test(+ "detect",+ async () => {+ const payload = await payloadOf(["install", "--json"]);+ expect(payload["schema_version"]).toBe(INSTALL_JSON_SCHEMA_VERSION);+ },+ CLI_TIMEOUT_MS,+ );++ test(+ "plan",+ async () => {+ const payload = await payloadOf(["install", "--target", "cursor", "--json"]);+ expect(payload["schema_version"]).toBe(INSTALL_JSON_SCHEMA_VERSION);+ },+ CLI_TIMEOUT_MS,+ );++ test(+ "apply - the one mode that changes the machine, and the one that had none",+ async () => {+ const payload = await payloadOf(["install", "--target", "cursor", "--apply", "--json"]);+ expect(payload["schema_version"]).toBe(INSTALL_JSON_SCHEMA_VERSION);+ },+ CLI_TIMEOUT_MS,+ );++ test(+ "verify",+ async () => {+ const payload = await payloadOf(["install", "--check", "--json"]);+ expect(payload["schema_version"]).toBe(INSTALL_JSON_SCHEMA_VERSION);+ },+ CLI_TIMEOUT_MS,+ );+});++describe("every install --json payload names its fields", () => {+ test(+ "detect carries a target row per adapter",+ async () => {+ const payload = await payloadOf(["install", "--json"]);+ expect(keys(payload)).toBe("schema_version,targets");+ const targets = payload["targets"] as ReadonlyArray<unknown>;+ expect(targets.length).toBeGreaterThan(0);+ for (const row of targets) expect(keys(row)).toBe("config_path,notes,status,target");+ },+ CLI_TIMEOUT_MS,+ );++ test(+ "plan carries the plan verbatim",+ async () => {+ const payload = await payloadOf(["install", "--target", "cursor", "--json"]);+ expect(keys(payload)).toBe("plan,schema_version");+ expect(keys(payload["plan"])).toBe("postNotes,steps,target");+ for (const step of (payload["plan"] as { steps: ReadonlyArray<unknown> }).steps) {+ expect(keys(step)).toBe("kind,path,preview");+ }+ },+ CLI_TIMEOUT_MS,+ );++ test(+ "apply carries the manifest it wrote, at the top level as before",+ async () => {+ const payload = await payloadOf(["install", "--target", "cursor", "--apply", "--json"]);+ // `schema_version` is ADDED beside the result's own fields rather than+ // nesting the result under a key: an existing consumer reading+ // `.manifest` or `.steps_executed` keeps working and gains a version,+ // which a re-nesting would have broken for no benefit.+ expect(keys(payload)).toContain("manifest");+ expect(keys(payload)).toContain("steps_executed");+ expect(keys(payload)).toContain("target");+ },+ CLI_TIMEOUT_MS,+ );++ test(+ "verify carries a verify row per adapter",+ async () => {+ const payload = await payloadOf(["install", "--check", "--json"]);+ expect(keys(payload)).toBe("schema_version,targets");+ const targets = payload["targets"] as ReadonlyArray<unknown>;+ expect(targets.length).toBeGreaterThan(0);+ for (const row of targets) expect(keys(row)).toBe("details,fix_hint,status,target");+ },+ CLI_TIMEOUT_MS,+ );+});diff --git a/tests/cli/install-ownership-close.test.ts b/tests/cli/install-ownership-close.test.tsnew file mode 100644index 00000000..a5e3b0bb--- /dev/null+++ b/tests/cli/install-ownership-close.test.ts@@ -0,0 +1,151 @@+/**+ * When the ownership close fires, and when it must not.+ *+ * `o2b install --check` exits 0 for `not-installed` by design - the+ * operator never asked for that runtime - so "exit 0" is the wrong trigger+ * for a statement congratulating them on owning their brain: on a machine+ * where the install did nothing, it would be the only output. The close is+ * bound to a target that verified `ok`, and to an apply that ran, which are+ * the two states where something was actually established.+ *+ * The second thing pinned here is PARITY. The human `--check` table is+ * pinned byte-for-byte against the install documents and the JSON twin is+ * pinned by this file; nothing else would notice a close that reached one+ * surface and not the other, which is exactly how the two drifted before.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli as baseRunCli, type RunCliOptions, type RunResult } from "../helpers/run-cli.ts";++function runCli(args: ReadonlyArray<string>, opts: RunCliOptions = {}): Promise<RunResult> {+ return baseRunCli(args, { ...opts, subprocess: true });+}++let vault: string;+let home: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-ioc-v-"));+ home = mkdtempSync(join(tmpdir(), "osb-ioc-h-"));+ configPath = join(home, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\nagent_name: "claude-vps"\ntimezone: "UTC"\n`);+});++afterEach(() => {+ for (const p of [vault, home]) {+ try {+ rmSync(p, { recursive: true, force: true });+ } catch {}+ }+});++function envBase() {+ return {+ HOME: home,+ OPEN_SECOND_BRAIN_CONFIG: configPath,+ VAULT_DIR: vault,+ VAULT_AGENT_NAME: "claude-vps",+ VAULT_TIMEZONE: "UTC",+ };+}++/**+ * Every case here spawns real `o2b` children, which cost about two seconds+ * of module graph each. The default five would make this file fail for+ * being slow rather than for being wrong.+ */+const CLI_TIMEOUT_MS = 30_000;++/** The heading the composed statement always opens with. */+const CLOSE_HEADING = "Your data, and where it is:";++describe("a successful apply closes by saying what the operator owns", () => {+ test(+ "the human surface names the resolved vault and the exceptions",+ async () => {+ const r = await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain(CLOSE_HEADING);+ expect(r.stdout).toContain(vault);+ // The counterexample is named rather than omitted.+ expect(r.stdout).toContain("opencode session spool");+ },+ CLI_TIMEOUT_MS,+ );++ test(+ "the machine surface carries the same value under data_ownership",+ async () => {+ const r = await runCli(["install", "--target", "cursor", "--apply", "--json"], {+ env: envBase(),+ });+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;+ const ownership = payload["data_ownership"] as Record<string, unknown>;+ expect(ownership).toBeDefined();+ expect(ownership["vault"]).toBe(vault);+ // A verdict is always present, and it is allowed to be `undetermined`.+ expect(typeof (ownership["backing"] as Record<string, unknown>)["state"]).toBe("string");+ expect((ownership["outside_vault"] as ReadonlyArray<unknown>).length).toBeGreaterThan(0);+ },+ CLI_TIMEOUT_MS,+ );+});++describe("a verify only closes when something verified ok", () => {+ test(+ "with nothing installed the close stays silent on both surfaces",+ async () => {+ const human = await runCli(["install", "--check"], { env: envBase() });+ expect(human.returncode).toBe(0);+ expect(human.stdout).toContain("not-installed");+ expect(human.stdout).not.toContain(CLOSE_HEADING);++ const machine = await runCli(["install", "--check", "--json"], { env: envBase() });+ expect(machine.returncode).toBe(0);+ expect(JSON.parse(machine.stdout)["data_ownership"]).toBeUndefined();+ },+ CLI_TIMEOUT_MS,+ );++ test(+ "after an install, a passing check closes on both surfaces",+ async () => {+ await runCli(["install", "--target", "cursor", "--apply"], { env: envBase() });++ const human = await runCli(["install", "--check", "--target", "cursor"], { env: envBase() });+ expect(human.returncode).toBe(0);+ expect(human.stdout).toContain(CLOSE_HEADING);++ const machine = await runCli(["install", "--check", "--target", "cursor", "--json"], {+ env: envBase(),+ });+ expect(machine.returncode).toBe(0);+ const ownership = JSON.parse(machine.stdout)["data_ownership"] as Record<string, unknown>;+ expect(ownership["vault"]).toBe(vault);+ // Three subprocess CLI runs: an apply plus both check surfaces.+ },+ CLI_TIMEOUT_MS,+ );+});++describe("the onboarding checklist carries the same field", () => {+ test(+ "o2b onboarding --json exposes data_ownership beside the steps",+ async () => {+ const r = await runCli(["onboarding", "--json"], { env: envBase() });+ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as Record<string, unknown>;+ expect(payload["steps"]).toBeDefined();+ const ownership = payload["data_ownership"] as Record<string, unknown>;+ expect(ownership["vault"]).toBe(vault);+ expect(ownership["backing"]).toBeDefined();+ },+ CLI_TIMEOUT_MS,+ );+});diff --git a/tests/cli/install-vault-resolution.test.ts b/tests/cli/install-vault-resolution.test.tsnew file mode 100644index 00000000..46273839--- /dev/null+++ b/tests/cli/install-vault-resolution.test.ts@@ -0,0 +1,114 @@+/**+ * `o2b install` resolves the vault the way the rest of the CLI does.+ *+ * The verb used to carry its own chain - `--vault` then the config `vault`+ * key then `VAULT_DIR` - which disagreed with {@link resolveVault} on two+ * points that change the answer rather than the spelling: `VAULT_DIR` came+ * LAST instead of first, and neither the project pointer nor the active+ * profile was consulted at all. A machine with both a config `vault` and a+ * `VAULT_DIR` got two different vaults from `o2b install` and from every+ * other verb, so the path the installer wrote into an agent's MCP entry+ * could name a directory nothing else was using.+ *+ * The precedence is pinned here rather than described, and it is pinned by+ * COMPARISON: every row asserts the install resolver returns exactly what+ * `resolveVault` returns for the same state, so a future edit to either+ * chain fails this file instead of silently re-opening the divergence.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { resolveInstallVault } from "../../src/cli/install/install.ts";+import { resolveVault } from "../../src/core/config.ts";+import { runCli } from "../helpers/run-cli.ts";++let configVault: string;+let envVault: string;+let explicitVault: string;+let home: string;+let configPath: string;+let savedVaultDir: string | undefined;++/**+ * What the canonical resolver answers, in the shape the install verb+ * consumes it.+ *+ * `resolveVault` returns `string | null` and every caller decides what an+ * unresolved vault means; `resolveInstallVault` answers `""` because+ * `InstallEnv.vault` is typed `string` and both of its readers - `runCheck`+ * and `loadPayload` - refuse an empty vault BY NAME rather than joining a+ * path onto it. Collapsing the null here is what makes the comparison+ * total, so a divergence between the two chains fails on the PATH rather+ * than on the type.+ */+function canonical(): string {+ return resolveVault(configPath) ?? "";+}++beforeEach(() => {+ configVault = mkdtempSync(join(tmpdir(), "osb-ivr-cfg-"));+ envVault = mkdtempSync(join(tmpdir(), "osb-ivr-env-"));+ explicitVault = mkdtempSync(join(tmpdir(), "osb-ivr-arg-"));+ home = mkdtempSync(join(tmpdir(), "osb-ivr-home-"));+ configPath = join(home, "config.yaml");+ writeFileSync(configPath, `vault: "${configVault}"\nagent_name: "unit"\ntimezone: "UTC"\n`);+ savedVaultDir = process.env["VAULT_DIR"];+});++afterEach(() => {+ if (savedVaultDir === undefined) delete process.env["VAULT_DIR"];+ else process.env["VAULT_DIR"] = savedVaultDir;+ for (const p of [configVault, envVault, explicitVault, home]) {+ try {+ rmSync(p, { recursive: true, force: true });+ } catch {}+ }+});++describe("o2b install shares the canonical vault chain", () => {+ test("VAULT_DIR wins over the config key, exactly as resolveVault does", () => {+ process.env["VAULT_DIR"] = envVault;+ expect(resolveInstallVault(null, configPath)).toBe(envVault);+ expect(resolveInstallVault(null, configPath)).toBe(canonical());+ });++ test("the config key answers when VAULT_DIR is unset", () => {+ delete process.env["VAULT_DIR"];+ expect(resolveInstallVault(null, configPath)).toBe(configVault);+ expect(resolveInstallVault(null, configPath)).toBe(canonical());+ });++ test("--vault outranks both - it is the operator naming the target directly", () => {+ process.env["VAULT_DIR"] = envVault;+ expect(resolveInstallVault(explicitVault, configPath)).toBe(explicitVault);+ });++ test("an unresolvable vault is the empty string, which every caller refuses by name", () => {+ delete process.env["VAULT_DIR"];+ const bare = join(home, "no-vault-key.yaml");+ writeFileSync(bare, `agent_name: "unit"\n`);+ expect(resolveInstallVault(null, bare)).toBe("");+ });++ test("a tilde in VAULT_DIR is expanded, so the payload never carries a literal ~", () => {+ process.env["VAULT_DIR"] = "~/some-vault";+ const resolved = resolveInstallVault(null, configPath);+ expect(resolved.startsWith("~")).toBe(false);+ expect(resolved).toBe(canonical());+ });+});++describe("the payload the installer writes names the resolved vault", () => {+ test("VAULT_DIR set alongside a different config vault writes VAULT_DIR's path", async () => {+ const r = await runCli(+ ["install", "--target", "generic", "--apply", "--out", "-", "--config", configPath],+ { env: { VAULT_DIR: envVault, OPEN_SECOND_BRAIN_CONFIG: configPath } },+ );+ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain(envVault);+ expect(r.stdout).not.toContain(configVault);+ });+});diff --git a/tests/cli/install-verb.test.ts b/tests/cli/install-verb.test.tsindex 6318874b..ebae7322 100644--- a/tests/cli/install-verb.test.ts+++ b/tests/cli/install-verb.test.ts@@ -6,11 +6,12 @@* --check, --json, exit codes.*/-import { describe, expect, test, beforeEach, afterEach } from "bun:test";+import { describe, expect, test, beforeEach, afterEach, setDefaultTimeout } from "bun:test";import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync, utimesSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";import { runCli as baseRunCli, type RunCliOptions, type RunResult } from "../helpers/run-cli.ts";import { INSTALL_EXIT, exitCodeForVerify } from "../../src/cli/install/install.ts";import type { VerifyResult } from "../../src/core/install/types.ts";@@ -23,6 +24,10 @@ function runCli(args: ReadonlyArray<string>, opts: RunCliOptions = {}): Promise<return baseRunCli(args, { ...opts, subprocess: true });}+// Every case here therefore pays a cold process start, which does not fit+// bun's 5 s default on a machine doing other work.+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);+let vault: string;let home: string;let configPath: string;diff --git a/tests/cli/interrupt-observability.test.ts b/tests/cli/interrupt-observability.test.tsnew file mode 100644index 00000000..0dbd6e97--- /dev/null+++ b/tests/cli/interrupt-observability.test.ts@@ -0,0 +1,278 @@+/**+ * Ctrl-C, and the four operations it cannot reach.+ *+ * The branch wired `onInterrupt()` into six verbs and claimed all six were+ * interruptible. Four of them - dream, bridges, clusters, architect - run+ * fully synchronously, and a JavaScript signal handler is dispatched from+ * the event loop, so it cannot run while they do. Registering the listener+ * anyway made those four STRICTLY worse: the listener suppresses Node's+ * default termination, so the first keystroke stopped killing the process+ * and started doing nothing at all.+ *+ * These tests pin the three rules that replaced the claim.+ *+ * 1. A handle may only be opened for an operation that yields to the+ * event loop. Asking for one for an operation that does not is a+ * defect reported by name, not a handle that quietly does nothing.+ * 2. A verb whose operation cannot observe the signal registers no+ * listener at all, so the keystroke keeps its default meaning.+ * 3. An interrupt that arrived and that no operation acted on still ends+ * the run. A verb cannot return 0 for a pass the operator stopped.+ *+ * Rules 3 and the platform fact underneath all of this are exercised in+ * child processes: they turn on real signal delivery and on real process+ * termination, neither of which can be faked in-process, and neither of+ * which may be aimed at the test runner itself.+ */++import { describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { interruptIsObservable, onInterrupt } from "../../src/cli/interrupt.ts";+import { OPERATION, type Operation } from "../../src/core/brain/safeguard.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { runCli } from "../helpers/run-cli.ts";++const SRC = resolve(import.meta.dir, "..", "..", "src");++interface DriverResult {+ readonly stdout: string;+ readonly stderr: string;+ readonly code: number | null;+ readonly signal: string | null;+}++/**+ * Run `body` as its own process and report how it ended.+ *+ * A child rather than the runner because every property here is about a+ * real SIGINT: delivered by the kernel, dispatched by the receiving+ * process's own event loop, and - in the cases that matter - killing the+ * process it reaches. A test that aimed any of that at the runner would+ * take the suite with it.+ */+async function runDriver(body: string): Promise<DriverResult> {+ const dir = mkdtempSync(join(tmpdir(), "o2b-interrupt-driver-"));+ try {+ const file = join(dir, "driver.ts");+ writeFileSync(file, body, "utf8");+ const proc = Bun.spawn(["bun", "run", file], { stdout: "pipe", stderr: "pipe" });+ const [stdout, stderr] = await Promise.all([+ new Response(proc.stdout).text(),+ new Response(proc.stderr).text(),+ ]);+ await proc.exited;+ return {+ stdout,+ stderr,+ code: proc.exitCode,+ signal: proc.signalCode,+ };+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+}++describe("the platform fact the rules rest on", () => {+ test("a delivered SIGINT is invisible to a fully synchronous checkpoint loop", async () => {+ // `dreamRun`, `detectCommunitiesRun`, `discoverBridgesRun` and+ // `generateRun` are all declared `function`, not `async`, and contain+ // no `await`. This drives production `onInterrupt` and production+ // `createSafeguard` through exactly that shape, with a real signal+ // pending for most of it, and records what the checkpoint saw.+ const result = await runDriver(`+ import { onInterrupt } from ${JSON.stringify(join(SRC, "cli", "interrupt.ts"))};+ import { createSafeguard, SafeguardAbortError, OPERATION } from ${JSON.stringify(join(SRC, "core", "brain", "safeguard.ts"))};++ const interrupt = onInterrupt(OPERATION.reindex);+ const safeguard = createSafeguard({ operation: "dream", signal: interrupt.signal });+ Bun.spawn(["bash", "-c", \`sleep 0.3; kill -INT \${process.pid}\`]);++ let checkpoints = 0;+ let stoppedByCtrlC = false;+ const start = Date.now();+ try {+ while (Date.now() - start < 1500) { safeguard.checkpoint(); checkpoints++; }+ } catch (e) { stoppedByCtrlC = e instanceof SafeguardAbortError; }+ const duringRun = interrupt.received();+ await new Promise((r) => setTimeout(r, 50));+ console.log(JSON.stringify({+ checkpoints, stoppedByCtrlC, duringRun, afterOneEventLoopTurn: interrupt.received(),+ }));+ interrupt.acknowledge();+ interrupt.release();+ `);+ const seen = JSON.parse(result.stdout.trim()) as Record<string, unknown>;+ // Millions of checkpoints, every one of them past the moment the key+ // was pressed, and not one of them saw it.+ expect(seen["checkpoints"]).toBeGreaterThan(100_000);+ expect(seen["stoppedByCtrlC"]).toBe(false);+ expect(seen["duringRun"]).toBeNull();+ // And it was never in doubt that the signal arrived: one turn of the+ // event loop later, it is there.+ expect(seen["afterOneEventLoopTurn"]).toBe("SIGINT");+ }, 30_000);+});++describe("a handle is opened only where the operation can observe it", () => {+ const SYNCHRONOUS: Operation[] = [+ OPERATION.dream,+ OPERATION.bridges,+ OPERATION.clusters,+ OPERATION.architect,+ ];++ test.each(SYNCHRONOUS)("%s cannot observe an interrupt, and says so", (operation) => {+ expect(interruptIsObservable(operation)).toBe(false);+ // Not a no-op handle: a handle that installs nothing would make the+ // wrong call site look like the right one.+ expect(() => onInterrupt(operation)).toThrow(+ new RegExp(`${operation}[\\s\\S]*runs to completion without yielding`),+ );+ });++ const ASYNCHRONOUS: Operation[] = [OPERATION.reindex, OPERATION.maintenance];++ test.each(ASYNCHRONOUS)("%s yields to the event loop, so it may hold a handle", (operation) => {+ expect(interruptIsObservable(operation)).toBe(true);+ const handle = onInterrupt(operation);+ try {+ expect(handle.signal.aborted).toBe(false);+ expect(handle.received()).toBeNull();+ } finally {+ handle.release();+ }+ });++ test("every operation in the vocabulary has an answer", () => {+ for (const operation of Object.values(OPERATION)) {+ expect(typeof interruptIsObservable(operation)).toBe("boolean");+ }+ });+});++describe("a verb that cannot observe the signal leaves it alone", () => {+ /**+ * Registering a SIGINT listener suppresses the default terminate for as+ * long as it is registered. So for the four synchronous operations the+ * observable property is not "the handle works" - it cannot - it is+ * that no listener is installed, which is what keeps the keystroke+ * lethal. Counting after the run would see nothing either way, because+ * `release()` removes what it added; the registration itself is what+ * has to be watched.+ */+ async function signalListenersRegisteredDuring(+ args: ReadonlyArray<string>,+ env: Record<string, string>,+ ): Promise<string[]> {+ const registered: string[] = [];+ const realOnce = process.once.bind(process);+ const spy = ((event: string, listener: (...a: unknown[]) => void) => {+ if (event === "SIGINT" || event === "SIGTERM") registered.push(event);+ return realOnce(event as never, listener as never);+ }) as typeof process.once;+ process.once = spy;+ try {+ await runCli(args, { env });+ } finally {+ process.once = realOnce;+ }+ return registered;+ }++ test("`brain dream` registers no signal listener", async () => {+ const vault = mkdtempSync(join(tmpdir(), "o2b-interrupt-vault-"));+ const cfgHome = mkdtempSync(join(tmpdir(), "o2b-interrupt-cfg-"));+ const configPath = join(cfgHome, "config.yaml");+ try {+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+ const registered = await signalListenersRegisteredDuring(["brain", "dream", "--dry-run"], {+ OPEN_SECOND_BRAIN_CONFIG: configPath,+ });+ expect(registered).toEqual([]);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ rmSync(cfgHome, { recursive: true, force: true });+ }+ }, 60_000);+});++describe("an interrupt nobody acted on still ends the run", () => {+ test("release re-raises a signal the operation never observed", async () => {+ // The window every one of the six verbs leaves open: `Store.open`, a+ // proposal write, a report render - work inside the handle's lifetime+ // that never consults the signal. Before this rule the controller+ // aborted, nobody read it, and the verb returned 0.+ const result = await runDriver(`+ import { onInterrupt } from ${JSON.stringify(join(SRC, "cli", "interrupt.ts"))};+ import { OPERATION } from ${JSON.stringify(join(SRC, "core", "brain", "safeguard.ts"))};++ const interrupt = onInterrupt(OPERATION.reindex);+ try {+ Bun.spawn(["bash", "-c", \`sleep 0.2; kill -INT \${process.pid}\`]);+ await new Promise((r) => setTimeout(r, 600));+ console.log("the operation finished without ever reading the signal");+ } finally {+ interrupt.release();+ }+ console.log("UNREACHABLE: the verb returned normally");+ process.exit(0);+ `);+ expect(result.stdout).toContain("without ever reading the signal");+ expect(result.stdout).not.toContain("UNREACHABLE");+ expect(result.stderr).toContain("interrupted");+ // The keystroke's own code, so a shell and a parent process read it+ // the way they read any other Ctrl-C. Asserted as the code rather+ // than as `signalCode`: Bun's default SIGINT disposition surfaces to+ // a parent as `exitCode: 130, signalCode: null` where a re-raise under+ // Node's would surface as the signal. What must hold is the number a+ // caller gates on, and that it is not 0.+ expect(result.code).toBe(130);+ }, 30_000);++ test("an acknowledged interrupt lets the verb report its own exit code", async () => {+ const result = await runDriver(`+ import { onInterrupt, reportInterrupted, EXIT_INTERRUPTED } from ${JSON.stringify(join(SRC, "cli", "interrupt.ts"))};+ import { OPERATION, SafeguardAbortError } from ${JSON.stringify(join(SRC, "core", "brain", "safeguard.ts"))};++ const interrupt = onInterrupt(OPERATION.reindex);+ let code;+ try {+ Bun.spawn(["bash", "-c", \`sleep 0.2; kill -INT \${process.pid}\`]);+ await new Promise((r) => setTimeout(r, 600));+ // What the real catch arm does when the operation stopped at a+ // checkpoint of its own.+ code = reportInterrupted(interrupt, new SafeguardAbortError("reindex"), false);+ } finally {+ interrupt.release();+ }+ console.log("verb returned " + code);+ process.exit(code);+ `);+ // Reported, not re-raised: the verb's own answer stands, and the line+ // after `reportInterrupted` still runs - which is the whole difference+ // from the unacknowledged case above.+ expect(result.stdout).toContain("verb returned 130");+ expect(result.stderr).not.toContain("stopping now");+ expect(result.code).toBe(130);+ }, 30_000);++ test("a run nobody interrupted releases silently and exits 0", async () => {+ const result = await runDriver(`+ import { onInterrupt } from ${JSON.stringify(join(SRC, "cli", "interrupt.ts"))};+ import { OPERATION } from ${JSON.stringify(join(SRC, "core", "brain", "safeguard.ts"))};++ const interrupt = onInterrupt(OPERATION.reindex);+ try { await new Promise((r) => setTimeout(r, 20)); } finally { interrupt.release(); }+ console.log("clean");+ process.exit(0);+ `);+ expect(result.stdout).toContain("clean");+ expect(result.stderr).toBe("");+ expect(result.code).toBe(0);+ }, 30_000);+});diff --git a/tests/cli/progress-emitter-census.test.ts b/tests/cli/progress-emitter-census.test.tsnew file mode 100644index 00000000..822d10c7--- /dev/null+++ b/tests/cli/progress-emitter-census.test.ts@@ -0,0 +1,413 @@+/**+ * The EXECUTION census over the progress spine (nothing-runs-unwatched, U1).+ *+ * `tests/core/architecture/progress-census.test.ts` is a source census: it+ * reads declarations and asserts that a type which accepts a `Safeguard`+ * also accepts a `ProgressSink`. That is the half its author could see,+ * and it is genuinely half. A declared sink proves an options interface+ * has a field; it proves nothing about whether any caller ever passes one,+ * so an operation can declare the whole spine - the field, the counter,+ * the terminator - and still be unreachable from every surface an+ * operator has. That is exactly what `search vector-backfill` was.+ *+ * The obvious repair - "every member of `OPERATION` must have an entry+ * point that can attach a sink" - does not catch it. `vector-backfill`+ * emits under `OPERATION.reindex`, so `o2b search index --progress`+ * satisfies that rule on the operation's behalf while the backfill itself+ * stays dark. The unobservable unit is not an operation. It is an+ * EMITTER: one `progressCounter(` call site.+ *+ * So this census is not a scan. It DRIVES each entry point for real, with+ * progress on, against a fixture, and asserts that records carrying the+ * expected operation and stage actually arrived and that the stream was+ * terminated. Three properties follow, and they are why it is worth the+ * seconds it costs:+ *+ * 1. **No false positives.** A record either reached stderr or it did+ * not. There is no pattern to match and therefore nothing to match+ * wrongly.+ * 2. **No syntactic bypass.** The source census has seven known ones+ * (a stage hoisted into a bare `const`, a `type` alias instead of an+ * `interface`, a required rather than optional safeguard, a sink+ * aliased through an indexed access, a heritage clause it cannot+ * resolve, a counter it cannot recognise as one, a generic+ * constraint that steers the block matcher). None of them can+ * change what arrives on a stream.+ * 3. **It tests what the operator gets**, not the shape of a+ * declaration.+ *+ * The declaration is {@link EMITTERS}: every `progressCounter(` call site+ * in `src/`, named by its file and enclosing function, mapped to the entry+ * point that reaches it and the (operation, stage) witness that proves it+ * ran. The population is enumerated from the source, so a new emitter+ * cannot be added without appearing here - and a call site with no entry+ * point named is a failure, which is the whole point of the file.+ *+ * ## What this census CANNOT see+ *+ * - **A site the map reaches by the wrong route.** The witness is the+ * (entry point, operation, stage) triple, so two sites that shared one+ * would be indistinguishable. That is why {@link uniqueWitnesses}+ * exists: a duplicate triple is a failure rather than a blind spot.+ * - **Two emitters inside one function.** The enumeration names a site+ * by its enclosing top-level `function`, so a second+ * `progressCounter(` in the same body would collapse onto the same+ * key. Also a failure, for the same reason.+ * - **An emitter reached only under conditions the fixture does not+ * create** - a provider-backed embed batch, a lock contended by a+ * second process. The fixture drives the DEFAULT path of each verb;+ * a stage that only opens under load is out of reach here and is+ * covered by the per-verb tests under `tests/cli/`.+ * - **Anything about the RATE of the stream.** A record that arrives+ * only at the very end still counts here; that a run reports while it+ * is still running is what the per-verb tests assert.+ * - **A surface that is not the CLI.** The MCP progress transport has+ * its own tests; an emitter reachable only from there would have to+ * name an entry point this file can drive, and today none does.+ */++import { beforeAll, afterAll, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, relative, resolve } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { PROGRESS_KIND } from "../../src/core/brain/progress.ts";+import { OPERATION, type Operation } from "../../src/core/brain/safeguard.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { progressRecords } from "../helpers/progress-records.ts";+import { runCli, type RunResult } from "../helpers/run-cli.ts";++const SRC = resolve(import.meta.dir, "..", "..", "src");++// ─────────────────────────────────────────────────────────────────────────────+// The population: every `progressCounter(` call site in src/+// ─────────────────────────────────────────────────────────────────────────────++/**+ * Blank every comment body in `source`, preserving length and therefore+ * every offset.+ *+ * A census that matched raw text would count `progressCounter(` inside a+ * docblock as an emitter, and two docblocks in `src/` discuss the counter+ * by name. Blanking rather than deleting keeps the offsets usable for the+ * enclosing-function scan that follows.+ */+function blankComments(source: string): string {+ const out = source.split("");+ let i = 0;+ while (i < source.length) {+ const ch = source[i]!;+ const next = source[i + 1];+ if (ch === "/" && next === "/") {+ while (i < source.length && source[i] !== "\n") out[i++] = " ";+ continue;+ }+ if (ch === "/" && next === "*") {+ out[i++] = " ";+ out[i++] = " ";+ while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) {+ if (source[i] !== "\n") out[i] = " ";+ i++;+ }+ if (i < source.length) {+ out[i++] = " ";+ out[i++] = " ";+ }+ continue;+ }+ if (ch === '"' || ch === "'" || ch === "`") {+ i++;+ while (i < source.length && source[i] !== ch) {+ if (source[i] === "\\") i++;+ i++;+ }+ i++;+ continue;+ }+ i++;+ }+ return out.join("");+}++/** Every `.ts` file under `dir`, recursively. */+function tsFiles(dir: string): ReadonlyArray<string> {+ const out: string[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...tsFiles(full));+ else if (entry.isFile() && entry.name.endsWith(".ts")) out.push(full);+ }+ return out;+}++/**+ * A call site's name: `<path under src/>#<enclosing top-level function>`.+ *+ * Deliberately not a line number. A key that moves whenever a comment+ * above it grows is a key nobody maintains, and the function name is what+ * a reader would look the site up by anyway.+ */+const CALL_RE = /\bprogressCounter\s*\(/g;+const FUNCTION_RE = /^(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s+([A-Za-z0-9_$]+)/gm;++function enumerateCallSites(): ReadonlyArray<string> {+ const sites: string[] = [];+ for (const file of tsFiles(SRC)) {+ const code = blankComments(readFileSync(file, "utf8"));+ const functions: Array<{ at: number; name: string }> = [];+ FUNCTION_RE.lastIndex = 0;+ for (let m = FUNCTION_RE.exec(code); m !== null; m = FUNCTION_RE.exec(code)) {+ functions.push({ at: m.index, name: m[1]! });+ }+ const rel = relative(SRC, file).split("\\").join("/");+ CALL_RE.lastIndex = 0;+ for (let m = CALL_RE.exec(code); m !== null; m = CALL_RE.exec(code)) {+ // The declaration itself is `export function progressCounter(`; the+ // enclosing-function scan already names it, so it is excluded by+ // name rather than by file - an emitter added inside `progress.ts`+ // must still be declared.+ const enclosing = functions.findLast((f) => f.at < m!.index);+ if (enclosing === undefined) {+ sites.push(`${rel}#<top-level@${code.slice(0, m.index).split("\n").length}>`);+ continue;+ }+ if (enclosing.name === "progressCounter") continue;+ sites.push(`${rel}#${enclosing.name}`);+ }+ }+ return sites;+}++// ─────────────────────────────────────────────────────────────────────────────+// The declaration+// ─────────────────────────────────────────────────────────────────────────────++interface EmitterSite {+ /** The entry point that reaches this call site, as an operator types it. */+ readonly entryPoint: string;+ /** The operation every record from this counter names. */+ readonly operation: Operation;+ /**+ * A stage THIS counter opens that no other counter opens on the same+ * entry point's stream. It is the discriminator: `search reindex` also+ * emits `walk`, but it does so through the counter `reindexVault` owns+ * and lends, so `lock` is what proves that counter ran.+ */+ readonly stage: string;+}++const EMITTERS: Readonly<Record<string, EmitterSite>> = Object.freeze({+ "core/brain/architect/scan.ts#scanProject": {+ entryPoint: "o2b brain architect --progress",+ operation: OPERATION.architect,+ stage: "walk",+ },+ "core/brain/architect/generate.ts#generateArchDocs": {+ entryPoint: "o2b brain architect --progress",+ operation: OPERATION.architect,+ stage: "render",+ },+ "core/brain/dream.ts#dream": {+ entryPoint: "o2b brain dream --progress",+ operation: OPERATION.dream,+ stage: "scan",+ },+ "core/brain/link-graph/bridge-discovery.ts#discoverBridges": {+ entryPoint: "o2b brain bridges discover --progress",+ operation: OPERATION.bridges,+ stage: "candidates",+ },+ "core/brain/link-graph/communities.ts#detectCommunities": {+ entryPoint: "o2b brain clusters run --progress",+ operation: OPERATION.clusters,+ stage: "sweep",+ },+ "core/search/indexer.ts#indexInto": {+ entryPoint: "o2b search index --progress",+ operation: OPERATION.reindex,+ stage: "walk",+ },+ "core/search/indexer.ts#reindexVault": {+ entryPoint: "o2b search reindex --progress",+ operation: OPERATION.reindex,+ stage: "lock",+ },+ "core/search/vector-backfill.ts#planVectorBackfill": {+ entryPoint: "o2b search vector-backfill --progress",+ operation: OPERATION.reindex,+ stage: "plan",+ },+});++// ─────────────────────────────────────────────────────────────────────────────+// The fixtures and the drivers+// ─────────────────────────────────────────────────────────────────────────────++let tmp: string;+/** Indexed, interlinked: serves index, reindex, vector-backfill, bridges, clusters. */+let searchVault: string;+/** Bootstrapped with signals to consolidate. */+let dreamVault: string;+let dreamConfig: string;+/** A tiny project tree plus the vault its notes are written into. */+let archProject: string;+let archVault: string;++/**+ * One run of one entry point, with `--progress` on.+ *+ * Every driver is a single in-process CLI invocation, which is what keeps+ * this census cheap enough to leave in the default suite: `runCli`+ * imports `main()` once rather than spawning `bun run` per call.+ */+const ENTRY_POINTS: Readonly<Record<string, () => Promise<RunResult>>> = Object.freeze({+ "o2b search index --progress": () =>+ runCli(["search", "index", "--vault", searchVault, "--progress"]),+ "o2b search reindex --progress": () =>+ runCli(["search", "reindex", "--vault", searchVault, "--progress"]),+ "o2b search vector-backfill --progress": () =>+ runCli(["search", "vector-backfill", "--vault", searchVault, "--progress"]),+ "o2b brain bridges discover --progress": () =>+ runCli(["brain", "bridges", "discover", "--vault", searchVault, "--progress"]),+ "o2b brain clusters run --progress": () =>+ runCli(["brain", "clusters", "run", "--vault", searchVault, "--progress"]),+ "o2b brain dream --progress": () =>+ runCli(["brain", "dream", "--dry-run", "--progress"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: dreamConfig },+ }),+ "o2b brain architect --progress": () =>+ runCli(["brain", "architect", archProject, "--vault", archVault, "--progress"]),+});++beforeAll(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-progress-emitter-census-"));++ searchVault = join(tmp, "search-vault");+ mkdirSync(join(searchVault, "Brain"), { recursive: true });+ const group = ["team-a", "team-b", "team-c", "team-d"];+ for (const name of group) {+ const others = group+ .filter((g) => g !== name)+ .map((g) => `[[${g}]]`)+ .join(" ");+ writeFileSync(join(searchVault, `${name}.md`), `# ${name}\n\nCanary rollout. See ${others}.\n`);+ }+ // Built through the CLI rather than through `indexVault` directly, so+ // every driver below sees the index the shipped verb would have left.+ const seeded = await runCli(["search", "index", "--vault", searchVault]);+ expect(seeded.returncode).toBe(0);++ dreamVault = join(tmp, "dream-vault");+ mkdirSync(dreamVault, { recursive: true });+ dreamConfig = join(tmp, "dream-config.yaml");+ atomicWriteFileSync(dreamConfig, `vault: ${dreamVault}\n`);+ bootstrapBrain(dreamVault, { configPath: dreamConfig });+ for (const [i, date] of ["2026-05-20", "2026-05-21", "2026-05-22"].entries()) {+ writeSignal(dreamVault, {+ topic: "census-progress",+ signal: "positive",+ agent: "claude",+ principle: "Prefer the census-progress approach",+ created_at: `${date}T10:00:00Z`,+ date,+ slug: `census-progress-${i}`,+ scope: "writing",+ });+ }++ archProject = join(tmp, "demo-app");+ mkdirSync(join(archProject, "src", "core"), { recursive: true });+ writeFileSync(join(archProject, "package.json"), JSON.stringify({ name: "demo-app" }));+ writeFileSync(join(archProject, "src", "core", "engine.ts"), "// x\n");+ archVault = join(tmp, "arch-vault");+ mkdirSync(join(archVault, "Brain"), { recursive: true });+});++afterAll(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** The witness triple, as one string, for the uniqueness rule. */+function uniqueWitnesses(): ReadonlyArray<string> {+ return Object.values(EMITTERS).map((s) => `${s.entryPoint}|${s.operation}|${s.stage}`);+}++/** First non-empty line of a stream, for a failure message. */+function firstLine(text: string): string {+ return text.split("\n").find((line) => line.trim() !== "") ?? "(no output)";+}++describe("progress emitter census", () => {+ test("every progressCounter call site in src/ is declared, exactly once", () => {+ const found = enumerateCallSites();+ // A second emitter in one function collapses onto one key, and the+ // census would then prove one of them and vouch for both.+ expect(found.toSorted()).toEqual([...new Set(found)].toSorted());+ expect(found.toSorted()).toEqual(Object.keys(EMITTERS).toSorted());+ });++ test("every declared entry point is drivable, and every driver is claimed", () => {+ const drivable = new Set(Object.keys(ENTRY_POINTS));+ for (const [site, decl] of Object.entries(EMITTERS)) {+ expect(`${site} -> ${decl.entryPoint} drivable: ${drivable.has(decl.entryPoint)}`).toBe(+ `${site} -> ${decl.entryPoint} drivable: true`,+ );+ }+ // No declared surface with no producer: an entry point nothing claims+ // is a driver that proves nothing and costs a CLI run.+ const claimed = new Set(Object.values(EMITTERS).map((s) => s.entryPoint));+ expect([...drivable].toSorted().filter((name) => !claimed.has(name))).toEqual([]);+ // The witness must discriminate, or two sites share one proof.+ const witnesses = uniqueWitnesses();+ expect(witnesses.toSorted()).toEqual([...new Set(witnesses)].toSorted());+ });++ test("driving each entry point delivers the stream its call sites promise", async () => {+ const streams = new Map<string, ReadonlyArray<Record<string, unknown>>>();+ const failures: string[] = [];++ // Sequential, not concurrent: `runCli` runs in-process and swaps+ // process-wide state, so two overlapping runs corrupt each other.+ for (const [name, drive] of Object.entries(ENTRY_POINTS)) {+ // oxlint-disable-next-line no-await-in-loop+ const run = await drive();+ if (run.returncode !== 0) {+ failures.push(`${name}: exited ${run.returncode} - ${firstLine(run.stderr)}`);+ continue;+ }+ const records = progressRecords(run.stderr);+ streams.set(name, records);+ if (records.length === 0) {+ failures.push(`${name}: exited 0 and wrote no progress record at all`);+ continue;+ }+ // A stream that simply stops arriving is the shape of a finished+ // run, a crashed run and a hung run at once, so the terminator is+ // as much of the contract as the ticks are.+ const terminators = records.filter(+ (r) => r["kind"] === PROGRESS_KIND.finished || r["kind"] === PROGRESS_KIND.stopped,+ );+ if (terminators.length !== 1) {+ failures.push(`${name}: ${terminators.length} terminator(s) for one run, expected 1`);+ } else if (records.at(-1) !== terminators[0]) {+ failures.push(`${name}: records arrived after the terminator`);+ }+ }++ for (const [site, decl] of Object.entries(EMITTERS)) {+ const records = streams.get(decl.entryPoint) ?? [];+ const witnessed = records.some(+ (r) => r["operation"] === decl.operation && r["stage"] === decl.stage,+ );+ if (!witnessed) {+ failures.push(+ `${site}: no ${decl.operation}/${decl.stage} record arrived from \`${decl.entryPoint}\``,+ );+ }+ }++ expect(failures).toEqual([]);+ });+});diff --git a/tests/cli/progress-rail.test.ts b/tests/cli/progress-rail.test.tsnew file mode 100644index 00000000..c7e43eea--- /dev/null+++ b/tests/cli/progress-rail.test.ts@@ -0,0 +1,134 @@+/**+ * The progress rail, and the fact it rests on.+ *+ * The rail refuses to write progress for a command whose streams are+ * buffered for the whole run, because a line there would be invisible+ * until completion and then dumped at once - which reads as though it had+ * worked. That refusal is only correct while `withJsonFallback` really+ * does patch stderr as well as stdout. The last test asserts it, so the+ * rail's reasoning cannot quietly become false.+ */++import { describe, expect, test } from "bun:test";++import {+ attachProgress,+ isProgressOutcome,+ PROGRESS_OUTCOME,+ PROGRESS_OUTCOMES,+ progressIsLegal,+ renderProgressLine,+} from "../../src/cli/progress-rail.ts";+import { advisoryIsLegal } from "../../src/cli/advisory-rail.ts";+import { COMMANDS_WITH_INTERNAL_JSON, withJsonFallback } from "../../src/cli/json-helpers.ts";+import { PROGRESS_KIND, PROGRESS_REASON, PROGRESS_SCHEMA } from "../../src/core/brain/progress.ts";+import { OPERATION } from "../../src/core/brain/safeguard.ts";++const EVENT = Object.freeze({+ schema: PROGRESS_SCHEMA,+ operation: OPERATION.dream,+ kind: PROGRESS_KIND.advanced,+ stage: "scan",+ completed: 3,+} as const);++describe("progress legality", () => {+ test("a human run is always observable", () => {+ expect(progressIsLegal({ command: "brain", argv: ["dream"], jsonRequested: false })).toBe(true);+ expect(progressIsLegal({ command: "vault", argv: ["map"], jsonRequested: false })).toBe(true);+ });++ test("a JSON run of a command that owns its own JSON is observable", () => {+ // `brain` and `search` render their own payloads, so `main` never+ // wraps them and stderr flows straight through. Both long-operation+ // families live there, which is what makes the rail useful at all.+ expect(COMMANDS_WITH_INTERNAL_JSON.has("brain")).toBe(true);+ expect(COMMANDS_WITH_INTERNAL_JSON.has("search")).toBe(true);+ expect(progressIsLegal({ command: "brain", argv: ["dream"], jsonRequested: true })).toBe(true);+ });++ test("a JSON run of a wrapped command is refused, not buffered", () => {+ const attached = attachProgress({+ command: "cron-recipe",+ argv: [],+ jsonRequested: true,+ });+ expect(attached.outcome).toBe(PROGRESS_OUTCOME.suppressedBufferedStream);+ expect(attached.sink).toBeUndefined();+ expect(attached.reason).toBe(PROGRESS_REASON.streamBuffered);+ });++ test("the outcome vocabulary is complete and guarded", () => {+ expect(PROGRESS_OUTCOMES.toSorted()).toEqual(Object.values(PROGRESS_OUTCOME).toSorted());+ for (const outcome of PROGRESS_OUTCOMES) expect(isProgressOutcome(outcome)).toBe(true);+ expect(isProgressOutcome("emitted ")).toBe(false);+ });+});++describe("progress rendering", () => {+ test("one newline-delimited record per event, schema included", () => {+ const line = renderProgressLine(EVENT);+ expect(line.endsWith("\n")).toBe(true);+ expect(line.split("\n")).toHaveLength(2);+ expect(JSON.parse(line)).toEqual({ ...EVENT });+ });++ test("the sink writes exactly the rendered line", () => {+ const written: string[] = [];+ const attached = attachProgress(+ { command: "brain", argv: ["dream"], jsonRequested: false },+ (chunk) => written.push(chunk),+ );+ attached.sink?.(EVENT);+ expect(written).toEqual([renderProgressLine(EVENT)]);+ });++ test("an event kind this build does not know is a defect, not a dropped line", () => {+ const attached = attachProgress({ command: "brain", argv: ["dream"], jsonRequested: false });+ expect(() => attached.sink?.({ ...EVENT, kind: "flying" as never })).toThrow(/unknown event/);+ });+});++describe("the fact the refusal rests on", () => {+ test("withJsonFallback buffers stderr, not only stdout", async () => {+ // If this ever stops holding, the rail's refusal becomes needlessly+ // strict and its docblock becomes wrong. Asserting it here is what+ // keeps the reasoning honest rather than historical.+ const seen: string[] = [];+ const realStderr = process.stderr.write.bind(process.stderr);+ const realStdout = process.stdout.write.bind(process.stdout);+ try {+ await withJsonFallback("cron-recipe", async () => {+ process.stderr.write("during-the-run\n");+ // Captured, not printed: the accumulator is installed by the+ // wrapper, so this write does not reach the real stream.+ seen.push(process.stderr.write === realStderr ? "unpatched" : "patched");+ return 0;+ });+ } finally {+ process.stderr.write = realStderr;+ process.stdout.write = realStdout;+ }+ expect(seen).toEqual(["patched"]);+ });++ test("under --json the two rails are opposites, and that is the point", () => {+ // One wrapper decides both, in opposite directions. Where it is+ // installed, stdout is accumulated - which makes an advisory line+ // harmless and a progress line worthless, because progress is only+ // worth anything while the operation is still running. So the same+ // buffering that legalises one surface disqualifies the other, and a+ // reader comparing the two rails should see that rather than assume+ // one of them has the predicate backwards.+ for (const command of ["brain", "search", "cron-recipe", "vault", "explorer"]) {+ const stream = { command, argv: [] as ReadonlyArray<string>, jsonRequested: true };+ expect(progressIsLegal(stream)).toBe(!advisoryIsLegal(stream));+ }+ // Without --json neither wrapper nor payload exists, so both allow.+ for (const command of ["brain", "cron-recipe"]) {+ const stream = { command, argv: [] as ReadonlyArray<string>, jsonRequested: false };+ expect(progressIsLegal(stream)).toBe(true);+ expect(advisoryIsLegal(stream)).toBe(true);+ }+ });+});diff --git a/tests/cli/progress-report.test.ts b/tests/cli/progress-report.test.tsnew file mode 100644index 00000000..b076faca--- /dev/null+++ b/tests/cli/progress-report.test.ts@@ -0,0 +1,134 @@+/**+ * The two things a long verb says about its own observation, written+ * once instead of once per verb (nothing-runs-unwatched, U1 + U3).+ *+ * Six verbs attach the progress rail, and the two whose operation yields+ * to the event loop also listen for an interrupt. Both facts they report -+ * "you asked to watch and the stream cannot carry it" and "the operator+ * stopped this run" - are single facts with a single wording, so they live+ * beside the mechanisms that produce them rather than being retyped at+ * each call site.+ *+ * The handles below name `reindex` because `onInterrupt` refuses any+ * operation that cannot observe a signal; the reporting arm under test is+ * the same one for every verb that reaches it.+ *+ * Neither is reachable through `o2b brain ...` or `o2b search ...`: both+ * families own their own JSON, so `main` never wraps them and the rail is+ * never refused there. That is precisely why these arms need a test of+ * their own - a copy per verb would be five untested branches, and the+ * refusal arm is what a SIXTH caller on a wrapped command would hit.+ */++import { describe, expect, test } from "bun:test";++import { EXIT_INTERRUPTED, onInterrupt, reportInterrupted } from "../../src/cli/interrupt.ts";+import {+ attachProgress,+ PROGRESS_OUTCOME,+ reportProgressRefusal,+} from "../../src/cli/progress-rail.ts";+import { PROGRESS_REASON } from "../../src/core/brain/progress.ts";+import { OPERATION, SafeguardAbortError } from "../../src/core/brain/safeguard.ts";++/** Run `body` with both output streams captured. */+function captured(body: () => void): { stdout: string; stderr: string } {+ let stdout = "";+ let stderr = "";+ const realOut = process.stdout.write.bind(process.stdout);+ const realErr = process.stderr.write.bind(process.stderr);+ process.stdout.write = ((chunk: unknown) => {+ stdout += String(chunk);+ return true;+ }) as typeof process.stdout.write;+ process.stderr.write = ((chunk: unknown) => {+ stderr += String(chunk);+ return true;+ }) as typeof process.stderr.write;+ try {+ body();+ } finally {+ process.stdout.write = realOut;+ process.stderr.write = realErr;+ }+ return { stdout, stderr };+}++describe("a refused rail", () => {+ test("is reported by name, not passed over in silence", () => {+ const written: string[] = [];+ // `cron-recipe` is wrapped by `withJsonFallback` under `--json`, which+ // accumulates BOTH streams for the whole run - so the rail refuses+ // rather than write a line nobody would see until the end.+ const attached = attachProgress({ command: "cron-recipe", argv: [], jsonRequested: true });+ expect(attached.outcome).toBe(PROGRESS_OUTCOME.suppressedBufferedStream);++ reportProgressRefusal(attached, (chunk) => written.push(chunk));+ const line = written.join("");+ expect(line).toContain(PROGRESS_REASON.streamBuffered);+ expect(line.endsWith("\n")).toBe(true);+ });++ test("says nothing when the rail attached, and nothing when nobody asked", () => {+ const written: string[] = [];+ const push = (chunk: string): void => {+ written.push(chunk);+ };+ reportProgressRefusal(+ attachProgress({ command: "brain", argv: ["bridges"], jsonRequested: true }, () => {}),+ push,+ );+ // `null` is the shape a verb holds when `--progress` was not passed.+ // There is no refusal to report, and inventing one would be noise.+ reportProgressRefusal(null, push);+ expect(written).toEqual([]);+ });++ test("is unreachable from the two families that emit progress, and that is the claim", () => {+ // `PROGRESS_OUTCOME.suppressedBufferedStream` documents itself as+ // having no shipped producer. That is a claim about these two+ // commands, so it is asserted rather than described: a verb outside+ // `brain`/`search` growing `--progress` makes the refusal reachable,+ // and the docblock that says otherwise must fail on the same day.+ for (const command of ["brain", "search"]) {+ for (const jsonRequested of [true, false]) {+ expect(attachProgress({ command, argv: [], jsonRequested }, () => {}).outcome).toBe(+ PROGRESS_OUTCOME.emitted,+ );+ }+ }+ });+});++describe("an interrupted run", () => {+ test("exits with the shell's signal convention rather than success", () => {+ const handle = onInterrupt(OPERATION.reindex);+ try {+ const out = captured(() =>+ expect(reportInterrupted(handle, new SafeguardAbortError("bridges"), false)).toBe(+ EXIT_INTERRUPTED,+ ),+ );+ expect(EXIT_INTERRUPTED).not.toBe(0);+ expect(out.stderr).toContain("bridges");+ // The human arm owns stderr only: a line on stdout would land in+ // the middle of the payload the verb had already begun writing.+ expect(out.stdout).toBe("");+ } finally {+ handle.release();+ }+ });++ test("hands a --json caller a parseable refusal instead of a bare stream", () => {+ const handle = onInterrupt(OPERATION.reindex);+ try {+ const out = captured(() => {+ reportInterrupted(handle, new SafeguardAbortError("clusters"), true);+ });+ expect(JSON.parse(out.stdout)).toMatchObject({ ok: false, interrupted: true });+ expect(out.stderr).toBe("");+ } finally {+ handle.release();+ }+ });+});diff --git a/tests/cli/run-cli-helper.test.ts b/tests/cli/run-cli-helper.test.tsindex 82fcc550..b5a40758 100644--- a/tests/cli/run-cli-helper.test.ts+++ b/tests/cli/run-cli-helper.test.ts@@ -8,13 +8,16 @@* error at the call site that caused it.*/-import { expect, test } from "bun:test";+import { expect, setDefaultTimeout, test } from "bun:test";import { mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";import { ConcurrentInProcessRunError, runCli } from "../helpers/run-cli.ts";+setDefaultTimeout(CLI_SPAWN_BUDGET_MS);+test("a second in-process run refuses while the first is still open", async () => {const first = runCli(["--help"]);await expect(runCli(["--help"])).rejects.toThrow(ConcurrentInProcessRunError);diff --git a/tests/cli/search-index-progress.test.ts b/tests/cli/search-index-progress.test.tsnew file mode 100644index 00000000..1e014f08--- /dev/null+++ b/tests/cli/search-index-progress.test.ts@@ -0,0 +1,150 @@+/**+ * `o2b search index` and `o2b search reindex` under observation+ * (nothing-runs-unwatched, U1 + U3).+ *+ * These two carry a second, older stream: `--verbose` writes one+ * tab-separated line per file. The two answer different questions -+ * `onFile` says WHAT happened to each file, progress says HOW FAR the run+ * has got - and they share stderr, so the test that matters most here is+ * that adding one did not move the other by a byte.+ */++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 { OPERATION } from "../../src/core/brain/safeguard.ts";+import { progressRecords, STAGE_IDENTIFIER } from "../helpers/progress-records.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++/** Everything on stderr that is NOT a progress record. */+function nonProgressLines(stderr: string): ReadonlyArray<string> {+ return stderr.split("\n").filter((line) => !line.startsWith(`{"schema":"o2b.progress`));+}++function args(verb: string, ...rest: string[]): string[] {+ return ["search", verb, "--vault", vault, "--db", join(tmp, "index.sqlite"), ...rest];+}++/**+ * A run report with its wall-clock field removed, so two runs can be+ * compared for equality without pretending a duration is stable.+ */+function reportWithoutTiming(stdout: string): unknown {+ const parsed = JSON.parse(stdout) as { duration_ms?: number };+ delete parsed.duration_ms;+ return parsed;+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-index-progress-"));+ vault = join(tmp, "vault");+ mkdirSync(vault, { recursive: true });+ for (const name of ["alpha", "beta", "gamma"]) {+ writeFileSync(join(vault, `${name}.md`), `# ${name}\n\nBody text for ${name}.\n`);+ }+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("o2b search index --progress", () => {+ test("writes records to stderr and leaves stdout untouched", async () => {+ const plain = await runCli(args("index", "--json"));+ rmSync(join(tmp, "index.sqlite"), { force: true });+ const watched = await runCli(args("index", "--json", "--progress"));++ expect(plain.returncode).toBe(0);+ expect(watched.returncode).toBe(0);+ expect(reportWithoutTiming(watched.stdout)).toEqual(reportWithoutTiming(plain.stdout));++ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ expect(records.every((r) => r["operation"] === OPERATION.reindex)).toBe(true);+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });++ test("integers and identifiers only - no prose on the structured stream", async () => {+ const watched = await runCli(args("index", "--progress"));+ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ for (const record of records) {+ expect(String(record["stage"])).toMatch(STAGE_IDENTIFIER);+ expect(Number.isInteger(record["completed"])).toBe(true);+ // The walk consumes a generator, so it has no denominator to+ // report and must not invent one.+ expect(record["total"]).toBeUndefined();+ }+ });++ test("the --verbose file stream is unchanged by this unit", async () => {+ const verbose = await runCli(args("index", "--verbose"));+ rmSync(join(tmp, "index.sqlite"), { force: true });+ const both = await runCli(args("index", "--verbose", "--progress"));++ expect(verbose.returncode).toBe(0);+ expect(both.returncode).toBe(0);+ // Same lines, same order, same text: `--progress` is additive on this+ // stream, never a rewrite of the one that was already there.+ expect(nonProgressLines(both.stderr)).toEqual(verbose.stderr.split("\n"));+ expect(verbose.stderr).toContain("added\t");+ expect(progressRecords(verbose.stderr)).toHaveLength(0);+ expect(progressRecords(both.stderr).length).toBeGreaterThan(0);+ });+});++describe("o2b search reindex --progress", () => {+ test("writes records to stderr and leaves stdout untouched", async () => {+ const plain = await runCli(args("reindex", "--json"));+ const watched = await runCli(args("reindex", "--json", "--progress"));++ expect(plain.returncode).toBe(0);+ expect(watched.returncode).toBe(0);++ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ expect(records.every((r) => r["operation"] === OPERATION.reindex)).toBe(true);+ for (const record of records) {+ expect(String(record["stage"])).toMatch(STAGE_IDENTIFIER);+ }+ expect(progressRecords(plain.stderr)).toHaveLength(0);+ });++ test("does not report finished until after the swap that makes the rebuild real", async () => {+ // A rebuild is not over when its build is: `indexVault` used to own+ // the counter and terminate it when the STAGING database was+ // complete, while the two renames that put it live happened+ // afterwards, outside any counter. A caller tailing the stream read+ // `finished` for a rebuild that was not yet the index anyone would+ // read - and if the rename then failed (ENOSPC, EPERM, a cross-device+ // `dbPath`) the command exited non-zero after a terminator that said+ // the run had finished.+ const watched = await runCli(args("reindex", "--progress"));+ expect(watched.returncode).toBe(0);+ const records = progressRecords(watched.stderr);++ const kinds = records.map((r) => String(r["kind"]));+ const stages = records.map((r) => String(r["stage"]));+ expect(kinds.at(-1)).toBe("finished");+ // Exactly one terminator, and the swap is on the near side of it.+ expect(kinds.filter((k) => k === "finished" || k === "stopped")).toHaveLength(1);+ // The swap is COUNTED before the run is terminated: an `advanced` on+ // the swap stage, then the terminator. (The terminator names `swap`+ // too, because it closes the stage that was open.)+ const swapDone = records.findIndex(+ (r) => r["stage"] === "swap" && r["kind"] === "advanced" && r["completed"] === 1,+ );+ expect(swapDone).toBeGreaterThanOrEqual(0);+ expect(swapDone).toBeLessThan(kinds.length - 1);++ // And the wait for the writer lock is no longer silent: it can be the+ // length of a competing rebuild, which is the state this release+ // calls indistinguishable from a hang.+ expect(stages[0]).toBe("lock");+ });+});diff --git a/tests/cli/search-query-flag-manifest.test.ts b/tests/cli/search-query-flag-manifest.test.tsindex b8924418..858558a9 100644--- a/tests/cli/search-query-flag-manifest.test.ts+++ b/tests/cli/search-query-flag-manifest.test.ts@@ -76,6 +76,18 @@ const COVERED: ReadonlyArray<CoveredVerb> = Object.freeze([minFlags: 5,witness: ["no-probe", "boolean"],},+ {+ // Added with `--progress` (nothing-runs-unwatched, U1): this verb+ // grew the whole progress spine in core - an options field, a+ // counter, a terminator - with no flag to reach it, so the wiring+ // was unreachable from every surface an operator has. The flag is+ // the reach, and an undeclared flag on this family is no reach at all.+ verb: "vector-backfill",+ source: "vector-backfill.ts",+ marker: "export async function cmdSearchVectorBackfill",+ minFlags: 6,+ witness: ["progress", "boolean"],+ },]);/**diff --git a/tests/cli/search-vector-backfill.test.ts b/tests/cli/search-vector-backfill.test.tsindex b9181d8a..b750e54e 100644--- a/tests/cli/search-vector-backfill.test.ts+++ b/tests/cli/search-vector-backfill.test.ts@@ -20,11 +20,14 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { PROGRESS_KIND, PROGRESS_REASON } from "../../src/core/brain/progress.ts";+import { OPERATION, SafeguardAbortError } from "../../src/core/brain/safeguard.ts";import { indexVault } from "../../src/core/search/indexer.ts";import { planVectorBackfill } from "../../src/core/search/vector-backfill.ts";import { SEMANTIC_CAPABILITY_TIER } from "../../src/core/search/capability-tier.ts";import { createTempVault, makeConfig, writeMd } from "../helpers/search-fixtures.ts";import { startFakeHttp, type FakeHttp } from "../helpers/fake-http.ts";+import { progressRecords, STAGE_IDENTIFIER } from "../helpers/progress-records.ts";import { sqliteVecLoadable } from "../helpers/sqlite-vec.ts";import { runCli } from "../helpers/run-cli.ts";@@ -326,6 +329,79 @@ test.skipIf(!VEC_LOADABLE || RUNNING_AS_ROOT)(},);+/**+ * `--progress` on this verb (nothing-runs-unwatched, U1 + U3).+ *+ * That a stream ARRIVES at all is asserted once, for every emitter in the+ * tree, by `tests/cli/progress-emitter-census.test.ts`; repeating it here+ * would be a seventh copy of one assertion. What lives here is what the+ * census cannot see: that the payload a caller parses does not move+ * because someone asked to watch, that nobody is watching unless they+ * ask, and that the cancellation seam this verb now passes a signal+ * through actually stops the run.+ */+test.skipIf(!VEC_LOADABLE)(+ "--progress is additive: stdout is byte-identical, and silent without the flag",+ async () => {+ await indexWithoutVectors();+ const args = ["search", "vector-backfill", "--vault", vault, "--db", dbPath, "--json"];++ const plain = await runCli(args);+ const watched = await runCli([...args, "--progress"]);++ expect(plain.returncode).toBe(0);+ expect(watched.returncode).toBe(0);+ // A dry run reads and counts; two runs over one index report the same+ // numbers, so the payloads are comparable byte for byte.+ expect(watched.stdout).toBe(plain.stdout);++ expect(progressRecords(plain.stderr)).toHaveLength(0);+ const records = progressRecords(watched.stderr);+ expect(records.length).toBeGreaterThan(0);+ expect(records.every((r) => r["operation"] === OPERATION.reindex)).toBe(true);+ for (const record of records) {+ expect(String(record["stage"])).toMatch(STAGE_IDENTIFIER);+ expect(Number.isInteger(record["completed"])).toBe(true);+ }+ },+);++test.skipIf(!VEC_LOADABLE)(+ "an aborted signal stops the run at a batch boundary and says so on the stream",+ async () => {+ await indexWithoutVectors();++ // Proved against the core rather than by racing a real SIGINT, for the+ // reason `brain-architect-progress.test.ts` gives: the fixture's+ // embedding phase finishes in milliseconds, so a test that pressed+ // Ctrl-C at the right moment would be a lottery. What the CLI adds on+ // top of this is one line - `signal: interrupt.signal` - and the arm+ // that turns the throw into an exit code.+ const controller = new AbortController();+ controller.abort();+ const events: Array<{ kind: string; stage: string; reason?: string }> = [];++ let thrown: unknown = null;+ try {+ await planVectorBackfill(semanticConfig(), {+ apply: true,+ signal: controller.signal,+ onProgress: (e) =>+ events.push({ kind: e.kind, stage: e.stage, ...(e.reason ? { reason: e.reason } : {}) }),+ });+ } catch (err) {+ thrown = err;+ }++ expect(thrown).toBeInstanceOf(SafeguardAbortError);+ // A cancelled run is not a crash and not a success: the stream names+ // which, rather than simply ceasing to arrive.+ const last = events.at(-1);+ expect(last?.kind).toBe(PROGRESS_KIND.stopped);+ expect(last?.reason).toBe(PROGRESS_REASON.aborted);+ },+);+test("a temp directory is never the real vault", () => {// Guard on the fixtures themselves: every path this file writes to is// created under the OS temp root by `createTempVault`.diff --git a/tests/core/architecture/progress-census.test.ts b/tests/core/architecture/progress-census.test.tsnew file mode 100644index 00000000..478d42cb--- /dev/null+++ b/tests/core/architecture/progress-census.test.ts@@ -0,0 +1,1281 @@+/**+ * Census over the long operations, and what they say while they run.+ *+ * The previous release's whole argument was that a mechanism which must+ * be called by hand is a mechanism that will be missed, and that the+ * answer is declaration plus a census. This is that census for the+ * progress spine, built on the same syntactic technique the write-site+ * and destructive-site censuses use: enumerate the population from the+ * source rather than from a hand-kept list, and fail when a member+ * appears without a declaration.+ *+ * The population is defined by the repository's own statement of what is+ * long: an options type that accepts a `Safeguard` is a type for an+ * operation someone already judged worth guarding with a deadline, and an+ * operation worth a deadline is an operation worth reporting on. So the+ * rule is: **a type that takes a safeguard takes a progress sink, or+ * carries a written reason why it cannot.**+ *+ * Two further rules keep the stream honest rather than merely present:+ *+ * - every stage handed to the counter is an IDENTIFIER, not prose. The+ * event shape cannot enforce this in the type system, so it is+ * enforced here - the same reason the advisory rail refuses+ * caller-supplied sentences rather than documenting that it would+ * prefer not to receive them. Every route a stage can travel is read:+ * an inline literal, a bare `const`, a frozen object, a `stage:`+ * field on a hand-built event - and an argument that resolves to none+ * of those is REPORTED, because "I could not tell" is not a pass.+ * - the sink type is synchronous. Four of the five operations are+ * synchronous functions and cannot await one; a `Promise`-returning+ * sink would compile and then silently drop every event's completion.+ * Read through aliases and through both member forms, and asserted+ * against `ProgressSink` itself, which is the shortest route to an+ * awaited event.+ *+ * ## Why this file lexes instead of matching lines+ *+ * The first version of this census was a handful of regexes over raw+ * source, and four independent reviewers walked past it with a positive+ * control each. A required `safeguard` escaped, because the file filter+ * was the literal string `safeguard?:`. A `type X = { … }` alias escaped,+ * because only `interface` was enumerated. A `Promise`-returning sink+ * split over three lines escaped, because the sync rule read one line at+ * a time. Three emitters that hoist their stage into a bare `const`+ * escaped both stage rules, so a stage reading `"Scanning candidate+ * pairs, please wait..."` was reported clean. And a generic constraint+ * containing a brace did not merely hide a violation - it made the block+ * matcher read the wrong body, which is worse than a miss, because a+ * mis-parse reports a fact about a block that was never examined.+ *+ * So the population is now read from a lexed view of each module rather+ * than from its raw text. {@link lex} blanks comment bodies and string,+ * template and regex CONTENTS while preserving every offset, so brace+ * matching cannot be steered by a `"{"` in a string or by a commented-out+ * member, and a rule that needs the literal value reads it back out of+ * the original text at the same offset. On top of that view sit three+ * small parsers - one for declarations (`interface`, `class` and `type`+ * alike, with generic constraints skipped rather than walked into), one+ * for object members, and one for the string constants a stage can be+ * named by.+ *+ * This project has one runtime dependency and no TypeScript AST, so a+ * real parser is out. What is in reach is a lexer that is CORRECT about+ * the two things a census gets wrong - what is code and where a block+ * ends - and that is what this is.+ *+ * ## What it still does not see, stated rather than implied+ *+ * - a heritage clause this tree cannot resolve: `extends` and `&` are+ * followed into declarations found in this tree (same file first,+ * then a uniquely-named one anywhere in `src/`), so a shape that+ * inherits its safeguard is enumerated - but a base imported from a+ * dependency, or one computed by `Omit<…>`, resolves to the whole+ * base rather than to the mapped result.+ * - a sink whose asynchrony is more than one alias deep. The type text+ * of an `onProgress` member is expanded through named aliases and+ * indexed accesses to a bounded depth; a chain longer than that is+ * read as declared.+ * - a counter it cannot recognise as one. A receiver is a counter when+ * it was bound from `progressCounter(…)`, was declared a+ * `ProgressCounter`, or is named for one; a counter arriving as an+ * un-annotated parameter under a third name is invisible.+ * - whether a declared `onProgress` is ever READ. This census is about+ * declaration; the CLI progress tests are what prove a sink attached+ * to a verb reaches the operation and produces records.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync, readdirSync } from "node:fs";+import { join, relative, sep } from "node:path";++const SRC_ROOT = join(import.meta.dir, "..", "..", "..", "src");++/** Directories with no operation code in them. */+const SKIP_DIRS: ReadonlySet<string> = new Set(["node_modules"]);++/**+ * Interfaces that take a safeguard and deliberately take no sink.+ *+ * A written reason per entry, on the pattern the write-site census uses:+ * an exemption a reader cannot reconstruct is indistinguishable from an+ * oversight. Keep this list short; an entry here is a claim that the+ * operation genuinely has nothing to report, not that wiring it was+ * inconvenient.+ */+const DECLARED_EXEMPTIONS: ReadonlyMap<string, string> = new Map<string, string>([+ [+ "EmbeddingPhaseOptions",+ "A PHASE, not a run: called from indexInto and standalone by the vector backfill. Given a sink it would build a second counter, and a stream carrying two terminators cannot say which one ended the run - so it borrows the run owner's ProgressCounter instead, which is strictly more wiring than a sink, not less.",+ ],+]);++/** A stage name, or a value on a frozen stage object, must look like this. */+const STAGE_IDENTIFIER = /^[a-z0-9]+([-_][a-z0-9]+)*$/;++/** Constants whose values are stage names by their own name. */+const STAGE_CONSTANT = /(?:^|_)STAGES?$/;++// ---------------------------------------------------------------------------+// Lexing+// ---------------------------------------------------------------------------++/** Characters after which a `/` opens a regex rather than divides. */+const REGEX_PRECEDING: ReadonlySet<string> = new Set([+ "",+ "(",+ ",",+ "=",+ ":",+ "[",+ "!",+ "&",+ "|",+ "?",+ "{",+ "}",+ ";",+ "+",+ "-",+ "*",+ "%",+ "~",+ "^",+ "<",+ ">",+]);++/** Keywords after which a `/` opens a regex, e.g. `return /x/.test(s)`. */+const REGEX_PRECEDING_KEYWORDS: ReadonlySet<string> = new Set([+ "return",+ "typeof",+ "instanceof",+ "in",+ "of",+ "case",+ "do",+ "else",+ "yield",+ "await",+ "void",+ "delete",+ "new",+]);++function regexCanStart(text: string, at: number, prev: string): boolean {+ if (REGEX_PRECEDING.has(prev)) return true;+ const before = text.slice(0, at).trimEnd();+ const word = /[A-Za-z_$][\w$]*$/.exec(before);+ return word !== null && REGEX_PRECEDING_KEYWORDS.has(word[0]);+}++/**+ * `text` with comment bodies and string, template and regex CONTENTS+ * replaced by spaces, every other character and every offset preserved.+ *+ * Quotes and delimiters survive so a literal is still recognisable as+ * one; what does not survive is anything a literal could be carrying that+ * a structural scan would otherwise read as syntax. This is the same+ * lexer the destructive-site census runs, for the same reason.+ */+function lex(text: string): string {+ const n = text.length;+ const code = [...text];+ const blank = (from: number, to: number): void => {+ for (let k = Math.max(from, 0); k < Math.min(to, n); k++) {+ if (code[k] !== "\n") code[k] = " ";+ }+ };+ // Top of the stack is the current mode. A template literal pushes+ // `template`; a `${` inside one pushes `code` back on, with its own+ // brace counter, so an interpolated expression is read as code.+ const modes: string[] = ["code"];+ const braces: number[] = [0];+ let prev = "";+ let i = 0;+ while (i < n) {+ const c = text[i]!;+ if (modes[modes.length - 1] === "template") {+ if (c === "\\") {+ blank(i, i + 2);+ i += 2;+ continue;+ }+ if (c === "`") {+ modes.pop();+ prev = "`";+ i += 1;+ continue;+ }+ if (c === "$" && text[i + 1] === "{") {+ modes.push("code");+ braces.push(0);+ prev = "{";+ i += 2;+ continue;+ }+ blank(i, i + 1);+ i += 1;+ continue;+ }+ const next = text[i + 1];+ if (c === "/" && next === "/") {+ let end = text.indexOf("\n", i);+ if (end === -1) end = n;+ blank(i, end);+ i = end;+ continue;+ }+ if (c === "/" && next === "*") {+ const close = text.indexOf("*/", i + 2);+ const end = close === -1 ? n : close + 2;+ blank(i, end);+ i = end;+ continue;+ }+ if (c === '"' || c === "'") {+ let j = i + 1;+ while (j < n && text[j] !== c) j += text[j] === "\\" ? 2 : 1;+ blank(i + 1, j);+ prev = c;+ i = j + 1;+ continue;+ }+ if (c === "`") {+ modes.push("template");+ i += 1;+ continue;+ }+ if (c === "/" && regexCanStart(text, i, prev)) {+ let j = i + 1;+ let inClass = false;+ while (j < n) {+ const e = text[j]!;+ if (e === "\\") {+ j += 2;+ continue;+ }+ if (e === "\n") break;+ if (e === "[") inClass = true;+ else if (e === "]") inClass = false;+ else if (e === "/" && !inClass) break;+ j += 1;+ }+ blank(i + 1, j);+ prev = "/";+ i = j + 1;+ continue;+ }+ if (c === "{") {+ braces[braces.length - 1]! += 1;+ } else if (c === "}") {+ if (braces[braces.length - 1] === 0 && modes.length > 1) {+ modes.pop();+ braces.pop();+ prev = "}";+ i += 1;+ continue;+ }+ braces[braces.length - 1]! -= 1;+ }+ if (!/\s/.test(c)) prev = c;+ i += 1;+ }+ return code.join("");+}++/**+ * Bracket depth before each character, counting `{}`, `()` and `[]` only.+ *+ * Angle brackets are deliberately absent: `<` is a comparison as often as+ * it is a type argument, and a depth map that counted `i < n` would be+ * wrong for the rest of the file. The two places generics actually matter+ * - an interface header and a type alias's left side - scan them locally,+ * where the text is types and nothing else.+ */+function depths(code: string): ReadonlyArray<number> {+ const out: number[] = Array.from<number>({ length: code.length + 1 });+ let d = 0;+ for (let i = 0; i < code.length; i++) {+ out[i] = d;+ const c = code[i]!;+ if (c === "{" || c === "(" || c === "[") d += 1;+ else if (c === "}" || c === ")" || c === "]") d = Math.max(0, d - 1);+ }+ out[code.length] = d;+ return out;+}++/** Index just past the `}` closing the block opened at `open`. */+function closeBrace(code: string, open: number): number {+ let depth = 0;+ for (let i = open; i < code.length; i++) {+ if (code[i] === "{") depth += 1;+ else if (code[i] === "}") {+ depth -= 1;+ if (depth === 0) return i;+ }+ }+ return code.length;+}++// ---------------------------------------------------------------------------+// Declarations+// ---------------------------------------------------------------------------++interface Declaration {+ readonly name: string;+ readonly file: string;+ /** `interface X { … }` / `class X { … }`, or `type X = …`. */+ readonly kind: "interface" | "alias";+ /** The block body, or the alias's right-hand side. */+ readonly body: string;+ /** Names in an `extends` clause, or referenced by the alias. */+ readonly references: ReadonlyArray<string>;+}++/**+ * Scans a type-only region forward to `stop`, skipping generic argument+ * lists whole. Returns the index of the first `stop` character seen at+ * generic depth zero, or `-1`.+ *+ * This is the fix for the mis-parse a reviewer reproduced: the old header+ * regex ended at `[^{]*`, so `interface X<T extends { k: string }>` began+ * brace matching inside the CONSTRAINT and read `k: string` as the body+ * of a block whose real members were never examined.+ */+function scanTypeHeader(code: string, from: number, stop: string): number {+ let angle = 0;+ for (let i = from; i < code.length; i++) {+ const c = code[i]!;+ if (c === "<") angle += 1;+ else if (c === ">") {+ // `=>` inside a constraint is an arrow, not a closing bracket.+ if (code[i - 1] !== "=" && angle > 0) angle -= 1;+ } else if (angle > 0 && c === "{") i = closeBrace(code, i);+ else if (angle === 0 && stop.includes(c)) return i;+ }+ return -1;+}++/**+ * Index of the first character after a declaration's name and its type+ * parameter list, whitespace skipped.+ *+ * What comes back is how a DECLARATION is told apart from a mention. A+ * type-only import written `import { type ProgressSink }` puts the two+ * keywords side by side exactly as a declaration does, and reading it as+ * one made the census attribute a nearby frozen object to the sink type.+ * A declaration is followed by `=`, by `{`, or by `extends`; a mention is+ * followed by a comma or a brace that closes the import.+ */+function skipTypeParameters(code: string, from: number): number {+ let i = from;+ while (i < code.length && /\s/.test(code[i] ?? "")) i += 1;+ if (code[i] === "<") {+ let angle = 0;+ for (; i < code.length; i++) {+ const c = code[i]!;+ if (c === "<") angle += 1;+ else if (c === ">" && code[i - 1] !== "=") {+ angle -= 1;+ if (angle === 0) {+ i += 1;+ break;+ }+ } else if (angle > 0 && c === "{") i = closeBrace(code, i);+ }+ while (i < code.length && /\s/.test(code[i] ?? "")) i += 1;+ }+ return i;+}++/** Capitalised names a heritage clause or alias body refers to. */+function referencedNames(text: string): ReadonlyArray<string> {+ return [...text.matchAll(/\b([A-Z][\w$]*)\b/g)].map((m) => m[1] ?? "");+}++/** Every `interface X { … }` and `type X = …` declared in `code`. */+function declarations(+ code: string,+ file: string,+ d: ReadonlyArray<number>,+): ReadonlyArray<Declaration> {+ const out: Declaration[] = [];+ const header =+ /\b(?:export\s+)?(?:default\s+)?(?:declare\s+)?(?:abstract\s+)?(interface|class|type)\s+([A-Za-z_$][\w$]*)/g;+ for (const match of code.matchAll(header)) {+ const kind = match[1];+ const name = match[2] ?? "";+ const after = (match.index ?? 0) + match[0].length;+ const tail = skipTypeParameters(code, after);+ if (kind === "interface" || kind === "class") {+ const heritage =+ code[tail] === "{" || /^(?:extends|implements)\b/.test(code.slice(tail, tail + 10));+ if (!heritage) continue;+ const open = scanTypeHeader(code, tail, "{");+ if (open === -1) continue;+ const close = closeBrace(code, open);+ out.push({+ name,+ file,+ kind: "interface",+ body: code.slice(open + 1, close),+ references: referencedNames(code.slice(tail, open)),+ });+ continue;+ }+ if (code[tail] !== "=") continue;+ const assign = tail;+ let end = assign + 1;+ while (end < code.length && !(d[end] === d[assign + 1] && code[end] === ";")) end += 1;+ const body = code.slice(assign + 1, end);+ out.push({ name, file, kind: "alias", body, references: referencedNames(body) });+ }+ return out;+}++/**+ * The regions of a declaration whose members belong to the declaration+ * itself.+ *+ * An interface body is one region. An alias can have several, because+ * `Readonly<{ … }>` and `{ … } & { … }` are both ways of writing one+ * options object, and a census that only understood a bare `{ … }` would+ * be answered by wrapping it.+ */+function memberRegions(body: string, kind: Declaration["kind"]): ReadonlyArray<string> {+ if (kind === "interface") return [body];+ const out: string[] = [];+ let i = 0;+ while (i < body.length) {+ if (body[i] === "{") {+ const close = closeBrace(body, i);+ out.push(body.slice(i + 1, close));+ i = close + 1;+ continue;+ }+ i += 1;+ }+ return out;+}++/**+ * The type text that follows `at`, to the member's terminator.+ *+ * A member ends at a `;` or `,` at depth zero, or at a newline that is+ * not continuing an expression - the last clause is what makes a sink+ * written across three lines one declaration rather than three.+ */+function typeText(body: string, d: ReadonlyArray<number>, at: number, stopAtBrace = false): string {+ let i = at;+ while (i < body.length) {+ const c = body[i]!;+ if (d[i] === 0 && (c === ";" || c === ",")) break;+ // A method signature in a CLASS is followed by its body; the return+ // type ends where that body opens.+ if (stopAtBrace && d[i] === 0 && c === "{") break;+ if (d[i] === 0 && c === "\n") {+ const soFar = body.slice(at, i).trim();+ if (soFar !== "" && !/[|&,?:]$|=>$/.test(soFar)) break;+ }+ i += 1;+ }+ return body.slice(at, i).trim();+}++/**+ * Member name to declared type text, for members at the top level of a+ * block or an object type. A nested member cannot satisfy the rule for+ * the shape that contains it, so depth zero is the whole filter.+ *+ * Both member forms are read. `onProgress?: (e) => void` is the idiom+ * this tree uses, but `onProgress(e): void` declares the same thing, and+ * a census that knew only the first would report the second as a shape+ * with no sink at all - a false alarm, which is the failure mode a census+ * does not survive twice.+ */+function objectMembers(body: string): ReadonlyMap<string, string> {+ const out = new Map<string, string>();+ const d = depths(body);+ const method =+ /(?:(?:public|private|protected|static|abstract|override)\s+)*(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\(/g;+ for (const match of body.matchAll(method)) {+ const start = match.index ?? 0;+ if (d[start] !== 0) continue;+ const before = body.slice(0, start).trimEnd();+ const prev = before.at(-1) ?? "";+ if (prev !== "" && !";,{}".includes(prev)) continue;+ const openParen = start + match[0].length - 1;+ let close = openParen + 1;+ while (close < body.length && !(body[close] === ")" && d[close] === 1)) close += 1;+ let after = close + 1;+ while (after < body.length && /\s/.test(body[after] ?? "")) after += 1;+ if (body[after] !== ":") continue;+ out.set(match[1] ?? "", typeText(body, d, after + 1, true));+ }+ const member =+ /(?:(?:public|private|protected|static|abstract|override)\s+)*(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:/g;+ for (const match of body.matchAll(member)) {+ const start = match.index ?? 0;+ if (d[start] !== 0) continue;+ const before = body.slice(0, start).trimEnd();+ const prev = before.at(-1) ?? "";+ if (prev !== "" && !";,{}&|(".includes(prev)) continue;+ out.set(match[1] ?? "", typeText(body, d, start + match[0].length));+ }+ return out;+}++// ---------------------------------------------------------------------------+// Constants a stage can be named by+// ---------------------------------------------------------------------------++interface Constants {+ /** `const X = "literal"`. */+ readonly bare: ReadonlyMap<string, string>;+ /** `const X = Object.freeze({ k: "literal" })`, and `{ … } as const`. */+ readonly objects: ReadonlyMap<string, ReadonlyMap<string, string>>;+}++/**+ * The string constants declared in one module.+ *+ * Both shapes are here because both are in this tree: three emitters+ * hoist a bare `const BRIDGE_STAGE = "candidates"` and three hoist a+ * frozen object. The old census read the second shape and not the first,+ * which is how a stage reading like a sentence passed it.+ */+function constants(text: string, code: string): Constants {+ const bare = new Map<string, string>();+ const objects = new Map<string, ReadonlyMap<string, string>>();+ const decl = /\b(?:export\s+)?const\s+([A-Za-z_$][\w$]*)\s*(?::[^=]*)?=\s*/g;+ for (const match of code.matchAll(decl)) {+ const name = match[1] ?? "";+ const at = (match.index ?? 0) + match[0].length;+ const quote = code[at];+ if (quote === '"' || quote === "'") {+ const end = code.indexOf(quote, at + 1);+ if (end !== -1) bare.set(name, text.slice(at + 1, end));+ continue;+ }+ const frozen = /^Object\.freeze\(\s*\{/.exec(code.slice(at, at + 24));+ const open = frozen !== null ? at + frozen[0].length - 1 : code[at] === "{" ? at : -1;+ if (open === -1) continue;+ const close = closeBrace(code, open);+ const block = code.slice(open + 1, close);+ const values = new Map<string, string>();+ const entry = /([A-Za-z_$][\w$]*)\s*:\s*(["'])/g;+ for (const pair of block.matchAll(entry)) {+ const from = open + 1 + (pair.index ?? 0) + pair[0].length;+ const end = code.indexOf(pair[2] ?? '"', from);+ if (end !== -1) values.set(pair[1] ?? "", text.slice(from, end));+ }+ objects.set(name, values);+ }+ return { bare, objects };+}++/**+ * Names in this module that hold a {@link ProgressCounter}.+ *+ * A counter is usually called `progress`, and reading the receiver by+ * convention would be a census that a rename escapes. So the binding is+ * read instead: whatever `progressCounter(…)` was assigned to, and+ * whatever was declared as a `ProgressCounter`, is a counter here - and+ * the naming convention stays in the set as well, for the receivers a+ * module takes from a caller it does not name.+ */+function counterBindings(code: string): ReadonlySet<string> {+ const out = new Set<string>();+ const bound = /\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=]*)?=\s*progressCounter\s*\(/g;+ for (const match of code.matchAll(bound)) out.add(match[1] ?? "");+ const typed = /\b([A-Za-z_$][\w$]*)\s*\??\s*:\s*(?:readonly\s+)?ProgressCounter\b/g;+ for (const match of code.matchAll(typed)) out.add(match[1] ?? "");+ return out;+}++// ---------------------------------------------------------------------------+// The tree under census+// ---------------------------------------------------------------------------++interface CensusFile {+ readonly path: string;+ readonly text: string;+}++interface CensusSource extends CensusFile {+ readonly code: string;+ readonly nesting: ReadonlyArray<number>;+ readonly decls: ReadonlyArray<Declaration>;+ readonly consts: Constants;+ readonly counters: ReadonlySet<string>;+}++/** One lex per module, kept, because the fixtures below re-run the tree. */+const ANALYZED = new Map<string, CensusSource>();++function analyze(files: ReadonlyArray<CensusFile>): ReadonlyArray<CensusSource> {+ return files.map((file) => {+ const cached = ANALYZED.get(file.path);+ if (cached !== undefined && cached.text === file.text) return cached;+ const code = lex(file.text);+ const nesting = depths(code);+ const source: CensusSource = {+ ...file,+ code,+ nesting,+ decls: declarations(code, file.path, nesting),+ consts: constants(file.text, code),+ counters: counterBindings(code),+ };+ ANALYZED.set(file.path, source);+ return source;+ });+}++/** Every `.ts` file under `src/`, in a stable order. */+function readSourceTree(dir: string = SRC_ROOT): CensusFile[] {+ const out: CensusFile[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>+ a.name < b.name ? -1 : 1,+ )) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) {+ if (SKIP_DIRS.has(entry.name)) continue;+ out.push(...readSourceTree(full));+ } else if (entry.isFile() && entry.name.endsWith(".ts")) {+ out.push({+ path: relative(SRC_ROOT, full).split(sep).join("/"),+ text: readFileSync(full, "utf8"),+ });+ }+ }+ return out;+}++// ---------------------------------------------------------------------------+// Rule 1: a type that takes a safeguard takes a sink+// ---------------------------------------------------------------------------++/** Declarations by name, same file first, then a unique one anywhere. */+function resolver(+ sources: ReadonlyArray<CensusSource>,+): (name: string, file: string) => ReadonlyArray<Declaration> {+ const byName = new Map<string, Declaration[]>();+ for (const source of sources) {+ for (const decl of source.decls) {+ const bucket = byName.get(decl.name) ?? [];+ bucket.push(decl);+ byName.set(decl.name, bucket);+ }+ }+ return (name, file) => {+ const all = byName.get(name) ?? [];+ // Declaration merging: two `interface X` in one module are one type.+ const local = all.filter((d) => d.file === file);+ if (local.length > 0) return local;+ // Cross-module, only when the name is unambiguous in the tree.+ const files = new Set(all.map((d) => d.file));+ return files.size === 1 ? all : [];+ };+}++type Resolve = ReturnType<typeof resolver>;++/**+ * Members of `decl`, plus the members of everything it extends or+ * intersects that this tree can resolve. Bounded, so a cyclic heritage+ * clause cannot hang the census.+ */+function effectiveMembers(+ decl: Declaration,+ resolve: Resolve,+ seen: Set<string> = new Set(),+): ReadonlyMap<string, string> {+ const key = `${decl.file}#${decl.name}#${decl.kind}`;+ const out = new Map<string, string>();+ if (seen.has(key) || seen.size > 16) return out;+ seen.add(key);+ for (const region of memberRegions(decl.body, decl.kind)) {+ for (const [name, type] of objectMembers(region)) out.set(name, type);+ }+ for (const reference of decl.references) {+ for (const parent of resolve(reference, decl.file)) {+ for (const [name, type] of effectiveMembers(parent, resolve, seen)) {+ if (!out.has(name)) out.set(name, type);+ }+ }+ }+ return out;+}++interface SafeguardRow {+ readonly id: string;+ readonly name: string;+ readonly file: string;+ readonly hasSink: boolean;+}++/**+ * Every declared shape that carries a `safeguard` member, optional or+ * required, declared or inherited.+ *+ * The member NAME is the whole test. Requiring the type to spell+ * `Safeguard` would drop `DreamStageOptions`, which types its field as+ * `DreamOptions["safeguard"]`, and a census that reads a type expression+ * is a census that can be evaded by writing a different one.+ */+function safeguardedShapes(sources: ReadonlyArray<CensusSource>): ReadonlyArray<SafeguardRow> {+ const resolve = resolver(sources);+ const out: SafeguardRow[] = [];+ for (const source of sources) {+ // Two `interface X` in one module are ONE type - the language merges+ // them - so the census reads them merged. A rule that read them apart+ // would report a violation against a type that does not exist.+ const merged = new Map<string, Declaration[]>();+ for (const decl of source.decls) {+ merged.set(decl.name, [...(merged.get(decl.name) ?? []), decl]);+ }+ for (const [name, group] of merged) {+ const members = new Map<string, string>();+ for (const decl of group) {+ for (const [member, type] of effectiveMembers(decl, resolve)) {+ if (!members.has(member)) members.set(member, type);+ }+ }+ if (!members.has("safeguard")) continue;+ out.push({+ id: `${source.path}: ${name}`,+ name,+ file: source.path,+ hasSink: members.has("onProgress"),+ });+ }+ }+ return out;+}++/**+ * Files that declare a `readonly safeguard` member, found without the+ * parser.+ *+ * This is the parser's own alarm. `readonly` appears in a type+ * declaration and nowhere else - not in an object literal, not in a+ * parameter list - so every file it matches must contribute at least one+ * row to the population above. A parser that stops finding blocks, or+ * reads the wrong one, goes quiet rather than red; this is what makes it+ * red.+ */+function filesDeclaringSafeguard(sources: ReadonlyArray<CensusSource>): ReadonlyArray<string> {+ return sources+ .filter((source) => /\breadonly\s+safeguard\s*\??\s*:/.test(source.code))+ .map((source) => source.path);+}++// ---------------------------------------------------------------------------+// Rule 2: no stage is prose+// ---------------------------------------------------------------------------++/** Offsets of the first argument of the call whose `(` is at `open`. */+function firstArgument(+ code: string,+ d: ReadonlyArray<number>,+ open: number,+): readonly [number, number] {+ const base = d[open + 1] ?? 0;+ let i = open + 1;+ while (i < code.length) {+ const c = code[i]!;+ if ((d[i] ?? 0) < base) break;+ if ((d[i] ?? 0) === base && (c === "," || c === ")")) break;+ i += 1;+ }+ let from = open + 1;+ while (from < i && /\s/.test(code[from] ?? "")) from += 1;+ let to = i;+ while (to > from && /\s/.test(code[to - 1] ?? "")) to -= 1;+ return [from, to];+}++/**+ * Every stage a counter is handed, resolved to its literal value.+ *+ * An argument this cannot resolve is reported rather than skipped. That+ * is the difference between a census and a sample: a stage computed at+ * run time is exactly the shape that would carry a caller's sentence onto+ * the stream, and "I could not tell" is not a pass.+ */+function proseStages(sources: ReadonlyArray<CensusSource>): ReadonlyArray<string> {+ const offenders: string[] = [];+ const globalBare = new Map<string, string>();+ const globalObjects = new Map<string, ReadonlyMap<string, string>>();+ for (const source of sources) {+ for (const [name, value] of source.consts.bare) globalBare.set(name, value);+ for (const [name, values] of source.consts.objects) globalObjects.set(name, values);+ }++ for (const source of sources) {+ // A constant named for stages must hold stage names, whether or not+ // any call site was found to hand one over.+ for (const [name, value] of source.consts.bare) {+ if (!STAGE_CONSTANT.test(name)) continue;+ if (!STAGE_IDENTIFIER.test(value)) {+ offenders.push(`${source.path}: ${name} = ${JSON.stringify(value)}`);+ }+ }+ for (const [name, values] of source.consts.objects) {+ if (!STAGE_CONSTANT.test(name)) continue;+ for (const [key, value] of values) {+ if (!STAGE_IDENTIFIER.test(value)) {+ offenders.push(`${source.path}: ${name}.${key} = ${JSON.stringify(value)}`);+ }+ }+ }++ // A hand-built event carries a stage too. Only in the modules that+ // know the progress schema, so an unrelated module's `stage:` field+ // is not conscripted into this vocabulary.+ if (source.code.includes("PROGRESS_SCHEMA")) {+ for (const match of source.code.matchAll(/\bstage\s*:\s*"/g)) {+ const from = (match.index ?? 0) + match[0].length;+ const end = source.code.indexOf('"', from);+ const value = source.text.slice(from, end === -1 ? from : end);+ if (!STAGE_IDENTIFIER.test(value)) {+ offenders.push(`${source.path}: stage: ${JSON.stringify(value)}`);+ }+ }+ }++ const call = /\b([A-Za-z_$][\w$]*)\s*(?:\?\.|\.)\s*(start|advance)\s*\(/g;+ for (const match of source.code.matchAll(call)) {+ const receiver = match[1] ?? "";+ if (!/progress|counter/i.test(receiver) && !source.counters.has(receiver)) continue;+ const open = (match.index ?? 0) + match[0].length - 1;+ const [from, to] = firstArgument(source.code, source.nesting, open);+ const argument = source.code.slice(from, to);+ // The lexer blanked the contents of a literal, so the site is+ // named from the original text and only READ from the lexed view.+ const site = `${source.path}: ${receiver}.${match[2]}(${source.text.slice(from, to)})`;++ let value: string | undefined;+ if (/^["']/.test(argument) && argument.length >= 2) {+ value = source.text.slice(from + 1, to - 1);+ } else if (/^[A-Za-z_$][\w$]*$/.test(argument)) {+ // A constant imported from elsewhere resolves across the tree; a+ // lower-case name is a local binding, and a local binding that+ // does not resolve HERE is a stage this census cannot read.+ value =+ source.consts.bare.get(argument) ??+ (/^[A-Z][A-Z0-9_]*$/.test(argument) ? globalBare.get(argument) : undefined);+ } else {+ const member = /^([A-Za-z_$][\w$]*)\.([A-Za-z_$][\w$]*)$/.exec(argument);+ if (member !== null) {+ const holder =+ source.consts.objects.get(member[1] ?? "") ?? globalObjects.get(member[1] ?? "");+ value = holder?.get(member[2] ?? "");+ }+ }+ if (value === undefined) {+ offenders.push(`${site}: stage does not resolve to a literal`);+ continue;+ }+ if (!STAGE_IDENTIFIER.test(value)) offenders.push(`${site} = ${JSON.stringify(value)}`);+ }+ }+ return offenders;+}++// ---------------------------------------------------------------------------+// Rule 3: the sink is synchronous+// ---------------------------------------------------------------------------++/** Expands a type expression through named aliases, to a bounded depth. */+function expandType(type: string, file: string, resolve: Resolve, depth = 0): string {+ if (depth > 3) return type;+ // `import("./progress.ts").ProgressSink` lexes to `import("").Name`.+ const direct = /^(?:import\(\s*["'][^"']*["']\s*\)\.)?([A-Za-z_$][\w$]*)$/.exec(type);+ if (direct !== null) {+ const parts = resolve(direct[1] ?? "", file).map((d) =>+ expandType(d.body.trim(), d.file, resolve, depth + 1),+ );+ return parts.length === 0 ? type : `${type} ${parts.join(" ")}`;+ }+ const indexed = /^([A-Za-z_$][\w$]*)\[\s*["']([^"']*)["']\s*\]$/.exec(type);+ if (indexed !== null) {+ const parts: string[] = [];+ for (const decl of resolve(indexed[1] ?? "", file)) {+ const member = effectiveMembers(decl, resolve).get(indexed[2] ?? "");+ if (member !== undefined) parts.push(expandType(member, decl.file, resolve, depth + 1));+ }+ return parts.length === 0 ? type : `${type} ${parts.join(" ")}`;+ }+ return type;+}++/**+ * Every `onProgress` declaration whose type can carry a promise.+ *+ * Whole declarations, not lines: the reviewer's control split a+ * `Promise`-returning sink over three lines and the line-based rule it+ * replaced never saw the return type. Aliases are expanded too, so+ * `onProgress?: AsyncSink` is read as what `AsyncSink` says it is.+ */+function asyncSinks(sources: ReadonlyArray<CensusSource>): ReadonlyArray<string> {+ const resolve = resolver(sources);+ const offenders: string[] = [];+ for (const source of sources) {+ const d = source.nesting;+ // Both forms: `onProgress?: (e) => T` and `onProgress(e): T`. The+ // second declares the same sink and would otherwise be read as the+ // parameter list it opens with.+ const sites = /\bonProgress\s*(?:\??\s*:|\()/g;+ for (const match of source.code.matchAll(sites)) {+ let from = (match.index ?? 0) + match[0].length;+ const methodForm = match[0].endsWith("(");+ if (methodForm) {+ const openParen = from - 1;+ const inner = (d[openParen] ?? 0) + 1;+ let close = from;+ while (close < source.code.length && !(source.code[close] === ")" && d[close] === inner)) {+ close += 1;+ }+ let after = close + 1;+ while (after < source.code.length && /\s/.test(source.code[after] ?? "")) after += 1;+ if (source.code[after] !== ":") continue;+ from = after + 1;+ }+ const base = d[from] ?? 0;+ let i = from;+ while (i < source.code.length) {+ const c = source.code[i]!;+ if ((d[i] ?? 0) < base) break;+ if ((d[i] ?? 0) === base && (c === ";" || c === ",")) break;+ if (methodForm && (d[i] ?? 0) === base && c === "{") break;+ if ((d[i] ?? 0) === base && c === "\n") {+ const soFar = source.code.slice(from, i).trim();+ if (soFar !== "" && !/[|&,?:]$|=>$/.test(soFar)) break;+ }+ i += 1;+ }+ const declared = source.code.slice(from, i).trim();+ if (/\bPromise\s*</.test(expandType(declared, source.path, resolve))) {+ offenders.push(`${source.path}: onProgress?: ${declared.replace(/\s+/g, " ")}`);+ }+ }+ }+ return offenders;+}++// ---------------------------------------------------------------------------+// The census+// ---------------------------------------------------------------------------++const TREE = readSourceTree();+const SOURCES = analyze(TREE);++describe("progress census", () => {+ test("every options type that takes a safeguard takes a progress sink", () => {+ const population = safeguardedShapes(SOURCES);+ const missing = population+ .filter((row) => !row.hasSink && !DECLARED_EXEMPTIONS.has(row.name))+ .map((row) => row.id);++ // A census that found nothing passes for the wrong reason.+ expect(population.length).toBeGreaterThan(0);+ expect(missing).toEqual([]);+ });++ test("the parser sees every module that declares a safeguard", () => {+ // The alarm on the parser itself: a block matcher that goes wrong+ // reports a clean tree, so the population is cross-checked against a+ // naive search that cannot mis-parse because it does not parse.+ const enumerated = new Set(safeguardedShapes(SOURCES).map((row) => row.file));+ const unseen = filesDeclaringSafeguard(SOURCES).filter((path) => !enumerated.has(path));+ expect(unseen).toEqual([]);+ });++ test("every declared exemption names a type that still exists", () => {+ const declared = new Set(safeguardedShapes(SOURCES).map((row) => row.name));+ const stale = [...DECLARED_EXEMPTIONS.keys()].filter((name) => !declared.has(name));+ expect(stale).toEqual([]);+ });++ test("every exemption carries a reason a reader can act on", () => {+ for (const [name, reason] of DECLARED_EXEMPTIONS) {+ // Long enough to be an argument rather than a label. The+ // destructive-site census uses the same floor for the same reason.+ expect(reason.length).toBeGreaterThanOrEqual(80);+ expect(reason).not.toMatch(/\bTODO\b|\bfor now\b|\blater\b/i);+ expect(name).not.toBe("");+ }+ });++ test("no stage is prose, wherever the emitter keeps it", () => {+ // Identifiers and integers only: the human sentence is rendered at+ // the edge from the identifier. A stage with a space in it would mean+ // a caller had started writing sentences onto a structured stream.+ expect(proseStages(SOURCES)).toEqual([]);+ });++ test("the sink is synchronous everywhere it is declared", () => {+ // Four of the five long operations are synchronous functions. An+ // async sink would typecheck and then drop every event's completion+ // on the floor, which is a silent failure of exactly the kind this+ // spine exists to remove.+ expect(asyncSinks(SOURCES)).toEqual([]);+ });++ test("the sink type itself promises nothing", () => {+ // The rule above reads call sites and members. This reads the one+ // declaration they all point at, so making the SINK async - the+ // shortest route to an awaited event - is not a way through.+ const sink = SOURCES.flatMap((source) => source.decls).filter(+ (decl) => decl.name === "ProgressSink",+ );+ expect(sink.length).toBeGreaterThan(0);+ for (const decl of sink) {+ expect(decl.body).not.toMatch(/\bPromise\s*</);+ expect(decl.body).toMatch(/=>\s*void/);+ }+ });+});++// ---------------------------------------------------------------------------+// The census can fail+// ---------------------------------------------------------------------------++/**+ * Each fixture below is one of the ways a reviewer walked past the+ * previous census, kept as a test so the hole cannot reopen quietly. The+ * shape a fixture is written in is the shape that was reproduced, not a+ * strawman: every one of them was confirmed to PASS the old rules before+ * the new ones were written.+ */+/** Only the intruder's own rows, so an unrelated module cannot answer for it. */+function onlyFrom(path: string, lines: ReadonlyArray<string>): ReadonlyArray<string> {+ return lines.filter((line) => line.startsWith(`${path}:`));+}++describe("the census can fail", () => {+ // The intruder joins the real tree rather than standing alone, so a+ // fixture proves the rule under the conditions the rule runs in - the+ // name resolution, the constant table, the lot. What each assertion+ // reads back is only the intruder's own rows, so a fixture cannot go+ // green or red because of an unrelated module.+ const intruder = (path: string, text: string): ReadonlyArray<CensusSource> =>+ analyze([...TREE, { path, text }]);++ const sinkless = (path: string, text: string): ReadonlyArray<string> =>+ safeguardedShapes(intruder(path, text))+ .filter((row) => row.file === path && !row.hasSink && !DECLARED_EXEMPTIONS.has(row.name))+ .map((row) => row.id);++ test("a REQUIRED safeguard is in the population too", () => {+ const path = "core/brain/synthetic-required.ts";+ expect(+ sinkless(path, "export interface EvadeRequired {\n readonly safeguard: Safeguard;\n}\n"),+ ).toEqual([`${path}: EvadeRequired`]);+ });++ test("a type alias is in the population too", () => {+ const path = "core/brain/synthetic-alias.ts";+ expect(+ sinkless(path, "export type EvadeAlias = {\n readonly safeguard?: Safeguard;\n};\n"),+ ).toEqual([`${path}: EvadeAlias`]);+ });++ test("a brace in a generic constraint does not move the block", () => {+ const path = "core/brain/synthetic-generic.ts";+ expect(+ sinkless(+ path,+ "export interface EvadeGeneric<T extends { k: string }> {\n readonly seed: T;\n readonly safeguard?: Safeguard;\n}\n",+ ),+ ).toEqual([`${path}: EvadeGeneric`]);+ });++ test("a brace inside a string literal does not move the block", () => {+ const path = "core/brain/synthetic-string-brace.ts";+ expect(+ sinkless(+ path,+ 'export interface EvadeStringBrace {\n readonly opener?: "{";\n readonly safeguard?: Safeguard;\n}\n\nexport interface Unrelated {\n readonly onProgress?: ProgressSink;\n}\n',+ ),+ ).toEqual([`${path}: EvadeStringBrace`]);+ });++ test("a commented-out sink is not a sink", () => {+ const path = "core/brain/synthetic-comment.ts";+ expect(+ sinkless(+ path,+ "export interface EvadeComment {\n readonly safeguard?: Safeguard;\n // readonly onProgress?: ProgressSink;\n}\n",+ ),+ ).toEqual([`${path}: EvadeComment`]);+ });++ test("an inherited safeguard puts the heir in the population", () => {+ const path = "core/brain/synthetic-extends.ts";+ expect(+ sinkless(+ path,+ "interface SyntheticGuarded {\n readonly safeguard?: Safeguard;\n}\n\nexport interface EvadeExtends extends SyntheticGuarded {\n readonly limit?: number;\n}\n",+ ),+ ).toEqual([`${path}: SyntheticGuarded`, `${path}: EvadeExtends`]);+ });++ test("an inherited sink satisfies the rule, so the census does not cry wolf", () => {+ const path = "core/brain/synthetic-inherited-sink.ts";+ expect(+ sinkless(+ path,+ "interface SyntheticWatched {\n readonly safeguard?: Safeguard;\n readonly onProgress?: ProgressSink;\n}\n\nexport interface HeirOptions extends SyntheticWatched {\n readonly limit?: number;\n}\n",+ ),+ ).toEqual([]);+ });++ test("a class that holds a safeguard is in the population too", () => {+ // An operation implemented as an object rather than a function is+ // still an operation, and `readonly safeguard` reads the same in a+ // class body as in an interface - so the naive cross-check would see+ // it whether or not the parser did.+ const path = "core/brain/synthetic-runner.ts";+ const text =+ "export class SyntheticRunner {\n" ++ " private readonly safeguard?: Safeguard;\n" ++ " run(): void {\n this.safeguard?.checkpoint();\n }\n}\n";+ expect(sinkless(path, text)).toEqual([`${path}: SyntheticRunner`]);+ });++ test("declaration merging is one type, not a violation", () => {+ const path = "core/brain/synthetic-merged.ts";+ expect(+ sinkless(+ path,+ "export interface MergedOptions {\n readonly safeguard?: Safeguard;\n}\n\nexport interface MergedOptions {\n readonly onProgress?: ProgressSink;\n}\n",+ ),+ ).toEqual([]);+ });++ test("a wrapper and an intersection are read through", () => {+ const path = "core/brain/synthetic-wrapped.ts";+ expect(+ sinkless(+ path,+ "export type EvadeWrapped = Readonly<{\n safeguard?: Safeguard;\n}>;\n\nexport type EvadeIntersected = { readonly limit?: number } & {\n readonly safeguard?: Safeguard;\n};\n",+ ),+ ).toEqual([`${path}: EvadeWrapped`, `${path}: EvadeIntersected`]);+ });++ test("a module the parser cannot read is reported, not skipped", () => {+ // The population and the naive search must agree. A block matcher+ // that walks off the end of a file goes quiet; this is the alarm.+ const path = "core/brain/synthetic-unparsed.ts";+ const sources = intruder(+ path,+ "export interface Broken {\n readonly safeguard?: Safeguard;\n",+ );+ const enumerated = new Set(safeguardedShapes(sources).map((row) => row.file));+ expect(filesDeclaringSafeguard(sources).filter((p) => !enumerated.has(p))).toEqual([]);+ // …and the unterminated block is still in the population, because+ // the matcher runs to the end of the file rather than giving up.+ expect(enumerated.has(path)).toBe(true);+ });++ test("a bare stage constant carrying prose is caught", () => {+ const path = "core/brain/synthetic-bare-stage.ts";+ const text =+ 'const SYNTHETIC_STAGE = "Scanning candidate pairs, please wait...";\n' ++ "export function run(): void {\n progress.start(SYNTHETIC_STAGE);\n}\n";+ expect(onlyFrom(path, proseStages(intruder(path, text)))).toEqual([+ `${path}: SYNTHETIC_STAGE = "Scanning candidate pairs, please wait..."`,+ `${path}: progress.start(SYNTHETIC_STAGE) = "Scanning candidate pairs, please wait..."`,+ ]);+ });++ test("a frozen stage object carrying prose is caught", () => {+ const path = "core/brain/synthetic-frozen-stage.ts";+ const text =+ 'const SYNTHETIC_STAGE = Object.freeze({ sweep: "Propagating labels ACROSS the graph" } as const);\n' ++ "export function run(): void {\n progress.advance(SYNTHETIC_STAGE.sweep);\n}\n";+ expect(onlyFrom(path, proseStages(intruder(path, text)))).toEqual([+ `${path}: SYNTHETIC_STAGE.sweep = "Propagating labels ACROSS the graph"`,+ `${path}: progress.advance(SYNTHETIC_STAGE.sweep) = "Propagating labels ACROSS the graph"`,+ ]);+ });++ test("an inline stage literal carrying prose is caught", () => {+ const path = "core/brain/synthetic-inline-stage.ts";+ const text = 'export function run(): void {\n progress.start("Working, please wait");\n}\n';+ expect(onlyFrom(path, proseStages(intruder(path, text)))).toEqual([+ `${path}: progress.start("Working, please wait") = "Working, please wait"`,+ ]);+ });++ test("a stage computed at run time is reported rather than skipped", () => {+ const path = "core/brain/synthetic-dynamic-stage.ts";+ const text = "export function run(label: string): void {\n progress.start(label);\n}\n";+ expect(onlyFrom(path, proseStages(intruder(path, text)))).toEqual([+ `${path}: progress.start(label): stage does not resolve to a literal`,+ ]);+ });++ test("a counter under any other name is still a counter", () => {+ const path = "core/brain/synthetic-renamed-counter.ts";+ const text =+ "export function run(): void {\n" ++ " const ticker = progressCounter(OPERATION.dream, undefined);\n" ++ ' ticker.start("Working away on it");\n' ++ "}\n";+ expect(onlyFrom(path, proseStages(intruder(path, text)))).toEqual([+ `${path}: ticker.start("Working away on it") = "Working away on it"`,+ ]);+ });++ test("a hand-built event carrying prose is caught", () => {+ const path = "core/brain/synthetic-hand-built.ts";+ const text =+ 'export function emit(): void {\n sink({ schema: PROGRESS_SCHEMA, stage: "still working" });\n}\n';+ expect(onlyFrom(path, proseStages(intruder(path, text)))).toEqual([+ `${path}: stage: "still working"`,+ ]);+ });++ test("a multi-line Promise-returning sink is caught", () => {+ const path = "core/brain/synthetic-async-sink.ts";+ const text =+ "export interface EvadeAsync {\n readonly safeguard?: Safeguard;\n readonly onProgress?: (\n event: ProgressEvent,\n ) => Promise<void>;\n}\n";+ expect(onlyFrom(path, asyncSinks(intruder(path, text)))).toEqual([+ `${path}: onProgress?: ( event: ProgressEvent, ) => Promise<void>`,+ ]);+ });++ test("a Promise-returning sink hidden behind an alias is caught", () => {+ const path = "core/brain/synthetic-alias-sink.ts";+ const text =+ "type SyntheticAsyncSink = (event: ProgressEvent) => Promise<void>;\n\nexport interface EvadeAliasSink {\n readonly safeguard?: Safeguard;\n readonly onProgress?: SyntheticAsyncSink;\n}\n";+ expect(onlyFrom(path, asyncSinks(intruder(path, text)))).toEqual([+ `${path}: onProgress?: SyntheticAsyncSink`,+ ]);+ });++ test("a method-form sink is a sink, promise and all", () => {+ const path = "core/brain/synthetic-method-sink.ts";+ const text =+ "export interface EvadeMethodSink {\n readonly safeguard?: Safeguard;\n onProgress(event: ProgressEvent): Promise<void>;\n}\n";+ // Declared, so the shape is not reported as sinkless…+ expect(sinkless(path, text)).toEqual([]);+ // …and the sink it declared is still held to being synchronous.+ expect(onlyFrom(path, asyncSinks(intruder(path, text)))).toEqual([+ `${path}: onProgress?: Promise<void>`,+ ]);+ });++ test("the real sink is not reported, so the rule discriminates", () => {+ const path = "core/brain/synthetic-sync-sink.ts";+ const text =+ 'export interface FineOptions {\n readonly safeguard?: Safeguard;\n readonly onProgress?: import("./progress.ts").ProgressSink;\n}\n';+ expect(onlyFrom(path, asyncSinks(intruder(path, text)))).toEqual([]);+ });+});diff --git a/tests/core/architecture/verdict-vocabulary-census.test.ts b/tests/core/architecture/verdict-vocabulary-census.test.tsindex f6ebc560..759c362d 100644--- a/tests/core/architecture/verdict-vocabulary-census.test.ts+++ b/tests/core/architecture/verdict-vocabulary-census.test.ts@@ -23,9 +23,88 @@* It deliberately does NOT require values to be unique across* vocabularies. An absent config file and an absent store file are both* honestly named `absent`, and forcing them apart would buy nothing.+ *+ * ## The population is READ, not remembered+ *+ * The registry below used to be the whole file: a hand-written list of+ * imports, auditing the vocabularies somebody remembered to add and+ * nothing at all about the ones they did not. A new module carrying a+ * duplicate value, a phantom member and a guard that accepts every+ * string ran clean, because an unregistered vocabulary was invisible.+ * {@link scanVocabularies} closes that: it walks `src/`, finds every+ * vocabulary that carries the FOUR-PIECE shape, and+ * {@link CENSUS} must account for each one.+ *+ * The four pieces, all four required and all four in one module:+ *+ * 1. `const NAME = Object.freeze({ … })` whose every entry is+ * `key: "string literal"`;+ * 2. a union derived from it - `(typeof NAME)[keyof typeof NAME]`;+ * 3. a membership list built from it - a const initialised from+ * `Object.values(NAME)` or from an array of `NAME.member`;+ * 4. a guard: a function or arrow taking a parameter typed `unknown`+ * that reads the membership list or the object.+ *+ * All four, because all four is exactly what {@link auditVocabulary}+ * audits: two of its seven checks ask what the guard accepts, and an+ * object with no guard is one whose values never have to survive the+ * round trip through a string that the guard exists to police.+ * Widening the rule to three pieces would also enrol lists that are+ * curated ORDERINGS rather than membership - `DREAM_STEP_RUNNABLE` (the+ * steps that can be run on their own) and `DREAM_GATE_NAMES` (the gates+ * an operator may override). Both name every member of their object+ * today; the day one of them does not - a step that cannot run alone, a+ * gate that is not overridable - that is a correct divergence, and a+ * census that reported it as drift would be teaching contributors to+ * ignore it. That is also why there is no exemption list here: a+ * construct with all four pieces has nothing to be excused from, and an+ * empty escape hatch is an invitation rather than a policy.+ *+ * ## What the scan cannot see, stated rather than implied+ *+ * It reads text, not a parse tree - this repository has one runtime+ * dependency and no TypeScript AST library - so it masks comments and+ * string CONTENTS before matching (a `"{"` inside a value cannot+ * mis-terminate a body) and then reads brackets. What that still leaves:+ *+ * - A vocabulary SPLIT ACROSS MODULES: object here, membership list or+ * guard there. Detection is per-file, so a split trio is out of+ * population entirely. No vocabulary in this tree is split.+ * - A vocabulary with no membership list or no guard. Two pieces are+ * not the idiom, and there is nothing for the audit to compare -+ * but it is the cheapest way to leave the population, so it is named+ * here rather than left for a reader to discover.+ * - Values that are not literals in the object: a spread of another+ * object, a computed key's value, a value built by a call. Any of+ * these drops the object out of the population.+ * - A guard whose parameter is typed `string`. It is a guard that can+ * only be called once the caller proved what it was asked to prove,+ * and the idiom's own rule is `unknown`.+ * - Trees other than `src/`. `hooks/`, `scripts/` and `plugins/`+ * declare no derived-union vocabulary today; if one appears there it+ * is invisible until this root list grows.+ * - Code inside a `${…}` interpolation: a template literal is blanked+ * whole, so a vocabulary piece written inside one is not read. A+ * template can also legally span lines, which is why the masker's+ * "a quote with no partner on this line is not a string" rule - the+ * rule that keeps a regex literal such as `/["]/` from blanking the+ * rest of a module - applies to `"` and `'` only.+ *+ * The progress census next door reads its population the same way, off a+ * lexed view with offsets preserved, and states its own blind spots in+ * the same place. Two censuses, one technique; the shared lexer they both+ * deserve is a consolidation neither owns alone.+ *+ * Each of those is a shape a future contributor could write. The+ * "the scan sees the shapes it claims to" block below pins the ones it+ * DOES see, one synthetic module per shape - and, in the same block, the+ * frozen objects that must stay OUT - so a scan that quietly stops+ * matching fails by name instead of reporting a smaller population.*/import { describe, expect, test } from "bun:test";+import { readdirSync, readFileSync } from "node:fs";+import { join, relative } from "node:path";import {isSchemaPackIntegrityStatus,@@ -60,7 +139,10 @@ import {SNAPSHOT_STORE_EXCLUSION_REASONS,} from "../../../src/core/brain/manifest.ts";import {+ isSnapshotEntrySkipReason,isSnapshotPruneRefusal,+ SNAPSHOT_ENTRY_SKIP_REASON,+ SNAPSHOT_ENTRY_SKIP_REASONS,SNAPSHOT_PRUNE_REFUSAL,SNAPSHOT_PRUNE_REFUSALS,} from "../../../src/core/brain/snapshot.ts";@@ -182,6 +264,85 @@ import {STUB_SCAFFOLD_ACTION,STUB_SCAFFOLD_ACTIONS,} from "../../../src/mcp/brain/lifecycle-file-tools.ts";+import {+ isSessionAdapterId,+ SESSION_ADAPTER_ID,+ SESSION_ADAPTER_IDS,+} from "../../../src/core/brain/sessions/types.ts";+import {+ isTranscriptScan,+ TRANSCRIPT_SCAN,+ TRANSCRIPT_SCANS,+} from "../../../src/core/discipline/transcripts/types.ts";+import {+ IMPORT_WRITE_MODE,+ IMPORT_WRITE_MODES,+ isImportWriteMode,+} from "../../../src/core/brain/sessions/import.ts";+import {+ EMBEDDING_SUNSET,+ EMBEDDING_SUNSET_SOURCE,+ EMBEDDING_SUNSET_SOURCES,+ EMBEDDING_SUNSET_STATES,+ EMBEDDING_SUNSET_UNDETERMINED_REASON,+ EMBEDDING_SUNSET_UNDETERMINED_REASONS,+ isEmbeddingSunsetSource,+ isEmbeddingSunsetState,+ isEmbeddingSunsetUndeterminedReason,+} from "../../../src/core/search/embeddings/sunset.ts";+import {+ isVaultBackingState,+ isVaultBackingUndeterminedReason,+ VAULT_BACKING,+ VAULT_BACKING_STATES,+ VAULT_BACKING_UNDETERMINED_REASON,+ VAULT_BACKING_UNDETERMINED_REASONS,+} from "../../../src/core/vault-backing.ts";+import {+ isSelfHealReindexOutcome,+ isSelfHealSpawnDecision,+ SELF_HEAL_REINDEX_OUTCOME,+ SELF_HEAL_REINDEX_OUTCOMES,+ SELF_HEAL_SPAWN,+ SELF_HEAL_SPAWN_DECISIONS,+} from "../../../src/core/maintenance/self-heal-reindex.ts";+import {+ isProgressKind,+ isProgressReason,+ PROGRESS_KIND,+ PROGRESS_KINDS,+ PROGRESS_REASON,+ PROGRESS_REASONS,+} from "../../../src/core/brain/progress.ts";+import { isOperation, OPERATION, OPERATIONS } from "../../../src/core/brain/safeguard.ts";+import {+ isTokenCountMethod,+ TOKEN_COUNT_METHOD,+ TOKEN_COUNT_METHODS,+} from "../../../src/core/brain/token-impact.ts";+import {+ isRecallFailure,+ RECALL_FAILURE,+ RECALL_FAILURES,+} from "../../../src/core/bench/failure-modes.ts";+import {+ isMaintenanceVerdict,+ MAINTENANCE_VERDICT,+ MAINTENANCE_VERDICTS,+} from "../../../src/core/brain/maintenance/journal.ts";+import {+ isProgressOutcome,+ PROGRESS_OUTCOME,+ PROGRESS_OUTCOMES,+} from "../../../src/cli/progress-rail.ts";+import {+ HOST_PRESSURE,+ HOST_PRESSURE_STATES,+ HOST_PRESSURE_UNMEASURABLE_REASON,+ HOST_PRESSURE_UNMEASURABLE_REASONS,+ isHostPressureState,+ isHostPressureUnmeasurableReason,+} from "../../../src/core/brain/maintenance/host-pressure.ts";interface VocabularyUnderCensus {/** Identifies the vocabulary in a failure message. */@@ -614,8 +775,558 @@ const CENSUS: ReadonlyArray<VocabularyUnderCensus> = Object.freeze([members: STUB_SCAFFOLD_ACTIONS,guard: isStubScaffoldAction,},+ {+ // U10. How a token-impact sample's counts were PRODUCED. Promoted to+ // the idiom when its members were renamed off `exact` / `fallback`:+ // the ledger counts nothing, so labelling a caller's integer exact+ // asserted a property nothing had checked. The guard is the boundary+ // for a value arriving as an untyped MCP argument or read back out of+ // a continuity payload written by an older build.+ name: "TOKEN_COUNT_METHOD",+ values: TOKEN_COUNT_METHOD,+ members: TOKEN_COUNT_METHODS,+ guard: isTokenCountMethod,+ },+ {+ // U10. How one proactive-recall decision failed. `faulted` is the+ // member that earns the vocabulary: a retriever that threw is not a+ // memory that stayed quiet, and a boolean would collapse them - which+ // would let a broken harness report itself as a cautious one. The+ // guard is the boundary for a value read back out of a persisted+ // retrieve-phase result file.+ name: "RECALL_FAILURE",+ values: RECALL_FAILURE,+ members: RECALL_FAILURES,+ guard: isRecallFailure,+ },+ {+ // U1. What one progress tick says happened. `refused` and `stopped`+ // are the members that earn the vocabulary: an operation whose events+ // no transport could carry, and one the operator cancelled, are+ // different facts, and both were previously reported as an absence of+ // progress - which is what a hung run looks like too.+ name: "PROGRESS_KIND",+ values: PROGRESS_KIND,+ members: PROGRESS_KINDS,+ guard: isProgressKind,+ },+ {+ // U1. Why a run stopped short or why its ticks could not be carried.+ // Closed for the same reason the kind is: a reader must branch on it,+ // and a free string would let prose onto a structured surface.+ name: "PROGRESS_REASON",+ values: PROGRESS_REASON,+ members: PROGRESS_REASONS,+ guard: isProgressReason,+ },+ {+ // U1. The operations this repository calls long. It was a bare union+ // owned by the safeguard; the progress spine needed to name the same+ // population, and a second list would have drifted. Registering it+ // here is what stops the two readers - the timeout ladder and the+ // progress event - from disagreeing about what is long.+ name: "OPERATION",+ values: OPERATION,+ members: OPERATIONS,+ guard: isOperation,+ },+ {+ // U5. What the parent did about a reindex it found necessary. The+ // values leave TypeScript into `Brain/metrics/self_heal_reindex.jsonl`,+ // a file that is synced to peer devices and read back by a build that+ // may not be the one that wrote it - so the guard is the boundary+ // between this release and a row it does not understand.+ name: "SELF_HEAL_SPAWN",+ values: SELF_HEAL_SPAWN,+ members: SELF_HEAL_SPAWN_DECISIONS,+ guard: isSelfHealSpawnDecision,+ },+ {+ // U5. Registered separately from the decision above because the two+ // are answered by different processes to different questions - whether+ // a child was started, and what a started child ended as - and one+ // guard over both would let a refusal to start be read back off the+ // same file as a rebuild that finished.+ name: "SELF_HEAL_REINDEX_OUTCOME",+ values: SELF_HEAL_REINDEX_OUTCOME,+ members: SELF_HEAL_REINDEX_OUTCOMES,+ guard: isSelfHealReindexOutcome,+ },+ {+ // A2. What filesystem backs the vault path. `undetermined` is the+ // member that earns the vocabulary: the alternative design classified+ // the HOST as local / cloud sandbox / ephemeral, and every signal that+ // classifier reads is one-way, so a negative container marker would+ // have bought a positive durability verdict on every modern container+ // that does not ship one.+ name: "VAULT_BACKING",+ values: VAULT_BACKING,+ members: VAULT_BACKING_STATES,+ guard: isVaultBackingState,+ },+ {+ // A2. Why the backing probe reached no verdict. Separate from the+ // state for the reason MATERIALIZE_UNKNOWN_REASON is separate from its+ // freshness: one guard over both would let `path_unreadable` be read+ // back off a payload everywhere a survival verdict is expected.+ name: "VAULT_BACKING_UNDETERMINED_REASON",+ values: VAULT_BACKING_UNDETERMINED_REASON,+ members: VAULT_BACKING_UNDETERMINED_REASONS,+ guard: isVaultBackingUndeterminedReason,+ },+ {+ // U7. The runtimes whose session adapters ship in this tree. It was a+ // hand-written string union with a guard taking `string`, which is a+ // guard that can only be called once the caller has already proved+ // what it was asked to prove - and `--format` hands it a raw argv+ // value. The registry it names is keyed by `string` and open to a+ // caller's own adapter; this vocabulary is the closed half, and+ // `tests/core/brain/sessions/adapter-registry.test.ts` locks it to+ // the built-in registry's keys.+ name: "SESSION_ADAPTER_ID",+ values: SESSION_ADAPTER_ID,+ members: SESSION_ADAPTER_IDS,+ guard: isSessionAdapterId,+ },+ {+ // U7. Which emptiness a transcript scan found. `root_absent`,+ // `unreadable` and `idle` were one value - a zero file count - feeding+ // an alert that exists to notice a day with no recorded work, so an+ // unreadable home was read as a confirmed quiet day. The three cannot+ // be one member for the same reason `partial` is not `full`: the+ // middle one is the report failing, not the agent resting.+ name: "TRANSCRIPT_SCAN",+ values: TRANSCRIPT_SCAN,+ members: TRANSCRIPT_SCANS,+ guard: isTranscriptScan,+ },+ {+ // U7. Whether an import result's counters describe writes that happened+ // or writes it would have made. Two members, and the vocabulary earns+ // its place on the pair it separates: `signals_created: 0` was the+ // honest answer for a dry run AND for a real run over a session with+ // nothing in it, so the counters alone could not say which run the+ // operator had just performed.+ name: "IMPORT_WRITE_MODE",+ values: IMPORT_WRITE_MODE,+ members: IMPORT_WRITE_MODES,+ guard: isImportWriteMode,+ },+ {+ // B1. What this build can say about one embedding model's+ // decommission. `unsurveyed` and `none_announced` are separate+ // members and that separation IS the unit: `embedding_model` is a+ // free string with no validation and off-catalog is the normal case,+ // so reporting "no sunset announced" for a model nobody looked up is+ // the misleading silence the check exists to remove.+ name: "EMBEDDING_SUNSET",+ values: EMBEDDING_SUNSET,+ members: EMBEDDING_SUNSET_STATES,+ guard: isEmbeddingSunsetState,+ },+ {+ // B1. Why no sunset verdict was reached. Separate from the state so+ // `survey_stale` - a fact about this build's own table rather than+ // about the model - can never be read back where a verdict belongs.+ name: "EMBEDDING_SUNSET_UNDETERMINED_REASON",+ values: EMBEDDING_SUNSET_UNDETERMINED_REASON,+ members: EMBEDDING_SUNSET_UNDETERMINED_REASONS,+ guard: isEmbeddingSunsetUndeterminedReason,+ },+ {+ // B1. Which layer answered a sunset question - the operator's+ // declaration in `_brain.yaml`, this build's table, or NEITHER. A+ // boolean was the obvious shape and it is wrong: it would have made+ // "the survey answered" and "nothing answered" the same value, which+ // is the collapse this whole check exists to undo.+ name: "EMBEDDING_SUNSET_SOURCE",+ values: EMBEDDING_SUNSET_SOURCE,+ members: EMBEDDING_SUNSET_SOURCES,+ guard: isEmbeddingSunsetSource,+ },+ {+ // U6. What one maintenance-lane journal row records. It was a bare+ // union, and the fourth gate is what made the trio worth having: the+ // rows are persisted as JSONL and read back by whichever build runs+ // next, which after an upgrade is not the build that wrote them.+ // `pressure:unmeasurable` is the member that earns the vocabulary -+ // it is a NOTICE that a gate did not evaluate, emitted beside the+ // decision rather than instead of it, so an operator can tell a host+ // that was quiet from one that could not say.+ name: "MAINTENANCE_VERDICT",+ values: MAINTENANCE_VERDICT,+ members: MAINTENANCE_VERDICTS,+ guard: isMaintenanceVerdict,+ },+ {+ // U6. Whether host pressure is a number or a named absence. Two+ // members, and the pair is the whole unit: `os.loadavg()` returns+ // zero both on an idle host and on the platform that does not+ // implement it, so without this state the gate's "quiet" would have+ // been indistinguishable from its "I cannot see".+ name: "HOST_PRESSURE",+ values: HOST_PRESSURE,+ members: HOST_PRESSURE_STATES,+ guard: isHostPressureState,+ },+ {+ // U6. Which question failed. Separate from the state for the reason+ // every undetermined-reason vocabulary here is separate from its+ // verdict: the value is persisted into a journal row's+ // `pressure_reason`, and one guard over both would let+ // `cpu_quota_in_force` be read back where a load percentage belongs.+ name: "HOST_PRESSURE_UNMEASURABLE_REASON",+ values: HOST_PRESSURE_UNMEASURABLE_REASON,+ members: HOST_PRESSURE_UNMEASURABLE_REASONS,+ guard: isHostPressureUnmeasurableReason,+ },+ {+ // U1. Whether a progress line reached stderr or was refused because+ // the command's streams are buffered for the whole run. It was NOT+ // registered here when it shipped, and the source scan below is how+ // it was found - the first vocabulary this census enrolled because+ // the tree said so rather than because an author remembered.+ name: "PROGRESS_OUTCOME",+ values: PROGRESS_OUTCOME,+ members: PROGRESS_OUTCOMES,+ guard: isProgressOutcome,+ },+ {+ // U6. Why one `.snapshots/` entry could not become a listing row.+ // The second vocabulary the scan enrolled rather than an author: it+ // shipped complete, beside SNAPSHOT_PRUNE_REFUSAL in the same module,+ // and was registered here by nobody.+ name: "SNAPSHOT_ENTRY_SKIP_REASON",+ values: SNAPSHOT_ENTRY_SKIP_REASON,+ members: SNAPSHOT_ENTRY_SKIP_REASONS,+ guard: isSnapshotEntrySkipReason,+ },]);+// ---------------------------------------------------------------------------+// The population, read from `src/`+// ---------------------------------------------------------------------------++const REPO_ROOT = join(import.meta.dir, "..", "..", "..");++/** Roots the scan walks. See the docblock for what living outside costs. */+const SCANNED_ROOTS: ReadonlyArray<string> = Object.freeze(["src"]);++interface SourceFile {+ readonly path: string;+ readonly text: string;+}++function readSourceTree(): SourceFile[] {+ const files: SourceFile[] = [];+ const walk = (dir: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const abs = join(dir, entry.name);+ if (entry.isDirectory()) walk(abs);+ else if (entry.name.endsWith(".ts")) {+ files.push({+ path: relative(REPO_ROOT, abs).split("\\").join("/"),+ text: readFileSync(abs, "utf8"),+ });+ }+ }+ };+ for (const root of SCANNED_ROOTS) walk(join(REPO_ROOT, root));+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ return files;+}++/**+ * The same source with comment bodies and string CONTENTS replaced by+ * spaces, character offsets preserved.+ *+ * Structure is read off the mask and content off the original at the same+ * index. This is what makes bracket matching honest: a `"}"` inside a+ * value cannot close an object, and `// }` in a comment cannot either.+ */+function maskSource(text: string): string {+ const out = text.split("");+ const blank = (from: number, to: number): void => {+ for (let k = from; k < to && k < out.length; k += 1) if (out[k] !== "\n") out[k] = " ";+ };+ let i = 0;+ while (i < text.length) {+ const char = text[i]!;+ const next = text[i + 1];+ if (char === "/" && next === "/") {+ const end = text.indexOf("\n", i);+ const stop = end === -1 ? text.length : end;+ blank(i, stop);+ i = stop;+ continue;+ }+ if (char === "/" && next === "*") {+ const end = text.indexOf("*/", i + 2);+ const stop = end === -1 ? text.length : end + 2;+ blank(i, stop);+ i = stop;+ continue;+ }+ if (char === '"' || char === "'" || char === "`") {+ let k = i + 1;+ while (k < text.length) {+ if (text[k] === "\\") {+ k += 2;+ continue;+ }+ if (text[k] === char) break;+ // A `"` or `'` with no partner before the newline is not a string+ // opener - it is a quote inside a regular expression literal,+ // `/["']/` being the shape that occurs here. Treating it as an+ // opener would blank real code from that point to the next quote+ // ANYWHERE in the file, which is worse than a miss: the scan would+ // report a fact about a module it never read. Only a template can+ // legally span lines.+ if (char !== "`" && text[k] === "\n") {+ k = i;+ break;+ }+ k += 1;+ }+ if (k === i) {+ i += 1;+ continue;+ }+ blank(i + 1, k);+ i = k + 1;+ continue;+ }+ i += 1;+ }+ return out.join("");+}++const CLOSER: Readonly<Record<string, string>> = Object.freeze({+ "{": "}",+ "[": "]",+ "(": ")",+});++/** Index of the bracket closing the one at `open`, or -1. */+function matchBracket(masked: string, open: number): number {+ const opener = masked[open]!;+ const closer = CLOSER[opener]!;+ let depth = 0;+ for (let i = open; i < masked.length; i += 1) {+ const char = masked[i];+ if (char === opener) depth += 1;+ else if (char === closer) {+ depth -= 1;+ if (depth === 0) return i;+ }+ }+ return -1;+}++/** A `const NAME = …` whose initialiser is a bracketed expression. */+interface Binding {+ readonly name: string;+ /** Index of the opening bracket of the initialiser's outermost group. */+ readonly open: number;+ /** Index of its closer. */+ readonly close: number;+ /** `{` for an object literal, `[` for an array, `(` for `Object.freeze(…)`. */+ readonly bracket: string;+}++/**+ * `Object.freeze(` and bare-array bindings. The optional type annotation+ * is matched as "anything up to the `=`" excluding `;` and `=`, which is+ * every annotation in this tree; a function-typed annotation (`() => T`)+ * would hide the binding, and hiding a MEMBERSHIP LIST is the only way+ * that matters - it drops its vocabulary out of the population.+ */+const FROZEN_BINDING_RE =+ /\bconst\s+([A-Za-z_$][\w$]*)\s*(?::[^;=]*)?=\s*Object\s*\.\s*freeze\s*\(/g;+const ARRAY_BINDING_RE = /\bconst\s+([A-Za-z_$][\w$]*)\s*(?::[^;=]*)?=\s*\[/g;++function bindings(masked: string): Binding[] {+ const found: Binding[] = [];+ for (const match of masked.matchAll(FROZEN_BINDING_RE)) {+ const paren = match.index! + match[0].length - 1;+ const close = matchBracket(masked, paren);+ if (close === -1) continue;+ // `Object.freeze({ … })` and `Object.freeze([ … ])` are reported as+ // the literal they wrap; `Object.freeze(Object.values(X))` stays a+ // call, which is a membership list and never an object literal.+ const inner = masked.slice(paren + 1, close);+ const offset = inner.search(/\S/);+ const first = offset === -1 ? "" : inner[offset];+ if (first === "{" || first === "[") {+ const open = paren + 1 + offset;+ const innerClose = matchBracket(masked, open);+ if (innerClose !== -1) {+ found.push({ name: match[1]!, open, close: innerClose, bracket: first });+ continue;+ }+ }+ found.push({ name: match[1]!, open: paren, close, bracket: "(" });+ }+ for (const match of masked.matchAll(ARRAY_BINDING_RE)) {+ const open = match.index! + match[0].length - 1;+ const close = matchBracket(masked, open);+ if (close !== -1) found.push({ name: match[1]!, open, close, bracket: "[" });+ }+ return found;+}++/** Top-level `,`-separated segments of a bracketed body, as index pairs. */+function segments(masked: string, open: number, close: number): Array<readonly [number, number]> {+ const parts: Array<readonly [number, number]> = [];+ let depth = 0;+ let start = open + 1;+ for (let i = open + 1; i < close; i += 1) {+ const char = masked[i];+ if (char === "(" || char === "[" || char === "{") depth += 1;+ else if (char === ")" || char === "]" || char === "}") depth -= 1;+ else if (char === "," && depth === 0) {+ parts.push([start, i]);+ start = i + 1;+ }+ }+ parts.push([start, close]);+ return parts;+}++const ENTRY_RE = /^\s*(?:[A-Za-z_$][\w$]*|"[^"]*"|'[^']*')\s*:\s*(["'])/;++/**+ * The declared values of a frozen object literal, in source order, or+ * `null` when ANY entry is something other than `key: "literal"` - a+ * spread, a nested object, a call. Not-a-literal is not a partial read:+ * it means this object is not a string vocabulary.+ */+function declaredValues(masked: string, text: string, binding: Binding): string[] | null {+ if (binding.bracket !== "{") return null;+ const values: string[] = [];+ for (const [from, to] of segments(masked, binding.open, binding.close)) {+ const segment = masked.slice(from, to);+ if (segment.trim() === "") continue;+ const match = ENTRY_RE.exec(segment);+ if (match === null) return null;+ const quote = match[1]!;+ const valueStart = from + match[0].length;+ const valueEnd = masked.indexOf(quote, valueStart);+ if (valueEnd === -1 || valueEnd >= to) return null;+ values.push(text.slice(valueStart, valueEnd));+ }+ return values.length > 0 ? values : null;+}++/** A declaration that takes a parameter typed `unknown`. */+interface GuardCandidate {+ readonly name: string;+ /** Source range of the whole declaration, signature and body. */+ readonly from: number;+ readonly to: number;+}++const FUNCTION_RE = /\bfunction\s+([A-Za-z_$][\w$]*)\s*\(/g;+const ARROW_RE = /\bconst\s+([A-Za-z_$][\w$]*)\s*(?::[^;=]*)?=\s*(?:async\s*)?\(/g;++/** Index of the end of the statement starting at `from`, at depth zero. */+function statementEnd(masked: string, from: number): number {+ let depth = 0;+ for (let i = from; i < masked.length; i += 1) {+ const char = masked[i];+ if (char === "(" || char === "[" || char === "{") depth += 1;+ else if (char === ")" || char === "]" || char === "}") {+ depth -= 1;+ if (depth < 0) return i;+ } else if (char === ";" && depth === 0) return i;+ }+ return masked.length;+}++function guardCandidates(masked: string): GuardCandidate[] {+ const found: GuardCandidate[] = [];+ for (const match of masked.matchAll(FUNCTION_RE)) {+ const paramsOpen = match.index! + match[0].length - 1;+ const paramsClose = matchBracket(masked, paramsOpen);+ if (paramsClose === -1) continue;+ if (!/:\s*unknown\b/.test(masked.slice(paramsOpen, paramsClose))) continue;+ const bodyOpen = masked.indexOf("{", paramsClose);+ const bodyClose = bodyOpen === -1 ? -1 : matchBracket(masked, bodyOpen);+ found.push({+ name: match[1]!,+ from: match.index!,+ to: bodyClose === -1 ? masked.length : bodyClose,+ });+ }+ for (const match of masked.matchAll(ARROW_RE)) {+ const paramsOpen = match.index! + match[0].length - 1;+ const paramsClose = matchBracket(masked, paramsOpen);+ if (paramsClose === -1) continue;+ if (!/:\s*unknown\b/.test(masked.slice(paramsOpen, paramsClose))) continue;+ if (!/^[^;{]*=>/.test(masked.slice(paramsClose + 1))) continue;+ found.push({ name: match[1]!, from: match.index!, to: statementEnd(masked, paramsClose + 1) });+ }+ return found;+}++/** One vocabulary the tree declares, as the scan reads it. */+interface ScannedVocabulary {+ readonly file: string;+ /** The frozen object's identifier. `CENSUS.name` must equal it. */+ readonly name: string;+ /** Its declared values, in source order. */+ readonly values: ReadonlyArray<string>;+ /** The membership-list constant built from it. */+ readonly members: string;+ /** The guard that takes `unknown`. */+ readonly guard: string;+}++function scanVocabularies(files: ReadonlyArray<SourceFile>): ScannedVocabulary[] {+ const found: ScannedVocabulary[] = [];+ for (const file of files) {+ const masked = maskSource(file.text);+ const declared = bindings(masked);+ const guards = guardCandidates(masked);+ for (const binding of declared) {+ const values = declaredValues(masked, file.text, binding);+ if (values === null) continue;+ const name = binding.name;+ const derived = new RegExp(+ String.raw`\(\s*typeof\s+${name}\s*\)\s*\[\s*keyof\s+typeof\s+${name}\s*\]`,+ );+ if (!derived.test(masked)) continue;+ const referencesObject = new RegExp(+ String.raw`\b${name}\s*\.|Object\s*\.\s*values\s*\(\s*${name}\s*\)`,+ );+ const list = declared.find(+ (candidate) =>+ candidate !== binding &&+ candidate.bracket !== "{" &&+ referencesObject.test(masked.slice(candidate.open, candidate.close)),+ );+ if (list === undefined) continue;+ const reads = new RegExp(String.raw`\b(?:${list.name}|${name})\b`);+ const guard = guards.find((candidate) =>+ reads.test(masked.slice(candidate.from, candidate.to)),+ );+ if (guard === undefined) continue;+ found.push({+ file: file.path,+ name,+ values,+ members: list.name,+ guard: guard.name,+ });+ }+ }+ return found;+}++const SOURCE_TREE = readSourceTree();+const SCANNED = scanVocabularies(SOURCE_TREE);+const REGISTERED = new Map(CENSUS.map((entry) => [entry.name, entry] as const));+describe("verdict vocabulary census", () => {test("the registry is not empty", () => {// A census with nothing in it passes for the wrong reason. This is the@@ -691,3 +1402,202 @@ describe("the census itself catches drift", () => {expect(problems).toContain("synthetic: values object carries a duplicate value");});});++describe("the census reads the tree", () => {+ test("every four-piece vocabulary in src/ is registered", () => {+ // The finding this block exists for: an unregistered vocabulary used+ // to be invisible, so a module carrying a duplicate value, a phantom+ // member and a guard that accepts every string ran clean.+ const unregistered = SCANNED.filter((row) => !REGISTERED.has(row.name)).map(+ (row) => `${row.name} (${row.file})`,+ );+ // Named, not counted: the failure has to say which vocabulary.+ expect(unregistered).toEqual([]);+ });++ test("no registration outlives the vocabulary it audits", () => {+ // The other direction, and the reason the scan can be trusted at all:+ // if it stopped seeing a shape, the vocabularies written in that shape+ // would go missing here rather than silently leave the population.+ const scanned = new Set(SCANNED.map((row) => row.name));+ const orphaned = CENSUS.filter((entry) => !scanned.has(entry.name)).map((entry) => entry.name);+ expect(orphaned).toEqual([]);+ });++ test("each registration names the object the source declares", () => {+ // `name` is the source identifier, which is what lets the two halves+ // be joined at all. A registration pointing at a different object -+ // the copy-paste failure this file is one long list of opportunities+ // for - lands here as a value mismatch.+ const mismatched: string[] = [];+ for (const row of SCANNED) {+ const entry = REGISTERED.get(row.name);+ if (entry === undefined) continue;+ const registered = Object.values(entry.values).toSorted();+ const read = [...row.values].toSorted();+ if (registered.join(" ") !== read.join(" ")) {+ mismatched.push(+ `${row.name}: registered [${registered.join(",")}] source [${read.join(",")}]`,+ );+ }+ }+ expect(mismatched).toEqual([]);+ });++ test("the scan still finds the population it measures", () => {+ // A scanner that matched nothing would report a clean sweep over an+ // empty set. Set just under the measurement: a floor of 20 against 57+ // would let two thirds of the population stop being seen.+ expect(SCANNED.length).toBeGreaterThan(50);+ expect(SOURCE_TREE.length).toBeGreaterThan(500);+ });++ test("a vocabulary whose list is a multi-line Object.values stays visible", () => {+ // The concrete shape a line-oriented scan loses: the membership list+ // is `Object.freeze(` then `Object.values(HOST_PRESSURE),` on the next+ // line, so no single line carries both. Pinned by name because a+ // regression to line matching drops 20-odd rows at once and every+ // other test in this file still passes.+ const row = SCANNED.find((candidate) => candidate.name === "HOST_PRESSURE");+ expect(`${row?.members} ${row?.guard} ${row?.values.join(",")}`).toBe(+ "HOST_PRESSURE_STATES isHostPressureState measured,unmeasurable",+ );+ });+});++describe("the scan sees the shapes it claims to", () => {+ /**+ * The real scan and the real registry, over one synthetic module.+ *+ * One file rather than the whole tree plus one, because+ * {@link scanVocabularies} decides per file - the four pieces must be+ * in one module - so the two runs cannot differ, and re-walking `src/`+ * once per shape costs a second each for an identical answer.+ */+ function unregisteredWith(intruder: SourceFile): string[] {+ return scanVocabularies([intruder])+ .filter((row) => !REGISTERED.has(row.name))+ .map((row) => row.name);+ }++ const OBJECT = 'export const ZZ = Object.freeze({\n a: "a",\n b: "b",\n} as const);\n';+ const DERIVED = "export type Zz = (typeof ZZ)[keyof typeof ZZ];\n";+ const FROZEN_LIST = "export const ZZS: ReadonlyArray<Zz> = Object.freeze([ZZ.a, ZZ.b]);\n";+ const GUARD =+ "export function isZz(value: unknown): value is Zz {\n" ++ " return typeof value === 'string' && (ZZS as ReadonlyArray<string>).includes(value);\n}\n";++ /**+ * Every source shape the four pieces can arrive in. Each must be+ * enrolled on its own: these are the forms a contributor reaches for+ * without thinking, and a scan that stops matching one fails here by+ * name rather than reporting a quietly smaller population.+ */+ const INTRUDER_SHAPES: ReadonlyArray<readonly [string, string]> = Object.freeze([+ ["an array-literal membership list", OBJECT + DERIVED + FROZEN_LIST + GUARD],+ [+ "a multi-line Object.values membership list",+ OBJECT ++ DERIVED ++ "export const ZZS: ReadonlyArray<Zz> = Object.freeze(\n Object.values(ZZ),\n);\n" ++ GUARD,+ ],+ [+ "an unfrozen membership list",+ OBJECT + DERIVED + "export const ZZS: ReadonlyArray<Zz> = [ZZ.a, ZZ.b];\n" + GUARD,+ ],+ [+ "an arrow-function guard",+ OBJECT ++ DERIVED ++ FROZEN_LIST ++ "export const isZz = (value: unknown): value is Zz =>\n" ++ " typeof value === 'string' && (ZZS as ReadonlyArray<string>).includes(value);\n",+ ],+ [+ "single-quoted values",+ "export const ZZ = Object.freeze({\n a: 'a',\n b: 'b',\n} as const);\n" ++ DERIVED ++ FROZEN_LIST ++ GUARD,+ ],+ [+ "a brace inside a value and a brace inside a comment",+ 'export const ZZ = Object.freeze({\n // closes nothing: }\n a: "a }",\n b: "b",\n} as const);\n' ++ DERIVED ++ FROZEN_LIST ++ GUARD,+ ],+ ["a guard declared before the object it reads", GUARD + OBJECT + DERIVED + FROZEN_LIST],+ [+ "a vocabulary behind a regex literal holding an unpaired quote",+ 'const QUOTED = /["]/;\nexport const ok = QUOTED.source;\n' ++ OBJECT ++ DERIVED ++ FROZEN_LIST ++ GUARD,+ ],+ ]);++ for (const [shape, source] of INTRUDER_SHAPES) {+ test(`a new vocabulary written as ${shape} is reported unregistered`, () => {+ expect(unregisteredWith({ path: "src/core/zz-intruder.ts", text: source })).toEqual(["ZZ"]);+ });+ }++ test("the module the reviewer smuggled past this file is now reported", () => {+ // Reproduced from the review: a duplicate value, a member no value+ // declares, and a guard that accepts every string - three of the+ // defects `auditVocabulary` exists to catch. It scored 63 pass /+ // 0 fail here before the scan existed.+ const text =+ 'export const ZZ_NEW_VOCAB = Object.freeze({\n first: "same",\n second: "same",\n} as const);\n' ++ "export type ZzNewVocab = (typeof ZZ_NEW_VOCAB)[keyof typeof ZZ_NEW_VOCAB];\n" ++ "export const ZZ_NEW_VOCABS: ReadonlyArray<string> = Object.freeze([\n" ++ ' ZZ_NEW_VOCAB.first,\n "phantom",\n]);\n' ++ "export function isZzNewVocab(value: unknown): value is ZzNewVocab {\n" ++ " return typeof value === 'string' && ZZ_NEW_VOCABS.length > 0;\n}\n";+ expect(unregisteredWith({ path: "src/core/zz-new-vocab.ts", text })).toEqual(["ZZ_NEW_VOCAB"]);+ });++ /**+ * Shapes that must stay OUT. A census that reports frozen objects which+ * are not vocabularies gets deleted, and each of these is a live idiom+ * in this tree - the second one by name.+ */+ const NON_VOCABULARY_SHAPES: ReadonlyArray<readonly [string, string]> = Object.freeze([+ [+ "a frozen object with no derived union type",+ 'export const ZZ = Object.freeze({ a: "a" });\n' ++ "export const ZZS = Object.freeze(Object.values(ZZ));\n" ++ "export function isZz(value: unknown): boolean {\n" ++ " return ZZS.includes(value as string);\n}\n",+ ],+ [+ "a curated ordering with no guard, as DREAM_STEP_RUNNABLE is",+ OBJECT + DERIVED + "export const ZZ_RUNNABLE: ReadonlyArray<Zz> = Object.freeze([ZZ.a]);\n",+ ],+ [+ "a frozen lookup whose values are not literals",+ "export const ZZ = Object.freeze({ a: readSourceTree, b: maskSource });\n" ++ DERIVED ++ "export const ZZS = Object.freeze(Object.values(ZZ));\n" ++ "export function isZz(value: unknown): boolean {\n" ++ " return ZZS.includes(value as never);\n}\n",+ ],+ [+ "a guard that takes an already-narrowed string",+ OBJECT ++ DERIVED ++ FROZEN_LIST ++ "export function isZz(value: string): value is Zz {\n" ++ " return (ZZS as ReadonlyArray<string>).includes(value);\n}\n",+ ],+ ]);++ for (const [shape, source] of NON_VOCABULARY_SHAPES) {+ test(`${shape} is not dragged into the population`, () => {+ expect(unregisteredWith({ path: "src/core/zz-intruder.ts", text: source })).toEqual([]);+ });+ }+});diff --git a/tests/core/bench/failure-modes-baseline.test.ts b/tests/core/bench/failure-modes-baseline.test.tsnew file mode 100644index 00000000..69dfa70f--- /dev/null+++ b/tests/core/bench/failure-modes-baseline.test.ts@@ -0,0 +1,102 @@+/**+ * The committed baseline for the four-failure-mode suite (t_72d6eb23).+ *+ * ## Why this is a test and not a CI step+ *+ * Before this file, NO baseline was committed anywhere in the repo: both+ * things called "baselines" were constants inside test files, and CI ran+ * no bench at all - `.github/workflows/ci.yml` runs `bun test` and that is+ * the entire gate. So there were two ways to make the numbers gate:+ *+ * 1. A new workflow step invoking `o2b brain bench memory`.+ * 2. A test inside the run that already gates every push.+ *+ * This is (2), deliberately. A separate CI step is a surface a developer+ * never sees until it goes red in a pull request, cannot run the same way+ * locally, and needs its own artifact plumbing to say WHICH number moved.+ * A test runs identically on a laptop and in CI, fails the build the same+ * way every other regression does, and prints the diff for free. A gate+ * nobody looks at is worse than a gate that fails the build. Cost is not+ * the reason - the whole suite runs in a few seconds offline, with the+ * semantic lane pinned off inside the harness.+ *+ * ## Re-measurement protocol+ *+ * The baseline is EXPECTED to move when the fixture or the shipped code+ * legitimately changes. It is not a number to nudge until the test passes.+ * When this fails:+ *+ * 1. Read WHICH field moved. A `fixture_hash` mismatch alone means the+ * fixture changed and the numbers were never re-measured.+ * 2. Decide whether the move is an improvement, a regression, or a+ * change in what is being measured. Say which in the commit message.+ * 3. Only then regenerate `failure-modes.baseline.json` from a green+ * run and commit it WITH the change that moved it, never separately.+ *+ * Latency is deliberately absent from the baseline: it is the one figure+ * that legitimately differs between a laptop and a CI runner, and pinning+ * it would make the gate flaky in exchange for nothing.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { loadBenchFixture } from "../../../src/core/bench/fixture.ts";+import { runMemoryBench } from "../../../src/core/bench/phases.ts";+import type { BenchReport } from "../../../src/core/bench/types.ts";++const FIXTURE_DIR = join("tests", "fixtures", "bench");+const FIXTURE_PATH = join(FIXTURE_DIR, "failure-modes.json");+const BASELINE_PATH = join(FIXTURE_DIR, "failure-modes.baseline.json");++let runsDir: string;++beforeEach(() => {+ runsDir = mkdtempSync(join(tmpdir(), "o2b-bench-baseline-"));+});++afterEach(() => {+ rmSync(runsDir, { recursive: true, force: true });+});++/** The reproducible slice of a report: everything but the clock. */+function comparable(report: BenchReport): Record<string, unknown> {+ return {+ schema: report.schema,+ fixture: report.fixture,+ fixture_hash: report.fixture_hash,+ quality: report.quality,+ context_cost: report.context_cost,+ failure_modes: report.failure_modes,+ questions: report.questions.map((question) => ({+ id: question.id,+ category: question.category,+ pass: question.pass,+ ...(question.context_chars !== undefined ? { context_chars: question.context_chars } : {}),+ ...(question.injected_tokens !== undefined+ ? { injected_tokens: question.injected_tokens }+ : {}),+ })),+ };+}++describe("failure-mode baseline", () => {+ test("the committed report still describes what the code does", async () => {+ const report = await runMemoryBench({ fixture: loadBenchFixture(FIXTURE_PATH), runsDir });+ const baseline = JSON.parse(readFileSync(BASELINE_PATH, "utf8")) as Record<string, unknown>;+ expect(comparable(report)).toEqual(baseline);+ }, 60_000);++ test("the baseline is pinned to the fixture that produced it", () => {+ // Without this, editing the fixture and forgetting to re-measure would+ // fail somewhere confusing instead of saying what happened.+ const baseline = JSON.parse(readFileSync(BASELINE_PATH, "utf8")) as {+ fixture_hash: string;+ schema: string;+ };+ expect(baseline.fixture_hash).toMatch(/^[0-9a-f]{16}$/);+ expect(baseline.schema).toBe("o2b.bench.v2");+ });+});diff --git a/tests/core/bench/failure-modes.test.ts b/tests/core/bench/failure-modes.test.tsnew file mode 100644index 00000000..3bf3f890--- /dev/null+++ b/tests/core/bench/failure-modes.test.ts@@ -0,0 +1,335 @@+/**+ * The four-failure-mode conformance suite (t_72d6eb23).+ *+ * Each test drives shipped code over a controlled vault. What ships by+ * DEFAULT and what is measured here are not the same thing, and the+ * difference is asserted rather than assumed: `recall_inject_enabled` is+ * off by default (the bench calls the decision core directly), and+ * `integrity.owner_scope_delivery` is off by default (the fixture turns it+ * to `fail`, and a negative control below proves the gate is what does the+ * isolating).+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ loadBenchFixture,+ materializeBenchVault,+ parseBenchFixture,+} from "../../../src/core/bench/fixture.ts";+import {+ benchRecallRetriever,+ classifyRecallDecision,+ isolationViolations,+ RECALL_FAILURE,+ scoreProactiveRecall,+ type RecallFailure,+} from "../../../src/core/bench/failure-modes.ts";+import { benchSearchConfig, runMemoryBench } from "../../../src/core/bench/phases.ts";+import type { BenchFixture } from "../../../src/core/bench/types.ts";+import {+ decideRecallInject,+ RECALL_INJECT_CONFIDENCE_FLOOR,+ type RecallResultSet,+} from "../../../src/core/brain/recall-inject.ts";+import { resolveSearchConfig, search } from "../../../src/core/search/index.ts";++const FIXTURE_PATH = join("tests", "fixtures", "bench", "failure-modes.json");++let runsDir: string;++beforeEach(() => {+ runsDir = mkdtempSync(join(tmpdir(), "o2b-bench-failure-modes-"));+});++afterEach(() => {+ rmSync(runsDir, { recursive: true, force: true });+});++function fixture(): BenchFixture {+ return loadBenchFixture(FIXTURE_PATH);+}++/**+ * The degenerate retriever a gaming implementation ships: hand back your+ * best note whatever was asked. Paired with a floor of 0 it is the+ * "always inject" arm - not a stub, but the real shape of the strategy+ * the scorer has to be able to rank below a selective one.+ */+async function alwaysConfident(): Promise<RecallResultSet> {+ return Object.freeze({+ candidates: Object.freeze([+ Object.freeze({+ path: "Brain/notes/pgbouncer.md",+ title: "Connection pooling",+ score: 1,+ searchType: "keyword",+ startLine: 1,+ endLine: 3,+ }),+ ]),+ total: 1,+ });+}++/** Both rates share one denominator, so their sum is what ranks strategies. */+function totalFailureRate(score: {+ know_to_ask_failure_rate: number;+ false_fire_rate: number;+}): number {+ return score.know_to_ask_failure_rate + score.false_fire_rate;+}++describe("the committed failure-mode fixture", () => {+ test("runs green and reports all four metrics", async () => {+ const report = await runMemoryBench({ fixture: fixture(), runsDir });+ expect(report.quality.passed).toBe(report.quality.total);+ expect(report.quality.by_category["proactive_recall"]).toEqual({ passed: 4, total: 4 });+ expect(report.quality.by_category["write_fidelity"]).toEqual({ passed: 2, total: 2 });+ expect(report.quality.by_category["source_isolation"]).toEqual({ passed: 1, total: 1 });+ expect(report.failure_modes.know_to_ask_failure_rate).toBe(0);+ expect(report.failure_modes.false_fire_rate).toBe(0);+ expect(report.failure_modes.source_isolation_violations).toBe(0);+ // The fourth metric is a COST, so it lives in the cost family.+ expect(report.context_cost.avg_injected_tokens).toBeGreaterThan(0);+ }, 60_000);++ test("is deterministic: two independent runs agree on every metric", async () => {+ // Separate run directories, so the second run genuinely redoes the+ // work instead of resuming the first one's checkpoints.+ const otherRunsDir = mkdtempSync(join(tmpdir(), "o2b-bench-failure-modes-b-"));+ const first = await runMemoryBench({ fixture: fixture(), runsDir });+ const second = await runMemoryBench({ fixture: fixture(), runsDir: otherRunsDir });+ rmSync(otherRunsDir, { recursive: true, force: true });+ expect(second.fixture_hash).toBe(first.fixture_hash);+ expect(second.quality).toEqual(first.quality);+ expect(second.failure_modes).toEqual(first.failure_modes);+ expect(second.context_cost).toEqual(first.context_cost);+ }, 60_000);+});++describe("the harness holds its own determinism", () => {+ test("a shell configured for semantic search still resolves the CI lane", () => {+ // `resolveSearchConfig` reads `process.env`, so before the override+ // the harness's "deterministic and network-free" claim was a property+ // of an unset developer shell: a configured semantic lane is a second+ // ranking signal, and on a remote provider a network call.+ const previous = {+ semantic: process.env["OPEN_SECOND_BRAIN_SEARCH_SEMANTIC"],+ provider: process.env["OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER"],+ };+ try {+ process.env["OPEN_SECOND_BRAIN_SEARCH_SEMANTIC"] = "1";+ process.env["OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER"] = "openai-compat";+ expect(resolveSearchConfig({ vault: runsDir }).semantic.enabled).toBe(true);+ // Same shell, same vault - the harness refuses the lane anyway.+ expect(benchSearchConfig(runsDir).semantic.enabled).toBe(false);+ } finally {+ for (const [key, value] of [+ ["OPEN_SECOND_BRAIN_SEARCH_SEMANTIC", previous.semantic],+ ["OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER", previous.provider],+ ] as const) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ }+ });+});++describe("metric 1: proactive know-to-ask, with the anti-gaming term", () => {+ test("an always-inject strategy scores worse than one that abstains correctly", async () => {+ // Both arms run the SAME shipped decision core over the SAME prompts+ // and are scored by the SAME scorer. Only the retriever and the+ // confidence floor differ, which is exactly what separates a memory+ // that knows when to speak from one that always speaks.+ const vault = join(runsDir, "vault");+ const loaded = fixture();+ materializeBenchVault(loaded, vault);+ const config = resolveSearchConfig({+ vault,+ overrides: { semantic: { enabled: false } },+ });+ await search(config, { query: "warmup", limit: 1 });++ const prompts = loaded.questions.filter((q) => q.category === "proactive_recall");+ expect(prompts.length).toBeGreaterThan(0);++ const shipped: Array<RecallFailure | null> = [];+ const always: Array<RecallFailure | null> = [];+ for (const question of prompts) {+ const expectInject = question.expect_inject === true;+ // oxlint-disable-next-line no-await-in-loop+ shipped.push(+ classifyRecallDecision(+ expectInject,+ // oxlint-disable-next-line no-await-in-loop+ await decideRecallInject(question.prompt ?? "", benchRecallRetriever(config, 4)),+ ),+ );+ always.push(+ classifyRecallDecision(+ expectInject,+ // oxlint-disable-next-line no-await-in-loop+ await decideRecallInject(question.prompt ?? "", alwaysConfident, {+ confidenceFloor: 0,+ }),+ ),+ );+ }++ const shippedScore = scoreProactiveRecall(shipped);+ const alwaysScore = scoreProactiveRecall(always);++ // The shipped strategy is right on both halves of the fixture.+ expect(shippedScore.know_to_ask_failure_rate).toBe(0);+ expect(shippedScore.false_fire_rate).toBe(0);+ // The gaming strategy buys a perfect know-to-ask rate and pays for it+ // in false fires - which is the whole point of carrying that term.+ expect(alwaysScore.know_to_ask_failure_rate).toBe(0);+ expect(alwaysScore.false_fire_rate).toBeGreaterThan(0);+ // Shared denominator, so the total failure rate is what ranks them.+ expect(totalFailureRate(alwaysScore)).toBeGreaterThan(totalFailureRate(shippedScore));+ }, 60_000);++ test("the anti-gaming pressure is on the confidence floor, not on the gate", () => {+ // `evaluateSurfacingGate` fails open by design, so it can carry no+ // pressure; the floor is the only discriminating bound the decision+ // core exposes, and the scorer is denominated so that using it wrong+ // costs something.+ expect(RECALL_INJECT_CONFIDENCE_FLOOR).toBeGreaterThan(0);+ const allWrong = scoreProactiveRecall([RECALL_FAILURE.falseFire, RECALL_FAILURE.falseFire]);+ expect(allWrong.false_fire_rate).toBe(1);+ // A fault is charged to neither rate: a broken retriever is not a+ // cautious one, and folding it in would report a number about the+ // harness under a name that promises a number about memory.+ const faulted = scoreProactiveRecall([RECALL_FAILURE.faulted, null]);+ expect(faulted.know_to_ask_failure_rate).toBe(0);+ expect(faulted.false_fire_rate).toBe(0);+ expect(faulted.faults).toBe(1);+ });+});++describe("metric 2: write-back fidelity on the shipped path", () => {+ test("grades provenance with no model call, and a lost field fails", async () => {+ const loaded = fixture();+ const broken = parseBenchFixture({+ ...(JSON.parse(JSON.stringify(loaded)) as Record<string, unknown>),+ name: "write-fidelity-missing-provenance",+ questions: [+ {+ id: "q-fidelity-demands-a-field-the-path-does-not-write",+ category: "write_fidelity",+ intake_text: "Decision: Cap the pool at ninety connections.",+ expected_labels: ["decision"],+ expected_provenance: ["dedupe_key", "confidence_score"],+ },+ ],+ });+ const report = await runMemoryBench({ fixture: broken, runsDir });+ expect(report.quality.passed).toBe(0);+ expect(report.questions[0]!.failure).toContain("confidence_score");+ }, 60_000);++ test("a non-Latin fixture scores on structure, not on a word list", async () => {+ const report = await runMemoryBench({ fixture: fixture(), runsDir });+ const nonLatin = report.questions.find((q) => q.id === "q-fidelity-non-latin")!;+ expect(nonLatin.pass).toBe(true);+ // And it really did extract - a pass over zero records would be a lie.+ const raw = JSON.parse(+ readFileSync(join(runsDir, report.run_id, "results", "q-fidelity-non-latin.json"), "utf8"),+ ) as { labels: string[]; dedup_stable: boolean };+ expect(raw.labels).toEqual(["решение", "открытый_вопрос"]);+ expect(raw.dedup_stable).toBe(true);+ }, 60_000);+});++describe("metric 3: cross-source isolation gates at zero, non-vacuously", () => {+ test("the strict gate is what isolates: without it the same fixture leaks", async () => {+ const loaded = JSON.parse(JSON.stringify(fixture())) as {+ notes: Array<{ path: string }>;+ questions: Array<{ category: string }>;+ };+ const defaultGate = parseBenchFixture({+ ...loaded,+ name: "failure-modes-shipped-default-gate",+ notes: loaded.notes.filter((note) => note.path !== "Brain/_brain.yaml"),+ questions: loaded.questions.filter((q) => q.category === "source_isolation"),+ });+ const report = await runMemoryBench({ fixture: defaultGate, runsDir });+ // Under the shipped `off` default no scope is evaluated at all, so the+ // other agent's memory is delivered. A gate asserted under that+ // default would pass for a reason that has nothing to do with+ // isolation, which is why the fixture sets `fail`.+ expect(report.failure_modes.source_isolation_violations).toBe(1);+ expect(report.questions[0]!.failure).toContain("pref-other");+ }, 60_000);++ test("the assertion reads delivered contents, never the hidden counter", () => {+ // `hiddenByOwnerScope` counts DELIVERED items under `warn` and is+ // withheld entirely under `fail`, so it cannot serve as a violation+ // numerator. The scorer takes ids that came back.+ expect(isolationViolations(["a", "b"], ["b", "c"])).toEqual(["b"]);+ expect(isolationViolations(["a"], ["b"])).toEqual([]);+ });++ test("isolation that withholds the caller's own memory is also a failure", async () => {+ const loaded = JSON.parse(JSON.stringify(fixture())) as Record<string, unknown>;+ const overreaching = parseBenchFixture({+ ...loaded,+ name: "failure-modes-overreaching-scope",+ questions: [+ {+ id: "q-isolation-must-not-narrow",+ category: "source_isolation",+ // Nobody owns this scope, so `pref-own` is correctly withheld -+ // and demanding it back proves the converse invariant is armed.+ agent_scope: "agent-z",+ expected_ids: ["pref-own"],+ forbidden_ids: ["pref-other"],+ max_tokens: 500,+ },+ ],+ });+ const report = await runMemoryBench({ fixture: overreaching, runsDir });+ expect(report.quality.passed).toBe(0);+ expect(report.questions[0]!.failure).toContain("pref-own");+ expect(report.failure_modes.source_isolation_violations).toBe(0);+ }, 60_000);+});++describe("metric 4: exactly one token estimator is reachable from the bench", () => {+ const BENCH_DIR = join("src", "core", "bench");++ function benchSources(): ReadonlyArray<{ file: string; code: string }> {+ return readdirSync(BENCH_DIR)+ .filter((file) => file.endsWith(".ts"))+ .map((file) => ({+ file,+ code: readFileSync(join(BENCH_DIR, file), "utf8")+ .replace(/\/\*[\s\S]*?\*\//g, "")+ .replace(/^\s*\/\/.*$/gm, ""),+ }));+ }++ test("the one estimator is imported once, from the shared tokenizer", () => {+ const importers = benchSources().filter(({ code }) => code.includes("estimateTokens"));+ expect(importers.map(({ file }) => file)).toEqual(["failure-modes.ts"]);+ expect(importers[0]!.code).toContain('from "../brain/text/tokenizer.ts"');+ });++ test("no second estimator survives anywhere in the bench", () => {+ // This repo carries five disagreeing estimators, two of which export+ // the SAME name from different modules - so the check is on the import+ // path and on the arithmetic, never on the identifier alone.+ for (const { file, code } of benchSources()) {+ expect(`${file}: ${code}`).not.toContain("embeddings/signature.ts");+ expect(`${file}: ${code}`).not.toContain("CHARS_PER_ESTIMATED_TOKEN");+ expect(`${file}: ${code}`).not.toContain("countTokens");+ // The inline `ceil(chars / 4)` the report used to carry.+ expect(code).not.toMatch(/\/\s*4\s*[);]/);+ }+ });+});diff --git a/tests/core/bench/phases.test.ts b/tests/core/bench/phases.test.tsindex 02192407..d51241d2 100644--- a/tests/core/bench/phases.test.ts+++ b/tests/core/bench/phases.test.ts@@ -113,7 +113,7 @@ describe("runMemoryBench", () => {expect(report.latency_ms.avg).toBeGreaterThanOrEqual(0);expect(report.latency_ms.max).toBeGreaterThanOrEqual(report.latency_ms.avg);expect(report.context_cost.avg_chars).toBeGreaterThan(0);- expect(report.context_cost.est_tokens).toBeGreaterThan(0);+ expect(report.context_cost.avg_injected_tokens).toBeGreaterThan(0);expect(report.judge.status).toBe("skipped");// Stable question order by id for diffability.expect(report.questions.map((q) => q.id)).toEqual(report.questions.map((q) => q.id).toSorted());diff --git a/tests/core/brain.snapshot.test.ts b/tests/core/brain.snapshot.test.tsindex 237543fb..cac8ba9c 100644--- a/tests/core/brain.snapshot.test.ts+++ b/tests/core/brain.snapshot.test.ts@@ -6,6 +6,7 @@ import {mkdtempSync,readFileSync,rmSync,+ symlinkSync,utimesSync,writeFileSync,} from "node:fs";@@ -16,9 +17,11 @@ import {BrainSnapshotListingError,BrainSnapshotToolingMissingError,createSnapshot,+ isSnapshotEntrySkipReason,listSnapshots,pruneSnapshots,restoreSnapshot,+ SNAPSHOT_ENTRY_SKIP_REASON,} from "../../src/core/brain/snapshot.ts";import { brainDirs, snapshotPath } from "../../src/core/brain/paths.ts";import { bootstrapBrain } from "../../src/core/brain/init.ts";@@ -150,7 +153,7 @@ describe("listSnapshots", () => {const newT = new Date("2026-05-15T00:00:00Z");utimesSync(c, newT, newT);- const list = listSnapshots(vault);+ const list = listSnapshots(vault).snapshots;expect(list).toHaveLength(3);expect(list[0]!.run_id).toBe("dream-2026-05-14-090000");expect(list[1]!.run_id).toBe("dream-2026-05-14-080000");@@ -162,7 +165,46 @@ describe("listSnapshots", () => {});test("returns [] when .snapshots/ is empty", () => {- expect(listSnapshots(vault)).toEqual([]);+ expect(listSnapshots(vault).snapshots).toEqual([]);+ });++ test("an empty history skips nothing, so the two fields cannot be confused", () => {+ expect(listSnapshots(vault)).toEqual({ snapshots: [], skipped: [] });+ });++ test("an archive that cannot be stat'ed is carried out, not dropped", () => {+ // The failure the swallow hid: a populated history in which nothing+ // survives both filters used to answer exactly like a vault that had+ // never taken a recovery point.+ createSnapshot(vault, "dream-readable", { reason: DREAM });+ const dir = brainDirs(vault).snapshots;+ symlinkSync(join(dir, "nowhere.tar.zst"), join(dir, "dream-dangling.tar.zst"));++ const listing = listSnapshots(vault);+ expect(listing.snapshots.map((s) => s.run_id)).toEqual(["dream-readable"]);+ expect(listing.skipped).toHaveLength(1);+ expect(listing.skipped[0]!.name).toBe("dream-dangling.tar.zst");+ expect(listing.skipped[0]!.reason).toBe(SNAPSHOT_ENTRY_SKIP_REASON.entryUnreadable);+ expect(isSnapshotEntrySkipReason(listing.skipped[0]!.reason)).toBe(true);+ expect(listing.skipped[0]!.detail.length).toBeGreaterThan(0);+ });++ test("an archive whose run id does not validate is carried out under its own reason", () => {+ writeFileSync(join(brainDirs(vault).snapshots, "not a run id!.tar.zst"), "x");+ const listing = listSnapshots(vault);+ expect(listing.snapshots).toEqual([]);+ expect(listing.skipped.map((s) => s.reason)).toEqual([+ SNAPSHOT_ENTRY_SKIP_REASON.runIdUnparseable,+ ]);+ });++ test("a file that is not an archive is skipped silently, because it is not one", () => {+ createSnapshot(vault, "dream-readable", { reason: DREAM });+ writeFileSync(join(brainDirs(vault).snapshots, "README.txt"), "mine");+ // The sidecar manifest createSnapshot just wrote is in this directory+ // too, and neither it nor the note is a recovery point that could not+ // be read.+ expect(listSnapshots(vault).skipped).toEqual([]);});test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(@@ -175,7 +217,7 @@ describe("listSnapshots", () => {const snapshots = brainDirs(vault).snapshots;chmodSync(snapshots, 0o000);try {- expect(() => listSnapshots(vault)).toThrow(BrainSnapshotListingError);+ expect(() => listSnapshots(vault).snapshots).toThrow(BrainSnapshotListingError);try {listSnapshots(vault);} catch (err) {@@ -186,7 +228,7 @@ describe("listSnapshots", () => {}// And the same directory, readable again, still lists its archive:// the throw is about the read, not about the snapshot.- expect(listSnapshots(vault)).toHaveLength(1);+ expect(listSnapshots(vault).snapshots).toHaveLength(1);},);@@ -200,7 +242,7 @@ describe("listSnapshots", () => {createSnapshot(vault, "dream-legacy", { reason: DREAM });rmSync(manifestSidecarPath(vault, "dream-legacy"), { force: true });- const list = listSnapshots(vault);+ const list = listSnapshots(vault).snapshots;const byId = new Map(list.map((s) => [s.run_id, s]));expect(byId.get("dream-with-sidecar")!.manifest_path).toBe(sidecar);expect(byId.get("dream-legacy")!.manifest_path).toBeNull();@@ -224,13 +266,13 @@ describe("pruneSnapshots", () => {const t = new Date(ts[i]!);utimesSync(p, t, t);}- const before = listSnapshots(vault);+ const before = listSnapshots(vault).snapshots;expect(before).toHaveLength(5);const res = pruneSnapshots(vault, 3);expect(res.deleted).toHaveLength(2);- const after = listSnapshots(vault);+ const after = listSnapshots(vault).snapshots;expect(after).toHaveLength(3);expect(after.map((s) => s.run_id)).toEqual(["dream-e-000000",@@ -243,7 +285,7 @@ describe("pruneSnapshots", () => {createSnapshot(vault, "dream-only", { reason: DREAM });const res = pruneSnapshots(vault, 10);expect(res.deleted).toEqual([]);- expect(listSnapshots(vault)).toHaveLength(1);+ expect(listSnapshots(vault).snapshots).toHaveLength(1);});test("removes sidecar manifest alongside the archive", () => {diff --git a/tests/core/brain/architect-concurrent-runs.test.ts b/tests/core/brain/architect-concurrent-runs.test.tsnew file mode 100644index 00000000..756edfb8--- /dev/null+++ b/tests/core/brain/architect-concurrent-runs.test.ts@@ -0,0 +1,197 @@+/**+ * Two architect runs on one repo, driven by genuinely concurrent+ * processes (finding C5 of the locks-and-races review).+ *+ * `generateArchDocs` takes `<vault>/Brain/projects/arch/<key>.lock` across+ * the whole plan-then-write pass, because planning is a read of every note+ * on disk and writing is a rewrite of the same notes. A lock that starts+ * after the read does not prevent a lost update - and the file's existing+ * lock test cannot see the difference: it samples `existsSync(lock)` from+ * the `advanced` events, and every one of those is emitted from the write+ * loop, which runs after all planning either way.+ *+ * WHY THE TALLY IS THE INSTRUMENT, AND NOT THE BYTES. One run's output is+ * a pure function of the scanned facts plus the prose already outside each+ * note's regions. Two runs on one repo therefore compute the same bytes,+ * so whichever writes last leaves the same file whether it read the+ * other's output or the state before it - the bytes cannot tell the two+ * interleavings apart. What CAN is `created`/`updated`/`unchanged`: those+ * counts are the verdict of the read, they are in the CLI's JSON envelope,+ * and they are only true if the read that produced them is inside the same+ * critical section as the write. Under the lock, exactly one of N+ * concurrent runs may report that it created a note; the rest must report+ * finding it already correct. With the lock moved to cover only the+ * writes, every run claims to have created the same file.+ *+ * Real `bun` children behind a wall-clock barrier, the discipline of+ * `tests/core/brain/ingest/concurrent-shared-writes.test.ts`: process+ * startup alone staggers three processes by more than a plan takes, which+ * would serialize them by accident and pass against the defect.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { generateArchDocs } from "../../../src/core/brain/architect/generate.ts";+import { repoKey } from "../../../src/core/brain/git/identity.ts";++/** Enough notes that one run's write loop outlasts another run's plan. */+const MODULES = 40;+const FILES_PER_MODULE = 3;+/** One overview plus one note per module. */+const NOTE_COUNT = MODULES + 1;++const RUNNERS = 3;+const SPAWN_TIMEOUT_MS = 60_000;++/**+ * Milliseconds the children wait before starting work. `bun` startup alone+ * staggers three processes by more than a plan pass takes, which would+ * serialize them by accident; the barrier makes the overlap real.+ */+const BARRIER_LEAD_MS = 1_500;++const GENERATE = join(import.meta.dir, "../../../src/core/brain/architect/generate.ts");++let tmp: string;+let project: string;+let vault: string;+let archDir: string;++function seedProject(): void {+ mkdirSync(project, { recursive: true });+ writeFileSync(+ join(project, "package.json"),+ JSON.stringify({ name: "race-app", version: "0.0.1" }),+ );+ for (let m = 0; m < MODULES; m += 1) {+ const name = `m${String(m).padStart(2, "0")}`;+ const dir = join(project, "src", name);+ mkdirSync(dir, { recursive: true });+ for (let f = 0; f < FILES_PER_MODULE; f += 1) {+ writeFileSync(join(dir, `f${f}.ts`), `// ${name} ${f}\n`, "utf8");+ }+ }+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-architect-race-"));+ project = join(tmp, "race-app");+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ seedProject();+ archDir = join(vault, "Brain", "projects", "arch", repoKey(project));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** What one child run reported about the disk it found. */+interface RunReport {+ readonly created: number;+ readonly updated: number;+ readonly unchanged: number;+}++/** Run `RUNNERS` copies of one architect run, released together. */+async function raceRuns(scriptName: string): Promise<ReadonlyArray<RunReport>> {+ const script = join(tmp, scriptName);+ writeFileSync(+ script,+ [+ // Imported BEFORE the barrier: module graph load is exactly the+ // startup stagger the barrier exists to absorb.+ `const { generateArchDocs } = await import(${JSON.stringify(GENERATE)});`,+ "const [vaultArg, projectArg, startAt] = process.argv.slice(2);",+ "while (Date.now() < Number(startAt)) Bun.sleepSync(1);",+ "const res = generateArchDocs(vaultArg, projectArg);",+ "process.stdout.write(JSON.stringify({",+ " created: res.created, updated: res.updated, unchanged: res.unchanged,",+ "}));",+ ].join("\n"),+ "utf8",+ );+ const startAt = String(Date.now() + BARRIER_LEAD_MS);+ const procs = Array.from({ length: RUNNERS }, () =>+ Bun.spawn(["bun", script, vault, project, startAt], { stdout: "pipe", stderr: "pipe" }),+ );+ const reports: RunReport[] = [];+ const failures: string[] = [];+ await Promise.all(+ procs.map(async (proc) => {+ const out = await new Response(proc.stdout).text();+ const err = await new Response(proc.stderr).text();+ const code = await proc.exited;+ if (code !== 0) {+ failures.push(`exit ${code}: ${err.trim()}`);+ return;+ }+ reports.push(JSON.parse(out) as RunReport);+ }),+ );+ expect(failures).toEqual([]);+ return reports;+}++/** Reports that claim the run changed something, and the ones that do not. */+function split(reports: ReadonlyArray<RunReport>): {+ readonly acting: ReadonlyArray<RunReport>;+ readonly observing: ReadonlyArray<RunReport>;+} {+ return {+ acting: reports.filter((r) => r.created + r.updated > 0),+ observing: reports.filter((r) => r.created + r.updated === 0),+ };+}++describe("concurrent architect runs on one repo", () => {+ test(+ "only one of three simultaneous first runs may report creating the notes",+ async () => {+ const reports = await raceRuns("first-run-racer.ts");++ // The winner of the lock finds an empty tree; the two that queue+ // behind it must find the tree it left, note for note.+ expect(split(reports).acting).toEqual([{ created: NOTE_COUNT, updated: 0, unchanged: 0 }]);+ expect(split(reports).observing).toEqual([+ { created: 0, updated: 0, unchanged: NOTE_COUNT },+ { created: 0, updated: 0, unchanged: NOTE_COUNT },+ ]);+ expect(existsSync(`${archDir}.lock`)).toBe(false);+ },+ SPAWN_TIMEOUT_MS,+ );++ test(+ "only one of three simultaneous re-runs may report refreshing the notes",+ async () => {+ // The read-modify-write shape proper: every note already exists, so+ // each run's plan is a `readFileSync` plus a `mergeRegions` of what+ // it read. Three runs that all read the same "before" state all+ // decide the same three notes need rewriting.+ const first = generateArchDocs(vault, project);+ expect(first.created).toBe(NOTE_COUNT);++ // One module gains a file and a new module appears: overview.md and+ // m00.md change, znew.md is new, the other 39 notes are already right.+ writeFileSync(join(project, "src", "m00", "extra.ts"), "// extra\n", "utf8");+ mkdirSync(join(project, "src", "znew"), { recursive: true });+ writeFileSync(join(project, "src", "znew", "a.ts"), "// new\n", "utf8");++ const reports = await raceRuns("rerun-racer.ts");++ expect(split(reports).acting).toEqual([+ { created: 1, updated: 2, unchanged: NOTE_COUNT - 2 },+ ]);+ expect(split(reports).observing).toEqual([+ { created: 0, updated: 0, unchanged: NOTE_COUNT + 1 },+ { created: 0, updated: 0, unchanged: NOTE_COUNT + 1 },+ ]);+ expect(existsSync(`${archDir}.lock`)).toBe(false);+ },+ SPAWN_TIMEOUT_MS,+ );+});diff --git a/tests/core/brain/architect-progress.test.ts b/tests/core/brain/architect-progress.test.tsnew file mode 100644index 00000000..60699ec5--- /dev/null+++ b/tests/core/brain/architect-progress.test.ts@@ -0,0 +1,175 @@+/**+ * The architecture scan reports while it walks (nothing-runs-unwatched,+ * U11).+ *+ * The walk is the longest thing this module does - measured at 388 ms of+ * a 396 ms run on this repository - and it used to say nothing until the+ * notes were already on disk. What is pinned here is what makes the+ * stream worth having: it starts at the walk, it advances once per+ * directory read, the render stage carries the denominator the walk+ * cannot have, and the run terminates. Plus the two properties that keep+ * the observer honest: a deadline stops the walk at a boundary, and a run+ * with a sink attached writes exactly what a run without one writes.+ */++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 { generateArchDocs } from "../../../src/core/brain/architect/generate.ts";+import { ARCHITECT_STAGE, scanProject } from "../../../src/core/brain/architect/scan.ts";+import {+ OPERATION,+ PROGRESS_KIND,+ PROGRESS_REASON,+ type ProgressEvent,+} from "../../../src/core/brain/progress.ts";+import { createSafeguard, SafeguardTimeoutError } from "../../../src/core/brain/safeguard.ts";+import { digestVaultTree } from "../../helpers/vault-digest.ts";++let tmp: string;+let project: string;++function seed(relPath: string, content = "// x\n"): void {+ const abs = join(project, relPath);+ mkdirSync(join(abs, ".."), { recursive: true });+ writeFileSync(abs, content);+}++function freshVault(name: string): string {+ const vault = join(tmp, name);+ mkdirSync(join(vault, "Brain"), { recursive: true });+ return vault;+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-architect-progress-"));+ project = join(tmp, "demo-app");+ mkdirSync(project, { recursive: true });+ writeFileSync(join(project, "package.json"), JSON.stringify({ name: "demo-app" }));+ seed("src/core/engine.ts");+ seed("src/core/deep/nested/util.ts");+ seed("src/cli/main.ts");+ seed("tests/engine.test.ts");+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** A clock that spends a second per reading, so the first checkpoint trips. */+function elapsingClock(): () => number {+ let millis = 0;+ return () => (millis += 1_000);+}++function record(): { events: ProgressEvent[]; sink: (e: ProgressEvent) => void } {+ const events: ProgressEvent[] = [];+ return { events, sink: (e) => events.push(e) };+}++describe("architect progress", () => {+ test("a run starts at the walk, advances, and finishes", () => {+ const { events, sink } = record();++ generateArchDocs(freshVault("vault"), project, { onProgress: sink });++ expect(events.length).toBeGreaterThan(0);+ expect(events.every((e) => e.operation === OPERATION.architect)).toBe(true);+ expect(events[0]?.kind).toBe(PROGRESS_KIND.started);+ expect(events.at(-1)?.kind).toBe(PROGRESS_KIND.finished);+ const started = events.filter((e) => e.kind === PROGRESS_KIND.started).map((e) => e.stage);+ expect(started).toEqual([ARCHITECT_STAGE.walk, ARCHITECT_STAGE.render]);+ });++ test("the walk counts without a denominator, the render stage has one", () => {+ const { events, sink } = record();++ // src/cli, src/core and one nested module: 3 notes, 2 of them modules.+ generateArchDocs(freshVault("vault"), project, { onProgress: sink });++ const walk = events.filter((e) => e.stage === ARCHITECT_STAGE.walk);+ const render = events.filter((e) => e.stage === ARCHITECT_STAGE.render);+ expect(walk.every((e) => e.total === undefined)).toBe(true);+ expect(walk.at(-1)?.completed).toBeGreaterThan(0);+ expect(render.every((e) => e.total === 3)).toBe(true);+ expect(render.at(-1)?.completed).toBe(3);+ });++ test("the scan stops at a boundary when the deadline has passed", () => {+ // A clock that jumps a second per reading: the budget is spent by+ // the FIRST directory read, so the walk stops at that boundary+ // rather than at the end of the tree.+ const safeguard = createSafeguard({+ operation: OPERATION.architect,+ timeoutMs: 10,+ now: elapsingClock(),+ });++ expect(() => scanProject(project, { safeguard })).toThrow(SafeguardTimeoutError);+ });++ test("a deadline that trips reports the stop on the stream and writes nothing", () => {+ const vault = freshVault("vault");+ const before = digestVaultTree(vault);+ const { events, sink } = record();+ const safeguard = createSafeguard({+ operation: OPERATION.architect,+ timeoutMs: 10,+ now: elapsingClock(),+ });++ expect(() => generateArchDocs(vault, project, { onProgress: sink, safeguard })).toThrow(+ SafeguardTimeoutError,+ );+ expect(events.at(-1)?.kind).toBe(PROGRESS_KIND.stopped);+ expect(events.at(-1)?.reason).toBe(PROGRESS_REASON.timedOut);+ expect(digestVaultTree(vault)).toBe(before);+ });++ test("attaching an observer changes nothing the run writes", () => {+ const silent = freshVault("vault-silent");+ const watched = freshVault("vault-watched");++ const { events, sink } = record();+ generateArchDocs(silent, project);+ generateArchDocs(watched, project, { onProgress: sink });++ expect(events.length).toBeGreaterThan(0);+ // Whole-tree digests, not spot checks: an observer that changed one+ // byte anywhere in the vault would have to show up here.+ expect(digestVaultTree(watched)).toBe(digestVaultTree(silent));+ });++ test("a sink that throws does not fail the run, and does not vanish either", () => {+ let calls = 0;+ const res = generateArchDocs(freshVault("vault"), project, {+ onProgress: () => {+ calls += 1;+ throw new Error("stream closed");+ },+ });++ expect(res.created).toBeGreaterThan(0);+ // Detached after the first failure: a stream that fails on the first+ // tick would otherwise fail on every one.+ expect(calls).toBe(1);+ expect(res.progressFault).toBe("stream closed");+ });++ test("a scan watched on its own opens the walk and does not close the run", () => {+ // A bare scan is half a run: it reports the walk, and the terminator+ // belongs to whoever also renders. `runIndex` reports its walk the+ // same way, and `runEmbeddingPhase` reports the other half.+ const { events, sink } = record();++ scanProject(project, { onProgress: sink });++ expect(events[0]?.kind).toBe(PROGRESS_KIND.started);+ expect(events[0]?.stage).toBe(ARCHITECT_STAGE.walk);+ expect(events.every((e) => e.stage === ARCHITECT_STAGE.walk)).toBe(true);+ expect(events.some((e) => e.kind === PROGRESS_KIND.advanced)).toBe(true);+ expect(events.some((e) => e.kind === PROGRESS_KIND.finished)).toBe(false);+ });+});diff --git a/tests/core/brain/architect.test.ts b/tests/core/brain/architect.test.tsindex bde3015a..a98bdbc6 100644--- a/tests/core/brain/architect.test.ts+++ b/tests/core/brain/architect.test.ts@@ -4,12 +4,23 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import {+ chmodSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";-import { generateArchDocs } from "../../../src/core/brain/architect/generate.ts";-import { scanProject } from "../../../src/core/brain/architect/scan.ts";+import { ArchWriteError, generateArchDocs } from "../../../src/core/brain/architect/generate.ts";+import { ARCHITECT_STAGE, scanProject } from "../../../src/core/brain/architect/scan.ts";+import { PROGRESS_KIND } from "../../../src/core/brain/progress.ts";+import { RegionError } from "../../../src/core/brain/regions.ts";let tmp: string;let project: string;@@ -69,6 +80,50 @@ test("scanProject produces deterministic structural facts", () => {expect(scanProject(project)).toEqual(facts);});+test("a dot-directory's contents never reach the facts", () => {+ const before = scanProject(project);+ // Tooling state, not architecture: agent worktrees, CI definitions,+ // caches. On this repository that rule is 88% of every file visited.+ seed(".claude/worktrees/copy/src/index.ts");+ seed(".github/workflows/ci.yml");+ seed(".cache-of-things/blob.ts");+ // A FILE whose name collides with a skipped directory is still a file.+ seed("src/core/build");++ const facts = scanProject(project);+ expect(facts.languages[".yml"]).toBeUndefined();+ expect(facts.totalFiles).toBe(before.totalFiles + 1);+ expect(facts.modules.map((m) => m.name)).toEqual(["cli", "core"]);+ expect(facts.modules.find((m) => m.name === "core")!.topFiles).toContain("build");+});++test("the traversal reads each directory exactly once", () => {+ seed("src/core/deep/nested/util.ts");+ // Every directory the scan is allowed to enter, listed rather than+ // computed: `node_modules/dep` and `.git` are skipped, so reading+ // either of them would show up here as an extra count.+ const walkable = [+ "",+ "src",+ "src/cli",+ "src/core",+ "src/core/deep",+ "src/core/deep/nested",+ "tests",+ ];++ // The progress counter is the instrument: it advances once per+ // directory read, so a subtree walked a second time doubles its count.+ let reads = 0;+ scanProject(project, {+ onProgress: (event) => {+ if (event.kind === PROGRESS_KIND.advanced) reads += 1;+ },+ });++ expect(reads).toBe(walkable.length);+});+test("scanProject skips symlinks instead of following them", () => {// A symlink cycle inside the tree must not hang or overflow the scan,// and symlinked content outside the module must not be counted.@@ -114,6 +169,158 @@ test("regeneration preserves operator edits outside regions and refreshes factsexpect(second.updated).toBeGreaterThanOrEqual(1);});+/**+ * The renderer must not consult the host's collation.+ *+ * Two children generate the same fixture and their overview bytes are+ * compared. `LC_ALL` alone cannot prove this: measured on this runtime,+ * `new Intl.Collator().resolvedOptions().locale` stays `en-US` whatever+ * `LC_ALL` says, so an env-only test would pass against a collator-based+ * tie-break too. The second child therefore installs a reversed collation+ * on `String.prototype.localeCompare` before importing the generator -+ * that is the collation difference the environment could not supply, and+ * it is exactly what a differently-collating host would do to a+ * `localeCompare` tie-break.+ */+const COLLATION_CHILD = `+if (process.env["O2B_TEST_REVERSE_COLLATION"] === "1") {+ Object.defineProperty(String.prototype, "localeCompare", {+ value(other) { return other < this ? -1 : other > this ? 1 : 0; },+ configurable: true,+ writable: true,+ });+}+const { readFileSync } = await import("node:fs");+const { generateArchDocs } = await import(process.env["O2B_TEST_GENERATE"]);+const res = generateArchDocs(process.env["O2B_TEST_VAULT"], process.env["O2B_TEST_PROJECT"]);+process.stdout.write(readFileSync(res.overviewPath, "utf8"));+`;++function renderUnderCollation(locale: string, reversed: boolean): string {+ const childVault = join(tmp, `vault-${locale}-${reversed ? "rev" : "plain"}`);+ mkdirSync(join(childVault, "Brain"), { recursive: true });+ const child = Bun.spawnSync([process.execPath, "-e", COLLATION_CHILD], {+ env: {+ ...process.env,+ LC_ALL: locale,+ LANG: locale,+ O2B_TEST_REVERSE_COLLATION: reversed ? "1" : "0",+ O2B_TEST_GENERATE: join(import.meta.dir, "../../../src/core/brain/architect/generate.ts"),+ O2B_TEST_VAULT: childVault,+ O2B_TEST_PROJECT: project,+ },+ });+ const stderr = new TextDecoder().decode(child.stderr);+ expect({ locale, code: child.exitCode, stderr }).toEqual({ locale, code: 0, stderr: "" });+ return new TextDecoder().decode(child.stdout);+}++test("the language tie-break does not depend on the host collation", () => {+ // Equal counts, so ONLY the tie-break decides their order.+ seed("src/core/one.aaa");+ seed("src/core/two.aab");++ const plain = renderUnderCollation("C", false);+ const reversed = renderUnderCollation("tr_TR.UTF-8", true);++ expect(reversed).toBe(plain);+ expect(plain).toContain(".aaa (1)");+});++test("a corrupted note aborts the run before any note is written", () => {+ const first = generateArchDocs(vault, project);+ const cliNote = first.modulePaths.find((p) => p.endsWith("cli.md"))!;+ // Unbalanced sentinels: `mergeRegions` fails closed on this note.+ writeFileSync(cliNote, readFileSync(cliNote, "utf8").replace("<!-- o2b:end facts -->", ""));+ const overviewBefore = readFileSync(first.overviewPath, "utf8");+ seed("src/core/added.ts"); // the overview WOULD change++ expect(() => generateArchDocs(vault, project)).toThrow(RegionError);+ // The overview is written first, so a run that wrote as it went would+ // have left it updated next to a module note it could not repair.+ expect(readFileSync(first.overviewPath, "utf8")).toBe(overviewBefore);+});++/**+ * Planning removes the error class that arises while DECIDING a note's+ * bytes. It cannot remove the one that arises while PLACING them, and the+ * module docblock no longer claims otherwise: this is the mid-loop write+ * failure, and it does leave a refreshed prefix beside stale notes.+ *+ * The failure is injected with a real errno rather than a mocked writer -+ * `modules/` is made read-only, so `atomicWriteFileSync`'s temp file+ * cannot be created there. The overview lives one directory up and is+ * written first, so exactly one note is refreshed before the loop stops.+ */+test("a write that fails part-way through reports the prefix it already refreshed", () => {+ const first = generateArchDocs(vault, project);+ const coreNote = first.modulePaths.find((p) => p.endsWith("core.md"))!;+ const coreBefore = readFileSync(coreNote, "utf8");+ const overviewBefore = readFileSync(first.overviewPath, "utf8");+ seed("src/core/added.ts"); // overview.md AND core.md must both change++ chmodSync(join(first.dir, "modules"), 0o555);+ let caught: unknown = null;+ try {+ generateArchDocs(vault, project);+ } catch (error) {+ caught = error;+ }+ chmodSync(join(first.dir, "modules"), 0o755);++ expect(caught).toBeInstanceOf(ArchWriteError);+ const failure = caught as ArchWriteError;+ expect(failure.path).toBe(coreNote);+ // The overview is on disk; `core.md` and nothing after it are not.+ expect(failure.written).toBe(1);+ expect(failure.pending).toBe(1);+ expect(failure.message).toContain("re-run");+ expect(failure.cause).toBeDefined();++ // The half-refreshed tree the counts describe, observed directly.+ expect(readFileSync(first.overviewPath, "utf8")).not.toBe(overviewBefore);+ expect(readFileSync(coreNote, "utf8")).toBe(coreBefore);+ // A failed write is not a leaked lock.+ expect(existsSync(`${first.dir}.lock`)).toBe(false);++ // And the repair the message promises is real: with the cause gone, one+ // ordinary re-run rewrites the suffix the failure left stale.+ const repaired = generateArchDocs(vault, project);+ expect(repaired.updated).toBe(1);+ expect(readFileSync(coreNote, "utf8")).toContain("added.ts");+});++test("module_paths follows the scan's module order, not the write order", () => {+ const res = generateArchDocs(vault, project);+ const facts = scanProject(project);+ expect(res.modulePaths).toEqual(+ facts.modules.map((m) => join(res.dir, "modules", `${m.name}.md`)),+ );+});++test("the notes are written inside one lock, which is released afterwards", () => {+ const first = generateArchDocs(vault, project);+ const lockPath = `${first.dir}.lock`;+ seed("src/core/added.ts"); // force real writes on the second run++ // The sink runs inside the run, so it can see what the run is holding.+ const heldDuringWrites: boolean[] = [];+ const res = generateArchDocs(vault, project, {+ onProgress: (event) => {+ // `advanced` only: the stage is announced BEFORE the lock is+ // waited for, so a watcher sees "rendering" during the wait too.+ if (event.stage === ARCHITECT_STAGE.render && event.kind === PROGRESS_KIND.advanced) {+ heldDuringWrites.push(existsSync(lockPath));+ }+ },+ });++ expect(res.updated).toBeGreaterThan(0);+ expect(heldDuringWrites.length).toBeGreaterThan(0);+ expect(heldDuringWrites.every(Boolean)).toBe(true);+ expect(existsSync(lockPath)).toBe(false);+});+test("unchanged project regenerates byte-identically", () => {const first = generateArchDocs(vault, project);const before = readFileSync(first.overviewPath, "utf8");diff --git a/tests/core/brain/config-template-ratchet.test.ts b/tests/core/brain/config-template-ratchet.test.tsindex b30e592d..013f3d0c 100644--- a/tests/core/brain/config-template-ratchet.test.ts+++ b/tests/core/brain/config-template-ratchet.test.ts@@ -36,6 +36,7 @@ import {resolveHealth,resolveIntegrity,resolveLinkGraph,+ resolveMaintenance,resolveNotes,resolveSessions,resolveTemporal,@@ -155,8 +156,13 @@ function resolvedView(cfg: BrainConfig): Record<string, unknown> {},guardrails: resolveGuardrails(cfg),link_graph: resolveLinkGraph(cfg),+ maintenance: resolveMaintenance(cfg),temporal: resolveTemporal(cfg),health: resolveHealth(cfg),+ // Both keys are commented examples with no default, so this is+ // `undefined` on both sides - which is the claim: exposing them+ // changed no behaviour for any existing vault.+ embeddings: cfg.embeddings,integrity: resolveIntegrity(cfg),notes: resolveNotes(cfg),sessions: resolveSessions(cfg),diff --git a/tests/core/brain/doctor-exit-census.test.ts b/tests/core/brain/doctor-exit-census.test.tsindex 86e0112b..614d265b 100644--- a/tests/core/brain/doctor-exit-census.test.ts+++ b/tests/core/brain/doctor-exit-census.test.ts@@ -184,12 +184,14 @@ const DOCTOR_REGISTERED_CODES: ReadonlyArray<string> = ["contradictory-preferences","dangling-workrun","duplicate-preferences",+ "embedding-model-sunset-announced","entity-label-malformed","entity-quote-variant-collision","low-evidence-confirmed","orphan-evidence","principle-corrupted","recall-channel-silent",+ "recovery-point-stale","schema-version-unknown","stale-claim","stale-dependency",diff --git a/tests/core/brain/doctor-uncertain-surfaces.test.ts b/tests/core/brain/doctor-uncertain-surfaces.test.tsindex 82be4603..7adc3996 100644--- a/tests/core/brain/doctor-uncertain-surfaces.test.ts+++ b/tests/core/brain/doctor-uncertain-surfaces.test.ts@@ -95,6 +95,27 @@ describe("runDoctor — writer locks left on disk", () => {}});+ /**+ * The retry docblock tells an operator that a lock a crash left behind+ * is what `brain doctor` reports. For the two locks the parallel ingest+ * path takes most often that was untrue: both live in+ * `.open-second-brain/`, and the probe walked `Brain/` only, so the+ * doctor reported nothing with the lock plainly on disk.+ */+ test("a held lock under .open-second-brain/ is named with its path", () => {+ writeVaultIdentity(vault);+ const target = join(vault, ".open-second-brain", "ingest-manifest.json");+ mkdirSync(join(vault, ".open-second-brain"), { recursive: true });+ const handle = acquireLockSync(target);+ try {+ const entry = (runDoctor(vault).uncertain ?? []).find((u) => u.code === "stale-lock");+ expect(entry).toBeDefined();+ expect(entry!.path).toBe(handle.path);+ } finally {+ handle.release();+ }+ });+test("a vault with no locks reports none", () => {writeVaultIdentity(vault);expect(codes()).not.toContain("stale-lock");diff --git a/tests/core/brain/doctor/embedding-sunset-check.test.ts b/tests/core/brain/doctor/embedding-sunset-check.test.tsnew file mode 100644index 00000000..8d88028c--- /dev/null+++ b/tests/core/brain/doctor/embedding-sunset-check.test.ts@@ -0,0 +1,335 @@+/**+ * The doctor half of the sunset warning (t_e7a226ce).+ *+ * The classifier is tested next door; what this file pins is the check's+ * own judgements: which verdicts become a warning, which reach the+ * uncertain stream, which are silence, and that the message never claims+ * to name a vendor.+ *+ * The last one is not a style rule. The resolved `provider` is one of four+ * TRANSPORT kinds - `openai-compat` says nothing about whose endpoint it+ * is - and vendor identity exists only inside a free-form+ * `embedding_base_url` that nothing in the tree maps. A message naming a+ * vendor would be inferring it from a URL.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { DIAGNOSTIC_SIGNALS } from "../../../../src/core/brain/diagnostics.ts";+import type { DoctorCheckContext } from "../../../../src/core/brain/doctor/check.ts";+import {+ EMBEDDING_MODEL_SUNSET_ANNOUNCED_CODE,+ EMBEDDING_MODEL_SUNSET_UNDETERMINED_CODE,+ EMBEDDING_MODEL_SUNSET_UNSURVEYED_CODE,+ EMBEDDING_SUNSET_WARNING_WINDOW_DAYS,+ makeEmbeddingSunsetCheck,+} from "../../../../src/core/brain/doctor/embedding-sunset-check.ts";+import type { DoctorUncertainEntry } from "../../../../src/core/brain/doctor/report.ts";+import { DOCTOR_EXIT_EXCLUSIONS } from "../../../../src/core/brain/doctor-exits.ts";+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import { loadBrainConfig } from "../../../../src/core/brain/policy.ts";+import type { EmbeddingSunsetSurvey } from "../../../../src/core/search/embeddings/sunset.ts";+import { EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS } from "../../../../src/core/search/embeddings/sunset.ts";+import type { DoctorIssue } from "../../../../src/core/brain/types.ts";++const MS_PER_DAY = 24 * 60 * 60 * 1000;+const NOW = new Date("2026-06-01T00:00:00.000Z");+const MODEL = "vendor-x/embed-v1";++let vault: string;+let configHome: string;+let configPath: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-sunset-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-sunset-cfg-"));+ configPath = join(configHome, "config.yaml");+ bootstrapBrain(vault);+ configure(MODEL);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++/** Semantic search on, an openai-compatible endpoint, and `model`. */+function configure(model: string | null): void {+ const lines = [+ `vault: ${vault}`,+ `search_semantic_enabled: "true"`,+ `embedding_provider: "openai-compat"`,+ `embedding_base_url: "https://example.invalid/v1"`,+ ];+ if (model !== null) lines.push(`embedding_model: "${model}"`);+ writeFileSync(configPath, lines.join("\n") + "\n");+}++function surveyWith(sunsetAt: string | null): EmbeddingSunsetSurvey {+ return {+ reviewedAt: "2026-05-31",+ entries: [{ model: MODEL, sunsetAt, source: "unit fixture", note: "" }],+ };+}++interface RunResult {+ readonly issues: ReadonlyArray<DoctorIssue>;+ readonly uncertain: ReadonlyArray<DoctorUncertainEntry>;+}++function run(survey: EmbeddingSunsetSurvey, now: Date = NOW): RunResult {+ const issues: DoctorIssue[] = [];+ const uncertain: DoctorUncertainEntry[] = [];+ makeEmbeddingSunsetCheck(survey).run(+ { vault, now, configPath } as unknown as DoctorCheckContext,+ { issues, uncertain },+ );+ return { issues, uncertain };+}++/** Every code the run reported, on either stream. */+function reportedCodes(result: RunResult): ReadonlyArray<string> {+ return [...result.issues, ...result.uncertain].map((e) => e.code);+}++function announced(result: RunResult): ReadonlyArray<DoctorIssue> {+ return result.issues.filter((i) => i.code === EMBEDDING_MODEL_SUNSET_ANNOUNCED_CODE);+}++/** Days before `NOW`, as the `YYYY-MM-DD` a survey entry carries. */+function inDays(days: number): string {+ return new Date(NOW.getTime() + days * MS_PER_DAY).toISOString().slice(0, 10);+}++describe("a declared date inside the window is a warning naming model and date", () => {+ test("the warning carries both facts", () => {+ const date = inDays(EMBEDDING_SUNSET_WARNING_WINDOW_DAYS - 10);+ const issues = announced(run(surveyWith(date)));+ expect(issues.length).toBe(1);+ expect(issues[0]!.severity).toBe("warning");+ expect(issues[0]!.message).toContain(MODEL);+ expect(issues[0]!.message).toContain(date);+ });++ test("a date beyond the window is not yet a finding", () => {+ const date = inDays(EMBEDDING_SUNSET_WARNING_WINDOW_DAYS + 30);+ const result = run(surveyWith(date));+ expect(announced(result)).toEqual([]);+ expect(result.uncertain).toEqual([]);+ });++ test("a date already past is still the warning", () => {+ const issues = announced(run(surveyWith(inDays(-5))));+ expect(issues.length).toBe(1);+ });++ test("the message never claims to name a vendor", () => {+ const message = announced(run(surveyWith(inDays(10))))[0]!.message;+ // The four transport kinds and the base URL are all things the check+ // COULD have reached for and must not present as a vendor identity.+ for (const forbidden of ["openai-compat", "zeroentropy", "example.invalid"]) {+ expect(`${forbidden} in message: ${message.includes(forbidden)}`).toBe(+ `${forbidden} in message: false`,+ );+ }+ });+});++describe("the SHIPPED survey reaches the warning, with no fixture", () => {+ test("a first-generation OpenAI model warns that it is already gone", () => {+ configure("text-search-ada-doc-001");+ const issues: DoctorIssue[] = [];+ const uncertain: DoctorUncertainEntry[] = [];+ // `makeEmbeddingSunsetCheck()` with no argument: the real table.+ makeEmbeddingSunsetCheck().run(+ { vault, now: NOW, configPath } as unknown as DoctorCheckContext,+ {+ issues,+ uncertain,+ },+ );+ const issue = issues.find((i) => i.code === EMBEDDING_MODEL_SUNSET_ANNOUNCED_CODE);+ expect(issue).toBeDefined();+ expect(issue!.message).toContain("text-search-ada-doc-001");+ expect(issue!.message).toContain("2024-01-04");+ });+});++describe("a model unknown to the survey is distinguishable from a clean one", () => {+ test("unsurveyed reaches the uncertain stream under its own code", () => {+ const result = run({ reviewedAt: "2026-05-31", entries: [] });+ expect(announced(result)).toEqual([]);+ const entry = result.uncertain.find((e) => e.code === EMBEDDING_MODEL_SUNSET_UNSURVEYED_CODE);+ expect(entry).toBeDefined();+ expect(entry!.message).toContain(MODEL);+ });++ test("a surveyed model with no announcement produces nothing at all", () => {+ const result = run(surveyWith(null));+ expect(result.issues).toEqual([]);+ expect(result.uncertain).toEqual([]);+ });++ test("the two states never share a code", () => {+ const unknown = run({ reviewedAt: "2026-05-31", entries: [] });+ const clean = run(surveyWith(null));+ expect(reportedCodes(unknown)).not.toEqual(reportedCodes(clean));+ });+});++describe("what the check cannot establish reaches the uncertain stream", () => {+ test("a stale survey stops the negative being reported as clean", () => {+ const survey = surveyWith(null);+ const late = new Date(+ Date.parse(`${survey.reviewedAt}T00:00:00Z`) ++ (EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS + 1) * MS_PER_DAY,+ );+ const result = run(survey, late);+ expect(result.uncertain.some((e) => e.code === EMBEDDING_MODEL_SUNSET_UNDETERMINED_CODE)).toBe(+ true,+ );+ });++ test("a survey entry this build cannot parse reaches the operator as a table defect", () => {+ // The producer of `survey_entry_malformed` is the SHIPPED table going+ // wrong, and the survey is injectable at this factory precisely so a+ // release that mistypes a date is caught here rather than reported to+ // an operator as "no announcement". A shipped table that parses today+ // is pinned separately (`embeddings.sunset.test.ts`); this pins what+ // happens when one does not.+ const result = run(surveyWith("2027-13-45"));+ const entry = result.uncertain.find((e) => e.code === EMBEDDING_MODEL_SUNSET_UNDETERMINED_CODE);+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("defect in the shipped table");+ expect(entry!.message).toContain(MODEL);+ });++ test("semantic search enabled with no model resolved is uncertain", () => {+ configure(null);+ const result = run(surveyWith(null));+ expect(result.uncertain.some((e) => e.code === EMBEDDING_MODEL_SUNSET_UNDETERMINED_CODE)).toBe(+ true,+ );+ });++ test("semantic search switched off says nothing - there is no model in use", () => {+ writeFileSync(configPath, `vault: ${vault}\nsearch_semantic_enabled: "false"\n`);+ const result = run(surveyWith(inDays(1)));+ expect(result.issues).toEqual([]);+ expect(result.uncertain).toEqual([]);+ });+});++describe("an operator declaration layers over the survey, end to end", () => {+ /**+ * Write a `_brain.yaml` declaring `sunsetAt` for `model`.+ *+ * NOT named `declare`: that is a TypeScript contextual keyword, and a+ * call to a helper of that name is silently swallowed at statement+ * position rather than reported - the test passed its setup and then+ * asserted against a vault nothing had been written to.+ */+ function declareSunset(model: string, sunsetAt: string): void {+ const path = join(vault, "Brain", "_brain.yaml");+ writeFileSync(+ path,+ `schema_version: 1\nembeddings:\n sunset_model: "${model}"\n sunset_at: "${sunsetAt}"\n`,+ );+ }++ /** Run with the real `_brain.yaml` resolved onto the context. */+ function runWithConfig(survey: EmbeddingSunsetSurvey, now: Date = NOW): RunResult {+ const issues: DoctorIssue[] = [];+ const uncertain: DoctorUncertainEntry[] = [];+ makeEmbeddingSunsetCheck(survey).run(+ {+ vault,+ now,+ configPath,+ config: loadBrainConfig(vault),+ } as unknown as DoctorCheckContext,+ { issues, uncertain },+ );+ return { issues, uncertain };+ }++ test("a declaration warns for a model the survey never heard of", () => {+ const date = inDays(EMBEDDING_SUNSET_WARNING_WINDOW_DAYS - 5);+ declareSunset(MODEL, date);+ const issues = announced(runWithConfig({ reviewedAt: "2026-05-31", entries: [] }));+ expect(issues.length).toBe(1);+ expect(issues[0]!.message).toContain(date);+ expect(issues[0]!.message).toContain("sunset_at");+ });++ test("a declaration OUTRANKS a survey row, and the disagreement is printed", () => {+ const declared = inDays(EMBEDDING_SUNSET_WARNING_WINDOW_DAYS - 5);+ const surveyed = inDays(EMBEDDING_SUNSET_WARNING_WINDOW_DAYS - 40);+ declareSunset(MODEL, declared);+ const issues = announced(runWithConfig(surveyWith(surveyed)));+ expect(issues.length).toBe(1);+ // Both dates are on the line: one of the two records is out of date+ // and a silent override is how the wrong one survives.+ expect(issues[0]!.message).toContain(declared);+ expect(issues[0]!.message).toContain(surveyed);+ });++ test("the SURVEY still answers when the declaration names another model", () => {+ const surveyed = inDays(EMBEDDING_SUNSET_WARNING_WINDOW_DAYS - 40);+ declareSunset("some-other/model", inDays(1));+ const issues = announced(runWithConfig(surveyWith(surveyed)));+ expect(issues.length).toBe(1);+ expect(issues[0]!.message).toContain(surveyed);+ });++ test("a malformed declared date never reaches the check at all", () => {+ // Why the classifier has no `declaration_malformed` verdict: the+ // config layer refuses the value at load time, naming the key, so the+ // operator meets this as a config error rather than as a doctor line+ // - and no vault can hand the classifier a date it cannot parse.+ declareSunset(MODEL, "next tuesday");+ expect(() => loadBrainConfig(vault)).toThrow(/sunset_at/);+ });++ test("a declaration turns a surveyed negative into a warning", () => {+ // The layer only ever ADDS a positive; the survey's own three answers+ // are untouched when nothing is declared.+ expect(announced(runWithConfig(surveyWith(null)))).toEqual([]);+ declareSunset(MODEL, inDays(10));+ expect(announced(runWithConfig(surveyWith(null))).length).toBe(1);+ });+});++describe("the clock is injected, never read", () => {+ test("two clocks over one configuration give two verdicts", () => {+ const survey = surveyWith(inDays(EMBEDDING_SUNSET_WARNING_WINDOW_DAYS + 30));+ const early = run(survey, NOW);+ const late = run(survey, new Date(NOW.getTime() + 60 * MS_PER_DAY));+ expect(announced(early)).toEqual([]);+ expect(announced(late).length).toBe(1);+ });+});++describe("every code is classified exactly once", () => {+ test("the warning code carries a registered command", () => {+ expect(DIAGNOSTIC_SIGNALS.has(EMBEDDING_MODEL_SUNSET_ANNOUNCED_CODE)).toBe(true);+ expect(DOCTOR_EXIT_EXCLUSIONS.has(EMBEDDING_MODEL_SUNSET_ANNOUNCED_CODE)).toBe(false);+ });++ test("both uncertain codes carry a written reason instead", () => {+ for (const code of [+ EMBEDDING_MODEL_SUNSET_UNSURVEYED_CODE,+ EMBEDDING_MODEL_SUNSET_UNDETERMINED_CODE,+ ]) {+ expect(`${code} excluded: ${DOCTOR_EXIT_EXCLUSIONS.has(code)}`).toBe(+ `${code} excluded: true`,+ );+ expect(`${code} registered: ${DIAGNOSTIC_SIGNALS.has(code)}`).toBe(+ `${code} registered: false`,+ );+ }+ });+});diff --git a/tests/core/brain/doctor/recovery-point-liveness.test.ts b/tests/core/brain/doctor/recovery-point-liveness.test.tsnew file mode 100644index 00000000..50eec564--- /dev/null+++ b/tests/core/brain/doctor/recovery-point-liveness.test.ts@@ -0,0 +1,255 @@+/**+ * A durability check that reports LIVENESS, and says so.+ *+ * The obvious shape - "is the durability job registered, and did it run" -+ * has no referent in this product. Nothing here registers a scheduled job:+ * every cron surface in the tree is a recipe RENDERER that prints text for+ * the operator's own scheduler and writes nothing, so there is no record+ * whose presence could be looked up. Presence is therefore unobservable,+ * and the only thing that can be measured is the age of the artifacts a+ * durability pass leaves behind.+ *+ * That is not a limitation to be papered over - a check that reported+ * "durability job missing" would be inventing a fact - so it is stated in+ * the finding's own message, and this file asserts that it is.+ *+ * The three states the check can be in are the three answers+ * `listSnapshots` already distinguishes: an absent directory is an empty+ * history (a real answer), a populated one is a measurable one, and a+ * directory that IS there and cannot be enumerated is neither.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ chmodSync,+ mkdirSync,+ mkdtempSync,+ rmSync,+ symlinkSync,+ utimesSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { DIAGNOSTIC_SIGNALS } from "../../../../src/core/brain/diagnostics.ts";+import type { DoctorCheckContext } from "../../../../src/core/brain/doctor/check.ts";+import type { DoctorUncertainEntry } from "../../../../src/core/brain/doctor/report.ts";+import {+ RECOVERY_POINT_LIVENESS_WINDOW_DAYS,+ RECOVERY_POINT_STALE_CODE,+ RECOVERY_POINT_UNMEASURED_CODE,+ recoveryPointLivenessCheck,+ SCHEDULE_UNOBSERVABLE_CLAUSE,+} from "../../../../src/core/brain/doctor/recovery-point-liveness.ts";+import { DOCTOR_EXIT_EXCLUSIONS } from "../../../../src/core/brain/doctor-exits.ts";+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";+import { SNAPSHOT_ARCHIVE_SUFFIX, snapshotsDir } from "../../../../src/core/brain/paths.ts";+import type { DoctorIssue } from "../../../../src/core/brain/types.ts";++let vault: string;++/** Pinned so every age below is arithmetic rather than wall clock. */+const NOW = new Date("2026-06-01T00:00:00.000Z");+const MS_PER_DAY = 24 * 60 * 60 * 1000;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-recovery-liveness-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ try {+ chmodSync(snapshotsDir(vault), 0o700);+ } catch {+ // The directory may never have been created; nothing to restore.+ }+ rmSync(vault, { recursive: true, force: true });+});++/** An archive named `runId`, stamped `daysAgo` before the pinned clock. */+function archive(runId: string, daysAgo: number): void {+ const dir = snapshotsDir(vault);+ mkdirSync(dir, { recursive: true });+ const path = join(dir, `${runId}${SNAPSHOT_ARCHIVE_SUFFIX}`);+ writeFileSync(path, "not-a-real-archive");+ const at = new Date(NOW.getTime() - daysAgo * MS_PER_DAY);+ utimesSync(path, at, at);+}++interface RunResult {+ readonly issues: ReadonlyArray<DoctorIssue>;+ readonly uncertain: ReadonlyArray<DoctorUncertainEntry>;+}++function run(now: Date = NOW): RunResult {+ const issues: DoctorIssue[] = [];+ const uncertain: DoctorUncertainEntry[] = [];+ recoveryPointLivenessCheck.run({ vault, now } as unknown as DoctorCheckContext, {+ issues,+ uncertain,+ });+ return { issues, uncertain };+}++function stale(result: RunResult): ReadonlyArray<DoctorIssue> {+ return result.issues.filter((i) => i.code === RECOVERY_POINT_STALE_CODE);+}++describe("recovery-point liveness", () => {+ test("the check never fails the pass", () => {+ expect(recoveryPointLivenessCheck.failSoft).toBe(true);+ });++ test("a vault with no recovery point at all reports nothing", () => {+ // No archive exists because no state-changing pass has ever run.+ // There is no schedule to have missed and no artifact to be stale,+ // so inventing a finding here would be inventing the expectation.+ const result = run();+ expect(stale(result)).toEqual([]);+ expect(result.uncertain).toEqual([]);+ });++ test("a recent recovery point is clean", () => {+ archive("dream-20260530T000000Z", 2);+ const result = run();+ expect(stale(result)).toEqual([]);+ expect(result.uncertain).toEqual([]);+ });++ test("a recovery point older than the window is a warning naming its age", () => {+ const age = RECOVERY_POINT_LIVENESS_WINDOW_DAYS + 7;+ archive("dream-20260101T000000Z", age);+ const issues = stale(run());+ expect(issues.length).toBe(1);+ expect(issues[0]!.severity).toBe("warning");+ expect(issues[0]!.message).toContain(String(age));+ expect(issues[0]!.message).toContain(String(RECOVERY_POINT_LIVENESS_WINDOW_DAYS));+ });++ test("the warning states that schedule PRESENCE was not checked", () => {+ archive("dream-20260101T000000Z", RECOVERY_POINT_LIVENESS_WINDOW_DAYS + 1);+ // The whole reason the check reports liveness only: nothing in this+ // tool registers a scheduled job, so a silent schedule and no+ // schedule at all leave identical evidence. The finding says so+ // rather than letting the reader assume it checked.+ expect(stale(run())[0]!.message).toContain(SCHEDULE_UNOBSERVABLE_CLAUSE);+ });++ test("the NEWEST recovery point decides, not the oldest", () => {+ archive("dream-20260101T000000Z", RECOVERY_POINT_LIVENESS_WINDOW_DAYS + 100);+ archive("dream-20260531T000000Z", 1);+ expect(stale(run())).toEqual([]);+ });++ test("a history whose ONLY archive cannot be stat'ed is uncertain, not an empty history", () => {+ // The directory is populated and enumerable; the archive inside it is+ // not readable by this user - the shape a vault synced with preserved+ // ownership takes. Reporting "no state-changing pass has ever run"+ // here is the silence this check exists to remove.+ const dir = snapshotsDir(vault);+ mkdirSync(dir, { recursive: true });+ symlinkSync(join(dir, "nothing-here.tar.zst"), join(dir, `dangling${SNAPSHOT_ARCHIVE_SUFFIX}`));++ const result = run();+ expect(stale(result)).toEqual([]);+ const entry = result.uncertain.find((e) => e.code === RECOVERY_POINT_UNMEASURED_CODE);+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("dangling");+ expect(entry!.message).toContain(SCHEDULE_UNOBSERVABLE_CLAUSE);+ });++ test("an unreadable archive beside a readable one is reported alongside the age", () => {+ // The measured age is the newest READABLE archive's, and the entry+ // nobody could stat may be newer - so the number is an upper bound and+ // the reader is told the listing was partial.+ archive("dream-20260531T000000Z", 1);+ const dir = snapshotsDir(vault);+ symlinkSync(join(dir, "nothing-here.tar.zst"), join(dir, `dangling${SNAPSHOT_ARCHIVE_SUFFIX}`));++ const result = run();+ const entry = result.uncertain.find((e) => e.code === RECOVERY_POINT_UNMEASURED_CODE);+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("dangling");+ });++ test("an archive whose run id does not validate is named, not swallowed", () => {+ const dir = snapshotsDir(vault);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, `not a run id!${SNAPSHOT_ARCHIVE_SUFFIX}`), "x");++ const result = run();+ const entry = result.uncertain.find((e) => e.code === RECOVERY_POINT_UNMEASURED_CODE);+ expect(entry).toBeDefined();+ expect(entry!.message).toContain("not a run id!");+ });++ test("a file in the directory that is not an archive at all is not a skipped entry", () => {+ // A sidecar manifest, a store archive, or an operator's stray note is+ // not a recovery point that could not be read - it is not a recovery+ // point. Reporting it would train the reader to ignore the code.+ archive("dream-20260531T000000Z", 1);+ writeFileSync(join(snapshotsDir(vault), "README.txt"), "mine");+ expect(run().uncertain).toEqual([]);+ });++ test("an unreadable snapshots directory is uncertain, never clean and never stale", () => {+ archive("dream-20260101T000000Z", RECOVERY_POINT_LIVENESS_WINDOW_DAYS + 7);+ chmodSync(snapshotsDir(vault), 0o000);++ const result = run();+ expect(stale(result)).toEqual([]);+ const entry = result.uncertain.find((e) => e.code === RECOVERY_POINT_UNMEASURED_CODE);+ expect(entry).toBeDefined();+ expect(entry!.message).toContain(SCHEDULE_UNOBSERVABLE_CLAUSE);+ });+});++describe("the verdict comes from the injected clock, never from the wall", () => {+ test("two clocks over one vault give two answers", () => {+ archive("dream-20260501T000000Z", 1);+ // Same archive, same vault: only the clock moves.+ const early = run(NOW);+ const late = run(+ new Date(NOW.getTime() + (RECOVERY_POINT_LIVENESS_WINDOW_DAYS + 5) * MS_PER_DAY),+ );+ expect(stale(early)).toEqual([]);+ expect(stale(late).length).toBe(1);+ });++ test("the module reads no global clock", () => {+ // Asserted structurally rather than by timing: a `Date.now()` here+ // would pass every test above while making the check unpinnable.+ const source = Bun.file(+ join(+ import.meta.dir,+ "..",+ "..",+ "..",+ "..",+ "src",+ "core",+ "brain",+ "doctor",+ "recovery-point-liveness.ts",+ ),+ );+ return source.text().then((text) => {+ const code = text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");+ expect(code.includes("Date.now(")).toBe(false);+ expect(code.includes("new Date()")).toBe(false);+ });+ });+});++describe("both codes are classified exactly once", () => {+ test("the stale code carries a registered command", () => {+ expect(DIAGNOSTIC_SIGNALS.has(RECOVERY_POINT_STALE_CODE)).toBe(true);+ expect(DOCTOR_EXIT_EXCLUSIONS.has(RECOVERY_POINT_STALE_CODE)).toBe(false);+ });++ test("the unmeasured code carries a written reason instead", () => {+ expect(DOCTOR_EXIT_EXCLUSIONS.has(RECOVERY_POINT_UNMEASURED_CODE)).toBe(true);+ expect(DIAGNOSTIC_SIGNALS.has(RECOVERY_POINT_UNMEASURED_CODE)).toBe(false);+ });+});diff --git a/tests/core/brain/dream-progress.test.ts b/tests/core/brain/dream-progress.test.tsnew file mode 100644index 00000000..bb458b58--- /dev/null+++ b/tests/core/brain/dream-progress.test.ts@@ -0,0 +1,201 @@+/**+ * A consolidation pass reports while it runs (nothing-runs-unwatched, U1).+ *+ * Before this, `dream` produced its first observable output after it had+ * already finished, so a caller could not tell a slow pass from a hung+ * one. The properties pinned here are the ones that make the stream worth+ * having: it starts, it advances, it terminates, and a run that changed+ * nothing terminates too - an idempotent rerun is the common case, and an+ * unterminated stream would make it look like a pass that died in+ * planning.+ *+ * The last test is the load-bearing one for the rest of the release: a+ * pass with no sink attached must be byte-identical to the previous+ * release. Absence of an observer is not a feature flag.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { cpSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { dream } from "../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import {+ PROGRESS_KIND,+ PROGRESS_REASON,+ type ProgressEvent,+} from "../../../src/core/brain/progress.ts";+import {+ createSafeguard,+ OPERATION,+ SafeguardAbortError,+} from "../../../src/core/brain/safeguard.ts";+import { writeSignal } from "../../../src/core/brain/signal.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import { digestVaultFiles, digestVaultTree } from "../../helpers/vault-digest.ts";++let vault: string;+let configHome: string;+let configPath: string;++const NOW = new Date("2026-05-23T12:00:00Z");++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-progress-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-dream-progress-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++/** Three same-sign signals on one topic: enough to plan a promotion. */+function seedPromotion(topic = "progress-topic"): void {+ for (const [i, date] of ["2026-05-20", "2026-05-21", "2026-05-22"].entries()) {+ writeSignal(vault, {+ topic,+ signal: "positive",+ agent: "claude",+ principle: `Prefer the ${topic} approach`,+ created_at: `${date}T10:00:00Z`,+ date,+ slug: `${topic}-${i}`,+ scope: "writing",+ });+ }+}++function record(): { events: ProgressEvent[]; sink: (e: ProgressEvent) => void } {+ const events: ProgressEvent[] = [];+ return { events, sink: (e) => events.push(e) };+}++describe("dream progress", () => {+ test("a changing run starts, advances through its stages, and finishes", () => {+ seedPromotion();+ const { events, sink } = record();++ dream(vault, { now: NOW, onProgress: sink });++ expect(events.length).toBeGreaterThan(0);+ expect(events.every((e) => e.operation === OPERATION.dream)).toBe(true);+ expect(events[0]?.kind).toBe(PROGRESS_KIND.started);+ expect(events.at(-1)?.kind).toBe(PROGRESS_KIND.finished);++ // Every stage the pass declares must actually be entered, in order,+ // or the stream is describing a pass that did not happen.+ const started = events.filter((e) => e.kind === PROGRESS_KIND.started).map((e) => e.stage);+ expect(started).toEqual(["scan", "plan", "apply", "log", "finalize"]);+ });++ test("a no-op rerun still terminates its stream", () => {+ seedPromotion();+ dream(vault, { now: NOW });++ const { events, sink } = record();+ dream(vault, { now: NOW, onProgress: sink });++ expect(events.at(-1)?.kind).toBe(PROGRESS_KIND.finished);+ });++ test("a dry run reports progress and still writes nothing", () => {+ seedPromotion();+ const before = digestVaultTree(vault);++ const { events, sink } = record();+ dream(vault, { now: NOW, dryRun: true, onProgress: sink });++ expect(events.at(-1)?.kind).toBe(PROGRESS_KIND.finished);+ expect(digestVaultTree(vault)).toEqual(before);+ });++ test("attaching an observer changes nothing the pass writes", () => {+ // Compared against a COPY of the same seeded vault rather than a+ // second bootstrap: a freshly bootstrapped vault carries its own+ // identity and its own root path inside `Brain/vault-id.json` and+ // `Brain/_BRAIN.md`, so two independent vaults differ before either+ // pass runs. The copy makes the comparison legitimate - identical+ // bytes in, so any difference out belongs to the observer.+ seedPromotion();+ const observed = mkdtempSync(join(tmpdir(), "o2b-dream-progress-b-"));+ try {+ cpSync(vault, observed, { recursive: true });++ const silent = dream(vault, { now: NOW });+ const { events, sink } = record();+ const watched = dream(observed, { now: NOW, onProgress: sink });++ expect(events.length).toBeGreaterThan(0);+ expect(watched.changed).toBe(silent.changed);+ // Two exclusions, each for a reason that predates this unit and is+ // not about the observer:+ // - the pre-run archive is a tar, and a tar carries the mtimes of+ // the tree it was taken from, which the harness wrote at two+ // different instants;+ // - the workrun journal stamps `new Date().toISOString()` per+ // line even when the caller injected a clock, because it is+ // forensic evidence of when the pass really ran.+ // Everything else the pass authored is compared.+ const EXCLUDED_PREFIXES = ["Brain/.snapshots/", "Brain/log/dream-runs/"];+ const authored = (root: string): Map<string, string> => {+ const kept = new Map<string, string>();+ for (const [path, digest] of digestVaultFiles(root)) {+ if (!EXCLUDED_PREFIXES.some((prefix) => path.startsWith(prefix))) kept.set(path, digest);+ }+ return kept;+ };+ expect(authored(observed)).toEqual(authored(vault));+ } finally {+ rmSync(observed, { recursive: true, force: true });+ }+ });++ test("a pre-aborted signal stops the pass and says so on the stream", () => {+ // SafeguardAbortError was unreachable in production before this+ // release: the class, the signal field and the abort-beats-deadline+ // priority were all written, and no call site passed a signal. This+ // is the test that proves the wiring, and it does it without racing a+ // real interrupt against a sub-second pass.+ seedPromotion();+ const controller = new AbortController();+ controller.abort();+ const { events, sink } = record();++ expect(() =>+ dream(vault, {+ now: NOW,+ onProgress: sink,+ safeguard: createSafeguard({ operation: OPERATION.dream, signal: controller.signal }),+ }),+ ).toThrow(SafeguardAbortError);++ // The stream must end with a stop, not simply end: a caller cannot+ // otherwise tell a cancelled pass from a crashed or hung one.+ expect(events.at(-1)).toMatchObject({+ kind: PROGRESS_KIND.stopped,+ reason: PROGRESS_REASON.aborted,+ });+ });++ test("a sink that throws does not fail the pass, and does not vanish either", () => {+ seedPromotion();+ let calls = 0;+ const summary = dream(vault, {+ now: NOW,+ onProgress: () => {+ calls += 1;+ throw new Error("stream closed");+ },+ });+ expect(summary.changed).toBe(true);+ // Detached after the first failure: a stream that fails on the first+ // tick would otherwise fail on every one.+ expect(calls).toBe(1);+ expect(summary.warnings.map((w) => w.code)).toContain("progress-sink-failed");+ });+});diff --git a/tests/core/brain/entities.label-hygiene.test.ts b/tests/core/brain/entities.label-hygiene.test.tsindex 3393474b..956f9a61 100644--- a/tests/core/brain/entities.label-hygiene.test.ts+++ b/tests/core/brain/entities.label-hygiene.test.ts@@ -136,7 +136,7 @@ describe("pruneEntityLabels", () => {expect(result.removed).toEqual([]);expect(result.snapshotRunId).toBeNull();expect(existsSync(junkPath)).toBe(true);- expect(listSnapshots(vault)).toHaveLength(0);+ expect(listSnapshots(vault).snapshots).toHaveLength(0);});test("confirm removes the node and its edges behind a snapshot, doctor-clean", () => {@@ -154,7 +154,7 @@ describe("pruneEntityLabels", () => {// Node file gone, snapshot recovery point written.expect(existsSync(junkPath)).toBe(false);- expect(listSnapshots(vault).length).toBeGreaterThan(0);+ expect(listSnapshots(vault).snapshots.length).toBeGreaterThan(0);// No orphaned references remain: the inbound edge was stripped, so the// doctor reports neither a broken relation nor a malformed-label lint.@@ -169,7 +169,7 @@ describe("pruneEntityLabels", () => {const result = pruneEntityLabels(vault, { confirm: true, now: NOW });expect(result.confirmed).toBe(false);expect(result.removed).toEqual([]);- expect(listSnapshots(vault)).toHaveLength(0);+ expect(listSnapshots(vault).snapshots).toHaveLength(0);});});diff --git a/tests/core/brain/ingest/concurrent-shared-writes.test.ts b/tests/core/brain/ingest/concurrent-shared-writes.test.tsnew file mode 100644index 00000000..ea7cf782--- /dev/null+++ b/tests/core/brain/ingest/concurrent-shared-writes.test.ts@@ -0,0 +1,264 @@+/**+ * The ingest path's read-modify-writes, driven by genuinely concurrent+ * processes (U7 of "nothing runs unwatched").+ *+ * `updateManifest`, `recordCompleted` and `appendGitRecords` each read a+ * shared file, merge one source's result into it, and write the whole thing+ * back. The batch planner exists so a caller dispatches each batch as a+ * PARALLEL SUBAGENT (`src/core/brain/ingest/batch-plan.ts:9-11`), so those+ * read-modify-writes overlap across processes by design.+ *+ * Atomicity is not exclusivity: `atomicWriteFileSync` renames a temp file into+ * place, which guarantees no reader sees a torn file and guarantees nothing+ * about a second writer that read the same "before" state+ * (`src/core/fs-atomic.ts:49-50`). Only a lock prevents the lost update.+ *+ * These tests spawn real `bun` children rather than simulating contention -+ * the same discipline as `tests/core/brain/lineage-ledger-integrity.test.ts`.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ checkpointPath,+ readCheckpoint,+ recordCompleted,+} from "../../../../src/core/brain/ingest/checkpoint.ts";+import {+ manifestPath,+ readManifest,+ writeManifestAtomic,+} from "../../../../src/core/brain/ingest/content-manifest.ts";+import { appendGitRecords, listGitCommits } from "../../../../src/core/brain/git/store.ts";+import {+ acquireLockSync,+ acquireLockSyncWithRetry,+} from "../../../../src/core/brain/sync-lockfile.ts";++const WRITERS = 4;+const PER_WRITER = 25;+const SEED_ENTRIES = 400;+const SPAWN_TIMEOUT_MS = 60_000;++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-ingest-race-"));+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++/** Absolute path of a module under `src/`, for a spawned child's import. */+function srcModule(rel: string): string {+ return join(import.meta.dir, "../../../../src", rel);+}++/**+ * Milliseconds the children wait before starting work. `bun` startup alone+ * staggers four processes by more than a read-modify-write takes, which would+ * serialize them by accident; the barrier makes the overlap real.+ */+const BARRIER_LEAD_MS = 1_500;++/**+ * Preamble every child script starts with: parse argv and spin until the+ * shared start instant so all four enter the critical section together.+ */+const BARRIER_PREAMBLE: ReadonlyArray<string> = Object.freeze([+ "const [vault, tag, count, startAt] = process.argv.slice(2);",+ "while (Date.now() < Number(startAt)) Bun.sleepSync(1);",+]);++/** Write a child script and run `WRITERS` copies of it concurrently. */+async function runWriters(scriptName: string, lines: readonly string[]): Promise<void> {+ const script = join(vault, scriptName);+ writeFileSync(script, [...BARRIER_PREAMBLE, ...lines].join("\n"), "utf8");+ const startAt = String(Date.now() + BARRIER_LEAD_MS);+ const procs = Array.from({ length: WRITERS }, (_, index) =>+ Bun.spawn(["bun", script, vault, `w${index}`, String(PER_WRITER), startAt], {+ stdout: "pipe",+ stderr: "pipe",+ }),+ );+ const failures: string[] = [];+ await Promise.all(+ procs.map(async (proc) => {+ const err = await new Response(proc.stderr).text();+ const code = await proc.exited;+ if (code !== 0) failures.push(`exit ${code}: ${err.trim()}`);+ }),+ );+ expect(failures).toEqual([]);+}++describe("updateManifest — concurrent writers", () => {+ test(+ "every source's content hash survives a four-process race",+ async () => {+ // A manifest big enough that the read-merge-write window is wide.+ const seeded: Record<string, string> = {};+ for (let i = 0; i < SEED_ENTRIES; i++) {+ seeded[`sources/seed-${i}.md`] = "0".repeat(64);+ }+ writeManifestAtomic(vault, seeded);++ const expected: string[] = [];+ for (let w = 0; w < WRITERS; w++) {+ for (let i = 0; i < PER_WRITER; i++) {+ const rel = `sources/w${w}-${i}.md`;+ mkdirSync(join(vault, "sources"), { recursive: true });+ writeFileSync(join(vault, rel), `body ${w}-${i}`, "utf8");+ expected.push(rel);+ }+ }++ await runWriters("manifest-writer.ts", [+ `import { updateManifest } from ${JSON.stringify(srcModule("core/brain/ingest/content-manifest.ts"))};`,+ "for (let i = 0; i < Number(count); i++) {",+ " updateManifest(vault, [`sources/${tag}-${i}.md`]);",+ "}",+ ]);++ const entries = readManifest(vault).entries;+ const missing = expected.filter((rel) => entries[rel] === undefined);+ expect(missing).toEqual([]);+ // The seeded entries are untouched by a merge that only names new paths.+ expect(Object.keys(entries).length).toBe(SEED_ENTRIES + WRITERS * PER_WRITER);+ // No lock file is left behind by a clean run.+ expect(existsSync(`${manifestPath(vault)}.lock`)).toBe(false);+ },+ SPAWN_TIMEOUT_MS,+ );+});++describe("recordCompleted — concurrent writers", () => {+ const PLAN_ID = "0123456789abcdef";++ test(+ "every completed item survives a four-process race",+ async () => {+ const seed: string[] = [];+ for (let i = 0; i < SEED_ENTRIES; i++) seed.push(`sources/seed-${i}.md`);+ recordCompleted(vault, PLAN_ID, "sources", seed, new Date("2026-08-15T00:00:00Z"));++ const expected: string[] = [];+ for (let w = 0; w < WRITERS; w++) {+ for (let i = 0; i < PER_WRITER; i++) expected.push(`sources/w${w}-${i}.md`);+ }++ await runWriters("checkpoint-writer.ts", [+ `import { recordCompleted } from ${JSON.stringify(srcModule("core/brain/ingest/checkpoint.ts"))};`,+ "for (let i = 0; i < Number(count); i++) {",+ ` recordCompleted(vault, ${JSON.stringify(PLAN_ID)}, "sources", [\`sources/\${tag}-\${i}.md\`], new Date());`,+ "}",+ ]);++ const checkpoint = readCheckpoint(vault, PLAN_ID);+ expect(checkpoint).not.toBeNull();+ const completed = new Set(checkpoint!.completed);+ const missing = expected.filter((rel) => !completed.has(rel));+ expect(missing).toEqual([]);+ expect(completed.size).toBe(SEED_ENTRIES + WRITERS * PER_WRITER);+ expect(existsSync(`${checkpointPath(vault, PLAN_ID)}.lock`)).toBe(false);+ },+ SPAWN_TIMEOUT_MS,+ );+});++/** A 40-hex sha derived from a writer tag and an index. */+function sha(tag: string, index: number): string {+ return `${tag}${index}`+ .padEnd(40, "0")+ .slice(0, 40)+ .replace(/[^0-9a-f]/g, "a");+}++describe("appendGitRecords — concurrent writers", () => {+ const REPO_KEY = "race-repo";+ /** Every writer tries to append this one; dedup must let exactly one land. */+ const SHARED_SHA = "f".repeat(40);++ test(+ "no record is lost and the shared sha is not duplicated",+ async () => {+ const seeded = Array.from({ length: SEED_ENTRIES }, (_, i) => ({+ kind: "commit" as const,+ sha: sha("seed", i),+ authorName: "seed",+ authorEmail: "[email protected]",+ committedAt: "2026-01-01T00:00:00Z",+ subject: `seed ${i}`,+ body: "",+ files: [],+ release: null,+ }));+ appendGitRecords(vault, REPO_KEY, seeded);++ await runWriters("git-writer.ts", [+ `import { appendGitRecords } from ${JSON.stringify(srcModule("core/brain/git/store.ts"))};`,+ `const shaFor = (t, i) => \`\${t}\${i}\`.padEnd(40, "0").slice(0, 40).replace(/[^0-9a-f]/g, "a");`,+ "for (let i = 0; i < Number(count); i++) {",+ ` appendGitRecords(vault, ${JSON.stringify(REPO_KEY)}, [`,+ " { kind: 'commit', sha: shaFor(tag, i), authorName: tag, authorEmail: '[email protected]',",+ " committedAt: '2026-02-02T00:00:00Z', subject: `c ${i}`, body: '', files: [], release: null },",+ ` { kind: 'commit', sha: ${JSON.stringify(SHARED_SHA)}, authorName: 'shared', authorEmail: '[email protected]',`,+ " committedAt: '2026-02-02T00:00:00Z', subject: 'shared', body: '', files: [], release: null },",+ " ]);",+ "}",+ ]);++ const commits = listGitCommits(vault, REPO_KEY);+ const shas = commits.map((c) => c.sha);+ for (let w = 0; w < WRITERS; w++) {+ for (let i = 0; i < PER_WRITER; i++) {+ expect(shas).toContain(sha(`w${w}`, i));+ }+ }+ // Dedup is only sound if the read and the append are one critical section.+ expect(shas.filter((s) => s === SHARED_SHA).length).toBe(1);+ expect(new Set(shas).size).toBe(shas.length);+ },+ SPAWN_TIMEOUT_MS,+ );+});++describe("acquireLockSyncWithRetry — an expired budget is loud", () => {+ test("rethrows ELOCKED naming the lock file rather than writing unlocked", () => {+ const target = join(vault, "contended.json");+ const held = acquireLockSync(target);+ try {+ let caught: NodeJS.ErrnoException | null = null;+ try {+ acquireLockSyncWithRetry(target, 50);+ } catch (err) {+ caught = err as NodeJS.ErrnoException;+ }+ expect(caught?.code).toBe("ELOCKED");+ expect(caught?.message).toContain(`${target}.lock`);+ } finally {+ held.release();+ }+ });+});++/*+ * REMOVED: "the shared files are not corrupted by the race" - a fifth test+ * that re-ran the manifest race and asserted only that the file still+ * parsed as JSON.+ *+ * It could not fail. `atomicWriteFileSync` renames a whole file into+ * place, so the manifest is parseable with the lock, without it, and with+ * every writer racing - which is the sibling docblock's own point at the+ * top of this file ("Atomicity is not exclusivity"). Neutralising the lock+ * turned the other four tests red and left that one green. It certified a+ * property the lock does not provide, under a heading claiming the+ * opposite, and it cost four more processes to do it. The property itself+ * is not lost: `tests/core/fs-atomic.test.ts` tests the atomic write+ * directly, and the `updateManifest` race above asserts every entry and an+ * exact count, neither of which survives an unparseable file.+ */diff --git a/tests/core/brain/maintenance/host-pressure.test.ts b/tests/core/brain/maintenance/host-pressure.test.tsnew file mode 100644index 00000000..53b47444--- /dev/null+++ b/tests/core/brain/maintenance/host-pressure.test.ts@@ -0,0 +1,281 @@+/**+ * Host pressure is either measured or named unmeasurable (t_992f0c33).+ *+ * The whole point of the vocabulary is the pair these tests keep apart: a+ * host whose run queue really is empty, and a host whose run queue this+ * build cannot read. `os.loadavg()` reports `[0, 0, 0]` on the platform it+ * does not implement, so the two are the same number and only the reason+ * separates them.+ */++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 } from "node:path";++import {+ HOST_PRESSURE,+ HOST_PRESSURE_UNMEASURABLE_REASON,+ LIVE_HOST_PRESSURE_IO,+ measureHostPressure,+ probeCpuQuota,+ readHostPressureProbe,+ type CgroupSource,+ type HostPressureIo,+ type HostPressureProbe,+} from "../../../../src/core/brain/maintenance/host-pressure.ts";++/** A POSIX host at half its capacity: 2 runnable tasks across 4 CPUs. */+const POSIX_PROBE: HostPressureProbe = Object.freeze({+ platform: "linux",+ loadAverage1m: 2,+ cpuCount: 4,+ cpuQuotaInForce: false,+});++describe("measureHostPressure", () => {+ test("a readable run queue normalises to a percentage of capacity", () => {+ expect(measureHostPressure(POSIX_PROBE)).toEqual({+ state: HOST_PRESSURE.measured,+ percent: 50,+ load_average_1m: 2,+ cpu_count: 4,+ });+ });++ test("a genuinely quiet POSIX host measures zero rather than refusing", () => {+ const reading = measureHostPressure({ ...POSIX_PROBE, loadAverage1m: 0 });+ expect(reading).toEqual({+ state: HOST_PRESSURE.measured,+ percent: 0,+ load_average_1m: 0,+ cpu_count: 4,+ });+ });++ test("the platform whose load average is a constant is unmeasurable, not idle", () => {+ // Same zero the quiet host above reported, and it must NOT read the+ // same way: on this platform the number is not a measurement.+ const reading = measureHostPressure({+ ...POSIX_PROBE,+ platform: "win32",+ loadAverage1m: 0,+ });+ expect(reading).toEqual({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.platformBlind,+ });+ });++ test("a CPU bandwidth quota makes the run queue the wrong machine's", () => {+ expect(measureHostPressure({ ...POSIX_PROBE, cpuQuotaInForce: true })).toEqual({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.cpuQuotaInForce,+ });+ });++ test("a quota interface that exists but cannot be read is not 'no quota'", () => {+ expect(measureHostPressure({ ...POSIX_PROBE, cpuQuotaInForce: null })).toEqual({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.cpuQuotaUnknown,+ });+ });++ test("no usable CPU count leaves nothing to normalise by", () => {+ for (const cpuCount of [0, -1, 1.5, Number.NaN]) {+ expect(measureHostPressure({ ...POSIX_PROBE, cpuCount })).toEqual({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.parallelismUnknown,+ });+ }+ });++ test("a run queue that is not a finite non-negative number is refused", () => {+ for (const loadAverage1m of [-1, Number.NaN, Number.POSITIVE_INFINITY]) {+ expect(measureHostPressure({ ...POSIX_PROBE, loadAverage1m })).toEqual({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.loadAverageInvalid,+ });+ }+ });++ test("an over-subscribed host reports above one hundred percent", () => {+ const reading = measureHostPressure({ ...POSIX_PROBE, loadAverage1m: 8, cpuCount: 4 });+ expect(reading).toEqual({+ state: HOST_PRESSURE.measured,+ percent: 200,+ load_average_1m: 8,+ cpu_count: 4,+ });+ });+});++describe("probeCpuQuota reads the cgroup this process is in", () => {+ let root: string;+ /** `/sys/fs/cgroup` and `/proc/self/cgroup`, relocated under a tmpdir. */+ let cgroupRoot: string;+ let selfCgroupPath: string;++ beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "o2b-cgroup-"));+ cgroupRoot = join(root, "sys", "fs", "cgroup");+ selfCgroupPath = join(root, "proc", "self", "cgroup");+ mkdirSync(cgroupRoot, { recursive: true });+ mkdirSync(dirname(selfCgroupPath), { recursive: true });+ });++ afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ });++ /** Write `cpu.max` (v2) at a path RELATIVE to the cgroup mount root. */+ function v2Interface(relative: string, contents: string): void {+ const dir = join(cgroupRoot, relative);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "cpu.max"), contents);+ }++ function source(platform = "linux"): CgroupSource {+ return { platform, cgroupRoot, selfCgroupPath };+ }++ test("a quota on the process's OWN cgroup is in force, though the root has no cpu.max", () => {+ // The exact layout of the host this was found on: no `cpu.max` at the+ // mount root - under cgroup v2 the root never carries one - and the+ // limit expressed on the leaf the process actually lives in.+ writeFileSync(selfCgroupPath, "0::/user.slice/session-9028.scope\n");+ v2Interface("user.slice/session-9028.scope", "50000 100000\n");+ expect(probeCpuQuota(source())).toBe(true);+ });++ test("an ANCESTOR's quota is in force too, because the limit is the minimum over the chain", () => {+ writeFileSync(selfCgroupPath, "0::/user.slice/session-9028.scope\n");+ v2Interface("user.slice", "20000 100000\n");+ v2Interface("user.slice/session-9028.scope", "max 100000\n");+ expect(probeCpuQuota(source())).toBe(true);+ });++ test("an unlimited chain is a real 'no quota', not an absence", () => {+ writeFileSync(selfCgroupPath, "0::/user.slice/session-9028.scope\n");+ v2Interface("user.slice", "max 100000\n");+ v2Interface("user.slice/session-9028.scope", "max 100000\n");+ expect(probeCpuQuota(source())).toBe(false);+ });++ test("a cgroup nobody could read is unknown, never 'no quota'", () => {+ writeFileSync(selfCgroupPath, "0::/user.slice/session-9028.scope\n");+ v2Interface("user.slice/session-9028.scope", "max 100000\n");+ const file = join(cgroupRoot, "user.slice/session-9028.scope", "cpu.max");+ chmodSync(file, 0o000);+ try {+ // EACCES on a file that EXISTS is the hardened-/sys case, and the+ // old probe reported it as "no bandwidth controller".+ expect(probeCpuQuota(source())).toBe(null);+ } finally {+ chmodSync(file, 0o600);+ }+ });++ test("not knowing which cgroup this process is in is its own answer", () => {+ // No `/proc/self/cgroup` to read at all on a platform that has one.+ expect(probeCpuQuota(source())).toBe(null);+ });++ test("a /proc/self/cgroup naming no hierarchy this build understands is unknown", () => {+ writeFileSync(selfCgroupPath, "7:name=systemd:/user.slice\n");+ expect(probeCpuQuota(source())).toBe(null);+ });++ test("a cgroup v1 cpu quota on the process's own path is in force", () => {+ writeFileSync(selfCgroupPath, "4:cpu,cpuacct:/user/1001.user\n");+ const dir = join(cgroupRoot, "cpu,cpuacct", "user/1001.user");+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "cpu.cfs_quota_us"), "50000\n");+ expect(probeCpuQuota(source())).toBe(true);+ });++ test("a cgroup v1 chain declaring -1 everywhere is unlimited", () => {+ writeFileSync(selfCgroupPath, "4:cpu,cpuacct:/user/1001.user\n");+ for (const rel of ["cpu,cpuacct", "cpu,cpuacct/user", "cpu,cpuacct/user/1001.user"]) {+ const dir = join(cgroupRoot, rel);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, "cpu.cfs_quota_us"), "-1\n");+ }+ expect(probeCpuQuota(source())).toBe(false);+ });++ test("a platform with no cgroups at all has no bandwidth controller", () => {+ // macOS: the question is answerable and the answer is no, which is+ // why this is `false` rather than the unknown above.+ expect(probeCpuQuota(source("darwin"))).toBe(false);+ });+});++describe("readHostPressureProbe turns a failed read into a named refusal", () => {+ const io = (over: Partial<HostPressureIo>): HostPressureIo => ({+ ...LIVE_HOST_PRESSURE_IO,+ ...over,+ });++ test("a run-queue read that throws is refused, never reported as an idle host", () => {+ const probe = readHostPressureProbe(+ io({+ loadAverage: () => {+ throw new Error("uv_loadavg: not supported");+ },+ }),+ );+ expect(measureHostPressure({ ...probe, cpuQuotaInForce: false, platform: "linux" })).toEqual({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.loadAverageInvalid,+ });+ });++ test("a CPU count read that throws leaves nothing to normalise by", () => {+ const probe = readHostPressureProbe(+ io({+ cpuCount: () => {+ throw new Error("uv_available_parallelism: not supported");+ },+ }),+ );+ expect(measureHostPressure({ ...probe, cpuQuotaInForce: false, platform: "linux" })).toEqual({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.parallelismUnknown,+ });+ });++ test("a CPU count of zero is refused rather than divided by", () => {+ const probe = readHostPressureProbe(io({ cpuCount: () => 0 }));+ expect(measureHostPressure({ ...probe, cpuQuotaInForce: false, platform: "linux" })).toEqual({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.parallelismUnknown,+ });+ });++ test("the platform whose load average is a constant reaches the refusal from the live probe", () => {+ // `platform_blind` is not a test-only member: this build runs on+ // win32 whenever OPEN_SECOND_BRAIN_CONFIG or XDG_CONFIG_HOME says+ // where the config lives, which is exactly the escape+ // `resolveDefaultConfigPath` documents.+ const probe = readHostPressureProbe(io({ platform: "win32", loadAverage: () => [0, 0, 0] }));+ expect(measureHostPressure(probe)).toEqual({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.platformBlind,+ });+ });+});++describe("readHostPressureProbe", () => {+ test("the real probe answers in the shape the measurement consumes", () => {+ const probe = readHostPressureProbe();+ expect(typeof probe.platform).toBe("string");+ expect(typeof probe.loadAverage1m).toBe("number");+ expect(typeof probe.cpuCount).toBe("number");+ expect(probe.cpuQuotaInForce === null || typeof probe.cpuQuotaInForce === "boolean").toBe(true);+ // And it reaches a verdict of one kind or the other on this host,+ // rather than throwing on a machine whose /sys layout differs.+ const reading = measureHostPressure(probe);+ expect([HOST_PRESSURE.measured, HOST_PRESSURE.unmeasurable]).toContain(reading.state);+ });+});diff --git a/tests/core/brain/maintenance/maintenance.test.ts b/tests/core/brain/maintenance/maintenance.test.tsindex 715bc55e..dd6d2126 100644--- a/tests/core/brain/maintenance/maintenance.test.ts+++ b/tests/core/brain/maintenance/maintenance.test.ts@@ -7,7 +7,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { appendFileSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -22,9 +22,20 @@ import {runMaintenance,} from "../../../../src/core/brain/maintenance/lane.ts";import {+ appendJournal,+ consecutiveTaskFailures,listJournal,MAINTENANCE_JOURNAL_CAP,+ MAINTENANCE_VERDICT,+ sweepJournal,} from "../../../../src/core/brain/maintenance/journal.ts";+import {+ HOST_PRESSURE,+ HOST_PRESSURE_UNMEASURABLE_REASON,+ type HostPressureReading,+} from "../../../../src/core/brain/maintenance/host-pressure.ts";+import { MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT } from "../../../../src/core/brain/policy/blocks/maintenance.ts";+import { brainConfigPath } from "../../../../src/core/brain/paths.ts";import {emitRecallTelemetry,RECALL_CHANNEL,@@ -84,13 +95,13 @@ describe("dailyWindowContains", () => {describe("evaluateGates", () => {test("no window configured and a quiet vault runs", () => {- expect(evaluateGates(vault, { now: NOW })).toBe("run");+ expect(evaluateGates(vault, { now: NOW }).verdict).toBe(MAINTENANCE_VERDICT.run);});test("outside the window skips", () => {expect(- evaluateGates(vault, { now: NOW, window: { startHour: 10, endHour: 12, tz: "UTC" } }),- ).toBe("skipped:window");+ evaluateGates(vault, { now: NOW, window: { startHour: 10, endHour: 12, tz: "UTC" } }).verdict,+ ).toBe(MAINTENANCE_VERDICT.skippedWindow);});test("recent interactive queries above the threshold skip as busy", () => {@@ -105,10 +116,85 @@ describe("evaluateGates", () => {createdAt: new Date(NOW.getTime() - 60_000).toISOString(),});}- expect(evaluateGates(vault, { now: NOW, busy: { minutes: 10, threshold: 5 } })).toBe(- "skipped:busy",+ expect(evaluateGates(vault, { now: NOW, busy: { minutes: 10, threshold: 5 } }).verdict).toBe(+ MAINTENANCE_VERDICT.skippedBusy,+ );+ expect(evaluateGates(vault, { now: NOW, busy: { minutes: 10, threshold: 6 } }).verdict).toBe(+ MAINTENANCE_VERDICT.run,);- expect(evaluateGates(vault, { now: NOW, busy: { minutes: 10, threshold: 6 } })).toBe("run");+ });+});++describe("the host-pressure gate", () => {+ const measured = (percent: number): HostPressureReading => ({+ state: HOST_PRESSURE.measured,+ percent,+ load_average_1m: percent / 25,+ cpu_count: 4,+ });+ const unmeasurable: HostPressureReading = {+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.platformBlind,+ };++ test("an unconfigured gate never fires and never measures", () => {+ let measurements = 0;+ const decision = evaluateGates(vault, {+ now: NOW,+ readPressure: () => {+ measurements += 1;+ return measured(999);+ },+ });+ expect(decision.verdict).toBe(MAINTENANCE_VERDICT.run);+ expect(decision.pressure).toBeUndefined();+ expect(measurements).toBe(0);+ });++ test("pressure at or above the configured percentage skips", () => {+ const decision = evaluateGates(vault, {+ now: NOW,+ pressure: { percent: 70 },+ readPressure: () => measured(70),+ });+ expect(decision.verdict).toBe(MAINTENANCE_VERDICT.skippedPressure);+ expect(decision.pressure).toEqual(measured(70));+ });++ test("pressure below the configured percentage leaves the gate open", () => {+ const decision = evaluateGates(vault, {+ now: NOW,+ pressure: { percent: 70 },+ readPressure: () => measured(69),+ });+ expect(decision.verdict).toBe(MAINTENANCE_VERDICT.run);+ });++ test("an unmeasurable host leaves the gate open and says so", () => {+ const decision = evaluateGates(vault, {+ now: NOW,+ pressure: { percent: 1 },+ readPressure: () => unmeasurable,+ });+ // A threshold of 1% would skip on any real reading; the gate is open+ // because nothing was read, which is a different fact from "quiet".+ expect(decision.verdict).toBe(MAINTENANCE_VERDICT.run);+ expect(decision.pressure).toEqual(unmeasurable);+ });++ test("an earlier closed gate wins and the host is never probed", () => {+ let measurements = 0;+ const decision = evaluateGates(vault, {+ now: NOW,+ window: { startHour: 10, endHour: 12, tz: "UTC" },+ pressure: { percent: 70 },+ readPressure: () => {+ measurements += 1;+ return measured(99);+ },+ });+ expect(decision.verdict).toBe(MAINTENANCE_VERDICT.skippedWindow);+ expect(measurements).toBe(0);});});@@ -176,3 +262,237 @@ describe("runMaintenance", () => {expect(MAINTENANCE_JOURNAL_CAP).toBeGreaterThanOrEqual(100);});});++describe("the host-pressure gate through the lane", () => {+ /** Configure the fourth gate in the vault the lane reads. */+ function configurePressureGate(percent: number): void {+ appendFileSync(brainConfigPath(vault), `\nmaintenance:\n host_pressure_percent: ${percent}\n`);+ }++ test("a loaded host skips with its own verdict and journals the reading", async () => {+ configurePressureGate(70);+ const result = await runMaintenance(vault, {+ now: NOW,+ holder: "worker-a",+ readPressure: () => ({+ state: HOST_PRESSURE.measured,+ percent: 180,+ load_average_1m: 7.2,+ cpu_count: 4,+ }),+ tasks: [+ {+ name: "dream",+ run: async () => {+ throw new Error("the gate should have refused before this ran");+ },+ },+ ],+ });+ expect(result.verdict).toBe(MAINTENANCE_VERDICT.skippedPressure);+ expect(result.tasks).toEqual([]);+ const row = listJournal(vault).find((e) => e.verdict === MAINTENANCE_VERDICT.skippedPressure);+ expect(row?.pressure_percent).toBe(180);+ });++ test("an unmeasurable host journals a SECOND kind of line and still runs", async () => {+ configurePressureGate(1);+ const ran: string[] = [];+ const result = await runMaintenance(vault, {+ now: NOW,+ holder: "worker-a",+ readPressure: () => ({+ state: HOST_PRESSURE.unmeasurable,+ reason: HOST_PRESSURE_UNMEASURABLE_REASON.platformBlind,+ }),+ tasks: [{ name: "dream", run: async () => void ran.push("dream") }],+ });+ expect(result.verdict).toBe(MAINTENANCE_VERDICT.run);+ expect(ran).toEqual(["dream"]);++ const journal = listJournal(vault);+ const notice = journal.find((e) => e.verdict === MAINTENANCE_VERDICT.pressureUnmeasurable);+ expect(notice?.pressure_reason).toBe(HOST_PRESSURE_UNMEASURABLE_REASON.platformBlind);+ // Two different lines, never one: the notice that the gate could not+ // evaluate is not the same row as the work that then went ahead, and+ // neither is a `skipped:pressure`.+ expect(journal.some((e) => e.verdict === MAINTENANCE_VERDICT.skippedPressure)).toBe(false);+ expect(journal.some((e) => e.verdict === MAINTENANCE_VERDICT.run && e.task === "dream")).toBe(+ true,+ );+ expect(notice?.task).toBeUndefined();+ });+});++describe("the consecutive-failure streak", () => {+ const TASK = "reindex";++ /** Run the lane once with the streak-tracked task failing or succeeding. */+ function laneRun(succeeds: boolean, force = false) {+ return runMaintenance(vault, {+ now: NOW,+ holder: "worker-a",+ ...(force ? { force: true } : {}),+ tasks: [+ {+ name: TASK,+ run: async () => {+ if (!succeeds) throw new Error("disk full");+ },+ },+ ],+ });+ }++ test("the streak counts journaled failures back to the newest success", async () => {+ expect(consecutiveTaskFailures(vault, TASK)).toBe(0);+ await laneRun(false);+ expect(consecutiveTaskFailures(vault, TASK)).toBe(1);+ await laneRun(false);+ expect(consecutiveTaskFailures(vault, TASK)).toBe(2);+ // A different task's failures are not this task's streak.+ await runMaintenance(vault, {+ now: NOW,+ holder: "worker-a",+ tasks: [+ {+ name: "dream",+ run: async () => {+ throw new Error("unrelated");+ },+ },+ ],+ });+ expect(consecutiveTaskFailures(vault, TASK)).toBe(2);+ });++ test("the limit refuses the task by name and states the streak", async () => {+ for (let i = 0; i < MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT; i++) {+ // eslint-disable-next-line no-await-in-loop+ await laneRun(false);+ }+ const refused = await laneRun(false);+ expect(refused.verdict).toBe(MAINTENANCE_VERDICT.run);+ const task = refused.tasks[0]!;+ expect(task.refused).toBe(true);+ expect(task.ok).toBe(false);+ expect(task.failure_streak).toBe(MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT);+ expect(task.error).toContain(String(MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT));+ expect(task.error).toContain("--force");++ const row = listJournal(vault).find((e) => e.verdict === MAINTENANCE_VERDICT.refusedStreak);+ expect(row?.task).toBe(TASK);+ expect(row?.streak).toBe(MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT);+ // A refusal is not an attempt: it must not deepen the streak it reports.+ expect(consecutiveTaskFailures(vault, TASK)).toBe(MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT);+ });++ test("a single success resets the streak", async () => {+ for (let i = 0; i < MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT; i++) {+ // eslint-disable-next-line no-await-in-loop+ await laneRun(false);+ }+ expect((await laneRun(false)).tasks[0]!.refused).toBe(true);++ // --force is the way past a refusal, and the success it produces is+ // what clears the streak for the next unforced run.+ const forced = await laneRun(true, true);+ expect(forced.tasks[0]!.ok).toBe(true);+ expect(consecutiveTaskFailures(vault, TASK)).toBe(0);++ const after = await laneRun(false);+ expect(after.tasks[0]!.refused).toBeUndefined();+ expect(after.tasks[0]!.ok).toBe(false);+ expect(consecutiveTaskFailures(vault, TASK)).toBe(1);+ });++ test("--force runs a task the streak would have refused", async () => {+ for (let i = 0; i < MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT; i++) {+ // eslint-disable-next-line no-await-in-loop+ await laneRun(false);+ }+ const forced = await laneRun(false, true);+ expect(forced.tasks[0]!.refused).toBeUndefined();+ expect(forced.tasks[0]!.ok).toBe(false);+ });++ test("retrying one task runs it while every other gate still applies", async () => {+ for (let i = 0; i < MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT; i++) {+ // eslint-disable-next-line no-await-in-loop+ await laneRun(false);+ }+ // Named: the refused task runs, and only that one - the second task's+ // own refusal is untouched by a retry that does not name it.+ const tasks = [+ { name: TASK, run: async () => void 0 },+ {+ name: "dream",+ run: async () => {+ throw new Error("should not have been reached");+ },+ },+ ];+ appendJournal(vault, {+ ts: NOW.toISOString(),+ holder: "worker-a",+ verdict: MAINTENANCE_VERDICT.refusedStreak,+ task: "dream",+ streak: MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT,+ });++ const retried = await runMaintenance(vault, {+ now: NOW,+ holder: "worker-a",+ retryTasks: [TASK],+ tasks,+ });+ expect(retried.tasks.find((t) => t.name === TASK)?.ok).toBe(true);+ expect(retried.tasks.find((t) => t.name === "dream")?.refused).toBe(true);++ // A retry is not a force: the window gate still closes on the same run.+ const gated = await runMaintenance(vault, {+ now: NOW,+ holder: "worker-a",+ retryTasks: [TASK],+ window: { startHour: 10, endHour: 12, tz: "UTC" },+ tasks: [+ {+ name: TASK,+ run: async () => {+ throw new Error("the window gate should have refused before this ran");+ },+ },+ ],+ });+ expect(gated.verdict).toBe(MAINTENANCE_VERDICT.skippedWindow);+ expect(gated.tasks).toEqual([]);+ });++ test("the streak survives the journal cap, because the refusal row carries it", async () => {+ for (let i = 0; i < MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT; i++) {+ // eslint-disable-next-line no-await-in-loop+ await laneRun(false);+ }+ expect((await laneRun(false)).tasks[0]!.refused).toBe(true);++ // The journal is a ring buffer. Trim it to the newest line - the same+ // rewrite `sweepJournal` performs under the lease, only sooner - so+ // every `run/ok:false` row that produced the streak is gone.+ sweepJournal(vault, 1);+ const kept = listJournal(vault);+ expect(kept.length).toBe(1);+ expect(kept[0]?.verdict).toBe(MAINTENANCE_VERDICT.refusedStreak);+ expect(kept.some((e) => e.verdict === MAINTENANCE_VERDICT.run)).toBe(false);++ // The refusal row records the count it refused on, so the streak does+ // not silently reset itself as its evidence rolls off the cap.+ expect(consecutiveTaskFailures(vault, TASK)).toBe(MAINTENANCE_FAILURE_STREAK_LIMIT_DEFAULT);+ expect((await laneRun(false)).tasks[0]!.refused).toBe(true);++ // And a success still clears it: the walk stops at the newest row that+ // is not a failure, which is newer than any carried refusal.+ const forced = await laneRun(true, true);+ expect(forced.tasks[0]!.ok).toBe(true);+ expect(consecutiveTaskFailures(vault, TASK)).toBe(0);+ });+});diff --git a/tests/core/brain/policy-safe-loaders.test.ts b/tests/core/brain/policy-safe-loaders.test.tsindex 062aa69c..bbe94942 100644--- a/tests/core/brain/policy-safe-loaders.test.ts+++ b/tests/core/brain/policy-safe-loaders.test.ts@@ -28,6 +28,7 @@ import { resolveNoteRoots } from "../../../src/core/brain/notes/note-walk.ts";import { brainConfigPath } from "../../../src/core/brain/paths.ts";import {BRAIN_GUARDRAIL_DEFAULTS,+ BRAIN_MAINTENANCE_DEFAULTS,BRAIN_MOST_APPLIED_DEFAULTS,BRAIN_NOTES_DEFAULTS,BRAIN_TEMPORAL_DEFAULTS,@@ -37,6 +38,7 @@ import {loadFeedbackDefaultScopeSafe,loadGuardrailsConfigSafe,loadIntegrityConfigSafe,+ loadMaintenanceConfigSafe,loadNotesConfigSafe,loadSnapshotDerivedStorePolicySafe,loadSnapshotRetentionSafe,@@ -83,6 +85,15 @@ const SAFE_LOADERS = [load: loadActiveMostAppliedSafe as (vault: string) => unknown,absentValue: BRAIN_MOST_APPLIED_DEFAULTS as unknown,},+ {+ // Both knobs decide whether heavy work STARTS, so serving the+ // defaults on a broken config would run a pass the operator had+ // gated behind a pressure threshold and retry a task their streak+ // limit had refused.+ name: "loadMaintenanceConfigSafe",+ load: loadMaintenanceConfigSafe as (vault: string) => unknown,+ absentValue: BRAIN_MAINTENANCE_DEFAULTS as unknown,+ },{// Coverage is what an operator turned ON, so answering `false` from// the defaults on a config that merely has a typo would silentlydiff --git a/tests/core/brain/policy/embeddings-block.test.ts b/tests/core/brain/policy/embeddings-block.test.tsnew file mode 100644index 00000000..accb69d2--- /dev/null+++ b/tests/core/brain/policy/embeddings-block.test.ts@@ -0,0 +1,108 @@+/**+ * The `embeddings:` block — an operator's own record of a decommission+ * announcement, and the refusals that keep it meaningful.+ *+ * The block exists because the sunset survey is compiled into the binary+ * and goes stale between releases. It is an ADDITIONAL layer, never the+ * only source: a declaration on its own cannot distinguish "the operator+ * declared nothing" from "no shutdown exists", and that collapse is the+ * defect the sunset check was built to remove.+ *+ * Two refusals are pinned here rather than described. Half a declaration+ * is an error, because a date with no model would have to mean "whatever+ * is configured" and would re-target itself on the next model change; and+ * an unparseable date is an error, because the instant it meant is not+ * recoverable from the text - the same disposition `health.silence_before`+ * already takes.+ */++import { describe, expect, test } from "bun:test";++import { BrainConfigError } from "../../../../src/core/brain/policy/errors.ts";+import { resolveEmbeddingSunsetDeclaration } from "../../../../src/core/brain/policy/blocks/embeddings.ts";+import { validateBrainConfigDetailed } from "../../../../src/core/brain/policy/validate.ts";+import { parseBrainYaml } from "../../../../src/core/brain/yaml-parse.ts";+import type { BrainConfig } from "../../../../src/core/brain/types.ts";++function load(yaml: string): BrainConfig {+ return validateBrainConfigDetailed(parseBrainYaml(yaml), "<unit>").config;+}++function warningsFor(yaml: string): ReadonlyArray<string> {+ return validateBrainConfigDetailed(parseBrainYaml(yaml), "<unit>").warnings.map((w) =>+ typeof w === "string" ? w : JSON.stringify(w),+ );+}++const VALID = `schema_version: 1+embeddings:+ sunset_model: "text-embedding-3-small"+ sunset_at: "2027-03-01"+`;++describe("a complete declaration is read", () => {+ test("both keys land on the config", () => {+ const cfg = load(VALID);+ expect(cfg.embeddings?.sunset_model).toBe("text-embedding-3-small");+ expect(cfg.embeddings?.sunset_at).toBe("2027-03-01");+ });++ test("it resolves to the shape the classifier consumes", () => {+ expect(resolveEmbeddingSunsetDeclaration(load(VALID))).toEqual({+ model: "text-embedding-3-small",+ sunsetAt: "2027-03-01",+ });+ });++ test("an absent block declares nothing, which is not a claim either way", () => {+ expect(resolveEmbeddingSunsetDeclaration(load("schema_version: 1\n"))).toBeNull();+ expect(resolveEmbeddingSunsetDeclaration(undefined)).toBeNull();+ });+});++describe("half a declaration is refused, never dropped", () => {+ test("a date with no model fails hard", () => {+ // Silently ignoring it would leave an operator believing a setting is+ // in force when it is not.+ expect(() => load(`schema_version: 1\nembeddings:\n sunset_at: "2027-03-01"\n`)).toThrow(+ BrainConfigError,+ );+ });++ test("a model with no date fails hard", () => {+ expect(() => load(`schema_version: 1\nembeddings:\n sunset_model: "m"\n`)).toThrow(+ BrainConfigError,+ );+ });+});++describe("a malformed value is refused, never substituted", () => {+ test("a date that is not ISO-8601 fails hard", () => {+ expect(() =>+ load(`schema_version: 1\nembeddings:\n sunset_model: "m"\n sunset_at: "next tuesday"\n`),+ ).toThrow(BrainConfigError);+ });++ test("an empty model string fails hard", () => {+ expect(() =>+ load(`schema_version: 1\nembeddings:\n sunset_model: ""\n sunset_at: "2027-03-01"\n`),+ ).toThrow(BrainConfigError);+ });++ test("the error names the key an operator has to edit", () => {+ try {+ load(`schema_version: 1\nembeddings:\n sunset_model: "m"\n sunset_at: "nope"\n`);+ throw new Error("expected a refusal");+ } catch (err) {+ expect((err as BrainConfigError).message).toContain("sunset_at");+ }+ });+});++describe("an unknown sub-key is a warning, not a refusal", () => {+ test("it is reported without losing the valid keys", () => {+ const yaml = `${VALID} sunset_reason: "vendor email"\n`;+ expect(warningsFor(yaml).join("\n")).toContain("sunset_reason");+ expect(load(yaml).embeddings?.sunset_at).toBe("2027-03-01");+ });+});diff --git a/tests/core/brain/pre-compact-extract.test.ts b/tests/core/brain/pre-compact-extract.test.tsindex 51ec18d9..f6a4460b 100644--- a/tests/core/brain/pre-compact-extract.test.ts+++ b/tests/core/brain/pre-compact-extract.test.ts@@ -89,3 +89,72 @@ describe("pre-compact extraction", () => {expect(listContinuityRecords(vault, { kind: "pre_compact_extract" })).toHaveLength(1);});});++describe("the label recognizer is structural, not a natural-language word list", () => {+ test("recognises labelled lines in a non-Latin script and keeps the label verbatim", () => {+ const result = extractPreCompactRecords(vault, {+ createdAt: "2026-05-20T17:00:00.000Z",+ sessionId: "session-ru",+ turnStart: "turn-1",+ turnEnd: "turn-2",+ text: [+ "Решение: перейти на новый пул соединений.",+ "決定: 明日リリースする。",+ "- قرار: نشر الإصدار غدا.",+ ].join("\n"),+ });++ expect(result.errors).toEqual([]);+ expect(result.records.map((record) => record.payload["extract_type"])).toEqual([+ "решение",+ "決定",+ "قرار",+ ]);+ expect(result.records[0]!.payload["text"]).toBe("перейти на новый пул соединений.");+ });++ test("a multi-word label collapses to one token, matching the English shape", () => {+ const result = extractPreCompactRecords(vault, {+ createdAt: "2026-05-20T17:00:00.000Z",+ sessionId: "session-multiword",+ turnStart: "turn-1",+ turnEnd: "turn-1",+ text: [+ "Open question: Should presets be configurable?",+ "Открытый вопрос: кто владелец?",+ ].join("\n"),+ });+ expect(result.records.map((record) => record.payload["extract_type"])).toEqual([+ "open_question",+ "открытый_вопрос",+ ]);+ });++ test("structural non-labels are refused: URLs, paths, clock times and prose", () => {+ const result = extractPreCompactRecords(vault, {+ createdAt: "2026-05-20T17:00:00.000Z",+ sessionId: "session-negative",+ turnStart: "turn-1",+ turnEnd: "turn-1",+ text: [+ "https://example.com/deploy",+ "file:///var/log/deploy.log",+ "C:\\Users\\dev\\notes.md",+ "10:30 standup with the platform team",+ "The one thing I would really like to say about all of this is: nothing",+ "[[wiki link]]: not a label",+ ].join("\n"),+ });+ expect(result.records).toEqual([]);+ });++ test("the module carries no natural-language word list", async () => {+ const source = await Bun.file(+ new URL("../../../src/core/brain/pre-compact-extract.ts", import.meta.url).pathname,+ ).text();+ const code = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");+ for (const word of ["decision", "commitment", "outcome", "rule", "open question"]) {+ expect(code.toLowerCase()).not.toContain(word);+ }+ });+});diff --git a/tests/core/brain/progress.test.ts b/tests/core/brain/progress.test.tsnew file mode 100644index 00000000..10f00d14--- /dev/null+++ b/tests/core/brain/progress.test.ts@@ -0,0 +1,254 @@+import { describe, expect, test } from "bun:test";++import {+ isProgressKind,+ isProgressReason,+ PROGRESS_KIND,+ PROGRESS_KINDS,+ PROGRESS_REASON,+ PROGRESS_REASONS,+ PROGRESS_SCHEMA,+ progressCounter,+ withProgress,+ withProgressAsync,+ type ProgressEvent,+} from "../../../src/core/brain/progress.ts";+import {+ isOperation,+ OPERATION,+ OPERATIONS,+ SafeguardAbortError,+} from "../../../src/core/brain/safeguard.ts";++describe("progress vocabulary", () => {+ test("kinds are frozen, complete, and guarded", () => {+ expect(Object.isFrozen(PROGRESS_KIND)).toBe(true);+ expect(PROGRESS_KINDS.toSorted()).toEqual(Object.values(PROGRESS_KIND).toSorted());+ for (const kind of PROGRESS_KINDS) expect(isProgressKind(kind)).toBe(true);+ });++ test("the guard refuses plausible drift, not only obvious garbage", () => {+ for (const outsider of ["", " ", "Started", "start", "advance", null, undefined, 7, {}]) {+ expect(isProgressKind(outsider)).toBe(false);+ }+ });++ test("reasons are frozen, complete, and guarded", () => {+ expect(Object.isFrozen(PROGRESS_REASON)).toBe(true);+ expect(PROGRESS_REASONS.toSorted()).toEqual(Object.values(PROGRESS_REASON).toSorted());+ for (const reason of PROGRESS_REASONS) expect(isProgressReason(reason)).toBe(true);+ expect(isProgressReason("aborted ")).toBe(false);+ });++ test("the operation vocabulary the safeguard already owned is now guarded", () => {+ expect(Object.isFrozen(OPERATION)).toBe(true);+ expect(OPERATIONS.toSorted()).toEqual(Object.values(OPERATION).toSorted());+ for (const operation of OPERATIONS) expect(isOperation(operation)).toBe(true);+ expect(isOperation("Dream")).toBe(false);+ expect(isOperation(undefined)).toBe(false);+ });+});++describe("progressCounter", () => {+ test("emits started once, advances monotonically, and finishes once", () => {+ const seen: ProgressEvent[] = [];+ const counter = progressCounter(OPERATION.dream, (e) => seen.push(e));++ counter.start("close");+ counter.advance("close");+ counter.advance("close");+ counter.start("reconcile", 4);+ counter.advance("reconcile");+ counter.finish();++ expect(seen.map((e) => `${e.kind}:${e.stage}:${e.completed}`)).toEqual([+ "started:close:0",+ "advanced:close:1",+ "advanced:close:2",+ "started:reconcile:0",+ "advanced:reconcile:1",+ "finished:reconcile:1",+ ]);+ expect(seen.every((e) => e.operation === OPERATION.dream)).toBe(true);+ expect(seen.every((e) => e.schema === PROGRESS_SCHEMA)).toBe(true);+ });++ test("a stage with no denominator omits total rather than inventing one", () => {+ const seen: ProgressEvent[] = [];+ const counter = progressCounter(OPERATION.reindex, (e) => seen.push(e));+ counter.start("walk");+ counter.advance("walk");+ expect(seen.every((e) => e.total === undefined)).toBe(true);+ expect(Object.hasOwn(seen[1] as object, "total")).toBe(false);+ });++ test("a stage with a denominator carries it on every event of that stage", () => {+ const seen: ProgressEvent[] = [];+ const counter = progressCounter(OPERATION.reindex, (e) => seen.push(e));+ counter.start("embed", 12);+ counter.advance("embed", 4);+ expect(seen.map((e) => e.total)).toEqual([12, 12]);+ expect(seen.map((e) => e.completed)).toEqual([0, 4]);+ });++ test("a total that is not a non-negative integer is refused loudly", () => {+ const counter = progressCounter(OPERATION.dream, () => {});+ expect(() => counter.start("close", -1)).toThrow(/total/);+ expect(() => counter.start("close", 1.5)).toThrow(/total/);+ });++ test("advancing before any stage started is refused rather than silently ignored", () => {+ const counter = progressCounter(OPERATION.dream, () => {});+ expect(() => counter.advance("close")).toThrow(/stage/);+ });++ test("stopped carries a reason from the closed vocabulary", () => {+ const seen: ProgressEvent[] = [];+ const counter = progressCounter(OPERATION.dream, (e) => seen.push(e));+ counter.start("close");+ counter.stop(PROGRESS_REASON.aborted);+ expect(seen.at(-1)).toMatchObject({+ kind: PROGRESS_KIND.stopped,+ reason: PROGRESS_REASON.aborted,+ });+ });++ test("a throwing sink with no reporter is contained, not fatal, and not silent", () => {+ // The default had to become the SAFE one. A reviewer found that with+ // the unsafe default - the throw propagating - one of six emitters+ // supplied a reporter and five did not, so a broken pipe aborted five+ // long operations and left the sixth running. A rule every caller+ // must remember is a rule five of six callers forget.+ const lines: string[] = [];+ const realWrite = process.stderr.write.bind(process.stderr);+ process.stderr.write = ((chunk: string) => {+ lines.push(String(chunk));+ return true;+ }) as typeof process.stderr.write;+ try {+ let calls = 0;+ const counter = progressCounter(OPERATION.clusters, () => {+ calls += 1;+ throw new Error("stream closed");+ });+ expect(() => counter.start("sweep")).not.toThrow();+ expect(() => counter.advance("sweep")).not.toThrow();+ // Detached after one failure: one defect, one report.+ expect(calls).toBe(1);+ expect(lines).toHaveLength(1);+ expect(lines[0]).toContain("clusters");+ expect(lines[0]).toContain("stream closed");+ } finally {+ process.stderr.write = realWrite;+ }+ });++ test("no sink attached is the absence of an observer, not a swallowed event", () => {+ // The house idiom is `opts.onProgress?.(...)`: absence means nobody+ // asked. A counter built with no sink must therefore be constructible+ // and inert, and must still refuse invalid input - a silent counter+ // that also silently accepted a bad total would hide the defect.+ const counter = progressCounter(OPERATION.dream, undefined);+ expect(() => counter.start("close")).not.toThrow();+ expect(() => counter.start("close", -3)).toThrow(/total/);+ });++ test("a sink that throws does not take the operation down with it", () => {+ // Progress is observation. An edge renderer with a broken stream must+ // not abort a consolidation pass that is otherwise succeeding, and the+ // failure must not be silent either - it is re-reported once, to the+ // reporter the caller supplied.+ const failures: unknown[] = [];+ const counter = progressCounter(+ OPERATION.dream,+ () => {+ throw new Error("stream closed");+ },+ { onSinkError: (e) => failures.push(e) },+ );+ expect(() => counter.start("close")).not.toThrow();+ expect(failures).toHaveLength(1);+ });+});++describe("a run ends once", () => {+ test("a second terminator is a defect, not a second ending", () => {+ const counter = progressCounter(OPERATION.dream, () => {});+ counter.start("close");+ counter.finish();+ expect(() => counter.finish()).toThrow(/stream ended/);+ expect(() => counter.stop(PROGRESS_REASON.aborted)).toThrow(/stream ended/);+ });++ test("nothing may be emitted after the stream ended", () => {+ const counter = progressCounter(OPERATION.dream, () => {});+ counter.start("close");+ counter.stop(PROGRESS_REASON.aborted);+ expect(() => counter.advance("close")).toThrow(/stream ended/);+ expect(() => counter.start("reconcile")).toThrow(/stream ended/);+ });++ test("the counter only moves forward", () => {+ // A stream whose counter can go backwards, or sit still while+ // claiming to advance, describes a run nobody could follow.+ const counter = progressCounter(OPERATION.dream, () => {});+ counter.start("close");+ expect(() => counter.advance("close", 0)).toThrow(/positive integer/);+ expect(() => counter.advance("close", -3)).toThrow(/positive integer/);+ expect(() => counter.advance("close", 1.5)).toThrow(/positive integer/);+ });+});++describe("withProgress keeps its own promise", () => {+ test("a normal return terminates the stream", () => {+ const seen: ProgressEvent[] = [];+ const counter = progressCounter(OPERATION.bridges, (e) => seen.push(e));+ counter.start("candidates");+ expect(withProgress(counter, () => 42)).toBe(42);+ expect(seen.at(-1)?.kind).toBe(PROGRESS_KIND.finished);+ });++ test("a crash terminates the stream too, and says so", () => {+ // The docblock promises termination "whichever way it ends", and a+ // crash is a way a run ends. Without this the promise held only for+ // the two safeguard stops, and a crashed run's stream simply stopped+ // arriving - which is the shape of a hung run.+ const seen: ProgressEvent[] = [];+ const counter = progressCounter(OPERATION.bridges, (e) => seen.push(e));+ counter.start("candidates");+ expect(() =>+ withProgress(counter, () => {+ throw new Error("store closed");+ }),+ ).toThrow("store closed");+ expect(seen.at(-1)).toMatchObject({+ kind: PROGRESS_KIND.stopped,+ reason: PROGRESS_REASON.failed,+ });+ });++ test("a safeguard stop keeps its own reason rather than reading as a crash", () => {+ const seen: ProgressEvent[] = [];+ const counter = progressCounter(OPERATION.dream, (e) => seen.push(e));+ counter.start("close");+ expect(() =>+ withProgress(counter, () => {+ throw new SafeguardAbortError("dream");+ }),+ ).toThrow(SafeguardAbortError);+ expect(seen.at(-1)?.reason).toBe(PROGRESS_REASON.aborted);+ });++ test("the async form behaves identically", async () => {+ const seen: ProgressEvent[] = [];+ const counter = progressCounter(OPERATION.reindex, (e) => seen.push(e));+ counter.start("walk");+ await expect(withProgressAsync(counter, () => Promise.reject(new Error("io")))).rejects.toThrow(+ "io",+ );+ expect(seen.at(-1)).toMatchObject({+ kind: PROGRESS_KIND.stopped,+ reason: PROGRESS_REASON.failed,+ });+ });+});diff --git a/tests/core/brain/retrieval-plan.test.ts b/tests/core/brain/retrieval-plan.test.tsindex 24b4f4a0..4e639c95 100644--- a/tests/core/brain/retrieval-plan.test.ts+++ b/tests/core/brain/retrieval-plan.test.ts@@ -55,8 +55,8 @@ function tokenImpact(firstPassRate: number | null): TokenImpactSummary {added_tokens: 0,mean_savings_tokens: 33.3,by_method: {- exact: { samples: 3, net_savings_tokens: 100 },- fallback: { samples: 0, net_savings_tokens: 0 },+ tokenizer: { samples: 3, net_savings_tokens: 100 },+ heuristic: { samples: 0, net_savings_tokens: 0 },},},modeled_inference_avoidance: {diff --git a/tests/core/brain/sessions/adapter-registry.test.ts b/tests/core/brain/sessions/adapter-registry.test.tsnew file mode 100644index 00000000..abf1dd21--- /dev/null+++ b/tests/core/brain/sessions/adapter-registry.test.ts@@ -0,0 +1,108 @@+/**+ * The session-adapter registry as a REGISTRY (U7 of "nothing runs+ * unwatched").+ *+ * The memory-backend registry already states the property this one has to+ * satisfy: "adding a runtime means adding ONE module that satisfies this+ * interface and registering it - no changes to the import core, CLI, or MCP+ * surfaces" (`src/core/brain/agent-backend/types.ts:9-11`). These tests hold+ * the session adapters to it: an id-keyed lookup that fails loudly on an+ * unknown id, and a seam that takes a caller's own adapter set without the+ * registry file knowing anything about it.+ *+ * They also lock the id vocabulary to the registry's contents, which is what+ * keeps `--format`'s guard honest as adapters are added.+ */++import { describe, expect, test } from "bun:test";++import {+ createSessionAdapterRegistry,+ detectAdapter,+ getAdapter,+ listSessionAdapters,+ SESSION_ADAPTER_REGISTRY,+ sessionAdapterFormatChoices,+} from "../../../../src/core/brain/sessions/registry.ts";+import {+ isSessionAdapterId,+ SESSION_ADAPTER_ID,+ SESSION_ADAPTER_IDS,+ type SessionAdapter,+ type SessionTurn,+} from "../../../../src/core/brain/sessions/types.ts";++/**+ * A whole adapter, defined here and nowhere else - the "one new module" of+ * the protocol. Nothing under `src/` mentions it.+ */+const FIXTURE_MARKER = `"runtime":"fixture-runtime"`;++const fixtureAdapter: SessionAdapter = {+ id: "fixture",+ defaultAgent: "fixture-agent",+ detect(firstLine: string): boolean {+ return firstLine.includes(FIXTURE_MARKER);+ },+ async *iterate(): AsyncIterable<SessionTurn> {+ yield { turnId: "t1", timestamp: "2026-08-15T00:00:00Z", role: "user", text: "hi" };+ },+};++describe("getAdapter — an unknown id is loud", () => {+ test("names the id that was asked for and the ids that exist", () => {+ let message = "";+ try {+ getAdapter("copilot");+ } catch (err) {+ message = (err as Error).message;+ }+ expect(message).toContain("copilot");+ for (const id of SESSION_ADAPTER_IDS) expect(message).toContain(id);+ });++ test("a registered id still resolves to its adapter", () => {+ for (const id of SESSION_ADAPTER_IDS) expect(getAdapter(id).id).toBe(id);+ });+});++describe("the registry is a seam, not a hardcoded array", () => {+ test("an adapter defined outside src/ resolves through the public seam", () => {+ const registry = createSessionAdapterRegistry([...listSessionAdapters(), fixtureAdapter]);+ expect(getAdapter("fixture", registry)).toBe(fixtureAdapter);+ expect(detectAdapter(`{${FIXTURE_MARKER}}`, registry)?.id).toBe("fixture");+ expect(sessionAdapterFormatChoices(registry)).toContain("fixture");+ // Every built-in still resolves through the extended registry.+ for (const id of SESSION_ADAPTER_IDS) expect(getAdapter(id, registry).id).toBe(id);+ });++ test("extending the registry does not mutate the built-in one", () => {+ createSessionAdapterRegistry([...listSessionAdapters(), fixtureAdapter]);+ expect(() => getAdapter("fixture")).toThrow();+ expect(detectAdapter(`{${FIXTURE_MARKER}}`)).toBeNull();+ expect(SESSION_ADAPTER_REGISTRY.has("fixture")).toBe(false);+ });++ test("a duplicate id is refused rather than silently shadowing", () => {+ const shadow: SessionAdapter = { ...fixtureAdapter, id: SESSION_ADAPTER_ID.claude };+ expect(() => createSessionAdapterRegistry([...listSessionAdapters(), shadow])).toThrow(+ /claude/,+ );+ });+});++describe("the id vocabulary and the registry agree", () => {+ test("the built-in registry's keys are exactly the declared ids", () => {+ expect([...SESSION_ADAPTER_REGISTRY.keys()].toSorted()).toEqual(+ [...SESSION_ADAPTER_IDS].toSorted(),+ );+ });++ test("isSessionAdapterId takes unknown, not string", () => {+ // A `string` parameter forces every caller to narrow first, which is+ // exactly what a guard exists to do. These calls must compile.+ const values: ReadonlyArray<unknown> = [null, undefined, 42, {}, [], "", " ", "Claude"];+ for (const value of values) expect(isSessionAdapterId(value)).toBe(false);+ for (const id of SESSION_ADAPTER_IDS) expect(isSessionAdapterId(id)).toBe(true);+ });+});diff --git a/tests/core/brain/sessions/dry-run-honesty.test.ts b/tests/core/brain/sessions/dry-run-honesty.test.tsnew file mode 100644index 00000000..1b4a4066--- /dev/null+++ b/tests/core/brain/sessions/dry-run-honesty.test.ts@@ -0,0 +1,134 @@+/**+ * A dry-run import result must be distinguishable from a real run that+ * wrote nothing (U7 of "nothing runs unwatched").+ *+ * `signals_created: 0` and `facts_extracted: 0` were the answer in both+ * cases by construction: a dry run returns before `writeSignal`, so its+ * counters report what WAS written, which is zero, and the caller cannot+ * tell a rehearsal from a session with nothing in it.+ */++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 { DEFAULT_BRAIN_CONFIG_YAML } from "../../../../src/core/brain/config-template.ts";+import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";+import { brainDirs } from "../../../../src/core/brain/paths.ts";+import { importSession, IMPORT_WRITE_MODE } from "../../../../src/core/brain/sessions/import.ts";++let tmp: string;++const NOW = new Date("2026-08-15T10:00:00Z");++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-dryrun-honesty-"));+ const dirs = brainDirs(tmp);+ for (const d of [dirs.brain, dirs.inbox, dirs.processed, dirs.preferences, dirs.log]) {+ mkdirSync(d, { recursive: true });+ }+ atomicWriteFileSync(join(dirs.brain, "config.yaml"), DEFAULT_BRAIN_CONFIG_YAML);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++/** One Claude-format transcript file with the given user texts. */+function writeSessionFile(name: string, texts: readonly string[]): string {+ const path = join(tmp, name);+ const lines = texts.map((text, index) =>+ JSON.stringify({+ type: "user",+ parentUuid: null,+ entrypoint: "cli",+ uuid: `u${index}`,+ timestamp: "2026-08-15T09:00:00.000Z",+ sessionId: "s1",+ message: { role: "user", content: [{ type: "text", text }] },+ }),+ );+ writeFileSync(path, lines.join("\n") + "\n", "utf8");+ return path;+}++const MARKER = '@osb feedback positive topic=dry-run-probe principle="Prove the rehearsal"';++function inboxCount(): number {+ return readdirSync(brainDirs(tmp).inbox).filter((n) => n.endsWith(".md")).length;+}++describe("a dry run reports what it would have written", () => {+ test("write_mode names the rehearsal and signals_withheld carries the forecast", async () => {+ const path = writeSessionFile("with-marker.jsonl", [MARKER]);+ const result = await importSession(tmp, path, {+ agent: "@t",+ dryRun: true,+ now: NOW,+ });+ expect(result.write_mode).toBe(IMPORT_WRITE_MODE.dryRun);+ expect(result.signals_created).toBe(0);+ expect(result.signals_withheld).toBe(1);+ // Inert: the rehearsal still wrote nothing.+ expect(inboxCount()).toBe(0);+ });++ test("a real run that found nothing is a different answer, not the same zero", async () => {+ const path = writeSessionFile("no-marker.jsonl", ["just some prose with no marker in it"]);+ const real = await importSession(tmp, path, { agent: "@t", now: NOW });+ expect(real.write_mode).toBe(IMPORT_WRITE_MODE.applied);+ expect(real.signals_created).toBe(0);+ expect(real.signals_withheld).toBe(0);++ const rehearsal = await importSession(tmp, writeSessionFile("m2.jsonl", [MARKER]), {+ agent: "@t",+ dryRun: true,+ now: NOW,+ });+ // The pair the defect collapsed: same created count, different runs.+ expect(rehearsal.signals_created).toBe(real.signals_created);+ expect(rehearsal.write_mode).not.toBe(real.write_mode);+ expect(rehearsal.signals_withheld).not.toBe(real.signals_withheld);+ });++ test("the forecast matches what the real run then writes", async () => {+ const path = writeSessionFile("forecast.jsonl", [MARKER]);+ const rehearsal = await importSession(tmp, path, { agent: "@t", dryRun: true, now: NOW });+ const applied = await importSession(tmp, path, { agent: "@t", now: NOW });+ expect(applied.signals_created).toBe(rehearsal.signals_withheld);+ expect(applied.signals_withheld).toBe(0);+ expect(inboxCount()).toBe(1);+ });++ test("a repeated marker in one dry run is forecast once, not twice", async () => {+ const path = writeSessionFile("repeat.jsonl", [MARKER, MARKER]);+ const rehearsal = await importSession(tmp, path, { agent: "@t", dryRun: true, now: NOW });+ expect(rehearsal.signals_withheld).toBe(1);+ expect(rehearsal.signals_deduped).toBe(1);+ });+});++describe("extracted facts are forecast the same way", () => {+ // A url is one of the language-neutral fact families the extractor knows.+ const FACT_TEXT = "The index lives at https://example.com/local-index";++ test("facts_withheld separates a rehearsal from a session with no facts", async () => {+ const withFacts = writeSessionFile("facts.jsonl", [FACT_TEXT]);+ const rehearsal = await importSession(tmp, withFacts, {+ agent: "@t",+ dryRun: true,+ now: NOW,+ });+ const empty = await importSession(tmp, writeSessionFile("nofacts.jsonl", ["ok"]), {+ agent: "@t",+ dryRun: true,+ now: NOW,+ });+ expect(rehearsal.facts_extracted).toBe(0);+ expect(empty.facts_extracted).toBe(0);+ expect(rehearsal.facts_withheld).toBeGreaterThan(0);+ expect(empty.facts_withheld).toBe(0);+ expect(inboxCount()).toBe(0);+ });+});diff --git a/tests/core/brain/snapshot-derived-store.test.ts b/tests/core/brain/snapshot-derived-store.test.tsindex b281b677..9af6802a 100644--- a/tests/core/brain/snapshot-derived-store.test.ts+++ b/tests/core/brain/snapshot-derived-store.test.ts@@ -243,7 +243,7 @@ describe("listSnapshots and pruneSnapshots over a covered snapshot", () => {await seedDerivedStore();createSnapshot(vault, "dream-list-covered", { reason: DREAM, derivedStore: COVERED });- const [info] = listSnapshots(vault);+ const [info] = listSnapshots(vault).snapshots;expect(info?.derived_store?.included).toBe(true);expect(info?.store_archive_path).toBe(snapshotStorePath(vault, "dream-list-covered"));});@@ -258,7 +258,7 @@ describe("listSnapshots and pruneSnapshots over a covered snapshot", () => {delete parsed["derived_store"];writeFileSync(sidecar, JSON.stringify(parsed, null, 2) + "\n");- const [info] = listSnapshots(vault);+ const [info] = listSnapshots(vault).snapshots;// `null` is UNKNOWN. An `excluded` record would claim a check ran.expect(info?.derived_store).toBeNull();expect(readManifestSidecar(vault, runId)).not.toBeNull();diff --git a/tests/core/brain/snapshot-gate-coverage.test.ts b/tests/core/brain/snapshot-gate-coverage.test.tsindex 5ccf64fd..58959c46 100644--- a/tests/core/brain/snapshot-gate-coverage.test.ts+++ b/tests/core/brain/snapshot-gate-coverage.test.ts@@ -134,6 +134,15 @@ function dreamOutputRows(brainRoot: string): string[] {const rel = relative(brainRoot, abs).split(sep).join("/");if (rel.startsWith(".snapshots/") || rel.startsWith("log/dream-runs/")) continue;if (rel === "vault-id.json") continue;+ // `_brain.yaml` is bootstrap output, not dream output - the pass+ // reads it and nothing writes the decision back (`dream.ts:194`).+ // It was inside this digest until a release that added commented+ // config keys moved the number without touching a single byte the+ // pass authored, which is a false alarm on a guard whose whole+ // value is that it never fires falsely. Verified before excluding:+ // with the config file out, main and this branch produce identical+ // rows for every other file.+ if (rel === "_brain.yaml") continue;const path = rel.replace(/^log\/(\d{4}-\d{2}-\d{2})\.[0-9a-f]{8}\./, "log/$1.");const text = readFileSync(abs, "utf8").replace(/^vault_name: .*$/gm, "vault_name: <name>")@@ -179,15 +188,15 @@ describe("a rollback keeps what it discards", () => {// restore's deletion, which is what makes this recoverable at all.expect(out.recoveryPoint.runId.startsWith(BRAIN_SNAPSHOT_REASON.manual)).toBe(true);expect(existsSync(out.recoveryPoint.path)).toBe(true);- expect(listSnapshots(vault).map((s) => s.run_id)).toContain(out.recoveryPoint.runId);+ expect(listSnapshots(vault).snapshots.map((s) => s.run_id)).toContain(out.recoveryPoint.runId);});test("the recovery point is taken after extraction, so a corrupt archive mints nothing", () => {// Ordering matters: a rollback that cannot read its target must not// leave an archive of a tree it never touched.- const before = listSnapshots(vault).length;+ const before = listSnapshots(vault).snapshots.length;expect(() => restoreSnapshotWithRecoveryPoint(vault, "manual-absent", { now: NOW })).toThrow();- expect(listSnapshots(vault).length).toBe(before);+ expect(listSnapshots(vault).snapshots.length).toBe(before);});test("a direct restore says it proved nothing rather than staying silent", () => {@@ -206,10 +215,18 @@ describe("the dream pass runs behind the gate, not beside it", () => {// this exact fixture against the tree WITHOUT this unit and pasted// here; it then had to keep matching with the unit applied. A// recomputed expectation would prove nothing at all.+ //+ // Re-measured once, in nothing-runs-unwatched, when `_brain.yaml`+ // left the row set: the digest had moved because a commented config+ // key made the bootstrapped template longer, which is not a byte the+ // pass authored. The replacement literal was taken from `main` with+ // the same exclusion applied, and this branch reproduces it - so it+ // is still a number from a tree without the units it guards, not a+ // number this branch invented about itself.seedSignal("tidy");dream(vault, { now: NOW, agentName: "tester" });expect(dreamOutputDigest(join(vault, "Brain"))).toBe(- "6ef6ceba9a49583ab15fef3d9f9889429e7cd82b00ba44cb571f0d7ef81500d8",+ "1944a3340e6aee531205e0e3042ca957b23cb67a9254d10b649d49a51e504446",);});@@ -240,7 +257,7 @@ describe("the dream pass runs behind the gate, not beside it", () => {test("the archive still carries the dream run id, not a second id of its own", () => {seedSignal("tidy");const summary = dream(vault, { now: NOW, agentName: "tester" });- const ids = listSnapshots(vault).map((s) => s.run_id);+ const ids = listSnapshots(vault).snapshots.map((s) => s.run_id);expect(ids).toContain(summary.run_id);// Exactly one archive per run. A gate that minted its own id beside// dream's would leave two, and the workrun would name neither.@@ -262,7 +279,7 @@ describe("the dream pass runs behind the gate, not beside it", () => {test("a dry run still takes no snapshot at all", () => {seedSignal("tidy");dream(vault, { now: NOW, dryRun: true, agentName: "tester" });- expect(listSnapshots(vault)).toEqual([]);+ expect(listSnapshots(vault).snapshots).toEqual([]);});});@@ -284,7 +301,7 @@ describe("the prune has a floor and says what it did", () => {expect(result.refusal).toBe(SNAPSHOT_PRUNE_REFUSAL.belowRetentionFloor);expect(result.deleted).toEqual([]);// The whole point: the archives are still there.- expect(listSnapshots(vault).length).toBe(3);+ expect(listSnapshots(vault).snapshots.length).toBe(3);});test("the floor is the smallest retention that keeps a way back", () => {diff --git a/tests/core/brain/snapshot-gate.test.ts b/tests/core/brain/snapshot-gate.test.tsindex 2cdfbac2..a688e488 100644--- a/tests/core/brain/snapshot-gate.test.ts+++ b/tests/core/brain/snapshot-gate.test.ts@@ -78,7 +78,7 @@ describe("withDestructiveSnapshot", () => {BRAIN_SNAPSHOT_REASON.deleteBySource,() => {// The snapshot archive must already exist by the time op runs.- archiveCountWhenOpRan = listSnapshots(vault).length;+ archiveCountWhenOpRan = listSnapshots(vault).snapshots.length;return "result-value";},{ now: new Date("2026-06-01T00:00:00Z") },@@ -93,9 +93,9 @@ describe("withDestructiveSnapshot", () => {test("op runs after the snapshot exists (order proven)", () => {let order: string[] = [];- const before = listSnapshots(vault).length;+ const before = listSnapshots(vault).snapshots.length;withDestructiveSnapshot(vault, BRAIN_SNAPSHOT_REASON.entityPrune, () => {- order.push(`snapshots=${listSnapshots(vault).length}`);+ order.push(`snapshots=${listSnapshots(vault).snapshots.length}`);});expect(order).toEqual([`snapshots=${before + 1}`]);});@@ -138,18 +138,18 @@ describe("withDestructiveSnapshot", () => {}),).toThrow(BrainSnapshotStoreError);expect(opRan).toBe(false);- expect(listSnapshots(vault)).toHaveLength(0);+ expect(listSnapshots(vault).snapshots).toHaveLength(0);});test("op error propagates but the snapshot is retained as recovery point", () => {- const before = listSnapshots(vault).length;+ const before = listSnapshots(vault).snapshots.length;expect(() =>withDestructiveSnapshot(vault, BRAIN_SNAPSHOT_REASON.deleteBySource, () => {throw new Error("op blew up");}),).toThrow("op blew up");// The snapshot survives - it is the recovery point.- expect(listSnapshots(vault).length).toBe(before + 1);+ expect(listSnapshots(vault).snapshots.length).toBe(before + 1);});test("prunes to the configured retention after a successful op", () => {@@ -163,7 +163,7 @@ describe("withDestructiveSnapshot", () => {now: new Date(`2026-06-0${i + 1}T00:00:00Z`),});}- expect(listSnapshots(vault).length).toBe(2);+ expect(listSnapshots(vault).snapshots.length).toBe(2);});test("mints unique run ids when the base id already exists", () => {@@ -211,7 +211,7 @@ describe("withDestructiveSnapshot", () => {test("stamps the reason it was given into the snapshot's sidecar", () => {const out = withDestructiveSnapshot(vault, BRAIN_SNAPSHOT_REASON.entityPrune, () => undefined);- const listed = listSnapshots(vault).find((s) => s.run_id === out.snapshot.runId);+ const listed = listSnapshots(vault).snapshots.find((s) => s.run_id === out.snapshot.runId);expect(listed?.reason).toBe(BRAIN_SNAPSHOT_REASON.entityPrune);});});@@ -280,7 +280,7 @@ describe("takeSnapshot and withDestructiveSnapshot share one archive path", () =const snap = takeSnapshot(vault, BRAIN_SNAPSHOT_REASON.manual);expect(snap.runId).toMatch(/^manual-/);expect(existsSync(snap.path)).toBe(true);- expect(listSnapshots(vault).find((s) => s.run_id === snap.runId)?.reason).toBe(+ expect(listSnapshots(vault).snapshots.find((s) => s.run_id === snap.runId)?.reason).toBe(BRAIN_SNAPSHOT_REASON.manual,);});@@ -294,7 +294,7 @@ describe("takeSnapshot and withDestructiveSnapshot share one archive path", () =process.env["PATH"] = emptyDir;try {expect(() => takeSnapshot(vault, BRAIN_SNAPSHOT_REASON.manual)).toThrow();- expect(listSnapshots(vault)).toHaveLength(0);+ expect(listSnapshots(vault).snapshots).toHaveLength(0);} finally {process.env["PATH"] = savedPath;rmSync(emptyDir, { recursive: true, force: true });diff --git a/tests/core/brain/snapshot-reason.test.ts b/tests/core/brain/snapshot-reason.test.tsindex 9395dcb7..5865ec63 100644--- a/tests/core/brain/snapshot-reason.test.ts+++ b/tests/core/brain/snapshot-reason.test.ts@@ -70,7 +70,7 @@ describe("createSnapshot stamps the reason into the sidecar", () => {expect(readManifestSidecar(vault, runId)?.snapshot_reason).toBe(BRAIN_SNAPSHOT_REASON.entityPrune,);- const listed = listSnapshots(vault).find((s) => s.run_id === runId);+ const listed = listSnapshots(vault).snapshots.find((s) => s.run_id === runId);expect(listed?.reason).toBe(BRAIN_SNAPSHOT_REASON.entityPrune);});@@ -96,7 +96,7 @@ describe("createSnapshot stamps the reason into the sidecar", () => {// for provenance nothing recorded.unlinkSync(manifestSidecarPath(vault, runId));- const listed = listSnapshots(vault).find((s) => s.run_id === runId);+ const listed = listSnapshots(vault).snapshots.find((s) => s.run_id === runId);expect(listed).toBeDefined();expect(listed!.reason).toBeNull();expect(listed!.manifest_path).toBeNull();@@ -121,7 +121,7 @@ describe("createSnapshot stamps the reason into the sidecar", () => {expect(manifest!.snapshot_reason_unreadable).toBe(true);expect(Object.keys(manifest!.files).length).toBeGreaterThan(0);// The listing still refuses to name a provenance it cannot read.- expect(listSnapshots(vault).find((s) => s.run_id === runId)!.reason).toBeNull();+ expect(listSnapshots(vault).snapshots.find((s) => s.run_id === runId)!.reason).toBeNull();});});diff --git a/tests/core/brain/snapshot-recovery-point.test.ts b/tests/core/brain/snapshot-recovery-point.test.tsindex ccc0ff3c..14e7065e 100644--- a/tests/core/brain/snapshot-recovery-point.test.ts+++ b/tests/core/brain/snapshot-recovery-point.test.ts@@ -171,7 +171,7 @@ describe("the retention pass behind a recovery point cannot evict it", () => {expect(existsSync(point.path)).toBe(true);expect(point.prune?.deleted).not.toContain(point.path);expect(existsSync(stale)).toBe(false);- expect(listSnapshots(vault).map((s) => s.run_id)).toEqual([point.runId]);+ expect(listSnapshots(vault).snapshots.map((s) => s.run_id)).toEqual([point.runId]);});test("an equal-millisecond mtime does not decide it either", () => {@@ -223,7 +223,7 @@ describe("the retention pass behind a recovery point cannot evict it", () => {// so a vault configured with zero takes no recovery point and runs no// destructive operation until the operator fixes the value.expect(() => takeSnapshot(vault, BRAIN_SNAPSHOT_REASON.manual)).toThrow(BrainConfigError);- expect(listSnapshots(vault)).toEqual([]);+ expect(listSnapshots(vault).snapshots).toEqual([]);});test("the gate refuses to run the operation when the point is not on disk", () => {@@ -245,7 +245,7 @@ describe("the retention pass behind a recovery point cannot evict it", () => {vault,BRAIN_SNAPSHOT_REASON.deleteBySource,() => {- archivesWhenOpRan = listSnapshots(vault).length;+ archivesWhenOpRan = listSnapshots(vault).snapshots.length;return 1;},{ now: new Date("2026-06-01T00:00:00Z") },diff --git a/tests/core/brain/source-cleanup.test.ts b/tests/core/brain/source-cleanup.test.tsindex 6a6d4323..e1f1c043 100644--- a/tests/core/brain/source-cleanup.test.ts+++ b/tests/core/brain/source-cleanup.test.ts@@ -270,7 +270,7 @@ describe("deleteBySource - D1 snapshot gate", () => {expect(existsSync(plan.snapshotPath!)).toBe(true);// A snapshot archive exists and is listed by the engine.- const snaps = listSnapshots(vault);+ const snaps = listSnapshots(vault).snapshots;expect(snaps.some((s) => s.run_id === plan.snapshotRunId)).toBe(true);// The archive is restorable: it contains the files that were deleted.@@ -297,16 +297,16 @@ describe("deleteBySource - D1 snapshot gate", () => {test("dry-run takes NO snapshot", () => {seedContaminatedVault();- const before = listSnapshots(vault).length;+ const before = listSnapshots(vault).snapshots.length;const plan = deleteBySource(vault, SOURCE, { now: NOW });expect(plan.snapshotRunId).toBeNull();expect(plan.snapshotPath).toBeNull();- expect(listSnapshots(vault).length).toBe(before);+ expect(listSnapshots(vault).snapshots.length).toBe(before);});test("confirm with nothing to delete takes NO snapshot (no-op stays a no-op)", () => {// A pristine vault with no derived material for this source.- const before = listSnapshots(vault).length;+ const before = listSnapshots(vault).snapshots.length;const plan = deleteBySource(vault, "imports/does-not-exist.md", {confirm: true,now: NOW,@@ -314,7 +314,7 @@ describe("deleteBySource - D1 snapshot gate", () => {expect(plan.deleted).toEqual([]);expect(plan.snapshotRunId).toBeNull();expect(plan.snapshotPath).toBeNull();- expect(listSnapshots(vault).length).toBe(before);+ expect(listSnapshots(vault).snapshots.length).toBe(before);});});diff --git a/tests/core/brain/sync-lockfile.test.ts b/tests/core/brain/sync-lockfile.test.tsindex afb5f171..e4739031 100644--- a/tests/core/brain/sync-lockfile.test.ts+++ b/tests/core/brain/sync-lockfile.test.ts@@ -6,11 +6,27 @@*/import { afterAll, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";-import { acquireLockSync, scanStaleLocks } from "../../../src/core/brain/sync-lockfile.ts";+import {+ acquireLockSync,+ acquireLockSyncWithRetry,+ LOCK_WAIT_BUDGET_MS,+ LOCK_WAIT_INTERACTIVE_MS,+ lockScanRoots,+ scanStaleLocks,+} from "../../../src/core/brain/sync-lockfile.ts";let tmpRoot: string;@@ -90,14 +106,14 @@ describe("acquireLockSync", () => {});describe("scanStaleLocks", () => {- test("returns paths of every .lock file under the given root", () => {- const a = join(tmpRoot, "pref-a.md");- const b = join(tmpRoot, "sub", "pref-b.md");+ test("returns paths of every .lock file under Brain/", () => {+ const a = join(tmpRoot, "Brain", "preferences", "pref-a.md");+ const b = join(tmpRoot, "Brain", "log", "continuity", "2026-06.jsonl");+ mkdirSync(dirname(a), { recursive: true });+ mkdirSync(dirname(b), { recursive: true });writeFileSync(a, "");const ha = acquireLockSync(a);- // Manually drop a lock under a subdirectory to exercise the walk.- const subDir = join(tmpRoot, "sub");- require("node:fs").mkdirSync(subDir, { recursive: true });+ // Manually drop a lock deeper in the tree to exercise the walk.writeFileSync(b + ".lock", "");const found = scanStaleLocks(tmpRoot).toSorted();@@ -108,8 +124,228 @@ describe("scanStaleLocks", () => {require("node:fs").unlinkSync(b + ".lock");});+ /**+ * The manifest and the ingest checkpoint - the two locks the parallel+ * ingest path takes most often - live in `.open-second-brain/`, not in+ * `Brain/`. A scan rooted at `Brain/` alone reported nothing for them,+ * so a crashed ingest left a lock the doctor could not name.+ */+ test("returns .lock files under the derived-store directory too", () => {+ const manifest = join(tmpRoot, ".open-second-brain", "ingest-manifest.json");+ const checkpoint = join(+ tmpRoot,+ ".open-second-brain",+ "ingest-checkpoints",+ "0123456789abcdef.json",+ );+ mkdirSync(dirname(checkpoint), { recursive: true });+ const hm = acquireLockSync(manifest);+ const hc = acquireLockSync(checkpoint);+ try {+ const found = scanStaleLocks(tmpRoot);+ expect(found).toContain(manifest + ".lock");+ expect(found).toContain(checkpoint + ".lock");+ } finally {+ hm.release();+ hc.release();+ }+ });+test("returns an empty array when no locks exist", () => {const found = scanStaleLocks(tmpRoot);expect(found).toEqual([]);});++ test("a lock outside every enumerated root is not reported", () => {+ // Not a defect - it is the enumeration's boundary, stated so the+ // census below has something to be a census OF.+ const stray = join(tmpRoot, "notes", "user-note.md");+ mkdirSync(dirname(stray), { recursive: true });+ const handle = acquireLockSync(stray);+ try {+ expect(scanStaleLocks(tmpRoot)).toEqual([]);+ } finally {+ handle.release();+ }+ });+});++/**+ * The scan walks an ENUMERATED set of roots ({@link lockScanRoots}) rather+ * than one hard-coded directory, so a lock location that is not under one+ * of them escapes `brain doctor` silently - which is exactly what happened+ * to the manifest and the checkpoint.+ *+ * This census reads the sources rather than their behaviour, in the same+ * discipline as `tests/hooks/audit-root.test.ts`: the defect is not that+ * any one module locks the wrong place today, it is that adding a+ * thirteenth lock site under a third root would leave the scan quietly+ * incomplete. A new site fails this list until its author states which+ * root the scan will find it under.+ */+describe("every module that takes a lock is under a scanned root", () => {+ const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "src");++ /**+ * Declared lock sites, each with the vault-relative root+ * {@link lockScanRoots} reaches it through. Verified against the path+ * builders: every entry resolves under `Brain/` except the two ingest+ * artefacts, which live in the derived-store directory.+ */+ const DECLARED: ReadonlyMap<string, string> = new Map([+ ["core/brain/architect/generate.ts", "Brain"],+ ["core/brain/continuity/store.ts", "Brain"],+ ["core/brain/diagnostics.ts", "Brain"],+ ["core/brain/git/store.ts", "Brain"],+ ["core/brain/health/remediation.ts", "Brain"],+ ["core/brain/idempotency-ledger.ts", "Brain"],+ ["core/brain/ingest/checkpoint.ts", ".open-second-brain"],+ ["core/brain/ingest/content-manifest.ts", ".open-second-brain"],+ ["core/brain/lineage/ledger.ts", "Brain"],+ ["core/brain/preference-txn.ts", "Brain"],+ ["core/brain/query-demand.ts", "Brain"],+ ["core/brain/skill-proposals.ts", "Brain"],+ ]);++ /** Every `src/` file that calls the lock primitive, vault-relative to `src/`. */+ function lockCallers(): string[] {+ const out: string[] = [];+ const walk = (dir: string): void => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) {+ walk(full);+ continue;+ }+ if (!entry.name.endsWith(".ts")) continue;+ const rel = full.slice(SRC.length + 1).replaceAll("\\", "/");+ if (rel === "core/brain/sync-lockfile.ts") continue;+ const text = readFileSync(full, "utf8");+ if (/acquireLockSync(WithRetry)?\(/.test(text)) out.push(rel);+ }+ };+ walk(SRC);+ return out.toSorted();+ }++ test("the sweep actually found the lock callers", () => {+ // A census over an empty set passes for the wrong reason.+ expect(lockCallers().length).toBeGreaterThan(5);+ });++ test("no lock site is missing from the declared set", () => {+ const undeclared = lockCallers().filter((rel) => !DECLARED.has(rel));+ expect(undeclared).toEqual([]);+ });++ test("every declared root is one the scan actually walks", () => {+ const roots = lockScanRoots("/vault").map((abs) => abs.slice("/vault/".length));+ for (const root of new Set(DECLARED.values())) {+ expect(roots).toContain(root);+ }+ });+});++describe("acquireLockSyncWithRetry — the budget is a bound this module can honour", () => {+ test.each([Number.NaN, Number.POSITIVE_INFINITY, -1, 1.5])(+ "refuses budgetMs %p by name instead of waiting on it",+ (budget) => {+ const target = join(tmpRoot, "budget.json");+ const held = acquireLockSync(target);+ try {+ expect(() => acquireLockSyncWithRetry(target, budget)).toThrow(+ /budgetMs must be an integer >= 0/,+ );+ } finally {+ held.release();+ }+ },+ );++ test("a zero budget is legal and means exactly one attempt", () => {+ const target = join(tmpRoot, "zero-budget.json");+ const held = acquireLockSync(target);+ try {+ const started = Date.now();+ let caught: NodeJS.ErrnoException | null = null;+ try {+ acquireLockSyncWithRetry(target, 0);+ } catch (err) {+ caught = err as NodeJS.ErrnoException;+ }+ expect(caught?.code).toBe("ELOCKED");+ expect(Date.now() - started).toBeLessThan(100);+ } finally {+ held.release();+ }+ });+});++/**+ * The wait is a synchronous FREEZE of the whole thread. That is the cost+ * the module's docblock states rather than argues away, and this is what+ * pins it, in both halves: the freeze is total (no timer runs during it,+ * so no progress event is emitted, no SIGINT handler runs, and inside the+ * MCP server no other tool call proceeds), and it ends when the budget+ * does rather than running on.+ */+describe("acquireLockSyncWithRetry — what the caller gives up while it waits", () => {+ test("the wait freezes the event loop, and ends when the budget does", () => {+ const target = join(tmpRoot, "frozen.json");+ const held = acquireLockSync(target);+ let ticks = 0;+ const timer = setInterval(() => {+ ticks++;+ }, 10);+ try {+ const budget = 300;+ const started = Date.now();+ let caught: NodeJS.ErrnoException | null = null;+ try {+ acquireLockSyncWithRetry(target, budget);+ } catch (err) {+ caught = err as NodeJS.ErrnoException;+ }+ const elapsed = Date.now() - started;+ expect(caught?.code).toBe("ELOCKED");+ // Bounded: the wait ends at the budget, not at some multiple of it.+ expect(elapsed).toBeGreaterThanOrEqual(budget);+ expect(elapsed).toBeLessThan(budget + 500);+ // Total: a 10 ms interval got no tick across 300 ms of waiting.+ // If this ever reads non-zero the wait has become interruptible,+ // and the docblock - not this expectation - is what should change+ // first.+ expect(ticks).toBe(0);+ } finally {+ clearInterval(timer);+ held.release();+ }+ });++ /**+ * The budget is not one number for everyone: it is how long a caller is+ * willing to freeze its process, which differs by what losing the race+ * costs that caller. Pinned so neither number can drift into the other's+ * job unnoticed - the default is the fan-out's, and the interactive one+ * is strictly shorter.+ */+ test("an interactive caller waits strictly less than the fan-out default", () => {+ expect(LOCK_WAIT_INTERACTIVE_MS).toBeLessThan(LOCK_WAIT_BUDGET_MS);+ // 1 s reproducibly fails the four-process manifest race, so the+ // shorter budget is a refusal to freeze, not a second default.+ expect(LOCK_WAIT_BUDGET_MS).toBeGreaterThanOrEqual(5_000);+ });++ test("the architect takes the interactive budget, not the default", () => {+ const generate = readFileSync(+ join(+ resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", ".."),+ "src/core/brain/architect/generate.ts",+ ),+ "utf8",+ );+ // An interactive pass with a progress stream and a Ctrl-C behind it+ // must not park the terminal for the fan-out's budget.+ expect(generate).toContain("acquireLockSyncWithRetry(dir, LOCK_WAIT_INTERACTIVE_MS)");+ });});diff --git a/tests/core/brain/token-impact-clip.test.ts b/tests/core/brain/token-impact-clip.test.tsindex 1532b97a..d53f0255 100644--- a/tests/core/brain/token-impact-clip.test.ts+++ b/tests/core/brain/token-impact-clip.test.ts@@ -31,7 +31,7 @@ describe("agent_id joins session_id on pack identity", () => {{baselineTokens: 100,packedTokens: 40,- method: "exact",+ method: "tokenizer",sessionId: "s-1",agentId: "claude-dev-agent",packId: "pk-1",@@ -46,7 +46,7 @@ describe("agent_id joins session_id on pack identity", () => {test("without agentId no agent_id key is written (byte-identical opt-out)", () => {const rec = emitTokenImpact(vault,- { baselineTokens: 100, packedTokens: 40, method: "exact", sessionId: "s-1" },+ { baselineTokens: 100, packedTokens: 40, method: "tokenizer", sessionId: "s-1" },true,);expect(rec).not.toBeNull();@@ -75,7 +75,7 @@ describe("clip-protected identity under an output budget", () => {{baselineTokens: 100,packedTokens: 40,- method: "exact",+ method: "tokenizer",sessionId: "s-1",agentId: "claude-dev-agent",packId: "pk-1",@@ -98,7 +98,7 @@ describe("clip-protected identity under an output budget", () => {{baselineTokens: 100,packedTokens: 40,- method: "exact",+ method: "tokenizer",sessionId: "s-1",agentId: "claude-dev-agent",},diff --git a/tests/core/brain/token-impact.test.ts b/tests/core/brain/token-impact.test.tsindex 9a0f88fe..231b2325 100644--- a/tests/core/brain/token-impact.test.ts+++ b/tests/core/brain/token-impact.test.ts@@ -3,12 +3,17 @@ import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";+import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";import {emitTokenImpact,+ isTokenCountMethod,listTokenImpact,listTokenImpactOutcomes,+ normalizeTokenCountMethod,recordTokenImpactOutcome,summarizeTokenImpact,+ TOKEN_COUNT_METHOD,+ TOKEN_COUNT_METHODS,} from "../../../src/core/brain/token-impact.ts";let tmp: string;@@ -27,10 +32,14 @@ afterEach(() => {describe("emitTokenImpact gating", () => {test("gate off writes nothing and returns null", () => {expect(- emitTokenImpact(vault, { baselineTokens: 100, packedTokens: 40, method: "exact" }, false),+ emitTokenImpact(vault, { baselineTokens: 100, packedTokens: 40, method: "tokenizer" }, false),).toBeNull();expect(- emitTokenImpact(vault, { baselineTokens: 100, packedTokens: 40, method: "exact" }, undefined),+ emitTokenImpact(+ vault,+ { baselineTokens: 100, packedTokens: 40, method: "tokenizer" },+ undefined,+ ),).toBeNull();expect(listTokenImpact(vault)).toHaveLength(0);});@@ -44,7 +53,7 @@ describe("emitTokenImpact gating", () => {packId: "receipt_123",baselineTokens: 1000,packedTokens: 320,- method: "exact",+ method: "tokenizer",},true,);@@ -53,7 +62,7 @@ describe("emitTokenImpact gating", () => {expect(record!.payload).toMatchObject({host: "mcp",pack_id: "receipt_123",- method: "exact",+ method: "tokenizer",baseline_tokens: 1000,packed_tokens: 320,delta_tokens: 680,@@ -63,7 +72,7 @@ describe("emitTokenImpact gating", () => {test("delta is negative when the memory layer adds tokens", () => {const record = emitTokenImpact(vault,- { baselineTokens: 200, packedTokens: 260, method: "fallback" },+ { baselineTokens: 200, packedTokens: 260, method: "heuristic" },true,);expect(record!.payload["delta_tokens"]).toBe(-60);@@ -73,13 +82,13 @@ describe("emitTokenImpact gating", () => {expect(emitTokenImpact(vault,- { baselineTokens: 1, packedTokens: 0, method: "bogus" as "exact" },+ { baselineTokens: 1, packedTokens: 0, method: "bogus" as "tokenizer" },true,),).toBeNull();// A negative count is also swallowed.expect(- emitTokenImpact(vault, { baselineTokens: -5, packedTokens: 0, method: "exact" }, true),+ emitTokenImpact(vault, { baselineTokens: -5, packedTokens: 0, method: "tokenizer" }, true),).toBeNull();expect(listTokenImpact(vault)).toHaveLength(0);});@@ -90,14 +99,14 @@ describe("emitTokenImpact gating", () => {{baselineTokens: 500,packedTokens: 500,- method: "exact",+ method: "tokenizer",modeledAvoidedInferences: 3,modeledTokensPerInference: 1200,},true,);expect(record!.payload).toMatchObject({- delta_tokens: 0, // exact ledger unaffected by the model+ delta_tokens: 0, // the measured delta is unaffected by the modelmodeled_avoided_inferences: 3,modeled_tokens_per_inference: 1200,modeled_savings_tokens: 3600,@@ -114,7 +123,7 @@ describe("token-impact privacy", () => {packId: "hash_abc",baselineTokens: 10,packedTokens: 4,- method: "fallback",+ method: "heuristic",},true,);@@ -123,8 +132,8 @@ describe("token-impact privacy", () => {expect(record.payload.pack_id).toBe("hash_abc");expect(record.sourceRefs).toEqual([]);// No free-text prompt/recall keys smuggled in.- expect(Object.keys(record.payload).sort()).toEqual(- ["baseline_tokens", "delta_tokens", "method", "pack_id", "packed_tokens"].sort(),+ expect(Object.keys(record.payload).toSorted()).toEqual(+ ["baseline_tokens", "delta_tokens", "method", "pack_id", "packed_tokens"].toSorted(),);});});@@ -137,7 +146,7 @@ describe("listTokenImpact", () => {createdAt: "2026-06-01T00:00:00.000Z",baselineTokens: 10,packedTokens: 1,- method: "exact",+ method: "tokenizer",},true,);@@ -147,7 +156,7 @@ describe("listTokenImpact", () => {createdAt: "2026-06-01T00:00:01.000Z",baselineTokens: 20,packedTokens: 2,- method: "fallback",+ method: "heuristic",packId: "p2",},true,@@ -155,36 +164,39 @@ describe("listTokenImpact", () => {const all = listTokenImpact(vault);expect(all).toHaveLength(2);expect(all[0]!.payload["baseline_tokens"]).toBe(20); // newest first- expect(listTokenImpact(vault, { method: "exact" })).toHaveLength(1);+ expect(listTokenImpact(vault, { method: "tokenizer" })).toHaveLength(1);expect(listTokenImpact(vault, { packId: "p2" })).toHaveLength(1);expect(listTokenImpact(vault, { limit: 1 })).toHaveLength(1);});});-describe("summarizeTokenImpact — exact vs modeled separation", () => {+describe("summarizeTokenImpact — measured vs modeled separation", () => {test("splits the prompt-token delta by method and never folds in the model", () => {- emitTokenImpact(vault, { baselineTokens: 100, packedTokens: 30, method: "exact" }, true); // +70- emitTokenImpact(vault, { baselineTokens: 50, packedTokens: 80, method: "exact" }, true); // -30+ emitTokenImpact(vault, { baselineTokens: 100, packedTokens: 30, method: "tokenizer" }, true); // +70+ emitTokenImpact(vault, { baselineTokens: 50, packedTokens: 80, method: "tokenizer" }, true); // -30emitTokenImpact(vault,{baselineTokens: 200,packedTokens: 100,- method: "fallback",+ method: "heuristic",modeledAvoidedInferences: 2,modeledTokensPerInference: 500,},true,- ); // +100 exact, 1000 modeled+ ); // +100 measured, 1000 modeledconst s = summarizeTokenImpact(vault);expect(s.total_samples).toBe(3);- // EXACT-type delta ledger.+ // Prompt-token delta ledger.expect(s.prompt_token_delta.net_savings_tokens).toBe(140); // 70 - 30 + 100expect(s.prompt_token_delta.saved_tokens).toBe(170); // 70 + 100expect(s.prompt_token_delta.added_tokens).toBe(30);- expect(s.prompt_token_delta.by_method.exact).toEqual({ samples: 2, net_savings_tokens: 40 });- expect(s.prompt_token_delta.by_method.fallback).toEqual({+ expect(s.prompt_token_delta.by_method.tokenizer).toEqual({+ samples: 2,+ net_savings_tokens: 40,+ });+ expect(s.prompt_token_delta.by_method.heuristic).toEqual({samples: 1,net_savings_tokens: 100,});@@ -205,7 +217,7 @@ describe("summarizeTokenImpact — exact vs modeled separation", () => {createdAt: `2026-06-01T00:00:0${i}.000Z`,baselineTokens: 10,packedTokens: 0,- method: "exact",+ method: "tokenizer",},true,);@@ -228,7 +240,7 @@ describe("outcome calibration", () => {{baselineTokens: 0,packedTokens: 0,- method: "exact",+ method: "tokenizer",modeledAvoidedInferences: 4,modeledTokensPerInference: 1000,},@@ -260,9 +272,63 @@ describe("outcome calibration", () => {describe("durability across restarts", () => {test("aggregates are recomputed from disk (a fresh read sees prior samples)", () => {- emitTokenImpact(vault, { baselineTokens: 90, packedTokens: 10, method: "exact" }, true);+ emitTokenImpact(vault, { baselineTokens: 90, packedTokens: 10, method: "tokenizer" }, true);// A brand-new summarize call reads only the on-disk continuity log.const s = summarizeTokenImpact(vault);expect(s.prompt_token_delta.net_savings_tokens).toBe(80);});});++describe("the ledger no longer claims exactness over caller-supplied integers", () => {+ test("the method vocabulary names provenance, not accuracy", () => {+ expect(TOKEN_COUNT_METHODS).toEqual(["tokenizer", "heuristic"]);+ expect(TOKEN_COUNT_METHOD.tokenizer).toBe("tokenizer");+ expect(TOKEN_COUNT_METHOD.heuristic).toBe("heuristic");+ expect(isTokenCountMethod("exact")).toBe(false);+ expect(isTokenCountMethod("fallback")).toBe(false);+ });++ test("records already on disk under the old labels are still classified, never dropped", () => {+ // Exactly what the pre-rename code path wrote: the two values the+ // guard now rejects. Dropping them out of the split would be a silent+ // loss of a ledger an operator already has on disk.+ appendContinuityRecord(vault, {+ kind: "token_impact",+ createdAt: "2026-05-01T10:00:00.000Z",+ sourceRefs: [],+ payload: { method: "tokenizer", baseline_tokens: 100, packed_tokens: 30, delta_tokens: 70 },+ });+ appendContinuityRecord(vault, {+ kind: "token_impact",+ createdAt: "2026-05-01T10:01:00.000Z",+ sourceRefs: [],+ payload: { method: "heuristic", baseline_tokens: 50, packed_tokens: 45, delta_tokens: 5 },+ });++ const s = summarizeTokenImpact(vault);+ expect(s.total_samples).toBe(2);+ expect(s.prompt_token_delta.by_method.tokenizer).toEqual({+ samples: 1,+ net_savings_tokens: 70,+ });+ expect(s.prompt_token_delta.by_method.heuristic).toEqual({+ samples: 1,+ net_savings_tokens: 5,+ });+ expect(normalizeTokenCountMethod("exact")).toBe(TOKEN_COUNT_METHOD.tokenizer);+ expect(normalizeTokenCountMethod("fallback")).toBe(TOKEN_COUNT_METHOD.heuristic);+ expect(normalizeTokenCountMethod("nonsense")).toBeNull();+ });++ test("no executable line still labels a caller's integers exact", async () => {+ const source = await Bun.file(+ new URL("../../../src/core/brain/token-impact.ts", import.meta.url).pathname,+ ).text();+ // Comments may (and do) explain the retired label; code may not use it+ // for anything but the documented legacy read.+ const code = source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "");+ expect(code).not.toContain('"exact"');+ expect(code).not.toContain('"fallback"');+ expect(code).not.toContain("byMethod.exact");+ });+});diff --git a/tests/core/brain/upgrade.test.ts b/tests/core/brain/upgrade.test.tsindex 0ab85680..d81990c6 100644--- a/tests/core/brain/upgrade.test.ts+++ b/tests/core/brain/upgrade.test.ts@@ -205,11 +205,11 @@ describe("planUpgrade", () => {describe("applyUpgrade", () => {test("nothing to do → no snapshot, no log row", () => {- const before = listSnapshots(vault).length;+ const before = listSnapshots(vault).snapshots.length;const res = applyUpgrade(vault, { agent: "claude-vps-agent" });expect(res.files_updated).toEqual([]);expect(res.run_id).toBe("");- expect(listSnapshots(vault).length).toBe(before);+ expect(listSnapshots(vault).snapshots.length).toBe(before);});test("pending update → snapshot, files rewritten, idempotent re-run", () => {@@ -218,7 +218,7 @@ describe("applyUpgrade", () => {expect(res.run_id.startsWith("upgrade-")).toBe(true);expect(res.files_updated).toContain("Brain/_BRAIN.md");// Snapshot exists with the upgrade prefix.- const snaps = listSnapshots(vault);+ const snaps = listSnapshots(vault).snapshots;expect(snaps.some((s) => s.run_id === res.run_id)).toBe(true);// The live file is now the canonical template body.expect(readFileSync(brainManualPath(vault), "utf8")).not.toBe("stale operator copy\n");@@ -244,9 +244,9 @@ describe("applyUpgrade", () => {test("malformed _brain.yaml refuses to apply (no snapshot taken)", () => {atomicWriteFileSync(brainConfigPath(vault), "not: a valid: brain yaml\n");- const before = listSnapshots(vault).length;+ const before = listSnapshots(vault).snapshots.length;expect(() => applyUpgrade(vault, { agent: "claude" })).toThrow(/upgrade aborted/);- expect(listSnapshots(vault).length).toBe(before);+ expect(listSnapshots(vault).snapshots.length).toBe(before);});test("can rollback to upgrade-<ts> snapshot to undo the apply", () => {@@ -259,7 +259,7 @@ describe("applyUpgrade", () => {// the snapshot exists and the upgrade actually changed bytes.const afterBytes = readFileSync(brainManualPath(vault), "utf8");expect(afterBytes).not.toBe(beforeBytes);- expect(listSnapshots(vault).some((s) => s.run_id === res.run_id)).toBe(true);+ expect(listSnapshots(vault).snapshots.some((s) => s.run_id === res.run_id)).toBe(true);});});diff --git a/tests/core/discipline/transcripts.test.ts b/tests/core/discipline/transcripts.test.tsindex 9c81085a..93167562 100644--- a/tests/core/discipline/transcripts.test.ts+++ b/tests/core/discipline/transcripts.test.ts@@ -35,7 +35,7 @@ function writeWithMtime(path: string, contents: string, when: Date): void {describe("claude-code transcript resolver", () => {test("returns nothing when ~/.claude/projects is missing", () => {- expect(claudeCodeTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ expect(claudeCodeTranscript.scan(DAY_START, DAY_END, home).files).toEqual([]);});test("returns sessions modified within the window", () => {@@ -43,7 +43,7 @@ describe("claude-code transcript resolver", () => {mkdirSync(projDir, { recursive: true });writeWithMtime(join(projDir, "sess-a.jsonl"), "{}", IN_DAY);writeWithMtime(join(projDir, "sess-b.jsonl"), "{}", OUT_OF_DAY);- const out = claudeCodeTranscript.collect(DAY_START, DAY_END, home);+ const out = claudeCodeTranscript.scan(DAY_START, DAY_END, home).files;expect(out).toHaveLength(1);expect(out[0]).toContain("sess-a.jsonl");});@@ -52,13 +52,13 @@ describe("claude-code transcript resolver", () => {const projDir = join(home, ".claude", "projects", "p");mkdirSync(projDir, { recursive: true });writeWithMtime(join(projDir, "readme.md"), "ok", IN_DAY);- expect(claudeCodeTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ expect(claudeCodeTranscript.scan(DAY_START, DAY_END, home).files).toEqual([]);});});describe("codex transcript resolver", () => {test("returns nothing when ~/.codex is missing", () => {- expect(codexTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ expect(codexTranscript.scan(DAY_START, DAY_END, home).files).toEqual([]);});test("walks sessions/ subdir for .json files", () => {@@ -66,7 +66,7 @@ describe("codex transcript resolver", () => {mkdirSync(dir, { recursive: true });writeWithMtime(join(dir, "a.json"), "{}", IN_DAY);writeWithMtime(join(dir, "b.json"), "{}", OUT_OF_DAY);- const out = codexTranscript.collect(DAY_START, DAY_END, home);+ const out = codexTranscript.scan(DAY_START, DAY_END, home).files;expect(out).toHaveLength(1);});@@ -74,21 +74,21 @@ describe("codex transcript resolver", () => {const dir = join(home, ".codex", ".tmp", "marketplaces", "x");mkdirSync(dir, { recursive: true });writeWithMtime(join(dir, "trace.json"), "{}", IN_DAY);- const out = codexTranscript.collect(DAY_START, DAY_END, home);+ const out = codexTranscript.scan(DAY_START, DAY_END, home).files;expect(out).toHaveLength(1);});});describe("cursor transcript resolver", () => {test("returns nothing when no Cursor workspace storage exists", () => {- expect(cursorTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ expect(cursorTranscript.scan(DAY_START, DAY_END, home).files).toEqual([]);});test("returns state.vscdb files modified within the window", () => {const dir = join(home, ".config", "Cursor", "User", "workspaceStorage", "abc123");mkdirSync(dir, { recursive: true });writeWithMtime(join(dir, "state.vscdb"), "binary", IN_DAY);- const out = cursorTranscript.collect(DAY_START, DAY_END, home);+ const out = cursorTranscript.scan(DAY_START, DAY_END, home).files;expect(out).toHaveLength(1);});@@ -96,7 +96,7 @@ describe("cursor transcript resolver", () => {const dir = join(home, ".config", "Cursor", "User", "workspaceStorage", "abc");mkdirSync(dir, { recursive: true });writeWithMtime(join(dir, "state.vscdb"), "binary", OUT_OF_DAY);- expect(cursorTranscript.collect(DAY_START, DAY_END, home)).toEqual([]);+ expect(cursorTranscript.scan(DAY_START, DAY_END, home).files).toEqual([]);});});diff --git a/tests/core/discipline/transcripts/scan-states.test.ts b/tests/core/discipline/transcripts/scan-states.test.tsnew file mode 100644index 00000000..e8b17d05--- /dev/null+++ b/tests/core/discipline/transcripts/scan-states.test.ts@@ -0,0 +1,165 @@+/**+ * Which emptiness a transcript scan found (U7 of "nothing runs unwatched").+ *+ * The resolvers used to answer with a bare `[]` for three unrelated+ * conditions: the runtime is not installed, its store is there but could not+ * be read, and the agent genuinely did nothing. That count feeds the+ * discipline alert, where the middle case - an unreadable home - was+ * indistinguishable from a confirmed quiet day.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { chmodSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { claudeCodeTranscript } from "../../../../src/core/discipline/transcripts/claude-code.ts";+import { codexTranscript } from "../../../../src/core/discipline/transcripts/codex.ts";+import { cursorTranscript } from "../../../../src/core/discipline/transcripts/cursor.ts";+import { collectTranscriptActivity } from "../../../../src/core/discipline/transcripts/index.ts";+import { TRANSCRIPT_SCAN } from "../../../../src/core/discipline/transcripts/types.ts";++const DAY_START = new Date("2026-05-19T00:00:00Z").getTime();+const DAY_END = new Date("2026-05-20T00:00:00Z").getTime();+const IN_DAY = new Date("2026-05-19T12:00:00Z");++/** Restored in afterEach so the temp tree can be removed. */+const lockedDirs: string[] = [];++let home: string;++beforeEach(() => {+ home = mkdtempSync(join(tmpdir(), "osb-transcript-scan-"));+});++afterEach(() => {+ for (const dir of lockedDirs) {+ try {+ chmodSync(dir, 0o755);+ } catch {+ // already gone+ }+ }+ lockedDirs.length = 0;+ rmSync(home, { recursive: true, force: true });+});++function writeInDay(path: string): void {+ writeFileSync(path, "{}");+ utimesSync(path, IN_DAY, IN_DAY);+}++/** Make a directory exist but refuse enumeration. */+function makeUnreadable(dir: string): string {+ chmodSync(dir, 0o000);+ lockedDirs.push(dir);+ return dir;+}++describe("claude-code — the three emptinesses are three answers", () => {+ test("an absent store is root_absent, not an empty day", () => {+ const scan = claudeCodeTranscript.scan(DAY_START, DAY_END, home);+ expect(scan.state).toBe(TRANSCRIPT_SCAN.rootAbsent);+ expect(scan.files).toEqual([]);+ expect(scan.unreadable).toEqual([]);+ });++ test("a store that exists and cannot be read is unreadable, and names the path", () => {+ const base = join(home, ".claude", "projects");+ mkdirSync(base, { recursive: true });+ makeUnreadable(base);+ const scan = claudeCodeTranscript.scan(DAY_START, DAY_END, home);+ expect(scan.state).toBe(TRANSCRIPT_SCAN.unreadable);+ expect(scan.unreadable).toContain(base);+ });++ test("a readable store with nothing in the window is idle", () => {+ mkdirSync(join(home, ".claude", "projects", "proj"), { recursive: true });+ const scan = claudeCodeTranscript.scan(DAY_START, DAY_END, home);+ expect(scan.state).toBe(TRANSCRIPT_SCAN.idle);+ expect(scan.files).toEqual([]);+ expect(scan.unreadable).toEqual([]);+ });++ test("files in the window are collected", () => {+ const proj = join(home, ".claude", "projects", "proj");+ mkdirSync(proj, { recursive: true });+ writeInDay(join(proj, "s.jsonl"));+ const scan = claudeCodeTranscript.scan(DAY_START, DAY_END, home);+ expect(scan.state).toBe(TRANSCRIPT_SCAN.collected);+ expect(scan.files).toHaveLength(1);+ });++ test("a partial read reports the files it found AND the directory it could not", () => {+ const good = join(home, ".claude", "projects", "good");+ const bad = join(home, ".claude", "projects", "bad");+ mkdirSync(good, { recursive: true });+ mkdirSync(bad, { recursive: true });+ writeInDay(join(good, "s.jsonl"));+ makeUnreadable(bad);+ const scan = claudeCodeTranscript.scan(DAY_START, DAY_END, home);+ expect(scan.state).toBe(TRANSCRIPT_SCAN.collected);+ expect(scan.files).toHaveLength(1);+ expect(scan.unreadable).toContain(bad);+ });+});++describe("codex and cursor answer the same three ways", () => {+ test("codex: absent store, unreadable store, idle store", () => {+ expect(codexTranscript.scan(DAY_START, DAY_END, home).state).toBe(TRANSCRIPT_SCAN.rootAbsent);++ const sessions = join(home, ".codex", "sessions");+ mkdirSync(sessions, { recursive: true });+ expect(codexTranscript.scan(DAY_START, DAY_END, home).state).toBe(TRANSCRIPT_SCAN.idle);++ makeUnreadable(sessions);+ const scan = codexTranscript.scan(DAY_START, DAY_END, home);+ expect(scan.state).toBe(TRANSCRIPT_SCAN.unreadable);+ expect(scan.unreadable).toContain(sessions);+ });++ test("cursor: absent store, unreadable store, idle store", () => {+ expect(cursorTranscript.scan(DAY_START, DAY_END, home).state).toBe(TRANSCRIPT_SCAN.rootAbsent);++ const root = join(home, ".config", "Cursor", "User", "workspaceStorage");+ mkdirSync(join(root, "ws"), { recursive: true });+ expect(cursorTranscript.scan(DAY_START, DAY_END, home).state).toBe(TRANSCRIPT_SCAN.idle);++ makeUnreadable(root);+ const scan = cursorTranscript.scan(DAY_START, DAY_END, home);+ expect(scan.state).toBe(TRANSCRIPT_SCAN.unreadable);+ expect(scan.unreadable).toContain(root);+ });+});++describe("the aggregator carries the reason, not just the count", () => {+ test("an unreadable runtime is not reported as a quiet one", () => {+ const base = join(home, ".claude", "projects");+ mkdirSync(base, { recursive: true });+ makeUnreadable(base);++ const activity = collectTranscriptActivity({+ dayStartMs: DAY_START,+ dayEndMs: DAY_END,+ home,+ });+ expect(activity.totalFiles).toBe(0);+ const claude = activity.byRuntime.find((r) => r.runtime === "claudecode");+ expect(claude?.scan).toBe(TRANSCRIPT_SCAN.unreadable);+ expect(activity.unreadableRuntimes).toContain("claudecode");+ // The runtimes that are simply not installed say so instead.+ const codex = activity.byRuntime.find((r) => r.runtime === "codex");+ expect(codex?.scan).toBe(TRANSCRIPT_SCAN.rootAbsent);+ });++ test("every runtime absent is zero files with nothing unreadable", () => {+ const activity = collectTranscriptActivity({+ dayStartMs: DAY_START,+ dayEndMs: DAY_END,+ home,+ });+ expect(activity.totalFiles).toBe(0);+ expect(activity.unreadableRuntimes).toEqual([]);+ expect(activity.byRuntime.every((r) => r.scan === TRANSCRIPT_SCAN.rootAbsent)).toBe(true);+ });+});diff --git a/tests/core/doctor-codegraph-switch.test.ts b/tests/core/doctor-codegraph-switch.test.tsnew file mode 100644index 00000000..655ad2e4--- /dev/null+++ b/tests/core/doctor-codegraph-switch.test.ts@@ -0,0 +1,136 @@+/**+ * The switch that turns the codegraph partner check off+ * (nothing-runs-unwatched, unit U12).+ *+ * `doctor()` has accepted `partner.codegraph.disabled` since the partner+ * check was written, and nothing ever set it: no flag, no env var, no+ * config key reached that field, so the option was a declared surface with+ * no producer. The consequence is measurable rather than cosmetic. When+ * the partner CLI is on PATH, `checkCodegraph` spawns `codegraph status -j+ * <repo>` on every `o2b doctor`, which costs ~0.7 s against a warm HOME+ * and ~5 s against a cold one (the partner caches under HOME). CI has no+ * such binary, so the check returns null there and the cost is invisible+ * to it - which is why this only ever hurt workstations.+ *+ * The spawn is what the assertions below watch, through a fake `codegraph`+ * on PATH that records having been called. A test that only read the+ * returned message would pass just as happily against a check that ran the+ * partner and then discarded the answer.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY,+ PARTNER_CODEGRAPH_DISABLED_ENV,+} from "../../src/core/config.ts";+import { doctor } from "../../src/core/doctor.ts";++let tmp: string;+let repo: string;+let vault: string;+let configPath: string;+let sentinel: string;+let savedPath: string | undefined;+let savedFlag: string | undefined;++/** A directory that passes `isCodeProject` and looks already indexed. */+function makeIndexedRepo(dir: string): string {+ mkdirSync(join(dir, ".git"), { recursive: true });+ mkdirSync(join(dir, ".codegraph"), { recursive: true });+ writeFileSync(join(dir, "package.json"), "{}\n", "utf8");+ return dir;+}++/**+ * A `codegraph` executable that records every invocation and answers like+ * an indexed project, so a check that spawns it gets a usable answer AND+ * leaves a trace.+ */+function makeFakeCodegraph(binDir: string, sentinelPath: string): void {+ mkdirSync(binDir, { recursive: true });+ const script = join(binDir, "codegraph");+ writeFileSync(+ script,+ ["#!/bin/sh", `echo "$@" >> "${sentinelPath}"`, "echo '{\"initialized\":true}'", ""].join("\n"),+ "utf8",+ );+ chmodSync(script, 0o755);+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-codegraph-switch-"));+ repo = makeIndexedRepo(join(tmp, "repo"));+ vault = join(tmp, "vault");+ mkdirSync(vault, { recursive: true });+ configPath = join(tmp, "config.yaml");+ sentinel = join(tmp, "spawned.log");+ makeFakeCodegraph(join(tmp, "bin"), sentinel);+ savedPath = process.env["PATH"];+ savedFlag = process.env[PARTNER_CODEGRAPH_DISABLED_ENV];+ process.env["PATH"] = join(tmp, "bin");+ delete process.env[PARTNER_CODEGRAPH_DISABLED_ENV];+});++afterEach(() => {+ if (savedPath === undefined) delete process.env["PATH"];+ else process.env["PATH"] = savedPath;+ if (savedFlag === undefined) delete process.env[PARTNER_CODEGRAPH_DISABLED_ENV];+ else process.env[PARTNER_CODEGRAPH_DISABLED_ENV] = savedFlag;+ rmSync(tmp, { recursive: true, force: true });+});++function codegraphCheck(): { name: string; ok: boolean; message: string } | undefined {+ return doctor({ vault, config: configPath, cwd: repo }).find((r) => r.name === "code_graph");+}++describe("the codegraph partner check can be turned off", () => {+ test("with the switch unset the partner is spawned - so the watch is not vacuous", () => {+ const check = codegraphCheck();+ expect(existsSync(sentinel)).toBe(true);+ expect(check?.ok).toBe(true);+ });++ test("the env var stops the spawn", () => {+ process.env[PARTNER_CODEGRAPH_DISABLED_ENV] = "true";+ codegraphCheck();+ expect(existsSync(sentinel)).toBe(false);+ });++ test("the config key stops the spawn, with no env var set", () => {+ writeFileSync(configPath, `${PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY}: "true"\n`, "utf8");+ codegraphCheck();+ expect(existsSync(sentinel)).toBe(false);+ });++ test("an explicit caller option still wins over the resolved default", () => {+ process.env[PARTNER_CODEGRAPH_DISABLED_ENV] = "true";+ const results = doctor({+ vault,+ config: configPath,+ cwd: repo,+ partner: { codegraph: { disabled: false } },+ });+ expect(existsSync(sentinel)).toBe(true);+ expect(results.some((r) => r.name === "code_graph")).toBe(true);+ });+});++describe("a check that did not run says so", () => {+ test("the disabled check reports itself rather than vanishing from the report", () => {+ // Silence would be indistinguishable from a machine with no codegraph+ // and from a directory that is not a code project - three different+ // facts, one empty report.+ process.env[PARTNER_CODEGRAPH_DISABLED_ENV] = "true";+ const check = codegraphCheck();+ expect(check).toBeDefined();+ expect(check?.message).toContain(PARTNER_CODEGRAPH_DISABLED_ENV);+ expect(check?.message).toContain(PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY);+ // Not a fault of the operator's making: an install they deliberately+ // told the doctor to leave alone must not fail the doctor.+ expect(check?.ok).toBe(true);+ });+});diff --git a/tests/core/doctor-readiness.test.ts b/tests/core/doctor-readiness.test.tsindex a1f68b84..17fd738a 100644--- a/tests/core/doctor-readiness.test.ts+++ b/tests/core/doctor-readiness.test.ts@@ -299,9 +299,10 @@ describe("runReadinessProbes", () => {expect(report.unknown).toBe(1);});- test("a probe that exceeds the per-check timeout is a fail, not a hang", async () => {- // An injected probe that sleeps past a tiny budget must surface as a- // fail with a "timed out" reason rather than blocking the run.+ test("a probe that exceeds the per-check timeout does not hang, and is not a failure", async () => {+ // An injected probe that sleeps past a tiny budget must surface with a+ // "timed out" reason rather than blocking the run - and that reason is a+ // fact about the probe's reach, never about the surface it was pointed at.const slowProbe = {name: "slow_unit_probe",fn: () =>@@ -313,11 +314,59 @@ describe("runReadinessProbes", () => {{ vault: tmp, config: configPath, perCheckTimeoutMs: 5 },[slowProbe],);- expect(report.failed).toBe(1);- expect(report.probes[0]!.status).toBe("fail");+ expect(report.failed).toBe(0);+ expect(report.unknown).toBe(1);+ expect(report.probes[0]!.status).toBe(READINESS_STATUS.unknown);expect(report.probes[0]!.detail.toLowerCase()).toContain("timed out");});+ test("a probe that did not answer is distinguishable from one that ran and failed", async () => {+ // The two run in the same batch so the comparison is between two+ // verdicts of one report, not between two runs of one probe.+ const slowProbe = {+ name: "slow_unit_probe",+ fn: () =>+ new Promise<{ status: "pass"; detail: string }>((resolve) =>+ setTimeout(() => resolve({ status: "pass", detail: "eventually" }), 100),+ ),+ };+ const brokenProbe = {+ name: "broken_unit_probe",+ fn: async () => ({+ status: READINESS_STATUS.fail,+ detail: "the surface answered, and the answer was a refusal",+ }),+ };+ const report = await runReadinessProbes(+ { vault: tmp, config: configPath, perCheckTimeoutMs: 5 },+ [slowProbe, brokenProbe],+ );+ const [timedOut, broken] = report.probes;+ expect(timedOut!.status).not.toBe(broken!.status);+ expect(timedOut!.status).toBe(READINESS_STATUS.unknown);+ expect(broken!.status).toBe(READINESS_STATUS.fail);+ // Nor is the unanswered probe folded into the healthy answer.+ expect(timedOut!.status).not.toBe(READINESS_STATUS.pass);+ expect(report.failed).toBe(1);+ expect(report.unknown).toBe(1);+ });++ test("a probe that throws claims nothing about the surface it could not read", async () => {+ // An exception escaping a probe body is evidence about the probe, not+ // about the surface: the run never got an answer to classify.+ const throwingProbe = {+ name: "throwing_unit_probe",+ fn: async (): Promise<{ status: "pass"; detail: string }> => {+ throw new Error("EACCES: permission denied");+ },+ };+ const report = await runReadinessProbes({ vault: tmp, config: configPath }, [throwingProbe]);+ expect(report.probes[0]!.status).toBe(READINESS_STATUS.unknown);+ expect(report.probes[0]!.detail).toContain("EACCES");+ expect(report.failed).toBe(0);+ expect(report.unknown).toBe(1);+ });+test("exposes a sane default per-check timeout constant", () => {expect(DEFAULT_READINESS_TIMEOUT_MS).toBeGreaterThan(0);});diff --git a/tests/core/doctor.test.ts b/tests/core/doctor.test.tsindex 8277a999..6cf147a4 100644--- a/tests/core/doctor.test.ts+++ b/tests/core/doctor.test.ts@@ -245,7 +245,13 @@ describe("checkHermesResolverParity", () => {describe("doctor aggregator", () => {test("returns at least the vault check", () => {- const results = doctor({ vault: tmp });+ // `cwd` is pinned to the temp vault rather than left to default.+ // Without it the aggregator walks up from the process's working+ // directory, finds THIS repository, decides it is a code project and+ // consults the codegraph partner - several seconds on any machine+ // that has the binary, and nothing this test asserts on. The partner+ // has its own tests; this one is about the aggregator returning.+ const results = doctor({ vault: tmp, cwd: tmp });expect(results.length).toBeGreaterThan(0);});@@ -256,7 +262,15 @@ describe("doctor aggregator", () => {expect(results.some((r) => r.name === "code_graph")).toBe(false);});- test("omits code_graph when partner.codegraph.disabled is true", () => {+ test("reports code_graph as deliberately not consulted when the check is disabled", () => {+ // This test asserted OMISSION until the switch gained a producer.+ // Omission was the wrong report: an operator who turned the check+ // off, one whose machine has no codegraph, and one standing outside+ // a code project all read the same empty result, so a setting that+ // had just taken effect was indistinguishable from one that had done+ // nothing. The line says the partner was not consulted and that+ // nothing is therefore claimed about any index - which is the only+ // honest thing to say about a check that did not run.const repo = join(tmp, "myrepo");mkdirSync(join(repo, ".git"), { recursive: true });writeFileSync(join(repo, "package.json"), "{}\n");@@ -267,7 +281,11 @@ describe("doctor aggregator", () => {cwd: repo,partner: { codegraph: { disabled: true } },});- expect(results.some((r) => r.name === "code_graph")).toBe(false);+ const codeGraph = results.find((r) => r.name === "code_graph");+ expect(codeGraph).toBeDefined();+ // Not a failure: a deliberate operator choice must not fail a doctor.+ expect(codeGraph?.ok).toBe(true);+ expect(codeGraph?.message).toContain("was not consulted");});test("includes code_graph for a code project only when codegraph is installed", () => {diff --git a/tests/core/install/ownership.test.ts b/tests/core/install/ownership.test.tsnew file mode 100644index 00000000..5a6ef5b6--- /dev/null+++ b/tests/core/install/ownership.test.ts@@ -0,0 +1,639 @@+/**+ * The ownership statement, and the census that keeps it true.+ *+ * "Every memory is a Markdown file in your own vault; copy it elsewhere,+ * delete it and the brain is gone; there is no service to cancel" is a+ * claim with known counterexamples, and a claim with a known counterexample+ * is exactly what this release exists to remove. So the sentence is not+ * written by hand: it is COMPOSED from the resolved vault path, a+ * filesystem-backing verdict, the measured location of the search index,+ * the measured state of every outbound integration, and an enumeration of+ * the durable state that can live outside the vault.+ *+ * Two families of test, and the split is the point:+ *+ * The first family pins the MEASURED clauses - every one of them has an+ * arm that says "not established", and none of them may render as the+ * confident arm when the input did not say so.+ *+ * The last describe block is the census. It sweeps the tree for every+ * module that BUILDS a path rooted outside the vault and demands each be+ * attributed to an entry in the enumeration or excused in writing - so a+ * new out-of-vault location cannot be added without the sentence learning+ * about it. It sweeps path construction rather than write calls because+ * the write-call form was blind to `fs/promises`, to this repository's+ * own `atomicWriteText` helper, and to any module that computes such a+ * path and hands it to something else to write.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import {+ existsSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ statSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join, relative, resolve } from "node:path";++import { registerAllAdapters } from "../../../src/core/install/adapters/all.ts";+import { measureDataOwnership } from "../../../src/core/install/ownership-measure.ts";+import {+ buildDataOwnership,+ OUT_OF_VAULT_STATE,+ OUT_OF_VAULT_SWEEP_EXCLUSIONS,+ OUTBOUND_SERVICE,+ OUTBOUND_SERVICES,+ OUTBOUND_STATE,+ renderDataOwnership,+ SEARCH_INDEX_LOCATION,+ SOURCES_INVISIBLE_TO_THE_SWEEP,+ type DataOwnershipInput,+ type OutboundMeasurement,+ type OutboundServiceId,+ type SearchIndexVerdict,+} from "../../../src/core/install/ownership.ts";+import {+ VAULT_BACKING,+ VAULT_BACKING_UNDETERMINED_REASON,+} from "../../../src/core/vault-backing.ts";++const REPO_ROOT = resolve(import.meta.dir, "..", "..", "..");+const VAULT = "/tmp/some-vault";+const INDEX_INSIDE = `${VAULT}/.open-second-brain/index.sqlite`;+const INDEX_OUTSIDE = "/var/tmp/elsewhere/index.sqlite";++const INSIDE_VAULT: SearchIndexVerdict = {+ state: SEARCH_INDEX_LOCATION.insideVault,+ path: INDEX_INSIDE,+ reason: null,+};++/** Every outbound integration measured as absent — the quiet machine. */+function nothingConfigured(): Record<OutboundServiceId, OutboundMeasurement> {+ const out = {} as Record<OutboundServiceId, OutboundMeasurement>;+ for (const service of OUTBOUND_SERVICES) out[service.id] = { state: OUTBOUND_STATE.absent };+ return out;+}++function ownership(overrides: Partial<DataOwnershipInput> = {}) {+ return buildDataOwnership({+ vault: VAULT,+ searchIndex: INSIDE_VAULT,+ adapterTargets: ["cursor", "kiro"],+ outbound: nothingConfigured(),+ backing: {+ state: VAULT_BACKING.durable,+ filesystem: "ext4",+ reason: null,+ detail: `${VAULT} is backed by ext4 (0xef53)`,+ },+ ...overrides,+ });+}++/** The line of the rendered statement that speaks about the search index. */+function indexLine(text: string): string {+ return text.split("\n")[2] ?? "";+}++/** How many bulleted rows the statement printed, catalogue and outbound alike. */+function catalogueRowCount(text: string): number {+ return text.split("\n").filter((l) => l.startsWith(" - ")).length;+}++/** The last sentence of the statement — the one that used to over-claim. */+function closingLine(text: string): string {+ const lines = text.trimEnd().split("\n");+ return lines[lines.length - 1] ?? "";+}++describe("the statement is built from what was measured", () => {+ test("it names the resolved vault, not a configured one", () => {+ const text = renderDataOwnership(ownership());+ expect(text).toContain(VAULT);+ });++ test("a durable backing is stated as such", () => {+ const text = renderDataOwnership(ownership());+ expect(text).toContain("ext4");+ });++ test("an undetermined backing is never rendered as durability", () => {+ const text = renderDataOwnership(+ ownership({+ backing: {+ state: VAULT_BACKING.undetermined,+ filesystem: null,+ reason: VAULT_BACKING_UNDETERMINED_REASON.probeUnsupported,+ detail: "the filesystem backing /tmp/some-vault was not probed",+ },+ }),+ );+ // The verdict is present and it is the honest one; nothing in the+ // rendering promises the vault survives anything.+ expect(text).toContain("was not probed");+ expect(text).not.toContain("survives this process and a reboot");+ });++ test("a memory-backed vault is stated as a loss, not as a caveat", () => {+ const text = renderDataOwnership(+ ownership({+ backing: {+ state: VAULT_BACKING.volatile,+ filesystem: "tmpfs",+ reason: null,+ detail: "/tmp/some-vault is backed by tmpfs (0x1021994)",+ },+ }),+ );+ expect(text).toContain("tmpfs");+ expect(text).toContain("reboot");+ });+});++describe("where the search index is, is measured rather than assumed", () => {+ test("an index inside the vault is named by path, not by assumption", () => {+ const text = renderDataOwnership(ownership());+ expect(indexLine(text)).toContain(INDEX_INSIDE);+ });++ test("a relocated index is never described as being in the vault", () => {+ // The reproduction from the review: OPEN_SECOND_BRAIN_SEARCH_DB points+ // somewhere else, and the first line used to say "in the same vault"+ // two lines above the row admitting it might not be.+ const text = renderDataOwnership(+ ownership({+ searchIndex: {+ state: SEARCH_INDEX_LOCATION.outsideVault,+ path: INDEX_OUTSIDE,+ reason: null,+ },+ }),+ );+ expect(indexLine(text)).toContain(INDEX_OUTSIDE);+ expect(indexLine(text)).not.toContain(indexLine(renderDataOwnership(ownership())));+ });++ test("an index whose location could not be established says so, and names nothing", () => {+ const why = "the search config would not resolve: search_chunk_size must be >= 1";+ const text = renderDataOwnership(+ ownership({+ searchIndex: { state: SEARCH_INDEX_LOCATION.unchecked, path: null, reason: why },+ }),+ );+ expect(indexLine(text)).toContain(why);+ expect(indexLine(text)).not.toContain(INDEX_INSIDE);+ });++ test("no two location states render the same sentence", () => {+ const rendered = new Set(+ [+ INSIDE_VAULT,+ { state: SEARCH_INDEX_LOCATION.outsideVault, path: INDEX_OUTSIDE, reason: null },+ { state: SEARCH_INDEX_LOCATION.unchecked, path: null, reason: "no reason given" },+ ].map((searchIndex) => indexLine(renderDataOwnership(ownership({ searchIndex })))),+ );+ // A vocabulary whose members collapse onto one sentence is a vocabulary+ // the reader cannot use.+ expect(rendered.size).toBe(3);+ });+});++describe("the exceptions are named as a catalogue, never as a scan", () => {+ test("every enumerated out-of-vault location reaches the rendered statement", () => {+ const text = renderDataOwnership(ownership());+ const missing = OUT_OF_VAULT_STATE.filter((entry) => !text.includes(entry.label));+ expect(missing.map((e) => e.id).join("\n")).toBe("");+ });++ test("every row says what creates it and what removes it", () => {+ const text = renderDataOwnership(ownership());+ // Without these two the rows read as a report about this machine, which+ // is what they are not: they are printed unconditionally.+ const silent = OUT_OF_VAULT_STATE.filter(+ (e) =>+ e.created_by.trim().length === 0 ||+ e.removed_by.trim().length === 0 ||+ !text.includes(e.created_by) ||+ !text.includes(e.removed_by),+ );+ expect(silent.map((e) => e.id).join("\n")).toBe("");+ });++ test("the one location that can hold memory content is called out by name", () => {+ const carriers = OUT_OF_VAULT_STATE.filter((e) => e.carries_memory);+ // Not an incidental fact: the opencode spool is the counterexample that+ // makes the unqualified sentence false, so an empty set here means the+ // statement has quietly become the unqualified one again.+ expect(carriers.length).toBeGreaterThan(0);+ const text = renderDataOwnership(ownership());+ for (const carrier of carriers) expect(text).toContain(carrier.location);+ });++ test("every installed runtime target is accounted for in the statement", () => {+ const targets = registerAllAdapters().targets();+ const text = renderDataOwnership(ownership({ adapterTargets: targets }));+ const missing = targets.filter((t) => !text.includes(t));+ expect(missing.join("\n")).toBe("");+ });++ test("the registry list is offered as what CAN be installed, not what is", () => {+ // `defaultRegistry.targets()` is every adapter this build registers, not+ // the ones this machine has. The row that carries it therefore has to+ // say which of the two it is, and it must not grow or shrink with the+ // machine.+ const few = renderDataOwnership(ownership({ adapterTargets: ["cursor"] }));+ const many = renderDataOwnership(ownership({ adapterTargets: ["aider", "cursor", "kiro"] }));+ expect(catalogueRowCount(few)).toBe(catalogueRowCount(many));+ expect(many).toContain("installable targets: aider, cursor, kiro");+ });++ test("no id is spelled twice", () => {+ const ids = OUT_OF_VAULT_STATE.map((e) => e.id);+ expect(new Set(ids).size).toBe(ids.length);+ });+});++describe("the closing sentence does not take the qualifications back", () => {+ test("it never restates the unqualified claim the module exists to correct", () => {+ const text = renderDataOwnership(ownership());+ // The exact sentence that shipped, pinned: row one of the list printed+ // immediately above it is a memory carrier outside the vault.+ expect(text).not.toContain("Delete the vault and the memory is gone");+ });++ test("it promises no removal verb on behalf of the rows", () => {+ const closing = closingLine(renderDataOwnership(ownership()));+ // `o2b uninstall` removes two of these rows. A closing sentence that+ // names it once for the whole list is false for the rest, so the+ // closing names no verb at all and each row carries its own.+ const removedByUninstall = OUT_OF_VAULT_STATE.filter((e) =>+ e.removed_by.includes("o2b uninstall"),+ );+ expect(removedByUninstall.length).toBeGreaterThan(0);+ expect(removedByUninstall.length).toBeLessThan(OUT_OF_VAULT_STATE.length);+ expect(closing).not.toContain("o2b uninstall");+ });++ test("it carries the count of memory-bearing rows it is qualified by", () => {+ const carriers = OUT_OF_VAULT_STATE.filter((e) => e.carries_memory).length;+ const closing = closingLine(renderDataOwnership(ownership()));+ expect(closing).toContain(String(carriers));+ expect(closing).toContain(String(OUT_OF_VAULT_STATE.length));+ });+});++describe("`nothing to cancel` is checked against every integration it names", () => {+ test("every outbound integration in the catalogue reaches the statement", () => {+ const text = renderDataOwnership(ownership());+ const missing = OUTBOUND_SERVICES.filter(+ (s) => !text.includes(s.label) || !text.includes(s.settings),+ );+ expect(missing.map((s) => s.id).join("\n")).toBe("");+ });++ test("a configured integration is named with the endpoint it sends to", () => {+ const text = renderDataOwnership(+ ownership({+ outbound: {+ ...nothingConfigured(),+ [OUTBOUND_SERVICE.rerank]: {+ state: OUTBOUND_STATE.configured,+ endpoint: "https://rerank.example/v1",+ },+ },+ }),+ );+ expect(text).toContain("https://rerank.example/v1");+ // The reranker POSTs the candidate document text, so the statement has+ // to say what leaves rather than only that something is configured.+ const rerank = OUTBOUND_SERVICES.find((s) => s.id === OUTBOUND_SERVICE.rerank)!;+ expect(text).toContain(rerank.sends);+ });++ test("an integration that could not be checked is not reported as absent", () => {+ const why = "the search config would not resolve: bad key";+ const unchecked = renderDataOwnership(+ ownership({+ outbound: {+ ...nothingConfigured(),+ [OUTBOUND_SERVICE.embedding]: { state: OUTBOUND_STATE.unchecked, reason: why },+ },+ }),+ );+ const absent = renderDataOwnership(ownership());+ expect(unchecked).toContain(why);+ expect(unchecked).not.toBe(absent);+ });++ test("an unchecked state with no reason still says a check did not run", () => {+ const text = renderDataOwnership(+ ownership({+ outbound: {+ ...nothingConfigured(),+ [OUTBOUND_SERVICE.telegram]: { state: OUTBOUND_STATE.unchecked },+ },+ }),+ );+ const absent = renderDataOwnership(ownership());+ // Silence here would be the whole defect: a check that did not run must+ // never render as the check that ran and found nothing.+ expect(text).not.toBe(absent);+ });++ test("the machine-readable record carries one status per catalogue row", () => {+ const record = ownership();+ expect(record.outbound_services.map((s) => s.id).toSorted()).toEqual(+ OUTBOUND_SERVICES.map((s) => s.id).toSorted(),+ );+ for (const status of record.outbound_services) {+ expect(Object.values(OUTBOUND_STATE)).toContain(status.state);+ }+ });+});++// ---------------------------------------------------------------------------+// The measuring half.+// ---------------------------------------------------------------------------++/** Env keys the measurements below read, saved and restored per test. */+const MEASURED_ENV_KEYS: ReadonlyArray<string> = Object.freeze([+ "OPEN_SECOND_BRAIN_SEARCH_DB",+ "OPEN_SECOND_BRAIN_SEARCH_CHUNK_SIZE",+ "OPEN_SECOND_BRAIN_SEARCH_RERANK_ENABLED",+ "OPEN_SECOND_BRAIN_SEARCH_RERANK_BASE_URL",+ "TELEGRAM_BOT_TOKEN",+ "TAVILY_API_KEY",+ "BRAVE_API_KEY",+]);++describe("the measurements the statement is composed from", () => {+ let saved: Record<string, string | undefined> = {};+ let tempVault = "";+ let configPath = "";++ beforeEach(() => {+ saved = {};+ for (const key of MEASURED_ENV_KEYS) {+ saved[key] = process.env[key];+ delete process.env[key];+ }+ tempVault = mkdtempSync(join(tmpdir(), "osb-own-"));+ configPath = join(tempVault, "config.yaml");+ writeFileSync(configPath, `vault: "${tempVault}"\n`);+ });++ afterEach(() => {+ for (const key of MEASURED_ENV_KEYS) {+ const value = saved[key];+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ rmSync(tempVault, { recursive: true, force: true });+ });++ function measured() {+ return measureDataOwnership({ vault: tempVault, configPath, adapterTargets: ["cursor"] });+ }++ test("the default index is measured as inside the vault", () => {+ const record = measured();+ expect(record.search_index.state).toBe(SEARCH_INDEX_LOCATION.insideVault);+ expect(record.search_index.path).toContain(tempVault);+ });++ test("a relocated index is measured as outside it, at the path it resolved to", () => {+ // The review's reproduction, end to end: the override is set, and the+ // statement's first line is what it changes.+ process.env["OPEN_SECOND_BRAIN_SEARCH_DB"] = "/var/tmp/elsewhere/index.sqlite";+ const record = measured();+ expect(record.search_index.state).toBe(SEARCH_INDEX_LOCATION.outsideVault);+ expect(record.search_index.path).toBe("/var/tmp/elsewhere/index.sqlite");+ expect(renderDataOwnership(record)).toContain("/var/tmp/elsewhere/index.sqlite");+ });++ test("a search config that will not resolve is reported, not read as `nothing configured`", () => {+ process.env["OPEN_SECOND_BRAIN_SEARCH_CHUNK_SIZE"] = "0";+ const record = measured();+ expect(record.search_index.state).toBe(SEARCH_INDEX_LOCATION.unchecked);+ const fromSearch = record.outbound_services.filter(+ (s) => s.id === OUTBOUND_SERVICE.embedding || s.id === OUTBOUND_SERVICE.rerank,+ );+ expect(fromSearch.length).toBe(2);+ for (const service of fromSearch) {+ expect(service.state).toBe(OUTBOUND_STATE.unchecked);+ expect(service.reason ?? "").toContain("search_chunk_size");+ }+ });++ test("the reranker is checked, and named with the endpoint it posts documents to", () => {+ process.env["OPEN_SECOND_BRAIN_SEARCH_RERANK_ENABLED"] = "true";+ process.env["OPEN_SECOND_BRAIN_SEARCH_RERANK_BASE_URL"] = "https://rerank.example/v1";+ const rerank = measured().outbound_services.find((s) => s.id === OUTBOUND_SERVICE.rerank)!;+ expect(rerank.state).toBe(OUTBOUND_STATE.configured);+ expect(rerank.endpoint).toBe("https://rerank.example/v1");+ });++ test("the Telegram bot token and a research key are each an account that was checked", () => {+ process.env["TELEGRAM_BOT_TOKEN"] = "123:abc";+ process.env["TAVILY_API_KEY"] = "tvly-x";+ const record = measured();+ const state = (id: string) =>+ record.outbound_services.find((s) => s.id === id)?.state ?? "missing";+ expect(state(OUTBOUND_SERVICE.telegram)).toBe(OUTBOUND_STATE.configured);+ expect(state(OUTBOUND_SERVICE.research)).toBe(OUTBOUND_STATE.configured);+ });++ test("a quiet machine reports every integration absent, and none unchecked", () => {+ // `embedding_provider` defaults to `openai-compat` with semantic search+ // off, so a check that reads the provider name alone announces a cloud+ // account on a machine that has never computed an embedding.+ for (const service of measured().outbound_services) {+ expect(`${service.id}: ${service.state}`).toBe(`${service.id}: ${OUTBOUND_STATE.absent}`);+ }+ });++ test("a networked embedding endpoint is reported once semantic search is on", () => {+ writeFileSync(+ configPath,+ `vault: "${tempVault}"\nsearch_semantic_enabled: true\nembedding_base_url: "https://api.openai.com/v1"\n`,+ );+ const embedding = measured().outbound_services.find(+ (s) => s.id === OUTBOUND_SERVICE.embedding,+ )!;+ expect(embedding.state).toBe(OUTBOUND_STATE.configured);+ expect(embedding.endpoint).toBe("https://api.openai.com/v1");+ });+});++// ---------------------------------------------------------------------------+// The census.+// ---------------------------------------------------------------------------++/**+ * Roots swept for out-of-vault path construction. `tests/` is deliberately+ * absent: a test writing into a temp home is staging a fixture, not+ * shipping a location an operator will find on their machine afterwards.+ * `scripts/` is present because it ships in `package.json` `files`.+ */+const SWEPT_ROOTS: ReadonlyArray<string> = Object.freeze(["src", "hooks", "plugins", "scripts"]);++/**+ * A path rooted somewhere other than the vault.+ *+ * This is the whole population filter now: a module that names one of+ * these roots is enrolled whether or not it writes through a call this+ * file recognises. The write-call half that used to accompany it was a+ * list of six synchronous `fs` functions, and it therefore could not see+ * `fs/promises`, `Bun.write`, a write stream, this repository's own+ * `atomicWriteText`, a spawned child writing on the module's behalf, or a+ * module that builds the path and hands it to any of those. Matching the+ * ROOT instead of the call catches all of them, at the cost of enrolling+ * read-only modules - which is why the exclusion map is the size it is.+ *+ * `env.home` is included because the install adapters receive the home+ * directory injected rather than reading it, and they are the largest+ * family of out-of-vault writers in the tree. `XDG_` is matched by prefix+ * rather than by naming the four variables this build happens to use, and+ * a quoted `~/` is matched because the cron recipes emit shell text whose+ * writes are performed by the operator's crontab: both widen the+ * population by nothing today, which is the moment to widen them.+ *+ * What it still cannot see, by construction: a root that arrives from a+ * config key or an env override with no token in the source, a path+ * resolved against the working directory, and a hardcoded absolute path+ * outside the vault. The first two are the shapes {@link+ * SOURCES_INVISIBLE_TO_THE_SWEEP} enumerates.+ */+const OUT_OF_VAULT_ANCHOR_RE =+ /XDG_[A-Z_]+|homedir\(\)|process\.env\[["']HOME["']\]|process\.env\[["']USERPROFILE["']\]|\.local\/(?:bin|share|state)|tmpdir\(\)|TMPDIR|env\.home|["'`]~\//;++/**+ * Comments stripped before the pattern runs: a docblock that explains why+ * a module does NOT write outside the vault would otherwise enrol it. The+ * `[^:]` guard keeps `https://` out of the line-comment arm.+ */+function code(source: string): string {+ return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");+}++function walk(dir: string, out: string[]): string[] {+ for (const name of readdirSync(dir)) {+ if (name === "node_modules" || name.startsWith(".")) continue;+ const full = join(dir, name);+ let isDir: boolean;+ try {+ isDir = statSync(full).isDirectory();+ } catch {+ // A dangling symlink is not a module, and a census that throws on one+ // reports nothing at all - which is strictly worse than reporting the+ // rest of the tree. `plugins/codex/skills` is a symlink; a checkout+ // that has not materialised it must not take the sweep down with it.+ continue;+ }+ if (isDir) walk(full, out);+ else if (name.endsWith(".ts")) out.push(full);+ }+ return out;+}++/** Every module that builds a path rooted outside the vault. */+function sweepOutOfVaultPathBuilders(): ReadonlyArray<string> {+ const hits: string[] = [];+ for (const root of SWEPT_ROOTS) {+ const dir = join(REPO_ROOT, root);+ if (!existsSync(dir)) continue;+ for (const file of walk(dir, [])) {+ const source = code(readFileSync(file, "utf8"));+ if (!OUT_OF_VAULT_ANCHOR_RE.test(source)) continue;+ hits.push(relative(REPO_ROOT, file));+ }+ }+ return hits.toSorted();+}++/** True when `file` sits under one of the entry's declared sources. */+function attributed(file: string): boolean {+ for (const entry of OUT_OF_VAULT_STATE) {+ for (const source of entry.sources) {+ if (file === source) return true;+ if (source.endsWith("/") && file.startsWith(source)) return true;+ }+ }+ return false;+}++const MIN_EXCLUSION_REASON_LENGTH = 80;++describe("no out-of-vault path escapes the enumeration", () => {+ test("the sweep found a real population", () => {+ // A regex that stopped matching, or a root that was renamed, would+ // sweep an empty set clean and pass every assertion below.+ expect(sweepOutOfVaultPathBuilders().length).toBeGreaterThan(8);+ });++ test("every path builder is either attributed to an entry or excused in writing", () => {+ const orphans = sweepOutOfVaultPathBuilders().filter(+ (file) => !attributed(file) && !OUT_OF_VAULT_SWEEP_EXCLUSIONS.has(file),+ );+ // Named, not counted: the failure message is the work to be done.+ expect(orphans.join("\n")).toBe("");+ });++ test("no exclusion outlives the module it excuses", () => {+ const population = new Set(sweepOutOfVaultPathBuilders());+ const stale = [...OUT_OF_VAULT_SWEEP_EXCLUSIONS.keys()].filter((file) => !population.has(file));+ expect(stale.toSorted().join("\n")).toBe("");+ });++ test("every exclusion reason says something specific", () => {+ for (const [file, reason] of OUT_OF_VAULT_SWEEP_EXCLUSIONS) {+ expect(`${file}: ${reason.trim().length >= MIN_EXCLUSION_REASON_LENGTH}`).toBe(+ `${file}: true`,+ );+ }+ });++ test("every declared source still exists", () => {+ const missing: string[] = [];+ for (const entry of OUT_OF_VAULT_STATE) {+ for (const source of entry.sources) {+ if (!existsSync(join(REPO_ROOT, source))) missing.push(`${entry.id} -> ${source}`);+ }+ }+ expect(missing.join("\n")).toBe("");+ });++ test("every source the sweep cannot see is declared as such, with its reason", () => {+ // The census guarantees nothing about a path whose root arrives from a+ // config key, an env override or the working directory. Which sources+ // those are is enumerated rather than left to the reader to discover by+ // adding a location and watching nothing happen.+ const population = new Set(sweepOutOfVaultPathBuilders());+ const undeclared: string[] = [];+ for (const entry of OUT_OF_VAULT_STATE) {+ for (const source of entry.sources) {+ if (source.endsWith("/")) continue;+ if (population.has(source)) continue;+ if (!SOURCES_INVISIBLE_TO_THE_SWEEP.has(source))+ undeclared.push(`${entry.id} -> ${source}`);+ }+ }+ expect(undeclared.join("\n")).toBe("");+ });++ test("no invisibility claim outlives the sweep that could not see it", () => {+ const population = new Set(sweepOutOfVaultPathBuilders());+ const nowVisible = [...SOURCES_INVISIBLE_TO_THE_SWEEP.keys()].filter((f) => population.has(f));+ expect(nowVisible.toSorted().join("\n")).toBe("");+ for (const [file, reason] of SOURCES_INVISIBLE_TO_THE_SWEEP) {+ expect(`${file}: ${reason.trim().length >= MIN_EXCLUSION_REASON_LENGTH}`).toBe(+ `${file}: true`,+ );+ }+ });+});diff --git a/tests/core/maintenance/self-heal-reindex.test.ts b/tests/core/maintenance/self-heal-reindex.test.tsnew file mode 100644index 00000000..50f65413--- /dev/null+++ b/tests/core/maintenance/self-heal-reindex.test.ts@@ -0,0 +1,272 @@+/**+ * The detached post-upgrade reindex, and the two silences it used to keep.+ *+ * N agent sessions starting after a schema bump each called+ * `ensureVaultCurrent(vault, { background: true })`, each spawned a detached+ * `o2b search reindex`, and N-1 of them spun on the writer lock for about+ * three seconds and died with their stderr pointed at nothing. Neither the+ * losing child nor the operator had any way to know it had happened.+ *+ * These tests hold both halves of the fix: the parent does not spawn a child+ * it can already see will lose, and a child that runs writes its terminal+ * outcome where it can be read back.+ */+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";++import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { listMetrics } from "../../../src/core/brain/metrics.ts";+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";+import { ensureVaultCurrent } from "../../../src/core/maintenance/ensure-current.ts";+import {+ mintSelfHealRunId,+ readSelfHealReindexRows,+ recordSelfHealOutcome,+ recordSelfHealSpawn,+ SELF_HEAL_REINDEX_OUTCOME,+ SELF_HEAL_REINDEX_SURFACE,+ SELF_HEAL_SPAWN,+} from "../../../src/core/maintenance/self-heal-reindex.ts";+import { cmdSearchReindex } from "../../../src/cli/search/verbs/indexing.ts";+import { resolveSearchConfig } from "../../../src/core/search/index.ts";+import { acquireWriterLock } from "../../../src/core/search/store/writer-lock.ts";++let vault: string;+let configHome: string;+let configPath: string;+let prevConfigEnv: string | undefined;++/**+ * Budget for the end-to-end spawn test. A detached child pays a cold Bun+ * start plus a full rebuild of a freshly bootstrapped vault; the poll below+ * returns as soon as the row lands, so this is a ceiling, not a wait.+ */+const CHILD_BUDGET_MS = 60_000;++/** Contention budget: three retries of one second, then INDEX_LOCKED. */+const CONTENTION_BUDGET_MS = 20_000;++/** How often the poll below re-reads the sink. */+const POLL_INTERVAL_MS = 50;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-self-heal-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-self-heal-cfg-"));+ configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);+ prevConfigEnv = process.env["OPEN_SECOND_BRAIN_CONFIG"];+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ if (prevConfigEnv === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = prevConfigEnv;+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++function dbPath(): string {+ return resolveSearchConfig({ vault, configPath }).dbPath;+}++/** The lock is taken on the live index path, whose directory must exist. */+async function holdWriterLock(): Promise<() => Promise<void>> {+ mkdirSync(dirname(dbPath()), { recursive: true });+ return await acquireWriterLock(dbPath());+}++async function pollUntil(predicate: () => boolean, budgetMs: number): Promise<boolean> {+ const deadline = Date.now() + budgetMs;+ while (Date.now() < deadline) {+ if (predicate()) return true;+ // The rule suggests Promise.all. There is nothing to run in parallel:+ // this waits on a detached process nothing in-process holds a handle+ // to, so the only way to learn it finished is to look again.+ // eslint-disable-next-line no-await-in-loop+ await Bun.sleep(POLL_INTERVAL_MS);+ }+ return predicate();+}++describe("self-heal reindex: the spawn decision", () => {+ test("does not spawn a child while another writer holds the index lock", async () => {+ const release = await holdWriterLock();+ try {+ const r = await ensureVaultCurrent(vault, { background: true, configPath });++ expect(r.reindexSpawn).toBe(SELF_HEAL_SPAWN.skippedWriterLock);+ expect(r.reindexTriggered).toBe(false);+ expect(r.errors).toEqual([]);++ const rows = readSelfHealReindexRows(vault);+ expect(rows.map((row) => row.decision)).toEqual([SELF_HEAL_SPAWN.skippedWriterLock]);+ // The parent records its own spawn, so the absence of that row is+ // what proves no child was started.+ expect(rows.some((row) => row.decision === SELF_HEAL_SPAWN.spawned)).toBe(false);+ } finally {+ await release();+ }+ });++ test(+ "spawns a child when the lock is free, and returns before the child finishes",+ async () => {+ expect(existsSync(dbPath())).toBe(false);++ const r = await ensureVaultCurrent(vault, { background: true, configPath });++ expect(r.reindexSpawn).toBe(SELF_HEAL_SPAWN.spawned);+ expect(r.reindexTriggered).toBe(true);++ // Read the sink at the instant the parent handed control back: the+ // spawn is recorded, the child's terminal row is not there yet. That+ // is the assertion that session start does not wait for the rebuild.+ const atReturn = readSelfHealReindexRows(vault);+ const spawned = atReturn.find((row) => row.decision === SELF_HEAL_SPAWN.spawned);+ expect(spawned).toBeDefined();+ expect(spawned?.runId ?? "").not.toBe("");+ expect(atReturn.some((row) => row.outcome !== null)).toBe(false);++ const done = await pollUntil(+ () =>+ readSelfHealReindexRows(vault).some(+ (row) => row.outcome === SELF_HEAL_REINDEX_OUTCOME.completed,+ ),+ CHILD_BUDGET_MS,+ );+ expect(done).toBe(true);+ expect(existsSync(dbPath())).toBe(true);++ // Parent and child rows pair on the run id the parent minted and+ // handed to the child - not on a pid, which is machine-local and+ // therefore false on every peer this vault syncs to.+ const rows = readSelfHealReindexRows(vault);+ const completed = rows.find((row) => row.outcome === SELF_HEAL_REINDEX_OUTCOME.completed);+ expect(completed?.runId).toBe(spawned?.runId ?? "");+ },+ CHILD_BUDGET_MS + 10_000,+ );++ test(+ "two parents probing in the same window both spawn: the probe thins nothing here",+ async () => {+ // The measured shape of the advisory probe, pinned so the docblock+ // cannot drift away from it: the window between the probe and the+ // child's own `acquireWriterLock` is a cold Bun start - measured at+ // 710-753 ms over five samples on a 400-note vault - so every parent+ // that probes inside it finds the lock free and spawns.+ const [a, b] = await Promise.all([+ ensureVaultCurrent(vault, { background: true, configPath }),+ ensureVaultCurrent(vault, { background: true, configPath }),+ ]);+ expect(a.reindexSpawn).toBe(SELF_HEAL_SPAWN.spawned);+ expect(b.reindexSpawn).toBe(SELF_HEAL_SPAWN.spawned);++ // Both children run; the writer lock - not the probe - is what makes+ // one of them the only rebuild. Waiting for both terminal rows also+ // keeps the teardown from racing a live child.+ const settled = await pollUntil(+ () => readSelfHealReindexRows(vault).filter((row) => row.outcome !== null).length >= 2,+ CHILD_BUDGET_MS,+ );+ expect(settled).toBe(true);+ const outcomes = readSelfHealReindexRows(vault).filter((row) => row.outcome !== null);+ expect(outcomes.some((row) => row.outcome === SELF_HEAL_REINDEX_OUTCOME.completed)).toBe(+ true,+ );+ },+ CHILD_BUDGET_MS + 10_000,+ );+});++describe("self-heal reindex: the child's terminal outcome", () => {+ test(+ "a child that loses the lock records the failure by name",+ async () => {+ const runId = mintSelfHealRunId();+ const release = await holdWriterLock();+ try {+ await expect(+ cmdSearchReindex([+ "--self-heal",+ runId,+ "--vault",+ vault,+ "--config",+ configPath,+ "--json",+ ]),+ ).rejects.toThrow();+ } finally {+ await release();+ }++ const failures = readSelfHealReindexRows(vault).filter(+ (row) => row.outcome === SELF_HEAL_REINDEX_OUTCOME.failed,+ );+ expect(failures.length).toBe(1);+ // Not a bare zero and not a bare boolean: the row names what failed.+ expect(failures[0]?.error ?? "").toContain("INDEX_LOCKED");+ expect(failures[0]?.runId).toBe(runId);+ },+ CONTENTION_BUDGET_MS,+ );++ test(+ "a child that cannot resolve its own configuration still records a terminal row",+ async () => {+ // C9 case 2: `resolveConfig` used to run outside the recording, so a+ // child that died here left its parent's spawn row unpaired - which+ // the docblock read as a child that vanished.+ const badConfig = join(configHome, "bad-config.yaml");+ atomicWriteFileSync(badConfig, `vault: ${vault}\nsearch_chunk_size: -5\n`);+ const runId = mintSelfHealRunId();++ await expect(+ cmdSearchReindex(["--self-heal", runId, "--vault", vault, "--config", badConfig]),+ ).rejects.toThrow(/search_chunk_size/);++ const rows = readSelfHealReindexRows(vault);+ const failed = rows.find((row) => row.runId === runId);+ expect(failed?.outcome).toBe(SELF_HEAL_REINDEX_OUTCOME.failed);+ expect(failed?.error ?? "").toContain("search_chunk_size");+ },+ CONTENTION_BUDGET_MS,+ );++ test("a run without --self-heal records nothing", async () => {+ const code = await cmdSearchReindex(["--vault", vault, "--config", configPath, "--json"]);+ expect(code).toBe(0);+ expect(readSelfHealReindexRows(vault)).toEqual([]);+ });+});++describe("self-heal reindex: what a pair is, and what it is not", () => {+ test("two runs in one process do not pair, because the pair is a run id", () => {+ const spawnedRun = mintSelfHealRunId();+ const otherRun = mintSelfHealRunId();+ recordSelfHealSpawn(vault, SELF_HEAL_SPAWN.spawned, spawnedRun);+ // A second, unrelated self-heal recorded by the SAME process - which is+ // exactly what a pid pairing cannot tell apart, on one host through pid+ // reuse and across a synced vault through two devices' pid spaces.+ recordSelfHealOutcome(vault, SELF_HEAL_REINDEX_OUTCOME.completed, otherRun, 12);++ const rows = readSelfHealReindexRows(vault);+ const spawned = rows.find((row) => row.decision === SELF_HEAL_SPAWN.spawned);+ expect(spawned?.runId).toBe(spawnedRun);+ expect(rows.some((row) => row.outcome !== null && row.runId === spawned?.runId)).toBe(false);+ });++ test("no machine-local value is written into a row", () => {+ recordSelfHealSpawn(vault, SELF_HEAL_SPAWN.spawned, mintSelfHealRunId());+ recordSelfHealOutcome(vault, SELF_HEAL_REINDEX_OUTCOME.completed, mintSelfHealRunId(), 3);+ // The module's own claim, asserted against the bytes: a pid is+ // machine-local, and these rows sync to peers where it is false.+ for (const record of listMetrics(vault, { surface: SELF_HEAL_REINDEX_SURFACE })) {+ expect(Object.keys(record.payload)).not.toContain("pid");+ }+ });+});diff --git a/tests/core/partner/codegraph-timeout.test.ts b/tests/core/partner/codegraph-timeout.test.tsnew file mode 100644index 00000000..4d190589--- /dev/null+++ b/tests/core/partner/codegraph-timeout.test.ts@@ -0,0 +1,140 @@+/**+ * A partner that never answers (nothing-runs-unwatched, review finding 8).+ *+ * `checkCodegraph` spawns the partner CLI SYNCHRONOUSLY and `doctor()` has+ * three callers: the CLI, the MCP `vault_health` tool and the OpenClaw+ * extension. Issued with no `timeout`, a partner that wedges - a stale+ * lock, an NFS stall, an index rebuild that never returns - blocks all+ * three for as long as it wedges, with no deadline and no refusal.+ *+ * These tests spawn a REAL process, because that is the only way to fail+ * for the intended reason: a fake `runStatusJson` returning a timeout+ * record would pass just as happily against a check that still has no+ * bound at all. The fake `codegraph` on PATH is a `sh` script that sleeps+ * far longer than the budget the check is given.+ *+ * The second thing asserted here is the DISTINCTION. "The partner said the+ * index is stale" and "the partner never answered" are different facts,+ * and a build that reports the second as the first sends an operator to+ * `codegraph init` over a process that is still running.+ */++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 {+ checkCodegraph,+ CODEGRAPH_CLI,+ CODEGRAPH_PARTNER_TIMEOUT_MS,+ defaultDetectProjectPathSupport,+ defaultRunStatusJson,+} from "../../../src/core/partner/codegraph.ts";++let tmp: string;+let repo: string;+let vault: string;+let savedPath: string | undefined;++/** How long the fake partner hangs: long enough that only a bound ends it. */+const HANG_SECONDS = 30;++/** The budget the check is given in these tests. Short, and still a real wait. */+const BUDGET_MS = 400;++/** A directory that passes `isCodeProject` and looks already indexed. */+function makeIndexedRepo(dir: string): string {+ mkdirSync(join(dir, ".git"), { recursive: true });+ mkdirSync(join(dir, ".codegraph"), { recursive: true });+ writeFileSync(join(dir, "package.json"), "{}\n", "utf8");+ return dir;+}++/** A `codegraph` on PATH that accepts every argument and never answers. */+function makeHangingCodegraph(binDir: string): void {+ mkdirSync(binDir, { recursive: true });+ const script = join(binDir, CODEGRAPH_CLI.bin);+ writeFileSync(script, `#!/bin/sh\nsleep ${HANG_SECONDS}\n`, "utf8");+ chmodSync(script, 0o755);+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-codegraph-timeout-"));+ repo = makeIndexedRepo(join(tmp, "repo"));+ vault = join(tmp, "vault");+ mkdirSync(vault, { recursive: true });+ makeHangingCodegraph(join(tmp, "bin"));+ savedPath = process.env["PATH"];+ // PREPENDED rather than replaced: the fake shadows any real partner on+ // this machine, and `sh` still has to find `sleep`.+ process.env["PATH"] = `${join(tmp, "bin")}:${savedPath ?? ""}`;+});++afterEach(() => {+ if (savedPath === undefined) delete process.env["PATH"];+ else process.env["PATH"] = savedPath;+ rmSync(tmp, { recursive: true, force: true });+});++describe("the partner consult is bounded", () => {+ test("a status query that never answers returns, and says it did not answer", () => {+ const started = Date.now();+ const result = defaultRunStatusJson(repo, BUDGET_MS);+ const waited = Date.now() - started;++ // Without a bound this call does not return for HANG_SECONDS.+ expect(waited).toBeLessThan(HANG_SECONDS * 1000);+ expect(result.ok).toBe(false);+ expect("unanswered" in result).toBe(true);+ });++ test("the check reports a probe that did not complete, not an index that failed", () => {+ const started = Date.now();+ const check = checkCodegraph({ cwd: repo, vault }, { timeoutMs: BUDGET_MS });+ const waited = Date.now() - started;++ expect(waited).toBeLessThan(HANG_SECONDS * 1000);+ expect(check).not.toBeNull();+ expect(check!.ok).toBe(false);+ // The distinction this test exists for: the message must not read as+ // the partner having answered, and must not send the operator to+ // `codegraph init` over a process that is still running.+ expect(check!.message).toContain("did not answer");+ expect(check!.message).toContain(String(BUDGET_MS));+ expect(check!.message).not.toContain("not indexed");+ expect(check!.message).not.toContain("status failed");+ });++ test("the help probe is bounded too, and a probe that timed out claims nothing", () => {+ const started = Date.now();+ const supported = defaultDetectProjectPathSupport(BUDGET_MS);+ expect(Date.now() - started).toBeLessThan(HANG_SECONDS * 1000);+ expect(supported).toBe(false);+ });++ test("a wedged partner is asked once, not once per project", () => {+ // Two projects and a partner that hangs: a per-project retry would+ // multiply the wait by the project count, which is how a bound stops+ // bounding anything.+ const second = makeIndexedRepo(join(tmp, "repo-b"));+ const started = Date.now();+ const check = checkCodegraph(+ { cwd: repo, vault, scanExtraPaths: [second] },+ { timeoutMs: BUDGET_MS, detectProjectPathSupport: () => true },+ );+ const waited = Date.now() - started;++ expect(check!.ok).toBe(false);+ expect(check!.message).toContain("not consulted");+ // One budget plus slack, not two.+ expect(waited).toBeLessThan(BUDGET_MS * 2);+ });++ test("the default budget is a bound rather than a target", () => {+ // Pinned so a later edit cannot quietly remove the deadline by+ // setting it to something no partner could exceed.+ expect(CODEGRAPH_PARTNER_TIMEOUT_MS).toBeGreaterThan(0);+ expect(CODEGRAPH_PARTNER_TIMEOUT_MS).toBeLessThanOrEqual(30_000);+ });+});diff --git a/tests/core/partner/codegraph.test.ts b/tests/core/partner/codegraph.test.tsindex 5859d3a0..2551a2dd 100644--- a/tests/core/partner/codegraph.test.ts+++ b/tests/core/partner/codegraph.test.ts@@ -149,13 +149,18 @@ describe("checkCodegraph", () => {expect(r).toBeNull();});- test("null when disabled", () => {+ test("disabled reports the switch that silenced it, rather than nothing at all", () => {+ // It used to return null, which made a check the operator turned off+ // indistinguishable from a machine with no codegraph on it (U12).const repo = makeRepo(join(tmp, "repo"));const r = checkCodegraph({ cwd: repo, vault: join(tmp, "vault"), disabled: true },{ whichCodegraph: () => "/usr/bin/codegraph" },);- expect(r).toBeNull();+ expect(r).not.toBeNull();+ expect(r!.ok).toBe(true);+ expect(r!.message).toContain("disabled");+ expect(r!.message).toContain("OPEN_SECOND_BRAIN_PARTNER_CODEGRAPH_DISABLED");});test("code project + no CLI -> skipped (codegraph is optional)", () => {diff --git a/tests/core/search/benchmark-concurrency.test.ts b/tests/core/search/benchmark-concurrency.test.tsnew file mode 100644index 00000000..d6c7425b--- /dev/null+++ b/tests/core/search/benchmark-concurrency.test.ts@@ -0,0 +1,62 @@+/**+ * The recall benchmark's fan-out is bounded (nothing-runs-unwatched, U4).+ *+ * `runRecallBenchmark` issued one concurrent `search()` per dataset query+ * with no cap - and `tuneRecall` amplifies that 24x through its parameter+ * grid, so an operator-supplied dataset of a few hundred queries opened a+ * few thousand concurrent SQLite reads. The queries being read-only makes+ * the concurrency CORRECT; it never made it bounded.+ */++import { test, expect, beforeEach, afterEach } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ BENCHMARK_QUERY_CONCURRENCY,+ _benchmarkQueryPeakForTests,+ parseRecallBenchmarkDataset,+ runRecallBenchmark,+} from "../../../src/core/search/benchmark.ts";+import { indexVault } from "../../../src/core/search/indexer.ts";+import { makeConfig } from "../../helpers/search-fixtures.ts";+import type { ResolvedSearchConfig } from "../../../src/core/search/types.ts";++/** Comfortably more queries than the ceiling, so the ceiling binds. */+const QUERY_COUNT = BENCHMARK_QUERY_CONCURRENCY * 2;++let vault: string;+let config: ResolvedSearchConfig;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-benchmark-ceiling-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+ writeFileSync(+ join(vault, "canary.md"),+ "# Canary rollout\n\nShip one instance, observe it, then widen the rollout.\n",+ );+ config = makeConfig({ vault, dbPath: join(vault, "index.sqlite") });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("the fan-out never exceeds its named ceiling on a larger dataset", async () => {+ await indexVault(config);+ const dataset = parseRecallBenchmarkDataset({+ queries: Array.from({ length: QUERY_COUNT }, (_, i) => ({+ id: `q${i}`,+ query: "canary rollout",+ expected: ["canary.md"],+ })),+ });++ const report = await runRecallBenchmark(config, dataset);++ expect(report.perQuery.length).toBe(QUERY_COUNT);+ // Exactly the ceiling: every task takes its permit before any search+ // can release one, so the high-water mark saturates.+ expect(_benchmarkQueryPeakForTests()).toBe(BENCHMARK_QUERY_CONCURRENCY);+});diff --git a/tests/core/search/embeddings.concurrency-ceiling.test.ts b/tests/core/search/embeddings.concurrency-ceiling.test.tsnew file mode 100644index 00000000..f9e29276--- /dev/null+++ b/tests/core/search/embeddings.concurrency-ceiling.test.ts@@ -0,0 +1,377 @@+/**+ * The outbound-request ceiling, from the counting primitive up+ * (nothing-runs-unwatched, U4).+ *+ * Four claims, in the order they compose:+ * 1. `Semaphore` never lets more holders in than its ceiling, including+ * when a fresh acquire lands in the same synchronous turn as a+ * release.+ * 2. A permit cannot be given back twice, so no caller can widen the+ * ceiling for every other caller - and `peakInFlight` counts what+ * actually entered rather than a number the breach itself lowers.+ * 3. The ceiling is taken exactly as configured or refused - never+ * truncated into a different one.+ * 4. The ceiling spans the PROCESS and is keyed per (identity,+ * endpoint): two overlapping `embed()` calls against one resolved+ * provider identity share one budget, and two identities against one+ * endpoint get one budget EACH - so an endpoint carries+ * `embedding_concurrency x identities` at most.+ */++import { test, expect, describe, beforeEach, afterEach } from "bun:test";++import { Semaphore } from "../../../src/core/search/embeddings/http-util.ts";+import type { SemaphorePermit } from "../../../src/core/search/embeddings/http-util.ts";+import { OpenAICompatProvider } from "../../../src/core/search/embeddings/openai-compat.ts";+import { _resetProviderCeilingsForTests } from "../../../src/core/search/embeddings/provider-semaphore.ts";+import { ZeroEntropyProvider } from "../../../src/core/search/embeddings/zeroentropy.ts";+import { SearchError } from "../../../src/core/search/types.ts";+import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";+import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";++test("Semaphore hands a released permit to the waiter, not to a racing acquirer", async () => {+ const sem = new Semaphore(1);+ let held = 0;+ let peak = 0;+ const enter = (): void => {+ held++;+ if (held > peak) peak = held;+ };+ const leave = (permit: SemaphorePermit): void => {+ held--;+ permit();+ };++ // A holds the only permit.+ const a = await sem.acquire();+ enter();++ // The critical section spans an await, so two holders overlap rather+ // than running to completion one microtask apart.+ const hold = async (permit: SemaphorePermit): Promise<void> => {+ enter();+ await Promise.resolve();+ leave(permit);+ };++ // B queues behind A.+ const b = sem.acquire().then(hold);++ // A releases. The freed permit is B's.+ leave(a);++ // C arrives in the SAME synchronous turn as that release - before B's+ // continuation has had a microtask to run. A semaphore that bumps its+ // permit count on release and lets the woken waiter decrement it later+ // hands this permit to C as well, and both run.+ const c = sem.acquire().then(hold);++ await Promise.all([b, c]);+ expect(peak).toBe(1);+ expect(held).toBe(0);+});++/**+ * Yield one macrotask turn, which drains every pending microtask first -+ * so a waiter that was going to be resumed has been resumed by the time+ * this returns, and one that was not, was not.+ */+async function settlePendingAcquirers(): Promise<void> {+ await new Promise<void>((resolve) => setTimeout(resolve, 0));+}++test("a permit cannot be given back twice, so no caller can widen the ceiling", async () => {+ const sem = new Semaphore(2);+ const first = await sem.acquire();+ const second = await sem.acquire();++ first();+ expect(() => first()).toThrow(SearchError);+ expect(() => first()).toThrow(/released twice/);++ // Exactly one permit came back, so exactly one of two acquirers enters.+ let entered = 0;+ const third = sem.acquire().then((p) => {+ entered++;+ return p;+ });+ const fourth = sem.acquire().then((p) => {+ entered++;+ return p;+ });+ await settlePendingAcquirers();+ expect(entered).toBe(1);+ expect(sem.peakInFlight).toBe(2);++ second();+ (await third)();+ (await fourth)();+});++test("a stray release cannot smuggle a queued waiter past the ceiling", async () => {+ const sem = new Semaphore(2);+ const a = await sem.acquire();+ const b = await sem.acquire();++ // C queues: both permits are out, so nothing is free for it to take.+ const queued = sem.acquire();+ a();+ const c = await queued;++ // The permit went straight from A to C, so the pool count is still 0+ // and a guard on "permits >= limit" sees nothing wrong here. The stray+ // release has to be refused on the holder's own record instead, or a+ // third permit exists against a ceiling of two.+ expect(() => a()).toThrow(SearchError);++ let entered = false;+ const fourth = sem.acquire().then((p) => {+ entered = true;+ return p;+ });+ await settlePendingAcquirers();+ expect(entered).toBe(false);+ expect(sem.peakInFlight).toBe(2);++ b();+ c();+ (await fourth)();+});++test("peakInFlight counts the holders that entered, not a number a stray release lowers", async () => {+ // The review's reproduction, turned into an assertion. Against the+ // previous Semaphore this printed:+ // limit: 2 | real concurrent holders: 4 | semaphore reports peakInFlight: 2+ // - the bound broken, and the instrument built to show it reading clean,+ // because the same stray releases drove the held count negative.+ const sem = new Semaphore(2);++ const stray = await sem.acquire();+ stray();+ expect(() => stray()).toThrow(SearchError);+ expect(() => stray()).toThrow(SearchError);++ let live = 0;+ let observedPeak = 0;+ const work = async (): Promise<void> => {+ const permit = await sem.acquire();+ live++;+ if (live > observedPeak) observedPeak = live;+ await new Promise<void>((r) => setTimeout(r, 5));+ live--;+ permit();+ };++ await Promise.all([work(), work(), work(), work()]);++ expect(observedPeak).toBe(2);+ expect(sem.peakInFlight).toBe(observedPeak);+ expect(live).toBe(0);+});++test("Semaphore takes a ceiling above 2^31-1 as given rather than truncating it", () => {+ // `embedding_concurrency` is validated as an integer >= 1 with no upper+ // bound, so this value is reachable from config. The former+ // `Math.max(1, n | 0)` wrapped it negative and the clamp lifted it to 1:+ // the largest ceiling an operator can ask for silently became the+ // smallest one possible.+ const sem = new Semaphore(3_000_000_000);+ expect(sem.limit).toBe(3_000_000_000);+});++test("Semaphore refuses a ceiling it cannot honour", () => {+ expect(() => new Semaphore(0)).toThrow(SearchError);+ expect(() => new Semaphore(-1)).toThrow(SearchError);+ expect(() => new Semaphore(2.5)).toThrow(SearchError);+ expect(() => new Semaphore(Number.NaN)).toThrow(SearchError);+});++/**+ * Milliseconds a stubbed embedding request stays in flight. Long enough+ * that overlapping requests are observable, short enough to keep the+ * suite fast.+ */+const STUB_LATENCY_MS = 25;++interface ConcurrencyProbe {+ /** Most stubbed requests in flight at once, over the server's lifetime. */+ peak: number;+}++/** Fixed-width, non-zero vector so unit-normalisation succeeds. */+const STUB_VECTOR: ReadonlyArray<number> = [1, 2];++/** OpenAI `/v1/embeddings` response body for `n` inputs. */+function openAiBody(inputs: ReadonlyArray<string>, model: string): unknown {+ return {+ model,+ data: inputs.map((_, index) => ({ object: "embedding", embedding: STUB_VECTOR, index })),+ };+}++/** ZeroEntropy `/models/embed` response body for `n` inputs. */+function zeroEntropyBody(inputs: ReadonlyArray<string>): unknown {+ return { results: inputs.map((_, index) => ({ index, embedding: STUB_VECTOR })) };+}++/**+ * Install a handler that holds each request open for {@link STUB_LATENCY_MS}+ * and reports the high-water mark of concurrent in-flight requests. Both+ * provider wire shapes carry their texts in `input`, so one probe serves+ * both; `respond` supplies the shape of the reply.+ */+function probeConcurrency(+ server: FakeHttp,+ respond: (inputs: ReadonlyArray<string>, model: string) => unknown = openAiBody,+): ConcurrencyProbe {+ const probe: ConcurrencyProbe = { peak: 0 };+ let inFlight = 0;+ server.setHandler(async (req) => {+ inFlight++;+ if (inFlight > probe.peak) probe.peak = inFlight;+ await new Promise<void>((r) => setTimeout(r, STUB_LATENCY_MS));+ inFlight--;+ const body = (req.body ?? {}) as { input?: string[]; model?: string };+ const inputs = Array.isArray(body.input) ? body.input : [];+ return { status: 200, body: respond(inputs, body.model ?? "fake-model") };+ });+ return probe;+}++/** One text per request, so the batch count equals the request count. */+function ceilingCfg(+ baseUrl: string,+ overrides: Partial<ResolvedEmbeddingConfig> = {},+): ResolvedEmbeddingConfig {+ return Object.freeze({+ enabled: true,+ provider: "openai-compat",+ baseUrl,+ model: "fake-model",+ apiKey: "test-key",+ dimension: 2,+ timeoutMs: 5_000,+ concurrency: 2,+ batchSize: 1,+ costGateUsd: 0,+ maxRetries: 1,+ ...overrides,+ });+}++const FOUR_TEXTS = ["a", "b", "c", "d"];++describe("the ceiling spans the process", () => {+ let server: FakeHttp;++ beforeEach(async () => {+ _resetProviderCeilingsForTests();+ server = await startFakeHttp();+ });++ afterEach(async () => {+ await server.close();+ });++ test("two overlapping embed() calls on one identity share one budget", async () => {+ const probe = probeConcurrency(server);+ const first = new OpenAICompatProvider(ceilingCfg(server.url));+ const second = new OpenAICompatProvider(ceilingCfg(server.url));++ await Promise.all([first.embed(FOUR_TEXTS), second.embed(FOUR_TEXTS)]);++ // A semaphore built inside embed() would allow 2 per call = 4.+ expect(probe.peak).toBe(2);+ expect(server.callCount()).toBe(FOUR_TEXTS.length * 2);+ });++ test("a ceiling of 1 serialises across two overlapping calls", async () => {+ const probe = probeConcurrency(server);+ const cfg = ceilingCfg(server.url, { concurrency: 1 });+ const first = new OpenAICompatProvider(cfg);+ const second = new OpenAICompatProvider(cfg);++ await Promise.all([first.embed(FOUR_TEXTS), second.embed(FOUR_TEXTS)]);++ expect(probe.peak).toBe(1);+ });++ test("two identities on one endpoint do not share a ceiling", async () => {+ const probe = probeConcurrency(server);+ const first = new OpenAICompatProvider(+ ceilingCfg(server.url, { concurrency: 1, model: "model-a" }),+ );+ const second = new OpenAICompatProvider(+ ceilingCfg(server.url, { concurrency: 1, model: "model-b" }),+ );++ await Promise.all([first.embed(FOUR_TEXTS), second.embed(FOUR_TEXTS)]);++ expect(probe.peak).toBe(2);+ });++ test("an endpoint carries the ceiling ONCE PER IDENTITY, not once in total", async () => {+ // What the ceiling bounds, pinned in the one arrangement that can+ // distinguish the three readings of it. Two identities, two+ // overlapping calls each, ceiling 2:+ // - 2 would mean the endpoint itself is the budget (it is not: the+ // key carries the identity, and `embedding_concurrency` is+ // configured per identity, so there is no per-host number to+ // enforce);+ // - 8 would mean the semaphore is per `embed()` call again;+ // - 4 is the shipped behaviour: one shared budget per identity.+ // The two negative tests below cannot tell these apart on their own -+ // they pin the partition, not the ceiling.+ const probe = probeConcurrency(server);+ const a = ceilingCfg(server.url, { concurrency: 2, model: "model-a" });+ const b = ceilingCfg(server.url, { concurrency: 2, model: "model-b" });++ await Promise.all([+ new OpenAICompatProvider(a).embed(FOUR_TEXTS),+ new OpenAICompatProvider(a).embed(FOUR_TEXTS),+ new OpenAICompatProvider(b).embed(FOUR_TEXTS),+ new OpenAICompatProvider(b).embed(FOUR_TEXTS),+ ]);++ expect(probe.peak).toBe(4);+ });++ test("one identity on two endpoints does not share a ceiling", async () => {+ const other = await startFakeHttp();+ try {+ const probe = probeConcurrency(server);+ const otherProbe = probeConcurrency(other);+ const here = new OpenAICompatProvider(ceilingCfg(server.url, { concurrency: 1 }));+ const there = new OpenAICompatProvider(ceilingCfg(other.url, { concurrency: 1 }));++ await Promise.all([here.embed(FOUR_TEXTS), there.embed(FOUR_TEXTS)]);++ expect(probe.peak).toBe(1);+ expect(otherProbe.peak).toBe(1);+ } finally {+ await other.close();+ }+ });++ test("two configurations that disagree on the ceiling are refused, not reconciled", async () => {+ probeConcurrency(server);+ const first = new OpenAICompatProvider(ceilingCfg(server.url, { concurrency: 2 }));+ const second = new OpenAICompatProvider(ceilingCfg(server.url, { concurrency: 3 }));++ await first.embed(["a"]);+ await expect(second.embed(["b"])).rejects.toThrow(SearchError);+ await expect(second.embed(["b"])).rejects.toThrow(/embedding_concurrency/);+ });++ test("the zeroentropy provider is bounded the same way", async () => {+ const probe = probeConcurrency(server, zeroEntropyBody);+ const cfg = ceilingCfg(server.url, { provider: "zeroentropy", concurrency: 2 });+ const first = new ZeroEntropyProvider(cfg);+ const second = new ZeroEntropyProvider(cfg);++ await Promise.all([first.embed(FOUR_TEXTS), second.embed(FOUR_TEXTS)]);++ expect(probe.peak).toBe(2);+ expect(server.callCount()).toBe(FOUR_TEXTS.length * 2);+ });+});diff --git a/tests/core/search/embeddings.sunset.test.ts b/tests/core/search/embeddings.sunset.test.tsnew file mode 100644index 00000000..3c46c29c--- /dev/null+++ b/tests/core/search/embeddings.sunset.test.ts@@ -0,0 +1,336 @@+/**+ * The sunset survey, and the three statements it is allowed to make.+ *+ * The distinction this file exists to hold is between "no decommission has+ * been announced for this model" and "this model is outside the survey, so+ * no statement was made about it". They are different facts and the second+ * is the NORMAL case - `embedding_model` is a free string with no+ * validation and this tool's own onboarding text recommends a preview+ * model that is in no catalog here. Collapsing them into silence is the+ * misleading-silence defect the codebase has already ruled on twice, for+ * the input window (`declaredInputWindowTokens`) and for the+ * `window-undeclared` census verdict.+ *+ * The third statement is the one a static catalog owes: a NEGATIVE is a+ * claim about the world and it expires. Past the horizon, "nothing+ * announced" becomes `undetermined` with `survey_stale` rather than+ * staying a confident negative that nobody has re-checked.+ */++import { describe, expect, test } from "bun:test";++import {+ classifyEmbeddingSunset,+ EMBEDDING_SUNSET,+ EMBEDDING_SUNSET_SOURCE,+ EMBEDDING_SUNSET_STATES,+ EMBEDDING_SUNSET_SURVEY,+ EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS,+ EMBEDDING_SUNSET_UNDETERMINED_REASON,+ EMBEDDING_SUNSET_UNDETERMINED_REASONS,+ isEmbeddingSunsetState,+ isEmbeddingSunsetUndeterminedReason,+ type EmbeddingSunsetSurvey,+} from "../../../src/core/search/embeddings/sunset.ts";+import { isValidIsoInstant, parseIsoUtc } from "../../../src/core/brain/health/iso-time.ts";++const MS_PER_DAY = 24 * 60 * 60 * 1000;+const NOW = Date.parse("2026-06-01T00:00:00.000Z");+/** A model string no shipped row carries, so a fixture owns it outright. */+const MODEL_A = "vendor/model-x";++/** A survey under this test's control, reviewed the day before `NOW`. */+function survey(entries: EmbeddingSunsetSurvey["entries"]): EmbeddingSunsetSurvey {+ return { reviewedAt: "2026-05-31", entries };+}++describe("a declared decommission date is reported with its date", () => {+ test("a date in the future yields `announced` and the days remaining", () => {+ const s = survey([+ { model: "vendor/model-x", sunsetAt: "2026-07-01", source: "unit fixture", note: "" },+ ]);+ const verdict = classifyEmbeddingSunset("vendor/model-x", NOW, s);+ expect(verdict.state).toBe(EMBEDDING_SUNSET.announced);+ expect(verdict.sunset_at).toBe("2026-07-01");+ expect(verdict.days_remaining).toBe(30);+ expect(verdict.reason).toBeNull();+ });++ test("a date already past is still `announced`, with a negative remainder", () => {+ const s = survey([+ { model: "vendor/model-x", sunsetAt: "2026-05-01", source: "unit fixture", note: "" },+ ]);+ const verdict = classifyEmbeddingSunset("vendor/model-x", NOW, s);+ expect(verdict.state).toBe(EMBEDDING_SUNSET.announced);+ expect(verdict.days_remaining).toBeLessThan(0);+ });++ test("lookup is by exact model string, with no family inference", () => {+ const s = survey([+ { model: "vendor/model-x", sunsetAt: "2026-07-01", source: "unit fixture", note: "" },+ ]);+ // `vendor/model-x-turbo` is a different checkpoint with a different+ // lifecycle; inferring a date from a shared prefix would invent one.+ expect(classifyEmbeddingSunset("vendor/model-x-turbo", NOW, s).state).toBe(+ EMBEDDING_SUNSET.unsurveyed,+ );+ });+});++describe("`unsurveyed` is never reported as `none_announced`", () => {+ test("a model outside the survey is its own state", () => {+ const verdict = classifyEmbeddingSunset("openrouter/whatever", NOW, survey([]));+ expect(verdict.state).toBe(EMBEDDING_SUNSET.unsurveyed);+ expect(verdict.state).not.toBe(EMBEDDING_SUNSET.noneAnnounced);+ expect(verdict.sunset_at).toBeNull();+ });++ test("a surveyed model with no announcement is the other state", () => {+ const s = survey([+ { model: "vendor/model-y", sunsetAt: null, source: "unit fixture", note: "" },+ ]);+ expect(classifyEmbeddingSunset("vendor/model-y", NOW, s).state).toBe(+ EMBEDDING_SUNSET.noneAnnounced,+ );+ });++ test("the tool's own recommended onboarding model is unsurveyed, not clean", () => {+ // `src/cli/main.ts` recommends a preview model that no catalog here+ // carries. That is the normal case, and it must read as "no statement+ // was made" rather than as a clean bill of health.+ const verdict = classifyEmbeddingSunset("google/gemini-embedding-2-preview", NOW);+ expect(verdict.state).toBe(EMBEDDING_SUNSET.unsurveyed);+ });+});++describe("a negative expires; the survey's own age bounds what it may claim", () => {+ test("past the horizon, `none_announced` degrades to undetermined", () => {+ const s = survey([+ { model: "vendor/model-y", sunsetAt: null, source: "unit fixture", note: "" },+ ]);+ const later =+ parseIsoUtc(s.reviewedAt) + (EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS + 1) * MS_PER_DAY;+ const verdict = classifyEmbeddingSunset("vendor/model-y", later, s);+ expect(verdict.state).toBe(EMBEDDING_SUNSET.undetermined);+ expect(verdict.reason).toBe(EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyStale);+ });++ test("a declared date survives a stale survey - a shutdown that was announced happened", () => {+ const s = survey([+ { model: "vendor/model-x", sunsetAt: "2030-01-01", source: "unit fixture", note: "" },+ ]);+ const later =+ parseIsoUtc(s.reviewedAt) + (EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS + 1) * MS_PER_DAY;+ expect(classifyEmbeddingSunset("vendor/model-x", later, s).state).toBe(+ EMBEDDING_SUNSET.announced,+ );+ });++ test("every verdict carries the review date it rests on", () => {+ const s = survey([]);+ expect(classifyEmbeddingSunset("anything", NOW, s).surveyed_at).toBe(s.reviewedAt);+ });+});++describe("what the classifier cannot establish", () => {+ test("no configured model is undetermined, never `none_announced`", () => {+ const verdict = classifyEmbeddingSunset(null, NOW, survey([]));+ expect(verdict.state).toBe(EMBEDDING_SUNSET.undetermined);+ expect(verdict.reason).toBe(EMBEDDING_SUNSET_UNDETERMINED_REASON.modelUnresolved);+ });++ test("a malformed date in the survey is refused loudly, never read as absent", () => {+ const s = survey([+ { model: "vendor/model-z", sunsetAt: "not-a-date", source: "unit fixture", note: "" },+ ]);+ const verdict = classifyEmbeddingSunset("vendor/model-z", NOW, s);+ expect(verdict.state).toBe(EMBEDDING_SUNSET.undetermined);+ expect(verdict.reason).toBe(EMBEDDING_SUNSET_UNDETERMINED_REASON.surveyEntryMalformed);+ });+});++describe("the clock is a parameter", () => {+ test("two instants over one survey give two verdicts", () => {+ const s = survey([+ { model: "vendor/model-y", sunsetAt: null, source: "unit fixture", note: "" },+ ]);+ const early = classifyEmbeddingSunset("vendor/model-y", parseIsoUtc(s.reviewedAt), s);+ const late = classifyEmbeddingSunset(+ "vendor/model-y",+ parseIsoUtc(s.reviewedAt) + (EMBEDDING_SUNSET_SURVEY_HORIZON_DAYS + 1) * MS_PER_DAY,+ s,+ );+ expect(early.state).not.toBe(late.state);+ });+});++describe("an operator declaration layers OVER the survey", () => {+ const DECLARED = "2026-09-01";++ test("it answers for a model the survey never heard of", () => {+ const verdict = classifyEmbeddingSunset("vendor-q/private-embed", NOW, survey([]), {+ model: "vendor-q/private-embed",+ sunsetAt: DECLARED,+ });+ expect(verdict.state).toBe(EMBEDDING_SUNSET.announced);+ expect(verdict.sunset_at).toBe(DECLARED);+ expect(verdict.source).toBe(EMBEDDING_SUNSET_SOURCE.declaration);+ expect(verdict.overrode_survey).toBe(false);+ });++ test("it WINS over a survey row that names a different date, and says so", () => {+ const s = survey([+ { model: MODEL_A, sunsetAt: "2027-01-01", source: "unit fixture", note: "" },+ ]);+ const verdict = classifyEmbeddingSunset(MODEL_A, NOW, s, {+ model: MODEL_A,+ sunsetAt: DECLARED,+ });+ // The declaration exists BECAUSE the static table goes stale, so the+ // operator who just read the vendor's notice outranks a table frozen+ // at release. The disagreement is carried, never erased.+ expect(verdict.sunset_at).toBe(DECLARED);+ expect(verdict.source).toBe(EMBEDDING_SUNSET_SOURCE.declaration);+ expect(verdict.overrode_survey).toBe(true);+ expect(verdict.survey_sunset_at).toBe("2027-01-01");+ });++ test("it WINS over a surveyed negative, and the contradiction is visible", () => {+ const s = survey([{ model: MODEL_A, sunsetAt: null, source: "unit fixture", note: "" }]);+ const verdict = classifyEmbeddingSunset(MODEL_A, NOW, s, {+ model: MODEL_A,+ sunsetAt: DECLARED,+ });+ expect(verdict.state).toBe(EMBEDDING_SUNSET.announced);+ expect(verdict.overrode_survey).toBe(true);+ // `null` is the survey's answer, not an absence of one.+ expect(verdict.survey_sunset_at).toBeNull();+ });++ test("the SURVEY wins when the declaration is about another model", () => {+ // The other direction. A declaration names its model explicitly, so a+ // stale one cannot silently re-target itself at whatever the operator+ // configured next.+ const s = survey([+ { model: MODEL_A, sunsetAt: "2027-01-01", source: "unit fixture", note: "" },+ ]);+ const verdict = classifyEmbeddingSunset(MODEL_A, NOW, s, {+ model: "some-other/model",+ sunsetAt: DECLARED,+ });+ expect(verdict.sunset_at).toBe("2027-01-01");+ expect(verdict.source).toBe(EMBEDDING_SUNSET_SOURCE.survey);+ expect(verdict.overrode_survey).toBe(false);+ });++ test("a verdict from neither layer names neither", () => {+ const verdict = classifyEmbeddingSunset("nobody/knows", NOW, survey([]));+ expect(verdict.state).toBe(EMBEDDING_SUNSET.unsurveyed);+ expect(verdict.source).toBe(EMBEDDING_SUNSET_SOURCE.none);+ });++ test("a declaration this build cannot parse is a caller's error, not a vault's verdict", () => {+ // It used to be `undetermined/declaration_malformed`: a reported+ // state, with its own vocabulary member and its own four-sentence+ // operator message, that no vault could produce. `sunset_at` is+ // validated by `parseEmbeddingsBlock` - the only producer of+ // `BrainConfig.embeddings` - which throws a `BrainConfigError` naming+ // the key at load time, and that refusal is pinned in+ // `tests/core/brain/policy/embeddings-block.test.ts`. What is left+ // here is an invariant over an exported function, and it says so+ // rather than inventing an instant.+ expect(() =>+ classifyEmbeddingSunset(MODEL_A, NOW, survey([]), {+ model: MODEL_A,+ sunsetAt: "next tuesday",+ }),+ ).toThrow(TypeError);+ });+});++describe("the shipped survey reaches the `announced` arm in production", () => {+ test("it carries at least one positive row - the code has a real producer", () => {+ // The reason this assertion exists: a registered doctor code whose+ // only producer is a table with no positive rows is a declared+ // surface with nothing behind it, which is the defect this release+ // hunts in other people's code.+ const positives = EMBEDDING_SUNSET_SURVEY.entries.filter((e) => e.sunsetAt !== null);+ expect(positives.length).toBeGreaterThan(0);+ });++ test("a first-generation OpenAI model resolves to its real shutdown date", () => {+ // No injected fixture: this is the shipped table answering.+ const verdict = classifyEmbeddingSunset("text-search-ada-doc-001", NOW);+ expect(verdict.state).toBe(EMBEDDING_SUNSET.announced);+ expect(verdict.sunset_at).toBe("2024-01-04");+ // The date is in the past, so an operator restoring an old config is+ // told the model is already gone rather than finding out at index time.+ expect(verdict.days_remaining).toBeLessThan(0);+ });++ test("a live sibling of a shut-down model is NOT reported as shut down", () => {+ // `text-search-ada-doc-001` is gone and `text-embedding-ada-002` is+ // not; a prefix rule over "ada" would report a working model dead.+ expect(classifyEmbeddingSunset("text-embedding-ada-002", NOW).state).toBe(+ EMBEDDING_SUNSET.noneAnnounced,+ );+ });+});++describe("the shipped survey is well formed", () => {+ test("every row records where its answer came from", () => {+ const unsourced = EMBEDDING_SUNSET_SURVEY.entries+ .filter((e) => e.source.trim().length === 0)+ .map((e) => e.model);+ expect(unsourced.join("\n")).toBe("");+ });++ test("every POSITIVE row cites a retrievable source", () => {+ // A date is a claim about somebody else's product. An entry that+ // cannot be checked against the announcement it came from is exactly+ // the invented value this design refuses.+ const uncitable = EMBEDDING_SUNSET_SURVEY.entries+ .filter((e) => e.sunsetAt !== null && !e.source.includes("https://"))+ .map((e) => e.model);+ expect(uncitable.join("\n")).toBe("");+ });++ test("its review date is a real ISO date", () => {+ expect(isValidIsoInstant(EMBEDDING_SUNSET_SURVEY.reviewedAt)).toBe(true);+ });++ test("no model is surveyed twice", () => {+ const models = EMBEDDING_SUNSET_SURVEY.entries.map((e) => e.model);+ expect(new Set(models).size).toBe(models.length);+ });++ test("every declared date parses, and every entry says where it came from", () => {+ const bad: string[] = [];+ for (const entry of EMBEDDING_SUNSET_SURVEY.entries) {+ if (entry.sunsetAt !== null && !isValidIsoInstant(entry.sunsetAt)) {+ bad.push(`${entry.model}: unparseable sunsetAt ${entry.sunsetAt}`);+ }+ if (entry.source.trim().length === 0) bad.push(`${entry.model}: empty source`);+ }+ expect(bad.join("\n")).toBe("");+ });+});++describe("the vocabularies are closed and carry the could-not-tell member", () => {+ test("`undetermined` is a member", () => {+ expect(EMBEDDING_SUNSET_STATES).toContain(EMBEDDING_SUNSET.undetermined);+ });++ test("a reason is never readable back as a state", () => {+ for (const reason of EMBEDDING_SUNSET_UNDETERMINED_REASONS) {+ expect(`${reason} is a state: ${isEmbeddingSunsetState(reason)}`).toBe(+ `${reason} is a state: false`,+ );+ }+ for (const state of EMBEDDING_SUNSET_STATES) {+ expect(`${state} is a reason: ${isEmbeddingSunsetUndeterminedReason(state)}`).toBe(+ `${state} is a reason: false`,+ );+ }+ });+});diff --git a/tests/core/vault-backing.test.ts b/tests/core/vault-backing.test.tsnew file mode 100644index 00000000..705606bb--- /dev/null+++ b/tests/core/vault-backing.test.ts@@ -0,0 +1,186 @@+/**+ * What backs the vault path - and what this probe refuses to guess.+ *+ * The tempting shape here was a host classifier: local machine vs cloud+ * sandbox vs ephemeral container. Every signal that classifier would read+ * is ONE-WAY. `/.dockerenv` absent is the normal reading inside podman,+ * containerd, LXC and any image that deleted it; `/proc/1/cgroup` on a+ * cgroup v2 unified host is `0::/<path>` for a container and for a plain+ * systemd scope alike; and "containerised" is not "ephemeral" - a+ * bind-mounted volume in a container outlives a laptop's `/tmp`.+ *+ * So this file pins the narrow claim instead: which filesystem backs one+ * resolved path, and an explicit `undetermined` everywhere else. The last+ * describe block is the guard that keeps it narrow - it asserts the module+ * reads no container signal at all, because the failure this whole design+ * avoids is a NEGATIVE container signal being read back as a POSITIVE+ * verdict of durability.+ */++import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import {+ isVaultBackingState,+ isVaultBackingUndeterminedReason,+ probeVaultBacking,+ VAULT_BACKING,+ VAULT_BACKING_STATES,+ VAULT_BACKING_UNDETERMINED_REASON,+ VAULT_BACKING_UNDETERMINED_REASONS,+} from "../../src/core/vault-backing.ts";++const EXT4 = 0xef53;+const TMPFS = 0x01021994;+const OVERLAYFS = 0x794c7630;+/** A magic number no released filesystem uses; stands for "not in the table". */+const UNRECOGNISED = 0x0badf00d;++function withFsType(type: number) {+ return () => ({ type });+}++describe("the filesystem under the vault path decides the state", () => {+ test("a journalling disk filesystem is durable and names itself", () => {+ const verdict = probeVaultBacking("/vault", { platform: "linux", statfs: withFsType(EXT4) });+ expect(verdict.state).toBe(VAULT_BACKING.durable);+ expect(verdict.filesystem).toBe("ext4");+ expect(verdict.reason).toBeNull();+ });++ test("a memory-backed filesystem is volatile - the one provable loss", () => {+ const verdict = probeVaultBacking("/vault", { platform: "linux", statfs: withFsType(TMPFS) });+ expect(verdict.state).toBe(VAULT_BACKING.volatile);+ expect(verdict.filesystem).toBe("tmpfs");+ });++ test("a container overlay is layered, never durable and never volatile", () => {+ const verdict = probeVaultBacking("/vault", {+ platform: "linux",+ statfs: withFsType(OVERLAYFS),+ });+ expect(verdict.state).toBe(VAULT_BACKING.layered);+ expect(verdict.state).not.toBe(VAULT_BACKING.durable);+ expect(verdict.state).not.toBe(VAULT_BACKING.volatile);+ });+});++describe("everything the probe cannot establish says so, with a reason", () => {+ test("an unrecognised magic number is undetermined, NOT durable", () => {+ const verdict = probeVaultBacking("/vault", {+ platform: "linux",+ statfs: withFsType(UNRECOGNISED),+ });+ expect(verdict.state).toBe(VAULT_BACKING.undetermined);+ expect(verdict.reason).toBe(VAULT_BACKING_UNDETERMINED_REASON.fsTypeUnknown);+ expect(verdict.filesystem).toBeNull();+ // The number is in the detail so a report names what it did not know.+ expect(verdict.detail).toContain("0xbadf00d");+ });++ test("a platform with no filesystem-type facility is undetermined, NOT durable", () => {+ for (const platform of ["darwin", "win32", "freebsd"]) {+ const verdict = probeVaultBacking("/vault", {+ platform,+ statfs: withFsType(EXT4),+ });+ expect(`${platform}: ${verdict.state}`).toBe(`${platform}: ${VAULT_BACKING.undetermined}`);+ expect(verdict.reason).toBe(VAULT_BACKING_UNDETERMINED_REASON.probeUnsupported);+ }+ });++ test("a path the probe cannot stat is undetermined, NOT durable", () => {+ const verdict = probeVaultBacking("/vault", {+ platform: "linux",+ statfs: () => {+ throw new Error("ENOENT: no such file or directory");+ },+ });+ expect(verdict.state).toBe(VAULT_BACKING.undetermined);+ expect(verdict.reason).toBe(VAULT_BACKING_UNDETERMINED_REASON.pathUnreadable);+ expect(verdict.detail).toContain("ENOENT");+ });++ test("the real host answers something, and never contradicts itself", () => {+ const verdict = probeVaultBacking(resolve(dirname(fileURLToPath(import.meta.url))));+ expect(isVaultBackingState(verdict.state)).toBe(true);+ expect(verdict.state === VAULT_BACKING.undetermined).toBe(verdict.reason !== null);+ expect(verdict.detail.length).toBeGreaterThan(0);+ });+});++describe("the vocabulary is closed and carries the could-not-tell member", () => {+ test("`undetermined` is a member, and no member claims to name a host class", () => {+ expect(VAULT_BACKING_STATES).toContain(VAULT_BACKING.undetermined);+ // No `local`, no `cloud_sandbox`, no `ephemeral`: two of those three are+ // unprovable from any signal this host exposes, and the third is a+ // property of a machine rather than of the path being probed.+ for (const forbidden of ["local", "cloud_sandbox", "ephemeral", "container"]) {+ expect(`${forbidden} is a member: ${isVaultBackingState(forbidden)}`).toBe(+ `${forbidden} is a member: false`,+ );+ }+ });++ test("a reason is never readable back as a state", () => {+ for (const reason of VAULT_BACKING_UNDETERMINED_REASONS) {+ expect(`${reason} is a state: ${isVaultBackingState(reason)}`).toBe(+ `${reason} is a state: false`,+ );+ }+ for (const state of VAULT_BACKING_STATES) {+ expect(`${state} is a reason: ${isVaultBackingUndeterminedReason(state)}`).toBe(+ `${state} is a reason: false`,+ );+ }+ });+});++describe("no container signal reaches this verdict", () => {+ const SOURCE = readFileSync(+ join(dirname(fileURLToPath(import.meta.url)), "..", "..", "src", "core", "vault-backing.ts"),+ "utf8",+ );++ /**+ * Comments stripped: the module docblock NAMES every marker below in+ * order to explain why it reads none of them, and a scan that counted+ * the explanation as a use would force the reasoning out of the file.+ */+ const CODE = SOURCE.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");++ test("the module never reads a one-way container marker", () => {+ // Naming them, not counting them: every one of these is evidence of a+ // container when PRESENT and evidence of nothing when absent, so a+ // verdict that consulted one would answer `durable` for every modern+ // container that simply does not ship the marker.+ const markers = ["/.dockerenv", "/run/.containerenv", "/proc/1/cgroup", "/proc/1/sched"];+ const found = markers.filter((marker) => CODE.includes(marker));+ expect(found.join("\n")).toBe("");+ });++ test("the only host facility it reaches for is statfs", () => {+ const fsImports = [...CODE.matchAll(/import \{([^}]*)\} from "node:fs"/g)].map((m) =>+ m[1]!.trim(),+ );+ expect(fsImports.join("\n")).toBe("statfsSync");+ });++ test("the verdict is a function of the filesystem alone", () => {+ // Same magic number, two unrelated call sites: nothing about the host+ // can move the answer, which is what makes the absence of a container+ // marker unable to purchase a durability claim.+ const first = probeVaultBacking("/one", {+ platform: "linux",+ statfs: withFsType(UNRECOGNISED),+ });+ const second = probeVaultBacking("/two", {+ platform: "linux",+ statfs: withFsType(UNRECOGNISED),+ });+ expect(first.state).toBe(second.state);+ expect(first.reason).toBe(second.reason);+ });+});diff --git a/tests/discipline/render.test.ts b/tests/discipline/render.test.tsindex 830b3443..e33ea69d 100644--- a/tests/discipline/render.test.ts+++ b/tests/discipline/render.test.ts@@ -1,5 +1,6 @@import { describe, expect, test } from "bun:test";import { renderReport } from "../../src/core/discipline/render.ts";+import { TRANSCRIPT_SCAN } from "../../src/core/discipline/transcripts/types.ts";describe("renderReport", () => {test("status: ok with two agents, one repo, vault delta", () => {@@ -124,11 +125,20 @@ describe("renderReport", () => {{runtime: "claudecode",fileCount: 2,+ scan: TRANSCRIPT_SCAN.collected,+ unreadable: [],agentHint: "claude-vps-agent",},- { runtime: "codex", fileCount: 0, agentHint: "codex-vps-agent" },+ {+ runtime: "codex",+ fileCount: 0,+ scan: TRANSCRIPT_SCAN.rootAbsent,+ unreadable: [],+ agentHint: "codex-vps-agent",+ },],totalFiles: 2,+ unreadableRuntimes: [],},},});@@ -137,6 +147,57 @@ describe("renderReport", () => {expect(text).toContain("transcript\\-confirmed");});+ test("a runtime whose store could not be read is named, not silently zero", () => {+ const text = renderReport({+ localDate: "2026-05-17",+ timezone: "UTC",+ status: "alert",+ events: {+ byAgent: {+ "@a": { feedback: 0, apply_evidence: 0, note: 0, other: 0, total: 0 },+ },+ unknownAgents: [],+ total: 0,+ },+ activity: {+ repo: [+ {+ path: "/x",+ git: { commits: 3, filesChanged: 5, insertions: 10, deletions: 2 },+ },+ ],+ nonRepo: [],+ vaultDelta: { newSignals: 0, newPreferences: 0, newRetired: 0, total: 0 },+ transcripts: {+ byRuntime: [+ {+ runtime: "claudecode",+ fileCount: 0,+ scan: TRANSCRIPT_SCAN.unreadable,+ unreadable: ["/home/agent/.claude/projects"],+ agentHint: "claude-vps-agent",+ },+ {+ runtime: "codex",+ fileCount: 0,+ scan: TRANSCRIPT_SCAN.idle,+ unreadable: [],+ agentHint: "codex-vps-agent",+ },+ ],+ totalFiles: 0,+ unreadableRuntimes: ["claudecode"],+ },+ },+ });+ // The zero is still reported, but never on its own.+ expect(text).toContain("transcripts — claudecode: 0");+ expect(text).toContain(TRANSCRIPT_SCAN.unreadable);+ expect(text).toContain("transcript\\-unreadable");+ // The runtime that genuinely had a quiet day is not implicated.+ expect(text).not.toContain("codex: 0");+ });+test("status: alert + complexity warning adds productivity-trap sub-reason", () => {const text = renderReport({localDate: "2026-05-17",@@ -206,10 +267,13 @@ describe("renderReport", () => {{runtime: "claudecode",fileCount: 0,+ scan: TRANSCRIPT_SCAN.idle,+ unreadable: [],agentHint: "claude-vps-agent",},],totalFiles: 0,+ unreadableRuntimes: [],},},});diff --git a/tests/e2e/memory-observability.integration.test.ts b/tests/e2e/memory-observability.integration.test.tsindex 83a30142..f441481c 100644--- a/tests/e2e/memory-observability.integration.test.ts+++ b/tests/e2e/memory-observability.integration.test.ts@@ -116,11 +116,15 @@ test("telemetry -> schema-stamped records -> ATOF/ATIF export -> bench report",const benchReport = JSON.parse(bench.stdout) as {quality: { passed: number; total: number };latency_ms: { avg: number };- context_cost: { est_tokens: number };+ context_cost: { avg_injected_tokens: number };};expect(benchReport.quality.passed).toBe(benchReport.quality.total);expect(benchReport.latency_ms.avg).toBeGreaterThanOrEqual(0);- expect(benchReport.context_cost.est_tokens).toBeGreaterThan(0);+ // Renamed with the v2 report schema, and not only renamed: the old+ // field averaged over whatever estimator each caller reached for, and+ // five of them disagreed. This one is a single estimator over the+ // strings actually injected.+ expect(benchReport.context_cost.avg_injected_tokens).toBeGreaterThan(0);// The bench vault is disposable and separate from the operator vault.expect(existsSync(join(vault, "Brain", "notes", "coffee.md"))).toBe(false);}, 120_000);diff --git a/tests/fixtures/bench/failure-modes.baseline.json b/tests/fixtures/bench/failure-modes.baseline.jsonnew file mode 100644index 00000000..afa2fac1--- /dev/null+++ b/tests/fixtures/bench/failure-modes.baseline.json@@ -0,0 +1,80 @@+{+ "schema": "o2b.bench.v2",+ "fixture": "failure-modes",+ "fixture_hash": "3a542496e25537b2",+ "quality": {+ "passed": 7,+ "total": 7,+ "pass_rate": 1,+ "by_category": {+ "proactive_recall": {+ "passed": 4,+ "total": 4+ },+ "source_isolation": {+ "passed": 1,+ "total": 1+ },+ "write_fidelity": {+ "passed": 2,+ "total": 2+ }+ }+ },+ "context_cost": {+ "avg_chars": 152,+ "avg_injected_tokens": 38+ },+ "failure_modes": {+ "know_to_ask_failure_rate": 0,+ "false_fire_rate": 0,+ "source_isolation_violations": 0+ },+ "questions": [+ {+ "id": "q-fidelity-latin",+ "category": "write_fidelity",+ "pass": true+ },+ {+ "id": "q-fidelity-non-latin",+ "category": "write_fidelity",+ "pass": true+ },+ {+ "id": "q-isolation-owner-scope",+ "category": "source_isolation",+ "pass": true,+ "context_chars": 90,+ "injected_tokens": 23+ },+ {+ "id": "q-recall-hit-pool",+ "category": "proactive_recall",+ "pass": true,+ "context_chars": 338,+ "injected_tokens": 85+ },+ {+ "id": "q-recall-hit-staging",+ "category": "proactive_recall",+ "pass": true,+ "context_chars": 333,+ "injected_tokens": 84+ },+ {+ "id": "q-recall-quiet-offtopic",+ "category": "proactive_recall",+ "pass": true,+ "context_chars": 0,+ "injected_tokens": 0+ },+ {+ "id": "q-recall-quiet-unrelated",+ "category": "proactive_recall",+ "pass": true,+ "context_chars": 0,+ "injected_tokens": 0+ }+ ]+}diff --git a/tests/fixtures/bench/failure-modes.json b/tests/fixtures/bench/failure-modes.jsonnew file mode 100644index 00000000..fc324ab7--- /dev/null+++ b/tests/fixtures/bench/failure-modes.json@@ -0,0 +1,99 @@+{+ "name": "failure-modes",+ "description": "The four ways agent memory fails that retrieval questions do not measure (t_72d6eb23): proactive know-to-ask with a false-fire term, write-back fidelity through the shipped extraction path, cross-source isolation under a strict owner-scope gate, and the tokens actually injected. The vault sets integrity.owner_scope_delivery to fail because the shipped default is off, under which no scope is evaluated and an isolation gate would be vacuous.",+ "notes": [+ {+ "path": "Brain/_brain.yaml",+ "body": "schema_version: 1\nintegrity:\n owner_scope_delivery: fail\n"+ },+ {+ "path": "Brain/notes/pgbouncer.md",+ "body": "# Connection pooling\n\nThe pgbouncer pool cap is ninety connections in production.\n"+ },+ {+ "path": "Brain/notes/staging-gate.md",+ "body": "# Deploy runbook\n\nDeployment requires the staging gate to pass before the production smoke checklist runs.\n"+ },+ {+ "path": "Brain/preferences/pref-shared.md",+ "body": "---\nid: pref-shared\ntopic: indentation\nstatus: confirmed\nprinciple: Use tabs for indentation in Go files\ncreated_at: 2026-05-01T10:00:00\n---\n\nUse tabs for indentation in Go files.\n"+ },+ {+ "path": "Brain/preferences/pref-own.md",+ "body": "---\nid: pref-own\nowner: agent-a\ntopic: changelog\nstatus: confirmed\nprinciple: Write the changelog entry before pushing the branch\ncreated_at: 2026-05-02T10:00:00\n---\n\nWrite the changelog entry before pushing the branch.\n"+ },+ {+ "path": "Brain/preferences/pref-other.md",+ "body": "---\nid: pref-other\nowner: agent-b\ntopic: rollout\nstatus: confirmed\nprinciple: Roll out behind a flag and watch the error budget\ncreated_at: 2026-05-03T10:00:00\n---\n\nRoll out behind a flag and watch the error budget.\n"+ }+ ],+ "continuity": [],+ "questions": [+ {+ "id": "q-recall-hit-pool",+ "category": "proactive_recall",+ "prompt": "pgbouncer pool cap",+ "expect_inject": true+ },+ {+ "id": "q-recall-hit-staging",+ "category": "proactive_recall",+ "prompt": "staging gate",+ "expect_inject": true+ },+ {+ "id": "q-recall-quiet-unrelated",+ "category": "proactive_recall",+ "prompt": "book a dentist appointment for thursday",+ "expect_inject": false+ },+ {+ "id": "q-recall-quiet-offtopic",+ "category": "proactive_recall",+ "prompt": "quantum tunnelling in superconductors",+ "expect_inject": false+ },+ {+ "id": "q-fidelity-latin",+ "category": "write_fidelity",+ "intake_text": "Decision: Cap the pool at ninety connections.\nOpen question: Who owns the rollout?",+ "expected_labels": ["decision", "open_question"],+ "expected_provenance": [+ "id",+ "kind",+ "createdAt",+ "sourceRefs",+ "session_id",+ "turn_start",+ "turn_end",+ "turn_range",+ "content_hash",+ "dedupe_key"+ ]+ },+ {+ "id": "q-fidelity-non-latin",+ "category": "write_fidelity",+ "intake_text": "Решение: ограничить пул девяноста соединениями.\nОткрытый вопрос: кто отвечает за выкатку?",+ "expected_labels": ["решение", "открытый_вопрос"],+ "expected_provenance": [+ "id",+ "kind",+ "createdAt",+ "sourceRefs",+ "session_id",+ "turn_range",+ "content_hash",+ "dedupe_key"+ ]+ },+ {+ "id": "q-isolation-owner-scope",+ "category": "source_isolation",+ "agent_scope": "agent-a",+ "expected_ids": ["pref-shared", "pref-own"],+ "forbidden_ids": ["pref-other"],+ "max_tokens": 500+ }+ ]+}diff --git a/tests/helpers/cli-timeout.ts b/tests/helpers/cli-timeout.tsnew file mode 100644index 00000000..665f4a84--- /dev/null+++ b/tests/helpers/cli-timeout.ts@@ -0,0 +1,41 @@+/**+ * The per-test budget for a test FILE whose tests drive the real `o2b`+ * command line, applied with `setDefaultTimeout(CLI_SPAWN_BUDGET_MS)` at the+ * top of that file.+ *+ * bun's default is 5 s per test. That is a budget for a unit test, not for a+ * test that boots the CLI: a single `o2b doctor` costs several seconds on a+ * loaded machine, and none of that cost belongs to the assertion - it is+ * process start, the import graph, and the external probes the command runs.+ * Tests that pay it passed only when the machine happened to be idle, so the+ * suite's verdict was a function of what else the machine was doing. That is+ * the same defect 1.45.1 fixed for a leaked config env and 1.47.0 fixed for a+ * pair of readiness tests that spawned twice; the predicate is simply wider+ * than "spawns twice".+ *+ * The number is one budget rather than a per-test guess. It is measured, not+ * chosen: one `o2b doctor` costs ~4.5 s on an idle 4-core box and up to ~27 s+ * on the same box at load average 20, and some tests here invoke the CLI+ * twice to compare an opt-out run against an opt-in one. Two worst-case+ * invocations is the budget. It is still finite, so a test that genuinely+ * hangs fails in a minute instead of never, and it matches the 60 s that the+ * bench and race tests in this suite already carry as their own annotation.+ *+ * It is applied per file rather than project-wide because bun offers no+ * working project-wide knob, which was established by experiment on bun+ * 1.3.14 rather than assumed:+ *+ * - bunfig.toml's `[test] timeout`, which bun's own bundled docs describe,+ * is parsed and ignored: a 3 s test still passes under `timeout = 1500`+ * while a `preload` in the same file demonstrably runs.+ * - `setDefaultTimeout()` from that preload applies only to the first test+ * file bun happens to execute, and bun's file order is not alphabetical -+ * so it silently leaves every other file on the 5 s default.+ * - `bun test --timeout` works, but CI runs bare `bun test`+ * (.github/workflows/ci.yml, "TypeScript test suite"), as does anyone+ * running one file, so a flag on a wrapper script would not reach them.+ *+ * Calling it in the test file itself is the one form that behaves the same+ * under `bun test`, `bun test <file>`, and `bun run test`.+ */+export const CLI_SPAWN_BUDGET_MS = 60_000;diff --git a/tests/helpers/progress-records.ts b/tests/helpers/progress-records.tsnew file mode 100644index 00000000..b5e14f4d--- /dev/null+++ b/tests/helpers/progress-records.ts@@ -0,0 +1,44 @@+/**+ * Read the progress stream a CLI run wrote to stderr.+ *+ * Progress shares stderr with warnings, advisory lines and the indexer's+ * `--verbose` per-file stream, so a reader selects by the envelope's own+ * schema discriminator rather than by position or by line count. That+ * discriminator is exactly why `renderProgressLine` writes `schema` on+ * every record, and reading the stream any other way here would let a+ * verb pass by emitting something that merely looks like progress.+ */++import { PROGRESS_SCHEMA } from "../../src/core/brain/progress.ts";++/**+ * A stage is an identifier from the emitting operation's own phase+ * vocabulary, never a sentence: the human line is rendered from it at the+ * edge. The census enforces this over the emission sites in `src/`; this+ * copy enforces it over what actually reached the terminal.+ */+export const STAGE_IDENTIFIER = /^[a-z0-9]+([-_][a-z0-9]+)*$/;++/** Every progress record on a stderr stream, in order. */+export function progressRecords(stderr: string): ReadonlyArray<Record<string, unknown>> {+ const out: Record<string, unknown>[] = [];+ for (const line of stderr.split("\n")) {+ if (!line.startsWith("{")) continue;+ let parsed: unknown;+ try {+ parsed = JSON.parse(line);+ } catch {+ // Another writer's brace-leading line, not a progress record. A+ // throw here would blame this reader for someone else's stderr.+ continue;+ }+ if (+ typeof parsed === "object" &&+ parsed !== null &&+ (parsed as { schema?: unknown }).schema === PROGRESS_SCHEMA+ ) {+ out.push(parsed as Record<string, unknown>);+ }+ }+ return out;+}diff --git a/tests/helpers/run-cli.ts b/tests/helpers/run-cli.tsindex 486ac22d..2ee56143 100644--- a/tests/helpers/run-cli.ts+++ b/tests/helpers/run-cli.ts@@ -13,6 +13,7 @@ import { join, dirname, resolve } from "node:path";import { fileURLToPath } from "node:url";import { main } from "../../src/cli/main.ts";+import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";export interface RunResult {readonly stdout: string;@@ -43,6 +44,16 @@ const RUNTIME_OVERRIDABLE_ENV = ["OPEN_SECOND_BRAIN_RECALL_GATE_TELEMETRY","OPEN_SECOND_BRAIN_BENCH_JUDGE_CMD","OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT",+ // Search-lane selection. `resolveSearchConfig` reads these straight off+ // `process.env`, so a developer with semantic search configured ran a+ // DIFFERENT pipeline than CI - against a remote embedding provider -+ // and every "deterministic and network-free" claim in the tree was a+ // property of an unset shell rather than of the code.+ "OPEN_SECOND_BRAIN_SEARCH_SEMANTIC",+ "OPEN_SECOND_BRAIN_EMBEDDING_PROVIDER",+ // The codegraph partner switch, for the same reason and with a default+ // of its own below.+ PARTNER_CODEGRAPH_DISABLED_ENV,] as const;export interface RunCliOptions {@@ -73,6 +84,17 @@ function resolveEnv(callerEnv: Record<string, string>): {if (!(key in callerEnv)) delete env[key];}Object.assign(env, callerEnv);+ // `o2b doctor` consults the codegraph partner by spawning a third-party+ // CLI once per discovered project whenever that binary is on PATH. The+ // suite runs from this repo, which IS such a project, so the check ran+ // for real on any developer machine with codegraph installed and did not+ // run at all on CI, where the binary is absent - the suite's cost and its+ // dependency on a foreign tool were both properties of the machine. On+ // this workstation that was 96.0 s for `tests/cli/cli.test.ts` against+ // 1.1 s with the partner left alone. Tests keep the switch ON by default+ // and the partner check has its own coverage that calls `doctor()`+ // directly; a caller that wants the real consultation passes the key.+ if (!(PARTNER_CODEGRAPH_DISABLED_ENV in env)) env[PARTNER_CODEGRAPH_DISABLED_ENV] = "true";let cleanupDir: string | null = null;if (!("OPEN_SECOND_BRAIN_CONFIG" in env)) {cleanupDir = mkdtempSync(join(tmpdir(), "o2b-test-"));diff --git a/tests/hooks/process-ceiling.test.ts b/tests/hooks/process-ceiling.test.tsindex 16548325..2ed18ffa 100644--- a/tests/hooks/process-ceiling.test.ts+++ b/tests/hooks/process-ceiling.test.ts@@ -1,7 +1,12 @@-import { expect, test } from "bun:test";+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";import {DEFAULT_HOOK_CEILING_MS,+ HOOK_CEILING_HEADROOM_MS,+ HOOK_HOST_TIMEOUT_SECONDS,armProcessCeiling,resolveHookCeilingMs,} from "../../hooks/lib/process-ceiling.ts";@@ -91,3 +96,45 @@ test("resolveHookCeilingMs: default, override, and invalid fallback", () => {DEFAULT_HOOK_CEILING_MS,);});++/**+ * The watchdog and the host timeout are one design, and the thing worth+ * pinning is the RELATION between them, not either number. Asserting the+ * two constants separately would let someone raise the ceiling past the+ * host timeout and still see green - which is the exact state this suite+ * was written to end, where a 55 s self-ceiling sat behind a 10 s host+ * timeout and could never once have fired.+ */+describe("the self-ceiling and the declared host timeout", () => {+ const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");+ const declaredTimeouts = (): number[] => {+ const parsed = JSON.parse(readFileSync(join(REPO, "hooks", "hooks.json"), "utf8")) as {+ hooks: Record<string, Array<{ hooks: Array<{ timeout?: number }> }>>;+ };+ const out: number[] = [];+ for (const groups of Object.values(parsed.hooks)) {+ for (const group of groups) {+ for (const entry of group.hooks) {+ if (entry.timeout !== undefined) out.push(entry.timeout);+ }+ }+ }+ return out;+ };++ test("every hooks.json entry declares the timeout the module is built against", () => {+ const timeouts = declaredTimeouts();+ expect(timeouts.length).toBeGreaterThan(0);+ expect([...new Set(timeouts)]).toEqual([HOOK_HOST_TIMEOUT_SECONDS]);+ });++ test("the self-ceiling fires first, by the stated headroom", () => {+ const hostMs = HOOK_HOST_TIMEOUT_SECONDS * 1000;+ expect(HOOK_CEILING_HEADROOM_MS).toBeGreaterThan(0);+ expect(DEFAULT_HOOK_CEILING_MS).toBe(hostMs - HOOK_CEILING_HEADROOM_MS);+ expect(DEFAULT_HOOK_CEILING_MS).toBeLessThan(hostMs);+ // And it is still a ceiling worth arming rather than a value the+ // floor would swallow.+ expect(resolveHookCeilingMs({})).toBe(DEFAULT_HOOK_CEILING_MS);+ });+});diff --git a/tests/mcp/config-read-failure-server.test.ts b/tests/mcp/config-read-failure-server.test.tsindex 5b998f88..0a540faf 100644--- a/tests/mcp/config-read-failure-server.test.ts+++ b/tests/mcp/config-read-failure-server.test.ts@@ -27,6 +27,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";const VALID_CONFIG = `vault: "/srv/example-vault"\nagent_name: "vps-agent"\n`;@@ -51,6 +52,13 @@ beforeEach(() => {savedEnv[k] = process.env[k];delete process.env[k];}+ // `vault_health` runs the full doctor, which consults the codegraph+ // partner whenever that binary is on PATH. The partner's cache lives+ // under HOME and this suite mandates a clean one, so each consultation+ // costs seconds. Nothing here asserts anything about the partner, so+ // the cost is removed rather than the ceiling raised.+ savedEnv[PARTNER_CODEGRAPH_DISABLED_ENV] = process.env[PARTNER_CODEGRAPH_DISABLED_ENV];+ process.env[PARTNER_CODEGRAPH_DISABLED_ENV] = "true";});afterEach(() => {diff --git a/tests/mcp/config-read-failure-tools.test.ts b/tests/mcp/config-read-failure-tools.test.tsindex cf21e040..3fd2f5a6 100644--- a/tests/mcp/config-read-failure-tools.test.ts+++ b/tests/mcp/config-read-failure-tools.test.ts@@ -26,6 +26,7 @@ import { join } from "node:path";import { buildToolTable, findTool } from "../../src/mcp/tools.ts";import type { ServerContext } from "../../src/mcp/tool-contract.ts";+import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";const VALID_CONFIG = `vault: "/srv/example-vault"\napi_key: "secret"\n`;@@ -48,6 +49,15 @@ beforeEach(() => {savedEnv[k] = process.env[k];delete process.env[k];}+ // `vault_health` runs the full doctor, which consults the codegraph+ // partner whenever that binary is on PATH. The partner's cache lives+ // under HOME and this suite mandates a clean one, so each consultation+ // costs seconds: these tests failed on bun's default budget on any+ // workstation with codegraph installed and passed on CI, where the+ // binary is absent. Nothing here asserts anything about the partner, so+ // the cost is removed rather than the ceiling raised.+ savedEnv[PARTNER_CODEGRAPH_DISABLED_ENV] = process.env[PARTNER_CODEGRAPH_DISABLED_ENV];+ process.env[PARTNER_CODEGRAPH_DISABLED_ENV] = "true";});afterEach(() => {diff --git a/tests/mcp/long-running-tools.test.ts b/tests/mcp/long-running-tools.test.tsnew file mode 100644index 00000000..7287040b--- /dev/null+++ b/tests/mcp/long-running-tools.test.ts@@ -0,0 +1,415 @@+/**+ * The MCP tools that can genuinely run for minutes are both bounded and+ * observable (nothing-runs-unwatched, U2).+ *+ * One theme, because a deadline and a progress tick sit at the same+ * boundary: a run worth guarding is a run worth reporting on, and the+ * safeguard checkpoints are where the spine emits.+ *+ * `brain_bridges` and `brain_clusters` call the same two core functions+ * the maintenance lane calls, and both accept a `Safeguard` there -+ * `admin-tools.ts` passes one per task, resolving the budget through+ * `resolveSafeguardTimeoutMs`. The two standalone MCP tools passed+ * nothing at all, so a graph sweep an agent started over MCP had no upper+ * bound on how long it could hold the server. They now resolve the budget+ * the same way the lane does.+ *+ * `brain_dream` was the fourth tool `docs/mcp.md` said was bounded and+ * the one that was not: the commit that added the deadlines and wrote+ * that sentence never touched `feedback-tools.ts`, and this file asserted+ * the deadline for two of the four it names. All four are asserted here+ * now, in both halves - bounded and observed - because the gap survived+ * exactly as long as the test covered half the population the prose did.+ * The lane is the one that does not abort the call: it converts a tripped+ * deadline into a `timed_out` row per task, which is where its deadline+ * is visible.+ *+ * The deadline is exercised through a clock that jumps past any budget on+ * its second reading, which is what `createSafeguard` compares against:+ * the alternative - waiting out a real budget - is measured in the+ * minutes the built-in default allows.+ */++import { afterEach, beforeEach, expect, spyOn, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { indexVault } from "../../src/core/search/indexer.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { makeConfig } from "../helpers/search-fixtures.ts";+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";+import { PROGRESS_META_KEY, PROGRESS_NOTIFICATION_METHOD } from "../../src/mcp/progress.ts";+import type { JsonRpcNotification } from "../../src/mcp/protocol.ts";+import { PROGRESS_SCHEMA } from "../../src/core/brain/progress.ts";++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-guard-"));+ vault = join(tmp, "vault");+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-guard-cfg-"));+ configPath = join(configHome, "config.yaml");+ for (const key of [+ "VAULT_AGENT_NAME",+ "VAULT_TIMEZONE",+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ "OPEN_SECOND_BRAIN_SAFEGUARD_TIMEOUT",+ ]) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ for (const [key, value] of Object.entries(savedEnv)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+});++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: { protocolVersion: PROTOCOL_VERSION },+ });+}++/** The tool-level envelope, whose `isError` carries a thrown core error. */+async function callRaw(+ server: MCPServer,+ tool: string,+ args: Record<string, unknown>,+): Promise<{ isError?: boolean; content?: Array<{ text?: string }> }> {+ const res = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/call",+ params: { name: tool, arguments: args },+ })) as { result?: { isError?: boolean; content?: Array<{ text?: string }> } };+ return res.result!;+}++function writeLinkedGroup(): void {+ const group = ["team-a", "team-b", "team-c", "team-d"];+ for (const name of group) {+ const others = group+ .filter((g) => g !== name)+ .map((g) => `[[${g}]]`)+ .join(" ");+ writeFileSync(join(vault, `${name}.md`), `# ${name}\n\nSee ${others}.\n`);+ }+}++/**+ * A clock whose every reading is a full day past the previous one, so any+ * budget `resolveSafeguardTimeoutMs` returns has elapsed by the first+ * checkpoint. `createSafeguard` reads `Date.now` when no clock is+ * injected, which is exactly the path an MCP tool takes.+ */+function jumpingClock(): () => void {+ let tick = 0;+ const spy = spyOn(Date, "now").mockImplementation(() => {+ tick += 1;+ return tick * 86_400_000;+ });+ return () => spy.mockRestore();+}++test("brain_bridges discover aborts once its deadline has passed", async () => {+ writeLinkedGroup();+ await indexVault(+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),+ );+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const restore = jumpingClock();+ try {+ const result = await callRaw(server, "brain_bridges", { operation: "discover" });+ expect(result.isError).toBe(true);+ expect(result.content![0]!.text).toContain("safeguard timeout");+ expect(result.content![0]!.text).toContain("bridges");+ } finally {+ restore();+ }+});++test("brain_clusters run aborts once its deadline has passed", async () => {+ writeLinkedGroup();+ await indexVault(+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),+ );+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const restore = jumpingClock();+ try {+ const result = await callRaw(server, "brain_clusters", { operation: "run" });+ expect(result.isError).toBe(true);+ expect(result.content![0]!.text).toContain("safeguard timeout");+ expect(result.content![0]!.text).toContain("clusters");+ } finally {+ restore();+ }+});++test("brain_dream run aborts once its deadline has passed", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const restore = jumpingClock();+ try {+ const result = await callRaw(server, "brain_dream", { action: "run", dry_run: true });+ expect(result.isError).toBe(true);+ expect(result.content![0]!.text).toContain("safeguard timeout");+ expect(result.content![0]!.text).toContain("dream");+ } finally {+ restore();+ }+});++test("brain_dream stage aborts once its deadline has passed", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const restore = jumpingClock();+ try {+ const result = await callRaw(server, "brain_dream", { action: "stage" });+ expect(result.isError).toBe(true);+ expect(result.content![0]!.text).toContain("safeguard timeout");+ expect(result.content![0]!.text).toContain("dream");+ } finally {+ restore();+ }+});++test("brain_maintenance names the task whose deadline tripped", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const restore = jumpingClock();+ let payload: { tasks: Array<{ name: string; ok: boolean; timed_out?: boolean }> };+ try {+ const res = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 4,+ method: "tools/call",+ params: { name: "brain_maintenance", arguments: { operation: "run", force: true } },+ })) as { result?: { isError?: boolean; structuredContent?: unknown } };+ expect(res.result!.isError).toBe(false);+ payload = res.result!.structuredContent as typeof payload;+ } finally {+ restore();+ }+ // The lane converts a tripped deadline into a per-task row rather than+ // an aborted tool call, so the deadline is visible as `timed_out`.+ const dreamTask = payload.tasks.find((t) => t.name === "dream");+ expect(dreamTask).toBeDefined();+ expect(dreamTask!.timed_out).toBe(true);+});++test("brain_review_candidates aborts once its deadline has passed", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const restore = jumpingClock();+ try {+ const result = await callRaw(server, "brain_review_candidates", {});+ expect(result.isError).toBe(true);+ expect(result.content![0]!.text).toContain("safeguard timeout");+ expect(result.content![0]!.text).toContain("dream");+ } finally {+ restore();+ }+});++test("brain_brief view=operator names the deadline its dream pass tripped", async () => {+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const restore = jumpingClock();+ let payload: { dream_error?: string };+ try {+ const res = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 5,+ method: "tools/call",+ params: { name: "brain_brief", arguments: { view: "operator" } },+ })) as { result?: { isError?: boolean; structuredContent?: unknown } };+ // The brief reports the missing half rather than failing the whole+ // dashboard, so the deadline is visible as `dream_error`, not isError.+ expect(res.result!.isError).toBe(false);+ payload = res.result!.structuredContent as typeof payload;+ } finally {+ restore();+ }+ expect(payload.dream_error).toContain("safeguard timeout");+});++test("a live clock leaves all four tools running to completion", async () => {+ writeLinkedGroup();+ await indexVault(+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),+ );+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const bridges = await callRaw(server, "brain_bridges", { operation: "discover" });+ expect(bridges.isError).toBe(false);+ const clusters = await callRaw(server, "brain_clusters", { operation: "run" });+ expect(clusters.isError).toBe(false);+ const dreamed = await callRaw(server, "brain_dream", { action: "run", dry_run: true });+ expect(dreamed.isError).toBe(false);+ const lane = await callRaw(server, "brain_maintenance", { operation: "run", force: true });+ expect(lane.isError).toBe(false);+});++// ---------------------------------------------------------------------------+// The same four tools, observed+// ---------------------------------------------------------------------------++/** The operations named by the progress events a call emitted. */+function operationsIn(frames: JsonRpcNotification[]): Set<string> {+ const seen = new Set<string>();+ for (const frame of frames) {+ if (frame.method !== PROGRESS_NOTIFICATION_METHOD) continue;+ const params = frame.params as Record<+ string,+ Record<string, { operation: string; schema: string }>+ >;+ const event = params["_meta"]![PROGRESS_META_KEY]!;+ expect(event.schema).toBe(PROGRESS_SCHEMA);+ seen.add(event.operation);+ }+ return seen;+}++/** A server whose notification frames this test can read back. */+function observedServer(frames: JsonRpcNotification[]): MCPServer {+ return new MCPServer(+ { vault, configPath },+ { sendNotification: (notification) => frames.push(notification) },+ );+}++async function callWithToken(+ server: MCPServer,+ tool: string,+ args: Record<string, unknown>,+): Promise<{ isError?: boolean }> {+ const res = (await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 3,+ method: "tools/call",+ params: { name: tool, arguments: args, _meta: { progressToken: `t-${tool}` } },+ })) as { result?: { isError?: boolean } };+ return res.result!;+}++test("brain_bridges reports its scan under a progress token", async () => {+ writeLinkedGroup();+ await indexVault(+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),+ );+ const frames: JsonRpcNotification[] = [];+ const server = observedServer(frames);+ await initialize(server);++ expect((await callWithToken(server, "brain_bridges", { operation: "discover" })).isError).toBe(+ false,+ );+ expect(operationsIn(frames)).toEqual(new Set(["bridges"]));+});++test("brain_clusters reports its sweeps under a progress token", async () => {+ writeLinkedGroup();+ await indexVault(+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),+ );+ const frames: JsonRpcNotification[] = [];+ const server = observedServer(frames);+ await initialize(server);++ expect((await callWithToken(server, "brain_clusters", { operation: "run" })).isError).toBe(false);+ expect(operationsIn(frames)).toEqual(new Set(["clusters"]));+});++test("brain_dream reports its consolidation pass under a progress token", async () => {+ const frames: JsonRpcNotification[] = [];+ const server = observedServer(frames);+ await initialize(server);++ expect(+ (await callWithToken(server, "brain_dream", { action: "run", dry_run: true })).isError,+ ).toBe(false);+ expect(operationsIn(frames)).toEqual(new Set(["dream"]));+});++test("brain_dream stage reports the pass it runs under a progress token", async () => {+ const frames: JsonRpcNotification[] = [];+ const server = observedServer(frames);+ await initialize(server);++ expect((await callWithToken(server, "brain_dream", { action: "stage" })).isError).toBe(false);+ expect(operationsIn(frames)).toEqual(new Set(["dream"]));+});++test("brain_review_candidates reports the pass behind its projection", async () => {+ const frames: JsonRpcNotification[] = [];+ const server = observedServer(frames);+ await initialize(server);++ expect((await callWithToken(server, "brain_review_candidates", {})).isError).toBe(false);+ expect(operationsIn(frames)).toEqual(new Set(["dream"]));+});++test("brain_brief view=operator reports its dry-run pass", async () => {+ const frames: JsonRpcNotification[] = [];+ const server = observedServer(frames);+ await initialize(server);++ expect((await callWithToken(server, "brain_brief", { view: "operator" })).isError).toBe(false);+ expect(operationsIn(frames)).toEqual(new Set(["dream"]));+});++test("brain_maintenance forwards the sink to every task it dispatches", async () => {+ writeLinkedGroup();+ const frames: JsonRpcNotification[] = [];+ const server = observedServer(frames);+ await initialize(server);++ expect(+ (await callWithToken(server, "brain_maintenance", { operation: "run", force: true })).isError,+ ).toBe(false);+ // The lane is a dispatcher, so it speaks with its tasks' voices: each+ // event names the operation that emitted it, never the lane.+ expect(operationsIn(frames)).toEqual(new Set(["dream", "reindex", "bridges", "clusters"]));+});++test("no token leaves every one of them silent", async () => {+ writeLinkedGroup();+ await indexVault(+ makeConfig({ vault, dbPath: join(vault, ".open-second-brain", "brain.sqlite") }),+ );+ const frames: JsonRpcNotification[] = [];+ const server = observedServer(frames);+ await initialize(server);++ await callRaw(server, "brain_bridges", { operation: "discover" });+ await callRaw(server, "brain_clusters", { operation: "run" });+ expect(frames).toEqual([]);+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 1c68fa1f..7ef24128 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -14,6 +14,7 @@ import {} from "../../src/mcp/index.ts";import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";+import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";let tmp: string;const savedEnv: Record<string, string | undefined> = {};@@ -24,6 +25,15 @@ beforeEach(() => {savedEnv[k] = process.env[k];delete process.env[k];}+ // `vault_health` runs the full doctor, which consults the codegraph+ // partner whenever that binary is on PATH. The partner's cache lives+ // under HOME and this suite mandates a clean one, so each consultation+ // costs seconds: these tests failed on bun's default budget on any+ // workstation with codegraph installed and passed on CI, where the+ // binary is absent. Nothing here asserts anything about the partner, so+ // the cost is removed rather than the ceiling raised.+ savedEnv[PARTNER_CODEGRAPH_DISABLED_ENV] = process.env[PARTNER_CODEGRAPH_DISABLED_ENV];+ process.env[PARTNER_CODEGRAPH_DISABLED_ENV] = "true";});afterEach(() => {diff --git a/tests/mcp/progress-token.test.ts b/tests/mcp/progress-token.test.tsnew file mode 100644index 00000000..9421dd77--- /dev/null+++ b/tests/mcp/progress-token.test.ts@@ -0,0 +1,356 @@+/**+ * `_meta.progressToken` at the MCP boundary (nothing-runs-unwatched, U2).+ *+ * Before this unit `handleToolsCall` read exactly two keys from `params`+ * - `name` and `arguments` - so a client's progress token was accepted by+ * the wire and then discarded without a word. These tests pin the four+ * facts that replace that silence:+ *+ * - stdio, which can write an unsolicited frame, carries the token as+ * `notifications/progress` frames emitted BEFORE the response frame;+ * - HTTP, which writes one response and closes, refuses the token by+ * name rather than accepting it and dropping the events;+ * - a call with no token is byte-identical to the call the previous+ * release made, which is what makes the feature additive;+ * - a tool that dispatches on a `view` argument hands the sink to the+ * view it dispatched to, rather than dropping it one link short of+ * the pass that had something to report.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { PassThrough } from "node:stream";++import {+ JSONRPC_VERSION,+ MCPServer,+ PROTOCOL_VERSION,+ serveStdio,+ serveStdioFromString,+ startHttp,+} from "../../src/mcp/index.ts";+import { PROGRESS_META_KEY, PROGRESS_NOTIFICATION_METHOD } from "../../src/mcp/progress.ts";+import {+ isProgressKind,+ PROGRESS_KIND,+ PROGRESS_REASON,+ PROGRESS_SCHEMA,+} from "../../src/core/brain/progress.ts";+import { bootstrapBrain } from "../../src/core/brain/init.ts";++interface JsonObject {+ readonly [key: string]: any;+}++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-mcp-progress-"));+ bootstrapBrain(vault);+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++const INITIALIZE = {+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: { protocolVersion: PROTOCOL_VERSION },+};++/** A `tools/call` for the one tool wired to the progress spine today. */+function dreamCall(id: number, token?: string | number): JsonObject {+ return {+ jsonrpc: JSONRPC_VERSION,+ id,+ method: "tools/call",+ params: {+ name: "brain_dream",+ arguments: { dry_run: true },+ ...(token === undefined ? {} : { _meta: { progressToken: token } }),+ },+ };+}++/**+ * One response frame with the only member a rerun cannot reproduce+ * NORMALISED rather than removed.+ *+ * `run_id` is derived from the wall clock, and it appears twice: once in+ * `structuredContent` and again inside `content`, which is that same+ * payload rendered. So the id is replaced wherever it occurs and every+ * other byte of both members is still compared.+ *+ * The earlier form deleted `content` outright, and deleting it excused+ * the entire rendered payload an MCP client displays: an independent+ * review replaced that array wholesale whenever a progress token was+ * present and this file stayed green. A frame with no run id to+ * normalise is a defect in the response, not a frame to compare loosely,+ * so it throws.+ */+function normalizeRunId(frame: JsonObject | undefined): string {+ const runId = (frame?.["result"] as JsonObject | undefined)?.["structuredContent"]?.["run_id"];+ if (typeof runId !== "string" || runId.length === 0) {+ throw new TypeError(`response frame carries no run_id to normalise: ${JSON.stringify(frame)}`);+ }+ return JSON.stringify(frame).split(runId).join("<run-id>");+}++function lines(out: string): JsonObject[] {+ return out+ .split("\n")+ .filter((l) => l.trim() !== "")+ .map((l) => JSON.parse(l) as JsonObject);+}++describe("stdio carries a progress token", () => {+ test("a valid token yields progress frames before the response frame", async () => {+ const input = JSON.stringify(INITIALIZE) + "\n" + JSON.stringify(dreamCall(2, "tok-42")) + "\n";+ const frames = lines(await serveStdioFromString({ vault }, input));++ const responseIndex = frames.findIndex((f) => f["id"] === 2);+ expect(responseIndex).toBeGreaterThan(-1);+ const notifications = frames.filter((f) => f["method"] === PROGRESS_NOTIFICATION_METHOD);+ expect(notifications.length).toBeGreaterThan(0);++ // Every notification precedes the response it belongs to.+ for (const n of notifications) expect(frames.indexOf(n)).toBeLessThan(responseIndex);++ const first = notifications[0]!;+ expect(first["jsonrpc"]).toBe(JSONRPC_VERSION);+ expect(first["id"]).toBeUndefined();+ const params = first["params"] as JsonObject;+ expect(params["progressToken"]).toBe("tok-42");+ expect(typeof params["progress"]).toBe("number");+ const event = (params["_meta"] as JsonObject)[PROGRESS_META_KEY] as JsonObject;+ expect(event["schema"]).toBe(PROGRESS_SCHEMA);+ expect(event["operation"]).toBe("dream");+ expect(event["kind"]).toBe(PROGRESS_KIND.started);+ expect(typeof event["stage"]).toBe("string");+ });++ test("an integer token is accepted and echoed back unchanged", async () => {+ const input = JSON.stringify(INITIALIZE) + "\n" + JSON.stringify(dreamCall(2, 7)) + "\n";+ const frames = lines(await serveStdioFromString({ vault }, input));+ const notifications = frames.filter((f) => f["method"] === PROGRESS_NOTIFICATION_METHOD);+ expect(notifications.length).toBeGreaterThan(0);+ expect((notifications[0]!["params"] as JsonObject)["progressToken"]).toBe(7);+ });++ test("the response frame is identical with and without a token", async () => {+ const withToken = lines(+ await serveStdioFromString(+ { vault },+ JSON.stringify(INITIALIZE) + "\n" + JSON.stringify(dreamCall(2, "tok")) + "\n",+ ),+ ).find((f) => f["id"] === 2);+ const without = lines(+ await serveStdioFromString(+ { vault },+ JSON.stringify(INITIALIZE) + "\n" + JSON.stringify(dreamCall(2)) + "\n",+ ),+ ).find((f) => f["id"] === 2);++ // The rendered payload is what a client displays, so the comparison+ // is worthless if both frames happen to carry nothing there.+ const content = (withToken?.["result"] as JsonObject | undefined)?.["content"] as+ | ReadonlyArray<JsonObject>+ | undefined;+ expect(content?.length).toBeGreaterThan(0);+ expect(normalizeRunId(withToken)).toBe(normalizeRunId(without));+ });++ test("no token produces no notification frames at all", async () => {+ const frames = lines(+ await serveStdioFromString(+ { vault },+ JSON.stringify(INITIALIZE) + "\n" + JSON.stringify(dreamCall(2)) + "\n",+ ),+ );+ expect(frames.filter((f) => f["method"] !== undefined)).toEqual([]);+ expect(frames.every((f) => f["id"] !== undefined)).toBe(true);+ });++ test("a progress frame never interleaves inside a response frame on a real stream", async () => {+ const stdin = new PassThrough();+ const chunks: string[] = [];+ const stdout = new PassThrough();+ stdout.on("data", (c: Buffer) => chunks.push(c.toString("utf8")));++ const done = serveStdio({ vault }, { stdin, stdout });+ stdin.write(JSON.stringify(INITIALIZE) + "\n");+ stdin.write(JSON.stringify(dreamCall(2, "tok")) + "\n");+ stdin.end();+ await done;++ // Every write is exactly one newline-terminated frame: joining the+ // chunks and splitting on "\n" must parse cleanly, and the last+ // progress frame must precede the response.+ const frames = lines(chunks.join(""));+ const responseIndex = frames.findIndex((f) => f["id"] === 2);+ const progressIndexes = frames+ .map((f, i) => (f["method"] === PROGRESS_NOTIFICATION_METHOD ? i : -1))+ .filter((i) => i !== -1);+ expect(progressIndexes.length).toBeGreaterThan(0);+ expect(Math.max(...progressIndexes)).toBeLessThan(responseIndex);+ for (const chunk of chunks) expect(chunk.endsWith("\n")).toBe(true);+ });+});++/**+ * The view dispatcher, from the outside.+ *+ * `dispatchByView` routes a consolidated tool's `view` argument to its+ * per-view handler, and it used to call `handler(ctx, args)` - dropping+ * the sink on the floor. Restoring that one-line defect left the whole+ * of `tests/mcp` plus the progress suites at 882 pass / 0 fail, because+ * no test sent a progress token through a dispatched tool. This block+ * is that test: `brain_brief view=operator` is the consumer that made+ * the fix necessary, since it runs a dry-run consolidation pass and is+ * the slow half of an operator summary on a large vault.+ */+describe("a dispatched view carries the sink", () => {+ function briefCall(id: number, token?: string): JsonObject {+ return {+ jsonrpc: JSONRPC_VERSION,+ id,+ method: "tools/call",+ params: {+ name: "brain_brief",+ arguments: { view: "operator" },+ ...(token === undefined ? {} : { _meta: { progressToken: token } }),+ },+ };+ }++ test("brain_brief view=operator emits progress frames for its dream pass", async () => {+ const frames = lines(+ await serveStdioFromString(+ { vault },+ JSON.stringify(INITIALIZE) + "\n" + JSON.stringify(briefCall(2, "tok-brief")) + "\n",+ ),+ );+ const responseIndex = frames.findIndex((f) => f["id"] === 2);+ expect(responseIndex).toBeGreaterThan(-1);+ expect(frames[responseIndex]?.["error"]).toBeUndefined();++ const notifications = frames.filter((f) => f["method"] === PROGRESS_NOTIFICATION_METHOD);+ // The assertion the dropped sink fails: a dispatcher that swallows it+ // produces a response and no frames at all, which is exactly what a+ // hung run looks like.+ expect(notifications.length).toBeGreaterThan(0);+ for (const n of notifications) expect(frames.indexOf(n)).toBeLessThan(responseIndex);++ const params = notifications[0]!["params"] as JsonObject;+ expect(params["progressToken"]).toBe("tok-brief");+ const event = (params["_meta"] as JsonObject)[PROGRESS_META_KEY] as JsonObject;+ expect(event["schema"]).toBe(PROGRESS_SCHEMA);+ // The operation naming the pass the sink reached, not merely "some+ // frames arrived": the dispatcher's job is to hand the sink to the+ // handler that runs the long half.+ expect(event["operation"]).toBe("dream");+ expect(isProgressKind(event["kind"])).toBe(true);+ });++ test("the same view with no token emits nothing", async () => {+ // The negative control for the test above: the frames it counts are+ // caused by the token, not by the tool being noisy.+ const frames = lines(+ await serveStdioFromString(+ { vault },+ JSON.stringify(INITIALIZE) + "\n" + JSON.stringify(briefCall(2)) + "\n",+ ),+ );+ expect(frames.filter((f) => f["method"] !== undefined)).toEqual([]);+ });+});++describe("a malformed progress token is refused by name", () => {+ const server = (): MCPServer => new MCPServer({ vault });++ test.each([+ [true, "boolean"],+ [null, "null"],+ [{}, "object"],+ [[], "array"],+ [1.5, "fractional"],+ ] as ReadonlyArray<readonly [unknown, string]>)(+ "%p is refused naming what was wrong",+ async (token, expected) => {+ const res = await server().handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 3,+ method: "tools/call",+ params: { name: "brain_dream", arguments: {}, _meta: { progressToken: token } },+ });+ expect(res?.error?.code).toBe(-32602);+ expect(res?.error?.message).toContain("_meta.progressToken");+ expect(res?.error?.message).toContain(expected);+ },+ );++ test("a non-object _meta is refused naming _meta", async () => {+ const res = await server().handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 4,+ method: "tools/call",+ params: { name: "brain_dream", arguments: {}, _meta: "nope" },+ });+ expect(res?.error?.code).toBe(-32602);+ expect(res?.error?.message).toContain("_meta");+ });++ test("a _meta without a progressToken is not a token and not an error", async () => {+ const res = await server().handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 5,+ method: "tools/call",+ params: { name: "brain_dream", arguments: { dry_run: true }, _meta: { other: 1 } },+ });+ expect(res?.error).toBeUndefined();+ const result = res?.result as JsonObject | undefined;+ expect(result?.["_meta"]).toBeUndefined();+ });+});++describe("HTTP refuses a progress token by name", () => {+ test("the refusal rides on result._meta and no progress frames are sent", async () => {+ const handle = await startHttp({ vault }, { host: "127.0.0.1", port: 0 });+ try {+ const res = await fetch(handle.url, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(dreamCall(2, "tok-http")),+ });+ const body = (await res.json()) as JsonObject;+ const refusal = (body["result"]["_meta"] as JsonObject)[PROGRESS_META_KEY] as JsonObject;+ expect(refusal["schema"]).toBe(PROGRESS_SCHEMA);+ expect(refusal["kind"]).toBe(PROGRESS_KIND.refused);+ expect(refusal["reason"]).toBe(PROGRESS_REASON.transportSingleResponse);+ expect(refusal["progressToken"]).toBe("tok-http");+ // One response, no notification frames anywhere in the body.+ expect(JSON.stringify(body)).not.toContain(PROGRESS_NOTIFICATION_METHOD);+ } finally {+ await handle.close();+ }+ });++ test("a call with no token carries no _meta at all", async () => {+ const handle = await startHttp({ vault }, { host: "127.0.0.1", port: 0 });+ try {+ const res = await fetch(handle.url, {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify(dreamCall(2)),+ });+ const body = (await res.json()) as JsonObject;+ expect(body["result"]["_meta"]).toBeUndefined();+ } finally {+ await handle.close();+ }+ });+});diff --git a/tests/mcp/token-impact-tool.test.ts b/tests/mcp/token-impact-tool.test.tsindex 9bb2c8be..2a6c34f2 100644--- a/tests/mcp/token-impact-tool.test.ts+++ b/tests/mcp/token-impact-tool.test.ts@@ -117,7 +117,7 @@ describe("brain_token_impact record gating", () => {expect(records[0]!.payload["pack_id"]).toBe("receipt_1");});- test("method defaults to fallback when omitted", async () => {+ test("method defaults to the heuristic label when omitted", async () => {writeConfig(true);const server = new MCPServer({ vault, configPath });await initialize(server);@@ -126,7 +126,20 @@ describe("brain_token_impact record gating", () => {baseline_tokens: 10,packed_tokens: 4,});- expect(out["method"]).toBe("fallback");+ expect(out["method"]).toBe("heuristic");+ });++ test("an adapter still posting the retired labels is translated, not rejected", async () => {+ writeConfig(true);+ const server = new MCPServer({ vault, configPath });+ await initialize(server);+ const out = await callTool(server, "brain_token_impact", {+ operation: "record",+ baseline_tokens: 10,+ packed_tokens: 4,+ method: "exact",+ });+ expect(out["method"]).toBe("tokenizer");});test("rejects a missing count", async () => {diff --git a/tests/openclaw/bundle.test.ts b/tests/openclaw/bundle.test.tsindex e5e1fbe9..efb1f0b0 100644--- a/tests/openclaw/bundle.test.ts+++ b/tests/openclaw/bundle.test.ts@@ -73,7 +73,13 @@ describe("openclaw bundle", () => {expect(bundleText).toContain("evaluateProjectStatus");expect(bundleText).toContain("defaultDetectProjectPathSupport");expect(bundleText).toContain("code projects:");- expect(bundleText).toContain("no per-query project_path support");+ // "did not report", not "has no": the probe reads the partner's own+ // usage text, so a probe that failed or ran out of time reads exactly+ // like a partner without the feature, and the stronger wording was+ // claiming something the check had not established. The phrase is+ // asserted here because it is the distinctive string that proves the+ // degrade path reached the bundle at all.+ expect(bundleText).toContain("did not report per-query project_path support");});test("bundles before_prompt_build hook (per-turn identity reminder)", () => {